cmake_minimum_required(VERSION 3.20)
project(tlsfp VERSION 4.0.0 LANGUAGES CXX C)

set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
if(NOT CMAKE_BUILD_TYPE)
  set(CMAKE_BUILD_TYPE Release)
endif()

find_package(OpenSSL REQUIRED)
find_package(nlohmann_json QUIET)
find_package(Threads REQUIRED)

# HTTP/3 spike probe (tools/h3probe.cpp). Independent of the H1/H2 stack: it
# links ngtcp2 + nghttp3 + ngtcp2_crypto_ossl directly and touches no libtlsfp
# code, so TLS/JA4/Akamai fingerprints are unaffected. Optional target; the
# library build never depends on it.
find_path(NGTCP2_INCLUDE_DIR ngtcp2/ngtcp2.h)
find_library(NGTCP2_LIBRARY ngtcp2)
find_path(NGHTTP3_INCLUDE_DIR nghttp3/nghttp3.h)
find_library(NGHTTP3_LIBRARY nghttp3)
find_library(NGTCP2_CRYPTO_OSSL_LIBRARY ngtcp2_crypto_ossl)
if(NGTCP2_INCLUDE_DIR AND NGTCP2_LIBRARY AND NGHTTP3_INCLUDE_DIR AND
   NGHTTP3_LIBRARY AND NGTCP2_CRYPTO_OSSL_LIBRARY)
  set(TLSFP_HAVE_QUIC_LIBS ON)
  message(STATUS "HTTP/3 probe: ngtcp2 + nghttp3 found")
else()
  set(TLSFP_HAVE_QUIC_LIBS OFF)
  message(STATUS "HTTP/3 probe: ngtcp2/nghttp3 not found, h3probe disabled")
endif()
option(TLSFP_BUILD_H3 "Build h3probe (HTTP/3 spike client)" ${TLSFP_HAVE_QUIC_LIBS})

find_path(NGHTTP2_INCLUDE_DIR nghttp2/nghttp2.h)
find_library(NGHTTP2_LIBRARY nghttp2)
if(NOT NGHTTP2_INCLUDE_DIR OR NOT NGHTTP2_LIBRARY)
  message(FATAL_ERROR "nghttp2 headers/library not found")
endif()

# RFC 8879 certificate decompression. Brotli is what Chrome-family servers
# pick (algorithm 0002); zlib and zstd are supported when the libraries are
# present. A build without one simply fails closed on that algorithm.
find_path(BROTLI_INCLUDE_DIR brotli/decode.h)
find_library(BROTLI_DEC_LIBRARY brotlidec)
find_library(BROTLI_COMMON_LIBRARY brotlicommon)
if(NOT BROTLI_INCLUDE_DIR OR NOT BROTLI_DEC_LIBRARY)
  message(FATAL_ERROR "brotli decoder not found (needed for TLS 1.3 CompressedCertificate)")
endif()
find_package(ZLIB QUIET)
# IKY8QL: zstd is optional. It is used for `content-encoding: zstd` bodies and
# advertised in `Accept-Encoding` only when this build can actually decode it,
# so a machine without libzstd still compiles and never asks a server for a
# body it cannot read. Turning it off explicitly models that build.
option(TLSFP_WITH_ZSTD "Enable zstd decoding when libzstd is available" ON)
if(TLSFP_WITH_ZSTD)
  find_path(ZSTD_INCLUDE_DIR zstd.h)
  find_library(ZSTD_LIBRARY zstd)
else()
  unset(ZSTD_INCLUDE_DIR CACHE)
  unset(ZSTD_LIBRARY CACHE)
endif()

# Shared library carrying the stable C ABI (libtlsfp.so, SOVERSION). The static
# archive stays available for embedders. BUILD_SHARED_LIBS, when set on the
# command line, controls the default.
if(DEFINED BUILD_SHARED_LIBS)
  set(_tlsfp_shared_default ${BUILD_SHARED_LIBS})
