diff --git a/.codacy.yaml b/.codacy.yaml new file mode 100644 index 00000000..9d602065 --- /dev/null +++ b/.codacy.yaml @@ -0,0 +1,13 @@ +--- +# Codacy project configuration. +# +# specs/ holds internal groundwork artifacts (product specs, architecture +# notes, task records, review notes). They are not user-facing docs and are +# not subject to the same markdown style as README/ChangeLog/CONTRIBUTING. +# +# test/*.md are internal test-suite documents (e.g. the v2.0 routing +# regression gate at test/REGRESSION.md). Same rationale as specs/. +exclude_paths: + - 'specs/**' + - 'test/*.md' + - 'test/**/*.md' diff --git a/.github/workflows/verify-build.yml b/.github/workflows/verify-build.yml index db762069..9ff8a1df 100644 --- a/.github/workflows/verify-build.yml +++ b/.github/workflows/verify-build.yml @@ -9,6 +9,11 @@ on: schedule: - cron: '0 0 * * 0' +# Restrict every job's GITHUB_TOKEN to read-only by default. +# Jobs that need broader access should override at the job level. +permissions: + contents: read + jobs: verify: name: Verify @@ -108,26 +113,7 @@ jobs: debug: debug coverage: nocoverage shell: bash - - test-group: extra - os: ubuntu-latest - os-type: ubuntu - build-type: none - compiler-family: gcc - c-compiler: gcc-9 - cc-compiler: g++-9 - debug: nodebug - coverage: nocoverage - shell: bash - - test-group: extra - os: ubuntu-latest - os-type: ubuntu - build-type: none - compiler-family: gcc - c-compiler: gcc-10 - cc-compiler: g++-10 - debug: nodebug - coverage: nocoverage - shell: bash + # gcc-9 and gcc-10 dropped: lack full C++20 support (no concepts library, no std::span, no features). - test-group: extra os: ubuntu-latest os-type: ubuntu @@ -168,26 +154,8 @@ jobs: debug: nodebug coverage: nocoverage shell: bash - - test-group: extra - os: ubuntu-22.04 - os-type: ubuntu - build-type: none - compiler-family: clang - c-compiler: clang-11 - cc-compiler: clang++-11 - debug: nodebug - coverage: nocoverage - shell: bash - - test-group: extra - os: ubuntu-22.04 - os-type: ubuntu - build-type: none - compiler-family: clang - c-compiler: clang-12 - cc-compiler: clang++-12 - debug: nodebug - coverage: nocoverage - shell: bash + # clang-11, clang-12, clang-14, and clang-15 dropped: incomplete C++20 support (concepts// gaps). + # clang-13 retained: passes the autoconf C++20 feature check on ubuntu-22.04. - test-group: extra os: ubuntu-22.04 os-type: ubuntu @@ -198,26 +166,6 @@ jobs: debug: nodebug coverage: nocoverage shell: bash - - test-group: extra - os: ubuntu-latest - os-type: ubuntu - build-type: none - compiler-family: clang - c-compiler: clang-14 - cc-compiler: clang++-14 - debug: nodebug - coverage: nocoverage - shell: bash - - test-group: extra - os: ubuntu-latest - os-type: ubuntu - build-type: none - compiler-family: clang - c-compiler: clang-15 - cc-compiler: clang++-15 - debug: nodebug - coverage: nocoverage - shell: bash - test-group: extra os: ubuntu-latest os-type: ubuntu @@ -275,8 +223,8 @@ jobs: os-type: ubuntu build-type: select compiler-family: gcc - c-compiler: gcc-10 - cc-compiler: g++-10 + c-compiler: gcc-14 + cc-compiler: g++-14 debug: nodebug coverage: nocoverage shell: bash @@ -285,8 +233,8 @@ jobs: os-type: ubuntu build-type: nodelay compiler-family: gcc - c-compiler: gcc-10 - cc-compiler: g++-10 + c-compiler: gcc-14 + cc-compiler: g++-14 debug: nodebug coverage: nocoverage shell: bash @@ -295,8 +243,8 @@ jobs: os-type: ubuntu build-type: threads compiler-family: gcc - c-compiler: gcc-10 - cc-compiler: g++-10 + c-compiler: gcc-14 + cc-compiler: g++-14 debug: nodebug coverage: nocoverage shell: bash @@ -305,11 +253,66 @@ jobs: os-type: ubuntu build-type: lint compiler-family: gcc - c-compiler: gcc-10 - cc-compiler: g++-10 + c-compiler: gcc-14 + cc-compiler: g++-14 debug: debug coverage: nocoverage shell: bash + # TASK-007: dedicated header-hygiene gate. Runs `make check-hygiene` + # (preprocesses against the staged install and greps + # for forbidden backend headers). Surfaces this gate as its own named + # GitHub Actions check so reviewers see header-hygiene status + # independently of the broader `make check` log. Until M5 lands the + # check is informational (HEADER_HYGIENE_STRICT defaults to "no"); + # TASK-020 flips it to strict. + - test-group: extra + os: ubuntu-latest + os-type: ubuntu + build-type: header-hygiene + compiler-family: gcc + c-compiler: gcc-14 + cc-compiler: g++-14 + debug: nodebug + coverage: nocoverage + linking: dynamic + shell: bash + # TASK-037: build-flag invariance gate (HAVE_* all ON lane). + # PRD-FLG-REQ-001 / arch §9 testing item 2. The consumer_fixture + # binary (test/consumer_fixture.cpp) touches every public symbol + # whose declaration was previously #ifdef HAVE_* gated. It MUST + # compile + link in this configuration. Stock libmicrohttpd + + # gnutls; isolated as its own matrix entry so the build-flag + # invariance gate has a dedicated status check. + - test-group: extra + os: ubuntu-latest + os-type: ubuntu + build-type: flag-invariance-on + compiler-family: gcc + c-compiler: gcc + cc-compiler: g++ + debug: nodebug + coverage: nocoverage + linking: dynamic + shell: bash + # TASK-037: build-flag invariance gate (HAVE_* all OFF lane). + # libmicrohttpd is rebuilt with --disable-bauth --disable-dauth + # --disable-websockets so libhttpserver auto-detects all three + # as off. The gnutls install step is gated off for this build- + # type so gnutls/gnutls.h is absent from the include search path + # and HAVE_GNUTLS auto-detects to off as well. The same + # consumer_fixture.cpp must compile + link without source changes, + # proving every flag-gated public declaration is unconditional. + - test-group: extra + os: ubuntu-latest + os-type: ubuntu + build-type: flag-invariance-off + compiler-family: gcc + c-compiler: gcc + cc-compiler: g++ + debug: nodebug + coverage: nocoverage + linking: dynamic + shell: bash - test-group: basic os: windows-latest os-type: windows @@ -393,8 +396,12 @@ jobs: pacman --noconfirm -S --needed msys2-devel gcc make libcurl-devel libgnutls-devel - name: Install Ubuntu test sources + # ppa:ubuntu-toolchain-r/test was historically used to backport newer + # gcc onto older Ubuntu LTS. With the C++20 floor (TASK-001), our matrix + # only retains compilers that ship in stock ubuntu-22.04 / 24.04 repos + # (gcc-11..14, clang-13/16/17/18), so the PPA is no longer needed -- and + # add-apt-repository talks to launchpad, which is a flaky dependency. run: | - sudo add-apt-repository ppa:ubuntu-toolchain-r/test ; sudo apt-get update ; if: ${{ matrix.os-type == 'ubuntu' }} @@ -505,7 +512,10 @@ jobs: - name: Setup gnutls dependency (only on linux) run: | sudo apt-get install libgnutls28-dev gnutls-bin ; - if: ${{ matrix.os-type == 'ubuntu' }} + # TASK-037: skip gnutls install on the flag-invariance-off lane so + # HAVE_GNUTLS auto-detects to off (the configure script just + # AC_CHECK_HEADER's gnutls/gnutls.h, no header == HAVE_GNUTLS=0). + if: ${{ matrix.os-type == 'ubuntu' && matrix.build-type != 'flag-invariance-off' }} - name: Fetch libmicrohttpd from cache id: cache-libmicrohttpd @@ -513,26 +523,42 @@ jobs: with: path: libmicrohttpd-1.0.3 key: ${{ matrix.os }}-${{ matrix.c-compiler }}-libmicrohttpd-1.0.3-pre-built-v2 - if: ${{ matrix.os-type != 'windows' && matrix.build-type != 'no-dauth' && matrix.compiler-family != 'arm-cross' }} + # TASK-037: the flag-invariance-off lane rebuilds libmicrohttpd with + # every sub-feature disabled, so it must skip the stock cache fetch. + if: ${{ matrix.os-type != 'windows' && matrix.build-type != 'no-dauth' && matrix.build-type != 'flag-invariance-off' && matrix.compiler-family != 'arm-cross' }} - name: Build libmicrohttpd dependency (if not cached) run: | curl https://s3.amazonaws.com/libhttpserver/libmicrohttpd_releases/libmicrohttpd-1.0.3.tar.gz -o libmicrohttpd-1.0.3.tar.gz ; + echo "7816b57aae199cf5c3645e8770e1be5f0a4dfafbcb24b3772173dc4ee634126a libmicrohttpd-1.0.3.tar.gz" | sha256sum -c ; tar -xzf libmicrohttpd-1.0.3.tar.gz ; cd libmicrohttpd-1.0.3 ; ./configure --disable-examples ; make ; - if: ${{ matrix.os-type != 'windows' && matrix.build-type != 'no-dauth' && matrix.compiler-family != 'arm-cross' && steps.cache-libmicrohttpd.outputs.cache-hit != 'true' }} + # TASK-037: as above -- flag-invariance-off has its own dedicated + # libmicrohttpd build step below. + if: ${{ matrix.os-type != 'windows' && matrix.build-type != 'no-dauth' && matrix.build-type != 'flag-invariance-off' && matrix.compiler-family != 'arm-cross' && steps.cache-libmicrohttpd.outputs.cache-hit != 'true' }} - name: Build libmicrohttpd without digest auth (no-dauth test) run: | curl https://s3.amazonaws.com/libhttpserver/libmicrohttpd_releases/libmicrohttpd-1.0.3.tar.gz -o libmicrohttpd-1.0.3.tar.gz ; + echo "7816b57aae199cf5c3645e8770e1be5f0a4dfafbcb24b3772173dc4ee634126a libmicrohttpd-1.0.3.tar.gz" | sha256sum -c ; tar -xzf libmicrohttpd-1.0.3.tar.gz ; cd libmicrohttpd-1.0.3 ; ./configure --disable-examples --disable-dauth ; make ; if: ${{ matrix.build-type == 'no-dauth' }} + - name: Build libmicrohttpd with all features off (TASK-037 flag-invariance-off lane) + run: | + curl https://s3.amazonaws.com/libhttpserver/libmicrohttpd_releases/libmicrohttpd-1.0.3.tar.gz -o libmicrohttpd-1.0.3.tar.gz ; + echo "7816b57aae199cf5c3645e8770e1be5f0a4dfafbcb24b3772173dc4ee634126a libmicrohttpd-1.0.3.tar.gz" | sha256sum -c ; + tar -xzf libmicrohttpd-1.0.3.tar.gz ; + cd libmicrohttpd-1.0.3 ; + ./configure --disable-examples --disable-bauth --disable-dauth --disable-websockets ; + make ; + if: ${{ matrix.build-type == 'flag-invariance-off' }} + - name: Install libmicrohttpd run: cd libmicrohttpd-1.0.3 ; sudo make install ; if: ${{ matrix.os-type != 'windows' && matrix.compiler-family != 'arm-cross' }} @@ -547,10 +573,37 @@ jobs: echo "Verified: libmicrohttpd built without digest auth support" ; if: ${{ matrix.build-type == 'no-dauth' }} + - name: Verify libmicrohttpd built without bauth/dauth/websockets (TASK-037 flag-invariance-off lane) + # TASK-037 / PRD-FLG-REQ-001: belt-and-braces check that the bespoke + # libmicrohttpd build above actually stripped the symbols that drive + # libhttpserver's HAVE_BAUTH / HAVE_DAUTH / HAVE_WEBSOCKET + # auto-detection. If any of these slipped back in, the configure + # step would (correctly) flip the corresponding HAVE_* back on and + # the lane would no longer be exercising the flag-off invariant. + run: | + fail=0 ; + for sym in MHD_basic_auth_get_username_password3 MHD_digest_auth_check3 MHD_queue_auth_fail_response; do + if nm /usr/local/lib/libmicrohttpd.so 2>/dev/null | grep -q "$sym"; then + echo "ERROR: $sym present in libmicrohttpd (expected absent)" ; + fail=1 ; + else + echo "Verified: $sym absent from libmicrohttpd" ; + fi ; + done ; + if ls /usr/local/lib/libmicrohttpd_ws* >/dev/null 2>&1; then + echo "ERROR: libmicrohttpd_ws present (expected absent)" ; + fail=1 ; + else + echo "Verified: libmicrohttpd_ws not built/installed" ; + fi ; + if [ "$fail" -ne 0 ]; then exit 1; fi + if: ${{ matrix.build-type == 'flag-invariance-off' }} + - name: Build and install libmicrohttpd (Windows) if: ${{ matrix.os-type == 'windows' }} run: | curl https://s3.amazonaws.com/libhttpserver/libmicrohttpd_releases/libmicrohttpd-1.0.3.tar.gz -o libmicrohttpd-1.0.3.tar.gz + echo "7816b57aae199cf5c3645e8770e1be5f0a4dfafbcb24b3772173dc4ee634126a libmicrohttpd-1.0.3.tar.gz" | sha256sum -c tar -xzf libmicrohttpd-1.0.3.tar.gz cd libmicrohttpd-1.0.3 ./configure --disable-examples --enable-poll=no @@ -568,6 +621,7 @@ jobs: - name: Cross-compile libmicrohttpd for ARM run: | curl https://s3.amazonaws.com/libhttpserver/libmicrohttpd_releases/libmicrohttpd-1.0.3.tar.gz -o libmicrohttpd-1.0.3.tar.gz + echo "7816b57aae199cf5c3645e8770e1be5f0a4dfafbcb24b3772173dc4ee634126a libmicrohttpd-1.0.3.tar.gz" | sha256sum -c tar -xzf libmicrohttpd-1.0.3.tar.gz mv libmicrohttpd-1.0.3 libmicrohttpd-1.0.3-${{ matrix.build-type }} cd libmicrohttpd-1.0.3-${{ matrix.build-type }} @@ -599,11 +653,17 @@ jobs: - name: Run libhttpserver configure run: | # Set memory check flags. They need to stay in step as env variables don't propagate across steps. - if [ "$BUILD_TYPE" = "asan" ]; then export CFLAGS='-fsanitize=address'; export CXXLAGS='-fsanitize=address'; export LDFLAGS='-fsanitize=address'; fi - if [ "$BUILD_TYPE" = "msan" ]; then export CFLAGS='-fsanitize=memory'; export CXXLAGS='-fsanitize=memory'; export LDFLAGS='-fsanitize=memory'; fi - if [ "$BUILD_TYPE" = "lsan" ]; then export CFLAGS='-fsanitize=leak'; export CXXLAGS='-fsanitize=leak'; export LDFLAGS='-fsanitize=leak'; fi - if [ "$BUILD_TYPE" = "tsan" ]; then export CFLAGS='-fsanitize=thread'; export CXXLAGS='-fsanitize=thread'; export LDFLAGS='-fsanitize=thread'; fi - if [ "$BUILD_TYPE" = "ubsan" ]; then export export CFLAGS='-fsanitize=undefined'; export CXXLAGS='-fsanitize=undefined'; export LDFLAGS='-fsanitize=undefined'; fi + # TASK-038: CXXFLAGS (NOT CXXLAGS) is the autoconf-recognized var + # that gets passed to the C++ compiler. A long-standing typo left + # C++ TUs uninstrumented under asan/msan/lsan/tsan/ubsan — the + # runtime libs were linked but the code itself was compiled + # without -fsanitize=..., so the sanitizers were no-ops on the + # library. The fix is a single missing 'F' per line. + if [ "$BUILD_TYPE" = "asan" ]; then export CFLAGS='-fsanitize=address'; export CXXFLAGS='-fsanitize=address'; export LDFLAGS='-fsanitize=address'; fi + if [ "$BUILD_TYPE" = "msan" ]; then export CFLAGS='-fsanitize=memory'; export CXXFLAGS='-fsanitize=memory'; export LDFLAGS='-fsanitize=memory'; fi + if [ "$BUILD_TYPE" = "lsan" ]; then export CFLAGS='-fsanitize=leak'; export CXXFLAGS='-fsanitize=leak'; export LDFLAGS='-fsanitize=leak'; fi + if [ "$BUILD_TYPE" = "tsan" ]; then export CFLAGS='-fsanitize=thread'; export CXXFLAGS='-fsanitize=thread'; export LDFLAGS='-fsanitize=thread'; fi + if [ "$BUILD_TYPE" = "ubsan" ]; then export CFLAGS='-fsanitize=undefined'; export CXXFLAGS='-fsanitize=undefined'; export LDFLAGS='-fsanitize=undefined'; fi # Additional flags on mac. They need to stay in step as env variables don't propagate across steps. if [ "${{ matrix.os }}" = "macos-latest" ]; then @@ -649,6 +709,26 @@ jobs: fi if: ${{ matrix.build-type == 'no-dauth' }} + - name: Verify libhttpserver detected all features off (TASK-037 flag-invariance-off lane) + # TASK-037 / PRD-FLG-REQ-001 / arch §9 testing item 2. Asserts that + # configure auto-detected every HAVE_* feature as off in this lane; + # if any of them are 'yes', the lane wouldn't actually be exercising + # the flag-off invariant and we want the matrix to go red loudly. + run: | + cd build ; + fail=0 ; + for feat in "TLS Enabled" "Basic Auth" "Digest Auth" "WebSocket"; do + if grep -qE "^ ${feat}[[:space:]]*:[[:space:]]*no$" config.log; then + echo "Verified: ${feat} is off" ; + else + echo "ERROR: ${feat} is NOT off in this configuration" ; + grep "${feat}" config.log || echo "${feat} line not found" ; + fail=1 ; + fi ; + done ; + if [ "$fail" -ne 0 ]; then exit 1; fi + if: ${{ matrix.build-type == 'flag-invariance-off' }} + - name: Print config.log shell: bash run: | @@ -662,7 +742,7 @@ jobs: # IWYU always return an error code. If it returns "2" it indicates a success so we manage this within the function below. function safe_make_iwyu() { { - make -k CXX='/usr/local/bin/include-what-you-use -Xiwyu --mapping_file=${top_builddir}/../custom_iwyu.imp' CXXFLAGS="-std=c++11 -DHTTPSERVER_COMPILATION -D_REENTRANT $CXXFLAGS" ; + make -k CXX='/usr/local/bin/include-what-you-use -Xiwyu --mapping_file=${top_builddir}/../custom_iwyu.imp' CXXFLAGS="-std=c++20 -DHTTPSERVER_COMPILATION -D_REENTRANT $CXXFLAGS" ; } || { if [ $? -ne 2 ]; then return 1; @@ -681,11 +761,43 @@ jobs: make ; fi + - name: Build consumer fixture (TASK-037 build-flag invariance gate) + # TASK-037 / PRD-FLG-REQ-001 / arch §9 testing item 2. The headline + # gate: the same test/consumer_fixture.cpp (which touches every + # previously HAVE_*-gated public symbol) must compile + link in + # both the all-features-on and all-features-off configurations. + # The matrix entries skip the broad `make check` / `cppcheck` steps + # below -- this single fixture compile + link is the build-flag- + # invariance assertion. + run: | + cd build ; + make -C test consumer_fixture ; + if: ${{ matrix.build-type == 'flag-invariance-on' || matrix.build-type == 'flag-invariance-off' }} + - name: Run tests run: | cd build ; + # tsan: suppress libstdc++'s benign std::ctype narrow-cache race + # (see test/tsan.supp). All libhttpserver-internal races stay fatal. + if [ "$BUILD_TYPE" = "tsan" ]; then + export TSAN_OPTIONS="suppressions=$(pwd)/../test/tsan.supp" ; + fi make check; - if: ${{ matrix.build-type != 'iwyu' && matrix.compiler-family != 'arm-cross' }} + # TASK-037: flag-invariance-{on,off} are compile/link-only gates, so + # skip the full `make check` (which spins up real servers and would + # crash on the OFF lane for the BAUTH/DAUTH/WS unit tests anyway). + if: ${{ matrix.build-type != 'iwyu' && matrix.compiler-family != 'arm-cross' && matrix.build-type != 'header-hygiene' && matrix.build-type != 'flag-invariance-on' && matrix.build-type != 'flag-invariance-off' }} + + - name: Run header-hygiene check + # TASK-007: dedicated public-header hygiene gate. Runs the + # preprocessor-grep target (Layer 2) against a staged install and + # reports any forbidden backend headers reaching . + # Currently informational (HEADER_HYGIENE_STRICT=no) -- TASK-020 + # flips this to strict when M5 closes the umbrella. + run: | + cd build + make check-hygiene + if: ${{ matrix.build-type == 'header-hygiene' }} - name: Print tests results shell: bash @@ -713,7 +825,8 @@ jobs: run: | cd src/ ; cppcheck --error-exitcode=1 . ; - if: ${{ matrix.os-type == 'ubuntu' && matrix.compiler-family != 'arm-cross' }} + # TASK-037: flag-invariance lanes are minimal gates -- skip cppcheck. + if: ${{ matrix.os-type == 'ubuntu' && matrix.compiler-family != 'arm-cross' && matrix.build-type != 'flag-invariance-on' && matrix.build-type != 'flag-invariance-off' }} - name: Run performance tests (select) run: | diff --git a/.gitignore b/.gitignore index addf8862..40430a4b 100644 --- a/.gitignore +++ b/.gitignore @@ -60,3 +60,5 @@ libtool .worktrees .claude CLAUDE.md +.groundwork-plans/ +.DS_Store diff --git a/ChangeLog b/ChangeLog index ea6c2045..ae87ddd3 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,5 +1,19 @@ +Version 2.0.0 + + v2.0 release. See RELEASE_NOTES.md for the full v1->v2 porting summary. + SOVERSION bumped: shared library now ships as libhttpserver.so.2 + (Linux) / libhttpserver.2.dylib (Darwin). Parallel-installable + with any prior libhttpserver.so.0/1 on disk (runtime artefacts + only; dev-time .la/.a/.pc/headers are last-installer-wins by + design). + Version 0.20.0 + Raised minimum C++ standard to C++20. Build now requires gcc >= 10 + or clang >= 13 (Apple Clang from Xcode 15+). Updated + AX_CXX_COMPILE_STDCXX macro (m4/ax_cxx_compile_stdcxx.m4) to + serial 25 to support C++20 detection. Pruned CI matrix rows + (gcc-9, clang-11, clang-12) that lack full C++20 support. Raised minimum libmicrohttpd requirement to 1.0.0. Migrated Basic Auth to v3 API (MHD_basic_auth_get_username_password3, MHD_queue_basic_auth_required_response3) with UTF-8 support. @@ -20,6 +34,16 @@ Version 0.20.0 suppress_date_header. Added WebSocket support (conditional on HAVE_WEBSOCKET): websocket_handler, websocket_session, register_ws_resource(). + TASK-035: replaced the raw-pointer + register_ws_resource(string, websocket_handler*) overload with + smart-pointer overloads register_ws_resource(string, + unique_ptr) and register_ws_resource(string, + shared_ptr); added unregister_ws_resource(string). + Mirrors the TASK-023 register_resource ownership model and is + consistent with DR-010 / PRD-HDL-REQ-003 / PRD-HDL-REQ-005. + Duplicate registrations now throw std::invalid_argument + (previously a silent overwrite). On HAVE_WEBSOCKET-off builds + all three entry points throw feature_unavailable. Added utility functions: reason_phrase(), is_feature_supported(), get_mhd_version(). Added example and documentation for serving binary data from memory diff --git a/Makefile.am b/Makefile.am index 02121fde..021b80a8 100644 --- a/Makefile.am +++ b/Makefile.am @@ -38,11 +38,333 @@ endif endif -EXTRA_DIST = libhttpserver.pc.in $(DX_CONFIG) scripts/extract-release-notes.sh scripts/validate-version.sh +EXTRA_DIST = libhttpserver.pc.in $(DX_CONFIG) scripts/extract-release-notes.sh scripts/validate-version.sh \ + scripts/check-examples.sh scripts/check-readme.sh scripts/check-release-notes.sh \ + scripts/check-doxygen.sh \ + scripts/check-soversion.sh scripts/check-parallel-install.sh \ + scripts/verify-installed-examples.sh \ + test/headers/consumer_direct.cpp test/headers/consumer_detail.cpp test/headers/consumer_umbrella.cpp \ + test/headers/consumer_post_umbrella.cpp \ + test/headers/consumer_umbrella_no_backend.cpp + +# --------------------------------------------------------------------------- +# Header-hygiene checks (TASK-002) +# +# check-headers verifies that the public/private header gates are wired up +# correctly: +# A.1 a consumer including a public header WITHOUT the umbrella must hit the +# inclusion-gate #error. +# A.2 a consumer including a detail header WITHOUT HTTPSERVER_COMPILATION +# must hit the gate. +# A.3 a consumer including only the umbrella, WITHOUT HTTPSERVER_COMPILATION, +# must compile cleanly. +# +# The CXX invocations below override CXXFLAGS to '' so that +# -DHTTPSERVER_COMPILATION (injected by configure.ac into CXXFLAGS for the +# library and test build) does NOT leak into the consumer-style compile. We +# still pass -std=c++20 explicitly because libhttpserver requires C++20. +# --------------------------------------------------------------------------- + +# Compose CXX with: explicit -std, the source/build include search paths used by +# the library, and $(CPPFLAGS) (e.g., -I/opt/homebrew/include from configure). +# Deliberately omit $(CXXFLAGS), $(AM_CPPFLAGS), and any per-target CPPFLAGS so +# that -DHTTPSERVER_COMPILATION (set in src/ and test/ AM_CPPFLAGS) cannot +# leak into the consumer-style compile. A true consumer never has that macro. +CHECK_HEADERS_CXX = $(CXX) -std=c++20 -I$(top_builddir) -I$(top_srcdir)/src -I$(top_srcdir)/src/httpserver $(CPPFLAGS) +CHECK_HEADERS_GATE_MSG = Only or can be included directly + +check-headers: + @echo "=== check-headers A.1: direct public-header include must fail ===" + @if $(CHECK_HEADERS_CXX) -c $(top_srcdir)/test/headers/consumer_direct.cpp -o /dev/null 2>check-headers-A1.log; then \ + echo "FAIL: consumer_direct.cpp compiled but should have errored"; \ + cat check-headers-A1.log; \ + rm -f check-headers-A1.log; \ + exit 1; \ + fi + @if ! grep -q "$(CHECK_HEADERS_GATE_MSG)" check-headers-A1.log; then \ + echo "FAIL: consumer_direct.cpp failed but not for the gate reason"; \ + cat check-headers-A1.log; \ + rm -f check-headers-A1.log; \ + exit 1; \ + fi + @rm -f check-headers-A1.log + @echo " PASS: A.1 gate fired as expected" + @echo "=== check-headers A.2: direct detail-header include must fail ===" + @if $(CHECK_HEADERS_CXX) -c $(top_srcdir)/test/headers/consumer_detail.cpp -o /dev/null 2>check-headers-A2.log; then \ + echo "FAIL: consumer_detail.cpp compiled but should have errored"; \ + cat check-headers-A2.log; \ + rm -f check-headers-A2.log; \ + exit 1; \ + fi + @if ! grep -q "$(CHECK_HEADERS_GATE_MSG)" check-headers-A2.log; then \ + echo "FAIL: consumer_detail.cpp failed but not for the gate reason"; \ + cat check-headers-A2.log; \ + rm -f check-headers-A2.log; \ + exit 1; \ + fi + @rm -f check-headers-A2.log + @echo " PASS: A.2 gate fired as expected" + @echo "=== check-headers A.3: umbrella include must succeed ===" + @if ! $(CHECK_HEADERS_CXX) -c $(top_srcdir)/test/headers/consumer_umbrella.cpp -o consumer_umbrella.check.o 2>check-headers-A3.log; then \ + echo "FAIL: consumer_umbrella.cpp did not compile"; \ + cat check-headers-A3.log; \ + rm -f check-headers-A3.log consumer_umbrella.check.o; \ + exit 1; \ + fi + @rm -f check-headers-A3.log consumer_umbrella.check.o + @echo " PASS: A.3 umbrella compiled cleanly" + @echo "=== check-headers A.4: post-umbrella direct include must fail ===" + @if $(CHECK_HEADERS_CXX) -c $(top_srcdir)/test/headers/consumer_post_umbrella.cpp -o /dev/null 2>check-headers-A4.log; then \ + echo "FAIL: consumer_post_umbrella.cpp compiled but should have errored"; \ + cat check-headers-A4.log; \ + rm -f check-headers-A4.log; \ + exit 1; \ + fi + @if ! grep -q "$(CHECK_HEADERS_GATE_MSG)" check-headers-A4.log; then \ + echo "FAIL: consumer_post_umbrella.cpp failed but not for the gate reason"; \ + cat check-headers-A4.log; \ + rm -f check-headers-A4.log; \ + exit 1; \ + fi + @rm -f check-headers-A4.log + @echo " PASS: A.4 umbrella does not leak _HTTPSERVER_HPP_INSIDE_" + +# check-install-layout asserts that `make install DESTDIR=$(STAGE)` produces +# a public include tree with NO `detail/` directory and NO `*_impl.hpp` files. +# This protects the public/private split as described in TASK-002 / DR-002. +CHECK_INSTALL_STAGE = $(abs_top_builddir)/.install-stage + +check-install-layout: + @echo "=== check-install-layout: staged install must hide detail/ and *_impl.hpp ===" + @if test "$(CHECK_INSTALL_SHARED)" != "yes"; then \ + rm -rf $(CHECK_INSTALL_STAGE); \ + $(MAKE) $(AM_MAKEFLAGS) install DESTDIR=$(CHECK_INSTALL_STAGE) >check-install.log 2>&1 || { \ + echo "FAIL: staged install failed"; \ + cat check-install.log; \ + rm -f check-install.log; \ + rm -rf $(CHECK_INSTALL_STAGE); \ + exit 1; \ + }; \ + rm -f check-install.log; \ + fi + @leaked_detail=`find $(CHECK_INSTALL_STAGE) -type d -name detail 2>/dev/null`; \ + if test -n "$$leaked_detail"; then \ + echo "FAIL: detail/ directory leaked into install:"; \ + echo "$$leaked_detail"; \ + if test "$(CHECK_INSTALL_SHARED)" != "yes"; then rm -rf $(CHECK_INSTALL_STAGE); fi; \ + exit 1; \ + fi + @leaked_impl=`find $(CHECK_INSTALL_STAGE) -name '*_impl.hpp' 2>/dev/null`; \ + if test -n "$$leaked_impl"; then \ + echo "FAIL: *_impl.hpp file leaked into install:"; \ + echo "$$leaked_impl"; \ + if test "$(CHECK_INSTALL_SHARED)" != "yes"; then rm -rf $(CHECK_INSTALL_STAGE); fi; \ + exit 1; \ + fi + @umbrella_count=`find $(CHECK_INSTALL_STAGE) -name 'httpserver.hpp' | wc -l | tr -d ' '`; \ + if test "$$umbrella_count" != "1"; then \ + echo "FAIL: expected exactly 1 installed httpserver.hpp, got $$umbrella_count"; \ + if test "$(CHECK_INSTALL_SHARED)" != "yes"; then rm -rf $(CHECK_INSTALL_STAGE); fi; \ + exit 1; \ + fi + @if test "$(CHECK_INSTALL_SHARED)" != "yes"; then rm -rf $(CHECK_INSTALL_STAGE); fi + @echo " PASS: staged install layout is clean" + +# --------------------------------------------------------------------------- +# Header-hygiene preprocessor gate (TASK-007). +# +# This is the preprocessor-grep half of the TASK-007 enforcement (the +# compile-time half lives as `header_hygiene` in test/Makefile.am). +# +# Procedure: +# 1. Stage `make install DESTDIR=$(CHECK_HYGIENE_STAGE)` to get a +# pristine public include tree -- exactly what packagers and +# downstream consumers see. +# 2. Preprocess test/headers/consumer_umbrella_no_backend.cpp using +# ONLY -I$(CHECK_HYGIENE_STAGE)$(includedir) plus $(CPPFLAGS) (so +# e.g. /opt/homebrew/include is on the search path -- the grep +# below NEEDS to resolve if the umbrella pulls it +# in, otherwise we couldn't detect the leak). +# 3. Grep the cpp output for `# ""` line markers that +# name any forbidden backend header. The line-marker filter +# avoids false positives from substrings in code or comments. +# +# HEADER_HYGIENE_STRICT controls whether a leak is fatal: +# - "yes" (default since TASK-020): leaks fail the build. The umbrella +# is now clean and any regression should break CI loudly. +# - "no" (legacy): leaks were reported as EXPECTED-FAIL and exit 0 +# while M2-M5 were in flight. Override from the command line +# (`make check-hygiene HEADER_HYGIENE_STRICT=no`) only if you +# are deliberately running against an in-flight umbrella. +# +# Cross-reference: keep HEADER_HYGIENE_FORBIDDEN in sync with the +# #ifdef ladder in test/unit/header_hygiene_test.cpp. +# +# TASK-020 caveat (libc++ AND libstdc++ in thread mode): +# is intentionally absent from the forbidden list below. Both +# mainstream STLs unconditionally pull in from any STL +# container header (, , , etc.) when threading +# is enabled: +# - libc++ (Apple's default STL on macOS) routes through +# <__thread/support/pthread.h>. +# - libstdc++ in thread-enabled mode (which is the default whenever +# -D_REENTRANT is set, as configure.ac does) routes through +# , which #include directly. +# The resulting `# N "...pthread.h"` line markers therefore appear in +# the preprocessed output even though libhttpserver itself does not +# include . The runtime sentinel +# test/unit/header_hygiene_test.cpp keeps the pthread guards but skips +# them on both libc++ (_LIBCPP_VERSION) and libstdc++ in thread mode +# (_GLIBCXX_HAS_GTHREADS), so the guards still fire on STLs that don't +# route std::thread through pthread (e.g. MSVC's Microsoft STL). +# --------------------------------------------------------------------------- + +HEADER_HYGIENE_FORBIDDEN = microhttpd\.h|gnutls/gnutls\.h|sys/socket\.h|sys/uio\.h +CHECK_HYGIENE_STAGE = $(abs_top_builddir)/.hygiene-stage +CHECK_HYGIENE_CXX = $(CXX) -std=c++20 -E -I$(CHECK_HYGIENE_STAGE)$(includedir) $(CPPFLAGS) +HEADER_HYGIENE_STRICT ?= yes + +# Sentinel file: only re-run the staged install when headers have changed. +# This is an mtime gate used exclusively for standalone `make check-hygiene` +# invocations — it avoids paying a full `make install` cost on every +# repeated standalone run. When check-local drives check-hygiene it sets +# CHECK_HYGIENE_SHARED=yes and passes CHECK_HYGIENE_STAGE pointing at its +# own pre-built shared stage, so this stamp target is bypassed entirely. +HYGIENE_STAMP = $(CHECK_HYGIENE_STAGE)/.hygiene-stamp + +$(HYGIENE_STAMP): $(wildcard $(top_srcdir)/src/httpserver/*.hpp) + @rm -rf $(CHECK_HYGIENE_STAGE) + @$(MAKE) $(AM_MAKEFLAGS) install DESTDIR=$(CHECK_HYGIENE_STAGE) >check-hygiene-install.log 2>&1 || { \ + echo "FAIL: staged install failed"; cat check-hygiene-install.log; \ + rm -f check-hygiene-install.log; rm -rf $(CHECK_HYGIENE_STAGE); exit 1; } + @rm -f check-hygiene-install.log + @touch $(HYGIENE_STAMP) + +check-hygiene: + @echo "=== check-hygiene: must not transitively include backend headers ===" + @if test "$(CHECK_HYGIENE_SHARED)" != "yes"; then \ + $(MAKE) $(AM_MAKEFLAGS) $(HYGIENE_STAMP); \ + else \ + if ! test -d "$(CHECK_HYGIENE_STAGE)"; then \ + echo "FAIL: CHECK_HYGIENE_SHARED=yes but stage dir '$(CHECK_HYGIENE_STAGE)' does not exist."; \ + echo " Always pair CHECK_HYGIENE_SHARED=yes with CHECK_HYGIENE_STAGE=."; \ + exit 1; \ + fi; \ + fi + @status=0; \ + if ! $(CHECK_HYGIENE_CXX) $(top_srcdir)/test/headers/consumer_umbrella_no_backend.cpp >check-hygiene.i 2>check-hygiene.err; then \ + if test "$(HEADER_HYGIENE_STRICT)" = "yes"; then \ + echo "FAIL: preprocessor failed"; cat check-hygiene.err; \ + status=1; \ + else \ + echo "EXPECTED-FAIL (informational until M5): preprocessor failed against staged install."; \ + echo " This is expected while M2-M5 are in flight (e.g. webserver.hpp still"; \ + echo " references private detail headers that aren't shipped)."; \ + echo " Tail of preprocessor diagnostics:"; \ + sed 's/^/ /' check-hygiene.err | tail -10; \ + fi; \ + else \ + leaks=`grep -hE '^# [0-9]+ "[^"]*/($(HEADER_HYGIENE_FORBIDDEN))"' check-hygiene.i | awk '{print $$3}' | sort -u`; \ + if test -n "$$leaks"; then \ + if test "$(HEADER_HYGIENE_STRICT)" = "yes"; then \ + echo "FAIL: forbidden headers leaked through :"; \ + echo "$$leaks"; \ + status=1; \ + else \ + echo "EXPECTED-FAIL (informational until M5): forbidden headers currently leak through :"; \ + echo "$$leaks"; \ + fi; \ + else \ + echo " PASS: no forbidden headers reached the consumer TU"; \ + fi; \ + fi; \ + rm -f check-hygiene.i check-hygiene.err; \ + exit $$status + +# check-local runs check-install-layout and check-hygiene against a single +# shared staged install to avoid paying two full `make install` costs on +# every `make check`. Both sub-checks can still be invoked standalone (they +# will do their own install when CHECK_*_SHARED is not set). +check-local: check-headers check-examples check-readme check-release-notes check-doxygen + @echo "=== Shared staged install for check-install-layout and check-hygiene ===" + @rm -rf $(abs_top_builddir)/.shared-check-stage + @$(MAKE) $(AM_MAKEFLAGS) install DESTDIR=$(abs_top_builddir)/.shared-check-stage >check-shared-install.log 2>&1 || { \ + echo "FAIL: shared staged install failed"; cat check-shared-install.log; \ + rm -f check-shared-install.log; rm -rf $(abs_top_builddir)/.shared-check-stage; exit 1; } + @rm -f check-shared-install.log + @$(MAKE) $(AM_MAKEFLAGS) check-install-layout \ + CHECK_INSTALL_STAGE=$(abs_top_builddir)/.shared-check-stage \ + CHECK_INSTALL_SHARED=yes + @$(MAKE) $(AM_MAKEFLAGS) check-hygiene \ + CHECK_HYGIENE_STAGE=$(abs_top_builddir)/.shared-check-stage \ + CHECK_HYGIENE_SHARED=yes + @rm -rf $(abs_top_builddir)/.shared-check-stage + +# TASK-040: enforce static invariants on the two flagship examples +# (hello_world.cpp <= 10 LOC, lambda-only; shared_state.cpp class+mutex). +# Run as part of `make check` via check-local. +check-examples: + @echo "=== check-examples: enforce TASK-040 invariants on examples/ ===" + @$(top_srcdir)/scripts/check-examples.sh + +# TASK-041: enforce static invariants on README.md +# (byte-for-byte hello-world snippet, no v1 tokens, required sections, cross-links). +# Run as part of `make check` via check-local. +check-readme: + @echo "=== check-readme: enforce TASK-041 invariants on README.md ===" + @$(top_srcdir)/scripts/check-readme.sh + +# TASK-042: enforce static invariants on RELEASE_NOTES.md +# (required v1/v2 tokens, sections, same-line rename pairs, arch citations, +# disclaimer). Run as part of `make check` via check-local. +check-release-notes: + @echo "=== check-release-notes: enforce TASK-042 invariants on RELEASE_NOTES.md ===" + @$(top_srcdir)/scripts/check-release-notes.sh + +# TASK-043: run doxygen and fail on any substantive warning. The script +# delegates to `make doxygen-run` and parses stderr; environmental noise +# (obsolete config tags, missing graphviz) is filtered out. Skips with +# exit 0 if doxygen is not installed. +check-doxygen: + @echo "=== check-doxygen: enforce TASK-043 zero-warning invariant ===" + @BUILD_DIR="$(abs_top_builddir)" $(top_srcdir)/scripts/check-doxygen.sh + +# TASK-044: SOVERSION acceptance gate. Stages a clean DESTDIR install and +# asserts that the v2.0 on-disk SONAME layout is correct (libhttpserver.so.2 +# on Linux / libhttpserver.2.dylib on Darwin, pkg-config --modversion 2.0.0, +# correct symlink chain). NOT wired into `make check` — it does its own +# `make install` and is intentionally invoked standalone to keep per-PR CI +# fast. Run manually before tagging a release. +check-soversion: + @echo "=== check-soversion: TASK-044 SOVERSION acceptance gate ===" + @BUILD_DIR="$(abs_top_builddir)" $(top_srcdir)/scripts/check-soversion.sh + +# TASK-044: parallel-installability verification. Builds master and installs +# v1 + v2 into the same DESTDIR and asserts both SONAMEd libraries coexist. +# Best-effort: emits SKIP and exits 0 if the v1 source cannot be built in +# this environment (toolchain mismatch, missing libtoolize, etc.). +# Definitely NOT in `make check` — requires a clean v1 build of master. +check-parallel-install: + @echo "=== check-parallel-install: TASK-044 v1+v2 coexistence ===" + @BUILD_DIR="$(abs_top_builddir)" $(top_srcdir)/scripts/check-parallel-install.sh + +.PHONY: check-headers check-install-layout check-hygiene check-examples check-readme check-release-notes check-doxygen check-soversion check-parallel-install + +# TASK-039: top-level convenience rule that descends into test/ to +# build and run the bench binaries (see test/Makefile.am and +# test/PERFORMANCE.md). NOT wired into `make check`; release-mode +# only. +bench: + $(MAKE) -C test bench + +.PHONY: bench MOSTLYCLEANFILES = $(DX_CLEANFILES) *.gcda *.gcno *.gcov DISTCLEANFILES = DIST_REVISION +clean-local: + rm -rf $(CHECK_HYGIENE_STAGE) $(abs_top_builddir)/.shared-check-stage $(CHECK_INSTALL_STAGE) + pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = libhttpserver.pc diff --git a/README.CentOS-7 b/README.CentOS-7 index 1dfaaa70..4cbaf071 100644 --- a/README.CentOS-7 +++ b/README.CentOS-7 @@ -1,7 +1,8 @@ ## Cent OS 7 / RHEL 7 -CentOS 7 has a lower version of gcc (4.8.7) that is barely C++11 capable and this library -needs a better compiler. We recommend at least gcc 5+ +CentOS 7's stock gcc (4.8.7) is far too old: this library requires a C++20 compiler +(gcc >= 10 or clang >= 13). -We recommend installing devtoolset-8 -https://www.softwarecollections.org/en/scls/rhscl/devtoolset-8/ +Install gcc-toolset-14 (or newer) from the RHEL/CentOS Software Collections and +`source /opt/rh/gcc-toolset-14/enable` before configuring. The same workaround applies +to RHEL 9 systems whose stock gcc-11 lacks some C++20 library features. diff --git a/README.md b/README.md index 7933a235..043bdb03 100644 --- a/README.md +++ b/README.md @@ -1,2837 +1,427 @@ - - -# The libhttpserver reference manual +# libhttpserver + ![GA: Build Status](https://github.com/etr/libhttpserver/actions/workflows/verify-build.yml/badge.svg) [![codecov](https://codecov.io/gh/etr/libhttpserver/branch/master/graph/badge.svg)](https://codecov.io/gh/etr/libhttpserver) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/1bd1e8c21f66400fb70e5a5ce357b525)](https://www.codacy.com/gh/etr/libhttpserver/dashboard?utm_source=github.com&utm_medium=referral&utm_content=etr/libhttpserver&utm_campaign=Badge_Grade) -[![Gitter chat](https://badges.gitter.im/etr/libhttpserver.png)](https://gitter.im/libhttpserver/community) [![ko-fi](https://www.ko-fi.com/img/donate_sm.png)](https://ko-fi.com/F1F5HY8B) -## Tl;dr -libhttpserver is a C++ library for building high performance RESTful web servers. -libhttpserver is built upon [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) to provide a simple API for developers to create HTTP services in C++. - -**Features:** -- HTTP 1.1 compatible request parser -- RESTful oriented interface -- Flexible handler API -- Cross-platform compatible -- Implementation is HTTP 1.1 compliant -- Multiple threading models -- Support for IPv6 -- Support for SHOUTcast -- Support for incremental processing of POST data (optional) -- Support for basic and digest authentication (optional) -- Support for centralized authentication with path-based skip rules -- Support for TLS (requires libgnutls, optional) -- WebSocket support (requires libmicrohttpd built with WebSocket support, optional) -- New response types: empty, iovec (scatter-gather), and pipe-based responses -- External event loop integration (run/run_wait, fd sets, add_connection) -- Daemon introspection (bound port, active connections, listen FD) -- Turbo mode for high-performance scenarios -- TCP Fast Open support -- Enhanced digest authentication with SHA-256 and SHA-512/256 algorithms - -## Table of Contents -* [Introduction](#introduction) -* [Requirements](#requirements) -* [Building](#building) -* [Getting Started](#getting-started) -* [Structures and classes type definition](#structures-and-classes-type-definition) -* [Create and work with a webserver](#create-and-work-with-a-webserver) -* [The resource object](#the-resource-object) -* [Registering resources](#registering-resources) -* [Parsing requests](#parsing-requests) -* [Building responses to requests](#building-responses-to-requests) -* [IP Blacklisting and Whitelisting](#ip-blacklisting-and-whitelisting) -* [Authentication](#authentication) -* [WebSocket Support](#websocket-support) -* [Daemon Introspection and External Event Loops](#daemon-introspection-and-external-event-loops) -* [HTTP Utils](#http-utils) -* [Other Examples](#other-examples) - -#### Community -* [Code of Conduct (on a separate page)](https://github.com/etr/libhttpserver/blob/master/CODE_OF_CONDUCT.md) -* [Contributing (on a separate page)](https://github.com/etr/libhttpserver/blob/master/CONTRIBUTING.md) - -#### Appendices -* [Copying statement](#copying) -* [GNU-LGPL](#GNU-lesser-general-public-license): The GNU Lesser General Public License says how you can copy and share almost all of libhttpserver. -* [GNU-FDL](#GNU-free-documentation-license): The GNU Free Documentation License says how you can copy and share the documentation of libhttpserver. - -## Introduction -libhttpserver is meant to constitute an easy system to build HTTP servers with REST fashion. -libhttpserver is based on [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) and, like this, it is a daemon library (parts of this documentation are, in fact, matching those of the wrapped library). -The mission of this library is to support all possible HTTP features directly and with a simple semantic allowing then the user to concentrate only on his application and not on HTTP request handling details. - -The library is supposed to work transparently for the client Implementing the business logic and using the library itself to realize an interface. -If the user wants it must be able to change every behavior of the library itself through the registration of callbacks. - -libhttpserver is able to decode certain body formats and automatically format them in object oriented fashion. This is true for query arguments and for *POST* and *PUT* requests bodies if *application/x-www-form-urlencoded* or *multipart/form-data* header are passed. - -All functions are guaranteed to be completely reentrant and thread-safe (unless differently specified). -Additionally, clients can specify resource limits on the overall number of connections, number of connections per IP address and memory used per connection to avoid resource exhaustion. - -[Back to TOC](#table-of-contents) - -## Requirements -libhttpserver can be used without any dependencies aside from libmicrohttpd. - -The minimum versions required are: -* g++ >= 5.5.0 or clang-3.6 -* C++17 or newer -* libmicrohttpd >= 1.0.0 -* [Optionally]: for TLS (HTTPS) support, you'll need [libgnutls](http://www.gnutls.org/). -* [Optionally]: to compile the code-reference, you'll need [doxygen](http://www.doxygen.nl/). - -Additionally, for MinGW on windows you will need: -* libwinpthread (For MinGW-w64, if you use thread model posix then you have this) - -For versions before 0.18.0, on MinGW, you will need: -* libgnurx >= 2.5.1 - -Furthermore, the testcases use [libcurl](http://curl.haxx.se/libcurl/) but you don't need it to compile the library. - -Please refer to the readme file for your particular distribution if there is one for important notes. - -[Back to TOC](#table-of-contents) - -## Building -libhttpserver uses the standard system where the usual build process involves running -> ./bootstrap -> mkdir build -> cd build -> \.\./configure -> make -> make install # (optionally to install on the system) - -[Back to TOC](#table-of-contents) - -### Optional parameters to configure script -A complete list of parameters can be obtained running 'configure --help'. -Here are listed the libhttpserver specific options (the canonical configure options are also supported). - -* _\-\-enable-same-directory-build:_ enable to compile in the same directory. This is heavily discouraged. (def=no) -* _\-\-enable-debug:_ enable debug data generation. (def=no) -* _\-\-disable-doxygen-doc:_ don't generate any doxygen documentation. Doxygen is automatically invoked if present on the system. Automatically disabled otherwise. -* _\-\-enable-fastopen:_ enable use of TCP_FASTOPEN (def=yes) -* _\-\-enable-static:_ enable use static linking (def=yes) - -[Back to TOC](#table-of-contents) - -### Building on Windows (MSYS2) - -MSYS2 provides multiple shell environments with different purposes. Understanding which shell to use is important: - -| Shell | Host Triplet | Runtime Dependency | Use Case | -|-------|--------------|-------------------|----------| -| **MinGW64** | `x86_64-w64-mingw32` | Native Windows | **Recommended** for native Windows apps | -| **MSYS** | `x86_64-pc-msys` | msys-2.0.dll | POSIX-style apps, build tools | - -**Recommended: Use the MinGW64 shell** for building libhttpserver to produce native Windows binaries without additional runtime dependencies. - -#### Step-by-step build instructions - -1. Install [MSYS2](https://www.msys2.org/) - -2. Open the **MINGW64** shell (not the MSYS shell) from the Start Menu - -3. Install dependencies: -```bash -pacman -S --needed mingw-w64-x86_64-{gcc,libtool,make,pkg-config,doxygen,gnutls,curl} autotools -``` - -4. Build and install [libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) (>= 1.0.0) - -5. Build libhttpserver: -```bash -./bootstrap -mkdir build && cd build -../configure --disable-fastopen -make -make check # run tests -``` - -**Important:** The `--disable-fastopen` flag is required on Windows as TCP_FASTOPEN is not supported. - -#### If you use the MSYS shell - -Building from the MSYS shell also works but the resulting binaries will depend on `msys-2.0.dll`. The configure script will display a warning when building in this environment. If you see: - -``` -configure: WARNING: Building from MSYS environment. Binaries will depend on msys-2.0.dll. -``` - -Consider switching to the MinGW64 shell for native Windows binaries. - -#### Library files on Windows - -When building with GCC-based toolchains (MSYS2/MinGW, Cygwin), the following library files are generated: - -| File | Purpose | -|------|---------| -| `libhttpserver.a` | Static library archive | -| `libhttpserver.dll` | Shared library (DLL) | -| `libhttpserver.dll.a` | Import library for linking against the DLL | -| `libhttpserver.la` | Libtool archive (used by libtool during linking) | - -**Note about `.lib` files:** The `.dll.a` format is the import library format used by GCC toolchains. If you're looking for `.lib` files, those are the MSVC (Microsoft Visual C++) import library format and are only generated when building with the MSVC toolchain. The `.dll.a` file serves the same purpose as `.lib` but for GCC-based compilers. - -**Linking against libhttpserver:** - -Using pkg-config (recommended): -```bash -g++ myapp.cpp $(pkg-config --cflags --libs libhttpserver) -o myapp -``` - -Manual linking: -```bash -g++ myapp.cpp -I/mingw64/include -L/mingw64/lib -lhttpserver -lmicrohttpd -o myapp -``` - -[Back to TOC](#table-of-contents) - -## Getting Started -The most basic example of creating a server and handling a requests for the path `/hello`: -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you could run the following command from a terminal: - - curl -XGET -v http://localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_hello_world.cpp). - -[Back to TOC](#table-of-contents) - -## Structures and classes type definition -* _webserver:_ Represents the daemon listening on a socket for HTTP traffic. - * _create_webserver:_ Builder class to support the creation of a webserver. -* _http_resource:_ Represents the resource associated with a specific http endpoint. -* _http_request:_ Represents the request received by the resource that process it. -* _http_response:_ Represents the response sent by the server once the resource finished its work. - * _string_response:_ A simple string response. - * _file_response:_ A response getting content from a file. - * _basic_auth_fail_response:_ A failure in basic authentication. - * _digest_auth_fail_response:_ A failure in digest authentication. - * _deferred_response:_ A response getting content from a callback. - * _empty_response:_ A response with no body (e.g., for 204 No Content). - * _iovec_response:_ A scatter-gather response from multiple buffers. - * _pipe_response:_ A response that streams content from a pipe file descriptor. -* _websocket_handler:_ Base class for handling WebSocket connections. Derive and implement `on_message()`. - * _websocket_session:_ Represents an active WebSocket connection with methods to send text, binary, ping/pong, and close frames. - -[Back to TOC](#table-of-contents) - -## Create and work with a webserver -As you can see from the example above, creating a webserver with standard configuration is quite simple: -```cpp - webserver ws = create_webserver(8080); -``` -The `create_webserver` class is a supporting _builder_ class that eases the building of a webserver through chained syntax. - -### Basic Startup Options - -In this section we will explore other basic options that you can use when configuring your server. More advanced options (custom callbacks, https support, etc...) will be discussed separately. - -* _.port(**int** port):_ The port at which the server will listen. This can also be passed to the consturctor of `create_webserver`. E.g. `create_webserver(8080)`. -* _.max_connections(**int** max_conns):_ Maximum number of concurrent connections to accept. The default is `FD_SETSIZE - 4` (the maximum number of file descriptors supported by `select` minus four for `stdin`, `stdout`, `stderr` and the server socket). In other words, the default is as large as possible. 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 access your “index.html” file, keep it open but use a second connection to retrieve CSS files, images and the like. In fact, modern browsers are typically by default configured for up to 15 parallel connections to a single server. If this happens, the library will refuse to even accept the second connection until the first connection is closed — which does not happen until timeout. As a result, the browser will fail to render the page and seem to hang. If you expect your server to operate close to the connection limit, you should first consider using a lower timeout value and also possibly add a “Connection: close” header to your response to ensure that request pipelining is not used and connections are closed immediately after the request has completed. -* _.content_size_limit(**size_t** size_limit):_ Sets the maximum size of the content that a client can send over in a single block. The default is `-1 = unlimited`. -* _.connection_timeout(**int** timeout):_ Determines after how many seconds of inactivity a connection should be timed out automatically. The default timeout is `180 seconds`. -* _.memory_limit(**int** memory_limit):_ Maximum memory size per connection (followed by a `size_t`). The default is 32 kB (32*1024 bytes). 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. -* _.per_IP_connection_limit(**int** 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. The default is `0`, which means no limit on the number of connections from the same IP address. -* _.bind_address(**const struct sockaddr*** address):_ Bind the server to a specific network interface by passing a pre-constructed `sockaddr` structure. This gives full control over the address configuration but requires manual socket address setup. -* _.bind_address(**const std::string&** ip):_ Bind the server to a specific network interface by IP address string (e.g., `"127.0.0.1"` for localhost only, or `"192.168.1.100"` for a specific interface). Supports both IPv4 and IPv6 addresses. When an IPv6 address is provided, IPv6 mode is automatically enabled. Example: `create_webserver(8080).bind_address("127.0.0.1")`. -* _.bind_socket(**int** socket_fd):_ Listen socket to use. Pass a listen socket for the daemon to use (systemd-style). If this option is used, the daemon will not open its own listen socket(s). The argument passed must be of type "int" and refer to an existing socket that has been bound to a port and is listening. -* _.max_thread_stack_size(**int** stack_size):_ Maximum stack size for threads created by the library. Not specifying this option or using a value of zero means using the system default (which is likely to differ based on your platform). Default is `0 (system default)`. -* _.use_ipv6() and .no_ipv6():_ Enable or disable the IPv6 protocol support (by default, libhttpserver will just support IPv4). If you specify this and the local platform does not support it, starting up the server will throw an exception. `off` by default. -* _.use_dual_stack() and .no_dual_stack():_ Enable or disable the support for both IPv6 and IPv4 protocols at the same time (by default, libhttpserver will just support IPv4). If you specify this and the local platform does not support it, starting up the server will throw an exception. Note that this will mean that IPv4 addresses are returned in the IPv6-mapped format (the ’structsockaddrin6’ format will be used for IPv4 and IPv6). `off` by default. -* _.pedantic() and .no_pedantic():_ Enables pedantic checks about the protocol (as opposed to as tolerant as possible). Specifically, at the moment, this flag causes the library 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 turn this **off** if you are testing clients against the library, and **on** in production. `off` by default. -* _.debug() and .no_debug():_ Enables debug messages from the library. `off` by default. -* _.regex_checking() and .no_regex_checking():_ Enables pattern matching for endpoints. Read more [here](#registering-resources). `on` by default. -* _.post_process() and .no_post_process():_ Enables/Disables the library to automatically parse the body of the http request as arguments if in querystring format. Read more [here](#parsing-requests). `on` by default. -* _.put_processed_data_to_content() and .no_put_processed_data_to_content():_ Enables/Disables the library to copy parsed body data to the content or to only store it in the arguments map. `on` by default. -* _.file_upload_target(**file_upload_target_T** file_upload_target):_ Controls, how the library stores uploaded files. Default value is `FILE_UPLOAD_MEMORY_ONLY`. - * `FILE_UPLOAD_MEMORY_ONLY`: The content of the file is only stored in memory. Depending on `put_processed_data_to_content` only as part of the arguments map or additionally in the content. - * `FILE_UPLOAD_DISK_ONLY`: The content of the file is stored only in the file system. The path is created from `file_upload_dir` and either a random name (if `generate_random_filename_on_upload` is true) or the actually uploaded file name. - * `FILE_UPLOAD_MEMORY_AND_DISK`: The content of the file is stored in memory and on the file system. -* _.file_upload_dir(**const std::string&** file_upload_dir):_ Specifies the directory to store all uploaded files. Default value is `/tmp`. -* _.generate_random_filename_on_upload() and .no_generate_random_filename_on_upload():_ Enables/Disables the library to generate a unique and unused filename to store the uploaded file to. Otherwise the actually uploaded file name is used. `off` by default. -* _.file_cleanup_callback(**file_cleanup_callback_ptr** callback):_ Sets a callback function to control what happens to uploaded files when the request completes. By default (when no callback is set), all uploaded files are automatically deleted. The callback signature is `bool(const std::string& key, const std::string& filename, const http::file_info& info)` where `key` is the form field name, `filename` is the original uploaded filename, and `info` contains file metadata including the filesystem path. Return `true` to delete the file (default behavior) or `false` to keep it (e.g., after moving it to permanent storage). If the callback throws an exception, the file will be deleted as a safety measure. -* _.deferred()_ and _.no_deferred():_ Enables/Disables the ability for the server to suspend and resume connections. Simply put, it enables/disables the ability to use `deferred_response`. Read more [here](#building-responses-to-requests). `on` by default. -* _.single_resource() and .no_single_resource:_ Sets or unsets the server in single resource mode. This limits all endpoints to be served from a single resource. The resultant is that the webserver will process the request matching to the endpoint skipping any complex semantic. Because of this, the option is incompatible with `regex_checking` and requires the resource to be registered against an empty endpoint or the root endpoint (`"/"`). The resource will also have to be registered as family. (For more information on resource registration, read more [here](#registering-resources)). `off` by default. -* _.no_listen_socket():_ Run the daemon without a listening socket. The server will not bind to any port on its own; instead, you must provide connections externally via `add_connection()`. Useful for integrating with an external accept loop or passing sockets from systemd or another process. `off` by default. -* _.no_thread_safety():_ Disable internal thread-safety mechanisms. This can improve performance when you guarantee that only a single thread will access the daemon at a time. **Only use this if you are sure you do not need concurrent access.** `off` by default. -* _.turbo():_ Enable turbo mode. This is a performance optimization that allows the daemon to skip certain internal operations. Requires the application to meet specific threading and response constraints — consult the libmicrohttpd documentation for details. `off` by default. -* _.suppress_date_header():_ Suppress the automatic addition of a `Date:` header in responses. Useful for reproducible tests or when the application manages its own date headers. `off` by default. -* _.listen_backlog(**int** backlog):_ Set the TCP listen backlog size. Higher values allow more pending connections in the kernel queue. Default is `0` (system default). -* _.address_reuse(**int** reuse):_ Control address reuse (`SO_REUSEADDR`/`SO_REUSEPORT`). Pass `1` to enable, `-1` to disable. Default is `0` (system default). -* _.connection_memory_increment(**size_t** increment):_ Increment size for per-connection memory allocation when the initial pool is exhausted. Default is `0` (system default, typically 1024 bytes). -* _.tcp_fastopen_queue_size(**int** queue_size):_ Set the size of the TCP Fast Open queue. When set, enables TCP Fast Open with the specified queue depth. Default is `0` (disabled). -* _.sigpipe_handled_by_app():_ Inform the daemon that the application is handling `SIGPIPE` on its own, so libmicrohttpd should not install a handler. `off` by default. -* _.client_discipline_level(**int** level):_ Controls how strictly the server enforces HTTP protocol compliance. Higher values make the server stricter with misbehaving clients. Default is `-1` (use libmicrohttpd default). - -### Threading Models -* _.start_method(**const http::http_utils::start_method_T&** start_method):_ libhttpserver can operate with two different threading models that can be selected through this method. Default value is `INTERNAL_SELECT`. - * `http::http_utils::INTERNAL_SELECT`: In this mode, libhttpserver uses only a single thread to handle listening on the port and processing of requests. This mode is preferable if spawning a thread for each connection would be costly. If the HTTP server is able to quickly produce responses without much computational overhead for each connection, this mode can be a great choice. Note that libhttpserver will still start a single thread for itself -- this way, the main program can continue with its operations after calling the start method. Naturally, if the HTTP server needs to interact with shared state in the main application, synchronization will be required. If such synchronization in code providing a response results in blocking, all HTTP server operations on all connections will stall. This mode is a bad choice if response data cannot always be provided instantly. The reason is that the code generating responses should not block (since that would block all other connections) and on the other hand, if response data is not available immediately, libhttpserver will start to busy wait on it. If you need to scale along the number of concurrent connection and scale on multiple thread you can specify a value for `max_threads` (see below) thus enabling a thread pool - this is different from `THREAD_PER_CONNECTION` below where a new thread is spawned for each connection. - * `http::http_utils::THREAD_PER_CONNECTION`: In this mode, libhttpserver starts one thread to listen on the port for new connections and then spawns a new thread to handle each connection. This mode is great if the HTTP server has hardly any state that is shared between connections (no synchronization issues!) and may need to perform blocking operations (such as extensive IO or running of code) to handle an individual connection. -* _.max_threads(**int** max_threads):_ A thread pool can be combined with the `INTERNAL_SELECT` mode to benefit implementations that require scalability. As said before, by default this mode only uses a single thread. When combined with the thread pool option, it is possible to handle multiple connections with multiple threads. Any value greater than one for this option will activate the use of the thread pool. In contrast to the `THREAD_PER_CONNECTION` mode (where each thread handles one and only one connection), threads in the pool can handle a large number of concurrent connections. Using `INTERNAL_SELECT` in combination with a thread pool is typically the most scalable (but also hardest to debug) mode of operation for libhttpserver. Default value is `1`. This option is incompatible with `THREAD_PER_CONNECTION`. - -### Custom defaulted error messages -libhttpserver allows to override internal error retrieving functions to provide custom messages to the HTTP client. There are only 3 cases in which implementing logic (an http_resource) cannot be invoked: (1) a not found resource, where the library is not being able to match the URL requested by the client to any implementing http_resource object; (2) a not allowed method, when the HTTP client is requesting a method explicitly marked as not allowed (more info [here](#allowing-and-disallowing-methods-on-a-resource)) by the implementation; (3) an exception being thrown. -In all these 3 cases libhttpserver would provide a standard HTTP response to the client with the correct error code; respectively a `404`, a `405` and a `500`. The library allows its user to specify custom callbacks that will be called to replace the default behavior. -* _.not_found_resource(**const shared_ptr(*render_ptr)(const http_request&)** resource):_ Specifies a function to handle a request when no matching registered endpoint exist for the URL requested by the client. -* _.method_not_allowed_resource(**const shared_ptr(*render_ptr)(const http_request&)** resource):_ Specifies a function to handle a request that is asking for a method marked as not allowed on the matching http_resource. -* _.internal_error_resource(**const shared_ptr(*render_ptr)(const http_request&)** resource):_ Specifies a function to handle a request that is causing an uncaught exception during its execution. **REMEMBER:** is this callback is causing an exception itself, the standard default response from libhttpserver will be reported to the HTTP client. - -#### Example of custom errors: -```cpp - #include - - using namespace httpserver; - - std::shared_ptr not_found_custom(const http_request& req) { - return std::shared_ptr(new string_response("Not found custom", 404, "text/plain")); - } - - std::shared_ptr not_allowed_custom(const http_request& req) { - return std::shared_ptr(new string_response("Not allowed custom", 405, "text/plain")); - } - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080) - .not_found_resource(not_found_custom) - .method_not_allowed_resource(not_allowed_custom); - - hello_world_resource hwr; - hwr.disallow_all(); - hwr.set_allowing("GET", true); - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v http://localhost:8080/hello - -If you try to run either of the two following commands, you'll see your custom errors: -* `curl -XGET -v http://localhost:8080/morning`: will return your custom `not found` error. -* `curl -XPOST -v http://localhost:8080/hello`: will return your custom `not allowed` error. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/custom_error.cpp). - -### Custom logging callbacks -* _.log_access(**void(*log_access_ptr)(const std::string&)** functor):_ Specifies a function used to log accesses (requests) to the server. -* _.log_error(**void(*log_error_ptr)(const std::string&)** functor):_ Specifies a function used to log errors generating from the server. - -#### Example of custom logging callback -```cpp - #include - #include - - using namespace httpserver; - - void custom_access_log(const std::string& url) { - std::cout << "ACCESSING: " << url << std::endl; - } - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080) - .log_access(custom_access_log); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v http://localhost:8080/hello - -You'll notice how, on the terminal runing your server, the logs will now be printed in output for each request received. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/custom_access_log.cpp). - -### TLS/HTTPS -* _.use_ssl() and .no_ssl():_ Determines whether to run in HTTPS-mode or not. If you set this as on and libhttpserver was compiled without SSL support, the library will throw an exception at start of the server. `off` by default. -* _.cred_type(**const http::http_utils::cred_type_T&** cred_type):_ Daemon credentials type. Either certificate or anonymous. Acceptable values are: - * `NONE`: No credentials. - * `CERTIFICATE`: Certificate credential. - * `ANON`: Anonymous credential. - * `SRP`: SRP credential. - * `PSK`: PSK credential. - * `IA`: IA credential. -* _.https_mem_key(**const std::string&** filename):_ String representing the path to a file containing the private key to be used by the HTTPS daemon. This must be used in conjunction with `https_mem_cert`. -* _.https_mem_cert(**const std::string&** filename):_ String representing the path to a file containing the certificate to be used by the HTTPS daemon. This must be used in conjunction with `https_mem_key`. -* _.https_mem_trust(**const std::string&** filename):_ String representing the path to a file containing the CA certificate to be used by the HTTPS daemon to authenticate and trust clients certificates. The presence of this option activates the request of certificate to the client. The request to the client is marked optional, and it is the responsibility of the server to check the presence of the certificate if needed. Note that most browsers will only present a client certificate only if they have one matching the specified CA, not sending any certificate otherwise. -* _.https_priorities(**const std::string&** priority_string):_ SSL/TLS protocol version and ciphers. Must be followed by a string specifying the SSL/TLS protocol versions and ciphers that are acceptable for the application. The string is passed unchanged to gnutls_priority_init. If this option is not specified, `"NORMAL"` is used. -* _.psk_cred_handler(**psk_cred_handler_callback** handler):_ Sets a callback function for TLS-PSK (Pre-Shared Key) authentication. The callback receives a username and should return the corresponding hex-encoded PSK, or an empty string if the user is unknown. This option requires `use_ssl()`, `cred_type(http::http_utils::PSK)`, and an appropriate `https_priorities()` string that enables PSK cipher suites. PSK authentication allows TLS without certificates by using a shared secret key. -* _.sni_callback(**sni_callback_t** callback):_ Sets a callback function for SNI (Server Name Indication) support. The callback receives the server name requested by the client and should return a `std::pair` containing the PEM-encoded certificate and key for that server name. Return empty strings to use the default certificate. Requires libmicrohttpd 1.0.0+ with GnuTLS. -* _.https_mem_dhparams(**const std::string&** dhparams):_ String containing the Diffie-Hellman (DH) parameters in PEM format. This is used for DHE key exchange in TLS. If not specified, default DH parameters may be used. -* _.https_key_password(**const std::string&** password):_ Password for the private key specified by `https_mem_key`, if the key file is encrypted. -* _.https_priorities_append(**const std::string&** priorities):_ Additional GnuTLS priorities to append to the base priority string. Unlike `https_priorities()` which replaces the entire string, this appends to the default, making it easier to adjust specific cipher suites or algorithms. -* _.no_alpn():_ Disable Application-Layer Protocol Negotiation (ALPN) for TLS connections. `off` by default. - -#### Minimal example using HTTPS -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080) - .use_ssl() - .https_mem_key("key.pem") - .https_mem_cert("cert.pem"); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v -k 'https://localhost:8080/hello' - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_https.cpp). - -#### Minimal example using TLS-PSK -```cpp - #include - #include - #include - - using namespace httpserver; - - // Simple PSK database - in production, use secure storage - std::map psk_database = { - {"client1", "0123456789abcdef0123456789abcdef"}, - {"client2", "fedcba9876543210fedcba9876543210"} - }; - - // PSK credential handler callback - std::string psk_handler(const std::string& username) { - auto it = psk_database.find(username); - if (it != psk_database.end()) { - return it->second; - } - return ""; // Return empty string for unknown users - } - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr( - new string_response("Hello, World (via TLS-PSK)!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080) - .use_ssl() - .cred_type(http::http_utils::PSK) - .psk_cred_handler(psk_handler) - .https_priorities("NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2:+PSK:+DHE-PSK"); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal using gnutls-cli: - - gnutls-cli --pskusername=client1 --pskkey=0123456789abcdef0123456789abcdef -p 8080 localhost - -Then type `GET /hello HTTP/1.1` followed by `Host: localhost` and two newlines. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_https_psk.cpp). - -### IP Blacklisting/Whitelisting -libhttpserver supports IP blacklisting and whitelisting as an internal feature. This section explains the startup options related with IP blacklisting/whitelisting. See the [specific section](#ip-blacklisting-and-whitelisting) to read more about the topic. -* _.ban_system() and .no_ban_system:_ Can be used to enable/disable the ban system. `on` by default. -* _.default_policy(**const http::http_utils::policy_T&** default_policy):_ Specifies what should be the default behavior when receiving a request. Possible values are `ACCEPT` and `REJECT`. Default is `ACCEPT`. - -### Authentication Parameters -* _.basic_auth() and .no_basic_auth:_ Can be used to enable/disable parsing of the basic authorization header sent by the client. `on` by default. -* _.digest_auth() and .no_digest_auth:_ Can be used to enable/disable parsing of the digested authentication data sent by the client. `on` by default. -* _.nonce_nc_size(**int** nonce_size):_ Size of an array of nonce and nonce counter map. This option represents the size (number of elements) of a map of a nonce and a nonce-counter. If this option is not specified, a default value of 4 will be used (which might be too small for servers handling many requests). -You should calculate the value of NC_SIZE based on the number of connections per second multiplied by your expected session duration plus a factor of about two for hash table collisions. For example, if you expect 100 digest-authenticated connections per second and the average user to stay on your site for 5 minutes, then you likely need a value of about 60000. On the other hand, if you can only expect only 10 digest-authenticated connections per second, tolerate browsers getting a fresh nonce for each request and expect a HTTP request latency of 250 ms, then a value of about 5 should be fine. -* _.digest_auth_random(**const std::string&** nonce_seed):_ Digest Authentication nonce’s seed. For security, you SHOULD provide a fresh random nonce when actually using Digest Authentication with libhttpserver in production. - -### Examples of chaining syntax to create a webserver -```cpp - webserver ws = create_webserver(8080) - .no_ssl() - .no_ipv6() - .no_debug() - .no_pedantic() - .no_basic_auth() - .no_digest_auth() - .no_comet() - .no_regex_checking() - .no_ban_system() - .no_post_process(); -``` -## -```cpp - webserver ws = create_webserver(8080) - .use_ssl() - .https_mem_key("key.pem") - .https_mem_cert("cert.pem"); -``` -### Starting and stopping a webserver -Once a webserver is created, you can manage its execution through the following methods on the `webserver` class: -* _**void** webserver::start(**bool** blocking):_ Allows to start a server. If the `blocking` flag is passed as `true`, it will block the execution of the current thread until a call to stop on the same webserver object is performed. -* _**void** webserver::stop():_ Allows to stop a server. It immediately stops it. -* _**bool** webserver::is_running():_ Checks if a server is running -* _**void** webserver::sweet_kill():_ Allows to stop a server. It doesn't guarantee an immediate halt to allow for thread termination and connection closure. -* _**int** webserver::quiesce():_ Quiesce the daemon: stop accepting new connections while letting in-flight requests complete. Returns the listen socket file descriptor (the caller can close it), or `-1` on error. -* _**bool** webserver::run():_ Run the webserver's event loop once (non-blocking). For use with external event loops when the server is started without internal threading. Returns `true` on success. -* _**bool** webserver::run_wait(**int32_t** millisec):_ Run the webserver's event loop, blocking until there is activity or the timeout expires. Pass `-1` for indefinite wait. Returns `true` on success. -* _**bool** webserver::get_fdset(**fd_set*** read_fd_set, **fd_set*** write_fd_set, **fd_set*** except_fd_set, **int*** max_fd):_ Get the file descriptor sets for `select()`-based external event loop integration. Returns `true` on success. -* _**bool** webserver::get_timeout(**uint64_t*** timeout):_ Get the timeout (in milliseconds) until the next daemon action is needed. Returns `true` if a timeout was set, `false` if no timeout is needed. -* _**bool** webserver::add_connection(**int** client_socket, **const struct sockaddr*** addr, **socklen_t** addrlen):_ Add an externally-accepted socket connection to the daemon. Useful with `no_listen_socket()`. Returns `true` on success. -* _**int** webserver::get_listen_fd():_ Get the listen socket file descriptor, or `-1` if not available. -* _**unsigned int** webserver::get_active_connections():_ Get the number of currently active connections. -* _**uint16_t** webserver::get_bound_port():_ Get the actual port the daemon is bound to. Particularly useful when port `0` was specified to let the OS choose an ephemeral port. - -[Back to TOC](#table-of-contents) - -## The Resource Object -The `http_resource` class represents a logical collection of HTTP methods that will be associated to a URL when registered on the webserver. The class is **designed for extension** and it is where most of your code should ideally live. When the webserver matches a request against a resource (see: [resource registration](#registering-resources)), the method correspondent to the one in the request (GET, POST, etc..) (see below) is called on the resource. - -Given this, the `http_resource` class contains the following extensible methods (also called `handlers` or `render methods`): -* _**std::shared_ptr** http_resource::render_GET(**const http_request&** req):_ Invoked on an HTTP GET request. -* _**std::shared_ptr** http_resource::render_POST(**const http_request&** req):_ Invoked on an HTTP POST request. -* _**std::shared_ptr** http_resource::render_PUT(**const http_request&** req):_ Invoked on an HTTP PUT request. -* _**std::shared_ptr** http_resource::render_HEAD(**const http_request&** req):_ Invoked on an HTTP HEAD request. -* _**std::shared_ptr** http_resource::render_DELETE(**const http_request&** req):_ Invoked on an HTTP DELETE request. -* _**std::shared_ptr** http_resource::render_TRACE(**const http_request&** req):_ Invoked on an HTTP TRACE request. -* _**std::shared_ptr** http_resource::render_OPTIONS(**const http_request&** req):_ Invoked on an HTTP OPTIONS request. -* _**std::shared_ptr** http_resource::render_CONNECT(**const http_request&** req):_ Invoked on an HTTP CONNECT request. -* _**std::shared_ptr** http_resource::render(**const http_request&** req):_ Invoked as a backup method if the matching method is not implemented. It can be used whenever you want all the invocations on a URL to activate the same behavior regardless of the HTTP method requested. The default implementation of the `render` method returns an empty response with a `404`. - -#### Example of implementation of render methods -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::shared_ptr(new string_response("GET: Hello, World!")); - } - - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("OTHER: Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following commands from a terminal: - * `curl -XGET -v http://localhost:8080/hello`: will return `GET: Hello, World!`. - * `curl -XPOST -v http://localhost:8080/hello`: will return `OTHER: Hello, World!`. You can try requesting other methods beside `POST` to verify how the same message will be returned. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/handlers.cpp). - -### Allowing and disallowing methods on a resource -By default, all methods an a resource are allowed, meaning that an HTTP request with that method will be invoked. It is possible to mark methods as `not allowed` on a resource. When a method not allowed is requested on a resource, the default `method_not_allowed` method is invoked - the default can be overriden as explain in the section [Custom defaulted error messages](custom-defaulted-error-messages). -The base `http_resource` class has a set of methods that can be used to allow and disallow HTTP methods. -* _**void** http_resource::set_allowing(**const std::string&** method, **bool** allowed):_ Used to allow or disallow a method. The `method` parameter is a string representing an HTTP method (GET, POST, PUT, etc...). -* _**void** http_resource::allow_all():_ Marks all HTTP methods as allowed. -* _**void** http_resource::disallow_all():_ Marks all HTTP methods as not allowed. - -#### Example of methods allowed/disallowed -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - hwr.disallow_all(); - hwr.set_allowing("GET", true); - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v http://localhost:8080/hello - -If you try to run the following command, you'll see a `method_not_allowed` error: -* `curl -XPOST -v http://localhost:8080/hello`. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/allowing_disallowing_methods.cpp). - -[Back to TOC](#table-of-contents) - -## Registering resources -Once you have created your resource and extended its methods, you'll have to register the resource on the webserver. Registering a resource will associate it with an endpoint and allows the webserver to route it. -The `webserver` class offers a method to register a resource: -* _**bool** register_resource(**const std::string&** endpoint, **http_resource*** resource, **bool** family = `false`):_ Registers the `resource` to an `endpoint`. The endpoint is a string representing the path on your webserver from where you want your resource to be served from (e.g. `"/path/to/resource"`). The optional `family` parameter allows to register a resource as a "family" resource that will match any path nested into the one specified. For example, if family is set to `true` and endpoint is set to `"/path"`, the webserver will route to the resource not only the requests against `"/path"` but also everything in its nested path `"/path/on/the/previous/one"`. - -### Specifying endpoints -There are essentially four ways to specify an endpoint string: -* **A simple path (e.g. `"/path/to/resource"`).** In this case, the webserver will try to match exactly the value of the endpoint. -* **A regular exception.** In this case, the webserver will try to match the URL of the request with the regex passed. For example, if passing `"/path/as/decimal/[0-9]+`, requests on URLs like `"/path/as/decimal/5"` or `"/path/as/decimal/42"` will be matched; instead, URLs like `"/path/as/decimal/three"` will not. -* **A parametrized path. (e.g. `"/path/to/resource/with/{arg1}/{arg2}/in/url"`)**. In this case, the webserver will match the argument with any value passed. In addition to this, the arguments will be passed to the resource as part of the arguments (readable from the `http_request::get_arg` method - see [here](#parsing-requests)). For example, if passing `"/path/to/resource/with/{arg1}/{arg2}/in/url"` will match any request on URL with any value in place of `{arg1}` and `{arg2}`. -* **A parametrized path with custom parameters.** This is the same of a normal parametrized path, but allows to specify a regular expression for the argument (e.g. `"/path/to/resource/with/{arg1|[0-9]+}/{arg2|[a-z]+}/in/url"`. In this case, the webserver will match the arguments with any value passed that satisfies the regex. In addition to this, as above, the arguments will be passed to the resource as part of the arguments (readable from the `http_request::get_arg` method - see [here](#parsing-requests)). For example, if passing `"/path/to/resource/with/{arg1|[0-9]+}/{arg2|[a-z]+}/in/url"` will match requests on URLs like `"/path/to/resource/with/10/AA/in/url"` but not like `""/path/to/resource/with/BB/10/in/url""` -* Any of the above marked as `family`. Will match any request on URLs having path that is prefixed by the path passed. For example, if family is set to `true` and endpoint is set to `"/path"`, the webserver will route to the resource not only the requests against `"/path"` but also everything in its nested path `"/path/on/the/previous/one"`. -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - class handling_multiple_resource : public http_resource { - public: - std::shared_ptr render(const http_request& req) { - return std::shared_ptr(new string_response("Your URL: " + req.get_path())); - } - }; - - class url_args_resource : public http_resource { - public: - std::shared_ptr render(const http_request& req) { - std::string arg1(req.get_arg("arg1")); - std::string arg2(req.get_arg("arg2")); - return std::shared_ptr(new string_response("ARGS: " + arg1 + " and " + arg2)); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - - handling_multiple_resource hmr; - ws.register_resource("/family", &hmr, true); - ws.register_resource("/with_regex_[0-9]+", &hmr); - - url_args_resource uar; - ws.register_resource("/url/with/{arg1}/and/{arg2}", &uar); - ws.register_resource("/url/with/parametric/args/{arg1|[0-9]+}/and/{arg2|[A-Z]+}", &uar); - - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following commands from a terminal: - -* `curl -XGET -v http://localhost:8080/hello`: will return the `Hello, World!` message. -* `curl -XGET -v http://localhost:8080/family`: will return the `Your URL: /family` message. -* `curl -XGET -v http://localhost:8080/family/with/suffix`: will return the `Your URL: /family/with/suffix` message. -* `curl -XGET -v http://localhost:8080/with_regex_10`: will return the `Your URL: /with_regex_10` message. -* `curl -XGET -v http://localhost:8080/url/with/AA/and/BB`: will return the `ARGS: AA and BB` message. You can change `AA` and `BB` with any value and observe how the URL is still matched and parameters are read. -* `curl -XGET -v http://localhost:8080/url/with/parametric/args/10/and/AA`: will return the `ARGS: 10 and AA` message. You can change `10` and `AA` with any value matching the regexes and observe how the URL is still matched and parameters are read. - -Conversely, you can observe how these URL will not be matched (al the following will give you a `not found` message): -* `curl -XGET -v http://localhost:8080/with_regex_A` -* `curl -XGET -v http://localhost:8080/url/with/parametric/args/AA/and/BB` - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/url_registration.cpp). - -[Back to TOC](#table-of-contents) - -## Parsing requests -As seen in the documentation of [http_resource](#the-resource-object), every extensible method takes in input a `http_request` object. The webserver takes the responsibility to extract the data from the HTTP request on the network and does all the heavy lifting to build the instance of `http_request`. - -The `http_request` class has a set of methods you will have access to when implementing your handlers: -* _**const std::string&** get_path() **const**:_ Returns the path as requested from the HTTP client. -* _**const std::vector\&** get_path_pieces() **const**:_ Returns the components of the path requested by the HTTP client (each piece of the path split by `'/'`. -* _**const std::string&** get_path_piece(int index) **const**:_ Returns one piece of the path requested by the HTTP client. The piece is selected through the `index` parameter (0-indexed). -* _**const std::string&** get_method() **const**:_ Returns the method requested by the HTTP client. -* _**std::string_view** get_header(**std::string_view** key) **const**:_ Returns the header with name equal to `key` if present in the HTTP request. Returns an `empty string` otherwise. -* _**std::string_view** get_cookie(**std::string_view** key) **const**:_ Returns the cookie with name equal to `key` if present in the HTTP request. Returns an `empty string` otherwise. -* _**std::string_view** get_footer(**std::string_view** key) **const**:_ Returns the footer with name equal to `key` if present in the HTTP request (only for http 1.1 chunked encodings). Returns an `empty string` otherwise. -* _**http_arg_value** get_arg(**std::string_view** key) **const**:_ Returns the argument with name equal to `key` if present in the HTTP request. Arguments can be (1) querystring parameters, (2) path argument (in case of parametric endpoint, (3) parameters parsed from the HTTP request body if the body is in `application/x-www-form-urlencoded` or `multipart/form-data` formats and the postprocessor is enabled in the webserver (enabled by default). Arguments are collected in a domain object that allows to collect multiple arguments with the same key while keeping the access transparent in the most common case of a single value provided per key. -* _**std::string_view** get_arg_flat(**std::string_view** key) **const**_ Returns the argument in the same way as `get_arg` but as a string. If multiple values are provided with the same key, this method only returns the first value provided. -* _**const std::map** get_headers() **const**:_ Returns a map containing all the headers present in the HTTP request. -* _**const std::map** get_cookies() **const**:_ Returns a map containing all the cookies present in the HTTP request. -* _**const std::map** get_footers() **const**:_ Returns a map containing all the footers present in the HTTP request (only for http 1.1 chunked encodings). -* _**const std::map** get_args() **const**:_ Returns all the arguments present in the HTTP request. Arguments can be (1) querystring parameters, (2) path argument (in case of parametric endpoint, (3) parameters parsed from the HTTP request body if the body is in `application/x-www-form-urlencoded` or `multipart/form-data` formats and the postprocessor is enabled in the webserver (enabled by default). For each key, arguments are collected in a domain object that allows to collect multiple arguments with the same key while keeping the access transparent in the most common case of a single value provided per key. -* _**const std::map** get_args_flat() **const**:_ Returns all the arguments as the `get_args` method but as strings. If multiple values are provided with the same key, this method will only return the first value provided. -* _**const std::map>** get_files() **const**:_ Returns information about all the uploaded files (if the files are stored to disk). This information includes the key (as identifier of the outer map), the original file name (as identifier of the inner map) and a class `file_info`, which includes the size of the file and the path to the file in the file system. -* _**const std::string&** get_content() **const**:_ Returns the body of the HTTP request. -* _**bool** content_too_large() **const**:_ Returns `true` if the body length of the HTTP request sent by the client is longer than the max allowed on the server. -* _**const std::string** get_querystring() **const**:_ Returns the `querystring` of the HTTP request. -* _**const std::string&** get_version() **const**:_ Returns the HTTP version of the client request. -* _**const std::string** get_requestor() **const**:_ Returns the IP from which the client is sending the request. -* _**unsigned short** get_requestor_port() **const**:_ Returns the port from which the client is sending the request. -* _**const std::string** get_user() **const**:_ Returns the `user` as self-identified through basic authentication. The content of the user header will be parsed only if basic authentication is enabled on the server (enabled by default). -* _**const std::string** get_pass() **const**:_ Returns the `password` as self-identified through basic authentication. The content of the password header will be parsed only if basic authentication is enabled on the server (enabled by default). -* _**const std::string** get_digested_user() **const**:_ Returns the `digested user` as self-identified through digest authentication. The content of the user header will be parsed only if digest authentication is enabled on the server (enabled by default). -* _**bool** check_digest_auth(**const std::string&** realm, **const std::string&** password, **int** nonce_timeout, **bool*** reload_nonce) **const**:_ Allows to check the validity of the authentication token sent through digest authentication (if the provided values in the WWW-Authenticate header are valid and sound according to RFC2716). Takes in input the `realm` of validity of the authentication, the `password` as known to the server to compare against, the `nonce_timeout` to indicate how long the nonce is valid and `reload_nonce` a boolean that will be set by the method to indicate a nonce being reloaded. The method returns `true` if the authentication is valid, `false` otherwise. -* _**bool** has_tls_session() **const**:_ Tests if there is an underlying TLS state of the current request. -* _**gnutls_session_t** get_tls_session() **const**:_ Returns the underlying TLS state of the current request for inspection. (It is an error to call this if the state does not exist.) -* _**bool** has_client_certificate() **const**:_ Returns `true` if the client presented a certificate during the TLS handshake. Requires GnuTLS support. -* _**std::string** get_client_cert_dn() **const**:_ Returns the Distinguished Name (DN) from the client certificate's subject field (e.g., "CN=John Doe,O=Example Corp"). Returns empty string if no client certificate. -* _**std::string** get_client_cert_issuer_dn() **const**:_ Returns the Distinguished Name of the certificate issuer. Returns empty string if no client certificate. -* _**std::string** get_client_cert_cn() **const**:_ Returns the Common Name (CN) from the client certificate's subject. Returns empty string if no client certificate or no CN field. -* _**bool** is_client_cert_verified() **const**:_ Returns `true` if the client certificate was verified against the trust store configured via `https_mem_trust()`. Returns `false` if verification failed or no TLS session. -* _**std::string** get_client_cert_fingerprint_sha256() **const**:_ Returns the SHA-256 fingerprint of the client certificate as a lowercase hex string (64 characters). Returns empty string if no client certificate. -* _**time_t** get_client_cert_not_before() **const**:_ Returns the start of the certificate validity period. Returns -1 if no client certificate. -* _**time_t** get_client_cert_not_after() **const**:_ Returns the end of the certificate validity period. Returns -1 if no client certificate. - -Details on the `http::file_info` structure. - -* _**size_t** get_file_size() **const**:_ Returns the size of the file uploaded through the HTTP request. -* _**const std::string** get_file_system_file_name() **const**:_ Returns the name of the file uploaded through the HTTP request as stored on the filesystem. -* _**const std::string** get_content_type() **const**:_ Returns the content type of the file uploaded through the HTTP request. -* _**const std::string** get_transfer_encoding() **const**:_ Returns the transfer encoding of the file uploaded through the HTTP request. - -#### Example of keeping uploaded files -By default, uploaded files are automatically deleted when the request completes. To keep files (e.g., move them to permanent storage), use the `file_cleanup_callback`: - -```cpp +libhttpserver is a C++20 library for building RESTful HTTP servers on top of +[GNU libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/). v2.0 is a +lambda-first redesign: a working server is ten lines, handlers are +`std::function`s, responses are value-typed, and every public method is +thread-safe by contract. + +This README introduces the v2.0 API. It is not exhaustive: the headers under +[`src/httpserver/`](src/httpserver/) and the [`examples/`](examples/) tree are +the authoritative reference. + +```cpp +// Copyright 2026 Sebastiano Merlino +// libhttpserver hello-world example — the lambda form (PRD §3.4). +// Compiles in ten lines including main(), with no http_resource subclass +// and no raw-pointer ownership. Production code typically qualifies names +// explicitly; the `using namespace` here is a one-off so this file can +// document the shortest possible end-to-end demo. See shared_state.cpp +// for the class-based pattern that is appropriate when handlers must +// share mutable state. #include -#include - -using namespace httpserver; - +using namespace httpserver; // NOLINT(build/namespaces) - keep the demo at <=10 LOC int main() { - webserver ws = create_webserver(8080) - .file_upload_target(FILE_UPLOAD_DISK_ONLY) - .file_upload_dir("/tmp/uploads") - .file_cleanup_callback([](const std::string& key, - const std::string& filename, - const http::file_info& info) { - // Move file to permanent storage - std::string dest = "/var/uploads/" + filename; - std::rename(info.get_file_system_file_name().c_str(), dest.c_str()); - return false; // Don't delete - we moved it - }); - - // ... register resources and start server + webserver ws{create_webserver(8080)}; + ws.on_get("/hello", [](const http_request&) { + return http_response::string("Hello, World!"); + }); + ws.start(true); } ``` -To test file uploads, you can run the following command from a terminal: - - curl -XPOST -F "file=@/path/to/your/file.txt" 'http://localhost:8080/upload' - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/file_upload_with_callback.cpp). - -Details on the `http_arg_value` structure. - -* _**std::string_view** get_flat_value() **const**:_ Returns only the first value provided for the key. -* _**std::vector\** get_all_values() **const**:_ Returns all the values provided for the key. -* _**operator** std::string() **const**:_ Converts the http_arg_value to a string with the same logic as `get_flat_value`. -* _**operator** std::string_view() **const**:_ Converts the http_arg_value to a string_view with the same logic as `get_flat_value`. -* _**operator** std::vector\() **const**:_ Converts the http_arg_value to a std::vector with the same logic as `get_value`. - -#### Example of handler reading arguments from a request -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request& req) { - return std::shared_ptr(new string_response("Hello: " + std::string(req.get_arg("name")))); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v "http://localhost:8080/hello?name=John" - -You will receive the message `Hello: John` in reply. Given that the body post processing is enabled, you can also run `curl -d "name=John" -X POST http://localhost:8080/hello` to obtain the same result. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/hello_with_get_arg.cpp). - -[Back to TOC](#table-of-contents) - -## Building responses to requests -As seen in the documentation of [http_resource](#the-resource-object), every extensible method returns in output a `http_response` object. The webserver takes the responsibility to convert the `http_response` object you create into a response on the network. - -There are 8 types of response that you can create - we will describe them here through their constructors: -* _string_response(**const std::string&** content, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`):_ The most basic type of response. It uses the `content` string passed in construction as body of the HTTP response. The other two optional parameters are the `response_code` and the `content_type`. You can find constant definition for the various response codes within the [http_utils](https://github.com/etr/libhttpserver/blob/master/src/httpserver/http_utils.hpp) library file. Note that `std::string` can hold arbitrary binary data (including null bytes), so `string_response` is also the right choice for serving binary content such as images directly from memory — simply set an appropriate `content_type` (e.g., `"image/png"`). -* _file_response(**const std::string&** filename, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`):_ Uses the `filename` passed in construction as pointer to a file on disk. The body of the HTTP response will be set using the content of the file. The file must be a regular file and exist on disk. Otherwise libhttpserver will return an error 500 (Internal Server Error). The other two optional parameters are the `response_code` and the `content_type`. You can find constant definition for the various response codes within the [http_utils](https://github.com/etr/libhttpserver/blob/master/src/httpserver/http_utils.hpp) library file. -* _basic_auth_fail_response(**const std::string&** content, **const std::string&** realm = `""`, **bool** prefer_utf8 = `true`, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`):_ A response in return to a failure during basic authentication. It allows to specify a `content` string as a message to send back to the client. The `realm` parameter should contain your realm of authentication (if any). The `prefer_utf8` parameter controls whether UTF-8 encoding is preferred in the `WWW-Authenticate` header. The other two optional parameters are the `response_code` and the `content_type`. You can find constant definition for the various response codes within the [http_utils](https://github.com/etr/libhttpserver/blob/master/src/httpserver/http_utils.hpp) library file. -* _digest_auth_fail_response(**const std::string&** content, **const std::string&** realm = `""`, **const std::string&** opaque = `""`, **bool** signal_stale = `false`, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`, **http::http_utils::digest_algorithm** algorithm = `SHA256`, **const std::string&** domain = `""`, **bool** userhash_support = `false`, **bool** prefer_utf8 = `true`):_ A response in return to a failure during digest authentication. It allows to specify a `content` string as a message to send back to the client. The `realm` parameter should contain your realm of authentication (if any). The `opaque` represents a value that gets passed to the client and expected to be passed again to the server as-is. The `signal_stale` parameter indicates whether to signal the client that its nonce is stale and should be refreshed (set to `true` when `check_digest_auth` returns `NONCE_STALE`). The `algorithm` selects the digest algorithm (`MD5`, `SHA256`, or `SHA512_256` — default is `SHA256`). The `domain` specifies the protection domain for digest authentication. The `userhash_support` enables RFC 7616 userhash support. The `prefer_utf8` controls whether UTF-8 encoding is preferred. -* _deferred_response(**ssize_t(*cycle_callback_ptr)(shared_ptr<T>, char*, size_t)** cycle_callback, **const std::string&** content = `""`, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`):_ A response that obtains additional content from a callback executed in a deferred way. It leaves the client in pending state (returning a `100 CONTINUE` message) and suspends the connection. Besides the callback, optionally, you can provide a `content` parameter that sets the initial message sent immediately to the client. The other two optional parameters are the `response_code` and the `content_type`. You can find constant definition for the various response codes within the [http_utils](https://github.com/etr/libhttpserver/blob/master/src/httpserver/http_utils.hpp) library file. To use `deferred_response` you need to have the `deferred` option active on your webserver (enabled by default). - * The `cycle_callback_ptr` has this shape: - _**ssize_t** cycle_callback(**shared_ptr<T> closure_data, char*** buf, **size_t** max_size)_. - You are supposed to implement a function in this shape and provide it to the `deferred_repsonse` method. The webserver will provide a `char*` to the function. It is responsibility of the function to allocate it and fill its content. The method is supposed to respect the `max_size` parameter passed in input. The function must return a `ssize_t` value representing the actual size you filled the `buf` with. Any value different from `-1` will keep the resume the connection, deliver the content and suspend it again (with a `100 CONTINUE`). If the method returns `-1`, the webserver will complete the communication with the client and close the connection. You can also pass a `shared_ptr` pointing to a data object of your choice (this will be templetized with a class of your choice). The server will guarantee that this object is passed at each invocation of the method allowing the client code to use it as a memory buffer during computation. -* _empty_response(**int** response_code = `204`, **int** flags = `NONE`):_ A response with no body. Ideal for `204 No Content` or `304 Not Modified` responses. The `flags` parameter supports the following values: - * `NONE`: No special flags (default). - * `HTTP_1_0_COMPATIBLE_STRICT`: Ensure strict HTTP 1.0 compatibility. - * `HTTP_1_0_SERVER`: Behave like an HTTP 1.0 server. - * `SEND_KEEP_ALIVE_HEADER`: Include a `Keep-Alive` header. - * `HEAD_ONLY`: Produce a response suitable for a HEAD request (headers only). -* _iovec_response(**std::vector** buffers, **int** response_code = `200`, **const std::string&** content_type = `"text/plain"`):_ A scatter-gather response that assembles its body from multiple string buffers. This allows you to efficiently compose a response from separate data segments without concatenating them first. The `buffers` are sent in order. -* _pipe_response(**int** pipe_fd, **int** response_code = `200`, **const std::string&** content_type = `"application/octet-stream"`):_ A response that streams content from a pipe file descriptor. The daemon reads data from the pipe until EOF and sends it to the client. The pipe should be the read end of a `pipe()` call. This is useful for streaming output from subprocesses or other producers. - -### Setting additional properties of the response -The `http_response` class offers an additional set of methods to "decorate" your responses. This set of methods is: -* _**void** with_header(**const std::string&** key, **const std::string&** value):_ Sets an HTTP header with name set to `key` and value set to `value`. -* _**void** with_footer(**const std::string&** key, **const std::string&** value):_ Sets an HTTP footer with name set to `key` and value set to `value`. -* _**void** with_cookie(**const std::string&** key, **const std::string&** value):_ Sets an HTTP cookie with name set to `key` and value set to `value` (only for http 1.1 chunked encodings). -* _**void** shoutCAST():_ Mark the response as a `shoutCAST` one. - -### Example of response setting headers -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - std::shared_ptr response = std::shared_ptr(new string_response("Hello, World!")); - response->with_header("MyHeader", "MyValue"); - return response; - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you could run the following command from a terminal: - - curl -XGET -v "http://localhost:8080/hello" - -You will receive the message custom header in reply. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/setting_headers.cpp). - -### Serving binary data from memory -`string_response` is not limited to text — it can serve arbitrary binary content directly from memory. This is useful when you have data in a buffer at runtime (e.g., from a camera, an image processing library, or a database) and want to serve it without writing to disk. - -```cpp - #include - - using namespace httpserver; - - class image_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - // binary_data could come from a camera capture, image library, etc. - std::string binary_data = get_image_bytes_from_camera(); - - return std::make_shared( - std::move(binary_data), 200, "image/jpeg"); - } - }; - - int main() { - webserver ws = create_webserver(8080); - - image_resource ir; - ws.register_resource("/image", &ir); - ws.start(true); - - return 0; - } -``` -To test the above example, you could run the following command from a terminal: - - curl -o image.jpg http://localhost:8080/image - -You can also check the complete example on [github](https://github.com/etr/libhttpserver/blob/master/examples/binary_buffer_response.cpp). - -[Back to TOC](#table-of-contents) - -## IP Blacklisting and Whitelisting -libhttpserver provides natively a system to blacklist and whitelist IP addresses. To enable/disable the system, it is possible to use the `ban_system` and `no_ban_system` methods on the `create_webserver` class. In the same way, you can specify what you want to be your "default behavior" (allow by default or disallow by default) by using the `default_policy` method (see [here](#create-and-work-with-a-webserver)). - -The system supports both IPV4 and IPV6 and manages them transparently. The only requirement is for ipv6 to be enabled on your server - you'll have to enable this by using the `use_ipv6` method on `create_webserver`. - -You can explicitly ban or allow an IP address using the following methods on the `webserver` class: -* _**void** ban_ip(**const std::string&** ip):_ Adds one IP (or a range of IPs) to the list of the banned ones. Takes in input a `string` that contains the IP (or range of IPs) to ban. To use when the `default_policy` is `ACCEPT`. -* _**void** allow_ip(**const std::string&** ip):_ Adds one IP (or a range of IPs) to the list of the allowed ones. Takes in input a `string` that contains the IP (or range of IPs) to allow. To use when the `default_policy` is `REJECT`. -* _**void** unban_ip(**const std::string&** ip):_ Removes one IP (or a range of IPs) from the list of the banned ones. Takes in input a `string` that contains the IP (or range of IPs) to remove from the list. To use when the `default_policy` is `ACCEPT`. -* _**void** disallow_ip(**const std::string&** ip):_ Removes one IP (or a range of IPs) from the list of the allowed ones. Takes in input a `string` that contains the IP (or range of IPs) to remove from the list. To use when the `default_policy` is `REJECT`. -### IP String Format -The IP string format can represent both IPV4 and IPV6. Addresses will be normalized by the webserver to operate in the same sapce. Any valid IPV4 or IPV6 textual representation works. -It is also possible to specify ranges of IPs. To do so, omit the octect you want to express as a range and specify a `'*'` in its place. -Examples of valid IPs include: -* `"192.168.5.5"`: standard IPV4 -* `"192.168.*.*"`: range of IPV4 addresses. In the example, everything between `192.168.0.0` and `192.168.255.255`. -* `"2001:db8:8714:3a90::12"`: standard IPV6 - clustered empty ranges are fully supported. -* `"2001:db8:8714:3a90:*:*"`: range of IPV6 addresses. -* `"::ffff:192.0.2.128"`: IPV4 IPs nested into IPV6. -* `"::192.0.2.128"`: IPV4 IPs nested into IPV6 (without `'ffff'` prefix) -* `"::ffff:192.0.*.*"`: ranges of IPV4 IPs nested into IPV6. +The block above is reproduced byte-for-byte from +[`examples/hello_world.cpp`](examples/hello_world.cpp); a CI gate +(`scripts/check-readme.sh`) enforces the byte-for-byte equality. -#### Example of IP Whitelisting/Blacklisting -```cpp - #include - - using namespace httpserver; - - class hello_world_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::shared_ptr(new string_response("Hello, World!")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080) - .default_policy(http::http_utils::REJECT); - - ws.allow_ip("127.0.0.1"); +## Table of contents - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); +* [Build / install](#build--install) +* [Hello, world — lambda form](#hello-world--lambda-form) +* [Class-form handlers](#class-form-handlers) +* [Request](#request) +* [Response](#response) +* [Routing](#routing) +* [Threading contract](#threading-contract) +* [Error propagation](#error-propagation) +* [Feature availability](#feature-availability) +* [WebSocket](#websocket) +* [Migrating from v1](#migrating-from-v1) +* [Examples index](#examples-index) +* [Community and license](#community-and-license) - return 0; - } -``` -To test the above example, you could run the following command from a terminal: - - curl -XGET -v "http://localhost:8080/hello" - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_ip_ban.cpp). +## Build / install -[Back to TOC](#table-of-contents) +**Compiler floor:** C++20. libhttpserver v2.0 will not build with a C++17 +compiler. -## Authentication -libhttpserver support three types of client authentication. +Supported toolchains: -Basic authentication uses a simple authentication method based on BASE64 algorithm. Username and password are exchanged in clear between the client and the server, so this method must only be used for non-sensitive content or when the session is protected with https. When using basic authentication libhttpserver will have access to the clear password, possibly allowing to create a chained authentication toward an external authentication server. You can enable/disable support for Basic authentication through the `basic_auth` and `no_basic_auth` methods of the `create_webserver` class. +| Platform | Toolchain | Notes | +|---|---|---| +| Debian 13 (trixie) | GCC 14.2 | Out-of-the-box | +| RHEL 9 | `gcc-toolset-14` | Stock GCC 11 is too old; install the Red Hat toolset overlay | +| RHEL 10 | GCC 14 | Out-of-the-box | +| FreeBSD 14.x | base Clang 18+ | Out-of-the-box | +| macOS | Homebrew GCC 15+ or current Apple Clang | Out-of-the-box | +| vcpkg / Conan | GCC 13+ / Clang 16+ | Out-of-the-box | -Digest authentication uses a one-way authentication method based on hash algorithms (MD5, SHA-256, or SHA-512/256). Only the hash will transit over the network, hence protecting the user password. The nonce will prevent replay attacks. This method is appropriate for general use, especially when https is not used to encrypt the session. SHA-256 is the default algorithm; SHA-512/256 is also available for stronger security. You can enable/disable support for Digest authentication through the `digest_auth` and `no_digest_auth` methods of the `create_webserver` class. +**Runtime dependencies:** [GNU libmicrohttpd](https://www.gnu.org/software/libmicrohttpd/) +≥ 1.0.0. Optional: GnuTLS (TLS), libgcrypt (digest auth), libmicrohttpd built +with WebSocket support. -Client certificate authentication uses a X.509 certificate from the client. This is the strongest authentication mechanism but it requires the use of HTTPS. Client certificate authentication can be used simultaneously with Basic or Digest Authentication in order to provide a two levels authentication (like for instance separate machine and user authentication). You can enable/disable support for Certificate authentication through the `use_ssl` and `no_ssl` methods of the `create_webserver` class. - -### Using Basic Authentication -```cpp - #include +**Build:** - using namespace httpserver; - - class user_pass_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - if (req.get_user() != "myuser" || req.get_pass() != "mypass") { - return std::shared_ptr(new basic_auth_fail_response("FAIL", "test@example.com")); - } - return std::shared_ptr(new string_response(req.get_user() + " " + req.get_pass(), 200, "text/plain")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - user_pass_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v -u myuser:mypass "http://localhost:8080/hello" - -You will receive back the user and password you passed in input. Try to pass the wrong credentials to see the failure. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/basic_authentication.cpp). - -### Using Digest Authentication - -The `check_digest_auth` method returns a `digest_auth_result` enum with fine-grained status codes: -* `OK` — authentication succeeded. -* `NONCE_STALE` — the nonce is stale; signal the client to retry with a fresh nonce by setting `signal_stale` to `true` in the response. -* `WRONG_USERNAME`, `WRONG_REALM`, `WRONG_URI`, `WRONG_QOP`, `WRONG_ALGO`, `RESPONSE_WRONG` — specific reasons for authentication failure. -* `WRONG_HEADER`, `TOO_LARGE`, `NONCE_WRONG`, `NONCE_OTHER_COND`, `ERROR` — other failure conditions. - -You can also use `check_digest_auth_digest` to verify against a pre-computed HA1 digest instead of a plaintext password. - -```cpp - #include - - #define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" - - using namespace httpserver; - using http::http_utils; - - class digest_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - if (req.get_digested_user() == "") { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, true, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } else { - auto result = req.check_digest_auth("test@example.com", "mypass", 300, 0, http_utils::digest_algorithm::MD5); - if (result == http_utils::digest_auth_result::NONCE_STALE) { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, true, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } else if (result != http_utils::digest_auth_result::OK) { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, false, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } - } - return std::make_shared("SUCCESS", 200, "text/plain"); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - digest_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v --digest --user myuser:mypass localhost:8080/hello - -You will receive a `SUCCESS` in response (observe the response message from the server in detail and you'll see the full interaction). Try to pass the wrong credentials or send a request without `digest` active to see the failure. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/digest_authentication.cpp). - -### Using Centralized Authentication -The examples above show authentication handled within each resource's `render_*` method. This approach requires duplicating authentication logic in every resource, which is error-prone and violates DRY (Don't Repeat Yourself) principles. - -libhttpserver provides a centralized authentication mechanism that runs a single authentication handler before any resource's render method is called. This allows you to: -- Define authentication logic once for all resources -- Automatically protect all endpoints by default -- Specify paths that should bypass authentication (e.g., health checks, public APIs) - -```cpp - #include - - using namespace httpserver; - - // Resources no longer need authentication logic - class hello_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("Hello, authenticated user!", 200, "text/plain"); - } - }; - - class health_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("OK", 200, "text/plain"); - } - }; - - // Centralized authentication handler - // Return nullptr to allow the request, or an http_response to reject it - std::shared_ptr my_auth_handler(const http_request& req) { - if (req.get_user() != "admin" || req.get_pass() != "secret") { - return std::make_shared("Unauthorized", "MyRealm"); - } - return nullptr; // Allow request to proceed to resource - } - - int main() { - webserver ws = create_webserver(8080) - .auth_handler(my_auth_handler) - .auth_skip_paths({"/health", "/public/*"}); - - hello_resource hello; - health_resource health; - - ws.register_resource("/api", &hello); - ws.register_resource("/health", &health); - - ws.start(true); - return 0; - } -``` - -The `auth_handler` callback is called for every request before the resource's render method. It receives the `http_request` and can: -- Return `nullptr` to allow the request to proceed normally -- Return an `http_response` (e.g., `basic_auth_fail_response` or `digest_auth_fail_response`) to reject the request - -The `auth_skip_paths` method accepts a vector of paths that should bypass authentication: -- Exact matches: `"/health"` matches only `/health` -- Wildcard suffixes: `"/public/*"` matches `/public/`, `/public/info`, `/public/docs/api`, etc. - -To test the above example: - - # Without auth - returns 401 Unauthorized - curl -v http://localhost:8080/api - - # With valid auth - returns 200 OK - curl -u admin:secret http://localhost:8080/api - - # Health endpoint (skip path) - works without auth - curl http://localhost:8080/health - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/centralized_authentication.cpp). - -### Using Client Certificate Authentication (mTLS) -Client certificate authentication (also known as mutual TLS or mTLS) provides strong authentication by requiring clients to present X.509 certificates during the TLS handshake. This is the most secure authentication method as it verifies client identity cryptographically. - -To enable client certificate authentication, configure your webserver with: -1. `use_ssl()` - Enable TLS -2. `https_mem_key()` and `https_mem_cert()` - Server certificate -3. `https_mem_trust()` - CA certificate(s) to verify client certificates - -```cpp - #include - - using namespace httpserver; - - class secure_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - // Check if client provided a certificate - if (!req.has_client_certificate()) { - return std::make_shared( - "Client certificate required", 401, "text/plain"); - } - - // Check if certificate is verified by our CA - if (!req.is_client_cert_verified()) { - return std::make_shared( - "Certificate not verified", 403, "text/plain"); - } - - // Extract certificate information - std::string cn = req.get_client_cert_cn(); // Common Name - std::string dn = req.get_client_cert_dn(); // Subject DN - std::string issuer = req.get_client_cert_issuer_dn(); // Issuer DN - std::string fingerprint = req.get_client_cert_fingerprint_sha256(); - time_t not_before = req.get_client_cert_not_before(); - time_t not_after = req.get_client_cert_not_after(); - - return std::make_shared( - "Welcome, " + cn + "!", 200, "text/plain"); - } - }; - - int main() { - webserver ws = create_webserver(8443) - .use_ssl() - .https_mem_key("server_key.pem") - .https_mem_cert("server_cert.pem") - .https_mem_trust("ca_cert.pem"); // CA for client certs - - secure_resource sr; - ws.register_resource("/secure", &sr); - ws.start(true); - - return 0; - } -``` - -Available client certificate methods (require GnuTLS support): -- `has_client_certificate()` - Check if client presented a certificate -- `get_client_cert_dn()` - Get the subject Distinguished Name -- `get_client_cert_issuer_dn()` - Get the issuer Distinguished Name -- `get_client_cert_cn()` - Get the Common Name from the subject -- `is_client_cert_verified()` - Check if the certificate chain is verified -- `get_client_cert_fingerprint_sha256()` - Get hex-encoded SHA-256 fingerprint -- `get_client_cert_not_before()` - Get certificate validity start time -- `get_client_cert_not_after()` - Get certificate validity end time - -To test with curl: - - # With client certificate - curl -k --cert client_cert.pem --key client_key.pem https://localhost:8443/secure - - # Without client certificate (will be rejected) - curl -k https://localhost:8443/secure - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/client_cert_auth.cpp). - -### Server Name Indication (SNI) Callback -SNI allows a server to host multiple TLS certificates on a single IP address. The client indicates which hostname it's connecting to during the TLS handshake, and the server can select the appropriate certificate. - -To use SNI with libhttpserver, configure an SNI callback that returns the certificate/key pair for each server name: - -```cpp - #include - #include - - using namespace httpserver; - - // Map of server names to cert/key pairs - std::map> certs; - - // SNI callback - returns (cert_pem, key_pem) for the requested server name - std::pair sni_callback(const std::string& server_name) { - auto it = certs.find(server_name); - if (it != certs.end()) { - return it->second; - } - return {"", ""}; // Use default certificate - } - - int main() { - // Load certificates for different hostnames - certs["www.example.com"] = {load_file("www_cert.pem"), load_file("www_key.pem")}; - certs["api.example.com"] = {load_file("api_cert.pem"), load_file("api_key.pem")}; - - webserver ws = create_webserver(443) - .use_ssl() - .https_mem_key("default_key.pem") // Default certificate - .https_mem_cert("default_cert.pem") - .sni_callback(sni_callback); // SNI callback - - // ... register resources and start - ws.start(true); - return 0; - } -``` - -Note: SNI support requires libmicrohttpd 1.0.0 or later compiled with GnuTLS. - -[Back to TOC](#table-of-contents) - -## WebSocket Support - -libhttpserver provides WebSocket support when libmicrohttpd is built with WebSocket functionality. To use WebSockets, derive from the `websocket_handler` class and implement the `on_message()` method. - -### The websocket_handler class -The `websocket_handler` class provides the following virtual methods: -* _**void** on_open(**websocket_session&** session):_ Called when a new WebSocket connection is established. Default implementation does nothing. -* _**void** on_message(**websocket_session&** session, **std::string_view** msg):_ Called when a text message is received. **This is the only pure virtual method and must be implemented.** -* _**void** on_binary(**websocket_session&** session, **const void*** data, **size_t** len):_ Called when a binary message is received. Default implementation does nothing. -* _**void** on_ping(**websocket_session&** session, **std::string_view** payload):_ Called when a ping frame is received. Default implementation sends a pong. -* _**void** on_close(**websocket_session&** session, **uint16_t** code, **const std::string&** reason):_ Called when the WebSocket connection is closed. Default implementation does nothing. - -### The websocket_session class -The `websocket_session` class provides methods to interact with the client: -* _**void** send_text(**const std::string&** msg):_ Send a text message. -* _**void** send_binary(**const void*** data, **size_t** len):_ Send a binary message. -* _**void** send_ping(**const std::string&** payload = `""`):_ Send a ping frame. -* _**void** send_pong(**const std::string&** payload = `""`):_ Send a pong frame. -* _**void** close(**uint16_t** code = `1000`, **const std::string&** reason = `""`):_ Close the WebSocket connection. -* _**bool** is_valid():_ Check if the session is still valid. - -### Registering WebSocket resources -Register a WebSocket handler using `register_ws_resource`: -```cpp - #include - - using namespace httpserver; - - class echo_handler : public websocket_handler { - public: - void on_message(websocket_session& session, std::string_view msg) override { - session.send_text("Echo: " + std::string(msg)); - } - }; - - int main() { - webserver ws = create_webserver(8080); - - echo_handler handler; - ws.register_ws_resource("/ws", &handler); - ws.start(true); - - return 0; - } -``` - -Note: WebSocket support requires libmicrohttpd 1.0.0 or later built with WebSocket support enabled. - -[Back to TOC](#table-of-contents) - -## Daemon Introspection and External Event Loops - -libhttpserver exposes several methods for integrating with external event loops and for querying daemon state at runtime. - -### Daemon introspection -* _**uint16_t** webserver::get_bound_port():_ Returns the actual port the daemon is bound to. This is especially useful when you pass port `0` to let the operating system choose an ephemeral port. -* _**int** webserver::get_listen_fd():_ Returns the listen socket file descriptor, or `-1` if not available. -* _**unsigned int** webserver::get_active_connections():_ Returns the number of currently active connections. - -### External event loop integration -When using the server without internal threading (e.g., with `no_listen_socket()` or a single-threaded design), you can drive the event loop yourself: -* _**bool** webserver::run():_ Process pending events once and return immediately. -* _**bool** webserver::run_wait(**int32_t** millisec):_ Block until events are available or the timeout expires. -* _**bool** webserver::get_fdset(...):_ Retrieve file descriptor sets for use with `select()`. -* _**bool** webserver::get_timeout(**uint64_t*** timeout):_ Get the maximum time to wait before calling `run()` again. -* _**bool** webserver::add_connection(**int** socket, **const sockaddr*** addr, **socklen_t** len):_ Hand off an externally-accepted connection to the daemon. -* _**int** webserver::quiesce():_ Stop accepting new connections while allowing in-flight requests to complete. Returns the listen socket FD. - -### Example: querying the bound port -```cpp - #include - #include - - using namespace httpserver; - - class hello_resource : public http_resource { - public: - std::shared_ptr render(const http_request&) { - return std::make_shared("Hello!"); - } - }; - - int main() { - webserver ws = create_webserver(0); // Let the OS choose a port - - hello_resource hr; - ws.register_resource("/hello", &hr); - ws.start(false); - - std::cout << "Listening on port: " << ws.get_bound_port() << std::endl; - std::cout << "Active connections: " << ws.get_active_connections() << std::endl; - - ws.stop(); - return 0; - } -``` - -[Back to TOC](#table-of-contents) - -## HTTP Utils -libhttpserver provides a set of constants to help you develop your HTTP server. It would be redundant to list them here; so, please, consult the list directly [here](https://github.com/etr/libhttpserver/blob/master/src/httpserver/http_utils.hpp). - -Additionally, the following utility methods are available: -* _**static const char*** http_utils::reason_phrase(**unsigned int** status_code):_ Returns the standard HTTP reason phrase for a given status code (e.g., `"OK"` for 200, `"Not Found"` for 404). -* _**static bool** http_utils::is_feature_supported(**int** feature):_ Checks whether a specific libmicrohttpd feature is supported on the current system. Feature constants are defined by the MHD_FEATURE enum. -* _**static const char*** http_utils::get_mhd_version():_ Returns the version string of the underlying libmicrohttpd library. - -[Back to TOC](#table-of-contents) - -## Other Examples - -#### Example of returning a response from a file -```cpp - #include - - using namespace httpserver; - - class file_response_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - return std::shared_ptr(new file_response("test_content", 200, "text/plain")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - file_response_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_file_response.cpp). - -#### Example of a deferred response through callback -```cpp - #include - - using namespace httpserver; - - static int counter = 0; - - ssize_t test_callback (std::shared_ptr closure_data, char* buf, size_t max) { - if (counter == 2) { - return -1; - } - else { - memset(buf, 0, max); - strcat(buf, " test "); - counter++; - return std::string(buf).size(); - } - } - - class deferred_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - return std::shared_ptr >(new deferred_response(test_callback, nullptr, "cycle callback response")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - deferred_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/minimal_deferred.cpp). - -#### Example of a deferred response through callback (passing additional data along) -```cpp - #include - #include - - using namespace httpserver; - - std::atomic counter; - - ssize_t test_callback (std::shared_ptr > closure_data, char* buf, size_t max) { - int reqid; - if (closure_data == nullptr) { - reqid = -1; - } else { - reqid = *closure_data; - } - - // only first 5 connections can be established - if (reqid >= 5) { - return -1; - } else { - // respond corresponding request IDs to the clients - std::string str = ""; - str += std::to_string(reqid) + " "; - memset(buf, 0, max); - std::copy(str.begin(), str.end(), buf); - - // keep sending reqid - sleep(1); - - return (ssize_t)max; - } - } - - class deferred_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request& req) { - std::shared_ptr > closure_data(new std::atomic(counter++)); - return std::shared_ptr > >(new deferred_response >(test_callback, closure_data, "cycle callback response")); - } - }; - - int main(int argc, char** argv) { - webserver ws = create_webserver(8080); - - deferred_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/deferred_with_accumulator.cpp). +```sh +./bootstrap +./configure +make +sudo make install +``` + +`make check` runs the test suite (unit + integration). `make examples` builds +every program under [`examples/`](examples/). + +**ABI / packaging.** SOVERSION bumps from 1 to 2 in v2.0. Distributions +package `libhttpserver2` parallel-installable with `libhttpserver1`. There is +no inline namespace and no symbol-versioning script: v1.x is end-of-life on +the day v2.0 ships, and code that needs both can link them side by side. + +## Hello, world — lambda form + +The snippet at the top of this README is the entire program. Walking through +it: + +* `webserver ws{create_webserver(8080)};` — `create_webserver` is a fluent + builder for the server configuration; `webserver` is constructed by direct + initialization from it. `webserver` is non-copyable and non-movable; pass it + by reference once it exists. +* `ws.on_get("/hello", [](const http_request&) { ... });` — register a + GET-only handler. The handler is a `std::function`. There is no subclass, no `shared_ptr`, no raw pointer. +* `return http_response::string("Hello, World!");` — `http_response` is a + value type. Factories on `http_response` build common shapes; the fluent + `with_*` mutators add headers, footers, cookies, and status. The response + is returned by value into the dispatcher. +* `ws.start(true);` — `true` means *block this thread until the server is + stopped*. Pass `false` to start the listener and return immediately; later + call `stop_and_wait()` from another thread. + +See [`examples/hello_world.cpp`](examples/hello_world.cpp) and +[`examples/hello_with_get_arg.cpp`](examples/hello_with_get_arg.cpp) for the +complete sources. + +## Class-form handlers + +Lambdas suffice when each HTTP method is independent. When several methods on +one path share state — a counter, a cache, a mutex — derive from +[`http_resource`](src/httpserver/http_resource.hpp) and register the subclass +once: + +```cpp +class counter : public httpserver::http_resource { + public: + httpserver::http_response render_get(const httpserver::http_request&) override { + std::lock_guard lock{m_}; + return httpserver::http_response::string(std::to_string(n_)); + } + httpserver::http_response render_post(const httpserver::http_request&) override { + std::lock_guard lock{m_}; + ++n_; + return httpserver::http_response::string(std::to_string(n_)); + } + private: + std::mutex m_; + int n_ = 0; +}; + +// ... +ws.register_path("/count", std::make_unique()); +``` + +The virtual hooks are `render_get`, `render_post`, `render_put`, +`render_delete`, `render_head`, `render_options`, `render_patch`, +`render_connect`, and `render_trace` — all lowercase, all returning +`http_response` by value. The `webserver` takes ownership of the resource +via `std::unique_ptr`. + +See [`examples/shared_state.cpp`](examples/shared_state.cpp) for the +canonical example. + +## Request + +`http_request` is read-only inside a handler. The accessors are designed +around `std::string_view` so reading headers and arguments does not allocate: + +| Accessor | Returns | Notes | +|---|---|---| +| `get_path()` | `std::string_view` | The decoded path | +| `get_method()` | `httpserver::http_method` | Strongly-typed enum; see [`http_method.hpp`](src/httpserver/http_method.hpp) | +| `get_arg(name)` | `std::string_view` | First value for a query/form arg | +| `get_arg_flat(name)` | `std::string_view` | Alias for `get_arg`; explicit "first value only" form | +| `get_querystring()` | `std::string_view` | Raw query string (no decoding) | +| `get_version()` | `std::string_view` | "HTTP/1.1", "HTTP/2", … | +| `get_headers()` | `const map&` | All headers | +| `get_args()` | `const map&` | All query/form arguments | +| `get_path_pieces()` | `const vector&` | Split path components | +| `get_files()` | `const map&` | Uploaded files (multipart) | +| `get_user()` | `std::string_view` | Basic-auth user; empty when `HAVE_BAUTH` is off | +| `get_pass()` | `std::string_view` | Basic-auth password; empty when `HAVE_BAUTH` is off | +| `get_digested_user()` | `std::string_view` | Digest-auth user; empty when `HAVE_DAUTH` is off | +| `get_client_cert_*()` | various | TLS-only; return empty / `-1` / `false` when `HAVE_GNUTLS` is off | + +**Lifetime contract.** Every `string_view` returned by `http_request` is +valid for the duration of the handler invocation and no longer. Copy what +you need to keep (e.g., into a `std::string`); do not hand a view to a +deferred callback. The references returned by `get_headers()`, `get_args()`, +`get_path_pieces()`, and `get_files()` follow the same rule. + +**Method enum.** `http_method` (declared in +[`http_method.hpp`](src/httpserver/http_method.hpp)) covers the canonical +HTTP methods. `method_set` is a bitset used by atomic multi-method +registration (see [Routing](#routing)). + +## Response + +`http_response` is a value type — move-only, returned by value, never +`shared_ptr`-wrapped. There is no class hierarchy of body subclasses; the +body shape is a runtime detail of one type. + +**Factories:** + +| Factory | Body shape | +|---|---| +| `http_response::string(body)` | An in-memory string (small bodies live inline via SBO) | +| `http_response::file(path)` | Stream a file from disk | +| `http_response::iovec(entries)` | Scatter-gather over a vector of `iovec_entry` (zero-copy) | +| `http_response::pipe(fd)` | Stream from a pipe / FIFO | +| `http_response::empty()` | Empty body | +| `http_response::deferred(producer)` | Body produced incrementally by a callback | +| `http_response::unauthorized(realm)` | 401 with the proper `WWW-Authenticate` header | + +**Fluent mutation.** Every `http_response` exposes `with_status`, +`with_header`, `with_footer`, and `with_cookie` returning `*this` by value +so calls can chain: + +```cpp +return httpserver::http_response::string("hi") + .with_header("X-Trace-Id", trace_id) + .with_status(201); +``` + +**Building error responses by value.** There is no throw-as-status idiom. +To return a 404 from a handler, build it explicitly: -#### Example of an empty response (204 No Content) ```cpp - #include - - using namespace httpserver; - - class no_content_resource : public http_resource { - public: - std::shared_ptr render_DELETE(const http_request&) { - // Return a 204 No Content response with no body - return std::make_shared( - http::http_utils::http_no_content); - } - - std::shared_ptr render_HEAD(const http_request&) { - // Return a HEAD-only response with headers but no body - auto response = std::make_shared( - http::http_utils::http_ok, - empty_response::HEAD_ONLY); - response->with_header("X-Total-Count", "42"); - return response; - } - }; - - int main() { - webserver ws = create_webserver(8080); - - no_content_resource ncr; - ws.register_resource("/items", &ncr); - ws.start(true); - - return 0; - } +if (!found) { + return httpserver::http_response::empty().with_status(404); +} ``` -To test the above example, you can run the following commands from a terminal: - - curl -XDELETE -v localhost:8080/items - curl -I -v localhost:8080/items - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/empty_response_example.cpp). - -#### Example of a scatter-gather (iovec) response -```cpp - #include - - using namespace httpserver; - - class iovec_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - // Build a response from multiple separate buffers without copying - std::vector parts; - parts.push_back("{\"header\": \"value\", "); - parts.push_back("\"items\": [1, 2, 3], "); - parts.push_back("\"footer\": \"end\"}"); - - return std::make_shared( - std::move(parts), 200, "application/json"); - } - }; - - int main() { - webserver ws = create_webserver(8080); - - iovec_resource ir; - ws.register_resource("/data", &ir); - ws.start(true); - return 0; - } +See [`examples/setting_headers.cpp`](examples/setting_headers.cpp), +[`examples/iovec_response_example.cpp`](examples/iovec_response_example.cpp), +[`examples/minimal_file_response.cpp`](examples/minimal_file_response.cpp), +and +[`examples/pipe_response_example.cpp`](examples/pipe_response_example.cpp) +for working programs. + +## Routing + +The `webserver` exposes three families of registration entry points: + +**Per-method, exact path.** `on_get`, `on_post`, `on_put`, `on_delete`, +`on_head`, `on_options`, `on_patch`, `on_connect`, `on_trace` each take a +path and a lambda. Re-registering the same `(method, path)` pair throws. + +**Atomic multi-method.** `route(http_method::GET | http_method::HEAD, +"/info", handler)` registers the handler under several methods in a single +critical section; either every slot is registered, or none of them are. +`route(http_method::GET, "/info", handler)` is the single-method form and +overlaps with `on_get`. A `method_set` is the bitwise-or of `http_method` +values. + +**Resource registration.** `register_path("/foo", std::make_unique())` +registers an `http_resource` subclass at an exact path; +`register_prefix("/foo/", std::make_unique())` registers it for the +subtree starting at `/foo/`. Parameterized paths use brace syntax: +`register_path("/users/{id}", ...)`; an optional per-segment regex +constrains a parameter: `register_path("/users/{id|[0-9]+}", ...)`. +Unregister with `unregister_path` and `unregister_prefix`. + +The lambda overloads (`on_get`, `route`) are sugar on top of the same +internal dispatcher used by `http_resource`. They are interoperable: +within one server, some paths can be lambdas and others can be +`http_resource` subclasses. + +See [`examples/url_registration.cpp`](examples/url_registration.cpp) and +[`examples/handlers.cpp`](examples/handlers.cpp). + +## Threading contract + +Distilled from `specs/architecture/05-cross-cutting.md` §5.1 and DR-008 +(`specs/architecture/11-decisions/DR-008.md`): + +1. **Public methods on `webserver` are thread-safe and re-entrant from + inside a handler.** Two exceptions: `stop()` and `~webserver()` + **deadlock** if invoked from a handler thread, because they wait for + that very thread to drain. `stop_and_wait()` delegates to `stop()` and + carries the same deadlock risk. Stop the server from a different thread, + or signal an external stop loop. v2 provides both `stop()` (signal and + return) and `stop_and_wait()` (signal and drain until all in-flight + handlers finish). +2. **Handlers run concurrently on libmicrohttpd worker threads.** The same + lambda or `http_resource` instance is invoked from many threads at once. + Any state you share — counters, caches, file handles — must be + synchronized on your side. The library does not synchronize user state + for you. +3. **`http_request` is single-threaded per request.** Sharing one + `http_request` across threads is undefined; the per-request arena makes + no guarantees outside the calling thread. +4. **`http_response` is value-typed with exclusive ownership.** Returning + it transfers ownership into the dispatcher. There is no shared mutable + response object. + +## Error propagation + +Distilled from `specs/architecture/05-cross-cutting.md` §5.2 and DR-009 +(`specs/architecture/11-decisions/DR-009.md`): + +1. **A handler that throws `std::exception` is caught.** The library logs + the exception via the configured `log_error` callback and invokes + `internal_error_handler(request, e.what())`. The response returned by + `internal_error_handler` is sent to the client; if no custom + `internal_error_handler` is configured, a hardcoded HTTP 500 with empty + body is sent. +2. **A handler that throws something other than `std::exception`** is also + caught, with `"unknown exception"` substituted for the message. +3. **Library-internal failures during dispatch** (allocation, body + materialization) flow through the same `internal_error_handler` path. +4. **If `internal_error_handler` itself throws**, the library logs and + sends a hardcoded 500 with an empty body. There is no third level of + fallback. +5. **`feature_unavailable` is a normal `std::runtime_error`** — no special + status mapping. Catch it explicitly if you want to map it to a 503 or + similar; the library does not. +6. **There is no throw-as-status idiom.** A handler that wants to return + 404, 400, etc. builds the response by value (see [Response](#response)): + `return httpserver::http_response::empty().with_status(404);`. + +Install custom error handlers on the builder: + +```cpp +auto cfg = httpserver::create_webserver(8080) + .not_found_handler([](const httpserver::http_request&) { + return httpserver::http_response::string("nope").with_status(404); + }) + .method_not_allowed_handler([](const httpserver::http_request&) { + return httpserver::http_response::empty().with_status(405); + }) + .internal_error_handler([](const httpserver::http_request&, std::string_view what) { + return httpserver::http_response::string(std::string{what}).with_status(500); + }); +httpserver::webserver ws{cfg}; +``` + +## Feature availability + +Several capabilities are gated by build-time flags. v2.0 makes the gating +visible at the API level so application code does not need preprocessor +guards on `HAVE_*` macros. + +| Build flag | When disabled | Public-API behavior | +|---|---|---| +| `HAVE_BAUTH` | Basic-auth disabled | `get_user`, `get_pass` return empty `string_view`; `features().basic_auth == false`; `create_webserver::basic_auth(true)` throws `feature_unavailable` at `webserver` construction | +| `HAVE_DAUTH` | Digest-auth disabled | `get_digested_user` returns empty; `check_digest_auth` returns a sentinel result; `features().digest_auth == false` | +| `HAVE_GNUTLS` | TLS disabled | All `get_client_cert_*` accessors return empty / `-1` / `false`; `features().tls == false`; `create_webserver::use_ssl(true)` throws `feature_unavailable` | +| `HAVE_WEBSOCKET` | WebSocket disabled | `register_ws_resource` throws `feature_unavailable`; `features().websocket == false` | + +**Probing at runtime.** `webserver::features()` returns a small struct of +four `bool`s — one per flag — so callers can branch without preprocessor +help: + +```cpp +if (ws.features().tls) { + // safe to call get_client_cert_* +} ``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/data -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/iovec_response_example.cpp). +**`feature_unavailable`.** Derives from `std::runtime_error`. Its +`what()` names both the disabled feature and the build flag that gates +it, so log lines pinpoint which flag a deployment is missing. Catch it +where you call a feature-gated method: -#### Example of a pipe-based streaming response ```cpp - #include - #include - #include - #include - - using namespace httpserver; - - class pipe_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - int pipefd[2]; - if (pipe(pipefd) == -1) { - return std::make_shared("pipe failed", 500); - } - - // Spawn a thread to write data into the pipe - std::thread writer([fd = pipefd[1]]() { - const char* messages[] = {"Hello ", "from ", "a pipe!\n"}; - for (const char* msg : messages) { - ssize_t ret = write(fd, msg, strlen(msg)); - (void)ret; - } - close(fd); - }); - writer.detach(); - - // Return the read end of the pipe as the response - return std::make_shared(pipefd[0], 200, "text/plain"); - } - }; - - int main() { - webserver ws = create_webserver(8080); - - pipe_resource pr; - ws.register_resource("/stream", &pr); - ws.start(true); - - return 0; - } +try { + ws.register_ws_resource("/sock", std::make_unique()); +} catch (const httpserver::feature_unavailable& e) { + std::cerr << "websocket support is not available: " << e.what() << '\n'; +} ``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/stream - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/pipe_response_example.cpp). - -#### Example of a WebSocket echo server -```cpp - #include - #include - - using namespace httpserver; - class echo_handler : public websocket_handler { - public: - void on_open(websocket_session& session) override { - std::cout << "WebSocket connection opened" << std::endl; - session.send_text("Welcome to the echo server!"); - } +Block lists, IP-allow handling, and similar features that do not depend on +external libraries are always available: `webserver::block_ip(addr)` and +`webserver::unblock_ip(addr)` install and clear per-server blocks at +runtime. - void on_message(websocket_session& session, std::string_view msg) override { - std::cout << "Received: " << msg << std::endl; - session.send_text("Echo: " + std::string(msg)); - } +## WebSocket - void on_close(websocket_session& session, uint16_t code, const std::string& reason) override { - std::cout << "WebSocket closed (code=" << code << ", reason=" << reason << ")" << std::endl; - } - }; +WebSocket handlers are registered with `register_ws_resource`, taking +ownership of a `websocket_handler` subclass: - int main() { - webserver ws = create_webserver(8080); - - echo_handler handler; - ws.register_ws_resource("/ws", &handler); - ws.start(true); - - return 0; - } -``` -Note: WebSocket support requires libmicrohttpd 1.0.0 built with WebSocket support. You can test this with any WebSocket client library or browser JavaScript: `new WebSocket("ws://localhost:8080/ws")`. - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/websocket_echo.cpp). - -#### Example of daemon introspection ```cpp - #include - #include - - using namespace httpserver; - - class hello_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("Hello, World!"); - } - }; - - int main() { - // Use port 0 to let the OS assign an ephemeral port - webserver ws = create_webserver(0); - - hello_resource hr; - ws.register_resource("/hello", &hr); - ws.start(false); - - // Query daemon information - std::cout << "libmicrohttpd version: " - << http::http_utils::get_mhd_version() << std::endl; - std::cout << "Bound port: " << ws.get_bound_port() << std::endl; - std::cout << "Listen FD: " << ws.get_listen_fd() << std::endl; - std::cout << "Active connections: " << ws.get_active_connections() << std::endl; - std::cout << "HTTP 200 reason: " - << http::http_utils::reason_phrase(200) << std::endl; - std::cout << "HTTP 404 reason: " - << http::http_utils::reason_phrase(404) << std::endl; - - ws.sweet_kill(); - return 0; - } +ws.register_ws_resource("/echo", std::make_unique()); +// or +auto handler = std::make_shared(); +ws.register_ws_resource("/echo", handler); ``` -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/daemon_info.cpp). - -#### Example of an external event loop -```cpp - #include - #include - #include - - using namespace httpserver; - static volatile bool running = true; +On a build with `HAVE_WEBSOCKET` disabled — for example, when the system +libmicrohttpd was built without WebSocket support — `register_ws_resource` +throws `feature_unavailable`. See +[`examples/websocket_echo.cpp`](examples/websocket_echo.cpp). - void signal_handler(int) { running = false; } +## Migrating from v1 - class hello_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("Hello from external event loop!"); - } - }; +v2.0 is a single breaking release. There is no opt-in compatibility shim: +every v1 client has at least one shape change to make (response factories, +handler signatures, threading contract, error propagation). The v1.x line +is end-of-life on the day v2.0 ships, and v2 is packaged as +`libhttpserver2` — parallel-installable with `libhttpserver1`, so old +binaries keep running while you port. - int main() { - signal(SIGINT, signal_handler); +The rename/removed/added cheat sheet — every API surface that moved — lives +in [`RELEASE_NOTES.md`](RELEASE_NOTES.md). - webserver ws = create_webserver(8080); +## Examples index - hello_resource hr; - ws.register_resource("/hello", &hr); - ws.start(false); +Every program under [`examples/`](examples/) is a standalone `.cpp` that +links against libhttpserver. The grouped index (HTTP basics, response +shapes, request features, authentication, TLS, WebSocket, performance, +diagnostics) lives in [`examples/README.md`](examples/README.md). - std::cout << "Server running on port " << ws.get_bound_port() << std::endl; +Start with: - // Drive the event loop externally using run_wait - while (running) { - // Block for up to 1000ms waiting for HTTP activity - ws.run_wait(1000); +* [`examples/hello_world.cpp`](examples/hello_world.cpp) — the ten-line + lambda form quoted at the top of this README. +* [`examples/shared_state.cpp`](examples/shared_state.cpp) — when the + class form is the right shape. +* [`examples/setting_headers.cpp`](examples/setting_headers.cpp) — fluent + `with_header` chaining. +* [`examples/url_registration.cpp`](examples/url_registration.cpp) — + paths, prefixes, parameters, and per-segment regex constraints. +* [`examples/custom_error.cpp`](examples/custom_error.cpp) — installing + `not_found_handler`, `method_not_allowed_handler`, and + `internal_error_handler`. - // You can do other work here between iterations - } +## Community and license - // Graceful shutdown: stop accepting new connections first - ws.quiesce(); - ws.stop(); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/external_event_loop.cpp). - -#### Example of turbo mode with performance options -```cpp - #include - - using namespace httpserver; - - class hello_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("Hello, turbo world!"); - } - }; - - int main() { - // Create a high-performance server with turbo mode, - // suppressed date headers, and a thread pool. - webserver ws = create_webserver(8080) - .start_method(http::http_utils::INTERNAL_SELECT) - .max_threads(4) - .turbo() - .suppress_date_header() - .tcp_fastopen_queue_size(16) - .listen_backlog(128); - - hello_resource hr; - ws.register_resource("/hello", &hr); - ws.start(true); - - return 0; - } -``` -To test the above example, you can run the following command from a terminal: - - curl -XGET -v localhost:8080/hello - -You can also check this example on [github](https://github.com/etr/libhttpserver/blob/master/examples/turbo_mode.cpp). - -[Back to TOC](#table-of-contents) - -## Copying -This manual is for libhttpserver, C++ library for creating an embedded Rest HTTP server (and more). - -> 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. - -[Back to TOC](#table-of-contents) - -## GNU Lesser General Public License -Version 2.1, February 1999 - -Copyright © 1991, 1999 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. - -_This is the first released version of the Lesser GPL. It also counts -as the successor of the GNU Library Public License, version 2, hence -the version number 2.1._ - -### Preamble - -The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, -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 and use pieces of -it in new free programs; and that you are informed that you can do -these things. - -To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - -Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - -When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - -We call this license the “Lesser” General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - -For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - -Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -“work based on the library” and a “work that uses the library”. The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - -### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - -**0.** This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called “this License”). -Each licensee is addressed as “you”. - -A “library” means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - -The “Library”, below, refers to any such software library or work -which has been distributed under these terms. A “work based on the -Library” means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term “modification”.) - -“Source code” for a work means the preferred form of the work for -making modifications to it. For a library, 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 library. - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - -**1.** You may copy and distribute verbatim copies of the Library's -complete 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 distribute a copy of this License along with the -Library. - -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. - -**2.** You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - -* **a)** The modified work must itself be a software library. -* **b)** You must cause the files modified to carry prominent notices -stating that you changed the files and the date of any change. -* **c)** You must cause the whole of the work to be licensed at no -charge to all third parties under the terms of this License. -* **d)** If a facility in the modified Library refers to a function or a -table of data to be supplied by an application program that uses -the facility, other than as an argument passed when the facility -is invoked, then you must make a good faith effort to ensure that, -in the event an application does not supply such function or -table, the facility still operates, and performs whatever part of -its purpose remains meaningful. -(For example, a function in a library to compute square roots has -a purpose that is entirely well-defined independent of the -application. Therefore, Subsection 2d requires that any -application-supplied function or table used by this function must -be optional: if the application does not supply it, the square -root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -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 Library, 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 Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - -**3.** You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - -Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - -**4.** You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you 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. - -If distribution of 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 satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - -**5.** A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a “work that uses the Library”. Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - -However, linking a “work that uses the Library” with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a “work that uses the -library”. The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - -When a “work that uses the Library” uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - -**6.** As an exception to the Sections above, you may also combine or -link a “work that uses the Library” with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - -* **a)** Accompany the work with the complete corresponding -machine-readable source code for the Library including whatever -changes were used in the work (which must be distributed under -Sections 1 and 2 above); and, if the work is an executable linked -with the Library, with the complete machine-readable “work that -uses the Library”, as object code and/or source code, so that the -user can modify the Library and then relink to produce a modified -executable containing the modified Library. (It is understood -that the user who changes the contents of definitions files in the -Library will not necessarily be able to recompile the application -to use the modified definitions.) -* **b)** Use a suitable shared library mechanism for linking with the -Library. A suitable mechanism is one that (1) uses at run time a -copy of the library already present on the user's computer system, -rather than copying library functions into the executable, and (2) -will operate properly with a modified version of the library, if -the user installs one, as long as the modified version is -interface-compatible with the version that the work was made with. -* **c)** Accompany the work with a written offer, valid for at -least three years, to give the same user the materials -specified in Subsection 6a, above, for a charge no more -than the cost of performing this distribution. -* **d)** If distribution of the work is made by offering access to copy -from a designated place, offer equivalent access to copy the above -specified materials from the same place. -* **e)** Verify that the user has already received a copy of these -materials or that you have already sent this user a copy. - -For an executable, the required form of the “work that uses the -Library” must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be 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. - -It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - -**7.** You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - -* **a)** Accompany the combined library with a copy of the same work -based on the Library, uncombined with any other library -facilities. This must be distributed under the terms of the -Sections above. -* **b)** Give prominent notice with the combined library of the fact -that part of it is a work based on the Library, and explaining -where to find the accompanying uncombined form of the same work. - -**8.** You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library 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. - -**9.** 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 Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - -**10.** Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -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 with -this License. - -**11.** 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 Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library 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 Library. - -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. - -**12.** If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library 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. - -**13.** The Free Software Foundation may publish revised and/or new -versions of the Lesser 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 Library -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 Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - -**14.** If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -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. - -### NO WARRANTY - -**15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY “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 -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -**16.** 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 LIBRARY 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 -LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -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. - - - Copyright (C) - - 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. - - , 1 April 1990 - Ty Coon, President of Vice - -That's all there is to it! - -[Back to TOC](#table-of-contents) - -## GNU Free Documentation License - -Version 1.3, 3 November 2008 - -Copyright © 2000, 2001, 2002, 2007, 2008 Free Software Foundation, Inc. <> - -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 -<>. - -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. - -[Back to TOC](#table-of-contents) - -## Thanks - -This library has been originally developed under the zencoders flags and this community has always supported me all along this work so I am happy to put the logo on this readme. - - When you see this tree, know that you've came across ZenCoders - - with open('ZenCoders. - `num` in numbers synchronized - datetime d glob. sys.argv[2] . - def myclass `..` @@oscla org. . class { - displ hooks( public static void ma functor: - $myclass->method( impport sys, os.pipe ` @param name` - fcl if(system(cmd) myc. /de ` $card( array("a" srand - format lists: ++: conc ++ "my an WHERE for( == myi - `sys: myvalue(myvalue) sys.t Console.W try{ rais using - connec SELECT * FROM table mycnf acco desc and or selector::clas at - openldap string sys. print "zenc der " { 'a': `ls -l` > appe &firs - import Tkinter paste( $obh &a or it myval bro roll: :: [] require a - case `` super. +y expr say " %rooms 1 --account fb- yy - proc meth Animate => send(D, open) putd EndIf 10 whi myc` cont - and main (--) import loop $$ or end onload UNION WITH tab timer 150 *2 - end. begin True GtkLabel *label doto partition te let auto i<- (i + d ); - .mushup ``/. ^/zenc/ myclass->her flv op <> element >> 71 or - QFileDi : and .. with myc toA channel::bo myc isEmpty a not bodt; - class T public pol str mycalc d pt &&a *i fc add ^ac - ::ZenCoders::core::namespac boost::function st f = std: ;; int assert - cout << endl public genera #include "b ost ::ac myna const cast mys - ac size_t return ran int (*getNextValue)(void) ff double sa_family_t famil - pu a do puts(" ac int main(int argc, char* "%5d struct nam - cs float for typedef enum puts getchar() - if( else #define fp FILE* f char* s - i++ strcat( %s int - 31] total+= do - }do while(1) sle - getc strcpy( a for - prin scanf(%d, & get - int void myfunc(int pa retu - BEQ BNEQZ R1 10 ANDI R1 R2 SYS - XOR SYSCALL 5 SLTIU MFLO 15 SW JAL - BNE BLTZAL R1 1 LUI 001 NOOP MULTU SLLV - MOV R1 ADD R1 R2 JUMP 10 1001 BEQ R1 R2 1 ANDI - 1101 1010001100 111 001 01 1010 101100 1001 100 - 110110 100 0 01 101 01100 100 100 1000100011 - 11101001001 00 11 100 11 10100010 - 000101001001 10 1001 101000101 - 010010010010110101001010 - -For further information: -visit our website https://zencoders.github.io - -**Author:** Sebastiano Merlino - -[Back to TOC](#table-of-contents) +* [Code of Conduct](CODE_OF_CONDUCT.md) +* [Contributing](CONTRIBUTING.md) +* The library is distributed under the GNU LGPL — see [`COPYING.LESSER`](COPYING.LESSER). +* This documentation is distributed under the GNU FDL — see [`LICENSE`](LICENSE). diff --git a/RELEASE_NOTES.md b/RELEASE_NOTES.md new file mode 100644 index 00000000..4dd3fef4 --- /dev/null +++ b/RELEASE_NOTES.md @@ -0,0 +1,236 @@ +# libhttpserver v2.0 — Release Notes + +> **Status:** Informational, not a compatibility commitment. +> This document summarises every public-surface change in v2.0 to help v1 +> consumers port. It is not part of the API contract and is not exhaustive +> — when in doubt, the headers in `src/httpserver/` are authoritative. + +## TL;DR + +libhttpserver v2.0 is a **clean cutover** from the v1.x line: no shims, no +deprecated overloads, no inline namespace. Handlers are now lambdas +(`ws.on_get("/", [](auto&){ return http_response::string("hi"); })`); +responses are value types built from `http_response::string` / `file` / +`iovec` / `pipe` / `empty` / `deferred` / `unauthorized` factories; +request getters return `const&` / `string_view` and never insert on miss; +the threading and error-propagation contracts are documented (DR-008, +DR-009); features disabled at build time report at runtime via +`feature_unavailable` or a documented sentinel value instead of vanishing +from the API. SOVERSION bumps from 1 to 2 and v2 ships as a +`libhttpserver2` binary that is parallel-installable with `libhttpserver1`. +v1.x is end-of-life on the day v2.0 ships. + +## What's gone + +- **Response subclasses.** `string_response`, `file_response`, + `iovec_response`, `pipe_response`, `deferred_response`, `empty_response`, + `basic_auth_fail_response`, `digest_auth_fail_response` are removed. + Build responses through the `http_response::*` factory chain instead + (see "What's renamed" for the 1:1 mapping). +- **Raw-pointer registration.** `register_resource(string, http_resource*, bool family)` + is gone. Use `register_path(unique_ptr|shared_ptr)` or + `register_prefix(unique_ptr|shared_ptr)`. + `register_ws_resource(string, websocket_handler*)` is gone. Use the + smart-pointer overload. +- **`sweet_kill`.** Removed. Use `stop_and_wait()` (or `stop()` for the + signal-only form). +- **IP allow/deny verbs.** `ban_ip`, `unban_ip`, `allow_ip`, + `disallow_ip` are removed. Use `block_ip` / `unblock_ip`. +- **Paired `no_*` boolean setters.** `no_basic_auth`, `no_digest_auth`, + `no_ssl`, `no_debug`, `no_pedantic`, `no_deferred`, `no_regex_checking`, + `no_ban_system`, `no_post_process`, `no_single_resource`, `no_ipv6`, + `no_dual_stack` are removed. The remaining single setter takes a `bool`: + e.g. `cw.ssl(false)` replaces `cw.no_ssl()`. +- **`#define` constants in public headers.** `DEFAULT_WS_PORT`, + `DEFAULT_WS_TIMEOUT`, and the `*_ERROR` / `*_RESPONSE` macros are gone. + Their `constexpr` replacements live in the `httpserver::constants` + namespace. +- **`gnutls_session_t`-returning methods on `http_request`.** Removed. + Use the high-level accessors: `get_client_cert_dn()`, + `get_client_cert_issuer_dn()`, `get_client_cert_fingerprint()`, + `get_cipher_suite()`, `get_protocol_version()`, `get_client_kx()`, + `get_client_cert_type()`, `get_client_credential_type()`. +- **Public virtuals on `http_response`.** `get_raw_response`, + `decorate_response`, `enqueue_response` are gone. `http_response` is no + longer an open base class; it is a value type with no virtual methods. +- **`#ifdef HAVE_BAUTH` / `HAVE_DAUTH` / `HAVE_GNUTLS` / `HAVE_WEBSOCKET` + guards in public headers.** Removed. The public API is now + build-flag-invariant: every method exists on every build. Calls into a + feature disabled at configure time throw `feature_unavailable` or + return a documented sentinel; query the runtime configuration via + `ws.features()`. +- **Public transitive includes of backend C headers.** ``, + ``, ``, `` no longer leak + through ``. A consumer that needs MHD or GnuTLS types + must include them directly. +- **The implicit conversion** `webserver ws = cw;` (where `cw` is a + `create_webserver`). The constructor is now `explicit`. + +## What's new + +- **Lambda registration.** `ws.on_get(path, handler)`, `on_post`, + `on_put`, `on_delete`, `on_patch`, `on_options`, `on_head`. The handler + is `http_response(const http_request&)`. No subclass required. +- **Runtime-method registration.** `ws.route(http_method | method_set, + path, handler)` registers a single handler for a method known only at + runtime, or atomically for a bitmask of methods. +- **Smart-pointer resource registration.** `register_path(path, h)` and + `register_prefix(path, h)` accept `std::unique_ptr` or + `std::shared_ptr`. The boolean `family` flag that used + to live as the third positional argument of `register_resource` is gone + — the choice is encoded in the method name. +- **`http_response` factory chain.** `http_response::string(body)`, + `http_response::file(path)`, `http_response::iovec(entries)`, + `http_response::pipe(fd)`, `http_response::empty(status)`, + `http_response::deferred(...)`, + `http_response::unauthorized(scheme, realm, ...)`. Each returns a + value-type `http_response`. Chain fluent mutators: + `.with_status(int)`, `.with_header(name, value)`, `.with_footer(...)`, + `.with_cookie(...)`. +- **`feature_unavailable`.** Public `std::runtime_error` subclass thrown + by API entry points whose backend feature was disabled at configure + time (e.g. calling `ssl_cert(...)` on a `HAVE_GNUTLS=no` build). +- **`webserver::features()`.** Returns a struct of `bool`s describing + which optional features are linked in (TLS, basic auth, digest auth, + websocket, …). Use this for runtime branching instead of `#ifdef HAVE_*`. +- **`iovec_entry`.** Public POD struct (`{void* iov_base; size_t iov_len;}`) + used by `http_response::iovec`. Replaces the opaque scatter-gather + type that v1 leaked from ``. +- **`http_method` / `method_set`.** Strongly-typed enum and bitmask for + HTTP methods. `route()` accepts either; `http_resource::allow_methods` + uses `method_set`. +- **`httpserver::constants` namespace.** `constexpr` replacements for + every removed `#define`. + +## What's renamed (v1 → v2) + +Every entry below is a single line so a v1 user can grep for the v1 name +and see the v2 replacement. + +| v1 | v2 | +|---|---| +| `sweet_kill` | `stop_and_wait` | +| `ban_ip` | `block_ip` | +| `unban_ip` | `unblock_ip` | +| `allow_ip` | `unblock_ip` (or `block_ip` to deny) | +| `disallow_ip` | `block_ip` (or `unblock_ip` to allow) | +| `not_found_resource` (setter) | `not_found_handler` | +| `method_not_allowed_resource` (setter) | `method_not_allowed_handler` | +| `internal_error_resource` (setter) | `internal_error_handler` | +| `render_GET` | `render_get` | +| `render_POST` | `render_post` | +| `render_PUT` | `render_put` | +| `render_DELETE` | `render_delete` | +| `render_HEAD` | `render_head` | +| `render_OPTIONS` | `render_options` | +| `render_PATCH` | `render_patch` | +| `render_CONNECT` | `render_connect` | +| `render_TRACE` | `render_trace` | +| `webserver(create_webserver const&)` — implicit | `explicit webserver(create_webserver const&)` | +| `register_resource(string, http_resource*, bool family)` — raw pointer + bool flag | `register_path` / `register_prefix` taking `unique_ptr` or `shared_ptr` | +| `register_ws_resource(string, websocket_handler*)` — raw pointer | `register_ws_resource(string, unique_ptr)` (and a `shared_ptr` overload) | +| `string_response` | `http_response::string` | +| `file_response` | `http_response::file` | +| `iovec_response` | `http_response::iovec` | +| `pipe_response` | `http_response::pipe` | +| `empty_response` | `http_response::empty` | +| `deferred_response` | `http_response::deferred` | +| `basic_auth_fail_response` | `http_response::unauthorized` | +| `digest_auth_fail_response` | `http_response::unauthorized` | + +## What changed semantically + +- **Handlers return `http_response` by value.** v1 returned + `std::unique_ptr` (and earlier `std::shared_ptr`); + v2 returns a value. The framework moves it into the dispatch path. No + heap allocation is required for small responses (small-buffer optimisation + inside `http_response`). +- **`http_request` getters return `const&` / `string_view`.** v1's + `get_header(name)` (and `get_arg`, `get_cookie`, `get_footer`) returned + by value and inserted an empty entry into the request map on miss; v2's + versions return a reference / `string_view` and never mutate the + request. Container getters (`get_headers()`, `get_args()`, …) return + `const&` to the underlying map. +- **`http_response::get_header` / `get_footer` / `get_cookie` are + const and do not insert on miss.** Mutation uses the + `with_header` / `with_footer` / `with_cookie` chain, which returns + `*this` by reference (`&` on lvalue calls, `&&` on rvalue calls) for + fluent assembly. +- **`webserver(create_webserver const&)` is `explicit`.** Direct-init + `webserver ws{cw};` rather than copy-init `webserver ws = cw;`. + +## Threading + +The threading contract is now documented; in v1 it was implicit. +See [README.md "Threading contract"](README.md), architecture §5.1 +([specs/architecture/05-cross-cutting.md](specs/architecture/05-cross-cutting.md)) +and DR-008 ([specs/architecture/11-decisions/DR-008.md](specs/architecture/11-decisions/DR-008.md)) +for the full statement. The load-bearing points for porters: + +- Handler invocations from MHD worker threads run concurrently. Shared + state owned by an `http_resource` subclass (or captured by a lambda) + must be synchronised by the application. +- `start()` is one-shot; **do not** call `stop()` or `stop_and_wait()` + from inside a handler thread — MHD's joinable internal thread cannot + join itself and the call aborts the process (DR-008). +- `~webserver()` runs `stop_and_wait()` if the server is still running, + so the same self-join restriction applies to destruction from a + handler thread. + +## Error propagation + +The error-propagation contract is now documented; in v1 it was implicit. +See [README.md "Error propagation"](README.md), architecture §5.2 +([specs/architecture/05-cross-cutting.md](specs/architecture/05-cross-cutting.md)) +and DR-009 ([specs/architecture/11-decisions/DR-009.md](specs/architecture/11-decisions/DR-009.md)) +for the full statement. The load-bearing points for porters: + +- A handler that throws lands at the configured + `internal_error_handler` (a `std::function`). + The `string_view` carries `what()` from the caught exception. Default + behaviour: log and return `500`. +- Calling an API entry point whose backend feature is disabled at + configure time (e.g. `ssl_cert(...)` on a `HAVE_GNUTLS=no` build) + throws `feature_unavailable` — a public `std::runtime_error` subclass. + Build-flag-disabled features therefore surface at **runtime** rather + than disappearing from the API at compile time; query + `ws.features()` to branch defensively. +- The framework never swallows exceptions silently. Anything that + escapes a handler is logged via the configured `log_error` callback + before the `internal_error_handler` fires. + +## Build prerequisites + +- **C++20 floor.** libhttpserver 1.x's last release was C++17-compatible; + v2.0 drops C++17. Concepts, ``, ``, and `consteval` appear + in public headers. +- **Toolchains known good out of the box:** Debian 13 GCC 14.2, + RHEL 10 GCC 14, FreeBSD 14 Clang 18+, current Apple Clang, and + Homebrew GCC 15+. +- **RHEL 9.** Stock GCC 11 on RHEL 9 is too old. Install Red Hat's + `gcc-toolset-14` overlay and `source scl_source enable gcc-toolset-14` + before configuring. + +See [specs/architecture/08-build-and-packaging.md](specs/architecture/08-build-and-packaging.md) +for the full matrix. + +## SOVERSION and packaging + +SOVERSION bumps from `1` to `2`. v2 ships as `libhttpserver2` (binary) +with `libhttpserver2-dev` / `libhttpserver2-devel` for headers and +pkg-config. v1's `libhttpserver1` and v2's `libhttpserver2` are +**parallel-installable**: applications mid-port can link against both +side by side, including under the same `/usr` prefix. + +There is **no inline namespace** and **no symbol-versioning script**: +v2 is a clean rename, not an ABI overlay over v1. v1.x is end-of-life +on the day v2.0 ships — there is no v1 maintenance branch (PRD §1, +DR-011 ([specs/architecture/11-decisions/DR-011.md](specs/architecture/11-decisions/DR-011.md))). + +## See also + +- [README.md](README.md) — full v2.0 introduction and worked examples. +- [examples/](examples/) — every example is v2.0-idiomatic. +- [specs/product_specs.md](specs/product_specs.md) §3.1–§3.7 — the + authoritative requirement set behind each change. +- [ChangeLog](ChangeLog) — formal per-version log. diff --git a/configure.ac b/configure.ac index 4069589d..f2ef0ec4 100644 --- a/configure.ac +++ b/configure.ac @@ -20,8 +20,8 @@ # Process this file with autoconf to produce a configure script. AC_PREREQ(2.57) -m4_define([libhttpserver_MAJOR_VERSION],[0])dnl -m4_define([libhttpserver_MINOR_VERSION],[20])dnl +m4_define([libhttpserver_MAJOR_VERSION],[2])dnl +m4_define([libhttpserver_MINOR_VERSION],[0])dnl m4_define([libhttpserver_REVISION],[0])dnl m4_define([libhttpserver_PKG_VERSION],[libhttpserver_MAJOR_VERSION.libhttpserver_MINOR_VERSION.libhttpserver_REVISION])dnl m4_define([libhttpserver_LDF_VERSION],[libhttpserver_MAJOR_VERSION:libhttpserver_MINOR_VERSION:libhttpserver_REVISION])dnl @@ -44,7 +44,7 @@ AC_LANG([C++]) AC_SYS_LARGEFILE # Minimal feature-set required -AX_CXX_COMPILE_STDCXX([17]) +AX_CXX_COMPILE_STDCXX([20], [noext], [mandatory]) native_srcdir=$srcdir @@ -80,10 +80,19 @@ For native Windows binaries, use the MinGW64 shell instead. ADDITIONAL_LIBS="-lpthread -no-undefined" NETWORK_LIBS="-lws2_32" native_srcdir=$(cd $srcdir; pwd -W) + # libmicrohttpd's asserts _SYS_TYPES_FD_SET on Cygwin/MSYS. + # newlib defines that macro via , included from + # only when __BSD_VISIBLE -- i.e. when _DEFAULT_SOURCE is set. Strict ANSI + # C++ (-std=c++NN, AX_CXX_COMPILE_STDCXX noext) suppresses newlib's + # auto-define, so expose it explicitly here. + CPPFLAGS="-D_DEFAULT_SOURCE $CPPFLAGS" ;; *-cygwin*) NETWORK_HEADER="arpa/inet.h" ADDITIONAL_LIBS="-lpthread -no-undefined" + # See *-msys* note: libmicrohttpd's fd_set check needs _DEFAULT_SOURCE + # under -std=c++NN strict mode. + CPPFLAGS="-D_DEFAULT_SOURCE $CPPFLAGS" ;; *) NETWORK_HEADER="arpa/inet.h" @@ -127,7 +136,11 @@ if test x"$host" = x"$build"; then [AC_MSG_ERROR(["microhttpd.h not found"])] ) - CXXFLAGS="-DHTTPSERVER_COMPILATION -D_REENTRANT $LIBMICROHTTPD_CFLAGS $CXXFLAGS" + # -DHTTPSERVER_COMPILATION is intentionally NOT injected globally into + # CXXFLAGS. It is added per-target via AM_CPPFLAGS in src/Makefile.am and + # test/Makefile.am so that examples (and any other consumer-style TUs) + # build through the umbrella header without seeing the internal macro. + CXXFLAGS="-D_REENTRANT $LIBMICROHTTPD_CFLAGS $CXXFLAGS" LDFLAGS="$LIBMICROHTTPD_LIBS $NETWORK_LIBS $ADDITIONAL_LIBS $LDFLAGS" cond_cross_compile="no" @@ -140,7 +153,9 @@ else [AC_MSG_ERROR(["microhttpd.h not found"])] ) - CXXFLAGS="-DHTTPSERVER_COMPILATION -D_REENTRANT $CXXFLAGS" + # See note above: HTTPSERVER_COMPILATION is scoped to lib + tests via + # per-directory AM_CPPFLAGS, not injected globally into CXXFLAGS. + CXXFLAGS="-D_REENTRANT $CXXFLAGS" LDFLAGS="$NETWORK_LIBS $ADDITIONAL_LIBS $LDFLAGS" cond_cross_compile="yes" @@ -221,7 +236,7 @@ AM_LDFLAGS="-lstdc++" if test x"$debugit" = x"yes"; then AC_DEFINE([DEBUG],[],[Debug Mode]) - AM_CXXFLAGS="$AM_CXXFLAGS -DDEBUG -g -Wall -Wextra -Werror -pedantic -std=c++17 -Wno-unused-command-line-argument -O0" + AM_CXXFLAGS="$AM_CXXFLAGS -DDEBUG -g -Wall -Wextra -Werror -pedantic -Wno-unused-command-line-argument -O0" AM_CFLAGS="$AM_CXXFLAGS -DDEBUG -g -Wall -Wextra -Werror -pedantic -Wno-unused-command-line-argument -O0" else AC_DEFINE([NDEBUG],[],[No-debug Mode]) diff --git a/examples/Makefile.am b/examples/Makefile.am index 9c5db4d1..e68b294c 100644 --- a/examples/Makefile.am +++ b/examples/Makefile.am @@ -19,11 +19,11 @@ LDADD = $(top_builddir)/src/libhttpserver.la AM_CPPFLAGS = -I$(top_srcdir)/src -I$(top_srcdir)/src/httpserver/ METASOURCES = AUTO -noinst_PROGRAMS = hello_world service minimal_hello_world custom_error allowing_disallowing_methods handlers hello_with_get_arg args_processing setting_headers custom_access_log minimal_https minimal_file_response minimal_deferred url_registration minimal_ip_ban benchmark_select benchmark_threads benchmark_nodelay deferred_with_accumulator file_upload file_upload_with_callback empty_response_example iovec_response_example pipe_response_example daemon_info external_event_loop turbo_mode binary_buffer_response +noinst_PROGRAMS = hello_world shared_state service custom_error allowing_disallowing_methods handlers hello_with_get_arg args_processing setting_headers custom_access_log minimal_https minimal_file_response minimal_deferred url_registration minimal_ip_ban benchmark_select benchmark_threads benchmark_nodelay deferred_with_accumulator file_upload file_upload_with_callback empty_response_example iovec_response_example pipe_response_example daemon_info external_event_loop turbo_mode binary_buffer_response hello_world_SOURCES = hello_world.cpp +shared_state_SOURCES = shared_state.cpp service_SOURCES = service.cpp -minimal_hello_world_SOURCES = minimal_hello_world.cpp custom_error_SOURCES = custom_error.cpp allowing_disallowing_methods_SOURCES = allowing_disallowing_methods.cpp handlers_SOURCES = handlers.cpp diff --git a/examples/README.md b/examples/README.md index d2faca33..cba7e80a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -1,58 +1,122 @@ -Example Programs -================ - -hello_world.cpp - a very simple example of using libhttpserver to - create a Rest server capable of receiving and processing - HTTP requests. The server will be listening on port - 8080. - - -service.cpp - an example using more of the libhttpserver API. - This creates a Rest server capable of running with - HTTP or HTTPS (provided that libhttpserver and - libmicrohttpd have been compiled with SSL support. - - The server can be configured via command line - arguments: +libhttpserver Examples +====================== - -p - port number to listen on (default 8080) - -s - enable HTTPS - -k - server key filename (default "key.pem") - -c - server certificate filename (default "cert.pem") +Every example is a standalone program built from a single `.cpp`. To +build the suite locally: + + ./bootstrap && mkdir build && cd build && ../configure && make + +Each binary lands in `build/examples/`. To verify that an example also +compiles against an *installed* libhttpserver (the consumer view), run +`scripts/verify-installed-examples.sh` after `make install`. To enforce +the structural invariants on `hello_world.cpp` and `shared_state.cpp` +(LOC budget, lambda-only form, mutex usage), run +`scripts/check-examples.sh`. + +Start here +---------- + +* `hello_world.cpp` — ten lines, no subclassing, no raw pointers. The + canonical "hello world" demo and the PRD §3.4 acceptance fixture for + the v2.0 lambda idiom. +* `shared_state.cpp` — the canonical example of when the class form is + the right shape: an `http_resource` subclass that shares a `std::mutex`- + guarded counter between `render_get` and `render_post`. + +HTTP basics +----------- + +* `setting_headers.cpp` — attach response headers fluently with + `with_header`. +* `hello_with_get_arg.cpp` — read a query-string parameter from + `http_request::get_arg`. +* `args_processing.cpp` — iterate every form/query argument. +* `custom_error.cpp` — install custom `not_found_handler` and + `method_not_allowed_handler` and let `set_allowing` restrict methods + on a resource. +* `allowing_disallowing_methods.cpp` — narrow a resource to a single + HTTP method via the allow mask. +* `url_registration.cpp` — exact paths, prefix matches, regex paths, + and parametric segments (with optional per-segment regex). +* `handlers.cpp` — register distinct lambdas for GET and POST on the + same path; the dispatcher composes them. + +Response shapes +--------------- + +* `minimal_file_response.cpp` — stream a file from disk. +* `binary_buffer_response.cpp` — return a binary buffer (e.g. a PNG). +* `iovec_response_example.cpp` — gather a response body from multiple + borrowed buffers without copying. +* `pipe_response_example.cpp` — stream from a pipe filled by a + background thread. +* `empty_response_example.cpp` — bodyless responses for DELETE / HEAD. +* `minimal_deferred.cpp` — deferred response: the body is produced + asynchronously by a callback. +* `deferred_with_accumulator.cpp` — deferred response that mutates + shared state across calls. + +TLS and authentication +---------------------- + +* `minimal_https.cpp` — enable TLS with PEM key/cert files. +* `minimal_https_psk.cpp` — TLS with pre-shared keys. +* `basic_authentication.cpp` — per-request HTTP Basic auth inside the + handler. +* `centralized_authentication.cpp` — server-wide `auth_handler` and + `auth_skip_paths`. +* `digest_authentication.cpp` — per-request HTTP Digest auth via + `http_request::check_digest_auth`. +* `client_cert_auth.cpp` — mutual TLS with X.509 client certificates. + Ships as a documentation artifact; not wired into `noinst_PROGRAMS`. + +Operations +---------- + +* `daemon_info.cpp` — introspect the running daemon (bound port, + listen FD, active connections). +* `external_event_loop.cpp` — drive `EXTERNAL_SELECT` from the + application's loop via `run_wait`. +* `custom_access_log.cpp` — server-wide access-log callback. +* `minimal_ip_ban.cpp` — `block_ip` / `unblock_ip` under the default + ACCEPT policy. +* `turbo_mode.cpp` — turbo, suppressed Date header, fastopen queue, + listen backlog. +* `service.cpp` — the kitchen-sink reference example: CLI args, + optional TLS, all `render_*` overrides. + +Benchmarks +---------- + +* `benchmark_select.cpp`, `benchmark_threads.cpp`, + `benchmark_nodelay.cpp` — micro-benchmarks. See `test/v1_baseline/` for + v1.x reference numbers. + +WebSockets +---------- + +* `websocket_echo.cpp` — `websocket_handler` subclass registered via + `register_ws_resource` with `std::make_unique`. + +File upload +----------- + +* `file_upload.cpp`, `file_upload_with_callback.cpp` — multipart + upload, GET serves the HTML form and POST processes the parts. Creating Certificates ===================== + Self-signed certificates can be created using OpenSSL using the following steps: - $ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 - $ openssl rsa -passin pass:x -in server.pass.key -out server.key - $ openssl req -new -key server.key -out server.csr - $ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt + $ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048 + $ openssl rsa -passin pass:x -in server.pass.key -out server.key + $ openssl req -new -key server.key -out server.csr + $ openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt On the last step when prompted for a challenge password it can be left empty. Thanks to https://devcenter.heroku.com/articles/ssl-certificate-self for these instructions. - -Keystore configuration -====================== -If using a local client such as RestClient -(https://github.com/wiztools/rest-client) for testing the Rest server -then a keystore needs to be established. These commands should be -bundled with your Java installation. - -$ keytool -noprompt -import -keystore /path/to/restclient.store -alias -restclient -file /path/to/server.crt - -The keys in the store can be listed as follows: - -$ keytool -list -v -keystore /path/to/restclient.store - -The client can then be configured to use this keystore. Thanks to -http://rubensgomes.blogspot.com/2012/01/how-to-set-up-restclient-for-ssl.html -for instructions on configuring RestClient. - - - diff --git a/examples/allowing_disallowing_methods.cpp b/examples/allowing_disallowing_methods.cpp index 50efa4fd..21b6c8e7 100644 --- a/examples/allowing_disallowing_methods.cpp +++ b/examples/allowing_disallowing_methods.cpp @@ -22,20 +22,25 @@ #include +// The class form is required here: disallow_all() and set_allowing() are +// methods on http_resource that control which HTTP methods are accepted. +// Lambda-registered routes (ws.on_get / ws.on_post / etc.) target a single +// method by construction and do not expose these per-resource controls. +// Use the class form whenever you need fine-grained per-instance method ACLs. class hello_world_resource : public httpserver::http_resource { public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); + httpserver::http_response render(const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); } }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - hello_world_resource hwr; - hwr.disallow_all(); - hwr.set_allowing("GET", true); - ws.register_resource("/hello", &hwr); + auto hwr = std::make_shared(); + hwr->disallow_all(); + hwr->set_allowing(httpserver::http_method::get, true); + ws.register_path("/hello", hwr); ws.start(true); return 0; diff --git a/examples/args_processing.cpp b/examples/args_processing.cpp index ddf41c4e..812669d3 100644 --- a/examples/args_processing.cpp +++ b/examples/args_processing.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,14 +18,7 @@ USA */ -#include -#include -#include -#include - -#include - -// This example demonstrates how to use get_args() and get_args_flat() to +// args_processing.cpp - demonstrates get_args() and get_args_flat() to // process all query string and body arguments from an HTTP request. // // Try these URLs: @@ -33,16 +26,26 @@ // http://localhost:8080/args?id=1&id=2&id=3 (multiple values for same key) // http://localhost:8080/args?colors=red&colors=green&colors=blue -class args_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request& req) { - std::stringstream response_body; +#include +#include +#include +#include + +#include + +int main() { + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/args", [](const httpserver::http_request& req) { + std::ostringstream response_body; response_body << "=== Using get_args() (supports multiple values per key) ===\n\n"; - // get_args() returns a map where each key maps to an http_arg_value. - // http_arg_value contains a vector of values for parameters like "?id=1&id=2&id=3" - auto args = req.get_args(); + // get_args() returns a const reference to a map where each key + // maps to an http_arg_value. http_arg_value contains a vector of + // values for parameters like "?id=1&id=2&id=3". The reference + // remains valid for the duration of this handler call. + const auto& args = req.get_args(); for (const auto& [key, arg_value] : args) { response_body << "Key: " << key << "\n"; // Use get_all_values() to get all values for this key @@ -80,21 +83,13 @@ class args_resource : public httpserver::http_resource { response_body << "name (via get_arg_flat): " << name_flat << "\n"; } - return std::make_shared(response_body.str(), 200, "text/plain"); - } -}; - -int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); - - args_resource ar; - ws.register_resource("/args", &ar); + return httpserver::http_response::string(response_body.str()); + }); std::cout << "Server running on http://localhost:8080/args\n"; std::cout << "Try: http://localhost:8080/args?name=john&age=30\n"; std::cout << "Or: http://localhost:8080/args?id=1&id=2&id=3\n"; ws.start(true); - return 0; } diff --git a/examples/basic_authentication.cpp b/examples/basic_authentication.cpp index 661bbb3c..127a921c 100644 --- a/examples/basic_authentication.cpp +++ b/examples/basic_authentication.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,28 +18,31 @@ USA */ -#include +// basic_authentication.cpp - per-request HTTP Basic auth check inside a +// lambda handler. For centralized auth that intercepts every request, +// see centralized_authentication.cpp. +// +// NOTE: Credentials are hardcoded here for illustration only. In production, +// load expected values from environment variables or a secrets store — never +// from source code. Never reflect the password in the response body. + #include #include -class user_pass_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request& req) { - if (req.get_user() != "myuser" || req.get_pass() != "mypass") { - return std::shared_ptr(new httpserver::basic_auth_fail_response("FAIL", "test@example.com")); - } - - return std::shared_ptr(new httpserver::string_response(std::string(req.get_user()) + " " + std::string(req.get_pass()), 200, "text/plain")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/hello", [](const httpserver::http_request& req) { + if (req.get_user() != "myuser" || req.get_pass() != "mypass") { + return httpserver::http_response::unauthorized( + "Basic", "test@example.com", "FAIL"); + } + // Only echo the username — never reflect the password back to the client. + return httpserver::http_response::string( + "Hello, " + std::string(req.get_user()) + "!"); + }); - user_pass_resource hwr; - ws.register_resource("/hello", &hwr); ws.start(true); - return 0; } diff --git a/examples/benchmark_nodelay.cpp b/examples/benchmark_nodelay.cpp index 96c2f570..bb7048c4 100755 --- a/examples/benchmark_nodelay.cpp +++ b/examples/benchmark_nodelay.cpp @@ -28,31 +28,24 @@ class hello_world_resource : public httpserver::http_resource { public: - explicit hello_world_resource(const std::shared_ptr& resp): - resp(resp) { + // TASK-036: http_response is a movable value type; build it + // per-request rather than caching a shared instance. + httpserver::http_response render(const httpserver::http_request&) override { + return httpserver::http_response::string(BODY) + .with_header("Server", "libhttpserver"); } - - std::shared_ptr render(const httpserver::http_request&) { - return resp; - } - - private: - std::shared_ptr resp; }; int main(int argc, char** argv) { std::ignore = argc; - httpserver::webserver ws = httpserver::create_webserver(atoi(argv[1])) + httpserver::webserver ws{httpserver::create_webserver(atoi(argv[1])) .start_method(httpserver::http::http_utils::INTERNAL_SELECT) .tcp_nodelay() - .max_threads(atoi(argv[2])); - - std::shared_ptr hello = std::shared_ptr(new httpserver::string_response(BODY, 200)); - hello->with_header("Server", "libhttpserver"); + .max_threads(atoi(argv[2]))}; - hello_world_resource hwr(hello); - ws.register_resource(PATH, &hwr, false); + auto hwr = std::make_shared(); + ws.register_path(PATH, hwr); ws.start(true); diff --git a/examples/benchmark_select.cpp b/examples/benchmark_select.cpp index ef5cd089..961068d5 100755 --- a/examples/benchmark_select.cpp +++ b/examples/benchmark_select.cpp @@ -28,30 +28,23 @@ class hello_world_resource : public httpserver::http_resource { public: - explicit hello_world_resource(const std::shared_ptr& resp): - resp(resp) { + // TASK-036: http_response is a movable value type; build it + // per-request rather than caching a shared instance. + httpserver::http_response render(const httpserver::http_request&) override { + return httpserver::http_response::string(BODY) + .with_header("Server", "libhttpserver"); } - - std::shared_ptr render(const httpserver::http_request&) { - return resp; - } - - private: - std::shared_ptr resp; }; int main(int argc, char** argv) { std::ignore = argc; - httpserver::webserver ws = httpserver::create_webserver(atoi(argv[1])) + httpserver::webserver ws{httpserver::create_webserver(atoi(argv[1])) .start_method(httpserver::http::http_utils::INTERNAL_SELECT) - .max_threads(atoi(argv[2])); - - std::shared_ptr hello = std::shared_ptr(new httpserver::string_response(BODY, 200)); - hello->with_header("Server", "libhttpserver"); + .max_threads(atoi(argv[2]))}; - hello_world_resource hwr(hello); - ws.register_resource(PATH, &hwr, false); + auto hwr = std::make_shared(); + ws.register_path(PATH, hwr); ws.start(true); diff --git a/examples/benchmark_threads.cpp b/examples/benchmark_threads.cpp index db376168..3c6fa92e 100755 --- a/examples/benchmark_threads.cpp +++ b/examples/benchmark_threads.cpp @@ -28,29 +28,22 @@ class hello_world_resource : public httpserver::http_resource { public: - explicit hello_world_resource(const std::shared_ptr& resp): - resp(resp) { + // TASK-036: http_response is a movable value type; build it + // per-request rather than caching a shared instance. + httpserver::http_response render(const httpserver::http_request&) override { + return httpserver::http_response::string(BODY) + .with_header("Server", "libhttpserver"); } - - std::shared_ptr render(const httpserver::http_request&) { - return resp; - } - - private: - std::shared_ptr resp; }; int main(int argc, char** argv) { std::ignore = argc; - httpserver::webserver ws = httpserver::create_webserver(atoi(argv[1])) - .start_method(httpserver::http::http_utils::THREAD_PER_CONNECTION); - - std::shared_ptr hello = std::shared_ptr(new httpserver::string_response(BODY, 200)); - hello->with_header("Server", "libhttpserver"); + httpserver::webserver ws{httpserver::create_webserver(atoi(argv[1])) + .start_method(httpserver::http::http_utils::THREAD_PER_CONNECTION)}; - hello_world_resource hwr(hello); - ws.register_resource(PATH, &hwr, false); + auto hwr = std::make_shared(); + ws.register_path(PATH, hwr); ws.start(true); diff --git a/examples/binary_buffer_response.cpp b/examples/binary_buffer_response.cpp index 19559cfc..82f63abe 100644 --- a/examples/binary_buffer_response.cpp +++ b/examples/binary_buffer_response.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,21 +18,14 @@ USA */ -// This example demonstrates how to serve binary data (e.g., images) directly -// from an in-memory buffer using string_response. Despite its name, -// string_response works with arbitrary binary content because std::string can -// hold any bytes, including null characters. -// -// This is useful when you generate or receive binary data at runtime (e.g., -// from a camera, an image library, or a database) and want to serve it over -// HTTP without writing it to disk first. +// binary_buffer_response.cpp - serve binary data (e.g., images) directly +// from an in-memory buffer. std::string holds arbitrary bytes, including +// null characters, making it suitable for any binary content. // // To test: // curl -o output.png http://localhost:8080/image -#include #include -#include #include @@ -52,31 +45,21 @@ static std::string generate_png_data() { 0x00, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, // IEND chunk 0x44, 0xae, 0x42, 0x60, 0x82 }; - return std::string(reinterpret_cast(png), sizeof(png)); } -class image_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - // Build binary content as a std::string. The string can contain any - // bytes — it is not limited to printable characters or null-terminated - // C strings. The size is tracked internally by std::string::size(). - std::string image_data = generate_png_data(); - - // Use string_response with the appropriate content type. The response - // will send the exact bytes contained in the string. - return std::make_shared( - std::move(image_data), 200, "image/png"); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - image_resource ir; - ws.register_resource("/image", &ir); - ws.start(true); + // Lambda form: stateless handlers need no class. generate_png_data() + // stays a plain static function; the lambda calls it per request. + ws.on_get("/image", [](const httpserver::http_request&) { + // The response sends the exact bytes in the string — the size is + // tracked internally, so null bytes and non-printable characters + // are transmitted correctly. + return httpserver::http_response::string(generate_png_data(), "image/png"); + }); + ws.start(true); return 0; } diff --git a/examples/centralized_authentication.cpp b/examples/centralized_authentication.cpp index 0f965af6..80e273fa 100644 --- a/examples/centralized_authentication.cpp +++ b/examples/centralized_authentication.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,71 +18,71 @@ USA */ +// centralized_authentication.cpp - install a server-wide auth_handler +// that runs before every request. The handler returns nullptr to +// accept, or an http_response to reject. auth_skip_paths lists routes +// that bypass auth entirely. +// +// SECURITY NOTE: Credentials MUST NOT be hardcoded in source code (CWE-798). +// This example loads AUTH_USER and AUTH_PASS from environment variables. +// Set them before running: +// export AUTH_USER=myuser +// export AUTH_PASS=mysecretpassword +// ./centralized_authentication + +#include +#include #include #include #include -using httpserver::http_request; -using httpserver::http_response; -using httpserver::http_resource; -using httpserver::webserver; -using httpserver::create_webserver; -using httpserver::string_response; -using httpserver::basic_auth_fail_response; - -// Simple resource that doesn't need to handle auth itself -class hello_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("Hello, authenticated user!", 200, "text/plain"); +// Returns nullptr to allow the request, or an http_response to reject it. +std::shared_ptr auth_handler( + const httpserver::http_request& req) { + const char* expected_user = std::getenv("AUTH_USER"); + const char* expected_pass = std::getenv("AUTH_PASS"); + if (!expected_user || !expected_pass) { + std::cerr << "centralized_authentication: AUTH_USER and AUTH_PASS " + "environment variables must be set.\n"; + return std::make_shared( + httpserver::http_response::string("Server configuration error") + .with_status(500)); } -}; - -class health_resource : public http_resource { - public: - std::shared_ptr render_GET(const http_request&) { - return std::make_shared("OK", 200, "text/plain"); + if (req.get_user() != expected_user || req.get_pass() != expected_pass) { + return std::make_shared( + httpserver::http_response::unauthorized( + "Basic", "MyRealm", "Unauthorized")); } -}; - -// Centralized authentication handler -// Returns nullptr to allow the request, or an http_response to reject it -std::shared_ptr auth_handler(const http_request& req) { - if (req.get_user() != "admin" || req.get_pass() != "secret") { - return std::make_shared("Unauthorized", "MyRealm"); - } - return nullptr; // Allow request + return nullptr; } int main() { - // Create webserver with centralized authentication - // - auth_handler: called before every resource's render method - // - auth_skip_paths: paths that bypass authentication - webserver ws = create_webserver(8080) - .auth_handler(auth_handler) - .auth_skip_paths({"/health", "/public/*"}); + httpserver::webserver ws{httpserver::create_webserver(8080) + .auth_handler(auth_handler) + .auth_skip_paths({"/health", "/public/*"})}; - hello_resource hello; - health_resource health; - - ws.register_resource("/api", &hello); - ws.register_resource("/health", &health); + ws.on_get("/api", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, authenticated user!"); + }); + ws.on_get("/health", [](const httpserver::http_request&) { + return httpserver::http_response::string("OK"); + }); ws.start(true); - return 0; } // Usage: -// # Start the server +// # Set credentials and start the server +// export AUTH_USER=myuser AUTH_PASS=mysecretpassword // ./centralized_authentication // // # Without auth - should get 401 Unauthorized // curl -v http://localhost:8080/api // // # With valid auth - should get 200 OK -// curl -u admin:secret http://localhost:8080/api +// curl -u myuser:mysecretpassword http://localhost:8080/api // // # Health endpoint (skip path) - works without auth // curl http://localhost:8080/health diff --git a/examples/client_cert_auth.cpp b/examples/client_cert_auth.cpp index 90a3ba84..05677ff6 100644 --- a/examples/client_cert_auth.cpp +++ b/examples/client_cert_auth.cpp @@ -52,6 +52,7 @@ * curl -k https://localhost:8443/secure */ +#include #include #include #include @@ -66,51 +67,45 @@ std::set allowed_fingerprints; // Resource that requires client certificate authentication class secure_resource : public httpserver::http_resource { public: - std::shared_ptr render_GET(const httpserver::http_request& req) { + httpserver::http_response render_get(const httpserver::http_request& req) { // Check if client provided a certificate if (!req.has_client_certificate()) { - return std::make_shared( - "Client certificate required", - httpserver::http::http_utils::http_unauthorized, "text/plain"); + return httpserver::http_response::string("Client certificate required").with_status(httpserver::http::http_utils::http_unauthorized); } - // Get certificate information - std::string cn = req.get_client_cert_cn(); - std::string dn = req.get_client_cert_dn(); - std::string issuer = req.get_client_cert_issuer_dn(); - std::string fingerprint = req.get_client_cert_fingerprint_sha256(); + // Get certificate information. TASK-019: the four string-typed + // accessors return string_view aliasing per-request storage; we + // copy into std::string here so the locals survive the rest of + // this method (and so the `+` chains below compile). + std::string cn(req.get_client_cert_cn()); + std::string dn(req.get_client_cert_dn()); + std::string issuer(req.get_client_cert_issuer_dn()); + std::string fingerprint(req.get_client_cert_fingerprint_sha256()); bool verified = req.is_client_cert_verified(); // Check if certificate is verified by our CA if (!verified) { - return std::make_shared( - "Certificate not verified by trusted CA", - httpserver::http::http_utils::http_forbidden, "text/plain"); + return httpserver::http_response::string("Certificate not verified by trusted CA").with_status(httpserver::http::http_utils::http_forbidden); } // Optional: Check fingerprint against allowlist if (!allowed_fingerprints.empty() && allowed_fingerprints.find(fingerprint) == allowed_fingerprints.end()) { - return std::make_shared( - "Certificate not in allowlist", - httpserver::http::http_utils::http_forbidden, "text/plain"); + return httpserver::http_response::string("Certificate not in allowlist").with_status(httpserver::http::http_utils::http_forbidden); } - // Check certificate validity times + // Check certificate validity times. TASK-019 narrows the + // accessor return type to std::int64_t. time_t now = time(nullptr); - time_t not_before = req.get_client_cert_not_before(); - time_t not_after = req.get_client_cert_not_after(); + std::int64_t not_before = req.get_client_cert_not_before(); + std::int64_t not_after = req.get_client_cert_not_after(); if (now < not_before) { - return std::make_shared( - "Certificate not yet valid", - httpserver::http::http_utils::http_forbidden, "text/plain"); + return httpserver::http_response::string("Certificate not yet valid").with_status(httpserver::http::http_utils::http_forbidden); } if (now > not_after) { - return std::make_shared( - "Certificate has expired", - httpserver::http::http_utils::http_forbidden, "text/plain"); + return httpserver::http_response::string("Certificate has expired").with_status(httpserver::http::http_utils::http_forbidden); } // Build response with certificate info @@ -121,26 +116,28 @@ class secure_resource : public httpserver::http_resource { response += " Fingerprint (SHA-256): " + fingerprint + "\n"; response += " Verified: " + std::string(verified ? "Yes" : "No") + "\n"; - return std::make_shared(response, 200, "text/plain"); + return httpserver::http_response::string(response); } }; // Public resource that shows certificate info but doesn't require it class info_resource : public httpserver::http_resource { public: - std::shared_ptr render_GET(const httpserver::http_request& req) { + httpserver::http_response render_get(const httpserver::http_request& req) { std::string response; if (req.has_client_certificate()) { response = "Client certificate detected:\n"; - response += " Common Name: " + req.get_client_cert_cn() + "\n"; + // TASK-019: get_client_cert_cn() returns string_view; copy + // into std::string for the `+` chain. + response += " Common Name: " + std::string(req.get_client_cert_cn()) + "\n"; response += " Verified: " + std::string(req.is_client_cert_verified() ? "Yes" : "No") + "\n"; } else { response = "No client certificate provided.\n"; response += "Use --cert and --key with curl to provide one.\n"; } - return std::make_shared(response, 200, "text/plain"); + return httpserver::http_response::string(response); } }; @@ -151,17 +148,17 @@ int main() { std::cout << " /secure - Requires valid client certificate\n\n"; // Create webserver with SSL and client certificate trust store - httpserver::webserver ws = httpserver::create_webserver(8443) + httpserver::webserver ws{httpserver::create_webserver(8443) .use_ssl() .https_mem_key("server_key.pem") // Server private key .https_mem_cert("server_cert.pem") // Server certificate - .https_mem_trust("ca_cert.pem"); // CA certificate for verifying client certs + .https_mem_trust("ca_cert.pem")}; // CA certificate for verifying client certs - secure_resource secure; - info_resource info; + auto secure = std::make_shared(); + auto info = std::make_shared(); - ws.register_resource("/secure", &secure); - ws.register_resource("/info", &info); + ws.register_path("/secure", secure); + ws.register_path("/info", info); std::cout << "Server started. Press Ctrl+C to stop.\n\n"; std::cout << "Test commands:\n"; diff --git a/examples/custom_access_log.cpp b/examples/custom_access_log.cpp index 8f596c90..488a7fb5 100644 --- a/examples/custom_access_log.cpp +++ b/examples/custom_access_log.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,8 +18,11 @@ USA */ +// custom_access_log.cpp - install a per-request access-log callback via +// create_webserver().log_access(). The callback is server-wide; the +// handler itself is a plain lambda. + #include -#include #include #include @@ -28,20 +31,14 @@ void custom_access_log(const std::string& url) { std::cout << "ACCESSING: " << url << std::endl; } -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080) - .log_access(custom_access_log); + httpserver::webserver ws{httpserver::create_webserver(8080) + .log_access(custom_access_log)}; - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); + }); + ws.start(true); return 0; } diff --git a/examples/custom_error.cpp b/examples/custom_error.cpp index c38fb169..4a837ef9 100644 --- a/examples/custom_error.cpp +++ b/examples/custom_error.cpp @@ -22,30 +22,30 @@ #include -std::shared_ptr not_found_custom(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Not found custom", 404, "text/plain")); +httpserver::http_response not_found_custom(const httpserver::http_request&) { + return httpserver::http_response::string("Not found custom").with_status(404); } -std::shared_ptr not_allowed_custom(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Not allowed custom", 405, "text/plain")); +httpserver::http_response not_allowed_custom(const httpserver::http_request&) { + return httpserver::http_response::string("Not allowed custom").with_status(405); } class hello_world_resource : public httpserver::http_resource { public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); + httpserver::http_response render(const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); } }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080) - .not_found_resource(not_found_custom) - .method_not_allowed_resource(not_allowed_custom); - - hello_world_resource hwr; - hwr.disallow_all(); - hwr.set_allowing("GET", true); - ws.register_resource("/hello", &hwr); + httpserver::webserver ws{httpserver::create_webserver(8080) + .not_found_handler(not_found_custom) + .method_not_allowed_handler(not_allowed_custom)}; + + auto hwr = std::make_shared(); + hwr->disallow_all(); + hwr->set_allowing(httpserver::http_method::get, true); + ws.register_path("/hello", hwr); ws.start(true); return 0; diff --git a/examples/daemon_info.cpp b/examples/daemon_info.cpp index c854bbac..07f4d047 100644 --- a/examples/daemon_info.cpp +++ b/examples/daemon_info.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2019 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,27 +18,23 @@ USA */ +// daemon_info.cpp - introspect the running daemon (bound port, listen FD, +// active connections, etc.) after start(false). Port 0 lets the OS pick +// an ephemeral port so multiple instances can coexist. + #include -#include #include -class hello_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::make_shared("Hello, World!"); - } -}; - int main() { - // Use port 0 to let the OS assign an ephemeral port - httpserver::webserver ws = httpserver::create_webserver(0); + httpserver::webserver ws{httpserver::create_webserver(0)}; + + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); + }); - hello_resource hr; - ws.register_resource("/hello", &hr); ws.start(false); - // Query daemon information std::cout << "libmicrohttpd version: " << httpserver::http::http_utils::get_mhd_version() << std::endl; std::cout << "Bound port: " << ws.get_bound_port() << std::endl; @@ -52,8 +48,6 @@ int main() { std::cout << "\nServer running on port " << ws.get_bound_port() << ". Press Ctrl+C to stop." << std::endl; - // Block until interrupted - ws.sweet_kill(); - + ws.stop_and_wait(); return 0; } diff --git a/examples/deferred_with_accumulator.cpp b/examples/deferred_with_accumulator.cpp index a4367773..f69b4249 100644 --- a/examples/deferred_with_accumulator.cpp +++ b/examples/deferred_with_accumulator.cpp @@ -20,6 +20,7 @@ #include #include +#include #include // cpplint errors on chrono and thread because they are replaced (in Chromium) by other google libraries. // This is not an issue here. @@ -30,47 +31,47 @@ #include +// Global counter: tracks how many connections have been established. +// Each render_get() call captures a snapshot (reqid) by value. std::atomic counter; -ssize_t test_callback(std::shared_ptr > closure_data, char* buf, size_t max) { - int reqid; - if (closure_data == nullptr) { - reqid = -1; - } else { - reqid = *closure_data; - } - - // only first 5 connections can be established - if (reqid >= 5) { - return -1; - } else { - // respond corresponding request IDs to the clients - std::string str = ""; - str += std::to_string(reqid) + " "; - memset(buf, 0, max); - std::copy(str.begin(), str.end(), buf); - - // keep sending reqid - // sleep(1); ==> adapted for C++11 on non-*Nix systems - std::this_thread::sleep_for(std::chrono::seconds(1)); - - return (ssize_t)max; - } -} - class deferred_resource : public httpserver::http_resource { public: - std::shared_ptr render_GET(const httpserver::http_request&) { - std::shared_ptr > closure_data(new std::atomic(counter++)); - return std::shared_ptr > >(new httpserver::deferred_response >(test_callback, closure_data, "cycle callback response")); + httpserver::http_response render_get(const httpserver::http_request&) override { + int reqid = counter++; + std::string preamble = "cycle callback response"; + return + httpserver::http_response::deferred( + [reqid, preamble, + served = false](std::uint64_t, char* buf, + std::size_t max) mutable -> ssize_t { + if (!served) { + served = true; + std::size_t n = std::min(preamble.size(), max); + memcpy(buf, preamble.data(), n); + return n; + } + // only first 5 connections can be established + if (reqid >= 5) { + return -1; + } + // respond corresponding request IDs to the clients + std::string str = std::to_string(reqid) + " "; + memset(buf, 0, max); + std::copy(str.begin(), str.end(), buf); + // keep sending reqid + // sleep(1); ==> adapted for C++11 on non-*Nix systems + std::this_thread::sleep_for(std::chrono::seconds(1)); + return static_cast(max); + }); } }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - deferred_resource hwr; - ws.register_resource("/hello", &hwr); + auto hwr = std::make_shared(); + ws.register_path("/hello", hwr); ws.start(true); return 0; diff --git a/examples/digest_authentication.cpp b/examples/digest_authentication.cpp index ddf0be77..a33eb8e7 100644 --- a/examples/digest_authentication.cpp +++ b/examples/digest_authentication.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,39 +18,41 @@ USA */ -#include +// digest_authentication.cpp - per-request HTTP Digest auth check inside +// a lambda handler. The two `unauthorized` returns are intentionally +// indistinguishable to the client to avoid leaking nonce-state info. +// +// NOTE: SHA-256 is used here (RFC 7616). MD5-based Digest auth is broken +// (trivially cracked by offline dictionary attacks against the HA1 hash) and +// must not be used in new deployments. Use SHA-256 or stronger. +// +// The 300-second nonce lifetime balances usability (clients can retry without +// re-authenticating) against replay-attack window. Shorten for higher security. +// +// NOTE: Credentials are hardcoded here for illustration only. In production, +// load them from environment variables or a secrets store. #include -#define MY_OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" - -class digest_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request& req) { - using httpserver::http::http_utils; - if (req.get_digested_user() == "") { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, true, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } else { - auto result = req.check_digest_auth("test@example.com", "mypass", 300, 0, http_utils::digest_algorithm::MD5); - if (result == http_utils::digest_auth_result::NONCE_STALE) { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, true, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } else if (result != http_utils::digest_auth_result::OK) { - return std::make_shared("FAIL", "test@example.com", MY_OPAQUE, false, - http_utils::http_ok, http_utils::text_plain, http_utils::digest_algorithm::MD5); - } - } - return std::make_shared("SUCCESS", 200, "text/plain"); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/hello", [](const httpserver::http_request& req) { + using httpserver::http::http_utils; + if (req.get_digested_user() == "") { + return httpserver::http_response::unauthorized( + "Digest", "test@example.com", "FAIL"); + } + auto result = req.check_digest_auth( + "test@example.com", "mypass", 300, 0, + http_utils::digest_algorithm::SHA256); + if (result != http_utils::digest_auth_result::OK) { + return httpserver::http_response::unauthorized( + "Digest", "test@example.com", "FAIL"); + } + return httpserver::http_response::string("SUCCESS"); + }); - digest_resource hwr; - ws.register_resource("/hello", &hwr); ws.start(true); - return 0; } diff --git a/examples/empty_response_example.cpp b/examples/empty_response_example.cpp index 17a4a443..e56cd736 100644 --- a/examples/empty_response_example.cpp +++ b/examples/empty_response_example.cpp @@ -24,27 +24,28 @@ class no_content_resource : public httpserver::http_resource { public: - std::shared_ptr render_DELETE(const httpserver::http_request&) { + httpserver::http_response render_delete(const httpserver::http_request&) override { // Return a 204 No Content response with no body - return std::make_shared( - httpserver::http::http_utils::http_no_content); + return + httpserver::http_response::empty(); } - std::shared_ptr render_HEAD(const httpserver::http_request&) { - // Return a HEAD-only response with headers but no body - auto response = std::make_shared( - httpserver::http::http_utils::http_ok, - httpserver::empty_response::HEAD_ONLY); - response->with_header("X-Total-Count", "42"); - return response; + httpserver::http_response render_head(const httpserver::http_request&) override { + // Return a 200 OK response with metadata headers and no body. + // libhttpserver already strips the body for HEAD requests, so + // http_response::empty() is the correct v2.0 idiom — no raw MHD + // flag is needed. + return httpserver::http_response::empty() + .with_status(httpserver::http::http_utils::http_ok) + .with_header("X-Total-Count", "42"); } }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - no_content_resource ncr; - ws.register_resource("/items", &ncr); + auto ncr = std::make_shared(); + ws.register_path("/items", ncr); ws.start(true); return 0; diff --git a/examples/external_event_loop.cpp b/examples/external_event_loop.cpp index df6d9749..828cb24c 100644 --- a/examples/external_event_loop.cpp +++ b/examples/external_event_loop.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2019 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,10 +18,13 @@ USA */ +// external_event_loop.cpp - run the daemon under EXTERNAL_SELECT and +// drive it via run_wait() from the application's own loop. The +// thread_safety(false) optimization is intentionally omitted for +// portability (some MHD builds reject the combination at start). + #include -#include #include -#include #include @@ -31,43 +34,29 @@ void signal_handler(int) { running = false; } -class hello_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::make_shared("Hello from external event loop!"); - } -}; - int main() { signal(SIGINT, signal_handler); - // EXTERNAL_SELECT runs MHD without an internal polling thread; the - // application drives it via run_wait() below. no_thread_safety() can be - // added for a small perf gain when the daemon is only ever touched from - // a single thread, but it is omitted here for portability (some MHD - // builds, notably Windows/MSYS2, reject that combination at start). - httpserver::webserver ws = httpserver::create_webserver(8080) - .start_method(httpserver::http::http_utils::EXTERNAL_SELECT); + httpserver::webserver ws{httpserver::create_webserver(8080) + .start_method(httpserver::http::http_utils::EXTERNAL_SELECT)}; + + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello from external event loop!"); + }); - hello_resource hr; - ws.register_resource("/hello", &hr); ws.start(false); std::cout << "Server running on port " << ws.get_bound_port() << std::endl; - // Drive the event loop externally using run_wait while (running) { - // Block for up to 1000ms waiting for HTTP activity ws.run_wait(1000); - - // You can do other work here between iterations + // Do other work between iterations as needed. } std::cout << "\nShutting down..." << std::endl; - // Graceful shutdown: stop accepting new connections first + // Graceful shutdown: stop accepting new connections first. ws.quiesce(); ws.stop(); - return 0; } diff --git a/examples/file_upload.cpp b/examples/file_upload.cpp index 0916a4fc..9bc14b38 100644 --- a/examples/file_upload.cpp +++ b/examples/file_upload.cpp @@ -26,45 +26,48 @@ class file_upload_resource : public httpserver::http_resource { public: - std::shared_ptr render_GET(const httpserver::http_request&) { - std::string get_response = "\n"; - get_response += " \n"; - get_response += "
\n"; - get_response += "

