diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 61e05ee97c..8de5535ba9 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -93,14 +93,15 @@ jobs: id: depends run: | sudo apt-get update - sudo apt-get install build-essential + sudo apt-get install -y build-essential libssl-dev - name: Build id: cmake_build run: | mkdir build cd build - cmake .. -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH='$ORIGIN' + cmake .. -DSD_BUILD_SHARED_LIBS=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH='$ORIGIN' \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE cmake --build . --config Release cmake --build . --config Release --target dgl-check-builtins @@ -126,6 +127,7 @@ jobs: cp LICENSE ./build/bin/stable-diffusion.cpp.txt cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt + cp /usr/share/doc/libssl-dev/copyright ./build/bin/openssl.txt chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -161,14 +163,15 @@ jobs: id: depends run: | sudo apt-get update - sudo apt-get install build-essential libvulkan-dev glslc spirv-headers + sudo apt-get install -y build-essential libvulkan-dev glslc spirv-headers libssl-dev - name: Build id: cmake_build run: | mkdir build cd build - cmake .. -DSD_BUILD_SHARED_LIBS=ON -DSD_VULKAN=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH='$ORIGIN' + cmake .. -DSD_BUILD_SHARED_LIBS=ON -DSD_VULKAN=ON -DGGML_NATIVE=OFF -DSD_BUILD_SHARED_GGML_LIB=ON -DGGML_BACKEND_DL=ON -DGGML_CPU_ALL_VARIANTS=ON -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON -DCMAKE_INSTALL_RPATH='$ORIGIN' \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE cmake --build . --config Release - name: Get commit hash @@ -193,6 +196,7 @@ jobs: cp LICENSE ./build/bin/stable-diffusion.cpp.txt cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt + cp /usr/share/doc/libssl-dev/copyright ./build/bin/openssl.txt chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-vulkan.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -350,8 +354,17 @@ jobs: sysctl -a mkdir build cd build - cmake .. -DGGML_AVX2=ON -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DSD_BUILD_SHARED_LIBS=ON + cmake .. -DGGML_AVX2=ON -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DSD_BUILD_SHARED_LIBS=ON \ + -DSD_OPENSSL=ON -DSD_BUILD_BORINGSSL=ON cmake --build . --config Release + for exe in bin/sd-cli bin/sd-server; do + lipo -verify_arch arm64 x86_64 "$exe" + libraries="$(otool -L "$exe")" + if grep -Eq 'lib(ssl|crypto)[^[:space:]]*\.dylib' <<< "$libraries"; then + echo "$exe links to a shared TLS library" >&2 + exit 1 + fi + done - name: Get commit hash id: commit @@ -375,6 +388,7 @@ jobs: cp LICENSE ./build/bin/stable-diffusion.cpp.txt cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt + cp ./build/boringssl.txt ./build/bin/ chmod +x start-server.sh zip -j sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-${{ steps.system-info.outputs.OS_NAME }}-${{ steps.system-info.outputs.OS_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}.zip ./build/bin/* ./start-server.sh ./start-server.bat @@ -456,8 +470,16 @@ jobs: mkdir build cd build - cmake .. -DCMAKE_CXX_FLAGS='/bigobj' -G Ninja -DCMAKE_C_COMPILER=cl.exe -DCMAKE_CXX_COMPILER=cl.exe -DCMAKE_BUILD_TYPE=Release ${{ matrix.defines }} + cmake .. -DCMAKE_CXX_FLAGS='/bigobj' -G Ninja -DCMAKE_C_COMPILER=cl.exe -DCMAKE_CXX_COMPILER=cl.exe -DCMAKE_BUILD_TYPE=Release ${{ matrix.defines }} ` + -DSD_OPENSSL=ON -DSD_BUILD_BORINGSSL=ON + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cmake --build . + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + foreach ($exe in 'sd-cli.exe', 'sd-server.exe') { + $imports = dumpbin /dependents (Join-Path 'bin' $exe) + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if ($imports -match '\b(?:lib)?(?:ssl|crypto)\S*\.dll') { throw "$exe links to a TLS DLL" } + } - name: Get commit hash id: commit @@ -486,6 +508,7 @@ jobs: $binPath = Split-Path -Parent $filePath Copy-Item thirdparty/libwebm/LICENSE.TXT (Join-Path $binPath 'libwebm.txt') Copy-Item thirdparty/libwebp/COPYING (Join-Path $binPath 'libwebp.txt') + Copy-Item .\build\boringssl.txt $binPath if ("${{ matrix.build }}" -eq "cuda12") { Copy-Item thirdparty/cutlass/LICENSE.txt (Join-Path $binPath 'cutlass.txt') } @@ -620,8 +643,10 @@ jobs: -DCMAKE_CXX_COMPILER="${env:HIP_PATH}\lib\llvm\bin\clang++.exe" ` -DCMAKE_HIP_COMPILER="${env:HIP_PATH}\lib\llvm\bin\clang.exe" ` -DHIP_PATH="${env:HIP_PATH}" ` + -DSD_OPENSSL=ON -DSD_BUILD_BORINGSSL=ON ` -DCMAKE_BUILD_TYPE=Release ` -DGPU_TARGETS="${{ env.GPU_TARGETS }}" + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } cmake --build . --config Release --parallel ${env:NUMBER_OF_PROCESSORS} - name: Get commit hash @@ -647,6 +672,7 @@ jobs: run: | Copy-Item thirdparty/libwebm/LICENSE.TXT .\build\bin\libwebm.txt Copy-Item thirdparty/libwebp/COPYING .\build\bin\libwebp.txt + Copy-Item .\build\boringssl.txt .\build\bin\ 7z a sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-win-rocm-${{ env.ROCM_VERSION }}-x64.zip .\build\bin\* .\start-server.sh .\start-server.bat - name: Upload artifacts @@ -696,7 +722,7 @@ jobs: - name: Dependencies id: depends run: | - sudo apt install -y build-essential git cmake wget + sudo apt install -y build-essential git cmake wget libssl-dev - name: Free disk space run: | @@ -779,6 +805,7 @@ jobs: -DSD_BUILD_SHARED_GGML_LIB=ON \ -DGGML_BACKEND_DL=ON \ -DGGML_CPU_ALL_VARIANTS=ON \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE \ -DSD_BUILD_SHARED_LIBS=ON cmake --build . --config Release @@ -812,6 +839,7 @@ jobs: cp LICENSE ./build/bin/stable-diffusion.cpp.txt cp thirdparty/libwebm/LICENSE.TXT ./build/bin/libwebm.txt cp thirdparty/libwebp/COPYING ./build/bin/libwebp.txt + cp /usr/share/doc/libssl-dev/copyright ./build/bin/openssl.txt chmod +x start-server.sh zip -y -r sd-${{ env.BRANCH_NAME }}-${{ steps.commit.outputs.short }}-bin-${{ steps.system-info.outputs.OS_TYPE }}-Ubuntu-${{ env.UBUNTU_VERSION }}-${{ steps.system-info.outputs.CPU_ARCH }}-rocm-${{ matrix.ROCM_VERSION }}.zip ./build/bin ./start-server.sh ./start-server.bat diff --git a/CMakeLists.txt b/CMakeLists.txt index 858ac8dfd5..136fd8a094 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -91,6 +91,8 @@ endif() # general #option(SD_BUILD_TESTS "sd: build tests" ${SD_STANDALONE}) option(SD_BUILD_EXAMPLES "sd: build examples" ${SD_STANDALONE}) +option(SD_OPENSSL "sd: enable OpenSSL support in the CLI and server" ON) +option(SD_BUILD_BORINGSSL "sd: build static BoringSSL for OpenSSL-compatible TLS" OFF) option(SD_BUILD_PCH "sd: use a C++ precompiled header for the library" ON) option(SD_WEBP "sd: enable WebP image I/O support" ${SD_WEBP_DEFAULT}) option(SD_USE_SYSTEM_WEBP "sd: link against system libwebp" OFF) diff --git a/cmake/boringssl.cmake b/cmake/boringssl.cmake new file mode 100644 index 0000000000..b29e01db35 --- /dev/null +++ b/cmake/boringssl.cmake @@ -0,0 +1,38 @@ +function(sd_build_boringssl) + if(CMAKE_VERSION VERSION_LESS 3.22) + message(FATAL_ERROR "SD_BUILD_BORINGSSL requires CMake 3.22 or newer") + endif() + + include(FetchContent) + set(boringssl_version 0.20261105.0) + set(boringssl_args + GIT_REPOSITORY https://boringssl.googlesource.com/boringssl + GIT_TAG ${boringssl_version} + GIT_SHALLOW TRUE) + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28) + list(APPEND boringssl_args EXCLUDE_FROM_ALL) + endif() + FetchContent_Declare(boringssl ${boringssl_args}) + + set(BUILD_SHARED_LIBS OFF) + set(BUILD_TESTING OFF) + set(FIPS OFF) + set(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT FALSE) + # Avoid a separate NASM dependency and single-architecture assembly in macOS universal builds. + set(OPENSSL_NO_ASM ON) + if(CMAKE_VERSION VERSION_GREATER_EQUAL 3.28) + FetchContent_MakeAvailable(boringssl) + else() + FetchContent_GetProperties(boringssl) + if(NOT boringssl_POPULATED) + FetchContent_Populate(boringssl) + add_subdirectory("${boringssl_SOURCE_DIR}" "${boringssl_BINARY_DIR}" EXCLUDE_FROM_ALL) + endif() + endif() + configure_file("${boringssl_SOURCE_DIR}/LICENSE" "${PROJECT_BINARY_DIR}/boringssl.txt" COPYONLY) + if(FETCHCONTENT_SOURCE_DIR_BORINGSSL) + message(STATUS "Using BoringSSL (static) from ${boringssl_SOURCE_DIR}") + else() + message(STATUS "Using BoringSSL ${boringssl_version} (static) from ${boringssl_SOURCE_DIR}") + endif() +endfunction() diff --git a/docker/Dockerfile b/docker/Dockerfile index 30735094e9..06dc802403 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -3,7 +3,7 @@ ARG UBUNTU_VERSION=24.04 FROM ubuntu:$UBUNTU_VERSION AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. -RUN apt-get update && apt-get install -y --no-install-recommends build-essential git cmake ca-certificates curl gnupg && \ +RUN apt-get update && apt-get install -y --no-install-recommends build-essential git cmake libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -20,6 +20,7 @@ WORKDIR /sd.cpp COPY . . RUN cmake . -B ./build \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE \ -DSD_BUILD_SHARED_LIBS=ON \ -DGGML_NATIVE=OFF \ -DSD_BUILD_SHARED_GGML_LIB=ON \ @@ -32,9 +33,10 @@ RUN cmake --build ./build --config Release --parallel FROM ubuntu:$UBUNTU_VERSION AS runtime RUN apt-get update && \ - apt-get install --yes --no-install-recommends libgomp1 && \ + apt-get install --yes --no-install-recommends ca-certificates libgomp1 && \ apt-get clean +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin /sd.cpp/bin RUN printf '#!/bin/sh\nexec /sd.cpp/bin/sd-cli "$@"\n' > /sd-cli && \ printf '#!/bin/sh\nexec /sd.cpp/bin/sd-server "$@"\n' > /sd-server && \ diff --git a/docker/Dockerfile.cuda b/docker/Dockerfile.cuda index e3364e8402..994613ca2d 100644 --- a/docker/Dockerfile.cuda +++ b/docker/Dockerfile.cuda @@ -6,7 +6,7 @@ ARG UBUNTU_VERSION=24.04 FROM nvidia/cuda:${CUDA_VERSION}-devel-ubuntu${UBUNTU_VERSION} AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. -RUN apt-get update && apt-get install -y --no-install-recommends build-essential git ccache cmake ca-certificates curl gnupg && \ +RUN apt-get update && apt-get install -y --no-install-recommends build-essential git ccache cmake libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -52,7 +52,7 @@ RUN set -- \ if [ -n "${GGML_CUDA_FA_ALL_QUANTS}" ]; then \ set -- "$@" "-DGGML_CUDA_FA_ALL_QUANTS=${GGML_CUDA_FA_ALL_QUANTS}"; \ fi; \ - cmake . -B ./build "$@" + cmake . -B ./build -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE "$@" RUN --mount=type=cache,target=/root/.cache/ccache \ ccache --zero-stats && \ cmake --build ./build --config Release -j$(nproc) && \ @@ -62,9 +62,10 @@ RUN --mount=type=cache,target=/root/.cache/ccache \ FROM nvidia/cuda:${CUDA_VERSION}-runtime-ubuntu${UBUNTU_VERSION} AS runtime RUN apt-get update && \ - apt-get install --yes --no-install-recommends libgomp1 && \ + apt-get install --yes --no-install-recommends ca-certificates libgomp1 && \ apt-get clean +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin /sd.cpp/bin COPY --from=build /sd.cpp/thirdparty/cutlass/LICENSE.txt /sd.cpp/bin/cutlass.txt RUN printf '#!/bin/sh\nexec /sd.cpp/bin/sd-cli "$@"\n' > /sd-cli && \ diff --git a/docker/Dockerfile.musa b/docker/Dockerfile.musa index 9042452d38..219a62a31f 100644 --- a/docker/Dockerfile.musa +++ b/docker/Dockerfile.musa @@ -3,7 +3,7 @@ ARG MUSA_IMAGE=registry.mthreads.com/mcconline/inference/pytorch:2.9.1.post1-py3 FROM ${MUSA_IMAGE} AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. -RUN apt-get update && apt-get install -y --no-install-recommends ccache cmake git ca-certificates curl gnupg && \ +RUN apt-get update && apt-get install -y --no-install-recommends ccache cmake git libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -21,6 +21,7 @@ COPY . . RUN mkdir build && cd build && \ cmake .. -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++ \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE \ -DSD_MUSA=ON \ -DMUSA_ARCHITECTURES=31 \ -DSD_BUILD_SHARED_LIBS=ON \ @@ -35,6 +36,10 @@ RUN mkdir build && cd build && \ FROM ${MUSA_IMAGE} AS runtime +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin /sd.cpp/bin RUN printf '#!/bin/sh\nexec /sd.cpp/bin/sd-cli "$@"\n' > /sd-cli && \ printf '#!/bin/sh\nexec /sd.cpp/bin/sd-server "$@"\n' > /sd-server && \ diff --git a/docker/Dockerfile.rocm b/docker/Dockerfile.rocm index 9236bdb1cd..711067ba89 100644 --- a/docker/Dockerfile.rocm +++ b/docker/Dockerfile.rocm @@ -2,7 +2,7 @@ FROM rocm/dev-ubuntu-24.04 AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. RUN apt-get update && apt-get install -y --no-install-recommends \ - build-essential git cmake ninja-build ccache ca-certificates curl gnupg && \ + build-essential git cmake ninja-build ccache libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -22,6 +22,7 @@ COPY . . ARG AMDGPU_TARGETS="" RUN cmake . -B ./build -G Ninja \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE \ -DCMAKE_C_COMPILER=clang \ -DCMAKE_CXX_COMPILER=clang++ \ -DSD_HIPBLAS=ON \ @@ -39,9 +40,10 @@ FROM rocm/dev-ubuntu-24.04 AS runtime ENV LD_LIBRARY_PATH="/opt/rocm/llvm/lib:/opt/rocm/lib:$LD_LIBRARY_PATH" RUN apt-get update && \ - apt-get install --yes --no-install-recommends libgomp1 && \ + apt-get install --yes --no-install-recommends ca-certificates libgomp1 && \ apt-get clean && rm -rf /var/lib/apt/lists/* +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin /sd.cpp/bin RUN printf '#!/bin/sh\nexec /sd.cpp/bin/sd-cli "$@"\n' > /sd-cli && \ printf '#!/bin/sh\nexec /sd.cpp/bin/sd-server "$@"\n' > /sd-server && \ diff --git a/docker/Dockerfile.sycl b/docker/Dockerfile.sycl index bdbb7509c4..3858f71289 100644 --- a/docker/Dockerfile.sycl +++ b/docker/Dockerfile.sycl @@ -4,7 +4,7 @@ ARG SYCL_VERSION=2025.3.2-0 FROM intel/oneapi-basekit:${SYCL_VERSION}-devel-ubuntu24.04 AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. -RUN apt-get update && apt-get install -y --no-install-recommends cmake ca-certificates curl gnupg && \ +RUN apt-get update && apt-get install -y --no-install-recommends cmake libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -21,11 +21,16 @@ WORKDIR /sd.cpp COPY . . RUN mkdir build && cd build && \ - cmake .. -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DSD_SYCL=ON -DCMAKE_BUILD_TYPE=Release && \ + cmake .. -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx -DSD_SYCL=ON -DCMAKE_BUILD_TYPE=Release \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE && \ cmake --build . --config Release -j$(nproc) FROM intel/oneapi-basekit:${SYCL_VERSION}-devel-ubuntu24.04 AS runtime +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin/sd-cli /sd-cli COPY --from=build /sd.cpp/build/bin/sd-server /sd-server diff --git a/docker/Dockerfile.vulkan b/docker/Dockerfile.vulkan index 576e5d9989..96e4eecb0f 100644 --- a/docker/Dockerfile.vulkan +++ b/docker/Dockerfile.vulkan @@ -3,7 +3,7 @@ ARG UBUNTU_VERSION=24.04 FROM ubuntu:$UBUNTU_VERSION AS build # sd-server embeds the web UI at build time, so the build image needs Node/pnpm. -RUN apt-get update && apt-get install -y --no-install-recommends build-essential git cmake libvulkan-dev glslc spirv-headers ca-certificates curl gnupg && \ +RUN apt-get update && apt-get install -y --no-install-recommends build-essential git cmake libvulkan-dev glslc spirv-headers libssl-dev ca-certificates curl gnupg && \ mkdir -p /etc/apt/keyrings && \ curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key -o /tmp/nodesource-repo.gpg.key && \ gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg /tmp/nodesource-repo.gpg.key && \ @@ -20,6 +20,7 @@ WORKDIR /sd.cpp COPY . . RUN cmake . -B ./build \ + -DSD_OPENSSL=ON -DOPENSSL_USE_STATIC_LIBS=TRUE -DCMAKE_REQUIRE_FIND_PACKAGE_OpenSSL=TRUE \ -DSD_VULKAN=ON \ -DSD_BUILD_SHARED_LIBS=ON \ -DGGML_NATIVE=OFF \ @@ -33,9 +34,10 @@ RUN cmake --build ./build --config Release -j$(nproc) FROM ubuntu:$UBUNTU_VERSION AS runtime RUN apt-get update && \ - apt-get install --yes --no-install-recommends libgomp1 libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 && \ + apt-get install --yes --no-install-recommends ca-certificates libgomp1 libvulkan1 mesa-vulkan-drivers libglvnd0 libgl1 libglx0 libegl1 libgles2 && \ apt-get clean +COPY --from=build /usr/share/doc/libssl-dev/copyright /usr/share/licenses/sd.cpp/openssl.txt COPY --from=build /sd.cpp/build/bin /sd.cpp/bin RUN printf '#!/bin/sh\nexec /sd.cpp/bin/sd-cli "$@"\n' > /sd-cli && \ printf '#!/bin/sh\nexec /sd.cpp/bin/sd-server "$@"\n' > /sd-server && \ diff --git a/docs/build.md b/docs/build.md index 804ba8e96f..d4d2494f56 100644 --- a/docs/build.md +++ b/docs/build.md @@ -87,6 +87,22 @@ cmake .. -DSD_USE_SYSTEM_WEBP=ON -DSD_USE_SYSTEM_WEBM=ON cmake --build . --config Release ``` +## OpenSSL support + +`SD_OPENSSL` defaults to `ON`. CMake detects the OpenSSL 3 development libraries +and enables DGL HTTPS downloads in `sd-cli` and `sd-server` when available. +Install OpenSSL before configuring, or set `OPENSSL_ROOT_DIR` if it is in a +custom location. If OpenSSL is unavailable, CMake warns and builds both +executables with local model support. Use `-DSD_OPENSSL=OFF` to skip detection. + +Windows and macOS release builds use `-DSD_BUILD_BORINGSSL=ON` to fetch and +statically link BoringSSL. This option needs CMake 3.22 or newer and applies when +`SD_OPENSSL` is enabled. The macOS package includes both arm64 and x86_64. +Linux release archives and container images link system OpenSSL 3 statically. +Containers include the CA certificates used to verify HTTPS connections. +To build locally against static OpenSSL 3, install the matching development +libraries and configure with `-DOPENSSL_USE_STATIC_LIBS=TRUE`. + ## Build (CPU only) If you don't have a GPU or CUDA installed, you can build a CPU-only version. diff --git a/docs/development/dgl.md b/docs/development/dgl.md index 14a5f31289..d96b38106e 100644 --- a/docs/development/dgl.md +++ b/docs/development/dgl.md @@ -26,6 +26,13 @@ use the same compiler and executor. The C API keeps the rendered source in idle weight buffers under memory pressure. The value returned by `main` becomes the program result. +With automatic downloads enabled, the CLI and server validate the script and +prepare its model files before execution. The +[DGL model-source adapter](../../examples/common/dgl_model_sources.cpp) parses +the annotations and applies the destination and host policies. It submits the +authorized targets to the [shared downloader](../../examples/common/download.h), +which handles HTTPS, retries, checkpoints, integrity checks, and progress. + ## Built-ins, operations and models The registry describes a built-in's script name, parameters, defaults and diff --git a/docs/dgl.md b/docs/dgl.md index 3185db5242..1897979dbb 100644 --- a/docs/dgl.md +++ b/docs/dgl.md @@ -94,7 +94,7 @@ fn main() { functions return `void`; using them in assignments, arguments, containers or returned expressions is a compile-time error. - Strings use JSON escaping. Comments start with `#` or `//`, on their own line - or after code. Only `# version: ...` is reserved for the file's version header. + or after code. Use `# version: ...` to declare the script version. Semicolons are optional. Lists use `[a, b]`. A dictionary (`dict`) groups named values using `{name = value, ...}`. Access a field with `dict_value.name`. A prompt condition contains the fields supplied by its encoder. Reading an @@ -236,6 +236,18 @@ its own minimum, which also covers the helpers it includes. The rendered header is part of the source retained in `generation_info` and embedded in generation metadata when enabled. +### Model sources + +A `# model-source:` comment in the script header records a model file's local +`path` and download `url`. Use one comment per file. Write both values as +double-quoted strings with DGL escapes and separate fields with commas. The +optional `sha256` field is an unquoted 64-digit hexadecimal SHA-256 digest. + +Declarations with a digest can be used for automatic downloads. See the +[SD 1.5 example](dgl/sd/sd1-5-txt2img.dgl), +[CLI usage](../examples/cli/README.md#automatic-dgl-model-downloads), and +[server setup](../examples/server/README.md#dgl-model-downloads). + ### Built-in functions The [built-in function catalog](dgl-builtins.md) lists registered functions, diff --git a/docs/dgl/sd/sd1-5-txt2img.dgl b/docs/dgl/sd/sd1-5-txt2img.dgl index 5057b2a2ee..2a39439fe2 100644 --- a/docs/dgl/sd/sd1-5-txt2img.dgl +++ b/docs/dgl/sd/sd1-5-txt2img.dgl @@ -1,4 +1,5 @@ # version: 0.0.0 +# model-source: path: "../models/checkpoints/v1-5-pruned-emaonly.safetensors", url: "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/f03de327dd89b501a01da37fc5240cf4fdba85a1/v1-5-pruned-emaonly.safetensors", sha256: 6ce0161689b3853acaa03779ec93eafe75a02f4ced659bee03f50797806fa2fa # docs/models/sd.md — SD 1.5 var { diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index dc8150a9ff..648e5a67e2 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,4 +1,41 @@ include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +set(SD_EXAMPLES_TLS_LIBRARIES) +if(SD_OPENSSL) + if(SD_BUILD_BORINGSSL) + include("${PROJECT_SOURCE_DIR}/cmake/boringssl.cmake") + sd_build_boringssl() + set(SD_EXAMPLES_TLS_LIBRARIES ssl crypto) + else() + find_package(OpenSSL 3 QUIET COMPONENTS SSL Crypto) + if(OpenSSL_FOUND) + set(SD_EXAMPLES_TLS_LIBRARIES OpenSSL::SSL OpenSSL::Crypto) + message(STATUS "Using OpenSSL ${OPENSSL_VERSION}: ${OPENSSL_SSL_LIBRARY} (SSL), ${OPENSSL_CRYPTO_LIBRARY} (Crypto)") + else() + message(WARNING "OpenSSL 3 not found. TLS support is unavailable.") + endif() + endif() +else() + message(STATUS "TLS support disabled (SD_OPENSSL=OFF)") +endif() + +function(sd_add_download target) + target_sources(${target} PRIVATE "${PROJECT_SOURCE_DIR}/examples/common/download.cpp") + if(SD_EXAMPLES_TLS_LIBRARIES) + target_sources(${target} PRIVATE + "${PROJECT_SOURCE_DIR}/examples/common/download_http.cpp" + "${PROJECT_SOURCE_DIR}/examples/common/download_file.cpp") + target_compile_definitions(${target} PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT) + target_link_libraries(${target} PRIVATE Threads::Threads ${SD_EXAMPLES_TLS_LIBRARIES}) + if(APPLE) + find_library(SD_SECURITY_FRAMEWORK Security) + find_library(SD_CORE_FOUNDATION_FRAMEWORK CoreFoundation) + target_link_libraries(${target} PRIVATE "${SD_SECURITY_FRAMEWORK}" "${SD_CORE_FOUNDATION_FRAMEWORK}") + elseif(WIN32) + target_link_libraries(${target} PRIVATE ws2_32 crypt32) + endif() + endif() +endfunction() + add_subdirectory(cli) add_subdirectory(server) diff --git a/examples/cli/CMakeLists.txt b/examples/cli/CMakeLists.txt index 5f8abc3a8a..0707850ec6 100644 --- a/examples/cli/CMakeLists.txt +++ b/examples/cli/CMakeLists.txt @@ -2,6 +2,7 @@ set(TARGET sd-cli) add_executable(${TARGET} ../common/common.cpp + ../common/dgl_model_sources.cpp ../common/log.cpp ../common/media_io.cpp main.cpp @@ -17,6 +18,7 @@ target_include_directories(${TARGET} PRIVATE ) install(TARGETS ${TARGET} RUNTIME) target_link_libraries(${TARGET} PRIVATE stable-diffusion zip ${CMAKE_THREAD_LIBS_INIT}) +sd_add_download(${TARGET}) target_compile_features(${TARGET} PUBLIC c_std_11 cxx_std_17) set(SD_DGL_BUILTIN_CATALOG "${PROJECT_SOURCE_DIR}/docs/dgl-builtins.md") diff --git a/examples/cli/README.md b/examples/cli/README.md index 0e56eed6ff..b809369b7c 100644 --- a/examples/cli/README.md +++ b/examples/cli/README.md @@ -49,6 +49,8 @@ before execution at debug level (`--log-level debug`). Run a [DGL program](../../docs/dgl.md) with `sd-cli -M dgl --script program.dgl`. DGL mode accepts the same logging options and sends logs to stderr. +See [Automatic DGL model downloads](#automatic-dgl-model-downloads) to fetch +missing model files. Use `--dgl-arg NAME=VALUE` to override a variable declared in the script's `var` block for one invocation. Repeat the option for different variables. @@ -146,3 +148,35 @@ For completely black or white images or videos, NaNs, and the `--linear-scale` / Generation outputs embed the core [generation record](../../docs/guides/generation_metadata.md). Images retain the native JSON and an additional WebUI-compatible infotext. `--disable-image-metadata` omits both from files. + +## Automatic DGL model downloads + +Pass `--autodl on` to fetch missing files declared with a SHA-256 digest in +[`# model-source:` comments](../../docs/dgl.md#model-sources) before execution. +Existing regular files are reused, and `--check` stays offline. HTTPS downloads +require [OpenSSL support](../../docs/build.md#openssl-support). + +Run the SD 1.5 example from the build directory. It downloads to +`../models/checkpoints`, so authorize `../models` for downloads. + +```powershell +.\bin\Release\sd-cli.exe -M dgl --script ..\docs\dgl\sd\sd1-5-txt2img.dgl ` + --autodl on --allow-download-dir ..\models +``` + +```sh +./bin/sd-cli -M dgl --script ../docs/dgl/sd/sd1-5-txt2img.dgl \ + --autodl on --allow-download-dir ../models +``` + +Downloads can write under the working directory by default. Repeat +`--allow-download-dir` to authorize additional directories, including the +target of a linked model directory outside the working directory. Hugging Face +download hosts are allowed by default. Repeat `--allow-download-host` to +authorize exact hostnames for trusted mirrors and their redirects. + +Set `--download-threads N` to control concurrency. Rerun the command to resume +an interrupted download when the remote server supports byte ranges. Set +`HTTPS_PROXY` to an HTTP proxy URL such as `http://localhost:8080`, and use +`NO_PROXY` for direct connections. Both variables accept lowercase spellings. +Use `SSL_CERT_FILE` to specify a custom CA bundle. diff --git a/examples/cli/dgl.cpp b/examples/cli/dgl.cpp index 8f4cca572d..7995802bb3 100644 --- a/examples/cli/dgl.cpp +++ b/examples/cli/dgl.cpp @@ -1,15 +1,26 @@ #include "dgl.h" +#include +#include +#include +#include +#include #include #include #include #include +#include #include #include #include "common/common.h" #include "stable-diffusion.h" +#ifndef _WIN32 +#include +#include +#endif + ArgOptions DGLModeParams::get_options() { ArgOptions options; options.string_options = { @@ -56,12 +67,14 @@ ArgOptions DGLModeParams::get_options() { return 2; }}, }; + download.add_options(options); return options; } bool DGLModeParams::has_options() const { return !script_path.empty() || !write_builtins_path.empty() || !check_builtins_path.empty() || - !tensor_paths.empty() || !script_args.empty() || !max_ram.empty() || check_only || run_once.has_value() || list_builtins; + !tensor_paths.empty() || !script_args.empty() || !max_ram.empty() || check_only || run_once.has_value() || + list_builtins || download.has_options(); } bool DGLModeParams::validate() const { @@ -78,6 +91,10 @@ bool DGLModeParams::validate() const { LOG_ERROR("--check, --run-once, --tensor and --max-ram require --script"); return false; } + if (script_path.empty() && download.has_options()) { + LOG_ERROR("DGL download options require --script"); + return false; + } return true; } @@ -86,6 +103,144 @@ static void check_dgl(bool success) { throw std::runtime_error(sd_dgl_error()); } +class DownloadDisplay { + using Clock = std::chrono::steady_clock; + + struct SpeedSample { + Clock::time_point time{}; + uint64_t bytes = 0; + + double rate_since(const SpeedSample& earlier) const { + const double seconds = std::chrono::duration(time - earlier.time).count(); + return seconds > 0 ? (bytes - earlier.bytes) / seconds : 0.0; + } + }; + + static bool terminal() { +#ifdef _WIN32 + DWORD mode; + return GetConsoleMode(GetStdHandle(STD_ERROR_HANDLE), &mode) != 0; +#else + return isatty(fileno(stderr)); +#endif + } + + static int terminal_columns() { +#ifdef _WIN32 + CONSOLE_SCREEN_BUFFER_INFO info{}; + if (GetConsoleScreenBufferInfo(GetStdHandle(STD_ERROR_HANDLE), &info)) + return info.srWindow.Right - info.srWindow.Left + 1; +#else + winsize size{}; + if (ioctl(fileno(stderr), TIOCGWINSZ, &size) == 0) + return size.ws_col; +#endif + return 0; + } + + const bool terminal_ = terminal(); + int line_width_ = 0; + Clock::time_point last_update_{}; + SpeedSample first_sample_; + SpeedSample last_transfer_; + std::deque recent_; + + double transfer_rate(SpeedSample now, bool finished) { + if (recent_.empty()) { + first_sample_ = now; + recent_.push_back(now); + } + if (now.bytes > last_transfer_.bytes) + last_transfer_ = now; + if (finished) + return last_transfer_.rate_since(first_sample_); + + const auto cutoff = now.time - std::chrono::seconds(1); + while (recent_.size() > 1 && recent_[1].time <= cutoff) + recent_.pop_front(); + const double rate = now.rate_since(recent_.front()); + if (now.time - recent_.back().time >= std::chrono::milliseconds(250)) + recent_.push_back(now); + return rate; + } + + static std::string download_eta(const sd::download::Progress& progress, double rate) { + if (progress.total <= 0 || !(rate > 0.0)) + return " | ETA --"; + + const auto remaining = std::max(0, progress.total - progress.completed); + const double estimate = std::ceil(remaining / rate); + if (estimate >= static_cast(std::numeric_limits::max())) + return " | ETA --"; + const auto seconds = static_cast(estimate); + char label[32]; + if (seconds >= 3600) + std::snprintf(label, sizeof(label), " | ETA %lld:%02lld:%02lld", seconds / 3600, seconds / 60 % 60, seconds % 60); + else + std::snprintf(label, sizeof(label), " | ETA %02lld:%02lld", seconds / 60, seconds % 60); + return label; + } + +public: + ~DownloadDisplay() { clear(); } + + void clear() { + if (line_width_ > 0) { + std::fprintf(stderr, "\r%*s\r", line_width_, ""); + std::fflush(stderr); + line_width_ = 0; + } + } + + void update(const sd::download::Progress& progress) { + if (log_level > SD_LOG_INFO) + return; + const auto now = Clock::now(); + const bool finished = progress.files_completed == progress.files_total; + const double rate = transfer_rate({now, progress.transferred}, finished); + const bool known = progress.total > 0 || finished; + const double fraction = progress.total > 0 + ? std::clamp(double(progress.completed) / double(progress.total), 0.0, 1.0) + : (finished ? 1.0 : 0.0); + const std::string percent = known ? std::to_string(static_cast(fraction * 100)) + "%" : " --"; + char amount[64]; + constexpr double mib = 1024 * 1024; + if (progress.total > 0) + std::snprintf(amount, sizeof(amount), "%.1f/%.1f MiB", progress.completed / mib, progress.total / mib); + else + std::snprintf(amount, sizeof(amount), "%.1f MiB", progress.completed / mib); + + char speed[32]; + if (rate >= mib) + std::snprintf(speed, sizeof(speed), "%.1f MiB/s", rate / mib); + else + std::snprintf(speed, sizeof(speed), "%.1f KiB/s", rate / 1024.0); + const auto eta = finished ? std::string{} : download_eta(progress, rate); + char summary[160]; + const int summary_width = std::snprintf(summary, sizeof(summary), "] %4s %s | %s%s%s (%zu/%zu files)", + percent.c_str(), amount, speed, finished ? " avg" : "", eta.c_str(), + progress.files_completed, progress.files_total); + constexpr char prefix[] = "Download ["; + constexpr int max_width = 40; + const int columns = terminal_ ? terminal_columns() : 0; + const int available = columns > 0 ? columns - static_cast(sizeof(prefix)) - summary_width : max_width; + const bool redraw = terminal_ && available > 0; + if (!redraw && !finished && now - last_update_ < std::chrono::seconds(2)) + return; + last_update_ = now; + + const int width = std::clamp(available, 0, max_width); + const int filled = static_cast(fraction * width); + std::string bar(filled, '='); + bar.resize(width, ' '); + clear(); + const bool same_line = redraw && !finished; + const int written = std::fprintf(stderr, "%s%s%s%s", prefix, bar.c_str(), summary, same_line ? "" : "\n"); + line_width_ = same_line ? written : 0; + std::fflush(stderr); + } +}; + int DGLModeParams::run(const SDContextParams& options, bool embed_metadata) const { try { if (script_path.empty()) { @@ -118,11 +273,22 @@ int DGLModeParams::run(const SDContextParams& options, bool embed_metadata) cons std::string source{std::istreambuf_iterator(file), std::istreambuf_iterator()}; if (!script_args.empty()) apply_dgl_args(source, script_args); - if (check_only) { + if (check_only || download.autodl.value_or(false)) check_dgl(sd_dgl_check(source.c_str(), false) == SD_STATUS_OK); + if (check_only) { std::cout << "DGL syntax and types are valid. Models were not loaded.\n"; return 0; } + if (download.autodl.value_or(false)) { + DownloadDisplay display; + sd::download::Events events; + events.log = [&display](const std::string& message) { + display.clear(); + LOG_INFO("%s", message.c_str()); + }; + events.progress = [&display](const sd::download::Progress& progress) { display.update(progress); }; + DGLModelSources(download).prepare(source, events); + } if (!options.register_rpc_devices()) return 1; auto* raw_context = run_once.value_or(true) ? sd_dgl_ctx_create_once() : sd_dgl_ctx_create(); diff --git a/examples/cli/dgl.h b/examples/cli/dgl.h index a03c0c66a6..ece25ea83a 100644 --- a/examples/cli/dgl.h +++ b/examples/cli/dgl.h @@ -7,6 +7,8 @@ #include #include +#include "common/dgl_model_sources.h" + struct ArgOptions; struct SDContextParams; @@ -24,6 +26,7 @@ struct DGLModeParams { bool check_only = false; std::optional run_once; bool list_builtins = false; + DGLModelSourceOptions download; ArgOptions get_options(); bool has_options() const; diff --git a/examples/cli/main.cpp b/examples/cli/main.cpp index dd9089f11c..46517ebaaa 100644 --- a/examples/cli/main.cpp +++ b/examples/cli/main.cpp @@ -49,12 +49,12 @@ struct SDCliParams { std::string preview_method = "none"; int preview_interval = 1; std::string preview_path; - int preview_fps = 16; - bool preview_noisy = false; - bool color = false; - bool metadata_raw = false; - bool metadata_brief = false; - bool metadata_all = false; + int preview_fps = 16; + bool preview_noisy = false; + bool color = false; + bool metadata_raw = false; + bool metadata_brief = false; + bool metadata_all = false; std::string imatrix_out; std::vector imatrix_in; diff --git a/examples/common/dgl_model_sources.cpp b/examples/common/dgl_model_sources.cpp new file mode 100644 index 0000000000..68aee78ba1 --- /dev/null +++ b/examples/common/dgl_model_sources.cpp @@ -0,0 +1,307 @@ +#include "dgl_model_sources.h" + +#include +#include +#include +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#endif + +#include "common.h" + +namespace fs = std::filesystem; + +void DGLModelSourceOptions::add_options(ArgOptions& options) { + options.manual_options.push_back({"", "--autodl", "on|off (default: off). Download missing DGL models", + [this](int argc, const char** argv, int index) { + const std::string_view value = index + 1 < argc ? argv[index + 1] : ""; + if (value != "on" && value != "off") { + LOG_ERROR("--autodl requires on or off"); + return -1; + } + autodl = value == "on"; + return 1; + }}); + options.manual_options.push_back({"", "--download-threads", + "maximum concurrent DGL transfers (default: " + std::to_string(sd::download::default_threads()) + + ", range: 1-" + std::to_string(sd::download::max_threads) + ")", + [this](int argc, const char** argv, int index) { + const std::string_view value = index + 1 < argc ? argv[index + 1] : ""; + int count = 0; + const auto end = value.data() + value.size(); + const auto parsed = std::from_chars(value.data(), end, count); + if (parsed.ec != std::errc{} || parsed.ptr != end || count < 1 || count > sd::download::max_threads) { + LOG_ERROR("--download-threads requires a number from 1 to %d", sd::download::max_threads); + return -1; + } + threads = count; + return 1; + }}); + options.manual_options.push_back({"", "--allow-download-dir", "allow downloads to this directory (repeatable)", + [this](int argc, const char** argv, int index) { + if (++index >= argc || !argv[index][0]) + return -1; + dirs.push_back(argv_to_utf8(index, argv)); + return 1; + }}); + options.manual_options.push_back({"", "--allow-download-host", "allow HTTPS downloads from this hostname (repeatable)", + [this](int argc, const char** argv, int index) { + if (++index >= argc || !sd::download::valid_host(argv[index])) { + LOG_ERROR("--allow-download-host requires a hostname"); + return -1; + } + hosts.push_back(sd::download::ascii_lowercase(argv[index])); + return 1; + }}); +} + +bool DGLModelSourceOptions::has_options() const { + return autodl.has_value() || threads.has_value() || !dirs.empty() || !hosts.empty(); +} + +static bool same_component(const fs::path& lhs, const fs::path& rhs) { +#ifdef _WIN32 + return CompareStringOrdinal(lhs.c_str(), -1, rhs.c_str(), -1, TRUE) == CSTR_EQUAL; +#else + return lhs == rhs; +#endif +} + +static bool inside(const fs::path& root, const fs::path& path) { + const auto [parent, child] = std::mismatch(root.begin(), root.end(), path.begin(), path.end(), same_component); + return parent == root.end() && child != path.end(); +} + +static fs::path canonical_download_root(const fs::path& path) { + auto root = fs::weakly_canonical(fs::absolute(path)); + if (!root.has_filename() && root.has_relative_path()) + root = root.parent_path(); + const auto status = fs::status(root); + if (fs::exists(status) && !fs::is_directory(status)) + throw std::runtime_error("download root is not a directory: " + path.u8string()); + return root; +} + +DGLModelSources::DGLModelSources(const DGLModelSourceOptions& options, std::vector model_roots) + : cwd_(fs::canonical(fs::current_path())), model_roots_(std::move(model_roots)), hosts_(options.hosts), threads_(options.threads.value_or(sd::download::default_threads())) { + write_roots_.push_back(cwd_); + for (const auto& dir : options.dirs) + write_roots_.push_back(canonical_download_root(cwd_ / fs::u8path(dir))); +} + +static void check_model_host(std::string_view host, const std::vector& extra) { + // https://huggingface.co/docs/hub/en/models-downloading#downloading-behind-a-proxy-or-firewall + constexpr std::string_view huggingface[] = { + "huggingface.co", + "cdn-lfs.huggingface.co", + "cdn-lfs.hf.co", + "cdn-lfs-us-1.hf.co", + "cdn-lfs-eu-1.hf.co", + "cas-bridge.xethub.hf.co", + "cas-server.xethub.hf.co", + "cas-server.xethub-eu.hf.co", + "transfer.xethub.hf.co", + "transfer.xethub-eu.hf.co", + "us.aws.cdn.hf.co", + "us.gcp.cdn.hf.co", + }; + if (std::find(std::begin(huggingface), std::end(huggingface), host) == std::end(huggingface) && + std::find(extra.begin(), extra.end(), host) == extra.end()) + throw std::runtime_error("download hostname is not allowed: " + std::string(host) + " (use --allow-download-host)"); +} + +struct DGLModelSource { + std::string path; + std::string url; + std::string sha256; + size_t line = 0; +}; + +static constexpr std::string_view whitespace = " \t\r"; + +static std::string_view trim_source(std::string_view value) { + const auto first = value.find_first_not_of(whitespace); + if (first == std::string_view::npos) + return {}; + return value.substr(first, value.find_last_not_of(whitespace) - first + 1); +} + +static std::string source_location(size_t line) { + return "DGL model-source line " + std::to_string(line); +} + +static std::runtime_error source_error(size_t line, const std::string& message) { + return std::runtime_error(source_location(line) + ": " + message); +} + +static std::string parse_source_string(std::string_view& rest) { + if (rest.empty() || rest.front() != '"') + throw std::runtime_error("expected a double-quoted string"); + size_t end = 1; + while (end < rest.size() && rest[end] != '"') { + if (rest[end++] == '\\' && end < rest.size()) + ++end; + } + if (end == rest.size()) + throw std::runtime_error("unterminated string"); + auto str = nlohmann::json::parse(rest.begin(), rest.begin() + end + 1, nullptr, false); + if (!str.is_string()) + throw std::runtime_error("invalid string escape or UTF-8"); + rest.remove_prefix(end + 1); + auto value = str.get(); + if (value.empty() || std::any_of(value.begin(), value.end(), [](unsigned char c) { return c < 32 || c == 127; })) + throw std::runtime_error("expected a nonempty string without control characters"); + return value; +} + +static DGLModelSource parse_model_source(std::string_view rest, size_t line) { + DGLModelSource entry; + entry.line = line; + while (true) { + const auto colon = rest.find(':'); + if (colon == std::string_view::npos) + throw std::runtime_error("expected a key and ':'"); + const auto key = trim_source(rest.substr(0, colon)); + rest = trim_source(rest.substr(colon + 1)); + if (key == "path" && entry.path.empty()) { + entry.path = parse_source_string(rest); + } else if (key == "url" && entry.url.empty()) { + entry.url = parse_source_string(rest); + } else if (key == "sha256" && entry.sha256.empty()) { + const auto end = rest.find(','); + entry.sha256 = sd::download::ascii_lowercase(trim_source(rest.substr(0, end))); + if (entry.sha256.size() != 64 || entry.sha256.find_first_not_of("0123456789abcdef") != std::string::npos) + throw std::runtime_error("sha256 must contain 64 hexadecimal digits"); + rest = end == std::string_view::npos ? std::string_view{} : rest.substr(end); + } else { + throw std::runtime_error("unknown or repeated field"); + } + rest = trim_source(rest); + if (rest.empty()) + break; + if (rest.front() != ',') + throw std::runtime_error("expected ',' between fields"); + rest.remove_prefix(1); + } + if (entry.path.empty() || entry.url.empty()) + throw std::runtime_error("path and url are required"); + return entry; +} + +static std::vector model_sources(std::string_view source) { + if (source.substr(0, 3) == "\xef\xbb\xbf") + source.remove_prefix(3); + constexpr std::string_view directive = "model-source:"; + std::vector entries; + size_t line_number = 0; + while (!source.empty()) { + ++line_number; + const auto end = source.find('\n'); + auto line = trim_source(source.substr(0, end)); + source = end == std::string_view::npos ? std::string_view{} : source.substr(end + 1); + if (line.empty() || line.substr(0, 2) == "//") + continue; + if (line.front() != '#') + break; + line = trim_source(line.substr(1)); + if (line.substr(0, directive.size()) != directive) + continue; + try { + entries.push_back(parse_model_source(line.substr(directive.size()), line_number)); + } catch (const std::exception& error) { + throw source_error(line_number, error.what()); + } + } + return entries; +} + +static fs::path model_source_path(const fs::path& cwd, const std::string& value) { + auto path = fs::u8path(value); +#ifdef _WIN32 + path.make_preferred(); + if (path.native().compare(0, 4, L"\\\\?\\") == 0 || path.native().compare(0, 4, L"\\\\.\\") == 0 || + (path.has_root_name() && !path.has_root_directory())) + throw std::runtime_error("invalid Windows model path"); + for (const auto& part : path.relative_path()) { + const auto name = part.u8string(); + if (name.empty() || name == "." || name == "..") + continue; + if (name.back() == ' ' || name.back() == '.' || name.find_first_of(":*?<>|\"") != std::string::npos) + throw std::runtime_error("invalid Windows model path component"); + auto device = sd::download::ascii_lowercase(name.substr(0, name.find('.'))); + device.erase(device.find_last_not_of(' ') + 1); + if (device == "con" || device == "prn" || device == "aux" || device == "nul" || + device == "conin$" || device == "conout$" || + ((device.compare(0, 3, "com") == 0 || device.compare(0, 3, "lpt") == 0) && + device.size() >= 4 && (device.substr(3) == "\xc2\xb9" || device.substr(3) == "\xc2\xb2" || device.substr(3) == "\xc2\xb3" || (device.size() == 4 && device.back() >= '0' && device.back() <= '9')))) + throw std::runtime_error("Windows device names cannot be model paths"); + } +#endif + return cwd / path; +} + +bool DGLModelSources::prepare(std::string_view source, const sd::download::Events& events) const { + struct Pending { + fs::path path; + const DGLModelSource* entry; + }; + const auto entries = model_sources(source); + std::vector pending; + for (const auto& entry : entries) { + if (events.cancelled && events.cancelled()) + return false; + if (entry.sha256.empty()) + continue; + try { + const auto path = model_source_path(cwd_, entry.path); +#ifdef _WIN32 + // Checking an untrusted UNC path can contact its SMB server before any HTTPS request. + if (path.native().compare(0, 2, L"\\\\") == 0 && + std::none_of(write_roots_.begin(), write_roots_.end(), + [&](const auto& root) { return inside(root, path.lexically_normal()); })) + throw std::runtime_error("UNC model path requires an explicitly allowed download directory"); +#endif + if (fs::is_regular_file(fs::status(path))) + continue; + if (fs::symlink_status(path).type() != fs::file_type::not_found) + throw std::runtime_error("target is not a regular file: " + entry.path); + const auto target = fs::weakly_canonical(path); + if (std::any_of(target.begin(), target.end(), [](const auto& part) { + return sd::download::ascii_lowercase(part.u8string()) == sd::download::cache_directory; + })) + throw std::runtime_error("model target is inside the download cache: " + entry.path); + if (!model_roots_.empty() && std::none_of(model_roots_.begin(), model_roots_.end(), + [&](const auto& root) { return inside(root, target); })) + throw std::runtime_error("download target is outside the server model directories: " + entry.path); + if (std::none_of(write_roots_.begin(), write_roots_.end(), [&](const auto& root) { return inside(root, target); })) + throw std::runtime_error("download target is outside the allowed directories: " + entry.path + + " (use --allow-download-dir)"); + auto previous = std::find_if(pending.begin(), pending.end(), [&](const auto& item) { + return same_component(item.path, target); + }); + if (previous != pending.end()) { + if (previous->entry->url != entry.url || previous->entry->sha256 != entry.sha256) + throw std::runtime_error("conflicting declaration for " + entry.path + + " on line " + std::to_string(previous->entry->line)); + continue; + } + pending.push_back({target, &entry}); + } catch (const std::exception& error) { + throw source_error(entry.line, error.what()); + } + } + + std::vector requests; + requests.reserve(pending.size()); + for (const auto& item : pending) { + const auto& entry = *item.entry; + requests.push_back({item.path, entry.url, entry.sha256, source_location(entry.line) + ": " + entry.path}); + } + return sd::download::fetch( + requests, [&](std::string_view host) { check_model_host(host, hosts_); }, threads_, events); +} diff --git a/examples/common/dgl_model_sources.h b/examples/common/dgl_model_sources.h new file mode 100644 index 0000000000..206dbf58e2 --- /dev/null +++ b/examples/common/dgl_model_sources.h @@ -0,0 +1,38 @@ +#ifndef __SD_EXAMPLES_COMMON_DGL_MODEL_SOURCES_H__ +#define __SD_EXAMPLES_COMMON_DGL_MODEL_SOURCES_H__ + +#include +#include +#include +#include +#include + +#include "download.h" + +struct ArgOptions; + +struct DGLModelSourceOptions { + std::optional autodl; + std::optional threads; + std::vector dirs; + std::vector hosts; + + void add_options(ArgOptions& options); + bool has_options() const; +}; + +class DGLModelSources { + std::filesystem::path cwd_; + std::vector write_roots_; + std::vector model_roots_; + std::vector hosts_; + int threads_; + +public: + explicit DGLModelSources(const DGLModelSourceOptions& options, + std::vector model_roots = {}); + // Returns false when cancelled. + bool prepare(std::string_view source, const sd::download::Events& events = {}) const; +}; + +#endif diff --git a/examples/common/download.cpp b/examples/common/download.cpp new file mode 100644 index 0000000000..fc39df0346 --- /dev/null +++ b/examples/common/download.cpp @@ -0,0 +1,146 @@ +#include "download.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "download_http.h" + +namespace sd::download { + + int default_threads() { + return static_cast(std::clamp(std::thread::hardware_concurrency(), 1u, 8u)); + } + + std::string ascii_lowercase(std::string_view value) { + std::string result(value); + for (char& c : result) + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + return result; + } + + bool valid_host(std::string_view host) { + if (host.empty() || host.size() > 253 || host.back() == '.') + return false; + while (!host.empty()) { + const auto dot = host.find('.'); + const auto label = host.substr(0, dot); + if (label.empty() || label.size() > 63 || label.front() == '-' || label.back() == '-' || + !std::all_of(label.begin(), label.end(), [](unsigned char c) { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-'; + })) + return false; + if (dot == std::string_view::npos) + break; + host.remove_prefix(dot + 1); + } + return true; + } + + bool fetch(const std::vector& requests, const HostCheck& check_host, int threads, const Events& events) { + if (requests.empty()) + return true; + if (threads < 1 || threads > max_threads) + throw std::invalid_argument("invalid download thread count"); +#ifdef CPPHTTPLIB_OPENSSL_SUPPORT + if (!check_host) + throw std::invalid_argument("missing download host policy"); + + struct FileProgress { + int64_t completed = 0; + int64_t total = 0; + uint64_t transferred = 0; + bool finished = false; + }; + std::vector files(requests.size()); + std::mutex output_mutex; + const auto report = [&] { + if (!events.progress) + return; + Progress progress; + progress.files_total = files.size(); + bool totals_known = true; + constexpr auto limit = std::numeric_limits::max(); + for (const auto& file : files) { + progress.completed += std::min(file.completed, limit - progress.completed); + progress.transferred += std::min(file.transferred, std::numeric_limits::max() - progress.transferred); + if ((!file.finished && file.total == 0) || file.total > limit - progress.total) + totals_known = false; + else + progress.total += file.total; + progress.files_completed += file.finished; + } + if (!totals_known) + progress.total = 0; + progress.detail = files.size() == 1 ? requests.front().path.filename().u8string() + : std::to_string(progress.files_completed) + "/" + std::to_string(files.size()) + " files"; + events.progress(progress); + }; + const auto log = [&](const std::string& message) { + std::lock_guard lock(output_mutex); + if (events.log) + events.log(message); + }; + std::atomic stopped{false}; + std::atomic next{0}; + const auto cancelled = [&] { return stopped.load() || (events.cancelled && events.cancelled()); }; + const int workers = static_cast(std::min(threads, requests.size())); + const auto worker = [&](int slot) { + const int file_threads = threads / workers + (slot < threads % workers ? 1 : 0); + while (!cancelled()) { + const auto index = next.fetch_add(1); + if (index >= requests.size()) + return; + const auto& request = requests[index]; + const FileEvents transfer{cancelled, log, [&](int64_t completed, int64_t total, uint64_t transferred) { + std::lock_guard lock(output_mutex); + files[index] = {completed, total, transferred, false}; + report(); + }}; + try { + if (!fetch_file(request, check_host, file_threads, transfer)) { + stopped.store(true); + return; + } + std::lock_guard lock(output_mutex); + auto& file = files[index]; + file.total = file.completed; + file.finished = true; + report(); + } catch (const std::exception& error) { + stopped.store(true); + const auto context = request.error_context.empty() ? request.path.u8string() : request.error_context; + throw std::runtime_error(context + ": " + error.what()); + } catch (...) { + stopped.store(true); + throw; + } + } + }; + + std::vector> background; + background.reserve(workers - 1); + try { + for (int slot = 1; slot < workers; ++slot) + background.push_back(std::async(std::launch::async, worker, slot)); + worker(0); + for (auto& task : background) + task.get(); + } catch (...) { + stopped.store(true); + throw; + } + return !cancelled(); +#else + (void)check_host; + (void)events; + throw std::runtime_error("downloads require a build with SD_OPENSSL enabled and OpenSSL available"); +#endif + } + +} // namespace sd::download diff --git a/examples/common/download.h b/examples/common/download.h new file mode 100644 index 0000000000..89ab8b3c7d --- /dev/null +++ b/examples/common/download.h @@ -0,0 +1,54 @@ +#ifndef __SD_EXAMPLES_COMMON_DOWNLOAD_H__ +#define __SD_EXAMPLES_COMMON_DOWNLOAD_H__ + +#include +#include +#include +#include +#include +#include + +namespace sd::download { + + inline constexpr int max_threads = 256; + // Keep the original directory so existing checkpoints can be resumed. + inline constexpr char cache_directory[] = ".dgl-download-cache"; + + int default_threads(); + std::string ascii_lowercase(std::string_view value); + bool valid_host(std::string_view host); + + struct Request { + std::filesystem::path path; + std::string url; + std::string sha256; + std::string error_context; + }; + + struct Progress { + std::string detail; + int64_t completed = 0; + int64_t total = 0; + uint64_t transferred = 0; + size_t files_completed = 0; + size_t files_total = 0; + }; + + struct Events { + // Cancellation may be queried by any worker. Output callbacks are serialized. + std::function cancelled; + std::function log; + std::function progress; + }; + + // Called on the original host and each redirect. Throw to reject a host. + // The callback may be invoked concurrently. + using HostCheck = std::function; + + // Supply distinct authorized absolute paths and lowercase SHA-256 digests. + // Returns false when cancelled. + bool fetch(const std::vector& requests, const HostCheck& check_host, int threads, const Events& events = {}); + +} // namespace sd::download + +#endif diff --git a/examples/common/download_file.cpp b/examples/common/download_file.cpp new file mode 100644 index 0000000000..dee4269365 --- /dev/null +++ b/examples/common/download_file.cpp @@ -0,0 +1,352 @@ +#if !defined(_WIN32) && !defined(_FILE_OFFSET_BITS) +#define _FILE_OFFSET_BITS 64 +#endif + +#include "download_file.h" + +#include "download.h" + +#include +#include +#include +#include +#include +#include + +#include + +#ifdef _WIN32 +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include +#include +#else +#include +#include +#include +#include +#include +#endif + +namespace sd::download { + + namespace fs = std::filesystem; + + static std::string temporary_name() { + std::array random{}; + if (RAND_bytes(random.data(), int(random.size())) != 1) + throw std::runtime_error("cannot create a temporary download name"); + const char hex[] = "0123456789abcdef"; + std::string result = ".download-"; + for (auto byte : random) { + result += hex[byte >> 4]; + result += hex[byte & 15]; + } + return result + ".part"; + } + + struct StagedFile::File { + fs::path target; + std::string temporary; + bool owned = false; + bool resumable = false; + bool keep = false; +#ifdef _WIN32 + std::vector parents; + HANDLE handle = INVALID_HANDLE_VALUE; +#else + int parent = -1; + int cache = -1; + std::FILE* stream = nullptr; + int temporary_dir() const { return cache >= 0 ? cache : parent; } +#endif + + explicit File(const fs::path& path) + : target(path) {} + ~File(); + void open(const std::string& checkpoint); + }; + +#ifdef _WIN32 + static std::system_error file_error(const char* message) { + return std::system_error(int(GetLastError()), std::system_category(), message); + } + + void StagedFile::File::open(const std::string& checkpoint) { + auto path = target.root_path(); + parents.reserve(std::distance(target.begin(), target.end()) + 1); + const auto hold_directory = [&](const fs::path& part) { + path /= part; + // Hold each parent without sharing delete so path-based operations stay in this tree. + const auto open_directory = [&] { + return CreateFileW(path.c_str(), FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + }; + auto directory = open_directory(); + if (directory == INVALID_HANDLE_VALUE && GetLastError() == ERROR_FILE_NOT_FOUND) { + if (!CreateDirectoryW(path.c_str(), nullptr) && GetLastError() != ERROR_ALREADY_EXISTS) + throw file_error("cannot create download directory"); + directory = open_directory(); + } + if (directory == INVALID_HANDLE_VALUE) + throw file_error("cannot open download directory"); + parents.push_back(directory); + FILE_ATTRIBUTE_TAG_INFO info{}; + if (!GetFileInformationByHandleEx(directory, FileAttributeTagInfo, &info, sizeof(info))) + throw file_error("cannot inspect download directory"); + if (!(info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)) + throw std::runtime_error("unsafe download directory"); + }; + for (const auto& part : target.parent_path().relative_path()) + hold_directory(part); + + constexpr DWORD access = GENERIC_READ | GENERIC_WRITE | DELETE; + if (!checkpoint.empty()) { + hold_directory(fs::u8path(cache_directory)); + temporary = checkpoint; + handle = CreateFileW((path / fs::u8path(temporary)).c_str(), access, 0, nullptr, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OPEN_REPARSE_POINT, nullptr); + if (handle != INVALID_HANDLE_VALUE) { + BY_HANDLE_FILE_INFORMATION info{}; + if (!GetFileInformationByHandle(handle, &info)) + throw file_error("cannot inspect download checkpoint"); + if (GetFileType(handle) != FILE_TYPE_DISK || info.nNumberOfLinks != 1 || + (info.dwFileAttributes & (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_REPARSE_POINT))) + throw std::runtime_error("unsafe download checkpoint"); + owned = resumable = keep = true; + // The checkpoint footer sits past the end of the payload. + DWORD bytes = 0; + DeviceIoControl(handle, FSCTL_SET_SPARSE, nullptr, 0, nullptr, 0, &bytes, nullptr); + return; + } + if (GetLastError() != ERROR_SHARING_VIOLATION) + throw file_error("cannot open download checkpoint"); + } + temporary = temporary_name(); + const auto path_tmp = path / fs::u8path(temporary); + handle = CreateFileW(path_tmp.c_str(), access, 0, nullptr, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + if (handle == INVALID_HANDLE_VALUE) + throw file_error("cannot create temporary download file"); + owned = true; + } + + StagedFile::File::~File() { + if (handle != INVALID_HANDLE_VALUE) { + if (owned && !keep) { + FILE_DISPOSITION_INFO discard{TRUE}; + SetFileInformationByHandle(handle, FileDispositionInfo, &discard, sizeof(discard)); + } + CloseHandle(handle); + } + for (auto it = parents.rbegin(); it != parents.rend(); ++it) + CloseHandle(*it); + } + + bool StagedFile::write(const char* data, size_t size) { + while (size) { + const auto chunk = DWORD(std::min(size, 1 << 20)); + DWORD written = 0; + if (!WriteFile(file_->handle, data, chunk, &written, nullptr) || written != chunk) + return false; + data += written; + size -= written; + } + return true; + } + + bool StagedFile::seek(int64_t offset) { + LARGE_INTEGER position{}; + position.QuadPart = offset; + return SetFilePointerEx(file_->handle, position, nullptr, FILE_BEGIN); + } + + bool StagedFile::read(char* data, size_t size) { + DWORD read = 0; + return ReadFile(file_->handle, data, DWORD(size), &read, nullptr) && read == size; + } + + int64_t StagedFile::size() const { + LARGE_INTEGER length{}; + if (!GetFileSizeEx(file_->handle, &length)) + throw file_error("cannot get download size"); + return length.QuadPart; + } + + void StagedFile::resize(int64_t size) { + if (!seek(size) || !SetEndOfFile(file_->handle)) + throw file_error("cannot resize download"); + } + + void StagedFile::publish() { + if (!FlushFileBuffers(file_->handle)) + throw file_error("cannot flush download"); + const auto& target = file_->target.native(); + const auto bytes = target.size() * sizeof(wchar_t); + const auto buffer_size = sizeof(FILE_RENAME_INFO) + bytes; + std::vector storage((buffer_size + sizeof(FILE_RENAME_INFO) - 1) / sizeof(FILE_RENAME_INFO)); + auto& rename = storage.front(); + rename.FileNameLength = DWORD(bytes); + std::copy(target.begin(), target.end(), reinterpret_cast(reinterpret_cast(&rename) + offsetof(FILE_RENAME_INFO, FileName))); + if (!SetFileInformationByHandle(file_->handle, FileRenameInfo, &rename, DWORD(buffer_size))) { + const auto error = file_error("cannot publish download"); + if (!fs::is_regular_file(fs::symlink_status(file_->target))) + throw error; + return; + } + file_->owned = false; + } +#else + static std::system_error file_error(const char* message) { + return std::system_error(errno, std::generic_category(), message); + } + + void StagedFile::File::open(const std::string& checkpoint) { + constexpr int directory_flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC; + parent = ::open(target.root_path().c_str(), directory_flags); + if (parent < 0) + throw file_error("cannot open download root"); + for (const auto& part : target.parent_path().relative_path()) { + auto child = openat(parent, part.c_str(), directory_flags); + if (child < 0 && errno == ENOENT) { + if (mkdirat(parent, part.c_str(), 0777) < 0 && errno != EEXIST) + throw file_error("cannot create download directory"); + child = openat(parent, part.c_str(), directory_flags); + } + if (child < 0) + throw file_error("cannot open download directory"); + close(parent); + parent = child; + } + int fd = -1; + if (!checkpoint.empty()) { + if (mkdirat(parent, cache_directory, 0700) < 0 && errno != EEXIST) + throw file_error("cannot create download cache"); + cache = openat(parent, cache_directory, directory_flags); + if (cache < 0) + throw file_error("cannot open download cache"); + struct stat status{}; + if (fstat(cache, &status) < 0) + throw file_error("cannot inspect download cache"); + if (status.st_uid != geteuid() || (status.st_mode & 077) != 0) + throw std::runtime_error("unsafe download cache permissions"); + + temporary = checkpoint; + fd = openat(cache, temporary.c_str(), O_RDWR | O_CREAT | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC, 0644); + if (fd < 0) + throw file_error("cannot open download checkpoint"); + if (fstat(fd, &status) < 0) { + const auto error = file_error("cannot inspect download checkpoint"); + close(fd); + throw error; + } + if (!S_ISREG(status.st_mode) || status.st_uid != geteuid()) { + close(fd); + throw std::runtime_error("unsafe download checkpoint"); + } + if (flock(fd, LOCK_EX | LOCK_NB) < 0) { + const auto error = file_error("cannot lock download checkpoint"); + close(fd); + if (error.code().value() != EWOULDBLOCK && error.code().value() != EAGAIN) + throw error; + fd = -1; + } else { + struct stat current{}; + // A waiter may have opened this inode before another process published it. + if (fstatat(cache, temporary.c_str(), ¤t, AT_SYMLINK_NOFOLLOW) == 0 && + current.st_dev == status.st_dev && current.st_ino == status.st_ino && current.st_nlink == 1) { + owned = resumable = keep = true; + } else { + close(fd); + fd = -1; + } + } + } + if (fd < 0) { + temporary = temporary_name(); + fd = openat(temporary_dir(), temporary.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644); + if (fd < 0) + throw file_error("cannot create temporary download file"); + owned = true; + } + stream = fdopen(fd, "r+b"); + if (!stream) { + const auto error = file_error("cannot open temporary download stream"); + close(fd); + throw error; + } + } + + StagedFile::File::~File() { + if (owned && !keep) + unlinkat(temporary_dir(), temporary.c_str(), 0); + if (stream) + std::fclose(stream); + if (cache >= 0) + close(cache); + if (parent >= 0) + close(parent); + } + + bool StagedFile::write(const char* data, size_t size) { + return std::fwrite(data, 1, size, file_->stream) == size; + } + + bool StagedFile::seek(int64_t offset) { + return fseeko(file_->stream, offset, SEEK_SET) == 0; + } + + bool StagedFile::read(char* data, size_t size) { + return std::fread(data, 1, size, file_->stream) == size; + } + + int64_t StagedFile::size() const { + struct stat status{}; + if (fstat(fileno(file_->stream), &status) < 0) + throw file_error("cannot get download size"); + return status.st_size; + } + + void StagedFile::resize(int64_t size) { + if (std::fflush(file_->stream) != 0 || ftruncate(fileno(file_->stream), size) < 0) + throw file_error("cannot resize download"); + } + + void StagedFile::publish() { + if (std::fflush(file_->stream) != 0) + throw file_error("cannot flush download"); + const int fd = fileno(file_->stream); + struct stat staged {}; + if (fstat(fd, &staged) < 0) + throw file_error("cannot inspect staged download"); + // Checkpoints created by older builds may still have shared write permissions. + constexpr mode_t shared_write = S_IWGRP | S_IWOTH; + if ((staged.st_mode & shared_write) != 0 && fchmod(fd, (staged.st_mode & 0777) & ~shared_write) < 0) + throw file_error("cannot restrict download permissions"); + const auto name = file_->target.filename(); + if (linkat(file_->temporary_dir(), file_->temporary.c_str(), file_->parent, name.c_str(), 0) < 0) { + const auto error = file_error("cannot publish download"); + struct stat status {}; + if (errno != EEXIST || fstatat(file_->parent, name.c_str(), &status, AT_SYMLINK_NOFOLLOW) < 0 || + !S_ISREG(status.st_mode)) + throw error; + } + } +#endif + + StagedFile::StagedFile(const fs::path& target, const std::string& checkpoint) + : file_(std::make_unique(target)) { + file_->open(checkpoint); + } + + StagedFile::~StagedFile() = default; + + bool StagedFile::persistent() const { + return file_->resumable; + } + + void StagedFile::discard_checkpoint() { + file_->keep = false; + } + +} // namespace sd::download diff --git a/examples/common/download_file.h b/examples/common/download_file.h new file mode 100644 index 0000000000..2b7f17bdcf --- /dev/null +++ b/examples/common/download_file.h @@ -0,0 +1,32 @@ +#ifndef __SD_EXAMPLES_COMMON_DOWNLOAD_FILE_H__ +#define __SD_EXAMPLES_COMMON_DOWNLOAD_FILE_H__ + +#include +#include +#include +#include +#include + +namespace sd::download { + + class StagedFile { + struct File; + std::unique_ptr file_; + + public: + explicit StagedFile(const std::filesystem::path& target, const std::string& checkpoint = {}); + ~StagedFile(); + + bool write(const char* data, size_t size); + bool seek(int64_t offset); + bool read(char* data, size_t size); + int64_t size() const; + void resize(int64_t size); + bool persistent() const; + void discard_checkpoint(); + void publish(); + }; + +} // namespace sd::download + +#endif diff --git a/examples/common/download_http.cpp b/examples/common/download_http.cpp new file mode 100644 index 0000000000..bf0f7ef0cd --- /dev/null +++ b/examples/common/download_http.cpp @@ -0,0 +1,711 @@ +#include "download_http.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "httplib.h" + +#include "download_file.h" + +namespace sd::download { + + struct Url { + std::string host; + int port; + std::string target; + }; + + static constexpr int max_redirects = 5; + static constexpr int64_t min_range_size = 16 * 1024 * 1024; + + static bool invalid_url_character(unsigned char c) { + return c <= 32 || c >= 127 || c == '\\'; + } + + static Url parse_authority(std::string_view authority, int default_port) { + const auto colon = authority.find(':'); + auto host = authority.substr(0, colon); + if (!valid_host(host)) + throw std::runtime_error("invalid URL hostname"); + int port = default_port; + if (colon != std::string_view::npos) { + const auto text = authority.substr(colon + 1); + const auto parsed = std::from_chars(text.data(), text.data() + text.size(), port); + if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size() || port <= 0 || port > 65535) + throw std::runtime_error("invalid URL port"); + } + return {ascii_lowercase(host), port, {}}; + } + + static Url parse_url(std::string_view url) { + if (ascii_lowercase(url.substr(0, 8)) != "https://" || + std::any_of(url.begin(), url.end(), invalid_url_character)) + throw std::runtime_error("expected an HTTPS URL with percent-encoded special characters"); + url.remove_prefix(8); + url = url.substr(0, url.find('#')); + const auto end = url.find_first_of("/?"); + auto parsed = parse_authority(url.substr(0, end), 443); + parsed.target = end != std::string_view::npos && url[end] == '/' ? "" : "/"; + if (end != std::string_view::npos) + parsed.target += url.substr(end); + return parsed; + } + + static std::string normalize_redirect_path(std::string_view target) { + const auto query = target.find('?'); + auto path = target.substr(0, query); + std::vector segments; + path.remove_prefix(1); + while (true) { + const auto slash = path.find('/'); + const auto segment = path.substr(0, slash); + if (segment == ".." && !segments.empty()) + segments.pop_back(); + if (segment != "." && segment != "..") + segments.push_back(segment); + if (slash == std::string_view::npos) { + if (segment == "." || segment == "..") + segments.emplace_back(); + break; + } + path.remove_prefix(slash + 1); + } + std::string result; + for (auto segment : segments) { + result += '/'; + result += segment; + } + if (query != std::string_view::npos) + result += target.substr(query); + return result; + } + + static Url redirect_url(Url current, std::string_view location) { + if (location.empty() || std::any_of(location.begin(), location.end(), invalid_url_character)) + throw std::runtime_error("missing or invalid redirect Location"); + location = location.substr(0, location.find('#')); + if (location.substr(0, 2) == "//") + return parse_url("https:" + std::string(location)); + if (location.substr(0, location.find_first_of("/?")).find(':') != std::string_view::npos) + return parse_url(location); + if (location.empty()) + return current; + + auto path = std::string_view(current.target); + path = path.substr(0, path.find('?')); + if (location.front() == '?') { + current.target = std::string(path) + std::string(location); + } else if (location.front() == '/') { + current.target = normalize_redirect_path(location); + } else { + current.target = normalize_redirect_path(std::string(path.substr(0, path.rfind('/') + 1)) + + std::string(location)); + } + return current; + } + + static std::string proxy_environment(const char* upper, const char* lower) { + const char* value = std::getenv(lower); + if (!value) + value = std::getenv(upper); + return value ? value : ""; + } + + static bool bypass_proxy(std::string_view list, const Url& url) { + while (!list.empty()) { + const auto comma = list.find(','); + auto entry = list.substr(0, comma); + list = comma == std::string_view::npos ? std::string_view{} : list.substr(comma + 1); + const auto start = entry.find_first_not_of(" \t"); + if (start == std::string_view::npos) + continue; + entry = entry.substr(start, entry.find_last_not_of(" \t") - start + 1); + if (entry == "*") + return true; + if (entry.front() == '.') + entry.remove_prefix(1); + const auto colon = entry.find(':'); + if (colon != std::string_view::npos && entry.substr(colon + 1) != std::to_string(url.port)) + continue; + const auto host = ascii_lowercase(entry.substr(0, colon)); + if (!host.empty() && (url.host == host || + (url.host.size() > host.size() && url.host.compare(url.host.size() - host.size() - 1, + host.size() + 1, "." + host) == 0))) + return true; + } + return false; + } + + static void configure_proxy(httplib::SSLClient& client, const Url& url) { + const auto value = proxy_environment("HTTPS_PROXY", "https_proxy"); + if (value.empty() || bypass_proxy(proxy_environment("NO_PROXY", "no_proxy"), url)) + return; + try { + auto proxy = std::string_view(value); + if (proxy.substr(0, 7) == "http://") + proxy.remove_prefix(7); + if (!proxy.empty() && proxy.back() == '/') + proxy.remove_suffix(1); + const auto parsed = parse_authority(proxy, 80); + client.set_proxy(parsed.host, parsed.port); + } catch (const std::exception&) { + throw std::runtime_error("invalid HTTPS_PROXY (expected an HTTP proxy host and port)"); + } + } + + static bool is_redirect(int status) { + return status == 301 || status == 302 || status == 303 || status == 307 || status == 308; + } + + static void set_raw_get_target(httplib::SSLClient& client, const std::string& target) { + // httplib's Get handles proxy CONNECT but normalizes query parameters. Restore + // the original target in its request buffer so CDN signatures survive. + client.set_header_writer([&target](httplib::Stream& stream, httplib::Headers& headers) { + const auto* request = dynamic_cast(&stream); + if (!request) + throw std::runtime_error("cannot preserve the HTTPS request target"); + auto& buffer = const_cast(request->get_buffer()); + if (buffer.compare(0, 4, "GET ") == 0) + buffer = "GET " + target + " HTTP/1.1\r\n"; + return httplib::detail::write_headers(stream, headers); + }); + } + + static std::string log_url(const Url& url) { + const auto query = url.target.find('?'); + return "https://" + url.host + (url.port == 443 ? "" : ":" + std::to_string(url.port)) + + url.target.substr(0, query) + (query == std::string::npos ? "" : "?[redacted]"); + } + + static void configure_client(httplib::SSLClient& client, const Url& url) { + client.set_path_encode(false); + client.enable_server_certificate_verification(true); + client.enable_server_hostname_verification(true); + client.set_connection_timeout(10); + client.set_read_timeout(30); + client.set_write_timeout(10); + client.set_decompress(false); + if (const char* ca = std::getenv("SSL_CERT_FILE"); ca && *ca) + client.set_ca_cert_path(ca); + configure_proxy(client, url); + if (url.target.find('?') != std::string::npos) + set_raw_get_target(client, url.target); + } + + static bool identity_encoding(const httplib::Response& response) { + const auto encoding = response.get_header_value("Content-Encoding"); + return encoding.empty() || ascii_lowercase(encoding) == "identity"; + } + + static constexpr int64_t checkpoint_interval = 1024 * 1024; + using Sha256 = std::array; + + static Sha256 hash_key(std::string_view value) { + Sha256 hash{}; + if (!SHA256(reinterpret_cast(value.data()), value.size(), hash.data())) + throw std::runtime_error("cannot hash download checkpoint key"); + return hash; + } + + static std::string hex_digest(const Sha256& hash) { + constexpr char hex[] = "0123456789abcdef"; + std::string result; + for (auto byte : hash) { + result += hex[byte >> 4]; + result += hex[byte & 15]; + } + return result; + } + + struct DownloadRanges { + struct Footer { + std::array version; + Sha256 validator; + int64_t count; + std::array received; + }; + static constexpr std::array version{'S', 'D', 'D', 'G', 'L', 'D', 'L', '1'}; + + int64_t total; + Footer footer; + + int count() const { return static_cast(footer.count); } + int64_t first(int index) const { return (total / count()) * index; } + int64_t end(int index) const { return index + 1 == count() ? total : first(index + 1); } + + int64_t completed() const { + int64_t bytes = 0; + for (int i = 0; i < count(); ++i) + bytes += footer.received[i]; + return bytes; + } + + DownloadRanges(StagedFile& file, int64_t length, int count, const std::string& etag) + : total(length), footer{version, hash_key(etag), count, {}} { + if (!file.persistent()) + return; + + const auto size = file.size(); + if (size == total) { + // A process may have stopped between removing the footer and publishing. + footer.count = 1; + footer.received[0] = total; + return; + } + Footer saved{}; + // The footer starts after the payload, so verified data can be + // published by truncating the footer and renaming the same file. + if (size == total + static_cast(sizeof(Footer)) && + file.seek(total) && file.read(reinterpret_cast(&saved), sizeof(saved)) && + saved.version == version && saved.validator == footer.validator && + saved.count >= 1 && saved.count <= max_threads && saved.count <= total) { + const auto fresh = footer; + footer = saved; + int i = 0; + while (i < this->count() && footer.received[i] >= 0 && footer.received[i] <= end(i) - first(i)) + ++i; + if (i == this->count()) + return; + footer = fresh; + } + file.resize(0); + } + + void save(StagedFile& file, int64_t position) const { + if (file.persistent() && + (!file.seek(total) || !file.write(reinterpret_cast(&footer), sizeof(footer)) || !file.seek(position))) + throw std::runtime_error("cannot save download checkpoint"); + } + }; + + enum class RangeStatus { complete, + retryable, + ignored, + unauthorized, + failed }; + + struct RangeResult { + RangeStatus status = RangeStatus::complete; + std::string detail; + }; + + static bool retryable_http_status(int status) { + return status == 408 || status == 429 || (status >= 500 && status < 600); + } + + static bool retryable_transport_error(httplib::Error error) { + switch (error) { + case httplib::Error::Connection: + case httplib::Error::ConnectionTimeout: + case httplib::Error::ProxyConnection: + case httplib::Error::Read: + case httplib::Error::Write: + case httplib::Error::SSLConnection: + return true; + default: + return false; + } + } + + static RangeResult range_failure(int status, bool accepted, httplib::Error error, int64_t received, int64_t length) { + if (status == 206) { + if (!accepted) + return {RangeStatus::retryable, "HTTP 206 with an unexpected Content-Range or encoding"}; + std::string detail = "HTTP 206, received " + std::to_string(received) + " of " + std::to_string(length) + " bytes"; + if (error != httplib::Error::Success) + detail += " (" + httplib::to_string(error) + ")"; + return {RangeStatus::retryable, std::move(detail)}; + } + if (status != 0) { + auto detail = "HTTP " + std::to_string(status); + if (status == 200) + return {RangeStatus::ignored, "HTTP 200 instead of HTTP 206"}; + if (status == 401 || status == 403) + return {RangeStatus::unauthorized, std::move(detail)}; + if (retryable_http_status(status) || status == 412 || status == 416 || is_redirect(status)) + return {RangeStatus::retryable, std::move(detail)}; + return {RangeStatus::failed, std::move(detail)}; + } + return {retryable_transport_error(error) ? RangeStatus::retryable : RangeStatus::failed, httplib::to_string(error)}; + } + + static RangeResult download_ranges(const Url& url, StagedFile& file, DownloadRanges& ranges, int threads, const std::string& etag, uint64_t& transferred, const FileEvents& events) { + std::vector pending; + for (int index = 0; index < ranges.count(); ++index) { + if (ranges.first(index) + ranges.footer.received[index] < ranges.end(index)) + pending.push_back(index); + } + if (pending.empty()) + return {}; + + RangeResult result; + std::atomic stopped{false}; + const auto cancelled = [&] { return stopped.load() || events.cancelled(); }; + std::mutex file_mutex; + int64_t completed = ranges.completed(); + int64_t checkpoint_at = completed; + int64_t position = -1; + auto last_progress = std::chrono::steady_clock::now(); + std::atomic next{0}; + const auto worker = [&] { + try { + while (!cancelled()) { + const auto job = next.fetch_add(1); + if (job >= pending.size()) + return; + const int index = pending[job]; + const auto start = ranges.first(index) + ranges.footer.received[index]; + int64_t offset = start; + const auto end = ranges.end(index); + const auto range = std::to_string(offset) + "-" + std::to_string(end - 1); + const auto expected = "bytes " + range + "/" + std::to_string(ranges.total); + httplib::SSLClient client(url.host, url.port); + configure_client(client, url); + httplib::Headers headers{{"Accept-Encoding", "identity"}, {"Range", "bytes=" + range}}; + if (!etag.empty()) + headers.emplace("If-Match", etag); + int status = 0; + bool accepted = false; + const auto response = client.Get( + url.target.substr(0, url.target.find('?')), headers, + [&](const httplib::Response& res) { + if (cancelled()) + return false; + status = res.status; + accepted = status == 206 && identity_encoding(res) && + ascii_lowercase(res.get_header_value("Content-Range")) == expected; + return accepted; + }, + [&](const char* data, size_t length) { + if (cancelled() || length > uint64_t(end - offset)) + return false; + std::lock_guard lock(file_mutex); + if ((position != offset && !file.seek(offset)) || !file.write(data, length)) + throw std::runtime_error("cannot write downloaded range"); + offset += int64_t(length); + position = offset; + ranges.footer.received[index] += int64_t(length); + completed += int64_t(length); + transferred += std::min(length, std::numeric_limits::max() - transferred); + if (completed - checkpoint_at >= checkpoint_interval) { + ranges.save(file, position); + checkpoint_at = completed; + } + const auto now = std::chrono::steady_clock::now(); + if (completed == ranges.total || now - last_progress >= std::chrono::milliseconds(250)) { + events.progress(completed, ranges.total, transferred); + last_progress = now; + } + return true; + }); + if (response && accepted && offset == end) + continue; + if (!events.cancelled() && !stopped.exchange(true)) { + result = range_failure(status, accepted, response.error(), offset - start, end - start); + result.detail = "bytes " + range + ": " + result.detail; + } + return; + } + } catch (...) { + stopped.store(true); + throw; + } + }; + + const int workers = std::min(threads, static_cast(pending.size())); + std::vector> background; + background.reserve(workers - 1); + try { + for (int index = 1; index < workers; ++index) + background.push_back(std::async(std::launch::async, worker)); + worker(); + for (auto& task : background) + task.get(); + } catch (...) { + stopped.store(true); + throw; + } + if (completed > checkpoint_at) + ranges.save(file, position); + return result; + } + + using Digest = std::unique_ptr; + + static Digest make_digest() { + Digest digest(EVP_MD_CTX_new(), &EVP_MD_CTX_free); + if (!digest || EVP_DigestInit_ex(digest.get(), EVP_sha256(), nullptr) != 1) + throw std::runtime_error("cannot start SHA-256"); + return digest; + } + + static bool hash_download(StagedFile& file, int64_t size, EVP_MD_CTX* digest, const FileEvents& events) { + std::vector buffer(1024 * 1024); + if (!file.seek(0)) + throw std::runtime_error("cannot seek in download"); + while (size > 0) { + if (events.cancelled()) + return false; + const auto chunk = static_cast(std::min(size, buffer.size())); + if (!file.read(buffer.data(), chunk) || EVP_DigestUpdate(digest, buffer.data(), chunk) != 1) + throw std::runtime_error("cannot read or hash download"); + size -= chunk; + } + return true; + } + + bool fetch_file(const Request& request, const HostCheck& check_host, int threads, const FileEvents& events) { + const auto origin = parse_url(request.url); + auto url = origin; + const auto& path = request.path; + const auto& sha256 = request.sha256; + const auto& cancelled = events.cancelled; + if (std::filesystem::is_regular_file(std::filesystem::symlink_status(path))) + return !cancelled(); + const auto destination = path.filename().u8string(); + events.log("Attempting download of " + destination + " from " + log_url(url)); + + constexpr int max_retries = 2; + int retries = 0; + uint64_t transferred = 0; + bool retried_checkpoint = false; + bool refreshed_url = false; + bool sequential_only = false; + const auto report = [&](int64_t completed, int64_t total) { events.progress(completed, total, transferred); }; + const auto retry_download = [&](std::string_view action, const std::string& detail) { + if (retries == max_retries || cancelled()) + return false; + ++retries; + events.log(std::string(action) + " for " + destination + " (" + std::to_string(retries) + "/" + + std::to_string(max_retries) + "): " + detail); + std::this_thread::sleep_for(std::chrono::milliseconds(500 * retries)); + return true; + }; + for (int hop = 0;;) { + if (cancelled()) + return false; + check_host(url.host); + const bool can_refresh_url = !refreshed_url && hop != 0; + const auto refresh_url = [&] { + refreshed_url = true; + url = origin; + hop = 0; + }; + httplib::SSLClient client(url.host, url.port); + configure_client(client, url); + + int status = 0; + std::string location; + std::string etag; + std::unique_ptr file; + std::optional ranges; + Digest digest(nullptr, &EVP_MD_CTX_free); + int64_t completed = 0; + int64_t total = 0; + int64_t resumed = 0; + int64_t checkpoint_at = 0; + bool has_length = false; + bool fetch_ranges = false; + bool advertised_ranges = false; + auto last_progress = std::chrono::steady_clock::now(); + + const auto response = client.Get( + url.target.substr(0, url.target.find('?')), {{"Accept-Encoding", "identity"}}, + [&](const httplib::Response& headers) { + status = headers.status; + if (is_redirect(status)) + location = headers.get_header_value("Location"); + if (status != 200 || cancelled()) + return false; + if (!identity_encoding(headers)) + throw std::runtime_error("unexpected Content-Encoding from " + url.host); + has_length = headers.has_header("Content-Length"); + const auto length_hint = headers.get_header_value_u64("Content-Length"); + if (length_hint > uint64_t(std::numeric_limits::max())) + throw std::runtime_error("download is too large"); + total = int64_t(length_hint); + const auto accept_ranges = ascii_lowercase(headers.get_header_value("Accept-Ranges")); + advertised_ranges = accept_ranges == "bytes"; + if (!sequential_only && has_length && total > 0 && + total <= std::numeric_limits::max() - static_cast(sizeof(DownloadRanges::Footer)) && + (accept_ranges.empty() || accept_ranges == "bytes")) { + const int range_threads = advertised_ranges + ? static_cast(std::clamp(total / min_range_size, 1, threads)) + : 1; + const auto validator = headers.get_header_value("ETag"); + if (validator.size() >= 2 && validator.front() == '"' && validator.back() == '"') + etag = validator; + const auto key = hex_digest(hash_key(destination + '\0' + sha256)); + file = std::make_unique(path, key + ".part"); + ranges.emplace(*file, total, range_threads, etag); + resumed = ranges->completed(); + fetch_ranges = resumed > 0 || ranges->count() > 1; + if (fetch_ranges) + return false; + } else { + file = std::make_unique(path); + } + if (!file->seek(0)) + throw std::runtime_error("cannot seek in download"); + digest = make_digest(); + events.log("Downloading " + destination); + report(0, total); + return true; + }, + [&](const char* data, size_t size) { + if (cancelled()) + return false; + const auto limit = has_length ? total : std::numeric_limits::max(); + if (size > uint64_t(limit - completed) || + !file->write(data, size) || EVP_DigestUpdate(digest.get(), data, size) != 1) + throw std::runtime_error("cannot write or hash downloaded data"); + completed += int64_t(size); + transferred += std::min(size, std::numeric_limits::max() - transferred); + if (ranges) { + ranges->footer.received[0] = completed; + if (completed - checkpoint_at >= checkpoint_interval) { + ranges->save(*file, completed); + checkpoint_at = completed; + } + } + const auto now = std::chrono::steady_clock::now(); + if (completed == total || now - last_progress >= std::chrono::milliseconds(250)) { + report(completed, total); + last_progress = now; + } + return true; + }); + + if (!fetch_ranges && ranges && completed > checkpoint_at) + ranges->save(*file, completed); + if (!fetch_ranges && file && completed == 0) + file->discard_checkpoint(); + if (cancelled()) + return false; + if (is_redirect(status)) { + if (hop++ == max_redirects) + throw std::runtime_error("too many download redirects"); + url = redirect_url(std::move(url), location); + events.log("HTTP " + std::to_string(status) + " for " + destination + " -> " + log_url(url)); + continue; + } + if (!response && status == 0) { + const auto detail = httplib::to_string(response.error()); + if (retryable_transport_error(response.error()) && + retry_download("Retrying HTTPS download", detail)) + continue; + throw std::runtime_error("HTTPS request to " + url.host + " failed: " + detail); + } + if (response) + status = response->status; + if ((status == 401 || status == 403) && can_refresh_url && + retry_download("Refreshing download URL", "HTTP " + std::to_string(status))) { + refresh_url(); + continue; + } + if (status != 200) { + const auto detail = "HTTP " + std::to_string(status); + if (retryable_http_status(status) && retry_download("Retrying HTTPS download", detail)) + continue; + throw std::runtime_error(detail + " from " + url.host); + } + if (fetch_ranges) { + if (resumed > 0) + events.log("Resuming " + destination + " from " + std::to_string(resumed) + " saved bytes"); + else + events.log("Downloading " + destination + " in " + std::to_string(ranges->count()) + " parallel ranges"); + report(resumed, total); + auto result = download_ranges(url, *file, *ranges, threads, etag, transferred, events); + bool refresh = false; + bool restart = false; + while (result.status == RangeStatus::retryable || result.status == RangeStatus::ignored || result.status == RangeStatus::unauthorized) { + refresh = result.status == RangeStatus::unauthorized && can_refresh_url; + // A single-stream checkpoint can test Range support even when the origin never advertised it. + restart = result.status == RangeStatus::ignored && !advertised_ranges && ranges->count() == 1; + const auto action = refresh ? "Refreshing download URL" + : restart ? "Restarting sequential download" + : "Retrying remaining HTTPS ranges"; + if (!retry_download(action, result.detail)) { + refresh = false; + restart = false; + break; + } + if (cancelled() || refresh || restart) + break; + report(ranges->completed(), total); + result = download_ranges(url, *file, *ranges, threads, etag, transferred, events); + } + if (ranges->completed() == 0) + file->discard_checkpoint(); + if (cancelled()) + return false; + if (refresh) { + refresh_url(); + continue; + } + if (restart) { + file->discard_checkpoint(); + sequential_only = true; + continue; + } + if (result.status != RangeStatus::complete) + throw std::runtime_error("incomplete HTTPS ranges from " + url.host + " after " + + std::to_string(retries) + " retries: " + result.detail); + events.log("Received " + destination + ". Checking SHA-256."); + digest = make_digest(); + if (!hash_download(*file, total, digest.get(), events)) + return false; + } else { + if (!response || !file || (has_length && completed != total)) { + std::string detail = "received " + std::to_string(completed) + " bytes"; + if (!response) + detail += " (" + httplib::to_string(response.error()) + ")"; + if (file && (response || retryable_transport_error(response.error())) && + retry_download("Retrying HTTPS download", detail)) + continue; + throw std::runtime_error("incomplete HTTPS response from " + url.host + " after " + + std::to_string(retries) + " retries: " + detail); + } + report(completed, has_length ? total : completed); + events.log("Received " + destination + ". Checking SHA-256."); + } + + Sha256 bytes{}; + unsigned int length = 0; + if (EVP_DigestFinal_ex(digest.get(), bytes.data(), &length) != 1 || length != bytes.size()) + throw std::runtime_error("cannot finish SHA-256"); + if (hex_digest(bytes) != sha256) { + file->discard_checkpoint(); + if (resumed > 0 && !retried_checkpoint && + retry_download("Saved download failed SHA-256. Starting over", "discarding invalid checkpoint")) { + report(0, total); + retried_checkpoint = true; + continue; + } + throw std::runtime_error("SHA-256 mismatch"); + } + if (cancelled()) + return false; + if (file->persistent()) + file->resize(total); + file->publish(); + file->discard_checkpoint(); + events.log("Verified " + destination + " (SHA-256)"); + return true; + } + } + +} // namespace sd::download diff --git a/examples/common/download_http.h b/examples/common/download_http.h new file mode 100644 index 0000000000..600b4121f6 --- /dev/null +++ b/examples/common/download_http.h @@ -0,0 +1,18 @@ +#ifndef __SD_EXAMPLES_COMMON_DOWNLOAD_HTTP_H__ +#define __SD_EXAMPLES_COMMON_DOWNLOAD_HTTP_H__ + +#include "download.h" + +namespace sd::download { + + struct FileEvents { + std::function cancelled; + std::function log; + std::function progress; + }; + + bool fetch_file(const Request& request, const HostCheck& check_host, int threads, const FileEvents& events); + +} // namespace sd::download + +#endif diff --git a/examples/common/media_io.cpp b/examples/common/media_io.cpp index 0b1d94250b..902777f50e 100644 --- a/examples/common/media_io.cpp +++ b/examples/common/media_io.cpp @@ -124,7 +124,7 @@ bool write_image_to_file(const std::string& path, const uint8_t* image, int widt return false; const sd_dgl_input_t inputs[] = {tensor_input("pixels", tensor.get()), media_path_input(path.c_str())}; const auto source = "fn main(pixels,path) { image::save(path, pixels, metadata=" + nlohmann::json(parameters).dump() + - ", quality=" + std::to_string(std::clamp(quality, 1, 100)) + ") }"; + ", quality=" + std::to_string(std::clamp(quality, 1, 100)) + ") }"; return bool(run_media(source, inputs, 2)); } @@ -268,7 +268,7 @@ bool write_wav_to_file(const std::string& path, const float* samples, uint64_t c return false; const sd_dgl_input_t inputs[] = {tensor_input("samples", tensor.get()), media_path_input(path.c_str())}; const auto source = "fn main(samples,path) { audio::save(path, { samples=samples, sample_rate=" + - std::to_string(rate) + " }, format=\"pcm16\") }"; + std::to_string(rate) + " }, format=\"pcm16\") }"; return bool(run_media(source, inputs, 2)); } diff --git a/examples/server/CMakeLists.txt b/examples/server/CMakeLists.txt index 9345ac2fcc..82d1cf9678 100644 --- a/examples/server/CMakeLists.txt +++ b/examples/server/CMakeLists.txt @@ -64,6 +64,7 @@ endif() add_executable(${TARGET} ../common/common.cpp + ../common/dgl_model_sources.cpp ../common/log.cpp ../common/media_io.cpp main.cpp @@ -106,6 +107,7 @@ target_include_directories(${TARGET} PRIVATE "${CMAKE_CURRENT_BINARY_DIR}") install(TARGETS ${TARGET} RUNTIME) target_link_libraries(${TARGET} PRIVATE stable-diffusion ${CMAKE_THREAD_LIBS_INIT}) +sd_add_download(${TARGET}) # due to httplib; it contains a pragma for MSVC, but other things need explicit flags if(WIN32 AND NOT MSVC) diff --git a/examples/server/README.md b/examples/server/README.md index 4a80b0683b..0f7c36ea08 100644 --- a/examples/server/README.md +++ b/examples/server/README.md @@ -186,6 +186,29 @@ Relative paths still resolve from the server's working directory. Absolute paths under the configured output directory also work. Writes outside that directory are denied. +### DGL model downloads + +Start the server with `--autodl on` to fetch missing files declared by +[`# model-source:`](../../docs/dgl.md#model-sources) +when a DGL job runs. The default is `off`. Both the configured model roots +and the download write policy must allow the target. The working directory +is writable by default for downloads. Repeat `--allow-download-dir` to +authorize extra roots, including the target of a linked model directory. + +```powershell +.\bin\Release\sd-server.exe --model-dir ..\models --autodl on --allow-download-dir ..\models +``` + +```sh +./bin/sd-server --model-dir ../models --autodl on --allow-download-dir ../models +``` + +Automatic downloads are available to requests authenticated with a server API +key and to loopback requests that send a same-origin `Origin` header. The job +reports download progress before loading models. +The [download concurrency and proxy settings](../cli/README.md#automatic-dgl-model-downloads) +also apply to the server. + ## Model management ### Model directories diff --git a/examples/server/api.md b/examples/server/api.md index 5a08131fc9..55c14f4f05 100644 --- a/examples/server/api.md +++ b/examples/server/api.md @@ -1825,6 +1825,12 @@ Failed jobs report `error.code` and `error.message`. When execution reports from the runtime. Scripts share the component cache and execution settings used for generation. +With `--autodl on`, API-key-authenticated DGL jobs and loopback jobs with a +same-origin `Origin` header can download missing declared models. The job reports +`progress.stage = "downloading"` with aggregate download progress, including +bytes reused from checkpoints, and a total once the sizes of all pending files +are known. Its detail shows the file name for a single download or the number +of verified files for multiple downloads. Model reads are restricted to the configured model directories. Script writes are restricted to `--output-dir`, which defaults to `output/` in the server's working directory. diff --git a/examples/server/async_jobs.cpp b/examples/server/async_jobs.cpp index 6e7275be57..d82da599e0 100644 --- a/examples/server/async_jobs.cpp +++ b/examples/server/async_jobs.cpp @@ -298,7 +298,7 @@ json make_async_job_json(const AsyncJobManager& manager, const AsyncGenerationJo {"stage", progress.stage}, {"detail", progress.detail}, {"pass", progress.sample_pass}, - {"completed", progress.total > 0 ? json(progress.completed) : json(nullptr)}, + {"completed", progress.total > 0 || progress.unit == "bytes" ? json(progress.completed) : json(nullptr)}, {"total", progress.total > 0 ? json(progress.total) : json(nullptr)}, {"unit", progress.unit.empty() ? json(nullptr) : json(progress.unit)}, {"stage_elapsed_ms", std::chrono::duration_cast(end - progress.stage_started).count()}, @@ -521,8 +521,8 @@ bool execute_vid_gen_job(ServerRuntime& runtime, return false; } - output_media_b64 = base64_encode(video_bytes); - output_frame_count = num_results; + output_media_b64 = base64_encode(video_bytes); + output_frame_count = num_results; return true; } @@ -732,6 +732,12 @@ void configure_server_file_access(ServerModels& models, const SDSvrParams& param // The DGL context gets a copy of the policy: take the snapshot after the // enrichment, or graphs cannot read from --lora-model-dir / --hires-upscalers-dir. models.workspace_file_access = policy; + if (params.download.autodl.value_or(false)) { + std::vector roots; + for (const auto& root : policy.models) + roots.push_back(root.path); + models.dgl_model_sources.emplace(params.download, std::move(roots)); + } if (sd_ctx_set_file_access_callback(models.context.get(), allowed_dgl_path, &policy) != SD_STATUS_OK) throw std::runtime_error(sd_get_last_error()); @@ -746,6 +752,23 @@ static sd_status_t execute_dgl_job(ServerRuntime& runtime, try { auto source = std::move(job.dgl_source); sd_dgl_result_t* raw_result = nullptr; + if (job.cancel_requested.load()) + return SD_STATUS_CANCELLED; + if (job.dgl_allow_download && runtime.models->dgl_model_sources) { + const auto status = sd_dgl_check(source.c_str(), false); + if (status != SD_STATUS_OK) { + error_message = sd_dgl_error(); + return status; + } + sd::download::Events events; + events.cancelled = [&job] { return job.cancel_requested.load(); }; + events.log = [](const std::string& message) { LOG_INFO("%s", message.c_str()); }; + events.progress = [&job](const sd::download::Progress& progress) { + update_job_progress(job, "downloading", progress.detail.c_str(), 0, progress.completed, progress.total, "bytes"); + }; + if (!runtime.models->dgl_model_sources->prepare(source, events)) + return SD_STATUS_CANCELLED; + } { std::lock_guard lock(*runtime.sd_ctx_mutex); if (job.cancel_requested.load()) diff --git a/examples/server/async_jobs.h b/examples/server/async_jobs.h index 0f8b932315..1be5618d78 100644 --- a/examples/server/async_jobs.h +++ b/examples/server/async_jobs.h @@ -56,6 +56,7 @@ struct AsyncGenerationJob { ImgGenJobRequest img_gen; VidGenJobRequest vid_gen; std::string dgl_source; + bool dgl_allow_download = false; json dgl_result_info; std::vector result_images_b64; json result_generation_info; diff --git a/examples/server/model_catalog.h b/examples/server/model_catalog.h index 934b246796..93ba97b9df 100644 --- a/examples/server/model_catalog.h +++ b/examples/server/model_catalog.h @@ -41,6 +41,7 @@ struct ServerModels { std::mutex catalog_mutex; ServerFileAccess file_access; ServerFileAccess workspace_file_access; + std::optional dgl_model_sources; SDCtxPtr context; SDContextParams base_context; SDGenerationParams base_defaults; diff --git a/examples/server/routes_dgl.cpp b/examples/server/routes_dgl.cpp index 1b7e1d6f8a..480c448cdd 100644 --- a/examples/server/routes_dgl.cpp +++ b/examples/server/routes_dgl.cpp @@ -165,10 +165,16 @@ void register_dgl_endpoints(httplib::Server& svr, ServerRuntime& runtime) { send_error(res, 400, "Expected non-empty UTF-8 source"); return; } - auto job = std::make_shared(); - job->kind = AsyncJobKind::Dgl; - job->dgl_source = std::move(source); - auto& manager = *runtime.async_job_manager; + auto job = std::make_shared(); + job->kind = AsyncJobKind::Dgl; + job->dgl_source = std::move(source); + const auto origin = req.get_header_value("Origin"); + const bool loopback = req.remote_addr == "127.0.0.1" || req.remote_addr == "::1" || + req.remote_addr == "::ffff:127.0.0.1"; + const bool local_same_origin = loopback && origin == "http://" + req.get_header_value("Host"); + // The server authenticates POST requests before routing when API keys are configured. + job->dgl_allow_download = !runtime.svr_params->api_keys.empty() || local_same_origin; + auto& manager = *runtime.async_job_manager; { std::lock_guard lock(manager.mutex); purge_expired_jobs(manager); diff --git a/examples/server/runtime.cpp b/examples/server/runtime.cpp index b34f48ab90..ebc1d0ad2e 100644 --- a/examples/server/runtime.cpp +++ b/examples/server/runtime.cpp @@ -309,6 +309,7 @@ ArgOptions SDSvrParams::get_options() { return 1; }}, }; + download.add_options(options); add_log_options(options, log_level); return options; } diff --git a/examples/server/runtime.h b/examples/server/runtime.h index 2b133ab875..746aaaed0c 100644 --- a/examples/server/runtime.h +++ b/examples/server/runtime.h @@ -9,6 +9,7 @@ #include #include "common/common.h" +#include "common/dgl_model_sources.h" #include "common/resource_owners.hpp" #include "stable-diffusion.h" @@ -29,6 +30,7 @@ struct SDSvrParams { std::string dgl_dir = "dgl"; bool media_view = true; std::vector model_dirs; + DGLModelSourceOptions download; std::string output_dir; std::vector api_keys; std::string api_key_file; diff --git a/src/dgl/bindings/audio.cpp b/src/dgl/bindings/audio.cpp index f8657d4518..702fbf244e 100644 --- a/src/dgl/bindings/audio.cpp +++ b/src/dgl/bindings/audio.cpp @@ -41,7 +41,7 @@ namespace sd::dgl { const auto path = get_string(args, "path"); require_file_access(path, SD_DGL_FILE_WRITE); const auto output = std::filesystem::u8path(path); - const auto audio = read_audio_dict(args.at("audio")); + const auto audio = read_audio_dict(args.at("audio")); ops::write_media_file(output, ops::encode_audio(audio, ops::media_path_format(output), get_string(args, "format") == "pcm16")); return Value::void_value(); } diff --git a/src/dgl/bindings/media.cpp b/src/dgl/bindings/media.cpp index 22fe643bd6..e583305674 100644 --- a/src/dgl/bindings/media.cpp +++ b/src/dgl/bindings/media.cpp @@ -31,7 +31,7 @@ namespace sd::dgl { } Value execute_encode_video(Values& args, RunState& state) { - const auto video = read_video_dict(args.at("video")); + const auto video = read_video_dict(args.at("video")); const auto format = get_string(args, "format"); return media_result(ops::encode_video(*video.frames, video_save_options(args, state, video), format), ops::media_mime_type(format)); } diff --git a/src/dgl/ops/audio.cpp b/src/dgl/ops/audio.cpp index 2c0bdc435c..29960bbf6c 100644 --- a/src/dgl/ops/audio.cpp +++ b/src/dgl/ops/audio.cpp @@ -90,7 +90,7 @@ namespace sd::dgl::ops { if (!std::memcmp(bytes.data() + offset, "fmt ", 4)) { if (format || size < 16) throw std::runtime_error("invalid WAV format chunk"); - format = bytes.data() + offset + 8; + format = bytes.data() + offset + 8; format_size = size_t(size); } else if (sample_chunk) { if (data) diff --git a/src/dgl/ops/ffmpeg.cpp b/src/dgl/ops/ffmpeg.cpp index c82919319d..4093076520 100644 --- a/src/dgl/ops/ffmpeg.cpp +++ b/src/dgl/ops/ffmpeg.cpp @@ -16,10 +16,12 @@ #define NOMINMAX #endif #include + +// sddl.h needs the Windows types and macros declared above. #include #else -#include #include +#include #endif namespace sd::dgl::ops { @@ -41,7 +43,7 @@ namespace sd::dgl::ops { #endif for (int attempt = 0; attempt < 32; ++attempt) { directory_ = parent / (".dgl-ffmpeg-" + std::to_string(random()) + "-" + std::to_string(random())); - path_ = directory_ / "input.mov"; + path_ = directory_ / "input.mov"; #ifdef _WIN32 if (CreateDirectoryW(directory_.c_str(), &attributes)) return; @@ -57,7 +59,7 @@ namespace sd::dgl::ops { throw std::runtime_error("cannot create a private FFmpeg temporary input directory"); } - TemporaryMediaInput(const TemporaryMediaInput&) = delete; + TemporaryMediaInput(const TemporaryMediaInput&) = delete; TemporaryMediaInput& operator=(const TemporaryMediaInput&) = delete; ~TemporaryMediaInput() { std::error_code ignored; diff --git a/src/dgl/ops/ffmpeg_process.cpp b/src/dgl/ops/ffmpeg_process.cpp index 2e1eec6778..4de082c1d9 100644 --- a/src/dgl/ops/ffmpeg_process.cpp +++ b/src/dgl/ops/ffmpeg_process.cpp @@ -224,7 +224,7 @@ namespace sd::dgl::ops { throw std::runtime_error("cannot configure FFmpeg standard streams"); } #ifdef __APPLE__ - auto env = *_NSGetEnviron(); + auto env = *_NSGetEnviron(); #else auto env = environ; #endif diff --git a/src/dgl/ops/image.cpp b/src/dgl/ops/image.cpp index 2526901096..be40bd9f4c 100644 --- a/src/dgl/ops/image.cpp +++ b/src/dgl/ops/image.cpp @@ -303,9 +303,9 @@ namespace sd::dgl::ops { const auto parameters = metadata.empty() ? std::string{} : sd::api::generation_metadata(metadata).value("infotext", ""); const bool ok = format == "jpeg" ? stbi_write_jpg_to_func(append, &bytes, image.width, image.height, image.channel, image.data, quality) && - sd::metadata::embed_jpeg_metadata(bytes, metadata, parameters) + sd::metadata::embed_jpeg_metadata(bytes, metadata, parameters) : stbi_write_png_to_func(append, &bytes, image.width, image.height, image.channel, image.data, image.width * image.channel) && - sd::metadata::embed_png_metadata(bytes, metadata, parameters); + sd::metadata::embed_png_metadata(bytes, metadata, parameters); if (!ok) throw std::runtime_error("cannot encode image or generation metadata"); return bytes; diff --git a/src/model/diffusion/minimax_h3.hpp b/src/model/diffusion/minimax_h3.hpp index e4a72fc06d..bd26d82d72 100644 --- a/src/model/diffusion/minimax_h3.hpp +++ b/src/model/diffusion/minimax_h3.hpp @@ -1111,7 +1111,7 @@ namespace MiniMaxH3 { } }; - float cursor = static_cast(text_len); + float cursor = static_cast(text_len); auto reference_end = [&](const MiniMaxH3ReferenceBlock& block, float start) { float end = block.kind == MiniMaxH3ReferenceKind::IMAGE ? start + 1.f : start; if (block.video_index >= 0 && block.kind != MiniMaxH3ReferenceKind::IMAGE) { @@ -1195,9 +1195,9 @@ namespace MiniMaxH3 { if (block.kind != MiniMaxH3ReferenceKind::AUDIO) { GGML_ASSERT(ref_video != nullptr); - auto axes = condition_spatial_axes(*ref_video); - int64_t count = ref_video->shape()[2] * - static_cast(axes.first.size() * axes.second.size()); + auto axes = condition_spatial_axes(*ref_video); + int64_t count = ref_video->shape()[2] * + static_cast(axes.first.size() * axes.second.size()); append_video_positions(*ref_video, start); layout.sequence_segments.push_back({row, row + count, diff --git a/src/model/vae/hunyuan_vae.hpp b/src/model/vae/hunyuan_vae.hpp index aa8e51647a..fb8a18eb90 100644 --- a/src/model/vae/hunyuan_vae.hpp +++ b/src/model/vae/hunyuan_vae.hpp @@ -86,14 +86,14 @@ namespace Hunyuan { auto conv = std::dynamic_pointer_cast(blocks["conv"]); - int pad_w = std::get<2>(kernel_size) / 2; - int pad_h = std::get<1>(kernel_size) / 2; - int pad_t = std::get<0>(kernel_size) - 1; + int pad_w = std::get<2>(kernel_size) / 2; + int pad_h = std::get<1>(kernel_size) / 2; + int pad_t = std::get<0>(kernel_size) - 1; auto padded = ggml_ext_cont(ctx, x); if (pad_t > 0) { - auto input = padded; - auto previous = carry != nullptr && carry->is_continuation() ? carry->take() : nullptr; - const int64_t frames = input->ne[2]; + auto input = padded; + auto previous = carry != nullptr && carry->is_continuation() ? carry->take() : nullptr; + const int64_t frames = input->ne[2]; const int64_t prev_frames = previous != nullptr ? previous->ne[2] : 0; GGML_ASSERT(prev_frames <= pad_t); const int64_t missing = pad_t - prev_frames; @@ -118,7 +118,7 @@ namespace Hunyuan { // Avoid retaining the padding buffer across decoder chunks. const int64_t keep_first = std::min(missing, pad_t - frames); const int64_t keep_prev = pad_t - frames - keep_first; - auto tail = input; + auto tail = input; if (keep_first > 0) { tail = frames == 1 ? repeat_first(keep_first + 1) : ggml_concat(ctx->ggml_ctx, repeat_first(keep_first), tail, 2);