else()
  set(_tlsfp_shared_default ON)
endif()
option(TLSFP_BUILD_SHARED "Build libtlsfp.so (stable C ABI)" ${_tlsfp_shared_default})

# Opt-in TCP TLS 1.2 BoringSSL backend (iteration 44). Declared before the
# source list because the fallback shim is part of libtlsfp only in that build.
option(TLSFP_BUILD_TLS12_BORINGSSL "Build the BoringSSL TCP TLS 1.2 probe" OFF)

# Opt-in TLS 1.1/1.0 legacy transport (iteration 45). Reuses the system
# OpenSSL already linked: no new dependency and nothing vendored. Off by
# default, so the default build neither compiles the code nor accepts
# --legacy-tls.
option(TLSFP_BUILD_LEGACY_TLS "Build the TLS 1.1/1.0 legacy opt-in transport" OFF)

set(TLSFP_SOURCES
  src/profile.cpp
  src/clienthello.cpp
  src/ja4.cpp
  src/tls_client.cpp
  src/net.cpp
  src/certverify.cpp
  src/cert_decompress.cpp
  src/h2.cpp
  src/h2_parse.cpp
  src/http1_parse.cpp
  src/tls_parse.cpp
  src/pool.cpp
  src/async.cpp
  src/multi_client.cpp
  src/reuse_client.cpp
  src/decode.cpp
  src/cookie.cpp
  src/http_client.cpp
  src/ladder.cpp
  src/tls12_state.cpp
  src/session.cpp
  src/multipart.cpp
  src/import.cpp
  src/c_api.cpp
  src/ws_parse.cpp
  src/ws_deflate.cpp
  src/ws_h2.cpp
  src/websocket.cpp
)

# The TLS 1.2 fallback shim is compiled into libtlsfp only when the opt-in
# BoringSSL backend is part of the build; it dlopens the backend library, so it
# never links BoringSSL symbols itself.
if(TLSFP_BUILD_TLS12_BORINGSSL)
  list(APPEND TLSFP_SOURCES src/tls12_stream.cpp)
endif()

# Legacy TLS 1.1/1.0 client: plain OpenSSL API use, no extra link. It is only
# reachable from `tlsfp get --legacy-tls`, and only after TLS 1.3/1.2 failed.
if(TLSFP_BUILD_LEGACY_TLS)
  list(APPEND TLSFP_SOURCES src/legacy_tls.cpp)
endif()

# Applies the common dependencies/definitions to a library target.
function(tlsfp_configure_library target)
  target_include_directories(${target} PUBLIC ${CMAKE_SOURCE_DIR}/include)
  target_include_directories(${target} PUBLIC ${NGHTTP2_INCLUDE_DIR})
  target_link_libraries(${target} PUBLIC OpenSSL::Crypto Threads::Threads ${NGHTTP2_LIBRARY})
  target_compile_definitions(${target} PRIVATE TLSFP_HAVE_BROTLI)
  target_link_libraries(${target} PRIVATE ${BROTLI_DEC_LIBRARY} ${BROTLI_COMMON_LIBRARY})
  target_include_directories(${target} PRIVATE ${BROTLI_INCLUDE_DIR})
  if(ZLIB_FOUND)
    target_compile_definitions(${target} PRIVATE TLSFP_HAVE_ZLIB)
    target_link_libraries(${target} PRIVATE ZLIB::ZLIB)
  endif()
  if(TLSFP_WITH_ZSTD AND ZSTD_INCLUDE_DIR AND ZSTD_LIBRARY)
    target_compile_definitions(${target} PRIVATE TLSFP_HAVE_ZSTD)
    target_link_libraries(${target} PRIVATE ${ZSTD_LIBRARY})
    target_include_directories(${target} PRIVATE ${ZSTD_INCLUDE_DIR})
  endif()
  if(nlohmann_json_FOUND)
    target_link_libraries(${target} PUBLIC nlohmann_json::nlohmann_json)
  endif()
  target_compile_options(${target} PRIVATE -Wall -Wextra -Wno-unused-parameter)