Upload 1 (key is 'files', multiple files can be selected)


\n"; - get_response += " \n"; - get_response += "

\n"; - get_response += "

Upload 2 (key is 'files2', multiple files can be selected)


\n"; - get_response += "

\n"; - get_response += " \n"; - get_response += "
\n"; - get_response += " \n"; - get_response += "\n"; - - return std::shared_ptr(new httpserver::string_response(get_response, 200, "text/html")); + httpserver::http_response render_get(const httpserver::http_request&) { + return httpserver::http_response::string(R"html( + +
+

Upload 1 (key is 'files', multiple files can be selected)


+ +

+

Upload 2 (key is 'files2', multiple files can be selected)


+

+ +
+ + +)html", "text/html"); } - std::shared_ptr render_POST(const httpserver::http_request& req) { - std::string post_response = "\n"; - post_response += "\n"; - post_response += " \n"; - post_response += "\n"; - post_response += "\n"; - post_response += " Uploaded files:\n"; - post_response += "

\n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; - post_response += " \n"; + httpserver::http_response render_post(const httpserver::http_request& req) { + // Static header built from a raw string literal to avoid per-append + // reallocations. The dynamic rows are appended after an upfront reserve. + std::string post_response = R"html( + + + + + Uploaded files: +

+
KeyUploaded filenameFile system pathFile sizeContent typeTransfer encoding
+ + + + + + + + +)html"; + post_response.reserve(post_response.size() + 512); for (auto &file_key : req.get_files()) { for (auto &files : file_key.second) { @@ -87,7 +90,7 @@ class file_upload_resource : public httpserver::http_resource { post_response += "
KeyUploaded filenameFile system pathFile sizeContent typeTransfer encoding