endfunction()

option(TLSFP_FUZZ "Build libFuzzer harnesses (Clang, sanitizers; off by default)" OFF)
if(TLSFP_FUZZ)
  if(NOT CMAKE_CXX_COMPILER_ID MATCHES "Clang")
    message(FATAL_ERROR "TLSFP_FUZZ requires Clang (libFuzzer + sanitizers)")
  endif()
  # Instrument the whole library so coverage and ASan/UBSan see the parsers.
  add_compile_options(-fsanitize=address,undefined,fuzzer-no-link
                      -fno-omit-frame-pointer -g -O1)
  add_link_options(-fsanitize=address,undefined)
endif()

# Async/epoll event-sequence driver (iteration 27). Opt-in: it is a stress
# harness, never a ctest case, and tests/async_stress.py drives it. Sanitizer
# builds pass their flags through CMAKE_CXX_FLAGS (see docs/ASYNC-FUZZ.md).
option(TLSFP_ASYNC_FUZZ "Build the async event-sequence stress driver" OFF)

add_library(tlsfp_core STATIC ${TLSFP_SOURCES})
tlsfp_configure_library(tlsfp_core)
if(TLSFP_BUILD_TLS12_BORINGSSL)
  target_compile_definitions(tlsfp_core PRIVATE TLSFP_HAVE_TLS12_FALLBACK=1)
endif()
if(TLSFP_BUILD_LEGACY_TLS)
  target_compile_definitions(tlsfp_core PRIVATE TLSFP_HAVE_LEGACY_TLS=1)
  # The legacy client is the only code in the tree that uses libssl (the
  # default stack implements TLS 1.3 on libcrypto directly). Same OpenSSL
  # install, already a required dependency: no new package.
  target_link_libraries(tlsfp_core PRIVATE OpenSSL::SSL)
endif()

if(TLSFP_BUILD_SHARED)
  add_library(tlsfp_shared SHARED ${TLSFP_SOURCES})
  tlsfp_configure_library(tlsfp_shared)
  set_target_properties(tlsfp_shared PROPERTIES
    OUTPUT_NAME tlsfp
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR}
    C_VISIBILITY_PRESET hidden
    CXX_VISIBILITY_PRESET hidden
    VISIBILITY_INLINES_HIDDEN ON)
  target_compile_definitions(tlsfp_shared PRIVATE TLSFP_BUILDING_SHARED)
  if(TLSFP_BUILD_TLS12_BORINGSSL)
    target_compile_definitions(tlsfp_shared PRIVATE TLSFP_HAVE_TLS12_FALLBACK=1)
  endif()
  if(TLSFP_BUILD_LEGACY_TLS)
    target_compile_definitions(tlsfp_shared PRIVATE TLSFP_HAVE_LEGACY_TLS=1)
    target_link_libraries(tlsfp_shared PRIVATE OpenSSL::SSL)
  endif()
endif()

add_executable(tlsfp-ch tools/tlsfp-ch.cpp)
target_link_libraries(tlsfp-ch PRIVATE tlsfp_core)

add_executable(tlsfp tools/tlsfp.cpp)

add_executable(tlsfp-bench-cli tools/tlsfp-bench-cli.cpp)
target_link_libraries(tlsfp-bench-cli PRIVATE tlsfp_core)

# IKX691: multi-origin batch driver. A diagnostics tool over the public C++
# request path (one lane per worker, shared TLS1.2/ladder host memory), not a
# library API (IKX690 owns the public shape) and not a ctest case.
add_executable(tlsfp-multi tools/tlsfp-multi.cpp)
target_link_libraries(tlsfp-multi PRIVATE tlsfp_core)
target_compile_options(tlsfp-multi PRIVATE -Wall -Wextra -Wno-unused-parameter)

# IKX690: same URL list, but driven by the library's multi-origin reactor
# (tlsfp::MultiAsyncClient) instead of N lane threads. This binary is the
# reference driver for the A/B and for the public API's own smoke test.
add_executable(tlsfp-multi-async tools/tlsfp-multi-async.cpp)
target_link_libraries(tlsfp-multi-async PRIVATE tlsfp_core)
target_compile_options(tlsfp-multi-async PRIVATE -Wall -Wextra -Wno-unused-parameter)
target_link_libraries(tlsfp PRIVATE tlsfp_core)
if(TLSFP_BUILD_LEGACY_TLS)
  target_compile_definitions(tlsfp PRIVATE TLSFP_HAVE_LEGACY_TLS=1)
endif()

# Reverse-engineering toolkit: fingerprint inspection and profile import.
if(TLSFP_BUILD_H3)
  if(NOT TLSFP_HAVE_QUIC_LIBS)
    message(FATAL_ERROR "TLSFP_BUILD_H3=ON but ngtcp2/nghttp3 were not found")
  endif()
  # One H3 implementation (src/h3_client.cpp) shared by h3probe and
  # `tlsfp get --http3`. Kept in its own static library so libtlsfp and its
  # H1/H2 consumers never take a QUIC dependency.
  add_library(tlsfp_h3 STATIC src/h3_client.cpp src/socks5_udp.cpp)
  target_include_directories(tlsfp_h3 PUBLIC ${CMAKE_SOURCE_DIR}/include
    PRIVATE ${NGTCP2_INCLUDE_DIR} ${NGHTTP3_INCLUDE_DIR})
  target_link_libraries(tlsfp_h3 PUBLIC OpenSSL::SSL OpenSSL::Crypto Threads::Threads
    ${NGTCP2_CRYPTO_OSSL_LIBRARY} ${NGHTTP3_LIBRARY} ${NGTCP2_LIBRARY})
  if(nlohmann_json_FOUND)
    target_link_libraries(tlsfp_h3 PRIVATE nlohmann_json::nlohmann_json)
  endif()
  target_compile_options(tlsfp_h3 PRIVATE -Wall -Wextra -Wno-unused-parameter)

  add_executable(h3probe tools/h3probe.cpp)
  target_include_directories(h3probe PRIVATE ${NGTCP2_INCLUDE_DIR})
  target_link_libraries(h3probe PRIVATE tlsfp_h3)
  target_compile_options(h3probe PRIVATE -Wall -Wextra -Wno-unused-parameter)

  # tlsfp get --http3: same binary, H3 path enabled at compile time.
  target_link_libraries(tlsfp PRIVATE tlsfp_h3)
  target_compile_definitions(tlsfp PRIVATE TLSFP_HAVE_H3=1)
endif()