\n"; post_response += " back\n"; post_response += "\n"; - return std::shared_ptr(new httpserver::string_response(post_response, 201, "text/html")); + return httpserver::http_response::string(post_response, "text/html").with_status(201); } }; @@ -104,14 +107,14 @@ int main(int argc, char** argv) { std::cout << "These files won't be deleted at termination" << std::endl; std::cout << "Please make sure, that the given directory exists and is writeable" << std::endl; - httpserver::webserver ws = httpserver::create_webserver(8080) - .no_put_processed_data_to_content() + httpserver::webserver ws{httpserver::create_webserver(8080) + .put_processed_data_to_content(false) .file_upload_dir(std::string(argv[1])) .generate_random_filename_on_upload() - .file_upload_target(httpserver::FILE_UPLOAD_DISK_ONLY); + .file_upload_target(httpserver::FILE_UPLOAD_DISK_ONLY)}; - file_upload_resource fur; - ws.register_resource("/", &fur); + auto fur = std::make_shared(); + ws.register_path("/", fur); ws.start(true); return 0; diff --git a/examples/file_upload_with_callback.cpp b/examples/file_upload_with_callback.cpp index edc5338f..dee0d4fa 100644 --- a/examples/file_upload_with_callback.cpp +++ b/examples/file_upload_with_callback.cpp @@ -27,40 +27,44 @@ class file_upload_resource : public httpserver::http_resource { public: - std::shared_ptr render_GET(const httpserver::http_request&) { - std::string get_response = "\n"; - get_response += " \n"; - get_response += "