# ── HTTP/3 BoringSSL spike (iteration 28, opt-in, never default) ──────────
# h3probe-boring needs a patched BoringSSL + ngtcp2 BoringSSL backend built by
# scripts/bootstrap-h3-boringssl.sh. It is a separate binary: the production H1/
# H2/H3 paths keep using OpenSSL and none of these libs are linked into
# libtlsfp or the default tools.
option(TLSFP_BUILD_H3_BORINGSSL "Build the BoringSSL HTTP/3 spike probe" OFF)
if(TLSFP_BUILD_H3_BORINGSSL)
  if(DEFINED TLSFP_H3_BORINGSSL_ROOT)
    set(_h3_boring_root "${TLSFP_H3_BORINGSSL_ROOT}")
  elseif(DEFINED ENV{TLSFP_H3_BORINGSSL_ROOT})
    set(_h3_boring_root "$ENV{TLSFP_H3_BORINGSSL_ROOT}")
  else()
    set(_h3_boring_root "$ENV{HOME}/.cache/tlsfp/h3-boringssl")
  endif()
  set(_h3_bs_inc "${_h3_boring_root}/boringssl/include")
  set(_h3_bs_ssl "${_h3_boring_root}/boringssl/build/libssl.a")
  set(_h3_bs_crypto "${_h3_boring_root}/boringssl/build/libcrypto.a")
  set(_h3_ngtcp2_lib "${_h3_boring_root}/ngtcp2/build/lib/libngtcp2.a")
  set(_h3_ngtcp2_crypto
      "${_h3_boring_root}/ngtcp2/build/crypto/boringssl/libngtcp2_crypto_boringssl.a")
  set(_h3_nghttp3_lib "${_h3_boring_root}/nghttp3/build/lib/libnghttp3.a")
  foreach(_f "${_h3_bs_ssl}" "${_h3_bs_crypto}" "${_h3_ngtcp2_lib}"
            "${_h3_ngtcp2_crypto}" "${_h3_nghttp3_lib}")
    if(NOT EXISTS "${_f}")
      message(FATAL_ERROR
        "TLSFP_BUILD_H3_BORINGSSL=ON but ${_f} is missing; run "
        "scripts/bootstrap-h3-boringssl.sh first")
    endif()
  endforeach()
  find_library(BROTLIDEC_LIBRARY brotlidec REQUIRED)
  find_library(BROTLICOMMON_LIBRARY brotlicommon REQUIRED)

  # The backend itself lives in one object library so the standalone probe and
  # the dlopen-able plugin are built from identical code.
  add_library(tlsfp_h3_boring_obj OBJECT
    src/h3_boring/client.cpp
    src/h3_boring/session.cpp
    src/h3_boring/cache.cpp
    src/h3_boring/profile.cpp
    src/h3_boring/ch.cpp
    src/socks5_udp.cpp)
  target_include_directories(tlsfp_h3_boring_obj PRIVATE
    "${CMAKE_SOURCE_DIR}/include"
    "${CMAKE_SOURCE_DIR}/src/h3_boring"
    "${_h3_bs_inc}"
    "${_h3_boring_root}/ngtcp2/lib/includes"
    "${_h3_boring_root}/ngtcp2/crypto/includes"
    "${_h3_boring_root}/nghttp3/lib/includes")
  target_compile_definitions(tlsfp_h3_boring_obj PRIVATE
    "TLSFP_PROFILE_DIR_DEFAULT=\"${CMAKE_SOURCE_DIR}/profiles\"")
  target_compile_options(tlsfp_h3_boring_obj PRIVATE -Wall -Wextra
    -Wno-unused-parameter -Wno-missing-field-initializers -fPIC)
  if(nlohmann_json_FOUND)
    target_link_libraries(tlsfp_h3_boring_obj PUBLIC nlohmann_json::nlohmann_json)
  endif()

  set(_h3_boring_libs
    "${_h3_ngtcp2_crypto}" "${_h3_ngtcp2_lib}" "${_h3_nghttp3_lib}"
    "${_h3_bs_ssl}" "${_h3_bs_crypto}"
    "${BROTLIDEC_LIBRARY}" "${BROTLICOMMON_LIBRARY}"
    Threads::Threads ${CMAKE_DL_LIBS})

  # Shared backend loaded at run time by `tlsfp get --http3 --backend boring`.
  # BoringSSL exports the same SSL_* names as OpenSSL, so the library hides
  # every symbol except the tlsfp_h3b_* C ABI (cmake/h3_boring.map) and the
  # caller dlopens it with RTLD_LOCAL.
  add_library(tlsfp_h3_boring SHARED
    $<TARGET_OBJECTS:tlsfp_h3_boring_obj>
    src/h3_boring/plugin.cpp)
  target_include_directories(tlsfp_h3_boring PRIVATE
    "${CMAKE_SOURCE_DIR}/include" "${CMAKE_SOURCE_DIR}/src/h3_boring")
  target_link_libraries(tlsfp_h3_boring PRIVATE ${_h3_boring_libs})
  target_link_options(tlsfp_h3_boring PRIVATE
    "-Wl,--exclude-libs,ALL"
    "-Wl,--version-script=${CMAKE_SOURCE_DIR}/cmake/h3_boring.map")
  # The version script (not -fvisibility=hidden) keeps only the C ABI global;
  # hidden visibility would hide the ABI functions themselves.
  set_target_properties(tlsfp_h3_boring PROPERTIES
    OUTPUT_NAME tlsfp_h3_boring
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR})
  target_compile_options(tlsfp_h3_boring PRIVATE -Wall -Wextra
    -Wno-unused-parameter -Wno-missing-field-initializers)

  # Offline fixture for the failure-classification table (IKX4XC): the pure
  # decision function needs no TLS/QUIC library, so it is a plain unit test.
  add_executable(test_h3_classify tests/test_h3_classify.cpp)
  target_include_directories(test_h3_classify PRIVATE
    "${CMAKE_SOURCE_DIR}/src/h3_boring")
  target_compile_options(test_h3_classify PRIVATE -Wall -Wextra)

  add_executable(h3probe-boring
    tools/h3probe_boring.cpp
    $<TARGET_OBJECTS:tlsfp_h3_boring_obj>)
  target_include_directories(h3probe-boring PRIVATE
    "${CMAKE_SOURCE_DIR}/include" "${CMAKE_SOURCE_DIR}/src"
    "${CMAKE_SOURCE_DIR}/src/h3_boring")
  target_link_libraries(h3probe-boring PRIVATE ${_h3_boring_libs})
  target_compile_options(h3probe-boring PRIVATE -Wall -Wextra
    -Wno-unused-parameter -Wno-missing-field-initializers)

  # The default tlsfp binary only learns how to dlopen the backend; its own
  # OpenSSL H1/H2/H3 code and link line are unchanged. --backend boring rides
  # on the H3 CLI path, so it needs TLSFP_BUILD_H3 as well.
  if(TLSFP_BUILD_H3)
    target_sources(tlsfp PRIVATE tools/h3_backend_boring.cpp)
    target_include_directories(tlsfp PRIVATE "${CMAKE_SOURCE_DIR}/tools")
    target_link_libraries(tlsfp PRIVATE ${CMAKE_DL_LIBS})
    target_compile_definitions(tlsfp PRIVATE TLSFP_HAVE_H3_BORING_BACKEND=1)
    # `h3probe --backend boring` uses the same dlopen glue as the CLI.
    if(TARGET h3probe)
      target_sources(h3probe PRIVATE tools/h3_backend_boring.cpp)
      target_include_directories(h3probe PRIVATE "${CMAKE_SOURCE_DIR}/tools")
      target_link_libraries(h3probe PRIVATE ${CMAKE_DL_LIBS})
      target_compile_definitions(h3probe PRIVATE TLSFP_HAVE_H3_BORING_BACKEND=1)
    endif()
  else()
    message(STATUS
      "TLSFP_BUILD_H3_BORINGSSL=ON but TLSFP_BUILD_H3=OFF: "
      "--backend boring stays unavailable (h3probe-boring is still built)")
  endif()
  message(STATUS "HTTP/3 BoringSSL backend: ${_h3_boring_root}")
endif()

# ── TCP TLS 1.2 BoringSSL spike (iteration 44, opt-in, never default) ──────
# tls12probe needs the same patched BoringSSL as the H3 backend (extension
# order, raw 0xca34/0x44cd, fixed ECH GREASE length). It is a separate binary
# because BoringSSL exports the same SSL_* symbols as OpenSSL: linking it into
# libtlsfp would interpose on the default stack.
if(TLSFP_BUILD_TLS12_BORINGSSL)
  if(DEFINED TLSFP_H3_BORINGSSL_ROOT)
    set(_t12_root "${TLSFP_H3_BORINGSSL_ROOT}")
  elseif(DEFINED ENV{TLSFP_H3_BORINGSSL_ROOT})
    set(_t12_root "$ENV{TLSFP_H3_BORINGSSL_ROOT}")
  else()
    set(_t12_root "$ENV{HOME}/.cache/tlsfp/h3-boringssl")
  endif()
  set(_t12_bs_inc "${_t12_root}/boringssl/include")
  set(_t12_bs_ssl "${_t12_root}/boringssl/build/libssl.a")
  set(_t12_bs_crypto "${_t12_root}/boringssl/build/libcrypto.a")
  foreach(_f "${_t12_bs_ssl}" "${_t12_bs_crypto}" "${_t12_bs_inc}/openssl/ssl.h")
    if(NOT EXISTS "${_f}")
      message(FATAL_ERROR
        "TLSFP_BUILD_TLS12_BORINGSSL=ON but ${_f} is missing; run "
        "scripts/bootstrap-h3-boringssl.sh first")
    endif()
  endforeach()
  find_library(BROTLIDEC_LIBRARY brotlidec REQUIRED)
  find_library(BROTLICOMMON_LIBRARY brotlicommon REQUIRED)

  add_library(tlsfp_tls12_boring_obj OBJECT
    src/tls12_boring/tls12_profile.cpp
    src/tls12_boring/tls12_client.cpp)
  target_include_directories(tlsfp_tls12_boring_obj PRIVATE
    "${CMAKE_SOURCE_DIR}/src"
    "${_t12_bs_inc}")
  target_compile_definitions(tlsfp_tls12_boring_obj PRIVATE
    "TLSFP_PROFILE_DIR_DEFAULT=\"${CMAKE_SOURCE_DIR}/profiles\"")
  target_compile_options(tlsfp_tls12_boring_obj PRIVATE -Wall -Wextra
    -Wno-unused-parameter -fPIC)
  if(nlohmann_json_FOUND)
    target_link_libraries(tlsfp_tls12_boring_obj PUBLIC nlohmann_json::nlohmann_json)
  endif()

  # Fork-free fallback: `tlsfp get --tls12-fallback` dlopens this library,
  # built from the same objects as the probe. Only tlsfp_tls12_* is exported.
  set_target_properties(tlsfp_tls12_boring_obj PROPERTIES POSITION_INDEPENDENT_CODE ON)
  add_library(tlsfp_tls12_boring SHARED
    $<TARGET_OBJECTS:tlsfp_tls12_boring_obj>
    src/tls12_boring/plugin.cpp)
  target_include_directories(tlsfp_tls12_boring PRIVATE
    "${CMAKE_SOURCE_DIR}/src" "${_t12_bs_inc}")
  target_link_libraries(tlsfp_tls12_boring PRIVATE
    "${_t12_bs_ssl}" "${_t12_bs_crypto}"
    "${BROTLIDEC_LIBRARY}" "${BROTLICOMMON_LIBRARY}" Threads::Threads)
  target_link_options(tlsfp_tls12_boring PRIVATE
    "-Wl,--exclude-libs,ALL"
    "-Wl,--version-script=${CMAKE_SOURCE_DIR}/cmake/tls12_boring.map")
  set_target_properties(tlsfp_tls12_boring PROPERTIES
    OUTPUT_NAME tlsfp_tls12_boring
    VERSION ${PROJECT_VERSION}
    SOVERSION ${PROJECT_VERSION_MAJOR})

  add_executable(tls12probe tools/tls12probe.cpp
    $<TARGET_OBJECTS:tlsfp_tls12_boring_obj>)
  target_include_directories(tls12probe PRIVATE
    "${CMAKE_SOURCE_DIR}/src" "${_t12_bs_inc}")
  target_link_libraries(tls12probe PRIVATE
    "${_t12_bs_ssl}" "${_t12_bs_crypto}"
    "${BROTLIDEC_LIBRARY}" "${BROTLICOMMON_LIBRARY}" Threads::Threads)
  target_compile_options(tls12probe PRIVATE -Wall -Wextra -Wno-unused-parameter)
  # The CLI's --tls12-fallback flag exists only in this build.
  if(TARGET tlsfp)
    target_compile_definitions(tlsfp PRIVATE TLSFP_HAVE_TLS12_FALLBACK=1)
  endif()
  message(STATUS "TCP TLS 1.2 BoringSSL probe: ${_t12_root}")