File Upload with Cleanup Callback Demo

\n"; - get_response += "

Uploaded files will be moved to the permanent directory.

\n"; - get_response += "
\n"; - get_response += " \n"; - get_response += "

\n"; - get_response += " \n"; - get_response += "
\n"; - get_response += " \n"; - get_response += "\n"; - - return std::shared_ptr(new httpserver::string_response(get_response, 200, "text/html")); + httpserver::http_response render_get(const httpserver::http_request&) { + return httpserver::http_response::string(R"html( + +

File Upload with Cleanup Callback Demo

+

Uploaded files will be moved to the permanent directory.

+
+ +

+ +
+ + +)html", "text/html"); } - std::shared_ptr render_POST(const httpserver::http_request& req) { - std::string post_response = "\n"; - post_response += "\n"; - post_response += "

Upload Complete

\n"; - post_response += "

Files have been moved to permanent storage:

\n"; - post_response += "
    \n"; + httpserver::http_response render_post(const httpserver::http_request& req) { + std::string post_response = R"html( + +

    Upload Complete

    +

    Files have been moved to permanent storage:

    +
      +)html"; + post_response.reserve(post_response.size() + 256); for (auto &file_key : req.get_files()) { for (auto &files : file_key.second) { - post_response += "
    • " + files.first + " (" + - std::to_string(files.second.get_file_size()) + " bytes)
    • \n"; + post_response += "
    • "; + post_response += files.first; + post_response += " ("; + post_response += std::to_string(files.second.get_file_size()); + post_response += " bytes)
    • \n"; } } post_response += "
    \n"; post_response += " Upload more\n"; post_response += "\n"; - return std::shared_ptr(new httpserver::string_response(post_response, 201, "text/html")); + return httpserver::http_response::string(post_response, "text/html").with_status(201); } }; @@ -82,7 +86,7 @@ int main(int argc, char** argv) { std::cout << std::endl; std::cout << "Open http://localhost:8080 in your browser to upload files." << std::endl; - httpserver::webserver ws = httpserver::create_webserver(8080) + httpserver::webserver ws{httpserver::create_webserver(8080) .file_upload_target(httpserver::FILE_UPLOAD_DISK_ONLY) .file_upload_dir(temp_dir) .generate_random_filename_on_upload() @@ -101,10 +105,10 @@ int main(int argc, char** argv) { std::cerr << "Failed to move " << filename << ", will be deleted" << std::endl; return true; // Delete the temp file on failure } - }); + })}; - file_upload_resource fur; - ws.register_resource("/", &fur); + auto fur = std::make_shared(); + ws.register_path("/", fur); ws.start(true); return 0; diff --git a/examples/handlers.cpp b/examples/handlers.cpp index 4fc70303..427fd4df 100644 --- a/examples/handlers.cpp +++ b/examples/handlers.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,28 +18,23 @@ USA */ -#include +// handlers.cpp - register distinct lambda handlers for two HTTP methods +// on the same path. The webserver composes them: a GET to /hello dispatches +// to the first lambda, a POST to the second, and any other method gets the +// default 405 Method Not Allowed response. #include -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("GET: Hello, World!")); - } - - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("OTHER: Hello, World!")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("GET: Hello, World!"); + }); + ws.on_post("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("POST: Hello, World!"); + }); + ws.start(true); return 0; } - diff --git a/examples/hello_with_get_arg.cpp b/examples/hello_with_get_arg.cpp index 41829a4d..d303fbd7 100644 --- a/examples/hello_with_get_arg.cpp +++ b/examples/hello_with_get_arg.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,24 +18,29 @@ USA */ -#include +// hello_with_get_arg.cpp - read a query-string argument inside a lambda +// handler. Try: curl 'http://localhost:8080/hello?name=world' +// +// NOTE: The response is plain text. If you adapt this for an HTML response, +// you must HTML-entity-encode user-supplied input before inserting it into +// the document body — raw reflection into HTML introduces reflected XSS +// (CWE-79). The explicit "text/plain" content type below signals that +// context and prevents browsers from sniffing the body as HTML. + #include #include -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request& req) { - return std::shared_ptr(new httpserver::string_response("Hello: " + std::string(req.get_arg("name")))); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request& req) { + // Explicit "text/plain" avoids browser content-type sniffing. + // Never reflect user input into an HTML response without encoding. + return httpserver::http_response::string( + "Hello: " + std::string(req.get_arg("name")), "text/plain"); + }); + ws.start(true); return 0; } diff --git a/examples/hello_world.cpp b/examples/hello_world.cpp index 9c06f87a..291e7e68 100755 --- a/examples/hello_world.cpp +++ b/examples/hello_world.cpp @@ -1,61 +1,17 @@ -/* - This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino - - 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 -*/ - -#include -#include -#include - +// Copyright 2026 Sebastiano Merlino +// libhttpserver hello-world example — the lambda form (PRD §3.4). +// Compiles in ten lines including main(), with no http_resource subclass +// and no raw-pointer ownership. Production code typically qualifies names +// explicitly; the `using namespace` here is a one-off so this file can +// document the shortest possible end-to-end demo. See shared_state.cpp +// for the class-based pattern that is appropriate when handlers must +// share mutable state. #include - -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&); - void set_some_data(const std::string &s) {data = s;} - std::string data; -}; - -// Using the render method you are able to catch each type of request you receive -std::shared_ptr hello_world_resource::render(const httpserver::http_request& req) { - // It is possible to store data inside the resource object that can be altered through the requests - std::cout << "Data was: " << data << std::endl; - std::string_view datapar = req.get_arg("data"); - set_some_data(datapar == "" ? "no data passed!!!" : std::string(datapar)); - std::cout << "Now data is:" << data << std::endl; - - // It is possible to send a response initializing an http_string_response that reads the content to send in response from a string. - return std::shared_ptr(new httpserver::string_response("Hello World!!!", 200)); -} - +using namespace httpserver; // NOLINT(build/namespaces) - keep the demo at <=10 LOC int main() { - // It is possible to create a webserver passing a great number of parameters. In this case we are just passing the port and the number of thread running. - httpserver::webserver ws = httpserver::create_webserver(8080).start_method(httpserver::http::http_utils::INTERNAL_SELECT).max_threads(5); - - hello_world_resource hwr; - // This way we are registering the hello_world_resource to answer for the endpoint - // "/hello". The requested method is called (if the request is a GET we call the render_GET - // method. In case that the specific render method is not implemented, the generic "render" - // method is called. - ws.register_resource("/hello", &hwr, true); - - // This way we are putting the created webserver in listen. We pass true in order to have - // a blocking call; if we want the call to be non-blocking we can just pass false to the method. + webserver ws{create_webserver(8080)}; + ws.on_get("/hello", [](const http_request&) { + return http_response::string("Hello, World!"); + }); ws.start(true); - return 0; } diff --git a/examples/iovec_response_example.cpp b/examples/iovec_response_example.cpp index 9822172c..def56c0e 100644 --- a/examples/iovec_response_example.cpp +++ b/examples/iovec_response_example.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2019 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,33 +18,31 @@ USA */ -#include -#include -#include +// iovec_response_example.cpp - build a response body from multiple +// borrowed buffers without copying. The buffers must outlive the +// response; static-lifetime literals satisfy that contract trivially. + #include #include -class iovec_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - // Build a response from multiple separate buffers without copying - std::vector parts; - parts.push_back("{\"header\": \"value\", "); - parts.push_back("\"items\": [1, 2, 3], "); - parts.push_back("\"footer\": \"end\"}"); - - return std::make_shared( - std::move(parts), 200, "application/json"); - } -}; +static const char kPart1[] = "{\"header\": \"value\", "; +static const char kPart2[] = "\"items\": [1, 2, 3], "; +static const char kPart3[] = "\"footer\": \"end\"}"; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/data", [](const httpserver::http_request&) { + std::vector parts = { + { kPart1, sizeof(kPart1) - 1 }, + { kPart2, sizeof(kPart2) - 1 }, + { kPart3, sizeof(kPart3) - 1 }, + }; + return httpserver::http_response::iovec(parts) + .with_header("Content-Type", "application/json"); + }); - iovec_resource ir; - ws.register_resource("/data", &ir); ws.start(true); - return 0; } diff --git a/examples/minimal_deferred.cpp b/examples/minimal_deferred.cpp index d7a61d90..f651abb7 100644 --- a/examples/minimal_deferred.cpp +++ b/examples/minimal_deferred.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,42 +18,34 @@ USA */ -#include +// minimal_deferred.cpp - serve a response body in chunks using a deferred +// callback lambda. The lambda is called repeatedly by libmicrohttpd until it +// returns -1 (signalling end-of-body). The `done` flag ensures the body is +// sent exactly once; the second call returns -1 to close the stream. + +#include +#include #include -#include #include #include -static int counter = 0; - -ssize_t test_callback(std::shared_ptr closure_data, char* buf, size_t max) { - std::ignore = closure_data; - - if (counter == 2) { - return -1; - } else { - memset(buf, 0, max); - snprintf(buf, max, "%s", " test "); - counter++; - return std::string(buf).size(); - } -} - -class deferred_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::shared_ptr >(new httpserver::deferred_response(test_callback, nullptr, "cycle callback response")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::deferred( + [body = std::string("hello from deferred"), + done = false](std::uint64_t, char* buf, + std::size_t max) mutable -> ssize_t { + if (done) return -1; + done = true; + std::size_t n = std::min(body.size(), max); + std::memcpy(buf, body.data(), n); + return static_cast(n); + }); + }); - deferred_resource hwr; - ws.register_resource("/hello", &hwr); ws.start(true); - return 0; } - diff --git a/examples/minimal_file_response.cpp b/examples/minimal_file_response.cpp index 34776993..5a67bc2f 100644 --- a/examples/minimal_file_response.cpp +++ b/examples/minimal_file_response.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,23 +18,19 @@ USA */ -#include +// minimal_file_response.cpp - stream a file from disk as the response +// body using the http_response::file() factory. #include -class file_response_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::file_response("test_content", 200, "text/plain")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - file_response_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::file("test_content") + .with_header("Content-Type", "text/plain"); + }); + ws.start(true); return 0; } diff --git a/examples/minimal_https.cpp b/examples/minimal_https.cpp index 79cd710c..27158021 100644 --- a/examples/minimal_https.cpp +++ b/examples/minimal_https.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,26 +18,30 @@ USA */ -#include +// minimal_https.cpp - enable HTTPS via the use_ssl / https_mem_key / +// https_mem_cert chain on create_webserver. +// +// The https_priorities call sets an explicit GnuTLS cipher-priority string +// that allows TLS 1.2 and TLS 1.3 with safe renegotiation. Without it, +// GnuTLS may fall back to TLS 1.0/1.1 depending on the system configuration. +// Port 8443 is used (convention for HTTPS on non-privileged ports). #include -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080) - .use_ssl() - .https_mem_key("key.pem") - .https_mem_cert("cert.pem"); + httpserver::webserver ws{httpserver::create_webserver(8443) + .use_ssl() + .https_mem_key("key.pem") + .https_mem_cert("cert.pem") + .https_priorities( + "NORMAL:-VERS-TLS-ALL" + ":+VERS-TLS1.2:+VERS-TLS1.3" + ":%SAFE_RENEGOTIATION")}; + + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); + }); - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); ws.start(true); - return 0; } diff --git a/examples/minimal_https_psk.cpp b/examples/minimal_https_psk.cpp index 9bb02ef6..2f2bd83e 100644 --- a/examples/minimal_https_psk.cpp +++ b/examples/minimal_https_psk.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2024 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,46 +18,70 @@ USA */ +// minimal_https_psk.cpp - TLS with pre-shared keys instead of certificates. +// The PSK lookup callback is invoked once per handshake to resolve a +// client-supplied identity into the shared secret. + +#include +#include #include -#include #include #include -// Simple PSK database - in production, use secure storage -std::map psk_database = { - {"client1", "0123456789abcdef0123456789abcdef"}, - {"client2", "fedcba9876543210fedcba9876543210"} -}; +// PSK database loaded from environment variables at startup. +// +// SECURITY NOTE: Never hardcode PSK keys in source code (CWE-321 / CWE-798). +// The values below are illustrative placeholders. In production: +// - Load keys from environment variables, a key file, or a secrets manager. +// - Use at least 128 bits of cryptographically-random key material. +// - Rotate keys regularly. +// +// Example environment setup before running: +// export PSK_CLIENT1=0123456789abcdef0123456789abcdef +// export PSK_CLIENT2=fedcba9876543210fedcba9876543210 +// ./minimal_https_psk +static std::map build_psk_database() { + std::map db; + const char* k1 = std::getenv("PSK_CLIENT1"); + const char* k2 = std::getenv("PSK_CLIENT2"); + if (!k1 || !k2) { + std::cerr << "minimal_https_psk: PSK_CLIENT1 and PSK_CLIENT2 " + "environment variables must be set.\n"; + std::exit(1); + } + db["client1"] = k1; + db["client2"] = k2; + return db; +} -// PSK credential handler callback -// Returns the hex-encoded PSK for the given username, or empty string if not found +static std::map psk_database = build_psk_database(); + +// PSK credential handler callback. Returns the hex-encoded PSK for the +// given username, or an empty string for unknown identities. std::string psk_handler(const std::string& username) { auto it = psk_database.find(username); if (it != psk_database.end()) { return it->second; } - return ""; // Return empty string for unknown users + return ""; } -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr( - new httpserver::string_response("Hello, World (via TLS-PSK)!")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080) - .use_ssl() - .cred_type(httpserver::http::http_utils::PSK) - .psk_cred_handler(psk_handler) - .https_priorities("NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2:+PSK:+DHE-PSK"); - - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + // The priority string locks to TLS 1.2 because GnuTLS external PSK in + // TLS 1.3 requires a different mechanism (session-ticket-based resumption). + // Port 8443 signals HTTPS semantics by convention. + httpserver::webserver ws{ + httpserver::create_webserver(8443) + .use_ssl() + .cred_type(httpserver::http::http_utils::PSK) + .psk_cred_handler(psk_handler) + .https_priorities("NORMAL:-VERS-TLS-ALL:+VERS-TLS1.2:+PSK:+DHE-PSK")}; + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World (via TLS-PSK)!"); + }); + + ws.start(true); return 0; } diff --git a/examples/minimal_ip_ban.cpp b/examples/minimal_ip_ban.cpp index 4b95b5f0..615b2520 100644 --- a/examples/minimal_ip_ban.cpp +++ b/examples/minimal_ip_ban.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,25 +18,23 @@ USA */ -#include +// minimal_ip_ban.cpp - demonstrate the v2.0 IP block API. +// +// TASK-029: the v2.0 public IP-control surface is the pair block_ip / +// unblock_ip, usable under the default ACCEPT policy. The historical +// allow_ip / disallow_ip pair (under REJECT) was dropped. #include -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080).default_policy(httpserver::http::http_utils::REJECT); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - ws.allow_ip("127.0.0.1"); + ws.block_ip("10.0.0.1"); - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); + }); + ws.start(true); return 0; } diff --git a/examples/pipe_response_example.cpp b/examples/pipe_response_example.cpp index 252bcc2a..6c3c480a 100644 --- a/examples/pipe_response_example.cpp +++ b/examples/pipe_response_example.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2019 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,6 +18,11 @@ USA */ +// pipe_response_example.cpp - stream a response from the read end of a +// pipe that a background thread writes into. The lambda owns the +// short-lived pipe + writer; ownership of the read-end fd transfers +// into the response. + #if defined(_WIN32) && !defined(__CYGWIN__) #include #include @@ -26,45 +31,37 @@ #endif #include -#include #include #include -class pipe_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - int pipefd[2]; +int main() { + httpserver::webserver ws{httpserver::create_webserver(8080)}; + + ws.on_get("/stream", [](const httpserver::http_request&) { + int pipefd[2]; #if defined(_WIN32) && !defined(__CYGWIN__) - if (_pipe(pipefd, 4096, _O_BINARY) == -1) { + if (_pipe(pipefd, 4096, _O_BINARY) == -1) { #else - if (pipe(pipefd) == -1) { + if (pipe(pipefd) == -1) { #endif - return std::make_shared("pipe failed", 500); - } + return httpserver::http_response::string("pipe failed").with_status(500); + } - // Spawn a thread to write data into the pipe - std::thread writer([fd = pipefd[1]]() { - const char* messages[] = {"Hello ", "from ", "a pipe!\n"}; - for (const char* msg : messages) { - auto ret = write(fd, msg, strlen(msg)); - (void)ret; - } - close(fd); - }); - writer.detach(); + std::thread writer([fd = pipefd[1]]() { + const char* messages[] = {"Hello ", "from ", "a pipe!\n"}; + for (const char* msg : messages) { + auto ret = write(fd, msg, strlen(msg)); + (void)ret; + } + close(fd); + }); + writer.detach(); - // Return the read end of the pipe as the response - return std::make_shared(pipefd[0], 200, "text/plain"); - } -}; // NOLINT(readability/braces) + return httpserver::http_response::pipe(pipefd[0]) + .with_header("Content-Type", "text/plain"); + }); -int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); - - pipe_resource pr; - ws.register_resource("/stream", &pr); ws.start(true); - return 0; } diff --git a/examples/service.cpp b/examples/service.cpp index 309628bc..8e866ca7 100644 --- a/examples/service.cpp +++ b/examples/service.cpp @@ -28,120 +28,80 @@ bool verbose = false; +static void log_if_verbose(const httpserver::http_request& req, + const httpserver::http_response& res) { + if (verbose) { + std::cout << req; + std::cout << res; + } +} + class service_resource: public httpserver::http_resource { public: - service_resource(); - - ~service_resource(); - - std::shared_ptr render_GET(const httpserver::http_request &req); - std::shared_ptr render_PUT(const httpserver::http_request &req); - std::shared_ptr render_POST(const httpserver::http_request &req); - std::shared_ptr render(const httpserver::http_request &req); - std::shared_ptr render_HEAD(const httpserver::http_request &req); - std::shared_ptr render_OPTIONS(const httpserver::http_request &req); - std::shared_ptr render_CONNECT(const httpserver::http_request &req); - std::shared_ptr render_DELETE(const httpserver::http_request &req); + httpserver::http_response render_get(const httpserver::http_request &req) override; + httpserver::http_response render_put(const httpserver::http_request &req) override; + httpserver::http_response render_post(const httpserver::http_request &req) override; + httpserver::http_response render(const httpserver::http_request &req) override; + httpserver::http_response render_head(const httpserver::http_request &req) override; + httpserver::http_response render_options(const httpserver::http_request &req) override; + httpserver::http_response render_connect(const httpserver::http_request &req) override; + httpserver::http_response render_delete(const httpserver::http_request &req) override; }; -service_resource::service_resource() { } - -service_resource::~service_resource() { } - -std::shared_ptr service_resource::render_GET(const httpserver::http_request &req) { - std::cout << "service_resource::render_GET()" << std::endl; - - if (verbose) std::cout << req; - httpserver::string_response* res = new httpserver::string_response("GET response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_get(const httpserver::http_request &req) { + std::cout << "service_resource::render_get()" << std::endl; + auto res = httpserver::http_response::string("GET response"); + log_if_verbose(req, res); + return res; } - -std::shared_ptr service_resource::render_PUT(const httpserver::http_request &req) { - std::cout << "service_resource::render_PUT()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("PUT response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_put(const httpserver::http_request &req) { + std::cout << "service_resource::render_put()" << std::endl; + auto res = httpserver::http_response::string("PUT response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render_POST(const httpserver::http_request &req) { - std::cout << "service_resource::render_POST()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("POST response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_post(const httpserver::http_request &req) { + std::cout << "service_resource::render_post()" << std::endl; + auto res = httpserver::http_response::string("POST response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render(const httpserver::http_request &req) { +httpserver::http_response service_resource::render(const httpserver::http_request &req) { std::cout << "service_resource::render()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("generic response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); + auto res = httpserver::http_response::string("generic response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render_HEAD(const httpserver::http_request &req) { - std::cout << "service_resource::render_HEAD()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("HEAD response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_head(const httpserver::http_request &req) { + std::cout << "service_resource::render_head()" << std::endl; + auto res = httpserver::http_response::string("HEAD response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render_OPTIONS(const httpserver::http_request &req) { - std::cout << "service_resource::render_OPTIONS()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("OPTIONS response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_options(const httpserver::http_request &req) { + std::cout << "service_resource::render_options()" << std::endl; + auto res = httpserver::http_response::string("OPTIONS response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render_CONNECT(const httpserver::http_request &req) { - std::cout << "service_resource::render_CONNECT()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("CONNECT response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_connect(const httpserver::http_request &req) { + std::cout << "service_resource::render_connect()" << std::endl; + auto res = httpserver::http_response::string("CONNECT response"); + log_if_verbose(req, res); + return res; } -std::shared_ptr service_resource::render_DELETE(const httpserver::http_request &req) { - std::cout << "service_resource::render_DELETE()" << std::endl; - - if (verbose) std::cout << req; - - httpserver::string_response* res = new httpserver::string_response("DELETE response", 200); - - if (verbose) std::cout << *res; - - return std::shared_ptr(res); +httpserver::http_response service_resource::render_delete(const httpserver::http_request &req) { + std::cout << "service_resource::render_delete()" << std::endl; + auto res = httpserver::http_response::string("DELETE response"); + log_if_verbose(req, res); + return res; } void usage() { @@ -198,13 +158,13 @@ int main(int argc, char **argv) { // // Create webserver using the configured options // - httpserver::webserver ws = cw; + httpserver::webserver ws{cw}; // // Create and register service resource available at /service // - service_resource res; - ws.register_resource("/service", &res, true); + auto res = std::make_shared(); + ws.register_prefix("/service", res); // // Start and block the webserver diff --git a/examples/setting_headers.cpp b/examples/setting_headers.cpp index f92b76c1..0aefbc3c 100644 --- a/examples/setting_headers.cpp +++ b/examples/setting_headers.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,25 +18,20 @@ USA */ -#include +// setting_headers.cpp - attach a response header to a lambda handler using +// the fluent with_header() setter, which is overloaded on both lvalue and +// rvalue http_response. #include -class hello_world_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request&) { - std::shared_ptr response = std::shared_ptr(new httpserver::string_response("Hello, World!")); - response->with_header("MyHeader", "MyValue"); - return response; - } -}; - int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); - ws.start(true); + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!") + .with_header("MyHeader", "MyValue"); + }); + ws.start(true); return 0; } diff --git a/examples/shared_state.cpp b/examples/shared_state.cpp new file mode 100644 index 00000000..cdaa6fa3 --- /dev/null +++ b/examples/shared_state.cpp @@ -0,0 +1,63 @@ +/* + This file is part of libhttpserver + Copyright (C) 2011-2025 Sebastiano Merlino + + 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 +*/ + +// shared_state.cpp - the canonical example of when the class form is the +// right shape. +// +// The lambda form (see hello_world.cpp) is the recommended idiom for +// stateless endpoints. When two HTTP methods on the same path share +// mutable state, however, two independent lambdas cannot safely capture +// the same data: each handler is invoked concurrently from libmicrohttpd +// worker threads, and there is no natural object lifetime that both +// lambdas can attach to. +// +// An http_resource subclass solves this cleanly. The resource owns the +// shared data, every render_* override is a member function with access +// to it, and a single std::mutex guards every mutation and read. + +#include +#include +#include + +#include + +class counter : public httpserver::http_resource { + public: + httpserver::http_response render_get(const httpserver::http_request&) override { + std::lock_guard lk(m_); + return httpserver::http_response::string(std::to_string(n_)); + } + + httpserver::http_response render_post(const httpserver::http_request&) override { + std::lock_guard lk(m_); + ++n_; + return httpserver::http_response::string(std::to_string(n_)).with_status(201); + } + + private: + std::mutex m_; + int n_ = 0; +}; + +int main() { + httpserver::webserver ws{httpserver::create_webserver(8080)}; + ws.register_path("/counter", std::make_unique()); + ws.start(true); +} diff --git a/examples/turbo_mode.cpp b/examples/turbo_mode.cpp index 378eca97..fd12de24 100644 --- a/examples/turbo_mode.cpp +++ b/examples/turbo_mode.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011-2019 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,31 +18,24 @@ USA */ -#include +// turbo_mode.cpp - high-performance server configuration: turbo mode, +// suppressed Date header, fastopen queue and a tuned listen backlog. #include -class hello_resource : public httpserver::http_resource { - public: - std::shared_ptr render_GET(const httpserver::http_request&) { - return std::make_shared("Hello, turbo world!"); - } -}; - int main() { - // Create a high-performance server with turbo mode, - // suppressed date headers, and a thread pool. - httpserver::webserver ws = httpserver::create_webserver(8080) - .start_method(httpserver::http::http_utils::INTERNAL_SELECT) - .max_threads(4) - .turbo() - .suppress_date_header() - .tcp_fastopen_queue_size(16) - .listen_backlog(128); - - hello_resource hr; - ws.register_resource("/hello", &hr); - ws.start(true); + httpserver::webserver ws{httpserver::create_webserver(8080) + .start_method(httpserver::http::http_utils::INTERNAL_SELECT) + .max_threads(4) + .turbo() + .suppress_date_header() + .tcp_fastopen_queue_size(16) + .listen_backlog(128)}; + + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, turbo world!"); + }); + ws.start(true); return 0; } diff --git a/examples/url_registration.cpp b/examples/url_registration.cpp index e6eef458..e55f419d 100644 --- a/examples/url_registration.cpp +++ b/examples/url_registration.cpp @@ -1,6 +1,6 @@ /* This file is part of libhttpserver - Copyright (C) 2011, 2012, 2013, 2014, 2015 Sebastiano Merlino + Copyright (C) 2011-2025 Sebastiano Merlino This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public @@ -18,47 +18,63 @@ USA */ +// url_registration.cpp - all four routing flavors: exact path, prefix +// match, plain regex, and parametric segments with optional constraints. +// +// The exact-path and parametric-arg endpoints register a stateless lambda +// directly. The prefix and regex endpoints share a small class because +// they want the same handler logic on multiple paths and on_* does not +// accept a precompiled-regex form for prefix matching. + #include #include #include -class hello_world_resource : public httpserver::http_resource { +class echo_path_resource : public httpserver::http_resource { public: - std::shared_ptr render(const httpserver::http_request&) { - return std::shared_ptr(new httpserver::string_response("Hello, World!")); - } -}; - -class handling_multiple_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request& req) { - return std::shared_ptr(new httpserver::string_response("Your URL: " + std::string(req.get_path()))); - } -}; - -class url_args_resource : public httpserver::http_resource { - public: - std::shared_ptr render(const httpserver::http_request& req) { - return std::shared_ptr(new httpserver::string_response("ARGS: " + std::string(req.get_arg("arg1")) + " and " + std::string(req.get_arg("arg2")))); - } + httpserver::http_response render(const httpserver::http_request& req) override { + return httpserver::http_response::string( + "Your URL: " + std::string(req.get_path())); + } }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - hello_world_resource hwr; - ws.register_resource("/hello", &hwr); + // Exact path, stateless: the lambda form is the v2.0 recommended idiom. + ws.on_get("/hello", [](const httpserver::http_request&) { + return httpserver::http_response::string("Hello, World!"); + }); - handling_multiple_resource hmr; - ws.register_resource("/family", &hmr, true); - ws.register_resource("/with_regex_[0-9]+", &hmr); + // Prefix-match and regex registration still go through the resource + // API. The same instance is registered against two routes. + auto echo = std::make_shared(); + ws.register_prefix("/family", echo); // /family and /family/* + ws.register_path("/with_regex_[0-9]+", echo); - url_args_resource uar; - ws.register_resource("/url/with/{arg1}/and/{arg2}", &uar); - ws.register_resource("/url/with/parametric/args/{arg1|[0-9]+}/and/{arg2|[A-Z]+}", &uar); + // Parametric segments with per-segment regex constraints (preferred form). + // The regex restricts arg1 to digits and arg2 to uppercase ASCII, so the + // router rejects invalid input before the handler is even invoked. + ws.on_get("/url/with/parametric/args/{arg1|[0-9]+}/and/{arg2|[A-Z]+}", + [](const httpserver::http_request& req) { + return httpserver::http_response::string( + "ARGS: " + std::string(req.get_arg("arg1")) + + " and " + std::string(req.get_arg("arg2"))); + }); - ws.start(true); + // Unconstrained parametric segments (accepts any bytes in the URL slot). + // SECURITY NOTE: with no per-segment constraint the handler receives + // arbitrary input. Validate or sanitize before using in HTML, SQL, or + // system calls — raw reflection into an HTML response is reflected XSS + // (CWE-79); passing directly to a shell or DB is injection (CWE-89/78). + ws.on_get("/url/with/{arg1}/and/{arg2}", + [](const httpserver::http_request& req) { + return httpserver::http_response::string( + "ARGS: " + std::string(req.get_arg("arg1")) + + " and " + std::string(req.get_arg("arg2"))); + }); + ws.start(true); return 0; } diff --git a/examples/websocket_echo.cpp b/examples/websocket_echo.cpp index 0e7f20fc..781dc04e 100644 --- a/examples/websocket_echo.cpp +++ b/examples/websocket_echo.cpp @@ -19,6 +19,7 @@ */ #include +#include #include #include @@ -42,10 +43,12 @@ class echo_handler : public httpserver::websocket_handler { }; int main() { - httpserver::webserver ws = httpserver::create_webserver(8080); + httpserver::webserver ws{httpserver::create_webserver(8080)}; - echo_handler handler; - ws.register_ws_resource("/ws", &handler); + // TASK-035: smart-pointer ownership. The webserver takes ownership + // of the echo_handler via unique_ptr; its dtor runs when the + // webserver is destroyed. + ws.register_ws_resource("/ws", std::make_unique()); ws.start(true); return 0; diff --git a/m4/ax_cxx_compile_stdcxx.m4 b/m4/ax_cxx_compile_stdcxx.m4 index 2bb9b25e..fe6ae17e 100644 --- a/m4/ax_cxx_compile_stdcxx.m4 +++ b/m4/ax_cxx_compile_stdcxx.m4 @@ -10,8 +10,8 @@ # # Check for baseline language coverage in the compiler for the specified # version of the C++ standard. If necessary, add switches to CXX and -# CXXCPP to enable support. VERSION may be '11' (for the C++11 standard) -# or '14' (for the C++14 standard). +# CXXCPP to enable support. VERSION may be '11', '14', '17', '20', or +# '23' for the respective C++ standard version. # # The second argument, if specified, indicates whether you insist on an # extended mode (e.g. -std=gnu++11) or a strict conformance mode (e.g. @@ -36,13 +36,15 @@ # Copyright (c) 2016, 2018 Krzesimir Nowak # Copyright (c) 2019 Enji Cooper # Copyright (c) 2020 Jason Merrill +# Copyright (c) 2021, 2024 Jörn Heusipp +# Copyright (c) 2015, 2022, 2023, 2024 Olly Betts # # 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 12 +#serial 25 dnl This macro is based on the code from the AX_CXX_COMPILE_STDCXX_11 macro dnl (serial version number 13). @@ -51,6 +53,8 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl m4_if([$1], [11], [ax_cxx_compile_alternatives="11 0x"], [$1], [14], [ax_cxx_compile_alternatives="14 1y"], [$1], [17], [ax_cxx_compile_alternatives="17 1z"], + [$1], [20], [ax_cxx_compile_alternatives="20"], + [$1], [23], [ax_cxx_compile_alternatives="23"], [m4_fatal([invalid first argument `$1' to AX_CXX_COMPILE_STDCXX])])dnl m4_if([$2], [], [], [$2], [ext], [], @@ -102,9 +106,18 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl dnl HP's aCC needs +std=c++11 according to: dnl http://h21007.www2.hp.com/portal/download/files/unprot/aCxx/PDF_Release_Notes/769149-001.pdf dnl Cray's crayCC needs "-h std=c++11" + dnl MSVC needs -std:c++NN for C++17 and later (default is C++14) for alternative in ${ax_cxx_compile_alternatives}; do - for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}"; do - cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + for switch in -std=c++${alternative} +std=c++${alternative} "-h std=c++${alternative}" MSVC; do + if test x"$switch" = xMSVC; then + dnl AS_TR_SH maps both `:` and `=` to `_` so -std:c++17 would collide + dnl with -std=c++17. We suffix the cache variable name with _MSVC to + dnl avoid this. + switch=-std:c++${alternative} + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_${switch}_MSVC]) + else + cachevar=AS_TR_SH([ax_cv_cxx_compile_cxx$1_$switch]) + fi AC_CACHE_CHECK(whether $CXX supports C++$1 features with $switch, $cachevar, [ac_save_CXX="$CXX" @@ -148,23 +161,44 @@ AC_DEFUN([AX_CXX_COMPILE_STDCXX], [dnl dnl Test body for checking C++11 support m4_define([_AX_CXX_COMPILE_STDCXX_testbody_11], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + [_AX_CXX_COMPILE_STDCXX_testbody_new_in_11] ) - dnl Test body for checking C++14 support m4_define([_AX_CXX_COMPILE_STDCXX_testbody_14], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + [_AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14] ) +dnl Test body for checking C++17 support + m4_define([_AX_CXX_COMPILE_STDCXX_testbody_17], - _AX_CXX_COMPILE_STDCXX_testbody_new_in_11 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 - _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 + [_AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17] +) + +dnl Test body for checking C++20 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_20], + [_AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_20] ) +dnl Test body for checking C++23 support + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_23], + [_AX_CXX_COMPILE_STDCXX_testbody_new_in_11 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_14 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_17 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_20 + _AX_CXX_COMPILE_STDCXX_testbody_new_in_23] +) + + dnl Tests for new features in C++11 m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ @@ -176,7 +210,21 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_11], [[ #error "This is not a C++ compiler" -#elif __cplusplus < 201103L +// MSVC always sets __cplusplus to 199711L in older versions; newer versions +// only set it correctly if /Zc:__cplusplus is specified as well as a +// /std:c++NN switch: +// +// https://devblogs.microsoft.com/cppblog/msvc-now-correctly-reports-__cplusplus/ +// +// The value __cplusplus ought to have is available in _MSVC_LANG since +// Visual Studio 2015 Update 3: +// +// https://learn.microsoft.com/en-us/cpp/preprocessor/predefined-macros +// +// This was also the first MSVC version to support C++14 so we can't use the +// value of either __cplusplus or _MSVC_LANG to quickly rule out MSVC having +// C++11 or C++14 support, but we can check _MSVC_LANG for C++17 and later. +#elif __cplusplus < 201103L && !defined _MSC_VER #error "This is not a C++11 compiler" @@ -467,7 +515,7 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_14], [[ #error "This is not a C++ compiler" -#elif __cplusplus < 201402L +#elif __cplusplus < 201402L && !defined _MSC_VER #error "This is not a C++14 compiler" @@ -591,7 +639,7 @@ m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_17], [[ #error "This is not a C++ compiler" -#elif __cplusplus < 201703L +#elif (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 201703L #error "This is not a C++17 compiler" @@ -957,8 +1005,66 @@ namespace cxx17 } // namespace cxx17 -#endif // __cplusplus < 201703L +#endif // (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 201703L + +]]) + + +dnl Tests for new features in C++20 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_20], [[ + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 202002L + +#error "This is not a C++20 compiler" + +#else + +#include + +namespace cxx20 +{ + +// As C++20 supports feature test macros in the standard, there is no +// immediate need to actually test for feature availability on the +// Autoconf side. + +} // namespace cxx20 + +#endif // (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 202002L ]]) +dnl Tests for new features in C++23 + +m4_define([_AX_CXX_COMPILE_STDCXX_testbody_new_in_23], [[ + +#ifndef __cplusplus + +#error "This is not a C++ compiler" + +#elif (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 202302L + +#error "This is not a C++23 compiler" + +#else + +#include + +namespace cxx23 +{ + +// As C++23 supports feature test macros in the standard, there is no +// immediate need to actually test for feature availability on the +// Autoconf side. + +} // namespace cxx23 + +#endif // (defined _MSVC_LANG ? _MSVC_LANG : __cplusplus) < 202302L + +]]) diff --git a/scripts/check-doxygen.sh b/scripts/check-doxygen.sh new file mode 100755 index 00000000..6d38c95a --- /dev/null +++ b/scripts/check-doxygen.sh @@ -0,0 +1,92 @@ +#!/usr/bin/env bash +# +# check-doxygen.sh — enforce TASK-043 invariant on the doxygen build. +# +# Runs `make doxygen-run` in the active build tree and asserts that the +# output contains zero substantive warnings or errors. Substantive means: +# anything from the doxygen parser about the SOURCE under +# `src/httpserver/` — e.g. an undocumented @param, a mismatched parameter +# name, a stale @copydoc target. +# +# Lines we deliberately filter OUT (environmental, not doc-content issues): +# +# E1. "Tag '' at line N of file '...doxyconfig.in' has become +# obsolete." — older config tags carried over from doxywizard. +# E2. "doxygen no longer ships with the FreeSans font." — packaging. +# E3. "the dot tool could not be found ..." — graphviz absent locally. +# E4. "Failed to rename ... .dot.png to ... .png" — dot post-processing +# failure (typically dot absent or installed late). +# E5. "Problems running dot: exit code=..." — same root cause as E4. +# E6. "Caller graph for '' not generated, too many nodes (N), +# threshold is M." — informational, DOT_GRAPH_MAX_NODES threshold. +# +# Everything else under the keywords `warning:` or `error:` is a real +# doc issue and FAILS the gate. Exits non-zero on the first violation. +# +# Behaviour when doxygen is not installed: SKIP (exit 0). The gate is +# CI-runnable on developer machines without doxygen; CI is expected to +# install it. This mirrors how scripts/check-readme.sh and friends are +# tolerant of missing tools. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" + +# Locate the build tree. Prefer $BUILD_DIR, else REPO_ROOT/build, else +# fall back to the current working directory (assumes invoker is already +# inside the build dir, mirroring `make` behaviour). +BUILD_DIR="${BUILD_DIR:-}" +if [ -z "$BUILD_DIR" ]; then + if [ -d "$REPO_ROOT/build" ] && [ -f "$REPO_ROOT/build/Makefile" ]; then + BUILD_DIR="$REPO_ROOT/build" + elif [ -f "Makefile" ]; then + BUILD_DIR="$(pwd)" + else + echo "check-doxygen: FAIL: no build directory found (set BUILD_DIR)" >&2 + exit 1 + fi +fi + +if ! command -v doxygen >/dev/null 2>&1; then + echo "check-doxygen: SKIP — doxygen not installed (gate is enforced in CI)" + exit 0 +fi + +LOGFILE="$(mktemp -t check-doxygen.XXXXXX)" +trap 'rm -f "$LOGFILE"' EXIT + +echo "check-doxygen: invoking 'make doxygen-run' in $BUILD_DIR" +# Force a fresh doxygen invocation. The make rule's recipe already does +# `rm -rf doxygen-doc` but only fires when an input is newer than the +# tag file. When NO header has changed (e.g. CI rerun) doxygen does not +# re-execute and warnings from a prior good run would not reappear here. +# Removing the tag file forces the rule to fire every time. +rm -f "$BUILD_DIR/doxygen-doc/libhttpserver.tag" +if ! ( cd "$BUILD_DIR" && make doxygen-run ) >"$LOGFILE" 2>&1; then + echo "check-doxygen: FAIL: 'make doxygen-run' exited non-zero" >&2 + sed -n '1,200p' "$LOGFILE" >&2 + exit 1 +fi + +# Strip the noisy-but-harmless environmental lines. The grep is portable +# (BSD/GNU): -E for ERE alternation, single anchored pattern per line. +FILTER='Tag .* has become obsolete\.' +FILTER+='|doxygen no longer ships with the FreeSans font' +FILTER+='|the dot tool could not be found' +FILTER+='|Failed to rename .*\.dot\.png to' +FILTER+='|Problems running dot: exit code=' +FILTER+='|Caller graph for .* not generated, too many nodes' + +REAL_WARNINGS="$(grep -E '(^|: )(warning|error):' "$LOGFILE" | grep -Ev "$FILTER" || true)" + +if [ -n "$REAL_WARNINGS" ]; then + echo "check-doxygen: FAIL: substantive doxygen warnings/errors found:" >&2 + echo "$REAL_WARNINGS" >&2 + echo "" >&2 + echo "(Full log: $LOGFILE — copy aside if needed before this script exits.)" >&2 + # Preserve log on failure for inspection. + trap - EXIT + exit 1 +fi + +echo "check-doxygen: PASS — doxygen-run produced zero substantive warnings" diff --git a/scripts/check-examples.sh b/scripts/check-examples.sh new file mode 100755 index 00000000..0c9f2153 --- /dev/null +++ b/scripts/check-examples.sh @@ -0,0 +1,178 @@ +#!/usr/bin/env bash +# +# check-examples.sh — enforce TASK-040 invariants on examples/. +# +# This script is a static-source check, not a build check. It asserts that: +# +# 1. examples/hello_world.cpp exists, is at most 10 lines (by the rule +# defined below), defines no class deriving from http_resource, and +# registers nothing via raw pointers. +# +# 2. examples/shared_state.cpp exists, defines a class deriving from +# http_resource, holds a std::mutex, overrides both render_get and +# render_post, and registers itself via register_path with +# std::make_unique. +# +# 3. Every program listed in examples/Makefile.am noinst_PROGRAMS has a +# corresponding .cpp source file on disk. This catches renames or +# deletions that would silently break `make examples`. +# +# LOC counting rule (TASK-040 plan D2): +# The LOC count is the number of non-empty, non-comment lines from the +# first non-comment line to EOF, after stripping any leading /* ... */ +# license header. Implemented with awk below. +# +# Exits non-zero on the first violation. + +set -u + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +HELLO="$REPO_ROOT/examples/hello_world.cpp" +SHARED="$REPO_ROOT/examples/shared_state.cpp" +MAKEFILE_AM="$REPO_ROOT/examples/Makefile.am" + +fail() { + echo "check-examples: FAIL: $*" >&2 + exit 1 +} + +count_loc() { + # Strip leading /* ... */ block(s), then count non-blank non-// lines. + awk ' + BEGIN { in_block = 0; seen_first = 0 } + { + line = $0 + # Handle block comments. + if (in_block) { + if (line ~ /\*\//) { in_block = 0; sub(/.*\*\//, "", line) } + else { next } + } + # Strip inline block-open comments that close on the same line. + while (match(line, /\/\*[^*]*\*\//)) { + line = substr(line, 1, RSTART-1) substr(line, RSTART+RLENGTH) + } + if (match(line, /\/\*/)) { + in_block = 1 + line = substr(line, 1, RSTART-1) + } + # Strip line comments. + sub(/\/\/.*/, "", line) + # Trim whitespace. + gsub(/^[ \t\r]+|[ \t\r]+$/, "", line) + if (line == "") next + count++ + } + END { print count + 0 } + ' "$1" +} + +# ---- hello_world.cpp ---------------------------------------------------- + +[ -f "$HELLO" ] || fail "examples/hello_world.cpp does not exist" + +loc=$(count_loc "$HELLO") +if [ "$loc" -gt 10 ]; then + fail "examples/hello_world.cpp is $loc LOC, must be <= 10" +fi +if [ "$loc" -lt 5 ]; then + fail "examples/hello_world.cpp is $loc LOC, suspiciously short (must be >= 5)" +fi + +if grep -Eq 'class[[:space:]]+[A-Za-z_][A-Za-z_0-9]*[[:space:]]*:[[:space:]]*public[[:space:]]+[A-Za-z_:]*http_resource' "$HELLO"; then + fail "examples/hello_world.cpp defines an http_resource subclass; the lambda form is required" +fi + +# No raw-pointer registration like ws.register_path("/x", new Foo()). +if grep -Eq 'register_(path|prefix|resource)[[:space:]]*\([^,]*,[[:space:]]*new[[:space:]]+' "$HELLO"; then + fail "examples/hello_world.cpp uses raw-pointer registration; use lambda or smart-pointer form" +fi + +# ---- shared_state.cpp --------------------------------------------------- + +[ -f "$SHARED" ] || fail "examples/shared_state.cpp does not exist" + +grep -Eq ':[[:space:]]*public[[:space:]]+[A-Za-z_:]*http_resource' "$SHARED" \ + || fail "examples/shared_state.cpp must define a class inheriting from http_resource" + +grep -q 'std::mutex' "$SHARED" \ + || fail "examples/shared_state.cpp must use std::mutex to demonstrate locking" + +grep -Eq '\brender_get\b' "$SHARED" \ + || fail "examples/shared_state.cpp must override render_get" + +grep -Eq '\brender_post\b' "$SHARED" \ + || fail "examples/shared_state.cpp must override render_post" + +grep -Eq 'register_path[[:space:]]*\(.*std::make_unique' "$SHARED" \ + || fail "examples/shared_state.cpp must register via register_path with std::make_unique" + +# ---- Makefile.am coverage --------------------------------------------------- +# Two-directional check: +# (a) Every program listed in noinst_PROGRAMS must have a .cpp source file. +# (b) Every .cpp in examples/ must be listed in noinst_PROGRAMS or be an +# explicitly acknowledged non-program artifact. +# +# KNOWN_ARTIFACTS: .cpp files that are intentionally not in noinst_PROGRAMS. +# client_cert_auth.cpp ships as a documentation artifact; it depends on extra +# GnuTLS APIs not part of the public libhttpserver consumer surface and is +# excluded from the build by design. Mirror the comment in +# scripts/verify-installed-examples.sh lines 96-101. +KNOWN_ARTIFACTS="client_cert_auth" + +[ -f "$MAKEFILE_AM" ] || fail "examples/Makefile.am does not exist" + +# Extract all tokens from noinst_PROGRAMS lines (handles = and +=). +# Strip the variable name and assignment operator, then collect program names. +# Use awk for portability (avoids sed \s and \? which differ between GNU/BSD). +programs="$(awk '/^[[:space:]]*noinst_PROGRAMS[[:space:]]*(=|\+=)/ { + sub(/^[[:space:]]*noinst_PROGRAMS[[:space:]]*(=|\+=)[[:space:]]*/, "") + gsub(/\\$/, "") + print +}' "$MAKEFILE_AM")" + +# (a) Makefile.am → disk: every listed program must have a .cpp file. +missing=0 +for prog in $programs; do + src="$REPO_ROOT/examples/${prog}.cpp" + if [ ! -f "$src" ]; then + echo "check-examples: FAIL: noinst_PROGRAMS lists '$prog' but examples/${prog}.cpp does not exist" >&2 + missing=$((missing + 1)) + fi +done +if [ "$missing" -gt 0 ]; then + fail "$missing program(s) listed in Makefile.am noinst_PROGRAMS have no .cpp source" +fi + +# (b) disk → Makefile.am: every .cpp must be in noinst_PROGRAMS or KNOWN_ARTIFACTS. +unlisted=0 +for src in "$REPO_ROOT"/examples/*.cpp; do + base="$(basename "$src" .cpp)" + # Check if in noinst_PROGRAMS. + found=0 + for prog in $programs; do + if [ "$prog" = "$base" ]; then + found=1 + break + fi + done + if [ "$found" -eq 0 ]; then + # Check if in KNOWN_ARTIFACTS allowlist. + in_artifacts=0 + for artifact in $KNOWN_ARTIFACTS; do + if [ "$artifact" = "$base" ]; then + in_artifacts=1 + break + fi + done + if [ "$in_artifacts" -eq 0 ]; then + echo "check-examples: FAIL: examples/${base}.cpp is on disk but not listed in noinst_PROGRAMS or KNOWN_ARTIFACTS" >&2 + unlisted=$((unlisted + 1)) + fi + fi +done +if [ "$unlisted" -gt 0 ]; then + fail "$unlisted .cpp file(s) in examples/ are not listed in Makefile.am noinst_PROGRAMS — add them or add to KNOWN_ARTIFACTS" +fi + +echo "check-examples: OK (hello_world.cpp = $loc LOC; shared_state.cpp asserted; Makefile.am coverage verified bidirectionally)" +exit 0 diff --git a/scripts/check-parallel-install.sh b/scripts/check-parallel-install.sh new file mode 100755 index 00000000..342e1a44 --- /dev/null +++ b/scripts/check-parallel-install.sh @@ -0,0 +1,211 @@ +#!/usr/bin/env bash +# +# check-parallel-install.sh — TASK-044 parallel-installability verification. +# +# This script proves that libhttpserver v1 and libhttpserver v2.0 can be +# installed side-by-side into the same prefix without their shared-library +# artefacts colliding. The promise is on the SONAME / runtime-library side — +# v1's `libhttpserver.so.0` and v2's `libhttpserver.so.2` (Linux) or +# `libhttpserver.0.dylib` and `libhttpserver.2.0.0.dylib` (Darwin) MUST +# coexist after installing both into the same DESTDIR. +# +# The dev-time artefacts (libhttpserver.la, libhttpserver.a, the .pc file, +# the headers, the bare `libhttpserver.so`/`libhttpserver.dylib` dev symlink) +# DO collide. The last installer wins — this is the standard C++ library +# behaviour and is intentional. We only assert the runtime SONAME duo here. +# +# Strategy: +# 1. Build the current (v2.0) tree from $BUILD_DIR and install into +# $SHARED_STAGE (a fresh DESTDIR). +# 2. Use `git worktree add` (read-only, ephemeral) to materialise a master +# checkout, bootstrap+configure+build it, and install it into the SAME +# $SHARED_STAGE. +# 3. Assert that both SONAMEd library files coexist on disk after step 2. +# +# Inputs (via env, all optional): +# BUILD_DIR — current-tree out-of-tree build directory. +# Default: $REPO_ROOT/build. +# SHARED_STAGE — DESTDIR root for the parallel install. +# Default: $BUILD_DIR/.parallel-stage. +# MASTER_REF — git ref to use as the v1 source. +# Default: master. +# MASTER_WORKTREE — path for the temporary v1 worktree. +# Default: $BUILD_DIR/.parallel-master-worktree. +# +# This script is best-effort and exits 0 with a clear SKIP message if the +# v1 source tree cannot be built in this environment (e.g. glibtoolize +# missing). It is NOT wired into `make check` to keep per-PR CI fast; it +# lives as an opt-in `make check-parallel-install` rule. +# +# Acceptance: +# * On Linux: $STAGE$libdir/libhttpserver.so.0 (or whatever v1 ships) +# coexists with $STAGE$libdir/libhttpserver.so.2.0.0 after step 2. +# * On Darwin: $STAGE$libdir/libhttpserver.0.dylib (or v1 SONAME) +# coexists with $STAGE$libdir/libhttpserver.2.dylib after step 2. +# (libtool's -version-number A:B:C on Mach-O emits only .A.dylib; +# the .A.B.C.dylib intermediate is a Linux-only convention.) +# +# This script is intentionally tolerant: any failure to even produce a v1 +# build is treated as a SKIP, because the user-visible promise (the v2 +# install is well-formed; the on-disk filenames don't clash) is verified +# either way. + +set -uo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +BUILD_DIR="${BUILD_DIR:-$REPO_ROOT/build}" +SHARED_STAGE="${SHARED_STAGE:-$BUILD_DIR/.parallel-stage}" +MASTER_REF="${MASTER_REF:-master}" +MASTER_WORKTREE="${MASTER_WORKTREE:-$BUILD_DIR/.parallel-master-worktree}" +PLATFORM="$(uname -s)" + +skip() { + echo "check-parallel-install: SKIP: $*" >&2 + exit 0 +} + +fail() { + echo "check-parallel-install: FAIL: $*" >&2 + exit 1 +} + +pass() { + echo " PASS: $*" +} + +cleanup() { + # Tear down the ephemeral worktree if we created one. Don't touch + # $SHARED_STAGE — the maintainer may want to inspect it. + if [ -d "$MASTER_WORKTREE" ]; then + # `git worktree remove --force` may exit non-zero on shallow clones; + # ignore errors — the directory cleanup is sufficient for re-run safety. + git -C "$REPO_ROOT" worktree remove --force "$MASTER_WORKTREE" 2>/dev/null || true + rm -rf "$MASTER_WORKTREE" + fi +} +trap cleanup EXIT + +[ -d "$BUILD_DIR" ] || skip "BUILD_DIR=$BUILD_DIR does not exist (run ./configure first)" + +# Resolve libdir from config.status (same trick as check-soversion.sh). +CONFIG_STATUS="$BUILD_DIR/config.status" +[ -x "$CONFIG_STATUS" ] || skip "$CONFIG_STATUS missing (run ./configure first)" +RESOLVED_PREFIX="$("$CONFIG_STATUS" --config 2>/dev/null \ + | tr ' ' '\n' | grep -E "^'?--prefix=" | head -1 | sed "s/^'\?--prefix=//;s/'\$//")" +[ -z "$RESOLVED_PREFIX" ] && RESOLVED_PREFIX="/usr/local" +LIBDIR="$RESOLVED_PREFIX/lib" +STAGE_LIB="$SHARED_STAGE$LIBDIR" + +case "$PLATFORM" in + Linux) + V2_FULL_BASENAME="libhttpserver.so.2.0.0" + # v1 install on disk uses the major from configure.ac's + # MAJOR_VERSION — most commonly .so.0 (legacy 0.x line) or + # .so.1. We don't pin the v1 SONAME here; we just require + # *some* sibling file shaped like libhttpserver.so.. + V1_PATTERN='^libhttpserver\.so\.[01]' + ;; + Darwin) + # libtool with -version-number on Mach-O produces only the + # major-numbered .N.dylib (no .N.M.P.dylib intermediate). + V2_FULL_BASENAME="libhttpserver.2.dylib" + V1_PATTERN='^libhttpserver\.[01]\.dylib' + ;; + *) + fail "unsupported platform '$PLATFORM' (need Linux or Darwin)" + ;; +esac + +echo "=== check-parallel-install: v2 + v1 coexistence on the same DESTDIR ===" +echo " BUILD_DIR : $BUILD_DIR" +echo " SHARED_STAGE : $SHARED_STAGE" +echo " MASTER_REF : $MASTER_REF" +echo " MASTER_WORKTREE : $MASTER_WORKTREE" + +# ---- Phase 1: install v2 into the shared stage -------------------------------- +rm -rf "$SHARED_STAGE" +mkdir -p "$SHARED_STAGE" +echo "Phase 1: installing v2 from $BUILD_DIR" +if ! ( cd "$BUILD_DIR" && make install DESTDIR="$SHARED_STAGE" ) >"$SHARED_STAGE/.v2-install.log" 2>&1; then + echo "---- v2 install log (tail) ----" >&2 + tail -40 "$SHARED_STAGE/.v2-install.log" >&2 + fail "v2 install into $SHARED_STAGE failed" +fi +pass "v2 install succeeded into $SHARED_STAGE" + +[ -f "$STAGE_LIB/$V2_FULL_BASENAME" ] \ + || fail "expected v2 library $V2_FULL_BASENAME after phase 1, got: $(ls "$STAGE_LIB" 2>/dev/null || echo '(libdir missing)')" + +# ---- Phase 2: materialise v1 source via git worktree -------------------------- +echo "Phase 2: building $MASTER_REF in a temporary git worktree" + +if ! git -C "$REPO_ROOT" rev-parse --verify "$MASTER_REF" >/dev/null 2>&1; then + skip "ref '$MASTER_REF' not in this repository — cannot do automated v1 build" +fi + +# Remove a stale worktree from a previous aborted run, if any. +if [ -d "$MASTER_WORKTREE" ]; then + git -C "$REPO_ROOT" worktree remove --force "$MASTER_WORKTREE" 2>/dev/null || true + rm -rf "$MASTER_WORKTREE" +fi + +if ! git -C "$REPO_ROOT" worktree add --detach "$MASTER_WORKTREE" "$MASTER_REF" >"$SHARED_STAGE/.worktree-add.log" 2>&1; then + cat "$SHARED_STAGE/.worktree-add.log" >&2 + skip "git worktree add failed; cannot do automated v1 build" +fi + +# Bootstrap, configure, build, install the v1 source. +echo " bootstrapping $MASTER_REF in $MASTER_WORKTREE" +if ! ( cd "$MASTER_WORKTREE" && ./bootstrap ) >"$SHARED_STAGE/.v1-bootstrap.log" 2>&1; then + echo " (v1 bootstrap failed; this often means glibtoolize/libtoolize is missing)" + tail -20 "$SHARED_STAGE/.v1-bootstrap.log" >&2 + skip "v1 bootstrap failed in $MASTER_WORKTREE (treating as environment limitation)" +fi + +V1_BUILD="$MASTER_WORKTREE/build" +mkdir -p "$V1_BUILD" +echo " configuring $MASTER_REF" +if ! ( cd "$V1_BUILD" && \ + CPPFLAGS="${CPPFLAGS:-} -I/opt/homebrew/include -I/opt/homebrew/opt/gnutls/include" \ + LDFLAGS="${LDFLAGS:-} -L/opt/homebrew/lib -L/opt/homebrew/opt/gnutls/lib" \ + LIBS="${LIBS:--lgnutls}" \ + ../configure --prefix="$RESOLVED_PREFIX" ) >"$SHARED_STAGE/.v1-configure.log" 2>&1; then + tail -20 "$SHARED_STAGE/.v1-configure.log" >&2 + skip "v1 configure failed (treating as environment limitation)" +fi + +echo " building $MASTER_REF" +if ! ( cd "$V1_BUILD" && make -j4 ) >"$SHARED_STAGE/.v1-make.log" 2>&1; then + tail -30 "$SHARED_STAGE/.v1-make.log" >&2 + skip "v1 make failed (treating as environment limitation; e.g. v1 sources may not build on this toolchain)" +fi + +echo " installing $MASTER_REF into $SHARED_STAGE" +if ! ( cd "$V1_BUILD" && make install DESTDIR="$SHARED_STAGE" ) >"$SHARED_STAGE/.v1-install.log" 2>&1; then + tail -30 "$SHARED_STAGE/.v1-install.log" >&2 + fail "v1 install into $SHARED_STAGE failed AFTER successful v1 build" +fi +pass "v1 ($MASTER_REF) install succeeded into shared stage" + +# ---- Phase 3: assert coexistence --------------------------------------------- +[ -f "$STAGE_LIB/$V2_FULL_BASENAME" ] \ + || fail "v2 library $V2_FULL_BASENAME disappeared from $STAGE_LIB after v1 install" + +# Look for any v1-style sibling that is NOT the v2 file we just confirmed. +v1_hits="$(ls "$STAGE_LIB" 2>/dev/null | grep -E "$V1_PATTERN" | grep -v "^$V2_FULL_BASENAME\$" || true)" +if [ -z "$v1_hits" ]; then + fail "no v1-style library file (matching $V1_PATTERN, excluding $V2_FULL_BASENAME) found in $STAGE_LIB; install contents: $(ls "$STAGE_LIB" 2>/dev/null)" +fi + +echo " v1 artefacts coexisting with v2:" +for f in $v1_hits; do + echo " $f" +done +pass "v1 and v2 SONAMEd libraries coexist in $STAGE_LIB" + +echo " Note: dev-time files (libhttpserver.la, libhttpserver.a, libhttpserver.pc," +echo " headers, the bare libhttpserver.so/.dylib dev symlink) are LAST-WRITER-WINS" +echo " by design — see RELEASE_NOTES.md 'SOVERSION & packaging'." + +echo " ALL PASS: parallel-installability verified" +exit 0 diff --git a/scripts/check-readme.sh b/scripts/check-readme.sh new file mode 100755 index 00000000..7003955a --- /dev/null +++ b/scripts/check-readme.sh @@ -0,0 +1,276 @@ +#!/usr/bin/env bash +# +# check-readme.sh — enforce TASK-041 invariants on README.md. +# +# This is a static-source check, mirroring scripts/check-examples.sh. It asserts +# that the v2.0 README: +# +# A1. Quotes examples/hello_world.cpp byte-for-byte in its first ```cpp fence. +# A2. Contains no v1-era tokens (sweet_kill, *_response subclasses, no_* setters, +# render_GET-style virtuals, ban_ip/allow_ip family, raw-pointer registration). +# A3. Mentions every load-bearing v2 surface (on_get, register_path, http_response::*, +# block_ip/unblock_ip, stop_and_wait, features(), feature_unavailable, ...). +# A4. The Threading and Error-propagation sections cite their architecture sources +# (DR-008/§5.1 and DR-009/§5.2) and mention the load-bearing details +# (stop() deadlock per DR-008; internal_error_handler + feature_unavailable). +# A5. The eleven structural sections from TASK-041 exist (case-insensitive H2 match). +# A6. Cross-links to examples/ and RELEASE_NOTES.md exist. +# +# Plus markdown sanity: +# - balanced ``` fences; +# - exactly one top-level `# ` H1; +# - no tab characters inside fenced code blocks. +# +# Exits non-zero on the first violation. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +README="$REPO_ROOT/README.md" +HELLO="$REPO_ROOT/examples/hello_world.cpp" + +fail() { + echo "check-readme: FAIL: $*" >&2 + exit 1 +} + +[ -f "$README" ] || fail "README.md does not exist at $README" +[ -f "$HELLO" ] || fail "examples/hello_world.cpp does not exist at $HELLO" + +# ---- A1: hello-world snippet matches examples/hello_world.cpp ---------------- +# Extract the first fenced ```cpp ... ``` block from README.md. + +extract_first_cpp_block() { + awk ' + BEGIN { in_block = 0; printed = 0 } + { + if (printed) next + if (!in_block && $0 ~ /^```cpp[[:space:]]*$/) { in_block = 1; next } + if (in_block && $0 ~ /^```[[:space:]]*$/) { in_block = 0; printed = 1; next } + if (in_block) print + } + ' "$1" +} + +tmp_block="$(mktemp)" +tmp_hello="$(mktemp)" +trap 'rm -f "$tmp_block" "$tmp_hello"' EXIT +extract_first_cpp_block "$README" | tr -d '\r' > "$tmp_block" +# Strip CRLFs from the cpp file too: msys2/MINGW Windows runners check out +# README.md with CRLF (git autocrlf=true) and the .cpp with LF, which makes +# the byte-for-byte diff fail even though the visible content is identical. +tr -d '\r' < "$HELLO" > "$tmp_hello" + +if [ ! -s "$tmp_block" ]; then + fail "A1: README.md contains no \`\`\`cpp fenced block (need first block to match $HELLO byte-for-byte)" +fi + +if ! diff -u "$tmp_hello" "$tmp_block" >/dev/null 2>&1; then + echo "check-readme: FAIL: A1: first \`\`\`cpp block in README.md does not match examples/hello_world.cpp byte-for-byte:" >&2 + diff -u "$tmp_hello" "$tmp_block" >&2 || true + exit 1 +fi + +# ---- A2: no v1-era tokens ---------------------------------------------------- +# Use a single grep -nE pass over README.md. Any hit fails. + +V1_TOKENS='\bsweet_kill\b|\bban_ip\b|\bunban_ip\b|\ballow_ip\b|\bdisallow_ip\b' +V1_TOKENS="$V1_TOKENS"'|\bno_(basic_auth|digest_auth|ssl|debug|pedantic|deferred|regex_checking|ban_system|post_process|single_resource|ipv6|dual_stack)\b' +V1_TOKENS="$V1_TOKENS"'|\brender_(GET|POST|PUT|DELETE|HEAD|OPTIONS|PATCH|CONNECT|TRACE)\b' +V1_TOKENS="$V1_TOKENS"'|\bstring_response\b|\bfile_response\b|\biovec_response\b|\bpipe_response\b' +V1_TOKENS="$V1_TOKENS"'|\bdeferred_response\b|\bempty_response\b' +V1_TOKENS="$V1_TOKENS"'|\bbasic_auth_fail_response\b|\bdigest_auth_fail_response\b' +V1_TOKENS="$V1_TOKENS"'|new[[:space:]]+[A-Za-z_]*_response[[:space:]]*\(' +V1_TOKENS="$V1_TOKENS"'|register_resource[[:space:]]*\([^,]*,[[:space:]]*new[[:space:]]+' +V1_TOKENS="$V1_TOKENS"'|\bnot_found_resource\b|\bmethod_not_allowed_resource\b|\binternal_error_resource\b' + +if hits="$(grep -nE "$V1_TOKENS" "$README")"; then + echo "check-readme: FAIL: A2: README.md contains v1-era tokens:" >&2 + echo "$hits" >&2 + exit 1 +fi + +# ---- A3: required v2 tokens appear at least once ----------------------------- +# Each pattern must match. Collect misses and report them all in one go. + +REQUIRED_V2_TOKENS=( + '\bon_get\b' + '\bon_post\b' + '\broute[[:space:]]*\(' + '\bregister_path\b' + '\bregister_prefix\b' + '\bregister_ws_resource\b' + '\bhttp_response::string\b' + '\bhttp_response::file\b' + '\bhttp_response::iovec\b' + '\bhttp_response::pipe\b' + '\bhttp_response::empty\b' + '\bhttp_response::deferred\b' + '\bhttp_response::unauthorized\b' + '\bwith_header\b' + '\bwith_status\b' + '\bblock_ip\b' + '\bunblock_ip\b' + '\bstop_and_wait\b' + '\bfeatures\(\)' + '\bfeature_unavailable\b' + '\binternal_error_handler\b' + '\bnot_found_handler\b' + '\bmethod_not_allowed_handler\b' + '\bhttp_method\b' + '\bmethod_set\b' + '\biovec_entry\b' +) + +missing=() +for tok in "${REQUIRED_V2_TOKENS[@]}"; do + if ! grep -qE "$tok" "$README"; then + missing+=("$tok") + fi +done +if [ "${#missing[@]}" -gt 0 ]; then + echo "check-readme: FAIL: A3: README.md is missing required v2 tokens:" >&2 + for tok in "${missing[@]}"; do echo " $tok" >&2; done + exit 1 +fi + +# ---- A4: threading & error sections cite architecture + key terms ----------- +# Find each section body (between its H2 heading and the next H2/EOF) and grep. + +extract_section_body() { + # $1 = file, $2 = regex matching the H2 heading line + awk -v re="$2" ' + BEGIN { in_section = 0 } + /^##[ \t]+/ { + if (in_section) { exit } + if (tolower($0) ~ tolower(re)) { in_section = 1; next } + } + in_section { print } + ' "$1" +} + +thread_body="$(extract_section_body "$README" '^##[ \t]+.*threading')" +err_body="$(extract_section_body "$README" '^##[ \t]+.*error[ \t-]+propag')" + +if [ -z "$thread_body" ]; then + fail "A4: README.md is missing a '## Threading...' section" +fi +if ! echo "$thread_body" | grep -qE '(DR-008|§[[:space:]]*5\.1|specs/architecture/05-cross-cutting\.md|specs/architecture/11-decisions/DR-008)'; then + fail "A4: Threading section must cite DR-008 or §5.1" +fi +if ! echo "$thread_body" | grep -qE '\bstop\(\)'; then + fail "A4: Threading section must mention stop() (the stop-from-handler deadlock, per DR-008)" +fi +if ! echo "$thread_body" | grep -qiE 'deadlock'; then + fail "A4: Threading section must mention the deadlock contract" +fi + +if [ -z "$err_body" ]; then + fail "A4: README.md is missing a '## Error propagation' section" +fi +if ! echo "$err_body" | grep -qE '(DR-009|§[[:space:]]*5\.2|specs/architecture/05-cross-cutting\.md|specs/architecture/11-decisions/DR-009)'; then + fail "A4: Error-propagation section must cite DR-009 or §5.2" +fi +if ! echo "$err_body" | grep -qE '\binternal_error_handler\b'; then + fail "A4: Error-propagation section must mention internal_error_handler" +fi +if ! echo "$err_body" | grep -qE '\bfeature_unavailable\b'; then + fail "A4: Error-propagation section must mention feature_unavailable" +fi + +# ---- A5: required structural sections exist --------------------------------- + +REQUIRED_SECTIONS=( + 'build.*install' + 'hello.*world' + 'class-form' + '^##[ \t]+request' + '^##[ \t]+response' + '^##[ \t]+routing' + 'threading' + 'error[ \t-]+propag' + 'feature[ \t-]+avail' + 'websocket' + 'migrat' +) + +missing_sections=() +for sec in "${REQUIRED_SECTIONS[@]}"; do + # Patterns starting with ^ are absolute; others match anywhere on H2 lines. + if [[ "$sec" == ^* ]]; then + if ! grep -qiE "$sec" "$README"; then + missing_sections+=("$sec") + fi + else + if ! grep -qiE "^##[ \t]+.*${sec}" "$README"; then + missing_sections+=("$sec") + fi + fi +done +if [ "${#missing_sections[@]}" -gt 0 ]; then + echo "check-readme: FAIL: A5: README.md is missing required ## sections:" >&2 + for sec in "${missing_sections[@]}"; do echo " pattern: $sec" >&2; done + exit 1 +fi + +# ---- A6: cross-links to examples/ and RELEASE_NOTES.md ---------------------- + +if ! grep -qE '\]\(examples/' "$README"; then + fail "A6: README.md must contain at least one Markdown link to examples/ (e.g., [examples/](examples/) or [foo](examples/foo.cpp))" +fi +if ! grep -qE '\]\(RELEASE_NOTES\.md' "$README"; then + fail "A6: README.md must contain at least one Markdown link to RELEASE_NOTES.md" +fi + +# ---- A6b: relative Markdown links resolve to existing files ----------------- +# Extract Markdown link targets of the form ]() where the target +# looks like a file path (no spaces, no C++ keywords). Skip http/https URLs +# and in-page anchors (#...). Verify each relative target exists on disk. +broken_links=() +while IFS= read -r target; do + case "$target" in + http://*|https://*) continue ;; # absolute URLs — not checked + \#*) continue ;; # in-page anchors — not checked + RELEASE_NOTES.md) continue ;; # created by TASK-042, not yet present + esac + if [ ! -e "$REPO_ROOT/$target" ]; then + broken_links+=("$target") + fi +done < <(grep -oE '\]\([^) ]+\)' "$README" | sed 's/^](//;s/)$//') + +if [ "${#broken_links[@]}" -gt 0 ]; then + echo "check-readme: FAIL: A6b: README.md contains relative links to non-existent files:" >&2 + for lnk in "${broken_links[@]}"; do echo " $lnk" >&2; done + exit 1 +fi + +# ---- Markdown sanity -------------------------------------------------------- +# (S1) Balanced ``` fences (count of ``` lines must be even). +fence_count="$(grep -cE '^```' "$README" || true)" +if [ $((fence_count % 2)) -ne 0 ]; then + fail "S1: README.md has an odd number of \`\`\` fence lines ($fence_count); fences are unbalanced" +fi + +# (S2) Exactly one top-level `# ` H1 line. +h1_count="$(grep -cE '^#[[:space:]]' "$README" || true)" +if [ "$h1_count" -ne 1 ]; then + fail "S2: README.md must have exactly one H1 (\`# \`) heading, found $h1_count" +fi + +# (S3) No literal tab characters inside fenced code blocks. +awk ' + BEGIN { in_block = 0; bad = 0 } + /^```/ { in_block = !in_block; next } + in_block && /\t/ { print NR": "$0; bad = 1 } + END { exit bad } +' "$README" >&2 || fail "S3: fenced code blocks in README.md contain tab characters (must use spaces)" + +# ---- Optional: markdownlint advisory ---------------------------------------- +if command -v markdownlint >/dev/null 2>&1; then + if ! markdownlint -q "$README" 2>/dev/null; then + echo "check-readme: NOTE: markdownlint reported issues (advisory only, not gating)" >&2 + fi +fi + +echo "check-readme: OK (A1 byte-for-byte snippet; A2 no v1 tokens; A3 ${#REQUIRED_V2_TOKENS[@]} v2 tokens; A4 threading+error citations; A5 ${#REQUIRED_SECTIONS[@]} sections; A6 cross-links; fences balanced)" +exit 0 diff --git a/scripts/check-release-notes.sh b/scripts/check-release-notes.sh new file mode 100755 index 00000000..8cf60750 --- /dev/null +++ b/scripts/check-release-notes.sh @@ -0,0 +1,299 @@ +#!/usr/bin/env bash +# +# check-release-notes.sh — enforce TASK-042 invariants on RELEASE_NOTES.md. +# +# Like scripts/check-readme.sh, this is a static-source check. It asserts that +# RELEASE_NOTES.md is a complete v1→v2.0 porting summary: +# +# A1. RELEASE_NOTES.md exists at REPO_ROOT. +# A2. Required v1-era tokens appear at least once (this is the inverse of +# check-readme.sh A2 — the rename/removal source list MUST be present +# so v1 users can grep for any old name). +# A3. Required v2-era tokens appear at least once (reuses the +# REQUIRED_V2_TOKENS list from check-readme.sh so the two checks agree). +# A4. Required H2 sections are present: TL;DR, What's gone, What's new, +# What's renamed, What changed semantically, Build prerequisites, +# SOVERSION (and packaging). +# A5. Rename-completeness: each high-value (v1 → v2) pair must appear on +# the SAME LINE (typically a Markdown table row). This is the +# load-bearing acceptance check — "a v1 user can grep for any v1 +# method name and find what replaced it." +# A6. Threading & error sub-sections cite the architecture sources +# (DR-008 / §5.1 and DR-009 / §5.2), mirroring check-readme.sh's A4. +# A7. An explicit "not a compatibility commitment" disclaimer is present +# (case-insensitive). +# +# Plus markdown sanity (S1–S3): +# S1. Balanced ``` fences (count is even). +# S2. Exactly one top-level `# ` H1 line. +# S3. No tab characters inside fenced code blocks. +# +# This script assumes LF-only line endings. Repo's .gitattributes / +# .editorconfig should enforce this; if RELEASE_NOTES.md is ever saved with +# CRLF, the A1/A5 string matches and table-row extractor will silently see +# a trailing \r on every line, which will surface as confusing pair-not-found +# failures rather than a clear "CRLF detected" error. +# +# Exits non-zero on the first violation. + +set -euo pipefail + +REPO_ROOT="$(cd "$(dirname "$0")/.." && pwd)" +NOTES="$REPO_ROOT/RELEASE_NOTES.md" + +fail() { + echo "check-release-notes: FAIL: $*" >&2 + exit 1 +} + +# Helper: check that every token in the given array appears at least once in +# the target file. Usage: check_tokens_present