endif()

# ── native CPython extension (opt-in fast path for python/tlsfp.py) ──────
# Pure CPython C API: no pybind11, no third-party build dependency. The
# extension links the shared library and releases the GIL around
# tlsfp_perform; python/tlsfp.py keeps working without it.
option(TLSFP_PYTHON "Build the native CPython extension (_tlsfp_native)" OFF)
if(TLSFP_PYTHON)
  find_package(Python3 REQUIRED COMPONENTS Interpreter Development)
  add_library(_tlsfp_native MODULE src/python_native.c)
  target_link_libraries(_tlsfp_native PRIVATE tlsfp_shared Python3::Module)
  if(Python3_SOABI)
    set(_tlsfp_py_suffix ".${Python3_SOABI}.so")
  else()
    set(_tlsfp_py_suffix ".so")
  endif()
  set_target_properties(_tlsfp_native PROPERTIES
    PREFIX ""
    OUTPUT_NAME "_tlsfp_native"
    SUFFIX "${_tlsfp_py_suffix}"
    LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}"
    BUILD_RPATH "${CMAKE_BINARY_DIR}"
    INSTALL_RPATH "$ORIGIN")
  target_compile_options(_tlsfp_native PRIVATE
    -Wall -Wextra -Wno-unused-parameter -Wno-cast-function-type)
  message(STATUS "Python native extension: ${Python3_VERSION}")
endif()

add_executable(fpcheck tools/fpcheck.cpp)
target_link_libraries(fpcheck PRIVATE tlsfp_core)
add_executable(tlsfp-import tools/tlsfp-import.cpp)
target_link_libraries(tlsfp-import PRIVATE tlsfp_core)

# ── install: header + static archive + shared library + pkg-config ─────────
include(GNUInstallDirs)
# Kept at "lib" so the documented /tmp/tlsfp-install/lib path is stable on
# every distro; override with -DTLSFP_INSTALL_LIBDIR=lib64 if wanted.
set(TLSFP_INSTALL_LIBDIR "lib" CACHE STRING "Library install directory (relative)")
set(TLSFP_INSTALL_INCLUDEDIR "include" CACHE STRING "Header install directory")

install(TARGETS tlsfp_core ARCHIVE DESTINATION ${TLSFP_INSTALL_LIBDIR})
if(TLSFP_BUILD_SHARED)
  install(TARGETS tlsfp_shared LIBRARY DESTINATION ${TLSFP_INSTALL_LIBDIR})
endif()
install(FILES include/tlsfp/tlsfp.h DESTINATION ${TLSFP_INSTALL_INCLUDEDIR}/tlsfp)
install(TARGETS tlsfp tlsfp-ch tlsfp-bench-cli fpcheck tlsfp-import tlsfp-multi RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
if(TLSFP_BUILD_H3_BORINGSSL)
  # Optional backend; `tlsfp get --http3 --backend boring` looks for it next to
  # the binary, so installing it beside the executable is enough.
  install(TARGETS tlsfp_h3_boring LIBRARY DESTINATION ${TLSFP_INSTALL_LIBDIR})
  install(TARGETS tlsfp_h3_boring LIBRARY DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()

# Relocatable pkg-config file: prefix is derived from the .pc location, so
# `cmake --install --prefix <dir>` needs no regeneration.
configure_file(cmake/tlsfp.pc.in ${CMAKE_CURRENT_BINARY_DIR}/tlsfp.pc @ONLY)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/tlsfp.pc
        DESTINATION ${TLSFP_INSTALL_LIBDIR}/pkgconfig)

enable_testing()
add_subdirectory(tests)
