mirror of
https://github.com/SagerNet/sing-box.git
synced 2026-04-12 01:57:18 +10:00
Compare commits
47 Commits
v1.13.0-al
...
copilot/im
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dfb4ef2deb | ||
|
|
9ec1549a23 | ||
|
|
76d447d7d9 | ||
|
|
ab3caabde1 | ||
|
|
1338c1e1a9 | ||
|
|
822e140eed | ||
|
|
c726237522 | ||
|
|
466925f636 | ||
|
|
517e1503e9 | ||
|
|
b5f62c1b88 | ||
|
|
6bdfa2d99e | ||
|
|
1662802db8 | ||
|
|
c09a10074b | ||
|
|
269e4a40f7 | ||
|
|
6a1640fe71 | ||
|
|
8cf6842a86 | ||
|
|
2e6af5185c | ||
|
|
9c36b00526 | ||
|
|
9d0510f384 | ||
|
|
6a0ceb7839 | ||
|
|
13ed7fce55 | ||
|
|
788fd491d4 | ||
|
|
c651b9b14c | ||
|
|
07a7530df0 | ||
|
|
362edd2731 | ||
|
|
42e842a7da | ||
|
|
63121f18c0 | ||
|
|
b13643bd42 | ||
|
|
9078f20860 | ||
|
|
a31ecd79c3 | ||
|
|
4f4d18bfaf | ||
|
|
af2ea8f8b9 | ||
|
|
5452980523 | ||
|
|
1f421c04ac | ||
|
|
159610556d | ||
|
|
16de8b394f | ||
|
|
52a0134af0 | ||
|
|
d1bee96553 | ||
|
|
0572e6c436 | ||
|
|
7c1ad09c4c | ||
|
|
89b8212ebb | ||
|
|
fb765bc0da | ||
|
|
83cb784de4 | ||
|
|
73df4a7665 | ||
|
|
044057168c | ||
|
|
4407105f11 | ||
|
|
fdeea12514 |
1
.github/CRONET_GO_VERSION
vendored
1
.github/CRONET_GO_VERSION
vendored
@@ -1 +0,0 @@
|
||||
5e61220bb2d22453eb6d105077c88c8ab1e1c3b2
|
||||
2
.github/setup_go_for_windows7.sh
vendored
2
.github/setup_go_for_windows7.sh
vendored
@@ -1,6 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
VERSION="1.25.5"
|
||||
VERSION="1.25.4"
|
||||
|
||||
mkdir -p $HOME/go
|
||||
cd $HOME/go
|
||||
|
||||
11
.github/setup_musl_cross.sh
vendored
Executable file
11
.github/setup_musl_cross.sh
vendored
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/bin/bash
|
||||
set -xeuo pipefail
|
||||
|
||||
TARGET="$1"
|
||||
|
||||
# Download musl-cross toolchain from musl.cc
|
||||
cd "$HOME"
|
||||
wget -q "https://musl.cc/${TARGET}-cross.tgz"
|
||||
mkdir -p musl-cross
|
||||
tar -xf "${TARGET}-cross.tgz" -C musl-cross --strip-components=1
|
||||
rm "${TARGET}-cross.tgz"
|
||||
10
.github/update_cronet.sh
vendored
10
.github/update_cronet.sh
vendored
@@ -1,13 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -e -o pipefail
|
||||
|
||||
SCRIPT_DIR=$(dirname "$0")
|
||||
PROJECTS=$SCRIPT_DIR/../..
|
||||
|
||||
git -C $PROJECTS/cronet-go fetch origin main
|
||||
PROJECTS=$(dirname "$0")/../..
|
||||
git -C $PROJECTS/cronet-go fetch origin go
|
||||
go get -x github.com/sagernet/cronet-go/all@$(git -C $PROJECTS/cronet-go rev-parse origin/go)
|
||||
go get -x github.com/sagernet/cronet-go@$(git -C $PROJECTS/cronet-go rev-parse origin/go)
|
||||
|
||||
go mod tidy
|
||||
git -C $PROJECTS/cronet-go rev-parse origin/HEAD > "$SCRIPT_DIR/CRONET_GO_VERSION"
|
||||
|
||||
314
.github/workflows/build.yml
vendored
314
.github/workflows/build.yml
vendored
@@ -46,7 +46,7 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Check input version
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: |-
|
||||
@@ -69,25 +69,13 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- { os: linux, arch: amd64, variant: purego, naive: true, openwrt: "x86_64" }
|
||||
- { os: linux, arch: amd64, variant: glibc, naive: true }
|
||||
- { os: linux, arch: amd64, variant: musl, naive: true, debian: amd64, rpm: x86_64, pacman: x86_64, openwrt: "x86_64" }
|
||||
|
||||
- { os: linux, arch: arm64, variant: purego, naive: true, openwrt: "aarch64_cortex-a53 aarch64_cortex-a72 aarch64_cortex-a76 aarch64_generic" }
|
||||
- { os: linux, arch: arm64, variant: glibc, naive: true }
|
||||
- { os: linux, arch: arm64, variant: musl, naive: true, debian: arm64, rpm: aarch64, pacman: aarch64, openwrt: "aarch64_cortex-a53 aarch64_cortex-a72 aarch64_cortex-a76 aarch64_generic" }
|
||||
|
||||
- { os: linux, arch: "386", go386: sse2, openwrt: "i386_pentium4" }
|
||||
- { os: linux, arch: "386", variant: glibc, naive: true, go386: sse2 }
|
||||
- { os: linux, arch: "386", variant: musl, naive: true, go386: sse2, debian: i386, rpm: i386, openwrt: "i386_pentium4" }
|
||||
|
||||
- { os: linux, arch: arm, goarm: "7", openwrt: "arm_cortex-a5_vfpv4 arm_cortex-a7_neon-vfpv4 arm_cortex-a7_vfpv4 arm_cortex-a8_vfpv3 arm_cortex-a9_neon arm_cortex-a9_vfpv3-d16 arm_cortex-a15_neon-vfpv4" }
|
||||
- { os: linux, arch: arm, variant: glibc, naive: true, goarm: "7" }
|
||||
- { os: linux, arch: arm, variant: musl, naive: true, goarm: "7", debian: armhf, rpm: armv7hl, pacman: armv7hl, openwrt: "arm_cortex-a5_vfpv4 arm_cortex-a7_neon-vfpv4 arm_cortex-a7_vfpv4 arm_cortex-a8_vfpv3 arm_cortex-a9_neon arm_cortex-a9_vfpv3-d16 arm_cortex-a15_neon-vfpv4" }
|
||||
|
||||
- { os: linux, arch: amd64, debian: amd64, rpm: x86_64, pacman: x86_64, openwrt: "x86_64" }
|
||||
- { os: linux, arch: "386", go386: sse2, debian: i386, rpm: i386, openwrt: "i386_pentium4" }
|
||||
- { os: linux, arch: "386", go386: softfloat, openwrt: "i386_pentium-mmx" }
|
||||
- { os: linux, arch: arm64, debian: arm64, rpm: aarch64, pacman: aarch64, openwrt: "aarch64_cortex-a53 aarch64_cortex-a72 aarch64_cortex-a76 aarch64_generic" }
|
||||
- { os: linux, arch: arm, goarm: "5", openwrt: "arm_arm926ej-s arm_cortex-a7 arm_cortex-a9 arm_fa526 arm_xscale" }
|
||||
- { os: linux, arch: arm, goarm: "6", debian: armel, rpm: armv6hl, openwrt: "arm_arm1176jzf-s_vfp" }
|
||||
- { os: linux, arch: arm, goarm: "7", debian: armhf, rpm: armv7hl, pacman: armv7hl, openwrt: "arm_cortex-a5_vfpv4 arm_cortex-a7_neon-vfpv4 arm_cortex-a7_vfpv4 arm_cortex-a8_vfpv3 arm_cortex-a9_neon arm_cortex-a9_vfpv3-d16 arm_cortex-a15_neon-vfpv4" }
|
||||
- { os: linux, arch: mips, gomips: softfloat, openwrt: "mips_24kc mips_4kec mips_mips32" }
|
||||
- { os: linux, arch: mipsle, gomips: hardfloat, debian: mipsel, rpm: mipsel, openwrt: "mipsel_24kc_24kf" }
|
||||
- { os: linux, arch: mipsle, gomips: softfloat, openwrt: "mipsel_24kc mipsel_74kc mipsel_mips32" }
|
||||
@@ -99,8 +87,11 @@ jobs:
|
||||
- { os: linux, arch: riscv64, debian: riscv64, rpm: riscv64, openwrt: "riscv64_generic" }
|
||||
- { os: linux, arch: loong64, debian: loongarch64, rpm: loongarch64, openwrt: "loongarch64_generic" }
|
||||
|
||||
- { os: windows, arch: amd64 }
|
||||
- { os: windows, arch: amd64, legacy_win7: true, legacy_name: "windows-7" }
|
||||
- { os: windows, arch: "386" }
|
||||
- { os: windows, arch: "386", legacy_win7: true, legacy_name: "windows-7" }
|
||||
- { os: windows, arch: arm64 }
|
||||
|
||||
- { os: android, arch: arm64, ndk: "aarch64-linux-android21" }
|
||||
- { os: android, arch: arm, ndk: "armv7a-linux-androideabi21" }
|
||||
@@ -115,7 +106,7 @@ jobs:
|
||||
if: ${{ ! (matrix.legacy_win7 || matrix.legacy_go124) }}
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Setup Go 1.24
|
||||
if: matrix.legacy_go124
|
||||
uses: actions/setup-go@v5
|
||||
@@ -128,7 +119,7 @@ jobs:
|
||||
with:
|
||||
path: |
|
||||
~/go/go_win7
|
||||
key: go_win7_1255
|
||||
key: go_win7_1254
|
||||
- name: Setup Go for Windows 7
|
||||
if: matrix.legacy_win7 && steps.cache-go-for-windows7.outputs.cache-hit != 'true'
|
||||
run: |-
|
||||
@@ -144,45 +135,6 @@ jobs:
|
||||
with:
|
||||
ndk-version: r28
|
||||
local-cache: true
|
||||
- name: Clone cronet-go
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
CRONET_GO_VERSION=$(cat .github/CRONET_GO_VERSION)
|
||||
git init ~/cronet-go
|
||||
git -C ~/cronet-go remote add origin https://github.com/sagernet/cronet-go.git
|
||||
git -C ~/cronet-go fetch --depth=1 origin "$CRONET_GO_VERSION"
|
||||
git -C ~/cronet-go checkout FETCH_HEAD
|
||||
git -C ~/cronet-go submodule update --init --recursive --depth=1
|
||||
- name: Cache Chromium toolchain
|
||||
if: matrix.naive
|
||||
id: cache-chromium-toolchain
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/cronet-go/naiveproxy/src/third_party/llvm-build/Release+Asserts
|
||||
~/cronet-go/naiveproxy/src/out/sysroot-build
|
||||
key: chromium-toolchain-${{ matrix.arch }}-${{ matrix.variant }}-${{ hashFiles('.github/CRONET_GO_VERSION') }}
|
||||
- name: Download Chromium toolchain
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
if [[ "${{ matrix.variant }}" == "musl" ]]; then
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl download-toolchain
|
||||
else
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} download-toolchain
|
||||
fi
|
||||
- name: Set Chromium toolchain environment
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
if [[ "${{ matrix.variant }}" == "musl" ]]; then
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl env >> $GITHUB_ENV
|
||||
else
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} env >> $GITHUB_ENV
|
||||
fi
|
||||
- name: Set tag
|
||||
run: |-
|
||||
git ls-remote --exit-code --tags origin v${{ needs.calculate_version.outputs.version }} || echo "PUBLISHED=false" >> "$GITHUB_ENV"
|
||||
@@ -190,70 +142,13 @@ jobs:
|
||||
- name: Set build tags
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.naive }}" == "true" ]]; then
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.os }}" == "android" ]]; then
|
||||
TAGS="${TAGS},with_naive_outbound"
|
||||
fi
|
||||
if [[ "${{ matrix.variant }}" == "purego" ]]; then
|
||||
TAGS="${TAGS},with_purego"
|
||||
elif [[ "${{ matrix.variant }}" == "musl" ]]; then
|
||||
TAGS="${TAGS},with_musl"
|
||||
fi
|
||||
echo "BUILD_TAGS=${TAGS}" >> "${GITHUB_ENV}"
|
||||
- name: Build (purego)
|
||||
if: matrix.variant == 'purego'
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOOS: ${{ matrix.os }}
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GO386: ${{ matrix.go386 }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
GOMIPS: ${{ matrix.gomips }}
|
||||
GOMIPS64: ${{ matrix.gomips }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Extract libcronet.so
|
||||
if: matrix.variant == 'purego' && matrix.naive
|
||||
run: |
|
||||
cd ~/cronet-go
|
||||
CGO_ENABLED=0 go run -v ./cmd/build-naive extract-lib --target ${{ matrix.os }}/${{ matrix.arch }} -o $GITHUB_WORKSPACE/dist
|
||||
- name: Build (glibc)
|
||||
if: matrix.variant == 'glibc'
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GO386: ${{ matrix.go386 }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build (musl)
|
||||
if: matrix.variant == 'musl'
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GO386: ${{ matrix.go386 }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build (non-variant)
|
||||
if: matrix.os != 'android' && matrix.variant == ''
|
||||
- name: Build
|
||||
if: matrix.os != 'android'
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
@@ -297,11 +192,6 @@ jobs:
|
||||
elif [[ -n "${{ matrix.legacy_name }}" ]]; then
|
||||
DIR_NAME="${DIR_NAME}-legacy-${{ matrix.legacy_name }}"
|
||||
fi
|
||||
if [[ "${{ matrix.variant }}" == "glibc" ]]; then
|
||||
DIR_NAME="${DIR_NAME}-glibc"
|
||||
elif [[ "${{ matrix.variant }}" == "musl" ]]; then
|
||||
DIR_NAME="${DIR_NAME}-musl"
|
||||
fi
|
||||
echo "DIR_NAME=${DIR_NAME}" >> "${GITHUB_ENV}"
|
||||
PKG_VERSION="${{ needs.calculate_version.outputs.version }}"
|
||||
PKG_VERSION="${PKG_VERSION//-/\~}"
|
||||
@@ -369,12 +259,8 @@ jobs:
|
||||
-p "dist/openwrt.deb" \
|
||||
--architecture all \
|
||||
dist/sing-box=/usr/bin/sing-box
|
||||
SUFFIX=""
|
||||
if [[ "${{ matrix.variant }}" == "musl" ]]; then
|
||||
SUFFIX="_musl"
|
||||
fi
|
||||
for architecture in ${{ matrix.openwrt }}; do
|
||||
.github/deb2ipk.sh "$architecture" "dist/openwrt.deb" "dist/sing-box_${{ needs.calculate_version.outputs.version }}_openwrt_${architecture}${SUFFIX}.ipk"
|
||||
.github/deb2ipk.sh "$architecture" "dist/openwrt.deb" "dist/sing-box_${{ needs.calculate_version.outputs.version }}_openwrt_${architecture}.ipk"
|
||||
done
|
||||
rm "dist/openwrt.deb"
|
||||
- name: Archive
|
||||
@@ -388,18 +274,15 @@ jobs:
|
||||
zip -r "${DIR_NAME}.zip" "${DIR_NAME}"
|
||||
else
|
||||
cp sing-box "${DIR_NAME}"
|
||||
if [ -f libcronet.so ]; then
|
||||
cp libcronet.so "${DIR_NAME}"
|
||||
fi
|
||||
tar -czvf "${DIR_NAME}.tar.gz" "${DIR_NAME}"
|
||||
fi
|
||||
rm -r "${DIR_NAME}"
|
||||
- name: Cleanup
|
||||
run: rm -f dist/sing-box dist/libcronet.so
|
||||
run: rm dist/sing-box
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: binary-${{ matrix.os }}_${{ matrix.arch }}${{ matrix.goarm && format('v{0}', matrix.goarm) }}${{ matrix.go386 && format('_{0}', matrix.go386) }}${{ matrix.gomips && format('_{0}', matrix.gomips) }}${{ matrix.legacy_name && format('-legacy-{0}', matrix.legacy_name) }}${{ matrix.variant && format('-{0}', matrix.variant) }}
|
||||
name: binary-${{ matrix.os }}_${{ matrix.arch }}${{ matrix.goarm && format('v{0}', matrix.goarm) }}${{ matrix.go386 && format('_{0}', matrix.go386) }}${{ matrix.gomips && format('_{0}', matrix.gomips) }}${{ matrix.legacy_name && format('-legacy-{0}', matrix.legacy_name) }}
|
||||
path: "dist"
|
||||
build_darwin:
|
||||
name: Build Darwin binaries
|
||||
@@ -435,10 +318,7 @@ jobs:
|
||||
- name: Set build tags
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.legacy_go124 }}" != "true" ]]; then
|
||||
TAGS="${TAGS},with_naive_outbound"
|
||||
fi
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_naive_outbound,badlinkname,tfogo_checklinkname0'
|
||||
echo "BUILD_TAGS=${TAGS}" >> "${GITHUB_ENV}"
|
||||
- name: Build
|
||||
run: |
|
||||
@@ -475,18 +355,25 @@ jobs:
|
||||
with:
|
||||
name: binary-darwin_${{ matrix.arch }}${{ matrix.legacy_name && format('-legacy-{0}', matrix.legacy_name) }}
|
||||
path: "dist"
|
||||
build_windows:
|
||||
name: Build Windows binaries
|
||||
build_naive_linux:
|
||||
name: Build Linux with naive outbound
|
||||
if: github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Binary'
|
||||
runs-on: windows-latest
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- calculate_version
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- { arch: amd64, naive: true }
|
||||
- { arch: "386" }
|
||||
- { arch: arm64, naive: true }
|
||||
# Linux glibc (dynamic linking with Debian Bullseye sysroot)
|
||||
- { arch: amd64, sysroot_arch: amd64, sysroot_sha: "36a164623d03f525e3dfb783a5e9b8a00e98e1ddd2b5cff4e449bd016dd27e50", cc_target: "x86_64-linux-gnu", suffix: "-naive" }
|
||||
- { arch: arm64, sysroot_arch: arm64, sysroot_sha: "2f915d821eec27515c0c6d21b69898e23762908d8d7ccc1aa2a8f5f25e8b7e18", cc_target: "aarch64-linux-gnu", suffix: "-naive" }
|
||||
- { arch: "386", sysroot_arch: i386, sysroot_sha: "63f0e5128b84f7b0421956a4a40affa472be8da0e58caf27e9acbc84072daee7", cc_target: "i686-linux-gnu", suffix: "-naive" }
|
||||
- { arch: arm, goarm: "7", sysroot_arch: armhf, sysroot_sha: "47b3a0b161ca011b2b33d4fc1ef6ef269b8208a0b7e4c900700c345acdfd1814", cc_target: "arm-linux-gnueabihf", suffix: "-naive" }
|
||||
# Linux musl (static linking)
|
||||
- { arch: amd64, musl: true, cc_target: "x86_64-linux-musl", suffix: "-naive-musl" }
|
||||
- { arch: arm64, musl: true, cc_target: "aarch64-linux-musl", suffix: "-naive-musl" }
|
||||
- { arch: "386", musl: true, cc_target: "i686-linux-musl", suffix: "-naive-musl" }
|
||||
- { arch: arm, goarm: "7", musl: true, cc_target: "arm-linux-musleabihf", suffix: "-naive-musl" }
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
|
||||
@@ -498,67 +385,97 @@ jobs:
|
||||
go-version: ^1.25.4
|
||||
- name: Set tag
|
||||
run: |-
|
||||
git ls-remote --exit-code --tags origin v${{ needs.calculate_version.outputs.version }} || echo "PUBLISHED=false" >> "$env:GITHUB_ENV"
|
||||
git ls-remote --exit-code --tags origin v${{ needs.calculate_version.outputs.version }} || echo "PUBLISHED=false" >> "$GITHUB_ENV"
|
||||
git tag v${{ needs.calculate_version.outputs.version }} -f
|
||||
- name: Build
|
||||
if: matrix.naive
|
||||
- name: Download sysroot (glibc)
|
||||
if: ${{ ! matrix.musl }}
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
wget -q "https://commondatastorage.googleapis.com/chrome-linux-sysroot/${{ matrix.sysroot_sha }}" -O sysroot.tar.xz
|
||||
mkdir -p /tmp/sysroot
|
||||
tar -xf sysroot.tar.xz -C /tmp/sysroot
|
||||
- name: Install cross compiler (glibc)
|
||||
if: ${{ ! matrix.musl }}
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y clang lld
|
||||
if [[ "${{ matrix.arch }}" == "arm64" ]]; then
|
||||
sudo apt-get install -y libc6-dev-arm64-cross
|
||||
elif [[ "${{ matrix.arch }}" == "386" ]]; then
|
||||
sudo apt-get install -y libc6-dev-i386-cross
|
||||
elif [[ "${{ matrix.arch }}" == "arm" ]]; then
|
||||
sudo apt-get install -y libc6-dev-armhf-cross
|
||||
fi
|
||||
- name: Install musl cross compiler
|
||||
if: matrix.musl
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
.github/setup_musl_cross.sh "${{ matrix.cc_target }}"
|
||||
echo "PATH=$HOME/musl-cross/bin:$PATH" >> $GITHUB_ENV
|
||||
- name: Set build tags
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_naive_outbound,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.musl }}" == "true" ]]; then
|
||||
TAGS="${TAGS},with_musl"
|
||||
fi
|
||||
echo "BUILD_TAGS=${TAGS}" >> "${GITHUB_ENV}"
|
||||
- name: Build (glibc)
|
||||
if: ${{ ! matrix.musl }}
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box.exe -tags "with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,with_naive_outbound,with_purego,badlinkname,tfogo_checklinkname0" `
|
||||
-ldflags "-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0" `
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0 -linkmode=external -extldflags "-fuse-ld=lld --sysroot=/tmp/sysroot"' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOOS: windows
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
CC: "clang --target=${{ matrix.cc_target }} --sysroot=/tmp/sysroot"
|
||||
CXX: "clang++ --target=${{ matrix.cc_target }} --sysroot=/tmp/sysroot"
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build
|
||||
if: ${{ !matrix.naive }}
|
||||
- name: Build (musl)
|
||||
if: matrix.musl
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box.exe -tags "with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0" `
|
||||
-ldflags "-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0" `
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0 -linkmode=external -extldflags "-static"' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOOS: windows
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
CC: "${{ matrix.cc_target }}-gcc"
|
||||
CXX: "${{ matrix.cc_target }}-g++"
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Extract libcronet.dll
|
||||
if: matrix.naive
|
||||
run: |
|
||||
$CRONET_GO_VERSION = Get-Content .github/CRONET_GO_VERSION
|
||||
$env:CGO_ENABLED = "0"
|
||||
go run -v "github.com/sagernet/cronet-go/cmd/build-naive@$CRONET_GO_VERSION" extract-lib --target windows/${{ matrix.arch }} -o dist
|
||||
- name: Set name
|
||||
run: |-
|
||||
DIR_NAME="sing-box-${{ needs.calculate_version.outputs.version }}-linux-${{ matrix.arch }}"
|
||||
if [[ -n "${{ matrix.goarm }}" ]]; then
|
||||
DIR_NAME="${DIR_NAME}v${{ matrix.goarm }}"
|
||||
fi
|
||||
DIR_NAME="${DIR_NAME}${{ matrix.suffix }}"
|
||||
echo "DIR_NAME=${DIR_NAME}" >> "${GITHUB_ENV}"
|
||||
- name: Archive
|
||||
if: matrix.naive
|
||||
run: |
|
||||
$DIR_NAME = "sing-box-${{ needs.calculate_version.outputs.version }}-windows-${{ matrix.arch }}"
|
||||
mkdir "dist/$DIR_NAME"
|
||||
Copy-Item LICENSE "dist/$DIR_NAME"
|
||||
Copy-Item "dist/sing-box.exe" "dist/$DIR_NAME"
|
||||
Copy-Item "dist/libcronet.dll" "dist/$DIR_NAME"
|
||||
Compress-Archive -Path "dist/$DIR_NAME" -DestinationPath "dist/$DIR_NAME.zip"
|
||||
Remove-Item -Recurse "dist/$DIR_NAME"
|
||||
- name: Archive
|
||||
if: ${{ !matrix.naive }}
|
||||
run: |
|
||||
$DIR_NAME = "sing-box-${{ needs.calculate_version.outputs.version }}-windows-${{ matrix.arch }}"
|
||||
mkdir "dist/$DIR_NAME"
|
||||
Copy-Item LICENSE "dist/$DIR_NAME"
|
||||
Copy-Item "dist/sing-box.exe" "dist/$DIR_NAME"
|
||||
Compress-Archive -Path "dist/$DIR_NAME" -DestinationPath "dist/$DIR_NAME.zip"
|
||||
Remove-Item -Recurse "dist/$DIR_NAME"
|
||||
set -xeuo pipefail
|
||||
cd dist
|
||||
mkdir -p "${DIR_NAME}"
|
||||
cp ../LICENSE "${DIR_NAME}"
|
||||
cp sing-box "${DIR_NAME}"
|
||||
tar -czvf "${DIR_NAME}.tar.gz" "${DIR_NAME}"
|
||||
rm -r "${DIR_NAME}"
|
||||
- name: Cleanup
|
||||
if: matrix.naive
|
||||
run: Remove-Item dist/sing-box.exe, dist/libcronet.dll
|
||||
- name: Cleanup
|
||||
if: ${{ !matrix.naive }}
|
||||
run: Remove-Item dist/sing-box.exe
|
||||
run: rm dist/sing-box
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: binary-windows_${{ matrix.arch }}
|
||||
name: binary-linux_${{ matrix.arch }}${{ matrix.goarm && format('v{0}', matrix.goarm) }}${{ matrix.suffix }}
|
||||
path: "dist"
|
||||
build_android:
|
||||
name: Build Android
|
||||
@@ -575,7 +492,7 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Setup Android NDK
|
||||
id: setup-ndk
|
||||
uses: nttld/setup-ndk@v1
|
||||
@@ -633,17 +550,8 @@ jobs:
|
||||
- name: Prepare upload
|
||||
run: |-
|
||||
mkdir -p dist
|
||||
#cp clients/android/app/build/outputs/apk/play/release/*.apk dist
|
||||
cp clients/android/app/build/outputs/apk/other/release/*.apk dist
|
||||
VERSION_CODE=$(grep VERSION_CODE clients/android/version.properties | cut -d= -f2)
|
||||
VERSION_NAME=$(grep VERSION_NAME clients/android/version.properties | cut -d= -f2)
|
||||
cat > dist/SFA-version-metadata.json << EOF
|
||||
{
|
||||
"version_code": ${VERSION_CODE},
|
||||
"version_name": "${VERSION_NAME}"
|
||||
}
|
||||
EOF
|
||||
cat dist/SFA-version-metadata.json
|
||||
cp clients/android/app/build/outputs/apk/play/release/*.apk dist
|
||||
cp clients/android/app/build/outputs/apk/other/release/*-universal.apk dist
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -664,7 +572,7 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Setup Android NDK
|
||||
id: setup-ndk
|
||||
uses: nttld/setup-ndk@v1
|
||||
@@ -717,7 +625,7 @@ jobs:
|
||||
build_apple:
|
||||
name: Build Apple clients
|
||||
runs-on: macos-26
|
||||
if: false # github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Apple' || inputs.build == 'app-store' || inputs.build == 'iOS' || inputs.build == 'macOS' || inputs.build == 'tvOS' || inputs.build == 'macOS-standalone'
|
||||
if: false
|
||||
needs:
|
||||
- calculate_version
|
||||
strategy:
|
||||
@@ -763,7 +671,7 @@ jobs:
|
||||
if: matrix.if
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Set tag
|
||||
if: matrix.if
|
||||
run: |-
|
||||
@@ -882,7 +790,7 @@ jobs:
|
||||
--app-drop-link 0 0 \
|
||||
--skip-jenkins \
|
||||
SFM.dmg "${{ matrix.export_path }}/SFM.app"
|
||||
xcrun notarytool submit "SFM.dmg" --wait --keychain-profile "notarytool-password"
|
||||
xcrun notarytool submit "SFM.dmg" --wait --keychain-profile "notarytool-password"
|
||||
cd "${{ matrix.archive }}"
|
||||
zip -r SFM.dSYMs.zip dSYMs
|
||||
popd
|
||||
@@ -904,7 +812,7 @@ jobs:
|
||||
- calculate_version
|
||||
- build
|
||||
- build_darwin
|
||||
- build_windows
|
||||
- build_naive_linux
|
||||
- build_android
|
||||
- build_apple
|
||||
steps:
|
||||
|
||||
149
.github/workflows/docker.yml
vendored
149
.github/workflows/docker.yml
vendored
@@ -1,10 +1,6 @@
|
||||
name: Publish Docker Images
|
||||
|
||||
on:
|
||||
#push:
|
||||
# branches:
|
||||
# - main-next
|
||||
# - dev-next
|
||||
release:
|
||||
types:
|
||||
- published
|
||||
@@ -17,134 +13,8 @@ env:
|
||||
REGISTRY_IMAGE: ghcr.io/sagernet/sing-box
|
||||
|
||||
jobs:
|
||||
build_binary:
|
||||
name: Build binary
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
# Naive-enabled builds (musl)
|
||||
- { arch: amd64, naive: true, docker_platform: "linux/amd64" }
|
||||
- { arch: arm64, naive: true, docker_platform: "linux/arm64" }
|
||||
- { arch: "386", naive: true, docker_platform: "linux/386" }
|
||||
- { arch: arm, goarm: "7", naive: true, docker_platform: "linux/arm/v7" }
|
||||
# Non-naive builds
|
||||
- { arch: arm, goarm: "6", docker_platform: "linux/arm/v6" }
|
||||
- { arch: ppc64le, docker_platform: "linux/ppc64le" }
|
||||
- { arch: riscv64, docker_platform: "linux/riscv64" }
|
||||
- { arch: s390x, docker_platform: "linux/s390x" }
|
||||
steps:
|
||||
- name: Get commit to build
|
||||
id: ref
|
||||
run: |-
|
||||
if [[ -z "${{ github.event.inputs.tag }}" ]]; then
|
||||
ref="${{ github.ref_name }}"
|
||||
else
|
||||
ref="${{ github.event.inputs.tag }}"
|
||||
fi
|
||||
echo "ref=$ref"
|
||||
echo "ref=$ref" >> $GITHUB_OUTPUT
|
||||
- name: Checkout
|
||||
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5
|
||||
with:
|
||||
ref: ${{ steps.ref.outputs.ref }}
|
||||
fetch-depth: 0
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.4
|
||||
- name: Clone cronet-go
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
CRONET_GO_VERSION=$(cat .github/CRONET_GO_VERSION)
|
||||
git init ~/cronet-go
|
||||
git -C ~/cronet-go remote add origin https://github.com/sagernet/cronet-go.git
|
||||
git -C ~/cronet-go fetch --depth=1 origin "$CRONET_GO_VERSION"
|
||||
git -C ~/cronet-go checkout FETCH_HEAD
|
||||
git -C ~/cronet-go submodule update --init --recursive --depth=1
|
||||
- name: Cache Chromium toolchain
|
||||
if: matrix.naive
|
||||
id: cache-chromium-toolchain
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/cronet-go/naiveproxy/src/third_party/llvm-build/Release+Asserts
|
||||
~/cronet-go/naiveproxy/src/out/sysroot-build
|
||||
key: chromium-toolchain-${{ matrix.arch }}-musl-${{ hashFiles('.github/CRONET_GO_VERSION') }}
|
||||
- name: Download Chromium toolchain
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl download-toolchain
|
||||
- name: Set version
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
VERSION=$(go run ./cmd/internal/read_tag)
|
||||
echo "VERSION=${VERSION}" >> "${GITHUB_ENV}"
|
||||
- name: Set Chromium toolchain environment
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl env >> $GITHUB_ENV
|
||||
- name: Set build tags
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.naive }}" == "true" ]]; then
|
||||
TAGS="${TAGS},with_naive_outbound,with_musl"
|
||||
fi
|
||||
echo "BUILD_TAGS=${TAGS}" >> "${GITHUB_ENV}"
|
||||
- name: Build (naive)
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
go build -v -trimpath -o sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=${VERSION}\" -s -w -buildid= -checklinkname=0" \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
- name: Build (non-naive)
|
||||
if: ${{ ! matrix.naive }}
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
go build -v -trimpath -o sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=${VERSION}\" -s -w -buildid= -checklinkname=0" \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "0"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
- name: Prepare artifact
|
||||
run: |
|
||||
platform=${{ matrix.docker_platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
# Rename binary to include arch info for Dockerfile.binary
|
||||
BINARY_NAME="sing-box-${{ matrix.arch }}"
|
||||
if [[ -n "${{ matrix.goarm }}" ]]; then
|
||||
BINARY_NAME="${BINARY_NAME}v${{ matrix.goarm }}"
|
||||
fi
|
||||
mv sing-box "${BINARY_NAME}"
|
||||
echo "BINARY_NAME=${BINARY_NAME}" >> $GITHUB_ENV
|
||||
- name: Upload binary
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: binary-${{ env.PLATFORM_PAIR }}
|
||||
path: ${{ env.BINARY_NAME }}
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
build_docker:
|
||||
name: Build Docker image
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build_binary
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
@@ -177,16 +47,6 @@ jobs:
|
||||
run: |
|
||||
platform=${{ matrix.platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
- name: Download binary
|
||||
uses: actions/download-artifact@v5
|
||||
with:
|
||||
name: binary-${{ env.PLATFORM_PAIR }}
|
||||
path: .
|
||||
- name: Prepare binary
|
||||
run: |
|
||||
# Find and make the binary executable
|
||||
chmod +x sing-box-*
|
||||
ls -la sing-box-*
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
- name: Setup Docker Buildx
|
||||
@@ -208,7 +68,8 @@ jobs:
|
||||
with:
|
||||
platforms: ${{ matrix.platform }}
|
||||
context: .
|
||||
file: Dockerfile.binary
|
||||
build-args: |
|
||||
BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
outputs: type=image,name=${{ env.REGISTRY_IMAGE }},push-by-digest=true,name-canonical=true,push=true
|
||||
- name: Export digest
|
||||
@@ -226,7 +87,7 @@ jobs:
|
||||
merge:
|
||||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- build_docker
|
||||
- build
|
||||
steps:
|
||||
- name: Get commit to build
|
||||
id: ref
|
||||
@@ -260,7 +121,6 @@ jobs:
|
||||
username: ${{ github.repository_owner }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Create manifest list and push
|
||||
if: github.event_name != 'push'
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
docker buildx imagetools create \
|
||||
@@ -268,7 +128,6 @@ jobs:
|
||||
-t "${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.ref }}" \
|
||||
$(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
|
||||
- name: Inspect image
|
||||
if: github.event_name != 'push'
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.latest }}
|
||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.ref }}
|
||||
|
||||
76
.github/workflows/linux.yml
vendored
76
.github/workflows/linux.yml
vendored
@@ -1,10 +1,6 @@
|
||||
name: Build Linux Packages
|
||||
|
||||
on:
|
||||
#push:
|
||||
# branches:
|
||||
# - main-next
|
||||
# - dev-next
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
version:
|
||||
@@ -34,7 +30,7 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
go-version: ^1.25.4
|
||||
- name: Check input version
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: |-
|
||||
@@ -56,13 +52,11 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
# Naive-enabled builds (musl)
|
||||
- { os: linux, arch: amd64, naive: true, debian: amd64, rpm: x86_64, pacman: x86_64 }
|
||||
- { os: linux, arch: arm64, naive: true, debian: arm64, rpm: aarch64, pacman: aarch64 }
|
||||
- { os: linux, arch: "386", naive: true, debian: i386, rpm: i386 }
|
||||
- { os: linux, arch: arm, goarm: "7", naive: true, debian: armhf, rpm: armv7hl, pacman: armv7hl }
|
||||
# Non-naive builds (unsupported architectures)
|
||||
- { os: linux, arch: amd64, debian: amd64, rpm: x86_64, pacman: x86_64 }
|
||||
- { os: linux, arch: "386", debian: i386, rpm: i386 }
|
||||
- { os: linux, arch: arm, goarm: "6", debian: armel, rpm: armv6hl }
|
||||
- { os: linux, arch: arm, goarm: "7", debian: armhf, rpm: armv7hl, pacman: armv7hl }
|
||||
- { os: linux, arch: arm64, debian: arm64, rpm: aarch64, pacman: aarch64 }
|
||||
- { os: linux, arch: mips64le, debian: mips64el, rpm: mips64el }
|
||||
- { os: linux, arch: mipsle, debian: mipsel, rpm: mipsel }
|
||||
- { os: linux, arch: s390x, debian: s390x, rpm: s390x }
|
||||
@@ -77,38 +71,13 @@ jobs:
|
||||
- name: Setup Go
|
||||
uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version: ^1.25.5
|
||||
- name: Clone cronet-go
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
CRONET_GO_VERSION=$(cat .github/CRONET_GO_VERSION)
|
||||
git init ~/cronet-go
|
||||
git -C ~/cronet-go remote add origin https://github.com/sagernet/cronet-go.git
|
||||
git -C ~/cronet-go fetch --depth=1 origin "$CRONET_GO_VERSION"
|
||||
git -C ~/cronet-go checkout FETCH_HEAD
|
||||
git -C ~/cronet-go submodule update --init --recursive --depth=1
|
||||
- name: Cache Chromium toolchain
|
||||
if: matrix.naive
|
||||
id: cache-chromium-toolchain
|
||||
uses: actions/cache@v4
|
||||
go-version: ^1.25.4
|
||||
- name: Setup Android NDK
|
||||
if: matrix.os == 'android'
|
||||
uses: nttld/setup-ndk@v1
|
||||
with:
|
||||
path: |
|
||||
~/cronet-go/naiveproxy/src/third_party/llvm-build/Release+Asserts
|
||||
~/cronet-go/naiveproxy/src/out/sysroot-build
|
||||
key: chromium-toolchain-${{ matrix.arch }}-musl-${{ hashFiles('.github/CRONET_GO_VERSION') }}
|
||||
- name: Download Chromium toolchain
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl download-toolchain
|
||||
- name: Set Chromium toolchain environment
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
cd ~/cronet-go
|
||||
go run ./cmd/build-naive --target=linux/${{ matrix.arch }} --libc=musl env >> $GITHUB_ENV
|
||||
ndk-version: r28
|
||||
local-cache: true
|
||||
- name: Set tag
|
||||
run: |-
|
||||
git ls-remote --exit-code --tags origin v${{ needs.calculate_version.outputs.version }} || echo "PUBLISHED=false" >> "$GITHUB_ENV"
|
||||
@@ -116,27 +85,9 @@ jobs:
|
||||
- name: Set build tags
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0'
|
||||
if [[ "${{ matrix.naive }}" == "true" ]]; then
|
||||
TAGS="${TAGS},with_naive_outbound,with_musl"
|
||||
fi
|
||||
TAGS='with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,badlinkname,tfogo_checklinkname0'
|
||||
echo "BUILD_TAGS=${TAGS}" >> "${GITHUB_ENV}"
|
||||
- name: Build (naive)
|
||||
if: matrix.naive
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
go build -v -trimpath -o dist/sing-box -tags "${BUILD_TAGS}" \
|
||||
-ldflags '-s -buildid= -X github.com/sagernet/sing-box/constant.Version=${{ needs.calculate_version.outputs.version }} -checklinkname=0' \
|
||||
./cmd/sing-box
|
||||
env:
|
||||
CGO_ENABLED: "1"
|
||||
GOOS: linux
|
||||
GOARCH: ${{ matrix.arch }}
|
||||
GOARM: ${{ matrix.goarm }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Build (non-naive)
|
||||
if: ${{ ! matrix.naive }}
|
||||
- name: Build
|
||||
run: |
|
||||
set -xeuo pipefail
|
||||
mkdir -p dist
|
||||
@@ -234,6 +185,5 @@ jobs:
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Publish packages
|
||||
if: github.event_name != 'push'
|
||||
run: |-
|
||||
ls dist | xargs -I {} curl -F "package=@dist/{}" https://${{ secrets.FURY_TOKEN }}@push.fury.io/sagernet/
|
||||
|
||||
@@ -13,7 +13,7 @@ RUN set -ex \
|
||||
&& export COMMIT=$(git rev-parse --short HEAD) \
|
||||
&& export VERSION=$(go run ./cmd/internal/read_tag) \
|
||||
&& go build -v -trimpath -tags \
|
||||
"with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0" \
|
||||
"with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,badlinkname,tfogo_checklinkname0" \
|
||||
-o /go/bin/sing-box \
|
||||
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=$VERSION\" -s -w -buildid= -checklinkname=0" \
|
||||
./cmd/sing-box
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
FROM alpine
|
||||
ARG TARGETARCH
|
||||
ARG TARGETVARIANT
|
||||
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
|
||||
RUN set -ex \
|
||||
&& apk add --no-cache --upgrade bash tzdata ca-certificates nftables
|
||||
COPY sing-box-${TARGETARCH}${TARGETVARIANT} /usr/local/bin/sing-box
|
||||
ENTRYPOINT ["sing-box"]
|
||||
6
Makefile
6
Makefile
@@ -1,6 +1,6 @@
|
||||
NAME = sing-box
|
||||
COMMIT = $(shell git rev-parse --short HEAD)
|
||||
TAGS ?= with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,with_ocm,badlinkname,tfogo_checklinkname0
|
||||
TAGS ?= with_gvisor,with_quic,with_dhcp,with_wireguard,with_utls,with_acme,with_clash_api,with_tailscale,with_ccm,badlinkname,tfogo_checklinkname0
|
||||
|
||||
GOHOSTOS = $(shell go env GOHOSTOS)
|
||||
GOHOSTARCH = $(shell go env GOHOSTARCH)
|
||||
@@ -249,8 +249,8 @@ lib:
|
||||
go run ./cmd/internal/build_libbox -target ios
|
||||
|
||||
lib_install:
|
||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.10
|
||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.10
|
||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.8
|
||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.8
|
||||
|
||||
docs:
|
||||
venv/bin/mkdocs serve
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"encoding/binary"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing/common/observable"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
@@ -15,7 +14,6 @@ type ClashServer interface {
|
||||
ConnectionTracker
|
||||
Mode() string
|
||||
ModeList() []string
|
||||
SetModeUpdateHook(hook *observable.Subscriber[struct{}])
|
||||
HistoryStorage() URLTestHistoryStorage
|
||||
}
|
||||
|
||||
@@ -25,7 +23,7 @@ type URLTestHistory struct {
|
||||
}
|
||||
|
||||
type URLTestHistoryStorage interface {
|
||||
SetHook(hook *observable.Subscriber[struct{}])
|
||||
SetHook(hook chan<- struct{})
|
||||
LoadURLTestHistory(tag string) *URLTestHistory
|
||||
DeleteURLTestHistory(tag string)
|
||||
StoreURLTestHistory(tag string, history *URLTestHistory)
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/common/process"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
@@ -84,7 +85,7 @@ type InboundContext struct {
|
||||
DestinationAddresses []netip.Addr
|
||||
SourceGeoIPCode string
|
||||
GeoIPCode string
|
||||
ProcessInfo *ConnectionOwner
|
||||
ProcessInfo *process.Info
|
||||
QueryType uint16
|
||||
FakeIP bool
|
||||
|
||||
|
||||
@@ -1,70 +0,0 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
)
|
||||
|
||||
type PlatformInterface interface {
|
||||
Initialize(networkManager NetworkManager) error
|
||||
|
||||
UsePlatformAutoDetectInterfaceControl() bool
|
||||
AutoDetectInterfaceControl(fd int) error
|
||||
|
||||
UsePlatformInterface() bool
|
||||
OpenInterface(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error)
|
||||
|
||||
UsePlatformDefaultInterfaceMonitor() bool
|
||||
CreateDefaultInterfaceMonitor(logger logger.Logger) tun.DefaultInterfaceMonitor
|
||||
|
||||
UsePlatformNetworkInterfaces() bool
|
||||
NetworkInterfaces() ([]NetworkInterface, error)
|
||||
|
||||
UnderNetworkExtension() bool
|
||||
NetworkExtensionIncludeAllNetworks() bool
|
||||
|
||||
ClearDNSCache()
|
||||
RequestPermissionForWIFIState() error
|
||||
ReadWIFIState() WIFIState
|
||||
SystemCertificates() []string
|
||||
|
||||
UsePlatformConnectionOwnerFinder() bool
|
||||
FindConnectionOwner(request *FindConnectionOwnerRequest) (*ConnectionOwner, error)
|
||||
|
||||
UsePlatformWIFIMonitor() bool
|
||||
|
||||
UsePlatformNotification() bool
|
||||
SendNotification(notification *Notification) error
|
||||
}
|
||||
|
||||
type FindConnectionOwnerRequest struct {
|
||||
IpProtocol int32
|
||||
SourceAddress string
|
||||
SourcePort int32
|
||||
DestinationAddress string
|
||||
DestinationPort int32
|
||||
}
|
||||
|
||||
type ConnectionOwner struct {
|
||||
ProcessID uint32
|
||||
UserId int32
|
||||
UserName string
|
||||
ProcessPath string
|
||||
AndroidPackageName string
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
Identifier string
|
||||
TypeName string
|
||||
TypeID int32
|
||||
Title string
|
||||
Subtitle string
|
||||
Body string
|
||||
OpenURL string
|
||||
}
|
||||
|
||||
type SystemProxyStatus struct {
|
||||
Available bool
|
||||
Enabled bool
|
||||
}
|
||||
7
box.go
7
box.go
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/sagernet/sing-box/dns/transport/local"
|
||||
"github.com/sagernet/sing-box/experimental"
|
||||
"github.com/sagernet/sing-box/experimental/cachefile"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-box/protocol/direct"
|
||||
@@ -138,7 +139,7 @@ func New(options Options) (*Box, error) {
|
||||
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
|
||||
needV2RayAPI = true
|
||||
}
|
||||
platformInterface := service.FromContext[adapter.PlatformInterface](ctx)
|
||||
platformInterface := service.FromContext[platform.Interface](ctx)
|
||||
var defaultLogWriter io.Writer
|
||||
if platformInterface != nil {
|
||||
defaultLogWriter = io.Discard
|
||||
@@ -526,7 +527,3 @@ func (s *Box) Inbound() adapter.InboundManager {
|
||||
func (s *Box) Outbound() adapter.OutboundManager {
|
||||
return s.outbound
|
||||
}
|
||||
|
||||
func (s *Box) LogFactory() log.Factory {
|
||||
return s.logFactory
|
||||
}
|
||||
|
||||
Submodule clients/android updated: f3763ba71d...3b2c371905
Submodule clients/apple updated: 532c140f05...84d8cf1757
@@ -46,7 +46,7 @@ var (
|
||||
sharedFlags []string
|
||||
debugFlags []string
|
||||
sharedTags []string
|
||||
darwinTags []string
|
||||
macOSTags []string
|
||||
memcTags []string
|
||||
notMemcTags []string
|
||||
debugTags []string
|
||||
@@ -62,8 +62,8 @@ func init() {
|
||||
sharedFlags = append(sharedFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -s -w -buildid= -checklinkname=0")
|
||||
debugFlags = append(debugFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -checklinkname=0")
|
||||
|
||||
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_utls", "with_naive_outbound", "with_clash_api", "with_conntrack", "badlinkname", "tfogo_checklinkname0")
|
||||
darwinTags = append(darwinTags, "with_dhcp")
|
||||
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_utls", "with_clash_api", "with_conntrack", "badlinkname", "tfogo_checklinkname0")
|
||||
macOSTags = append(macOSTags, "with_dhcp")
|
||||
memcTags = append(memcTags, "with_tailscale")
|
||||
notMemcTags = append(notMemcTags, "with_low_memory")
|
||||
debugTags = append(debugTags, "debug")
|
||||
@@ -158,7 +158,9 @@ func buildApple() {
|
||||
"-tags-not-macos=with_low_memory",
|
||||
}
|
||||
if !withTailscale {
|
||||
args = append(args, "-tags-macos="+strings.Join(memcTags, ","))
|
||||
args = append(args, "-tags-macos="+strings.Join(append(macOSTags, memcTags...), ","))
|
||||
} else {
|
||||
args = append(args, "-tags-macos="+strings.Join(macOSTags, ","))
|
||||
}
|
||||
|
||||
if !debugEnabled {
|
||||
@@ -167,7 +169,7 @@ func buildApple() {
|
||||
args = append(args, debugFlags...)
|
||||
}
|
||||
|
||||
tags := append(sharedTags, darwinTags...)
|
||||
tags := sharedTags
|
||||
if withTailscale {
|
||||
tags = append(tags, memcTags...)
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/sagernet/fswatch"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
@@ -35,7 +36,7 @@ func NewStore(ctx context.Context, logger logger.Logger, options option.Certific
|
||||
switch options.Store {
|
||||
case C.CertificateStoreSystem, "":
|
||||
systemPool = x509.NewCertPool()
|
||||
platformInterface := service.FromContext[adapter.PlatformInterface](ctx)
|
||||
platformInterface := service.FromContext[platform.Interface](ctx)
|
||||
var systemValid bool
|
||||
if platformInterface != nil {
|
||||
for _, cert := range platformInterface.SystemCertificates() {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"github.com/sagernet/sing-box/common/conntrack"
|
||||
"github.com/sagernet/sing-box/common/listener"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
@@ -48,7 +49,7 @@ type DefaultDialer struct {
|
||||
|
||||
func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDialer, error) {
|
||||
networkManager := service.FromContext[adapter.NetworkManager](ctx)
|
||||
platformInterface := service.FromContext[adapter.PlatformInterface](ctx)
|
||||
platformInterface := service.FromContext[platform.Interface](ctx)
|
||||
|
||||
var (
|
||||
dialer net.Dialer
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/netip"
|
||||
"os/user"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-tun"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
@@ -13,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
type Searcher interface {
|
||||
FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error)
|
||||
FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error)
|
||||
}
|
||||
|
||||
var ErrNotFound = E.New("process not found")
|
||||
@@ -23,7 +22,15 @@ type Config struct {
|
||||
PackageManager tun.PackageManager
|
||||
}
|
||||
|
||||
func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error) {
|
||||
type Info struct {
|
||||
ProcessID uint32
|
||||
ProcessPath string
|
||||
PackageName string
|
||||
User string
|
||||
UserId int32
|
||||
}
|
||||
|
||||
func FindProcessInfo(searcher Searcher, ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||
info, err := searcher.FindProcessInfo(ctx, network, source, destination)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -31,7 +38,7 @@ func FindProcessInfo(searcher Searcher, ctx context.Context, network string, sou
|
||||
if info.UserId != -1 {
|
||||
osUser, _ := user.LookupId(F.ToString(info.UserId))
|
||||
if osUser != nil {
|
||||
info.UserName = osUser.Username
|
||||
info.User = osUser.Username
|
||||
}
|
||||
}
|
||||
return info, nil
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"net/netip"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-tun"
|
||||
)
|
||||
|
||||
@@ -18,22 +17,22 @@ func NewSearcher(config Config) (Searcher, error) {
|
||||
return &androidSearcher{config.PackageManager}, nil
|
||||
}
|
||||
|
||||
func (s *androidSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error) {
|
||||
func (s *androidSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||
_, uid, err := resolveSocketByNetlink(network, source, destination)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if sharedPackage, loaded := s.packageManager.SharedPackageByID(uid % 100000); loaded {
|
||||
return &adapter.ConnectionOwner{
|
||||
UserId: int32(uid),
|
||||
AndroidPackageName: sharedPackage,
|
||||
return &Info{
|
||||
UserId: int32(uid),
|
||||
PackageName: sharedPackage,
|
||||
}, nil
|
||||
}
|
||||
if packageName, loaded := s.packageManager.PackageByID(uid % 100000); loaded {
|
||||
return &adapter.ConnectionOwner{
|
||||
UserId: int32(uid),
|
||||
AndroidPackageName: packageName,
|
||||
return &Info{
|
||||
UserId: int32(uid),
|
||||
PackageName: packageName,
|
||||
}, nil
|
||||
}
|
||||
return &adapter.ConnectionOwner{UserId: int32(uid)}, nil
|
||||
return &Info{UserId: int32(uid)}, nil
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
@@ -24,12 +23,12 @@ func NewSearcher(_ Config) (Searcher, error) {
|
||||
return &darwinSearcher{}, nil
|
||||
}
|
||||
|
||||
func (d *darwinSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error) {
|
||||
func (d *darwinSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||
processName, err := findProcessName(network, source.Addr(), int(source.Port()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &adapter.ConnectionOwner{ProcessPath: processName, UserId: -1}, nil
|
||||
return &Info{ProcessPath: processName, UserId: -1}, nil
|
||||
}
|
||||
|
||||
var structSize = func() int {
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"context"
|
||||
"net/netip"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
)
|
||||
|
||||
@@ -20,7 +19,7 @@ func NewSearcher(config Config) (Searcher, error) {
|
||||
return &linuxSearcher{config.Logger}, nil
|
||||
}
|
||||
|
||||
func (s *linuxSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error) {
|
||||
func (s *linuxSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||
inode, uid, err := resolveSocketByNetlink(network, source, destination)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -29,7 +28,7 @@ func (s *linuxSearcher) FindProcessInfo(ctx context.Context, network string, sou
|
||||
if err != nil {
|
||||
s.logger.DebugContext(ctx, "find process path: ", err)
|
||||
}
|
||||
return &adapter.ConnectionOwner{
|
||||
return &Info{
|
||||
UserId: int32(uid),
|
||||
ProcessPath: processPath,
|
||||
}, nil
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"net/netip"
|
||||
"syscall"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/winiphlpapi"
|
||||
|
||||
@@ -28,16 +27,16 @@ func initWin32API() error {
|
||||
return winiphlpapi.LoadExtendedTable()
|
||||
}
|
||||
|
||||
func (s *windowsSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*adapter.ConnectionOwner, error) {
|
||||
func (s *windowsSearcher) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*Info, error) {
|
||||
pid, err := winiphlpapi.FindPid(network, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path, err := getProcessPath(pid)
|
||||
if err != nil {
|
||||
return &adapter.ConnectionOwner{ProcessID: pid, UserId: -1}, err
|
||||
return &Info{ProcessID: pid, UserId: -1}, err
|
||||
}
|
||||
return &adapter.ConnectionOwner{ProcessID: pid, ProcessPath: path, UserId: -1}, nil
|
||||
return &Info{ProcessID: pid, ProcessPath: path, UserId: -1}, nil
|
||||
}
|
||||
|
||||
func getProcessPath(pid uint32) (string, error) {
|
||||
|
||||
@@ -51,7 +51,6 @@ func parseECHClientConfig(ctx context.Context, clientConfig ECHCapableConfig, op
|
||||
return &ECHClientConfig{
|
||||
ECHCapableConfig: clientConfig,
|
||||
dnsRouter: service.FromContext[adapter.DNSRouter](ctx),
|
||||
queryServerName: options.ECH.QueryServerName,
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
@@ -109,11 +108,10 @@ func parseECHKeys(echKey []byte) ([]tls.EncryptedClientHelloKey, error) {
|
||||
|
||||
type ECHClientConfig struct {
|
||||
ECHCapableConfig
|
||||
access sync.Mutex
|
||||
dnsRouter adapter.DNSRouter
|
||||
queryServerName string
|
||||
lastTTL time.Duration
|
||||
lastUpdate time.Time
|
||||
access sync.Mutex
|
||||
dnsRouter adapter.DNSRouter
|
||||
lastTTL time.Duration
|
||||
lastUpdate time.Time
|
||||
}
|
||||
|
||||
func (s *ECHClientConfig) ClientHandshake(ctx context.Context, conn net.Conn) (aTLS.Conn, error) {
|
||||
@@ -132,17 +130,13 @@ func (s *ECHClientConfig) fetchAndHandshake(ctx context.Context, conn net.Conn)
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
if len(s.ECHConfigList()) == 0 || s.lastTTL == 0 || time.Since(s.lastUpdate) > s.lastTTL {
|
||||
queryServerName := s.queryServerName
|
||||
if queryServerName == "" {
|
||||
queryServerName = s.ServerName()
|
||||
}
|
||||
message := &mDNS.Msg{
|
||||
MsgHdr: mDNS.MsgHdr{
|
||||
RecursionDesired: true,
|
||||
},
|
||||
Question: []mDNS.Question{
|
||||
{
|
||||
Name: mDNS.Fqdn(queryServerName),
|
||||
Name: mDNS.Fqdn(s.ServerName()),
|
||||
Qtype: mDNS.TypeHTTPS,
|
||||
Qclass: mDNS.ClassINET,
|
||||
},
|
||||
@@ -181,12 +175,7 @@ func (s *ECHClientConfig) fetchAndHandshake(ctx context.Context, conn net.Conn)
|
||||
}
|
||||
|
||||
func (s *ECHClientConfig) Clone() Config {
|
||||
return &ECHClientConfig{
|
||||
ECHCapableConfig: s.ECHCapableConfig.Clone().(ECHCapableConfig),
|
||||
dnsRouter: s.dnsRouter,
|
||||
queryServerName: s.queryServerName,
|
||||
lastUpdate: s.lastUpdate,
|
||||
}
|
||||
return &ECHClientConfig{ECHCapableConfig: s.ECHCapableConfig.Clone().(ECHCapableConfig), dnsRouter: s.dnsRouter, lastUpdate: s.lastUpdate}
|
||||
}
|
||||
|
||||
func UnmarshalECHKeys(raw []byte) ([]tls.EncryptedClientHelloKey, error) {
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/common/ntp"
|
||||
"github.com/sagernet/sing/common/observable"
|
||||
)
|
||||
|
||||
var _ adapter.URLTestHistoryStorage = (*HistoryStorage)(nil)
|
||||
@@ -22,7 +21,7 @@ var _ adapter.URLTestHistoryStorage = (*HistoryStorage)(nil)
|
||||
type HistoryStorage struct {
|
||||
access sync.RWMutex
|
||||
delayHistory map[string]*adapter.URLTestHistory
|
||||
updateHook *observable.Subscriber[struct{}]
|
||||
updateHook chan<- struct{}
|
||||
}
|
||||
|
||||
func NewHistoryStorage() *HistoryStorage {
|
||||
@@ -31,7 +30,7 @@ func NewHistoryStorage() *HistoryStorage {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *HistoryStorage) SetHook(hook *observable.Subscriber[struct{}]) {
|
||||
func (s *HistoryStorage) SetHook(hook chan<- struct{}) {
|
||||
s.updateHook = hook
|
||||
}
|
||||
|
||||
@@ -61,7 +60,10 @@ func (s *HistoryStorage) StoreURLTestHistory(tag string, history *adapter.URLTes
|
||||
func (s *HistoryStorage) notifyUpdated() {
|
||||
updateHook := s.updateHook
|
||||
if updateHook != nil {
|
||||
updateHook.Emit(struct{}{})
|
||||
select {
|
||||
case updateHook <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,5 +4,5 @@ import "time"
|
||||
|
||||
const (
|
||||
DHCPTTL = time.Hour
|
||||
DHCPTimeout = 5 * time.Second
|
||||
DHCPTimeout = time.Minute
|
||||
)
|
||||
|
||||
@@ -29,7 +29,6 @@ const (
|
||||
TypeResolved = "resolved"
|
||||
TypeSSMAPI = "ssm-api"
|
||||
TypeCCM = "ccm"
|
||||
TypeOCM = "ocm"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
var _ deprecated.Manager = (*deprecatedManager)(nil)
|
||||
|
||||
type deprecatedManager struct {
|
||||
access sync.Mutex
|
||||
notes []deprecated.Note
|
||||
}
|
||||
|
||||
func (m *deprecatedManager) ReportDeprecated(feature deprecated.Note) {
|
||||
m.access.Lock()
|
||||
defer m.access.Unlock()
|
||||
m.notes = common.Uniq(append(m.notes, feature))
|
||||
}
|
||||
|
||||
func (m *deprecatedManager) Get() []deprecated.Note {
|
||||
m.access.Lock()
|
||||
defer m.access.Unlock()
|
||||
notes := m.notes
|
||||
m.notes = nil
|
||||
return notes
|
||||
}
|
||||
@@ -1,702 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
reflect "reflect"
|
||||
sync "sync"
|
||||
unsafe "unsafe"
|
||||
|
||||
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
|
||||
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
|
||||
emptypb "google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
const (
|
||||
// Verify that this generated code is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
|
||||
// Verify that runtime/protoimpl is sufficiently up-to-date.
|
||||
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
|
||||
)
|
||||
|
||||
type SubscribeHelperRequestRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
AcceptGetWIFIStateRequests bool `protobuf:"varint,1,opt,name=acceptGetWIFIStateRequests,proto3" json:"acceptGetWIFIStateRequests,omitempty"`
|
||||
AcceptFindConnectionOwnerRequests bool `protobuf:"varint,2,opt,name=acceptFindConnectionOwnerRequests,proto3" json:"acceptFindConnectionOwnerRequests,omitempty"`
|
||||
AcceptSendNotificationRequests bool `protobuf:"varint,3,opt,name=acceptSendNotificationRequests,proto3" json:"acceptSendNotificationRequests,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) Reset() {
|
||||
*x = SubscribeHelperRequestRequest{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[0]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*SubscribeHelperRequestRequest) ProtoMessage() {}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[0]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use SubscribeHelperRequestRequest.ProtoReflect.Descriptor instead.
|
||||
func (*SubscribeHelperRequestRequest) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{0}
|
||||
}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) GetAcceptGetWIFIStateRequests() bool {
|
||||
if x != nil {
|
||||
return x.AcceptGetWIFIStateRequests
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) GetAcceptFindConnectionOwnerRequests() bool {
|
||||
if x != nil {
|
||||
return x.AcceptFindConnectionOwnerRequests
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (x *SubscribeHelperRequestRequest) GetAcceptSendNotificationRequests() bool {
|
||||
if x != nil {
|
||||
return x.AcceptSendNotificationRequests
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type HelperRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
// Types that are valid to be assigned to Request:
|
||||
//
|
||||
// *HelperRequest_GetWIFIState
|
||||
// *HelperRequest_FindConnectionOwner
|
||||
// *HelperRequest_SendNotification
|
||||
Request isHelperRequest_Request `protobuf_oneof:"request"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HelperRequest) Reset() {
|
||||
*x = HelperRequest{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[1]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HelperRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HelperRequest) ProtoMessage() {}
|
||||
|
||||
func (x *HelperRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[1]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HelperRequest.ProtoReflect.Descriptor instead.
|
||||
func (*HelperRequest) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{1}
|
||||
}
|
||||
|
||||
func (x *HelperRequest) GetId() int64 {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *HelperRequest) GetRequest() isHelperRequest_Request {
|
||||
if x != nil {
|
||||
return x.Request
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *HelperRequest) GetGetWIFIState() *emptypb.Empty {
|
||||
if x != nil {
|
||||
if x, ok := x.Request.(*HelperRequest_GetWIFIState); ok {
|
||||
return x.GetWIFIState
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *HelperRequest) GetFindConnectionOwner() *FindConnectionOwnerRequest {
|
||||
if x != nil {
|
||||
if x, ok := x.Request.(*HelperRequest_FindConnectionOwner); ok {
|
||||
return x.FindConnectionOwner
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *HelperRequest) GetSendNotification() *Notification {
|
||||
if x != nil {
|
||||
if x, ok := x.Request.(*HelperRequest_SendNotification); ok {
|
||||
return x.SendNotification
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type isHelperRequest_Request interface {
|
||||
isHelperRequest_Request()
|
||||
}
|
||||
|
||||
type HelperRequest_GetWIFIState struct {
|
||||
GetWIFIState *emptypb.Empty `protobuf:"bytes,2,opt,name=getWIFIState,proto3,oneof"`
|
||||
}
|
||||
|
||||
type HelperRequest_FindConnectionOwner struct {
|
||||
FindConnectionOwner *FindConnectionOwnerRequest `protobuf:"bytes,3,opt,name=findConnectionOwner,proto3,oneof"`
|
||||
}
|
||||
|
||||
type HelperRequest_SendNotification struct {
|
||||
SendNotification *Notification `protobuf:"bytes,4,opt,name=sendNotification,proto3,oneof"`
|
||||
}
|
||||
|
||||
func (*HelperRequest_GetWIFIState) isHelperRequest_Request() {}
|
||||
|
||||
func (*HelperRequest_FindConnectionOwner) isHelperRequest_Request() {}
|
||||
|
||||
func (*HelperRequest_SendNotification) isHelperRequest_Request() {}
|
||||
|
||||
type FindConnectionOwnerRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
IpProtocol int32 `protobuf:"varint,1,opt,name=ipProtocol,proto3" json:"ipProtocol,omitempty"`
|
||||
SourceAddress string `protobuf:"bytes,2,opt,name=sourceAddress,proto3" json:"sourceAddress,omitempty"`
|
||||
SourcePort int32 `protobuf:"varint,3,opt,name=sourcePort,proto3" json:"sourcePort,omitempty"`
|
||||
DestinationAddress string `protobuf:"bytes,4,opt,name=destinationAddress,proto3" json:"destinationAddress,omitempty"`
|
||||
DestinationPort int32 `protobuf:"varint,5,opt,name=destinationPort,proto3" json:"destinationPort,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) Reset() {
|
||||
*x = FindConnectionOwnerRequest{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[2]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*FindConnectionOwnerRequest) ProtoMessage() {}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[2]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use FindConnectionOwnerRequest.ProtoReflect.Descriptor instead.
|
||||
func (*FindConnectionOwnerRequest) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{2}
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) GetIpProtocol() int32 {
|
||||
if x != nil {
|
||||
return x.IpProtocol
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) GetSourceAddress() string {
|
||||
if x != nil {
|
||||
return x.SourceAddress
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) GetSourcePort() int32 {
|
||||
if x != nil {
|
||||
return x.SourcePort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) GetDestinationAddress() string {
|
||||
if x != nil {
|
||||
return x.DestinationAddress
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *FindConnectionOwnerRequest) GetDestinationPort() int32 {
|
||||
if x != nil {
|
||||
return x.DestinationPort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Identifier string `protobuf:"bytes,1,opt,name=identifier,proto3" json:"identifier,omitempty"`
|
||||
TypeName string `protobuf:"bytes,2,opt,name=typeName,proto3" json:"typeName,omitempty"`
|
||||
TypeId int32 `protobuf:"varint,3,opt,name=typeId,proto3" json:"typeId,omitempty"`
|
||||
Title string `protobuf:"bytes,4,opt,name=title,proto3" json:"title,omitempty"`
|
||||
Subtitle string `protobuf:"bytes,5,opt,name=subtitle,proto3" json:"subtitle,omitempty"`
|
||||
Body string `protobuf:"bytes,6,opt,name=body,proto3" json:"body,omitempty"`
|
||||
OpenURL string `protobuf:"bytes,7,opt,name=openURL,proto3" json:"openURL,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *Notification) Reset() {
|
||||
*x = Notification{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[3]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *Notification) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*Notification) ProtoMessage() {}
|
||||
|
||||
func (x *Notification) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[3]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use Notification.ProtoReflect.Descriptor instead.
|
||||
func (*Notification) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{3}
|
||||
}
|
||||
|
||||
func (x *Notification) GetIdentifier() string {
|
||||
if x != nil {
|
||||
return x.Identifier
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Notification) GetTypeName() string {
|
||||
if x != nil {
|
||||
return x.TypeName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Notification) GetTypeId() int32 {
|
||||
if x != nil {
|
||||
return x.TypeId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *Notification) GetTitle() string {
|
||||
if x != nil {
|
||||
return x.Title
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Notification) GetSubtitle() string {
|
||||
if x != nil {
|
||||
return x.Subtitle
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Notification) GetBody() string {
|
||||
if x != nil {
|
||||
return x.Body
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *Notification) GetOpenURL() string {
|
||||
if x != nil {
|
||||
return x.OpenURL
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type HelperResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"`
|
||||
// Types that are valid to be assigned to Response:
|
||||
//
|
||||
// *HelperResponse_WifiState
|
||||
// *HelperResponse_Error
|
||||
// *HelperResponse_ConnectionOwner
|
||||
Response isHelperResponse_Response `protobuf_oneof:"response"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *HelperResponse) Reset() {
|
||||
*x = HelperResponse{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[4]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *HelperResponse) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*HelperResponse) ProtoMessage() {}
|
||||
|
||||
func (x *HelperResponse) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[4]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use HelperResponse.ProtoReflect.Descriptor instead.
|
||||
func (*HelperResponse) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{4}
|
||||
}
|
||||
|
||||
func (x *HelperResponse) GetId() int64 {
|
||||
if x != nil {
|
||||
return x.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *HelperResponse) GetResponse() isHelperResponse_Response {
|
||||
if x != nil {
|
||||
return x.Response
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *HelperResponse) GetWifiState() *WIFIState {
|
||||
if x != nil {
|
||||
if x, ok := x.Response.(*HelperResponse_WifiState); ok {
|
||||
return x.WifiState
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (x *HelperResponse) GetError() string {
|
||||
if x != nil {
|
||||
if x, ok := x.Response.(*HelperResponse_Error); ok {
|
||||
return x.Error
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *HelperResponse) GetConnectionOwner() *ConnectionOwner {
|
||||
if x != nil {
|
||||
if x, ok := x.Response.(*HelperResponse_ConnectionOwner); ok {
|
||||
return x.ConnectionOwner
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type isHelperResponse_Response interface {
|
||||
isHelperResponse_Response()
|
||||
}
|
||||
|
||||
type HelperResponse_WifiState struct {
|
||||
WifiState *WIFIState `protobuf:"bytes,2,opt,name=wifiState,proto3,oneof"`
|
||||
}
|
||||
|
||||
type HelperResponse_Error struct {
|
||||
Error string `protobuf:"bytes,3,opt,name=error,proto3,oneof"`
|
||||
}
|
||||
|
||||
type HelperResponse_ConnectionOwner struct {
|
||||
ConnectionOwner *ConnectionOwner `protobuf:"bytes,4,opt,name=connectionOwner,proto3,oneof"`
|
||||
}
|
||||
|
||||
func (*HelperResponse_WifiState) isHelperResponse_Response() {}
|
||||
|
||||
func (*HelperResponse_Error) isHelperResponse_Response() {}
|
||||
|
||||
func (*HelperResponse_ConnectionOwner) isHelperResponse_Response() {}
|
||||
|
||||
type ConnectionOwner struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
UserId int32 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"`
|
||||
UserName string `protobuf:"bytes,2,opt,name=userName,proto3" json:"userName,omitempty"`
|
||||
ProcessPath string `protobuf:"bytes,3,opt,name=processPath,proto3" json:"processPath,omitempty"`
|
||||
AndroidPackageName string `protobuf:"bytes,4,opt,name=androidPackageName,proto3" json:"androidPackageName,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) Reset() {
|
||||
*x = ConnectionOwner{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[5]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*ConnectionOwner) ProtoMessage() {}
|
||||
|
||||
func (x *ConnectionOwner) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[5]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use ConnectionOwner.ProtoReflect.Descriptor instead.
|
||||
func (*ConnectionOwner) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{5}
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) GetUserId() int32 {
|
||||
if x != nil {
|
||||
return x.UserId
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) GetUserName() string {
|
||||
if x != nil {
|
||||
return x.UserName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) GetProcessPath() string {
|
||||
if x != nil {
|
||||
return x.ProcessPath
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *ConnectionOwner) GetAndroidPackageName() string {
|
||||
if x != nil {
|
||||
return x.AndroidPackageName
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type WIFIState struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
Ssid string `protobuf:"bytes,1,opt,name=ssid,proto3" json:"ssid,omitempty"`
|
||||
Bssid string `protobuf:"bytes,2,opt,name=bssid,proto3" json:"bssid,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *WIFIState) Reset() {
|
||||
*x = WIFIState{}
|
||||
mi := &file_daemon_helper_proto_msgTypes[6]
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
|
||||
func (x *WIFIState) String() string {
|
||||
return protoimpl.X.MessageStringOf(x)
|
||||
}
|
||||
|
||||
func (*WIFIState) ProtoMessage() {}
|
||||
|
||||
func (x *WIFIState) ProtoReflect() protoreflect.Message {
|
||||
mi := &file_daemon_helper_proto_msgTypes[6]
|
||||
if x != nil {
|
||||
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||
if ms.LoadMessageInfo() == nil {
|
||||
ms.StoreMessageInfo(mi)
|
||||
}
|
||||
return ms
|
||||
}
|
||||
return mi.MessageOf(x)
|
||||
}
|
||||
|
||||
// Deprecated: Use WIFIState.ProtoReflect.Descriptor instead.
|
||||
func (*WIFIState) Descriptor() ([]byte, []int) {
|
||||
return file_daemon_helper_proto_rawDescGZIP(), []int{6}
|
||||
}
|
||||
|
||||
func (x *WIFIState) GetSsid() string {
|
||||
if x != nil {
|
||||
return x.Ssid
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (x *WIFIState) GetBssid() string {
|
||||
if x != nil {
|
||||
return x.Bssid
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
var File_daemon_helper_proto protoreflect.FileDescriptor
|
||||
|
||||
const file_daemon_helper_proto_rawDesc = "" +
|
||||
"\n" +
|
||||
"\x13daemon/helper.proto\x12\x06daemon\x1a\x1bgoogle/protobuf/empty.proto\"\xf5\x01\n" +
|
||||
"\x1dSubscribeHelperRequestRequest\x12>\n" +
|
||||
"\x1aacceptGetWIFIStateRequests\x18\x01 \x01(\bR\x1aacceptGetWIFIStateRequests\x12L\n" +
|
||||
"!acceptFindConnectionOwnerRequests\x18\x02 \x01(\bR!acceptFindConnectionOwnerRequests\x12F\n" +
|
||||
"\x1eacceptSendNotificationRequests\x18\x03 \x01(\bR\x1eacceptSendNotificationRequests\"\x84\x02\n" +
|
||||
"\rHelperRequest\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x12<\n" +
|
||||
"\fgetWIFIState\x18\x02 \x01(\v2\x16.google.protobuf.EmptyH\x00R\fgetWIFIState\x12V\n" +
|
||||
"\x13findConnectionOwner\x18\x03 \x01(\v2\".daemon.FindConnectionOwnerRequestH\x00R\x13findConnectionOwner\x12B\n" +
|
||||
"\x10sendNotification\x18\x04 \x01(\v2\x14.daemon.NotificationH\x00R\x10sendNotificationB\t\n" +
|
||||
"\arequest\"\xdc\x01\n" +
|
||||
"\x1aFindConnectionOwnerRequest\x12\x1e\n" +
|
||||
"\n" +
|
||||
"ipProtocol\x18\x01 \x01(\x05R\n" +
|
||||
"ipProtocol\x12$\n" +
|
||||
"\rsourceAddress\x18\x02 \x01(\tR\rsourceAddress\x12\x1e\n" +
|
||||
"\n" +
|
||||
"sourcePort\x18\x03 \x01(\x05R\n" +
|
||||
"sourcePort\x12.\n" +
|
||||
"\x12destinationAddress\x18\x04 \x01(\tR\x12destinationAddress\x12(\n" +
|
||||
"\x0fdestinationPort\x18\x05 \x01(\x05R\x0fdestinationPort\"\xc2\x01\n" +
|
||||
"\fNotification\x12\x1e\n" +
|
||||
"\n" +
|
||||
"identifier\x18\x01 \x01(\tR\n" +
|
||||
"identifier\x12\x1a\n" +
|
||||
"\btypeName\x18\x02 \x01(\tR\btypeName\x12\x16\n" +
|
||||
"\x06typeId\x18\x03 \x01(\x05R\x06typeId\x12\x14\n" +
|
||||
"\x05title\x18\x04 \x01(\tR\x05title\x12\x1a\n" +
|
||||
"\bsubtitle\x18\x05 \x01(\tR\bsubtitle\x12\x12\n" +
|
||||
"\x04body\x18\x06 \x01(\tR\x04body\x12\x18\n" +
|
||||
"\aopenURL\x18\a \x01(\tR\aopenURL\"\xbc\x01\n" +
|
||||
"\x0eHelperResponse\x12\x0e\n" +
|
||||
"\x02id\x18\x01 \x01(\x03R\x02id\x121\n" +
|
||||
"\twifiState\x18\x02 \x01(\v2\x11.daemon.WIFIStateH\x00R\twifiState\x12\x16\n" +
|
||||
"\x05error\x18\x03 \x01(\tH\x00R\x05error\x12C\n" +
|
||||
"\x0fconnectionOwner\x18\x04 \x01(\v2\x17.daemon.ConnectionOwnerH\x00R\x0fconnectionOwnerB\n" +
|
||||
"\n" +
|
||||
"\bresponse\"\x97\x01\n" +
|
||||
"\x0fConnectionOwner\x12\x16\n" +
|
||||
"\x06userId\x18\x01 \x01(\x05R\x06userId\x12\x1a\n" +
|
||||
"\buserName\x18\x02 \x01(\tR\buserName\x12 \n" +
|
||||
"\vprocessPath\x18\x03 \x01(\tR\vprocessPath\x12.\n" +
|
||||
"\x12androidPackageName\x18\x04 \x01(\tR\x12androidPackageName\"5\n" +
|
||||
"\tWIFIState\x12\x12\n" +
|
||||
"\x04ssid\x18\x01 \x01(\tR\x04ssid\x12\x14\n" +
|
||||
"\x05bssid\x18\x02 \x01(\tR\x05bssidB%Z#github.com/sagernet/sing-box/daemonb\x06proto3"
|
||||
|
||||
var (
|
||||
file_daemon_helper_proto_rawDescOnce sync.Once
|
||||
file_daemon_helper_proto_rawDescData []byte
|
||||
)
|
||||
|
||||
func file_daemon_helper_proto_rawDescGZIP() []byte {
|
||||
file_daemon_helper_proto_rawDescOnce.Do(func() {
|
||||
file_daemon_helper_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_daemon_helper_proto_rawDesc), len(file_daemon_helper_proto_rawDesc)))
|
||||
})
|
||||
return file_daemon_helper_proto_rawDescData
|
||||
}
|
||||
|
||||
var (
|
||||
file_daemon_helper_proto_msgTypes = make([]protoimpl.MessageInfo, 7)
|
||||
file_daemon_helper_proto_goTypes = []any{
|
||||
(*SubscribeHelperRequestRequest)(nil), // 0: daemon.SubscribeHelperRequestRequest
|
||||
(*HelperRequest)(nil), // 1: daemon.HelperRequest
|
||||
(*FindConnectionOwnerRequest)(nil), // 2: daemon.FindConnectionOwnerRequest
|
||||
(*Notification)(nil), // 3: daemon.Notification
|
||||
(*HelperResponse)(nil), // 4: daemon.HelperResponse
|
||||
(*ConnectionOwner)(nil), // 5: daemon.ConnectionOwner
|
||||
(*WIFIState)(nil), // 6: daemon.WIFIState
|
||||
(*emptypb.Empty)(nil), // 7: google.protobuf.Empty
|
||||
}
|
||||
)
|
||||
|
||||
var file_daemon_helper_proto_depIdxs = []int32{
|
||||
7, // 0: daemon.HelperRequest.getWIFIState:type_name -> google.protobuf.Empty
|
||||
2, // 1: daemon.HelperRequest.findConnectionOwner:type_name -> daemon.FindConnectionOwnerRequest
|
||||
3, // 2: daemon.HelperRequest.sendNotification:type_name -> daemon.Notification
|
||||
6, // 3: daemon.HelperResponse.wifiState:type_name -> daemon.WIFIState
|
||||
5, // 4: daemon.HelperResponse.connectionOwner:type_name -> daemon.ConnectionOwner
|
||||
5, // [5:5] is the sub-list for method output_type
|
||||
5, // [5:5] is the sub-list for method input_type
|
||||
5, // [5:5] is the sub-list for extension type_name
|
||||
5, // [5:5] is the sub-list for extension extendee
|
||||
0, // [0:5] is the sub-list for field type_name
|
||||
}
|
||||
|
||||
func init() { file_daemon_helper_proto_init() }
|
||||
func file_daemon_helper_proto_init() {
|
||||
if File_daemon_helper_proto != nil {
|
||||
return
|
||||
}
|
||||
file_daemon_helper_proto_msgTypes[1].OneofWrappers = []any{
|
||||
(*HelperRequest_GetWIFIState)(nil),
|
||||
(*HelperRequest_FindConnectionOwner)(nil),
|
||||
(*HelperRequest_SendNotification)(nil),
|
||||
}
|
||||
file_daemon_helper_proto_msgTypes[4].OneofWrappers = []any{
|
||||
(*HelperResponse_WifiState)(nil),
|
||||
(*HelperResponse_Error)(nil),
|
||||
(*HelperResponse_ConnectionOwner)(nil),
|
||||
}
|
||||
type x struct{}
|
||||
out := protoimpl.TypeBuilder{
|
||||
File: protoimpl.DescBuilder{
|
||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_daemon_helper_proto_rawDesc), len(file_daemon_helper_proto_rawDesc)),
|
||||
NumEnums: 0,
|
||||
NumMessages: 7,
|
||||
NumExtensions: 0,
|
||||
NumServices: 0,
|
||||
},
|
||||
GoTypes: file_daemon_helper_proto_goTypes,
|
||||
DependencyIndexes: file_daemon_helper_proto_depIdxs,
|
||||
MessageInfos: file_daemon_helper_proto_msgTypes,
|
||||
}.Build()
|
||||
File_daemon_helper_proto = out.File
|
||||
file_daemon_helper_proto_goTypes = nil
|
||||
file_daemon_helper_proto_depIdxs = nil
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package daemon;
|
||||
option go_package = "github.com/sagernet/sing-box/daemon";
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
|
||||
message SubscribeHelperRequestRequest {
|
||||
bool acceptGetWIFIStateRequests = 1;
|
||||
bool acceptFindConnectionOwnerRequests = 2;
|
||||
bool acceptSendNotificationRequests = 3;
|
||||
}
|
||||
|
||||
message HelperRequest {
|
||||
int64 id = 1;
|
||||
oneof request {
|
||||
google.protobuf.Empty getWIFIState = 2;
|
||||
FindConnectionOwnerRequest findConnectionOwner = 3;
|
||||
Notification sendNotification = 4;
|
||||
}
|
||||
}
|
||||
|
||||
message FindConnectionOwnerRequest {
|
||||
int32 ipProtocol = 1;
|
||||
string sourceAddress = 2;
|
||||
int32 sourcePort = 3;
|
||||
string destinationAddress = 4;
|
||||
int32 destinationPort = 5;
|
||||
}
|
||||
|
||||
message Notification {
|
||||
string identifier = 1;
|
||||
string typeName = 2;
|
||||
int32 typeId = 3;
|
||||
string title = 4;
|
||||
string subtitle = 5;
|
||||
string body = 6;
|
||||
string openURL = 7;
|
||||
}
|
||||
|
||||
message HelperResponse {
|
||||
int64 id = 1;
|
||||
oneof response {
|
||||
WIFIState wifiState = 2;
|
||||
string error = 3;
|
||||
ConnectionOwner connectionOwner = 4;
|
||||
}
|
||||
}
|
||||
|
||||
message ConnectionOwner {
|
||||
int32 userId = 1;
|
||||
string userName = 2;
|
||||
string processPath = 3;
|
||||
string androidPackageName = 4;
|
||||
}
|
||||
|
||||
message WIFIState {
|
||||
string ssid = 1;
|
||||
string bssid = 2;
|
||||
}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
|
||||
"github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing-box/include"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
"github.com/sagernet/sing/service"
|
||||
"github.com/sagernet/sing/service/pause"
|
||||
)
|
||||
|
||||
type Instance struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
instance *box.Box
|
||||
clashServer adapter.ClashServer
|
||||
cacheFile adapter.CacheFile
|
||||
pauseManager pause.Manager
|
||||
urlTestHistoryStorage *urltest.HistoryStorage
|
||||
}
|
||||
|
||||
func (s *StartedService) CheckConfig(configContent string) error {
|
||||
options, err := parseConfig(s.ctx, configContent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, cancel := context.WithCancel(s.ctx)
|
||||
defer cancel()
|
||||
instance, err := box.New(box.Options{
|
||||
Context: ctx,
|
||||
Options: options,
|
||||
})
|
||||
if err == nil {
|
||||
instance.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *StartedService) FormatConfig(configContent string) (string, error) {
|
||||
options, err := parseConfig(s.ctx, configContent)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var buffer bytes.Buffer
|
||||
encoder := json.NewEncoder(&buffer)
|
||||
encoder.SetIndent("", " ")
|
||||
err = encoder.Encode(options)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return buffer.String(), nil
|
||||
}
|
||||
|
||||
type OverrideOptions struct {
|
||||
AutoRedirect bool
|
||||
IncludePackage []string
|
||||
ExcludePackage []string
|
||||
}
|
||||
|
||||
func (s *StartedService) newInstance(profileContent string, overrideOptions *OverrideOptions) (*Instance, error) {
|
||||
ctx := s.ctx
|
||||
service.MustRegister[deprecated.Manager](ctx, new(deprecatedManager))
|
||||
ctx, cancel := context.WithCancel(include.Context(ctx))
|
||||
options, err := parseConfig(ctx, profileContent)
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
if overrideOptions != nil {
|
||||
for _, inbound := range options.Inbounds {
|
||||
if tunInboundOptions, isTUN := inbound.Options.(*option.TunInboundOptions); isTUN {
|
||||
tunInboundOptions.AutoRedirect = overrideOptions.AutoRedirect
|
||||
tunInboundOptions.IncludePackage = append(tunInboundOptions.IncludePackage, overrideOptions.IncludePackage...)
|
||||
tunInboundOptions.ExcludePackage = append(tunInboundOptions.ExcludePackage, overrideOptions.ExcludePackage...)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
urlTestHistoryStorage := urltest.NewHistoryStorage()
|
||||
ctx = service.ContextWithPtr(ctx, urlTestHistoryStorage)
|
||||
i := &Instance{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
urlTestHistoryStorage: urlTestHistoryStorage,
|
||||
}
|
||||
boxInstance, err := box.New(box.Options{
|
||||
Context: ctx,
|
||||
Options: options,
|
||||
PlatformLogWriter: s,
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
i.instance = boxInstance
|
||||
i.clashServer = service.FromContext[adapter.ClashServer](ctx)
|
||||
i.pauseManager = service.FromContext[pause.Manager](ctx)
|
||||
i.cacheFile = service.FromContext[adapter.CacheFile](ctx)
|
||||
return i, nil
|
||||
}
|
||||
|
||||
func (i *Instance) Start() error {
|
||||
return i.instance.Start()
|
||||
}
|
||||
|
||||
func (i *Instance) Close() error {
|
||||
i.cancel()
|
||||
i.urlTestHistoryStorage.Close()
|
||||
return i.instance.Close()
|
||||
}
|
||||
|
||||
func (i *Instance) Box() *box.Box {
|
||||
return i.instance
|
||||
}
|
||||
|
||||
func (i *Instance) PauseManager() pause.Manager {
|
||||
return i.pauseManager
|
||||
}
|
||||
|
||||
func parseConfig(ctx context.Context, configContent string) (option.Options, error) {
|
||||
options, err := json.UnmarshalExtendedContext[option.Options](ctx, []byte(configContent))
|
||||
if err != nil {
|
||||
return option.Options{}, E.Cause(err, "decode config")
|
||||
}
|
||||
return options, nil
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package daemon
|
||||
|
||||
type PlatformHandler interface {
|
||||
ServiceStop() error
|
||||
ServiceReload() error
|
||||
SystemProxyStatus() (*SystemProxyStatus, error)
|
||||
SetSystemProxyEnabled(enabled bool) error
|
||||
WriteDebugMessage(message string)
|
||||
}
|
||||
@@ -1,835 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/conntrack"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/protocol/group"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/batch"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/memory"
|
||||
"github.com/sagernet/sing/common/observable"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"github.com/sagernet/sing/service"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
var _ StartedServiceServer = (*StartedService)(nil)
|
||||
|
||||
type StartedService struct {
|
||||
ctx context.Context
|
||||
// platform adapter.PlatformInterface
|
||||
handler PlatformHandler
|
||||
debug bool
|
||||
logMaxLines int
|
||||
// workingDirectory string
|
||||
// tempDirectory string
|
||||
// userID int
|
||||
// groupID int
|
||||
// systemProxyEnabled bool
|
||||
serviceAccess sync.RWMutex
|
||||
serviceStatus *ServiceStatus
|
||||
serviceStatusSubscriber *observable.Subscriber[*ServiceStatus]
|
||||
serviceStatusObserver *observable.Observer[*ServiceStatus]
|
||||
logAccess sync.RWMutex
|
||||
logLines list.List[*log.Entry]
|
||||
logSubscriber *observable.Subscriber[*log.Entry]
|
||||
logObserver *observable.Observer[*log.Entry]
|
||||
instance *Instance
|
||||
urlTestSubscriber *observable.Subscriber[struct{}]
|
||||
urlTestObserver *observable.Observer[struct{}]
|
||||
urlTestHistoryStorage *urltest.HistoryStorage
|
||||
clashModeSubscriber *observable.Subscriber[struct{}]
|
||||
clashModeObserver *observable.Observer[struct{}]
|
||||
}
|
||||
|
||||
type ServiceOptions struct {
|
||||
Context context.Context
|
||||
// Platform adapter.PlatformInterface
|
||||
Handler PlatformHandler
|
||||
Debug bool
|
||||
LogMaxLines int
|
||||
// WorkingDirectory string
|
||||
// TempDirectory string
|
||||
// UserID int
|
||||
// GroupID int
|
||||
// SystemProxyEnabled bool
|
||||
}
|
||||
|
||||
func NewStartedService(options ServiceOptions) *StartedService {
|
||||
s := &StartedService{
|
||||
ctx: options.Context,
|
||||
// platform: options.Platform,
|
||||
handler: options.Handler,
|
||||
debug: options.Debug,
|
||||
logMaxLines: options.LogMaxLines,
|
||||
// workingDirectory: options.WorkingDirectory,
|
||||
// tempDirectory: options.TempDirectory,
|
||||
// userID: options.UserID,
|
||||
// groupID: options.GroupID,
|
||||
// systemProxyEnabled: options.SystemProxyEnabled,
|
||||
serviceStatus: &ServiceStatus{Status: ServiceStatus_IDLE},
|
||||
serviceStatusSubscriber: observable.NewSubscriber[*ServiceStatus](4),
|
||||
logSubscriber: observable.NewSubscriber[*log.Entry](128),
|
||||
urlTestSubscriber: observable.NewSubscriber[struct{}](1),
|
||||
urlTestHistoryStorage: urltest.NewHistoryStorage(),
|
||||
clashModeSubscriber: observable.NewSubscriber[struct{}](1),
|
||||
}
|
||||
s.serviceStatusObserver = observable.NewObserver(s.serviceStatusSubscriber, 2)
|
||||
s.logObserver = observable.NewObserver(s.logSubscriber, 64)
|
||||
s.urlTestObserver = observable.NewObserver(s.urlTestSubscriber, 1)
|
||||
s.clashModeObserver = observable.NewObserver(s.clashModeSubscriber, 1)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *StartedService) resetLogs() {
|
||||
s.logAccess.Lock()
|
||||
s.logLines = list.List[*log.Entry]{}
|
||||
s.logAccess.Unlock()
|
||||
s.logSubscriber.Emit(nil)
|
||||
}
|
||||
|
||||
func (s *StartedService) updateStatus(newStatus ServiceStatus_Type) {
|
||||
statusObject := &ServiceStatus{Status: newStatus}
|
||||
s.serviceStatusSubscriber.Emit(statusObject)
|
||||
s.serviceStatus = statusObject
|
||||
}
|
||||
|
||||
func (s *StartedService) updateStatusError(err error) error {
|
||||
statusObject := &ServiceStatus{Status: ServiceStatus_FATAL, ErrorMessage: err.Error()}
|
||||
s.serviceStatusSubscriber.Emit(statusObject)
|
||||
s.serviceStatus = statusObject
|
||||
s.serviceAccess.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *StartedService) waitForStarted(ctx context.Context) error {
|
||||
s.serviceAccess.RLock()
|
||||
currentStatus := s.serviceStatus.Status
|
||||
s.serviceAccess.RUnlock()
|
||||
|
||||
switch currentStatus {
|
||||
case ServiceStatus_STARTED:
|
||||
return nil
|
||||
case ServiceStatus_STARTING:
|
||||
default:
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
subscription, done, err := s.serviceStatusObserver.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.serviceStatusObserver.UnSubscribe(subscription)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case status := <-subscription:
|
||||
switch status.Status {
|
||||
case ServiceStatus_STARTED:
|
||||
return nil
|
||||
case ServiceStatus_FATAL:
|
||||
return E.New(status.ErrorMessage)
|
||||
case ServiceStatus_IDLE, ServiceStatus_STOPPING:
|
||||
return os.ErrInvalid
|
||||
}
|
||||
case <-done:
|
||||
return os.ErrClosed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) StartOrReloadService(profileContent string, options *OverrideOptions) error {
|
||||
s.serviceAccess.Lock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_IDLE, ServiceStatus_STARTED, ServiceStatus_STARTING:
|
||||
default:
|
||||
s.serviceAccess.Unlock()
|
||||
return os.ErrInvalid
|
||||
}
|
||||
oldInstance := s.instance
|
||||
if oldInstance != nil {
|
||||
s.updateStatus(ServiceStatus_STOPPING)
|
||||
s.serviceAccess.Unlock()
|
||||
_ = oldInstance.Close()
|
||||
s.serviceAccess.Lock()
|
||||
}
|
||||
s.updateStatus(ServiceStatus_STARTING)
|
||||
s.resetLogs()
|
||||
instance, err := s.newInstance(profileContent, options)
|
||||
if err != nil {
|
||||
return s.updateStatusError(err)
|
||||
}
|
||||
s.instance = instance
|
||||
instance.urlTestHistoryStorage.SetHook(s.urlTestSubscriber)
|
||||
if instance.clashServer != nil {
|
||||
instance.clashServer.SetModeUpdateHook(s.clashModeSubscriber)
|
||||
}
|
||||
s.serviceAccess.Unlock()
|
||||
err = instance.Start()
|
||||
s.serviceAccess.Lock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTING {
|
||||
s.serviceAccess.Unlock()
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return s.updateStatusError(err)
|
||||
}
|
||||
s.updateStatus(ServiceStatus_STARTED)
|
||||
s.serviceAccess.Unlock()
|
||||
runtime.GC()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StartedService) CloseService() error {
|
||||
s.serviceAccess.Lock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_STARTING, ServiceStatus_STARTED:
|
||||
default:
|
||||
s.serviceAccess.Unlock()
|
||||
return os.ErrInvalid
|
||||
}
|
||||
s.updateStatus(ServiceStatus_STOPPING)
|
||||
if s.instance != nil {
|
||||
err := s.instance.Close()
|
||||
if err != nil {
|
||||
return s.updateStatusError(err)
|
||||
}
|
||||
}
|
||||
s.instance = nil
|
||||
s.updateStatus(ServiceStatus_IDLE)
|
||||
s.serviceAccess.Unlock()
|
||||
runtime.GC()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SetError(err error) {
|
||||
s.serviceAccess.Lock()
|
||||
s.updateStatusError(err)
|
||||
s.WriteMessage(log.LevelError, err.Error())
|
||||
}
|
||||
|
||||
func (s *StartedService) StopService(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
err := s.handler.ServiceStop()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) ReloadService(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
err := s.handler.ServiceReload()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeServiceStatus(empty *emptypb.Empty, server grpc.ServerStreamingServer[ServiceStatus]) error {
|
||||
subscription, done, err := s.serviceStatusObserver.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.serviceStatusObserver.UnSubscribe(subscription)
|
||||
err = server.Send(s.serviceStatus)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case newStatus := <-subscription:
|
||||
err = server.Send(newStatus)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeLog(empty *emptypb.Empty, server grpc.ServerStreamingServer[Log]) error {
|
||||
var savedLines []*log.Entry
|
||||
s.logAccess.Lock()
|
||||
savedLines = make([]*log.Entry, 0, s.logLines.Len())
|
||||
for element := s.logLines.Front(); element != nil; element = element.Next() {
|
||||
savedLines = append(savedLines, element.Value)
|
||||
}
|
||||
subscription, done, err := s.logObserver.Subscribe()
|
||||
s.logAccess.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.logObserver.UnSubscribe(subscription)
|
||||
err = server.Send(&Log{
|
||||
Messages: common.Map(savedLines, func(it *log.Entry) *Log_Message {
|
||||
return &Log_Message{
|
||||
Level: LogLevel(it.Level),
|
||||
Message: it.Message,
|
||||
}
|
||||
}),
|
||||
Reset_: true,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case message := <-subscription:
|
||||
var rawMessage Log
|
||||
if message == nil {
|
||||
rawMessage.Reset_ = true
|
||||
} else {
|
||||
rawMessage.Messages = append(rawMessage.Messages, &Log_Message{
|
||||
Level: LogLevel(message.Level),
|
||||
Message: message.Message,
|
||||
})
|
||||
}
|
||||
fetch:
|
||||
for {
|
||||
select {
|
||||
case message = <-subscription:
|
||||
if message == nil {
|
||||
rawMessage.Messages = nil
|
||||
rawMessage.Reset_ = true
|
||||
} else {
|
||||
rawMessage.Messages = append(rawMessage.Messages, &Log_Message{
|
||||
Level: LogLevel(message.Level),
|
||||
Message: message.Message,
|
||||
})
|
||||
}
|
||||
default:
|
||||
break fetch
|
||||
}
|
||||
}
|
||||
err = server.Send(&rawMessage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) GetDefaultLogLevel(ctx context.Context, empty *emptypb.Empty) (*DefaultLogLevel, error) {
|
||||
s.serviceAccess.RLock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_STARTING, ServiceStatus_STARTED:
|
||||
default:
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
logLevel := s.instance.instance.LogFactory().Level()
|
||||
s.serviceAccess.RUnlock()
|
||||
return &DefaultLogLevel{Level: LogLevel(logLevel)}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) ClearLogs(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
s.resetLogs()
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeStatus(request *SubscribeStatusRequest, server grpc.ServerStreamingServer[Status]) error {
|
||||
interval := time.Duration(request.Interval)
|
||||
if interval <= 0 {
|
||||
interval = time.Second // Default to 1 second
|
||||
}
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
status := s.readStatus()
|
||||
uploadTotal := status.UplinkTotal
|
||||
downloadTotal := status.DownlinkTotal
|
||||
for {
|
||||
err := server.Send(status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
status = s.readStatus()
|
||||
upload := status.UplinkTotal - uploadTotal
|
||||
download := status.DownlinkTotal - downloadTotal
|
||||
uploadTotal = status.UplinkTotal
|
||||
downloadTotal = status.DownlinkTotal
|
||||
status.Uplink = upload
|
||||
status.Downlink = download
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) readStatus() *Status {
|
||||
var status Status
|
||||
status.Memory = memory.Inuse()
|
||||
status.Goroutines = int32(runtime.NumGoroutine())
|
||||
status.ConnectionsOut = int32(conntrack.Count())
|
||||
s.serviceAccess.RLock()
|
||||
nowService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
if nowService != nil {
|
||||
if clashServer := nowService.clashServer; clashServer != nil {
|
||||
status.TrafficAvailable = true
|
||||
trafficManager := clashServer.(*clashapi.Server).TrafficManager()
|
||||
status.UplinkTotal, status.DownlinkTotal = trafficManager.Total()
|
||||
status.ConnectionsIn = int32(trafficManager.ConnectionsLen())
|
||||
}
|
||||
}
|
||||
return &status
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeGroups(empty *emptypb.Empty, server grpc.ServerStreamingServer[Groups]) error {
|
||||
err := s.waitForStarted(server.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subscription, done, err := s.urlTestObserver.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.urlTestObserver.UnSubscribe(subscription)
|
||||
for {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return os.ErrInvalid
|
||||
}
|
||||
groups := s.readGroups()
|
||||
s.serviceAccess.RUnlock()
|
||||
err = server.Send(groups)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-subscription:
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) readGroups() *Groups {
|
||||
historyStorage := s.instance.urlTestHistoryStorage
|
||||
boxService := s.instance
|
||||
outbounds := boxService.instance.Outbound().Outbounds()
|
||||
var iGroups []adapter.OutboundGroup
|
||||
for _, it := range outbounds {
|
||||
if group, isGroup := it.(adapter.OutboundGroup); isGroup {
|
||||
iGroups = append(iGroups, group)
|
||||
}
|
||||
}
|
||||
var gs Groups
|
||||
for _, iGroup := range iGroups {
|
||||
var g Group
|
||||
g.Tag = iGroup.Tag()
|
||||
g.Type = iGroup.Type()
|
||||
_, g.Selectable = iGroup.(*group.Selector)
|
||||
g.Selected = iGroup.Now()
|
||||
if boxService.cacheFile != nil {
|
||||
if isExpand, loaded := boxService.cacheFile.LoadGroupExpand(g.Tag); loaded {
|
||||
g.IsExpand = isExpand
|
||||
}
|
||||
}
|
||||
|
||||
for _, itemTag := range iGroup.All() {
|
||||
itemOutbound, isLoaded := boxService.instance.Outbound().Outbound(itemTag)
|
||||
if !isLoaded {
|
||||
continue
|
||||
}
|
||||
|
||||
var item GroupItem
|
||||
item.Tag = itemTag
|
||||
item.Type = itemOutbound.Type()
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(itemOutbound)); history != nil {
|
||||
item.UrlTestTime = history.Time.Unix()
|
||||
item.UrlTestDelay = int32(history.Delay)
|
||||
}
|
||||
g.Items = append(g.Items, &item)
|
||||
}
|
||||
if len(g.Items) < 2 {
|
||||
continue
|
||||
}
|
||||
gs.Group = append(gs.Group, &g)
|
||||
}
|
||||
return &gs
|
||||
}
|
||||
|
||||
func (s *StartedService) GetClashModeStatus(ctx context.Context, empty *emptypb.Empty) (*ClashModeStatus, error) {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
clashServer := s.instance.clashServer
|
||||
s.serviceAccess.RUnlock()
|
||||
if clashServer == nil {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
return &ClashModeStatus{
|
||||
ModeList: clashServer.ModeList(),
|
||||
CurrentMode: clashServer.Mode(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeClashMode(empty *emptypb.Empty, server grpc.ServerStreamingServer[ClashMode]) error {
|
||||
err := s.waitForStarted(server.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
subscription, done, err := s.clashModeObserver.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.clashModeObserver.UnSubscribe(subscription)
|
||||
for {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return os.ErrInvalid
|
||||
}
|
||||
message := &ClashMode{Mode: s.instance.clashServer.Mode()}
|
||||
s.serviceAccess.RUnlock()
|
||||
err = server.Send(message)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-subscription:
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case <-done:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) SetClashMode(ctx context.Context, request *ClashMode) (*emptypb.Empty, error) {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
clashServer := s.instance.clashServer
|
||||
s.serviceAccess.RUnlock()
|
||||
clashServer.(*clashapi.Server).SetMode(request.Mode)
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) URLTest(ctx context.Context, request *URLTestRequest) (*emptypb.Empty, error) {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
boxService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
groupTag := request.OutboundTag
|
||||
abstractOutboundGroup, isLoaded := boxService.instance.Outbound().Outbound(groupTag)
|
||||
if !isLoaded {
|
||||
return nil, E.New("outbound group not found: ", groupTag)
|
||||
}
|
||||
outboundGroup, isOutboundGroup := abstractOutboundGroup.(adapter.OutboundGroup)
|
||||
if !isOutboundGroup {
|
||||
return nil, E.New("outbound is not a group: ", groupTag)
|
||||
}
|
||||
urlTest, isURLTest := abstractOutboundGroup.(*group.URLTest)
|
||||
if isURLTest {
|
||||
go urlTest.CheckOutbounds()
|
||||
} else {
|
||||
historyStorage := boxService.urlTestHistoryStorage
|
||||
|
||||
outbounds := common.Filter(common.Map(outboundGroup.All(), func(it string) adapter.Outbound {
|
||||
itOutbound, _ := boxService.instance.Outbound().Outbound(it)
|
||||
return itOutbound
|
||||
}), func(it adapter.Outbound) bool {
|
||||
if it == nil {
|
||||
return false
|
||||
}
|
||||
_, isGroup := it.(adapter.OutboundGroup)
|
||||
if isGroup {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
b, _ := batch.New(boxService.ctx, batch.WithConcurrencyNum[any](10))
|
||||
for _, detour := range outbounds {
|
||||
outboundToTest := detour
|
||||
outboundTag := outboundToTest.Tag()
|
||||
b.Go(outboundTag, func() (any, error) {
|
||||
t, err := urltest.URLTest(boxService.ctx, "", outboundToTest)
|
||||
if err != nil {
|
||||
historyStorage.DeleteURLTestHistory(outboundTag)
|
||||
} else {
|
||||
historyStorage.StoreURLTestHistory(outboundTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: t,
|
||||
})
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
}
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SelectOutbound(ctx context.Context, request *SelectOutboundRequest) (*emptypb.Empty, error) {
|
||||
s.serviceAccess.RLock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_STARTING, ServiceStatus_STARTED:
|
||||
default:
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
boxService := s.instance.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
outboundGroup, isLoaded := boxService.Outbound().Outbound(request.GroupTag)
|
||||
if !isLoaded {
|
||||
return nil, E.New("selector not found: ", request.GroupTag)
|
||||
}
|
||||
selector, isSelector := outboundGroup.(*group.Selector)
|
||||
if !isSelector {
|
||||
return nil, E.New("outbound is not a selector: ", request.GroupTag)
|
||||
}
|
||||
if !selector.SelectOutbound(request.OutboundTag) {
|
||||
return nil, E.New("outbound not found in selector: ", request.OutboundTag)
|
||||
}
|
||||
s.urlTestObserver.Emit(struct{}{})
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SetGroupExpand(ctx context.Context, request *SetGroupExpandRequest) (*emptypb.Empty, error) {
|
||||
s.serviceAccess.RLock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_STARTING, ServiceStatus_STARTED:
|
||||
default:
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
boxService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
if boxService.cacheFile != nil {
|
||||
err := boxService.cacheFile.StoreGroupExpand(request.GroupTag, request.IsExpand)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) GetSystemProxyStatus(ctx context.Context, empty *emptypb.Empty) (*SystemProxyStatus, error) {
|
||||
return s.handler.SystemProxyStatus()
|
||||
}
|
||||
|
||||
func (s *StartedService) SetSystemProxyEnabled(ctx context.Context, request *SetSystemProxyEnabledRequest) (*emptypb.Empty, error) {
|
||||
err := s.handler.SetSystemProxyEnabled(request.Enabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeConnections(request *SubscribeConnectionsRequest, server grpc.ServerStreamingServer[Connections]) error {
|
||||
err := s.waitForStarted(server.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.serviceAccess.RLock()
|
||||
boxService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
ticker := time.NewTicker(time.Duration(request.Interval))
|
||||
defer ticker.Stop()
|
||||
trafficManager := boxService.clashServer.(*clashapi.Server).TrafficManager()
|
||||
var (
|
||||
connections = make(map[uuid.UUID]*Connection)
|
||||
outConnections []*Connection
|
||||
)
|
||||
for {
|
||||
outConnections = outConnections[:0]
|
||||
for _, connection := range trafficManager.Connections() {
|
||||
outConnections = append(outConnections, newConnection(connections, connection, false))
|
||||
}
|
||||
for _, connection := range trafficManager.ClosedConnections() {
|
||||
outConnections = append(outConnections, newConnection(connections, connection, true))
|
||||
}
|
||||
err := server.Send(&Connections{Connections: outConnections})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-s.ctx.Done():
|
||||
return s.ctx.Err()
|
||||
case <-server.Context().Done():
|
||||
return server.Context().Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newConnection(connections map[uuid.UUID]*Connection, metadata trafficontrol.TrackerMetadata, isClosed bool) *Connection {
|
||||
if oldConnection, loaded := connections[metadata.ID]; loaded {
|
||||
if isClosed {
|
||||
if oldConnection.ClosedAt == 0 {
|
||||
oldConnection.Uplink = 0
|
||||
oldConnection.Downlink = 0
|
||||
oldConnection.ClosedAt = metadata.ClosedAt.UnixMilli()
|
||||
}
|
||||
return oldConnection
|
||||
}
|
||||
lastUplink := oldConnection.UplinkTotal
|
||||
lastDownlink := oldConnection.DownlinkTotal
|
||||
uplinkTotal := metadata.Upload.Load()
|
||||
downlinkTotal := metadata.Download.Load()
|
||||
oldConnection.Uplink = uplinkTotal - lastUplink
|
||||
oldConnection.Downlink = downlinkTotal - lastDownlink
|
||||
oldConnection.UplinkTotal = uplinkTotal
|
||||
oldConnection.DownlinkTotal = downlinkTotal
|
||||
return oldConnection
|
||||
}
|
||||
var rule string
|
||||
if metadata.Rule != nil {
|
||||
rule = metadata.Rule.String()
|
||||
}
|
||||
uplinkTotal := metadata.Upload.Load()
|
||||
downlinkTotal := metadata.Download.Load()
|
||||
uplink := uplinkTotal
|
||||
downlink := downlinkTotal
|
||||
var closedAt int64
|
||||
if !metadata.ClosedAt.IsZero() {
|
||||
closedAt = metadata.ClosedAt.UnixMilli()
|
||||
uplink = 0
|
||||
downlink = 0
|
||||
}
|
||||
connection := &Connection{
|
||||
Id: metadata.ID.String(),
|
||||
Inbound: metadata.Metadata.Inbound,
|
||||
InboundType: metadata.Metadata.InboundType,
|
||||
IpVersion: int32(metadata.Metadata.IPVersion),
|
||||
Network: metadata.Metadata.Network,
|
||||
Source: metadata.Metadata.Source.String(),
|
||||
Destination: metadata.Metadata.Destination.String(),
|
||||
Domain: metadata.Metadata.Domain,
|
||||
Protocol: metadata.Metadata.Protocol,
|
||||
User: metadata.Metadata.User,
|
||||
FromOutbound: metadata.Metadata.Outbound,
|
||||
CreatedAt: metadata.CreatedAt.UnixMilli(),
|
||||
ClosedAt: closedAt,
|
||||
Uplink: uplink,
|
||||
Downlink: downlink,
|
||||
UplinkTotal: uplinkTotal,
|
||||
DownlinkTotal: downlinkTotal,
|
||||
Rule: rule,
|
||||
Outbound: metadata.Outbound,
|
||||
OutboundType: metadata.OutboundType,
|
||||
ChainList: metadata.Chain,
|
||||
}
|
||||
connections[metadata.ID] = connection
|
||||
return connection
|
||||
}
|
||||
|
||||
func (s *StartedService) CloseConnection(ctx context.Context, request *CloseConnectionRequest) (*emptypb.Empty, error) {
|
||||
s.serviceAccess.RLock()
|
||||
switch s.serviceStatus.Status {
|
||||
case ServiceStatus_STARTING, ServiceStatus_STARTED:
|
||||
default:
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
boxService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
targetConn := boxService.clashServer.(*clashapi.Server).TrafficManager().Connection(uuid.FromStringOrNil(request.Id))
|
||||
if targetConn != nil {
|
||||
targetConn.Close()
|
||||
}
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) CloseAllConnections(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
conntrack.Close()
|
||||
return &emptypb.Empty{}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) GetDeprecatedWarnings(ctx context.Context, empty *emptypb.Empty) (*DeprecatedWarnings, error) {
|
||||
s.serviceAccess.RLock()
|
||||
if s.serviceStatus.Status != ServiceStatus_STARTED {
|
||||
s.serviceAccess.RUnlock()
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
boxService := s.instance
|
||||
s.serviceAccess.RUnlock()
|
||||
notes := service.FromContext[deprecated.Manager](boxService.ctx).(*deprecatedManager).Get()
|
||||
return &DeprecatedWarnings{
|
||||
Warnings: common.Map(notes, func(it deprecated.Note) *DeprecatedWarning {
|
||||
return &DeprecatedWarning{
|
||||
Message: it.Message(),
|
||||
Impending: it.Impending(),
|
||||
MigrationLink: it.MigrationLink,
|
||||
}
|
||||
}),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *StartedService) SubscribeHelperEvents(empty *emptypb.Empty, server grpc.ServerStreamingServer[HelperRequest]) error {
|
||||
return os.ErrInvalid
|
||||
}
|
||||
|
||||
func (s *StartedService) SendHelperResponse(ctx context.Context, response *HelperResponse) (*emptypb.Empty, error) {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
func (s *StartedService) mustEmbedUnimplementedStartedServiceServer() {
|
||||
}
|
||||
|
||||
func (s *StartedService) WriteMessage(level log.Level, message string) {
|
||||
item := &log.Entry{Level: level, Message: message}
|
||||
s.logAccess.Lock()
|
||||
s.logLines.PushBack(item)
|
||||
if s.logLines.Len() > s.logMaxLines {
|
||||
s.logLines.Remove(s.logLines.Front())
|
||||
}
|
||||
s.logAccess.Unlock()
|
||||
s.logSubscriber.Emit(item)
|
||||
if s.debug {
|
||||
s.handler.WriteDebugMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *StartedService) Instance() *Instance {
|
||||
s.serviceAccess.RLock()
|
||||
defer s.serviceAccess.RUnlock()
|
||||
return s.instance
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,205 +0,0 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package daemon;
|
||||
option go_package = "github.com/sagernet/sing-box/daemon";
|
||||
|
||||
import "google/protobuf/empty.proto";
|
||||
import "daemon/helper.proto";
|
||||
|
||||
service StartedService {
|
||||
rpc StopService(google.protobuf.Empty) returns (google.protobuf.Empty);
|
||||
rpc ReloadService(google.protobuf.Empty) returns (google.protobuf.Empty);
|
||||
|
||||
rpc SubscribeServiceStatus(google.protobuf.Empty) returns(stream ServiceStatus) {}
|
||||
rpc SubscribeLog(google.protobuf.Empty) returns(stream Log) {}
|
||||
rpc GetDefaultLogLevel(google.protobuf.Empty) returns(DefaultLogLevel) {}
|
||||
rpc ClearLogs(google.protobuf.Empty) returns(google.protobuf.Empty) {}
|
||||
rpc SubscribeStatus(SubscribeStatusRequest) returns(stream Status) {}
|
||||
rpc SubscribeGroups(google.protobuf.Empty) returns(stream Groups) {}
|
||||
|
||||
rpc GetClashModeStatus(google.protobuf.Empty) returns(ClashModeStatus) {}
|
||||
rpc SubscribeClashMode(google.protobuf.Empty) returns(stream ClashMode) {}
|
||||
rpc SetClashMode(ClashMode) returns(google.protobuf.Empty) {}
|
||||
|
||||
rpc URLTest(URLTestRequest) returns(google.protobuf.Empty) {}
|
||||
rpc SelectOutbound(SelectOutboundRequest) returns (google.protobuf.Empty) {}
|
||||
rpc SetGroupExpand(SetGroupExpandRequest) returns (google.protobuf.Empty) {}
|
||||
|
||||
rpc GetSystemProxyStatus(google.protobuf.Empty) returns(SystemProxyStatus) {}
|
||||
rpc SetSystemProxyEnabled(SetSystemProxyEnabledRequest) returns(google.protobuf.Empty) {}
|
||||
|
||||
rpc SubscribeConnections(SubscribeConnectionsRequest) returns(stream Connections) {}
|
||||
rpc CloseConnection(CloseConnectionRequest) returns(google.protobuf.Empty) {}
|
||||
rpc CloseAllConnections(google.protobuf.Empty) returns(google.protobuf.Empty) {}
|
||||
rpc GetDeprecatedWarnings(google.protobuf.Empty) returns(DeprecatedWarnings) {}
|
||||
|
||||
rpc SubscribeHelperEvents(google.protobuf.Empty) returns(stream HelperRequest) {}
|
||||
rpc SendHelperResponse(HelperResponse) returns(google.protobuf.Empty) {}
|
||||
}
|
||||
|
||||
message ServiceStatus {
|
||||
enum Type {
|
||||
IDLE = 0;
|
||||
STARTING = 1;
|
||||
STARTED = 2;
|
||||
STOPPING = 3;
|
||||
FATAL = 4;
|
||||
}
|
||||
Type status = 1;
|
||||
string errorMessage = 2;
|
||||
}
|
||||
|
||||
message ReloadServiceRequest {
|
||||
string newProfileContent = 1;
|
||||
}
|
||||
|
||||
message SubscribeStatusRequest {
|
||||
int64 interval = 1;
|
||||
}
|
||||
|
||||
enum LogLevel {
|
||||
PANIC = 0;
|
||||
FATAL = 1;
|
||||
ERROR = 2;
|
||||
WARN = 3;
|
||||
INFO = 4;
|
||||
DEBUG = 5;
|
||||
TRACE = 6;
|
||||
}
|
||||
|
||||
message Log {
|
||||
repeated Message messages = 1;
|
||||
bool reset = 2;
|
||||
message Message {
|
||||
LogLevel level = 1;
|
||||
string message = 2;
|
||||
}
|
||||
}
|
||||
|
||||
message DefaultLogLevel {
|
||||
LogLevel level = 1;
|
||||
}
|
||||
|
||||
message Status {
|
||||
uint64 memory = 1;
|
||||
int32 goroutines = 2;
|
||||
int32 connectionsIn = 3;
|
||||
int32 connectionsOut = 4;
|
||||
bool trafficAvailable = 5;
|
||||
int64 uplink = 6;
|
||||
int64 downlink = 7;
|
||||
int64 uplinkTotal = 8;
|
||||
int64 downlinkTotal = 9;
|
||||
}
|
||||
|
||||
message Groups {
|
||||
repeated Group group = 1;
|
||||
}
|
||||
|
||||
message Group {
|
||||
string tag = 1;
|
||||
string type = 2;
|
||||
bool selectable = 3;
|
||||
string selected = 4;
|
||||
bool isExpand = 5;
|
||||
repeated GroupItem items = 6;
|
||||
}
|
||||
|
||||
message GroupItem {
|
||||
string tag = 1;
|
||||
string type = 2;
|
||||
int64 urlTestTime = 3;
|
||||
int32 urlTestDelay = 4;
|
||||
}
|
||||
|
||||
message URLTestRequest {
|
||||
string outboundTag = 1;
|
||||
}
|
||||
|
||||
message SelectOutboundRequest {
|
||||
string groupTag = 1;
|
||||
string outboundTag = 2;
|
||||
}
|
||||
|
||||
message SetGroupExpandRequest {
|
||||
string groupTag = 1;
|
||||
bool isExpand = 2;
|
||||
}
|
||||
|
||||
message ClashMode {
|
||||
string mode = 3;
|
||||
}
|
||||
|
||||
message ClashModeStatus {
|
||||
repeated string modeList = 1;
|
||||
string currentMode = 2;
|
||||
}
|
||||
|
||||
message SystemProxyStatus {
|
||||
bool available = 1;
|
||||
bool enabled = 2;
|
||||
}
|
||||
|
||||
message SetSystemProxyEnabledRequest {
|
||||
bool enabled = 1;
|
||||
}
|
||||
|
||||
message SubscribeConnectionsRequest {
|
||||
int64 interval = 1;
|
||||
ConnectionFilter filter = 2;
|
||||
ConnectionSortBy sortBy = 3;
|
||||
}
|
||||
|
||||
enum ConnectionFilter {
|
||||
ALL = 0;
|
||||
ACTIVE = 1;
|
||||
CLOSED = 2;
|
||||
}
|
||||
|
||||
enum ConnectionSortBy {
|
||||
DATE = 0;
|
||||
TRAFFIC = 1;
|
||||
TOTAL_TRAFFIC = 2;
|
||||
}
|
||||
|
||||
message Connections {
|
||||
repeated Connection connections = 1;
|
||||
}
|
||||
|
||||
message Connection {
|
||||
string id = 1;
|
||||
string inbound = 2;
|
||||
string inboundType = 3;
|
||||
int32 ipVersion = 4;
|
||||
string network = 5;
|
||||
string source = 6;
|
||||
string destination = 7;
|
||||
string domain = 8;
|
||||
string protocol = 9;
|
||||
string user = 10;
|
||||
string fromOutbound = 11;
|
||||
int64 createdAt = 12;
|
||||
int64 closedAt = 13;
|
||||
int64 uplink = 14;
|
||||
int64 downlink = 15;
|
||||
int64 uplinkTotal = 16;
|
||||
int64 downlinkTotal = 17;
|
||||
string rule = 18;
|
||||
string outbound = 19;
|
||||
string outboundType = 20;
|
||||
repeated string chainList = 21;
|
||||
}
|
||||
|
||||
message CloseConnectionRequest {
|
||||
string id = 1;
|
||||
}
|
||||
|
||||
message DeprecatedWarnings {
|
||||
repeated DeprecatedWarning warnings = 1;
|
||||
}
|
||||
|
||||
message DeprecatedWarning {
|
||||
string message = 1;
|
||||
bool impending = 2;
|
||||
string migrationLink = 3;
|
||||
}
|
||||
@@ -1,958 +0,0 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
context "context"
|
||||
|
||||
grpc "google.golang.org/grpc"
|
||||
codes "google.golang.org/grpc/codes"
|
||||
status "google.golang.org/grpc/status"
|
||||
emptypb "google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
// Requires gRPC-Go v1.64.0 or later.
|
||||
const _ = grpc.SupportPackageIsVersion9
|
||||
|
||||
const (
|
||||
StartedService_StopService_FullMethodName = "/daemon.StartedService/StopService"
|
||||
StartedService_ReloadService_FullMethodName = "/daemon.StartedService/ReloadService"
|
||||
StartedService_SubscribeServiceStatus_FullMethodName = "/daemon.StartedService/SubscribeServiceStatus"
|
||||
StartedService_SubscribeLog_FullMethodName = "/daemon.StartedService/SubscribeLog"
|
||||
StartedService_GetDefaultLogLevel_FullMethodName = "/daemon.StartedService/GetDefaultLogLevel"
|
||||
StartedService_ClearLogs_FullMethodName = "/daemon.StartedService/ClearLogs"
|
||||
StartedService_SubscribeStatus_FullMethodName = "/daemon.StartedService/SubscribeStatus"
|
||||
StartedService_SubscribeGroups_FullMethodName = "/daemon.StartedService/SubscribeGroups"
|
||||
StartedService_GetClashModeStatus_FullMethodName = "/daemon.StartedService/GetClashModeStatus"
|
||||
StartedService_SubscribeClashMode_FullMethodName = "/daemon.StartedService/SubscribeClashMode"
|
||||
StartedService_SetClashMode_FullMethodName = "/daemon.StartedService/SetClashMode"
|
||||
StartedService_URLTest_FullMethodName = "/daemon.StartedService/URLTest"
|
||||
StartedService_SelectOutbound_FullMethodName = "/daemon.StartedService/SelectOutbound"
|
||||
StartedService_SetGroupExpand_FullMethodName = "/daemon.StartedService/SetGroupExpand"
|
||||
StartedService_GetSystemProxyStatus_FullMethodName = "/daemon.StartedService/GetSystemProxyStatus"
|
||||
StartedService_SetSystemProxyEnabled_FullMethodName = "/daemon.StartedService/SetSystemProxyEnabled"
|
||||
StartedService_SubscribeConnections_FullMethodName = "/daemon.StartedService/SubscribeConnections"
|
||||
StartedService_CloseConnection_FullMethodName = "/daemon.StartedService/CloseConnection"
|
||||
StartedService_CloseAllConnections_FullMethodName = "/daemon.StartedService/CloseAllConnections"
|
||||
StartedService_GetDeprecatedWarnings_FullMethodName = "/daemon.StartedService/GetDeprecatedWarnings"
|
||||
StartedService_SubscribeHelperEvents_FullMethodName = "/daemon.StartedService/SubscribeHelperEvents"
|
||||
StartedService_SendHelperResponse_FullMethodName = "/daemon.StartedService/SendHelperResponse"
|
||||
)
|
||||
|
||||
// StartedServiceClient is the client API for StartedService service.
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type StartedServiceClient interface {
|
||||
StopService(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
ReloadService(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
SubscribeServiceStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ServiceStatus], error)
|
||||
SubscribeLog(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Log], error)
|
||||
GetDefaultLogLevel(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*DefaultLogLevel, error)
|
||||
ClearLogs(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
SubscribeStatus(ctx context.Context, in *SubscribeStatusRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Status], error)
|
||||
SubscribeGroups(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Groups], error)
|
||||
GetClashModeStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*ClashModeStatus, error)
|
||||
SubscribeClashMode(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ClashMode], error)
|
||||
SetClashMode(ctx context.Context, in *ClashMode, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
URLTest(ctx context.Context, in *URLTestRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
SelectOutbound(ctx context.Context, in *SelectOutboundRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
SetGroupExpand(ctx context.Context, in *SetGroupExpandRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
GetSystemProxyStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*SystemProxyStatus, error)
|
||||
SetSystemProxyEnabled(ctx context.Context, in *SetSystemProxyEnabledRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
SubscribeConnections(ctx context.Context, in *SubscribeConnectionsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Connections], error)
|
||||
CloseConnection(ctx context.Context, in *CloseConnectionRequest, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
CloseAllConnections(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
GetDeprecatedWarnings(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*DeprecatedWarnings, error)
|
||||
SubscribeHelperEvents(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[HelperRequest], error)
|
||||
SendHelperResponse(ctx context.Context, in *HelperResponse, opts ...grpc.CallOption) (*emptypb.Empty, error)
|
||||
}
|
||||
|
||||
type startedServiceClient struct {
|
||||
cc grpc.ClientConnInterface
|
||||
}
|
||||
|
||||
func NewStartedServiceClient(cc grpc.ClientConnInterface) StartedServiceClient {
|
||||
return &startedServiceClient{cc}
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) StopService(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_StopService_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) ReloadService(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_ReloadService_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SubscribeServiceStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ServiceStatus], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[0], StartedService_SubscribeServiceStatus_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[emptypb.Empty, ServiceStatus]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeServiceStatusClient = grpc.ServerStreamingClient[ServiceStatus]
|
||||
|
||||
func (c *startedServiceClient) SubscribeLog(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Log], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[1], StartedService_SubscribeLog_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[emptypb.Empty, Log]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeLogClient = grpc.ServerStreamingClient[Log]
|
||||
|
||||
func (c *startedServiceClient) GetDefaultLogLevel(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*DefaultLogLevel, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DefaultLogLevel)
|
||||
err := c.cc.Invoke(ctx, StartedService_GetDefaultLogLevel_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) ClearLogs(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_ClearLogs_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SubscribeStatus(ctx context.Context, in *SubscribeStatusRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Status], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[2], StartedService_SubscribeStatus_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[SubscribeStatusRequest, Status]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeStatusClient = grpc.ServerStreamingClient[Status]
|
||||
|
||||
func (c *startedServiceClient) SubscribeGroups(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Groups], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[3], StartedService_SubscribeGroups_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[emptypb.Empty, Groups]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeGroupsClient = grpc.ServerStreamingClient[Groups]
|
||||
|
||||
func (c *startedServiceClient) GetClashModeStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*ClashModeStatus, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ClashModeStatus)
|
||||
err := c.cc.Invoke(ctx, StartedService_GetClashModeStatus_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SubscribeClashMode(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[ClashMode], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[4], StartedService_SubscribeClashMode_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[emptypb.Empty, ClashMode]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeClashModeClient = grpc.ServerStreamingClient[ClashMode]
|
||||
|
||||
func (c *startedServiceClient) SetClashMode(ctx context.Context, in *ClashMode, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_SetClashMode_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) URLTest(ctx context.Context, in *URLTestRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_URLTest_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SelectOutbound(ctx context.Context, in *SelectOutboundRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_SelectOutbound_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SetGroupExpand(ctx context.Context, in *SetGroupExpandRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_SetGroupExpand_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) GetSystemProxyStatus(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*SystemProxyStatus, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SystemProxyStatus)
|
||||
err := c.cc.Invoke(ctx, StartedService_GetSystemProxyStatus_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SetSystemProxyEnabled(ctx context.Context, in *SetSystemProxyEnabledRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_SetSystemProxyEnabled_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SubscribeConnections(ctx context.Context, in *SubscribeConnectionsRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[Connections], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[5], StartedService_SubscribeConnections_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[SubscribeConnectionsRequest, Connections]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeConnectionsClient = grpc.ServerStreamingClient[Connections]
|
||||
|
||||
func (c *startedServiceClient) CloseConnection(ctx context.Context, in *CloseConnectionRequest, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_CloseConnection_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) CloseAllConnections(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_CloseAllConnections_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) GetDeprecatedWarnings(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (*DeprecatedWarnings, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(DeprecatedWarnings)
|
||||
err := c.cc.Invoke(ctx, StartedService_GetDeprecatedWarnings_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *startedServiceClient) SubscribeHelperEvents(ctx context.Context, in *emptypb.Empty, opts ...grpc.CallOption) (grpc.ServerStreamingClient[HelperRequest], error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
stream, err := c.cc.NewStream(ctx, &StartedService_ServiceDesc.Streams[6], StartedService_SubscribeHelperEvents_FullMethodName, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &grpc.GenericClientStream[emptypb.Empty, HelperRequest]{ClientStream: stream}
|
||||
if err := x.ClientStream.SendMsg(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := x.ClientStream.CloseSend(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeHelperEventsClient = grpc.ServerStreamingClient[HelperRequest]
|
||||
|
||||
func (c *startedServiceClient) SendHelperResponse(ctx context.Context, in *HelperResponse, opts ...grpc.CallOption) (*emptypb.Empty, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(emptypb.Empty)
|
||||
err := c.cc.Invoke(ctx, StartedService_SendHelperResponse_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// StartedServiceServer is the server API for StartedService service.
|
||||
// All implementations must embed UnimplementedStartedServiceServer
|
||||
// for forward compatibility.
|
||||
type StartedServiceServer interface {
|
||||
StopService(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
|
||||
ReloadService(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
|
||||
SubscribeServiceStatus(*emptypb.Empty, grpc.ServerStreamingServer[ServiceStatus]) error
|
||||
SubscribeLog(*emptypb.Empty, grpc.ServerStreamingServer[Log]) error
|
||||
GetDefaultLogLevel(context.Context, *emptypb.Empty) (*DefaultLogLevel, error)
|
||||
ClearLogs(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
|
||||
SubscribeStatus(*SubscribeStatusRequest, grpc.ServerStreamingServer[Status]) error
|
||||
SubscribeGroups(*emptypb.Empty, grpc.ServerStreamingServer[Groups]) error
|
||||
GetClashModeStatus(context.Context, *emptypb.Empty) (*ClashModeStatus, error)
|
||||
SubscribeClashMode(*emptypb.Empty, grpc.ServerStreamingServer[ClashMode]) error
|
||||
SetClashMode(context.Context, *ClashMode) (*emptypb.Empty, error)
|
||||
URLTest(context.Context, *URLTestRequest) (*emptypb.Empty, error)
|
||||
SelectOutbound(context.Context, *SelectOutboundRequest) (*emptypb.Empty, error)
|
||||
SetGroupExpand(context.Context, *SetGroupExpandRequest) (*emptypb.Empty, error)
|
||||
GetSystemProxyStatus(context.Context, *emptypb.Empty) (*SystemProxyStatus, error)
|
||||
SetSystemProxyEnabled(context.Context, *SetSystemProxyEnabledRequest) (*emptypb.Empty, error)
|
||||
SubscribeConnections(*SubscribeConnectionsRequest, grpc.ServerStreamingServer[Connections]) error
|
||||
CloseConnection(context.Context, *CloseConnectionRequest) (*emptypb.Empty, error)
|
||||
CloseAllConnections(context.Context, *emptypb.Empty) (*emptypb.Empty, error)
|
||||
GetDeprecatedWarnings(context.Context, *emptypb.Empty) (*DeprecatedWarnings, error)
|
||||
SubscribeHelperEvents(*emptypb.Empty, grpc.ServerStreamingServer[HelperRequest]) error
|
||||
SendHelperResponse(context.Context, *HelperResponse) (*emptypb.Empty, error)
|
||||
mustEmbedUnimplementedStartedServiceServer()
|
||||
}
|
||||
|
||||
// UnimplementedStartedServiceServer must be embedded to have
|
||||
// forward compatible implementations.
|
||||
//
|
||||
// NOTE: this should be embedded by value instead of pointer to avoid a nil
|
||||
// pointer dereference when methods are called.
|
||||
type UnimplementedStartedServiceServer struct{}
|
||||
|
||||
func (UnimplementedStartedServiceServer) StopService(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method StopService not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) ReloadService(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ReloadService not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeServiceStatus(*emptypb.Empty, grpc.ServerStreamingServer[ServiceStatus]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeServiceStatus not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeLog(*emptypb.Empty, grpc.ServerStreamingServer[Log]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeLog not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) GetDefaultLogLevel(context.Context, *emptypb.Empty) (*DefaultLogLevel, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetDefaultLogLevel not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) ClearLogs(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method ClearLogs not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeStatus(*SubscribeStatusRequest, grpc.ServerStreamingServer[Status]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeStatus not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeGroups(*emptypb.Empty, grpc.ServerStreamingServer[Groups]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeGroups not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) GetClashModeStatus(context.Context, *emptypb.Empty) (*ClashModeStatus, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetClashModeStatus not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeClashMode(*emptypb.Empty, grpc.ServerStreamingServer[ClashMode]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeClashMode not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SetClashMode(context.Context, *ClashMode) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SetClashMode not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) URLTest(context.Context, *URLTestRequest) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method URLTest not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SelectOutbound(context.Context, *SelectOutboundRequest) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SelectOutbound not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SetGroupExpand(context.Context, *SetGroupExpandRequest) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SetGroupExpand not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) GetSystemProxyStatus(context.Context, *emptypb.Empty) (*SystemProxyStatus, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetSystemProxyStatus not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SetSystemProxyEnabled(context.Context, *SetSystemProxyEnabledRequest) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SetSystemProxyEnabled not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeConnections(*SubscribeConnectionsRequest, grpc.ServerStreamingServer[Connections]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeConnections not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) CloseConnection(context.Context, *CloseConnectionRequest) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CloseConnection not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) CloseAllConnections(context.Context, *emptypb.Empty) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method CloseAllConnections not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) GetDeprecatedWarnings(context.Context, *emptypb.Empty) (*DeprecatedWarnings, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method GetDeprecatedWarnings not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SubscribeHelperEvents(*emptypb.Empty, grpc.ServerStreamingServer[HelperRequest]) error {
|
||||
return status.Errorf(codes.Unimplemented, "method SubscribeHelperEvents not implemented")
|
||||
}
|
||||
|
||||
func (UnimplementedStartedServiceServer) SendHelperResponse(context.Context, *HelperResponse) (*emptypb.Empty, error) {
|
||||
return nil, status.Errorf(codes.Unimplemented, "method SendHelperResponse not implemented")
|
||||
}
|
||||
func (UnimplementedStartedServiceServer) mustEmbedUnimplementedStartedServiceServer() {}
|
||||
func (UnimplementedStartedServiceServer) testEmbeddedByValue() {}
|
||||
|
||||
// UnsafeStartedServiceServer may be embedded to opt out of forward compatibility for this service.
|
||||
// Use of this interface is not recommended, as added methods to StartedServiceServer will
|
||||
// result in compilation errors.
|
||||
type UnsafeStartedServiceServer interface {
|
||||
mustEmbedUnimplementedStartedServiceServer()
|
||||
}
|
||||
|
||||
func RegisterStartedServiceServer(s grpc.ServiceRegistrar, srv StartedServiceServer) {
|
||||
// If the following call pancis, it indicates UnimplementedStartedServiceServer was
|
||||
// embedded by pointer and is nil. This will cause panics if an
|
||||
// unimplemented method is ever invoked, so we test this at initialization
|
||||
// time to prevent it from happening at runtime later due to I/O.
|
||||
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
|
||||
t.testEmbeddedByValue()
|
||||
}
|
||||
s.RegisterService(&StartedService_ServiceDesc, srv)
|
||||
}
|
||||
|
||||
func _StartedService_StopService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).StopService(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_StopService_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).StopService(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_ReloadService_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).ReloadService(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_ReloadService_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).ReloadService(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SubscribeServiceStatus_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(emptypb.Empty)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeServiceStatus(m, &grpc.GenericServerStream[emptypb.Empty, ServiceStatus]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeServiceStatusServer = grpc.ServerStreamingServer[ServiceStatus]
|
||||
|
||||
func _StartedService_SubscribeLog_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(emptypb.Empty)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeLog(m, &grpc.GenericServerStream[emptypb.Empty, Log]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeLogServer = grpc.ServerStreamingServer[Log]
|
||||
|
||||
func _StartedService_GetDefaultLogLevel_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).GetDefaultLogLevel(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_GetDefaultLogLevel_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).GetDefaultLogLevel(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_ClearLogs_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).ClearLogs(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_ClearLogs_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).ClearLogs(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SubscribeStatus_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(SubscribeStatusRequest)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeStatus(m, &grpc.GenericServerStream[SubscribeStatusRequest, Status]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeStatusServer = grpc.ServerStreamingServer[Status]
|
||||
|
||||
func _StartedService_SubscribeGroups_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(emptypb.Empty)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeGroups(m, &grpc.GenericServerStream[emptypb.Empty, Groups]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeGroupsServer = grpc.ServerStreamingServer[Groups]
|
||||
|
||||
func _StartedService_GetClashModeStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).GetClashModeStatus(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_GetClashModeStatus_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).GetClashModeStatus(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SubscribeClashMode_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(emptypb.Empty)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeClashMode(m, &grpc.GenericServerStream[emptypb.Empty, ClashMode]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeClashModeServer = grpc.ServerStreamingServer[ClashMode]
|
||||
|
||||
func _StartedService_SetClashMode_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ClashMode)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).SetClashMode(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_SetClashMode_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).SetClashMode(ctx, req.(*ClashMode))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_URLTest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(URLTestRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).URLTest(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_URLTest_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).URLTest(ctx, req.(*URLTestRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SelectOutbound_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SelectOutboundRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).SelectOutbound(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_SelectOutbound_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).SelectOutbound(ctx, req.(*SelectOutboundRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SetGroupExpand_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetGroupExpandRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).SetGroupExpand(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_SetGroupExpand_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).SetGroupExpand(ctx, req.(*SetGroupExpandRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_GetSystemProxyStatus_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).GetSystemProxyStatus(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_GetSystemProxyStatus_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).GetSystemProxyStatus(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SetSystemProxyEnabled_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetSystemProxyEnabledRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).SetSystemProxyEnabled(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_SetSystemProxyEnabled_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).SetSystemProxyEnabled(ctx, req.(*SetSystemProxyEnabledRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SubscribeConnections_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(SubscribeConnectionsRequest)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeConnections(m, &grpc.GenericServerStream[SubscribeConnectionsRequest, Connections]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeConnectionsServer = grpc.ServerStreamingServer[Connections]
|
||||
|
||||
func _StartedService_CloseConnection_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(CloseConnectionRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).CloseConnection(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_CloseConnection_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).CloseConnection(ctx, req.(*CloseConnectionRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_CloseAllConnections_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).CloseAllConnections(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_CloseAllConnections_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).CloseAllConnections(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_GetDeprecatedWarnings_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(emptypb.Empty)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).GetDeprecatedWarnings(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_GetDeprecatedWarnings_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).GetDeprecatedWarnings(ctx, req.(*emptypb.Empty))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StartedService_SubscribeHelperEvents_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
m := new(emptypb.Empty)
|
||||
if err := stream.RecvMsg(m); err != nil {
|
||||
return err
|
||||
}
|
||||
return srv.(StartedServiceServer).SubscribeHelperEvents(m, &grpc.GenericServerStream[emptypb.Empty, HelperRequest]{ServerStream: stream})
|
||||
}
|
||||
|
||||
// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
|
||||
type StartedService_SubscribeHelperEventsServer = grpc.ServerStreamingServer[HelperRequest]
|
||||
|
||||
func _StartedService_SendHelperResponse_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(HelperResponse)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StartedServiceServer).SendHelperResponse(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StartedService_SendHelperResponse_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StartedServiceServer).SendHelperResponse(ctx, req.(*HelperResponse))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
// StartedService_ServiceDesc is the grpc.ServiceDesc for StartedService service.
|
||||
// It's only intended for direct use with grpc.RegisterService,
|
||||
// and not to be introspected or modified (even as a copy)
|
||||
var StartedService_ServiceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "daemon.StartedService",
|
||||
HandlerType: (*StartedServiceServer)(nil),
|
||||
Methods: []grpc.MethodDesc{
|
||||
{
|
||||
MethodName: "StopService",
|
||||
Handler: _StartedService_StopService_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ReloadService",
|
||||
Handler: _StartedService_ReloadService_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetDefaultLogLevel",
|
||||
Handler: _StartedService_GetDefaultLogLevel_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ClearLogs",
|
||||
Handler: _StartedService_ClearLogs_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetClashModeStatus",
|
||||
Handler: _StartedService_GetClashModeStatus_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetClashMode",
|
||||
Handler: _StartedService_SetClashMode_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "URLTest",
|
||||
Handler: _StartedService_URLTest_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SelectOutbound",
|
||||
Handler: _StartedService_SelectOutbound_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetGroupExpand",
|
||||
Handler: _StartedService_SetGroupExpand_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetSystemProxyStatus",
|
||||
Handler: _StartedService_GetSystemProxyStatus_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetSystemProxyEnabled",
|
||||
Handler: _StartedService_SetSystemProxyEnabled_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CloseConnection",
|
||||
Handler: _StartedService_CloseConnection_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "CloseAllConnections",
|
||||
Handler: _StartedService_CloseAllConnections_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetDeprecatedWarnings",
|
||||
Handler: _StartedService_GetDeprecatedWarnings_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SendHelperResponse",
|
||||
Handler: _StartedService_SendHelperResponse_Handler,
|
||||
},
|
||||
},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "SubscribeServiceStatus",
|
||||
Handler: _StartedService_SubscribeServiceStatus_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeLog",
|
||||
Handler: _StartedService_SubscribeLog_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeStatus",
|
||||
Handler: _StartedService_SubscribeStatus_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeGroups",
|
||||
Handler: _StartedService_SubscribeGroups_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeClashMode",
|
||||
Handler: _StartedService_SubscribeClashMode_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeConnections",
|
||||
Handler: _StartedService_SubscribeConnections_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
{
|
||||
StreamName: "SubscribeHelperEvents",
|
||||
Handler: _StartedService_SubscribeHelperEvents_Handler,
|
||||
ServerStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "daemon/started_service.proto",
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/taskmonitor"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
R "github.com/sagernet/sing-box/route/rule"
|
||||
@@ -37,7 +38,7 @@ type Router struct {
|
||||
rules []adapter.DNSRule
|
||||
defaultDomainStrategy C.DomainStrategy
|
||||
dnsReverseMapping freelru.Cache[netip.Addr, string]
|
||||
platformInterface adapter.PlatformInterface
|
||||
platformInterface platform.Interface
|
||||
}
|
||||
|
||||
func NewRouter(ctx context.Context, logFactory log.Factory, options option.DNSOptions) *Router {
|
||||
|
||||
@@ -49,7 +49,6 @@ type Transport struct {
|
||||
interfaceCallback *list.Element[tun.DefaultInterfaceUpdateCallback]
|
||||
transportLock sync.RWMutex
|
||||
updatedAt time.Time
|
||||
lastError error
|
||||
servers []M.Socksaddr
|
||||
search []string
|
||||
ndots int
|
||||
@@ -93,7 +92,7 @@ func (t *Transport) Start(stage adapter.StartStage) error {
|
||||
t.interfaceCallback = t.networkManager.InterfaceMonitor().RegisterCallback(t.interfaceUpdated)
|
||||
}
|
||||
go func() {
|
||||
_, err := t.fetch()
|
||||
_, err := t.Fetch()
|
||||
if err != nil {
|
||||
t.logger.Error(E.Cause(err, "fetch DNS servers"))
|
||||
}
|
||||
@@ -109,7 +108,7 @@ func (t *Transport) Close() error {
|
||||
}
|
||||
|
||||
func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg, error) {
|
||||
servers, err := t.fetch()
|
||||
servers, err := t.Fetch()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -129,20 +128,11 @@ func (t *Transport) Exchange0(ctx context.Context, message *mDNS.Msg, servers []
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Transport) Fetch() []M.Socksaddr {
|
||||
servers, _ := t.fetch()
|
||||
return servers
|
||||
}
|
||||
|
||||
func (t *Transport) fetch() ([]M.Socksaddr, error) {
|
||||
func (t *Transport) Fetch() ([]M.Socksaddr, error) {
|
||||
t.transportLock.RLock()
|
||||
updatedAt := t.updatedAt
|
||||
lastError := t.lastError
|
||||
servers := t.servers
|
||||
t.transportLock.RUnlock()
|
||||
if lastError != nil {
|
||||
return nil, lastError
|
||||
}
|
||||
if time.Since(updatedAt) < C.DHCPTTL {
|
||||
return servers, nil
|
||||
}
|
||||
@@ -153,7 +143,7 @@ func (t *Transport) fetch() ([]M.Socksaddr, error) {
|
||||
}
|
||||
err := t.updateServers()
|
||||
if err != nil {
|
||||
return servers, err
|
||||
return nil, err
|
||||
}
|
||||
return t.servers, nil
|
||||
}
|
||||
@@ -183,15 +173,12 @@ func (t *Transport) updateServers() error {
|
||||
fetchCtx, cancel := context.WithTimeout(t.ctx, C.DHCPTimeout)
|
||||
err = t.fetchServers0(fetchCtx, iface)
|
||||
cancel()
|
||||
t.updatedAt = time.Now()
|
||||
if err != nil {
|
||||
t.lastError = err
|
||||
return err
|
||||
} else if len(t.servers) == 0 {
|
||||
t.lastError = E.New("dhcp: empty DNS servers response")
|
||||
return t.lastError
|
||||
return E.New("dhcp: empty DNS servers response")
|
||||
} else {
|
||||
t.lastError = nil
|
||||
t.updatedAt = time.Now()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ type Transport struct {
|
||||
|
||||
type dhcpTransport interface {
|
||||
adapter.DNSTransport
|
||||
Fetch() []M.Socksaddr
|
||||
Fetch() ([]M.Socksaddr, error)
|
||||
Exchange0(ctx context.Context, message *mDNS.Msg, servers []M.Socksaddr) (*mDNS.Msg, error)
|
||||
}
|
||||
|
||||
@@ -74,12 +74,14 @@ func (t *Transport) Start(stage adapter.StartStage) error {
|
||||
break
|
||||
}
|
||||
}
|
||||
if t.fallback {
|
||||
t.dhcpTransport = newDHCPTransport(t.TransportAdapter, log.ContextWithOverrideLevel(t.ctx, log.LevelDebug), t.dialer, t.logger)
|
||||
if t.dhcpTransport != nil {
|
||||
err := t.dhcpTransport.Start(stage)
|
||||
if err != nil {
|
||||
return err
|
||||
if !C.IsIos {
|
||||
if t.fallback {
|
||||
t.dhcpTransport = newDHCPTransport(t.TransportAdapter, log.ContextWithOverrideLevel(t.ctx, log.LevelDebug), t.dialer, t.logger)
|
||||
if t.dhcpTransport != nil {
|
||||
err := t.dhcpTransport.Start(stage)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,10 +105,12 @@ func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg,
|
||||
if !t.fallback {
|
||||
return t.exchange(ctx, message, question.Name)
|
||||
}
|
||||
if t.dhcpTransport != nil {
|
||||
dhcpTransports := t.dhcpTransport.Fetch()
|
||||
if len(dhcpTransports) > 0 {
|
||||
return t.dhcpTransport.Exchange0(ctx, message, dhcpTransports)
|
||||
if !C.IsIos {
|
||||
if t.dhcpTransport != nil {
|
||||
dhcpTransports, _ := t.dhcpTransport.Fetch()
|
||||
if len(dhcpTransports) > 0 {
|
||||
return t.dhcpTransport.Exchange0(ctx, message, dhcpTransports)
|
||||
}
|
||||
}
|
||||
}
|
||||
if t.preferGo {
|
||||
@@ -130,5 +134,9 @@ func (t *Transport) Exchange(ctx context.Context, message *mDNS.Msg) (*mDNS.Msg,
|
||||
}
|
||||
return dns.FixedResponse(message.Id, question, addresses, C.DefaultDNSTTL), nil
|
||||
}
|
||||
return nil, E.New("only A and AAAA queries are supported on Apple platforms when using TUN and DHCP unavailable.")
|
||||
if C.IsIos {
|
||||
return nil, E.New("only A and AAAA queries are supported on iOS and tvOS when using NetworkExtension.")
|
||||
} else {
|
||||
return nil, E.New("only A and AAAA queries are supported on macOS when using NetworkExtension and DHCP unavailable.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,96 +2,25 @@
|
||||
icon: material/alert-decagram
|
||||
---
|
||||
|
||||
#### 1.13.0-alpha.32
|
||||
|
||||
* Remove `certificate_public_key_sha256` option for NaiveProxy outbound **1**
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
Self-signed certificates change traffic behavior significantly, which defeats the purpose of NaiveProxy's design to resist traffic analysis.
|
||||
For this reason, and due to maintenance costs, there is no reason to continue supporting `certificate_public_key_sha256`, which was designed to simplify the use of self-signed certificates.
|
||||
|
||||
#### 1.13.0-alpha.31
|
||||
|
||||
* Add QUIC support for NaiveProxy outbound **1**
|
||||
* Add QUIC congestion control option for NaiveProxy **2**
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
NaiveProxy outbound now supports QUIC.
|
||||
|
||||
See [NaiveProxy outbound](/configuration/outbound/naive/#quic).
|
||||
|
||||
**2**:
|
||||
|
||||
NaiveProxy inbound and outbound now supports configurable QUIC congestion control algorithms, including BBR and BBRv2.
|
||||
|
||||
See [NaiveProxy inbound](/configuration/inbound/naive/#quic_congestion_control) and [NaiveProxy outbound](/configuration/outbound/naive/#quic_congestion_control).
|
||||
|
||||
#### 1.13.0-alpha.30
|
||||
|
||||
* Add ECH support for NaiveProxy outbound **1**
|
||||
* Add `tls.ech.query_server_name` option **2**
|
||||
* Fix NaiveProxy outbound on Windows **3**
|
||||
* Add OpenAI Codex Multiplexer service **4**
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
See [NaiveProxy outbound](/configuration/outbound/naive/#tls).
|
||||
|
||||
**2**:
|
||||
|
||||
See [TLS](/configuration/shared/tls/#query_server_name).
|
||||
|
||||
**3**:
|
||||
|
||||
Each Windows release now includes `libcronet.dll`.
|
||||
Ensure this file is in the same directory as `sing-box.exe` or in a directory listed in `PATH`.
|
||||
|
||||
**4**:
|
||||
|
||||
See [OCM](/configuration/service/ocm).
|
||||
|
||||
#### 1.13.0-alpha.29
|
||||
|
||||
* Add UDP over TCP support for naiveproxy outbound **1**
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
See [NaiveProxy outbound](/configuration/outbound/naive/#udp_over_tcp).
|
||||
|
||||
#### 1.13.0-alpha.28
|
||||
|
||||
* Add naiveproxy outbound **1**
|
||||
* Add `disable_tcp_keep_alive`, `tcp_keep_alive` and `tcp_keep_alive_interval` options for dial fields **2**
|
||||
* Update default TCP keep-alive initial period from 10 minutes to 5 minutes
|
||||
* Update quic-go to v0.57.1
|
||||
* Add `disable_tcp_keep_alive`, `tcp_keep_alive` and `tcp_keep_alive_interval` options for dial fields **1**
|
||||
* Update default TCP keep-alive initial period from 10 minutes to 5 minutes
|
||||
* Fixes and improvements
|
||||
|
||||
**1**:
|
||||
|
||||
Only available on Apple platforms, Android, Windows and some Linux architectures.
|
||||
|
||||
See [NaiveProxy outbound](/configuration/outbound/naive/).
|
||||
|
||||
**2**:
|
||||
|
||||
See [Dial Fields](/configuration/shared/dial/#tcp_keep_alive).
|
||||
|
||||
* __Unfortunately, for non-technical reasons, we are currently unable to notarize the standalone version of the macOS client:
|
||||
__Unfortunately, for non-technical reasons, we are currently unable to notarize the standalone version of the macOS client:
|
||||
because system extensions require signatures to function, we have had to temporarily halt its release.__
|
||||
|
||||
__We plan to fix the App Store release issue and launch a new standalone desktop client, but until then,
|
||||
only clients on TestFlight will be available (unless you have an Apple Developer Program and compile from source code).__
|
||||
|
||||
|
||||
#### 1.12.13
|
||||
|
||||
* Fix naive inbound
|
||||
* Fixes and improvements
|
||||
|
||||
__Unfortunately, for non-technical reasons, we are currently unable to notarize the standalone version of the macOS client:
|
||||
|
||||
@@ -1,48 +1,48 @@
|
||||
---
|
||||
icon: material/alert-decagram
|
||||
---
|
||||
|
||||
!!! quote "sing-box 1.12.0 中的更改"
|
||||
|
||||
:material-plus: [type](#type)
|
||||
|
||||
# DNS Server
|
||||
|
||||
### 结构
|
||||
|
||||
```json
|
||||
{
|
||||
"dns": {
|
||||
"servers": [
|
||||
{
|
||||
"type": "",
|
||||
"tag": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### type
|
||||
|
||||
DNS 服务器的类型。
|
||||
|
||||
| 类型 | 格式 |
|
||||
|-----------------|---------------------------|
|
||||
| empty (default) | [Legacy](./legacy/) |
|
||||
| `local` | [Local](./local/) |
|
||||
| `hosts` | [Hosts](./hosts/) |
|
||||
| `tcp` | [TCP](./tcp/) |
|
||||
| `udp` | [UDP](./udp/) |
|
||||
| `tls` | [TLS](./tls/) |
|
||||
| `quic` | [QUIC](./quic/) |
|
||||
| `https` | [HTTPS](./https/) |
|
||||
| `h3` | [HTTP/3](./http3/) |
|
||||
| `dhcp` | [DHCP](./dhcp/) |
|
||||
| `fakeip` | [Fake IP](./fakeip/) |
|
||||
| `tailscale` | [Tailscale](./tailscale/) |
|
||||
| `resolved` | [Resolved](./resolved/) |
|
||||
|
||||
#### tag
|
||||
|
||||
DNS 服务器的标签。
|
||||
---
|
||||
icon: material/alert-decagram
|
||||
---
|
||||
|
||||
!!! quote "sing-box 1.12.0 中的更改"
|
||||
|
||||
:material-plus: [type](#type)
|
||||
|
||||
# DNS Server
|
||||
|
||||
### 结构
|
||||
|
||||
```json
|
||||
{
|
||||
"dns": {
|
||||
"servers": [
|
||||
{
|
||||
"type": "",
|
||||
"tag": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### type
|
||||
|
||||
DNS 服务器的类型。
|
||||
|
||||
| 类型 | 格式 |
|
||||
|-----------------|---------------------------|
|
||||
| empty (default) | [Legacy](./legacy/) |
|
||||
| `local` | [Local](./local/) |
|
||||
| `hosts` | [Hosts](./hosts/) |
|
||||
| `tcp` | [TCP](./tcp/) |
|
||||
| `udp` | [UDP](./udp/) |
|
||||
| `tls` | [TLS](./tls/) |
|
||||
| `quic` | [QUIC](./quic/) |
|
||||
| `https` | [HTTPS](./https/) |
|
||||
| `h3` | [HTTP/3](./http3/) |
|
||||
| `dhcp` | [DHCP](./dhcp/) |
|
||||
| `fakeip` | [Fake IP](./fakeip/) |
|
||||
| `tailscale` | [Tailscale](./tailscale/) |
|
||||
| `resolved` | [Resolved](./resolved/) |
|
||||
|
||||
#### tag
|
||||
|
||||
DNS 服务器的标签。
|
||||
|
||||
@@ -1,25 +1,20 @@
|
||||
!!! quote "Changes in sing-box 1.13.0"
|
||||
|
||||
:material-plus: [quic_congestion_control](#quic_congestion_control)
|
||||
|
||||
### Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "naive",
|
||||
"tag": "naive-in",
|
||||
"network": "udp",
|
||||
...
|
||||
// Listen Fields
|
||||
"type": "naive",
|
||||
"tag": "naive-in",
|
||||
"network": "udp",
|
||||
|
||||
"users": [
|
||||
{
|
||||
"username": "sekai",
|
||||
"password": "password"
|
||||
}
|
||||
],
|
||||
"quic_congestion_control": "",
|
||||
"tls": {}
|
||||
... // Listen Fields
|
||||
|
||||
"users": [
|
||||
{
|
||||
"username": "sekai",
|
||||
"password": "password"
|
||||
}
|
||||
],
|
||||
"tls": {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -41,23 +36,6 @@ Both if empty.
|
||||
|
||||
Naive users.
|
||||
|
||||
#### quic_congestion_control
|
||||
|
||||
!!! question "Since sing-box 1.13.0"
|
||||
|
||||
QUIC congestion control algorithm.
|
||||
|
||||
| Algorithm | Description |
|
||||
|----------------|---------------------------------|
|
||||
| `bbr` | BBR |
|
||||
| `bbr_standard` | BBR (Standard version) |
|
||||
| `bbr2` | BBRv2 |
|
||||
| `bbr2_variant` | BBRv2 (An experimental variant) |
|
||||
| `cubic` | CUBIC |
|
||||
| `reno` | New Reno |
|
||||
|
||||
`bbr` is used by default (the default of QUICHE, used by Chromium which NaiveProxy is based on).
|
||||
|
||||
#### tls
|
||||
|
||||
TLS configuration, see [TLS](/configuration/shared/tls/#inbound).
|
||||
@@ -1,25 +1,20 @@
|
||||
!!! quote "sing-box 1.13.0 中的更改"
|
||||
|
||||
:material-plus: [quic_congestion_control](#quic_congestion_control)
|
||||
|
||||
### 结构
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "naive",
|
||||
"tag": "naive-in",
|
||||
"network": "udp",
|
||||
"type": "naive",
|
||||
"tag": "naive-in",
|
||||
"network": "udp",
|
||||
|
||||
... // 监听字段
|
||||
... // 监听字段
|
||||
|
||||
"users": [
|
||||
{
|
||||
"username": "sekai",
|
||||
"password": "password"
|
||||
}
|
||||
],
|
||||
"quic_congestion_control": "",
|
||||
"tls": {}
|
||||
"users": [
|
||||
{
|
||||
"username": "sekai",
|
||||
"password": "password"
|
||||
}
|
||||
],
|
||||
"tls": {}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -41,23 +36,6 @@
|
||||
|
||||
Naive 用户。
|
||||
|
||||
#### quic_congestion_control
|
||||
|
||||
!!! question "Since sing-box 1.13.0"
|
||||
|
||||
QUIC 拥塞控制算法。
|
||||
|
||||
| 算法 | 描述 |
|
||||
|----------------|--------------------|
|
||||
| `bbr` | BBR |
|
||||
| `bbr_standard` | BBR (标准版) |
|
||||
| `bbr2` | BBRv2 |
|
||||
| `bbr2_variant` | BBRv2 (一种试验变体) |
|
||||
| `cubic` | CUBIC |
|
||||
| `reno` | New Reno |
|
||||
|
||||
默认使用 `bbr`(NaiveProxy 基于的 Chromium 使用的 QUICHE 的默认值)。
|
||||
|
||||
#### tls
|
||||
|
||||
TLS 配置, 参阅 [TLS](/zh/configuration/shared/tls/#inbound)。
|
||||
@@ -36,7 +36,6 @@
|
||||
| `dns` | [DNS](./dns/) |
|
||||
| `selector` | [Selector](./selector/) |
|
||||
| `urltest` | [URLTest](./urltest/) |
|
||||
| `naive` | [NaiveProxy](./naive/) |
|
||||
|
||||
#### tag
|
||||
|
||||
|
||||
@@ -36,7 +36,6 @@
|
||||
| `dns` | [DNS](./dns/) |
|
||||
| `selector` | [Selector](./selector/) |
|
||||
| `urltest` | [URLTest](./urltest/) |
|
||||
| `naive` | [NaiveProxy](./naive/) |
|
||||
|
||||
#### tag
|
||||
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
---
|
||||
icon: material/new-box
|
||||
---
|
||||
|
||||
!!! question "Since sing-box 1.13.0"
|
||||
|
||||
### Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "naive",
|
||||
"tag": "naive-out",
|
||||
|
||||
"server": "127.0.0.1",
|
||||
"server_port": 443,
|
||||
"username": "sekai",
|
||||
"password": "password",
|
||||
"insecure_concurrency": 0,
|
||||
"extra_headers": {},
|
||||
"udp_over_tcp": false | {},
|
||||
"quic": false,
|
||||
"quic_congestion_control": "",
|
||||
"tls": {},
|
||||
|
||||
... // Dial Fields
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "Platform Support"
|
||||
|
||||
NaiveProxy outbound is only available on Apple platforms, Android, Windows and certain Linux builds.
|
||||
|
||||
**Official Release Build Variants:**
|
||||
|
||||
| Build Variant | Platforms | Description |
|
||||
|---------------|-----------|-------------|
|
||||
| (default) | Linux amd64/arm64 | purego build with `libcronet.so` included |
|
||||
| `-glibc` | Linux 386/amd64/arm/arm64 | CGO build dynamically linked with glibc, requires glibc >= 2.31 |
|
||||
| `-musl` | Linux 386/amd64/arm/arm64 | CGO build statically linked with musl, no system requirements |
|
||||
| (default) | Windows amd64/arm64 | purego build with `libcronet.dll` included |
|
||||
|
||||
**Runtime Requirements:**
|
||||
|
||||
- **Linux purego**: `libcronet.so` must be in the same directory as the sing-box binary or in system library path
|
||||
- **Windows**: `libcronet.dll` must be in the same directory as `sing-box.exe` or in a directory listed in `PATH`
|
||||
|
||||
For self-built binaries, see [Build from source](/installation/build-from-source/#with_naive_outbound).
|
||||
|
||||
### Fields
|
||||
|
||||
#### server
|
||||
|
||||
==Required==
|
||||
|
||||
The server address.
|
||||
|
||||
#### server_port
|
||||
|
||||
==Required==
|
||||
|
||||
The server port.
|
||||
|
||||
#### username
|
||||
|
||||
Authentication username.
|
||||
|
||||
#### password
|
||||
|
||||
Authentication password.
|
||||
|
||||
#### insecure_concurrency
|
||||
|
||||
Number of concurrent tunnel connections. Multiple connections make the tunneling easier to detect through traffic analysis, which defeats the purpose of NaiveProxy's design to resist traffic analysis.
|
||||
|
||||
#### extra_headers
|
||||
|
||||
Extra headers to send in HTTP requests.
|
||||
|
||||
#### udp_over_tcp
|
||||
|
||||
UDP over TCP protocol settings.
|
||||
|
||||
See [UDP Over TCP](/configuration/shared/udp-over-tcp/) for details.
|
||||
|
||||
#### quic
|
||||
|
||||
Use QUIC instead of HTTP/2.
|
||||
|
||||
#### quic_congestion_control
|
||||
|
||||
QUIC congestion control algorithm.
|
||||
|
||||
| Algorithm | Description |
|
||||
|-----------|-------------|
|
||||
| `bbr` | BBR |
|
||||
| `bbr2` | BBRv2 |
|
||||
| `cubic` | CUBIC |
|
||||
| `reno` | New Reno |
|
||||
|
||||
`bbr` is used by default (the default of QUICHE, used by Chromium which NaiveProxy is based on).
|
||||
|
||||
#### tls
|
||||
|
||||
==Required==
|
||||
|
||||
TLS configuration, see [TLS](/configuration/shared/tls/#outbound).
|
||||
|
||||
Only `server_name`, `certificate`, `certificate_path` and `ech` are supported.
|
||||
|
||||
Self-signed certificates change traffic behavior significantly, which defeats the purpose of NaiveProxy's design to resist traffic analysis, and should not be used in production.
|
||||
|
||||
### Dial Fields
|
||||
|
||||
See [Dial Fields](/configuration/shared/dial/) for details.
|
||||
@@ -1,114 +0,0 @@
|
||||
---
|
||||
icon: material/new-box
|
||||
---
|
||||
|
||||
!!! question "自 sing-box 1.13.0 起"
|
||||
|
||||
### 结构
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "naive",
|
||||
"tag": "naive-out",
|
||||
|
||||
"server": "127.0.0.1",
|
||||
"server_port": 443,
|
||||
"username": "sekai",
|
||||
"password": "password",
|
||||
"insecure_concurrency": 0,
|
||||
"extra_headers": {},
|
||||
"udp_over_tcp": false | {},
|
||||
"quic": false,
|
||||
"quic_congestion_control": "",
|
||||
"tls": {},
|
||||
|
||||
... // 拨号字段
|
||||
}
|
||||
```
|
||||
|
||||
!!! warning "平台支持"
|
||||
|
||||
NaiveProxy 出站仅在 Apple 平台、Android、Windows 和特定 Linux 构建上可用。
|
||||
|
||||
**官方发布版本区别:**
|
||||
|
||||
| 构建变体 | 平台 | 说明 |
|
||||
|-----------|------------------------|------------------------------------------|
|
||||
| (默认) | Linux amd64/arm64 | purego 构建,包含 `libcronet.so` |
|
||||
| `-glibc` | Linux 386/amd64/arm/arm64 | CGO 构建,动态链接 glibc,要求 glibc >= 2.31 |
|
||||
| `-musl` | Linux 386/amd64/arm/arm64 | CGO 构建,静态链接 musl,无系统要求 |
|
||||
| (默认) | Windows amd64/arm64 | purego 构建,包含 `libcronet.dll` |
|
||||
|
||||
**运行时要求:**
|
||||
|
||||
- **Linux purego**:`libcronet.so` 必须位于 sing-box 二进制文件相同目录或系统库路径中
|
||||
- **Windows**:`libcronet.dll` 必须位于 `sing-box.exe` 相同目录或 `PATH` 中的任意目录
|
||||
|
||||
自行构建请参阅 [从源代码构建](/zh/installation/build-from-source/#with_naive_outbound)。
|
||||
|
||||
### 字段
|
||||
|
||||
#### server
|
||||
|
||||
==必填==
|
||||
|
||||
服务器地址。
|
||||
|
||||
#### server_port
|
||||
|
||||
==必填==
|
||||
|
||||
服务器端口。
|
||||
|
||||
#### username
|
||||
|
||||
认证用户名。
|
||||
|
||||
#### password
|
||||
|
||||
认证密码。
|
||||
|
||||
#### insecure_concurrency
|
||||
|
||||
并发隧道连接数。多连接使隧道更容易被流量分析检测,违背 NaiveProxy 抵抗流量分析的设计目的。
|
||||
|
||||
#### extra_headers
|
||||
|
||||
HTTP 请求中发送的额外头部。
|
||||
|
||||
#### udp_over_tcp
|
||||
|
||||
UDP over TCP 配置。
|
||||
|
||||
参阅 [UDP Over TCP](/zh/configuration/shared/udp-over-tcp/)。
|
||||
|
||||
#### quic
|
||||
|
||||
使用 QUIC 代替 HTTP/2。
|
||||
|
||||
#### quic_congestion_control
|
||||
|
||||
QUIC 拥塞控制算法。
|
||||
|
||||
| 算法 | 描述 |
|
||||
|------|------|
|
||||
| `bbr` | BBR |
|
||||
| `bbr2` | BBRv2 |
|
||||
| `cubic` | CUBIC |
|
||||
| `reno` | New Reno |
|
||||
|
||||
默认使用 `bbr`(NaiveProxy 基于的 Chromium 使用的 QUICHE 的默认值)。
|
||||
|
||||
#### tls
|
||||
|
||||
==必填==
|
||||
|
||||
TLS 配置, 参阅 [TLS](/zh/configuration/shared/tls/#outbound)。
|
||||
|
||||
只有 `server_name`、`certificate`、`certificate_path` 和 `ech` 是被支持的。
|
||||
|
||||
自签名证书会显著改变流量行为,违背了 NaiveProxy 旨在抵抗流量分析的设计初衷,不应该在生产环境中使用。
|
||||
|
||||
### 拨号字段
|
||||
|
||||
参阅 [拨号字段](/zh/configuration/shared/dial/)。
|
||||
@@ -25,7 +25,6 @@ icon: material/new-box
|
||||
|------------|------------------------|
|
||||
| `ccm` | [CCM](./ccm) |
|
||||
| `derp` | [DERP](./derp) |
|
||||
| `ocm` | [OCM](./ocm) |
|
||||
| `resolved` | [Resolved](./resolved) |
|
||||
| `ssm-api` | [SSM API](./ssm-api) |
|
||||
|
||||
|
||||
@@ -25,7 +25,6 @@ icon: material/new-box
|
||||
|-----------|------------------------|
|
||||
| `ccm` | [CCM](./ccm) |
|
||||
| `derp` | [DERP](./derp) |
|
||||
| `ocm` | [OCM](./ocm) |
|
||||
| `resolved`| [Resolved](./resolved) |
|
||||
| `ssm-api` | [SSM API](./ssm-api) |
|
||||
|
||||
|
||||
@@ -1,171 +0,0 @@
|
||||
---
|
||||
icon: material/new-box
|
||||
---
|
||||
|
||||
!!! question "Since sing-box 1.13.0"
|
||||
|
||||
# OCM
|
||||
|
||||
OCM (OpenAI Codex Multiplexer) service is a multiplexing service that allows you to access your local OpenAI Codex subscription remotely through custom tokens.
|
||||
|
||||
It handles OAuth authentication with OpenAI's API on your local machine while allowing remote clients to authenticate using custom tokens.
|
||||
|
||||
### Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "ocm",
|
||||
|
||||
... // Listen Fields
|
||||
|
||||
"credential_path": "",
|
||||
"usages_path": "",
|
||||
"users": [],
|
||||
"headers": {},
|
||||
"detour": "",
|
||||
"tls": {}
|
||||
}
|
||||
```
|
||||
|
||||
### Listen Fields
|
||||
|
||||
See [Listen Fields](/configuration/shared/listen/) for details.
|
||||
|
||||
### Fields
|
||||
|
||||
#### credential_path
|
||||
|
||||
Path to the OpenAI OAuth credentials file.
|
||||
|
||||
If not specified, defaults to `~/.codex/auth.json`.
|
||||
|
||||
Refreshed tokens are automatically written back to the same location.
|
||||
|
||||
#### usages_path
|
||||
|
||||
Path to the file for storing aggregated API usage statistics.
|
||||
|
||||
Usage tracking is disabled if not specified.
|
||||
|
||||
When enabled, the service tracks and saves comprehensive statistics including:
|
||||
- Request counts
|
||||
- Token usage (input, output, cached)
|
||||
- Calculated costs in USD based on OpenAI API pricing
|
||||
|
||||
Statistics are organized by model and optionally by user when authentication is enabled.
|
||||
|
||||
The statistics file is automatically saved every minute and upon service shutdown.
|
||||
|
||||
#### users
|
||||
|
||||
List of authorized users for token authentication.
|
||||
|
||||
If empty, no authentication is required.
|
||||
|
||||
Object format:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "",
|
||||
"token": ""
|
||||
}
|
||||
```
|
||||
|
||||
Object fields:
|
||||
|
||||
- `name`: Username identifier for tracking purposes.
|
||||
- `token`: Bearer token for authentication. Clients authenticate by setting the `Authorization: Bearer <token>` header.
|
||||
|
||||
#### headers
|
||||
|
||||
Custom HTTP headers to send to the OpenAI API.
|
||||
|
||||
These headers will override any existing headers with the same name.
|
||||
|
||||
#### detour
|
||||
|
||||
Outbound tag for connecting to the OpenAI API.
|
||||
|
||||
#### tls
|
||||
|
||||
TLS configuration, see [TLS](/configuration/shared/tls/#inbound).
|
||||
|
||||
### Example
|
||||
|
||||
#### Server
|
||||
|
||||
```json
|
||||
{
|
||||
"services": [
|
||||
{
|
||||
"type": "ocm",
|
||||
"listen": "127.0.0.1",
|
||||
"listen_port": 8080
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Client
|
||||
|
||||
Add to `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[model_providers.ocm]
|
||||
name = "OCM Proxy"
|
||||
base_url = "http://127.0.0.1:8080/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
codex --model-provider ocm
|
||||
```
|
||||
|
||||
### Example with Authentication
|
||||
|
||||
#### Server
|
||||
|
||||
```json
|
||||
{
|
||||
"services": [
|
||||
{
|
||||
"type": "ocm",
|
||||
"listen": "0.0.0.0",
|
||||
"listen_port": 8080,
|
||||
"usages_path": "./codex-usages.json",
|
||||
"users": [
|
||||
{
|
||||
"name": "alice",
|
||||
"token": "sk-alice-secret-token"
|
||||
},
|
||||
{
|
||||
"name": "bob",
|
||||
"token": "sk-bob-secret-token"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Client
|
||||
|
||||
Add to `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[model_providers.ocm]
|
||||
name = "OCM Proxy"
|
||||
base_url = "http://127.0.0.1:8080/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "sk-alice-secret-token"
|
||||
```
|
||||
|
||||
Then run:
|
||||
|
||||
```bash
|
||||
codex --model-provider ocm
|
||||
```
|
||||
@@ -1,171 +0,0 @@
|
||||
---
|
||||
icon: material/new-box
|
||||
---
|
||||
|
||||
!!! question "自 sing-box 1.13.0 起"
|
||||
|
||||
# OCM
|
||||
|
||||
OCM(OpenAI Codex 多路复用器)服务是一个多路复用服务,允许您通过自定义令牌远程访问本地的 OpenAI Codex 订阅。
|
||||
|
||||
它在本地机器上处理与 OpenAI API 的 OAuth 身份验证,同时允许远程客户端使用自定义令牌进行身份验证。
|
||||
|
||||
### 结构
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "ocm",
|
||||
|
||||
... // 监听字段
|
||||
|
||||
"credential_path": "",
|
||||
"usages_path": "",
|
||||
"users": [],
|
||||
"headers": {},
|
||||
"detour": "",
|
||||
"tls": {}
|
||||
}
|
||||
```
|
||||
|
||||
### 监听字段
|
||||
|
||||
参阅 [监听字段](/zh/configuration/shared/listen/) 了解详情。
|
||||
|
||||
### 字段
|
||||
|
||||
#### credential_path
|
||||
|
||||
OpenAI OAuth 凭据文件的路径。
|
||||
|
||||
如果未指定,默认值为 `~/.codex/auth.json`。
|
||||
|
||||
刷新的令牌会自动写回相同位置。
|
||||
|
||||
#### usages_path
|
||||
|
||||
用于存储聚合 API 使用统计信息的文件路径。
|
||||
|
||||
如果未指定,使用跟踪将被禁用。
|
||||
|
||||
启用后,服务会跟踪并保存全面的统计信息,包括:
|
||||
- 请求计数
|
||||
- 令牌使用量(输入、输出、缓存)
|
||||
- 基于 OpenAI API 定价计算的美元成本
|
||||
|
||||
统计信息按模型以及可选的用户(启用身份验证时)进行组织。
|
||||
|
||||
统计文件每分钟自动保存一次,并在服务关闭时保存。
|
||||
|
||||
#### users
|
||||
|
||||
用于令牌身份验证的授权用户列表。
|
||||
|
||||
如果为空,则不需要身份验证。
|
||||
|
||||
对象格式:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "",
|
||||
"token": ""
|
||||
}
|
||||
```
|
||||
|
||||
对象字段:
|
||||
|
||||
- `name`:用于跟踪的用户名标识符。
|
||||
- `token`:用于身份验证的 Bearer 令牌。客户端通过设置 `Authorization: Bearer <token>` 头进行身份验证。
|
||||
|
||||
#### headers
|
||||
|
||||
发送到 OpenAI API 的自定义 HTTP 头。
|
||||
|
||||
这些头会覆盖同名的现有头。
|
||||
|
||||
#### detour
|
||||
|
||||
用于连接 OpenAI API 的出站标签。
|
||||
|
||||
#### tls
|
||||
|
||||
TLS 配置,参阅 [TLS](/zh/configuration/shared/tls/#inbound)。
|
||||
|
||||
### 示例
|
||||
|
||||
#### 服务端
|
||||
|
||||
```json
|
||||
{
|
||||
"services": [
|
||||
{
|
||||
"type": "ocm",
|
||||
"listen": "127.0.0.1",
|
||||
"listen_port": 8080
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 客户端
|
||||
|
||||
在 `~/.codex/config.toml` 中添加:
|
||||
|
||||
```toml
|
||||
[model_providers.ocm]
|
||||
name = "OCM Proxy"
|
||||
base_url = "http://127.0.0.1:8080/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
```
|
||||
|
||||
然后运行:
|
||||
|
||||
```bash
|
||||
codex --model-provider ocm
|
||||
```
|
||||
|
||||
### 带身份验证的示例
|
||||
|
||||
#### 服务端
|
||||
|
||||
```json
|
||||
{
|
||||
"services": [
|
||||
{
|
||||
"type": "ocm",
|
||||
"listen": "0.0.0.0",
|
||||
"listen_port": 8080,
|
||||
"usages_path": "./codex-usages.json",
|
||||
"users": [
|
||||
{
|
||||
"name": "alice",
|
||||
"token": "sk-alice-secret-token"
|
||||
},
|
||||
{
|
||||
"name": "bob",
|
||||
"token": "sk-bob-secret-token"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### 客户端
|
||||
|
||||
在 `~/.codex/config.toml` 中添加:
|
||||
|
||||
```toml
|
||||
[model_providers.ocm]
|
||||
name = "OCM Proxy"
|
||||
base_url = "http://127.0.0.1:8080/v1"
|
||||
wire_api = "responses"
|
||||
requires_openai_auth = false
|
||||
experimental_bearer_token = "sk-alice-secret-token"
|
||||
```
|
||||
|
||||
然后运行:
|
||||
|
||||
```bash
|
||||
codex --model-provider ocm
|
||||
```
|
||||
@@ -4,17 +4,16 @@ icon: material/new-box
|
||||
|
||||
!!! quote "Changes in sing-box 1.13.0"
|
||||
|
||||
:material-plus: [kernel_tx](#kernel_tx)
|
||||
:material-plus: [kernel_rx](#kernel_rx)
|
||||
:material-plus: [curve_preferences](#curve_preferences)
|
||||
:material-plus: [certificate_public_key_sha256](#certificate_public_key_sha256)
|
||||
:material-plus: [client_certificate](#client_certificate)
|
||||
:material-plus: [client_certificate_path](#client_certificate_path)
|
||||
:material-plus: [client_key](#client_key)
|
||||
:material-plus: [client_key_path](#client_key_path)
|
||||
:material-plus: [client_authentication](#client_authentication)
|
||||
:material-plus: [client_certificate_public_key_sha256](#client_certificate_public_key_sha256)
|
||||
:material-plus: [ech.query_server_name](#query_server_name)
|
||||
:material-plus: [kernel_tx](#kernel_tx)
|
||||
:material-plus: [kernel_rx](#kernel_rx)
|
||||
:material-plus: [curve_preferences](#curve_preferences)
|
||||
:material-plus: [certificate_public_key_sha256](#certificate_public_key_sha256)
|
||||
:material-plus: [client_certificate](#client_certificate)
|
||||
:material-plus: [client_certificate_path](#client_certificate_path)
|
||||
:material-plus: [client_key](#client_key)
|
||||
:material-plus: [client_key_path](#client_key_path)
|
||||
:material-plus: [client_authentication](#client_authentication)
|
||||
:material-plus: [client_certificate_public_key_sha256](#client_certificate_public_key_sha256)
|
||||
|
||||
!!! quote "Changes in sing-box 1.12.0"
|
||||
|
||||
@@ -119,7 +118,6 @@ icon: material/new-box
|
||||
"enabled": false,
|
||||
"config": [],
|
||||
"config_path": "",
|
||||
"query_server_name": "",
|
||||
|
||||
// Deprecated
|
||||
"pq_signature_schemes_enabled": false,
|
||||
@@ -507,16 +505,6 @@ The path to ECH configuration, in PEM format.
|
||||
|
||||
If empty, load from DNS will be attempted.
|
||||
|
||||
#### query_server_name
|
||||
|
||||
!!! question "Since sing-box 1.13.0"
|
||||
|
||||
==Client only==
|
||||
|
||||
Overrides the domain name used for ECH HTTPS record queries.
|
||||
|
||||
If empty, `server_name` is used for queries.
|
||||
|
||||
#### fragment
|
||||
|
||||
!!! question "Since sing-box 1.12.0"
|
||||
|
||||
@@ -4,17 +4,16 @@ icon: material/new-box
|
||||
|
||||
!!! quote "sing-box 1.13.0 中的更改"
|
||||
|
||||
:material-plus: [kernel_tx](#kernel_tx)
|
||||
:material-plus: [kernel_rx](#kernel_rx)
|
||||
:material-plus: [curve_preferences](#curve_preferences)
|
||||
:material-plus: [certificate_public_key_sha256](#certificate_public_key_sha256)
|
||||
:material-plus: [client_certificate](#client_certificate)
|
||||
:material-plus: [client_certificate_path](#client_certificate_path)
|
||||
:material-plus: [client_key](#client_key)
|
||||
:material-plus: [client_key_path](#client_key_path)
|
||||
:material-plus: [client_authentication](#client_authentication)
|
||||
:material-plus: [client_certificate_public_key_sha256](#client_certificate_public_key_sha256)
|
||||
:material-plus: [ech.query_server_name](#query_server_name)
|
||||
:material-plus: [kernel_tx](#kernel_tx)
|
||||
:material-plus: [kernel_rx](#kernel_rx)
|
||||
:material-plus: [curve_preferences](#curve_preferences)
|
||||
:material-plus: [certificate_public_key_sha256](#certificate_public_key_sha256)
|
||||
:material-plus: [client_certificate](#client_certificate)
|
||||
:material-plus: [client_certificate_path](#client_certificate_path)
|
||||
:material-plus: [client_key](#client_key)
|
||||
:material-plus: [client_key_path](#client_key_path)
|
||||
:material-plus: [client_authentication](#client_authentication)
|
||||
:material-plus: [client_certificate_public_key_sha256](#client_certificate_public_key_sha256)
|
||||
|
||||
!!! quote "sing-box 1.12.0 中的更改"
|
||||
|
||||
@@ -119,7 +118,6 @@ icon: material/new-box
|
||||
"enabled": false,
|
||||
"config": [],
|
||||
"config_path": "",
|
||||
"query_server_name": "",
|
||||
|
||||
// 废弃的
|
||||
"pq_signature_schemes_enabled": false,
|
||||
@@ -505,16 +503,6 @@ ECH 配置路径,PEM 格式。
|
||||
|
||||
如果为空,将尝试从 DNS 加载。
|
||||
|
||||
#### query_server_name
|
||||
|
||||
!!! question "自 sing-box 1.13.0 起"
|
||||
|
||||
==仅客户端==
|
||||
|
||||
覆盖用于 ECH HTTPS 记录查询的域名。
|
||||
|
||||
如果为空,使用 `server_name` 查询。
|
||||
|
||||
#### fragment
|
||||
|
||||
!!! question "自 sing-box 1.12.0 起"
|
||||
|
||||
@@ -57,45 +57,6 @@ go build -tags "tag_a tag_b" ./cmd/sing-box
|
||||
| `with_v2ray_api` | :material-close:️ | Build with V2Ray API support, see [Experimental](/configuration/experimental#v2ray-api-fields). |
|
||||
| `with_gvisor` | :material-check: | Build with gVisor support, see [Tun inbound](/configuration/inbound/tun#stack) and [WireGuard outbound](/configuration/outbound/wireguard#system_interface). |
|
||||
| `with_embedded_tor` (CGO required) | :material-close:️ | Build with embedded Tor support, see [Tor outbound](/configuration/outbound/tor/). |
|
||||
| `with_tailscale` | :material-check: | Build with Tailscale support, see [Tailscale endpoint](/configuration/endpoint/tailscale) |
|
||||
| `with_naive_outbound` | :material-close:️ | Build with NaiveProxy outbound support, see [NaiveProxy outbound](/configuration/outbound/naive/). |
|
||||
| `with_tailscale` | :material-check: | Build with Tailscale support, see [Tailscale endpoint](/configuration/endpoint/tailscale) |
|
||||
|
||||
It is not recommended to change the default build tag list unless you really know what you are adding.
|
||||
|
||||
## :material-layers: with_naive_outbound
|
||||
|
||||
NaiveProxy outbound requires special build configurations depending on your target platform.
|
||||
|
||||
### Supported Platforms
|
||||
|
||||
| Platform | Architectures | Mode | Requirements |
|
||||
|-----------------|------------------------|--------|---------------------------------------------------|
|
||||
| Linux | amd64, arm64 | purego | None (library included in official releases) |
|
||||
| Linux | 386, amd64, arm, arm64 | CGO | Chromium toolchain, glibc >= 2.31 at runtime |
|
||||
| Linux (musl) | 386, amd64, arm, arm64 | CGO | Chromium toolchain |
|
||||
| Windows | amd64, arm64 | purego | None (library included in official releases) |
|
||||
| Apple platforms | * | CGO | Xcode |
|
||||
| Android | * | CGO | Android NDK |
|
||||
|
||||
### Windows
|
||||
|
||||
Use `with_purego` tag.
|
||||
|
||||
For official releases, `libcronet.dll` is included in the archive. For self-built binaries, download from [cronet-go releases](https://github.com/sagernet/cronet-go/releases) and place in the same directory as `sing-box.exe` or in a directory listed in `PATH`.
|
||||
|
||||
### Linux (purego, amd64/arm64 only)
|
||||
|
||||
Use `with_purego` tag.
|
||||
|
||||
For official releases, `libcronet.so` is included in the archive. For self-built binaries, download from [cronet-go releases](https://github.com/sagernet/cronet-go/releases) and place in the same directory as sing-box binary or in system library path.
|
||||
|
||||
### Linux (CGO)
|
||||
|
||||
See [cronet-go](https://github.com/sagernet/cronet-go#linux-build-instructions).
|
||||
|
||||
- **glibc build**: Requires glibc >= 2.31 at runtime
|
||||
- **musl build**: Use `with_musl` tag, statically linked, no runtime requirements
|
||||
|
||||
### Apple platforms / Android
|
||||
|
||||
See [cronet-go](https://github.com/sagernet/cronet-go).
|
||||
|
||||
@@ -62,44 +62,5 @@ go build -tags "tag_a tag_b" ./cmd/sing-box
|
||||
| `with_gvisor` | :material-check: | Build with gVisor support, see [Tun inbound](/configuration/inbound/tun#stack) and [WireGuard outbound](/configuration/outbound/wireguard#system_interface). |
|
||||
| `with_embedded_tor` (CGO required) | :material-close:️ | Build with embedded Tor support, see [Tor outbound](/configuration/outbound/tor/). |
|
||||
| `with_tailscale` | :material-check: | Build with Tailscale support, see [Tailscale endpoint](/configuration/endpoint/tailscale) |
|
||||
| `with_naive_outbound` | :material-close:️ | 构建 NaiveProxy 出站支持,参阅 [NaiveProxy 出站](/zh/configuration/outbound/naive/)。 |
|
||||
|
||||
除非您确实知道您正在启用什么,否则不建议更改默认构建标签列表。
|
||||
|
||||
## :material-layers: with_naive_outbound
|
||||
|
||||
NaiveProxy 出站需要根据目标平台进行特殊的构建配置。
|
||||
|
||||
### 支持的平台
|
||||
|
||||
| 平台 | 架构 | 模式 | 要求 |
|
||||
|---------------|------------------------|--------|--------------------------------|
|
||||
| Linux | amd64, arm64 | purego | 无(官方发布版本已包含库文件) |
|
||||
| Linux | 386, amd64, arm, arm64 | CGO | Chromium 工具链,运行时需要 glibc >= 2.31 |
|
||||
| Linux (musl) | 386, amd64, arm, arm64 | CGO | Chromium 工具链 |
|
||||
| Windows | amd64, arm64 | purego | 无(官方发布版本已包含库文件) |
|
||||
| Apple 平台 | * | CGO | Xcode |
|
||||
| Android | * | CGO | Android NDK |
|
||||
|
||||
### Windows
|
||||
|
||||
使用 `with_purego` 标记。
|
||||
|
||||
官方发布版本已包含 `libcronet.dll`。自行构建时,从 [cronet-go releases](https://github.com/sagernet/cronet-go/releases) 下载并放置在 `sing-box.exe` 相同目录或 `PATH` 中的任意目录。
|
||||
|
||||
### Linux (purego, 仅 amd64/arm64)
|
||||
|
||||
使用 `with_purego` 标记。
|
||||
|
||||
官方发布版本已包含 `libcronet.so`。自行构建时,从 [cronet-go releases](https://github.com/sagernet/cronet-go/releases) 下载并放置在 sing-box 二进制文件相同目录或系统库路径中。
|
||||
|
||||
### Linux (CGO)
|
||||
|
||||
参阅 [cronet-go](https://github.com/sagernet/cronet-go#linux-build-instructions)。
|
||||
|
||||
- **glibc 构建**:运行时需要 glibc >= 2.31
|
||||
- **musl 构建**:使用 `with_musl` 标记,静态链接,无运行时要求
|
||||
|
||||
### Apple 平台 / Android
|
||||
|
||||
参阅 [cronet-go](https://github.com/sagernet/cronet-go)。
|
||||
|
||||
@@ -24,7 +24,6 @@ import (
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/common/observable"
|
||||
"github.com/sagernet/sing/service"
|
||||
"github.com/sagernet/sing/service/filemanager"
|
||||
"github.com/sagernet/ws"
|
||||
@@ -54,7 +53,7 @@ type Server struct {
|
||||
|
||||
mode string
|
||||
modeList []string
|
||||
modeUpdateHook *observable.Subscriber[struct{}]
|
||||
modeUpdateHook chan<- struct{}
|
||||
|
||||
externalController bool
|
||||
externalUI string
|
||||
@@ -204,7 +203,7 @@ func (s *Server) ModeList() []string {
|
||||
return s.modeList
|
||||
}
|
||||
|
||||
func (s *Server) SetModeUpdateHook(hook *observable.Subscriber[struct{}]) {
|
||||
func (s *Server) SetModeUpdateHook(hook chan<- struct{}) {
|
||||
s.modeUpdateHook = hook
|
||||
}
|
||||
|
||||
@@ -222,7 +221,10 @@ func (s *Server) SetMode(newMode string) {
|
||||
}
|
||||
s.mode = newMode
|
||||
if s.modeUpdateHook != nil {
|
||||
s.modeUpdateHook.Emit(struct{}{})
|
||||
select {
|
||||
case s.modeUpdateHook <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
s.dnsRouter.ClearCache()
|
||||
cacheFile := service.FromContext[adapter.CacheFile](s.ctx)
|
||||
|
||||
@@ -45,15 +45,15 @@ func (t TrackerMetadata) MarshalJSON() ([]byte, error) {
|
||||
if t.Metadata.ProcessInfo != nil {
|
||||
if t.Metadata.ProcessInfo.ProcessPath != "" {
|
||||
processPath = t.Metadata.ProcessInfo.ProcessPath
|
||||
} else if t.Metadata.ProcessInfo.AndroidPackageName != "" {
|
||||
processPath = t.Metadata.ProcessInfo.AndroidPackageName
|
||||
} else if t.Metadata.ProcessInfo.PackageName != "" {
|
||||
processPath = t.Metadata.ProcessInfo.PackageName
|
||||
}
|
||||
if processPath == "" {
|
||||
if t.Metadata.ProcessInfo.UserId != -1 {
|
||||
processPath = F.ToString(t.Metadata.ProcessInfo.UserId)
|
||||
}
|
||||
} else if t.Metadata.ProcessInfo.UserName != "" {
|
||||
processPath = F.ToString(processPath, " (", t.Metadata.ProcessInfo.UserName, ")")
|
||||
} else if t.Metadata.ProcessInfo.User != "" {
|
||||
processPath = F.ToString(processPath, " (", t.Metadata.ProcessInfo.User, ")")
|
||||
} else if t.Metadata.ProcessInfo.UserId != -1 {
|
||||
processPath = F.ToString(processPath, " (", t.Metadata.ProcessInfo.UserId, ")")
|
||||
}
|
||||
|
||||
@@ -3,7 +3,18 @@ package libbox
|
||||
const (
|
||||
CommandLog int32 = iota
|
||||
CommandStatus
|
||||
CommandServiceReload
|
||||
CommandServiceClose
|
||||
CommandCloseConnections
|
||||
CommandGroup
|
||||
CommandSelectOutbound
|
||||
CommandURLTest
|
||||
CommandGroupExpand
|
||||
CommandClashMode
|
||||
CommandSetClashMode
|
||||
CommandGetSystemProxyStatus
|
||||
CommandSetSystemProxyEnabled
|
||||
CommandConnections
|
||||
CommandCloseConnection
|
||||
CommandGetDeprecatedNotes
|
||||
)
|
||||
|
||||
124
experimental/libbox/command_clash_mode.go
Normal file
124
experimental/libbox/command_clash_mode.go
Normal file
@@ -0,0 +1,124 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
func (c *CommandClient) SetClashMode(newMode string) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandSetClashMode))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(conn, binary.BigEndian, newMode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleSetClashMode(conn net.Conn) error {
|
||||
newMode, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := s.service
|
||||
if service == nil {
|
||||
return writeError(conn, E.New("service not ready"))
|
||||
}
|
||||
service.clashServer.(*clashapi.Server).SetMode(newMode)
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleModeConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
for {
|
||||
newMode, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.UpdateClashMode(newMode)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleModeConn(conn net.Conn) error {
|
||||
ctx := connKeepAlive(conn)
|
||||
for s.service == nil {
|
||||
select {
|
||||
case <-time.After(time.Second):
|
||||
continue
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
err := writeClashModeList(conn, s.service.clashServer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for {
|
||||
select {
|
||||
case <-s.modeUpdate:
|
||||
err = varbin.Write(conn, binary.BigEndian, s.service.clashServer.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readClashModeList(reader io.Reader) (modeList []string, currentMode string, err error) {
|
||||
var modeListLength uint16
|
||||
err = binary.Read(reader, binary.BigEndian, &modeListLength)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if modeListLength == 0 {
|
||||
return
|
||||
}
|
||||
modeList = make([]string, modeListLength)
|
||||
for i := 0; i < int(modeListLength); i++ {
|
||||
modeList[i], err = varbin.ReadValue[string](reader, binary.BigEndian)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
currentMode, err = varbin.ReadValue[string](reader, binary.BigEndian)
|
||||
return
|
||||
}
|
||||
|
||||
func writeClashModeList(writer io.Writer, clashServer adapter.ClashServer) error {
|
||||
modeList := clashServer.ModeList()
|
||||
err := binary.Write(writer, binary.BigEndian, uint16(len(modeList)))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(modeList) > 0 {
|
||||
for _, mode := range modeList {
|
||||
err = varbin.Write(writer, binary.BigEndian, mode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = varbin.Write(writer, binary.BigEndian, clashServer.Mode())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,49 +1,32 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/protobuf/types/known/emptypb"
|
||||
)
|
||||
|
||||
type CommandClient struct {
|
||||
handler CommandClientHandler
|
||||
grpcConn *grpc.ClientConn
|
||||
grpcClient daemon.StartedServiceClient
|
||||
options CommandClientOptions
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
clientMutex sync.RWMutex
|
||||
handler CommandClientHandler
|
||||
conn net.Conn
|
||||
options CommandClientOptions
|
||||
}
|
||||
|
||||
type CommandClientOptions struct {
|
||||
commands []int32
|
||||
Command int32
|
||||
StatusInterval int64
|
||||
}
|
||||
|
||||
func (o *CommandClientOptions) AddCommand(command int32) {
|
||||
o.commands = append(o.commands, command)
|
||||
}
|
||||
|
||||
type CommandClientHandler interface {
|
||||
Connected()
|
||||
Disconnected(message string)
|
||||
SetDefaultLogLevel(level int32)
|
||||
ClearLogs()
|
||||
WriteLogs(messageList LogIterator)
|
||||
WriteLogs(messageList StringIterator)
|
||||
WriteStatus(message *StatusMessage)
|
||||
WriteGroups(message OutboundGroupIterator)
|
||||
InitializeClashMode(modeList StringIterator, currentMode string)
|
||||
@@ -51,17 +34,6 @@ type CommandClientHandler interface {
|
||||
WriteConnections(message *Connections)
|
||||
}
|
||||
|
||||
type LogEntry struct {
|
||||
Level int32
|
||||
Message string
|
||||
}
|
||||
|
||||
type LogIterator interface {
|
||||
Len() int32
|
||||
HasNext() bool
|
||||
Next() *LogEntry
|
||||
}
|
||||
|
||||
func NewStandaloneCommandClient() *CommandClient {
|
||||
return new(CommandClient)
|
||||
}
|
||||
@@ -73,38 +45,24 @@ func NewCommandClient(handler CommandClientHandler, options *CommandClientOption
|
||||
}
|
||||
}
|
||||
|
||||
func unaryClientAuthInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
|
||||
if sCommandServerSecret != "" {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, "x-command-secret", sCommandServerSecret)
|
||||
}
|
||||
return invoker(ctx, method, req, reply, cc, opts...)
|
||||
}
|
||||
|
||||
func streamClientAuthInterceptor(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {
|
||||
if sCommandServerSecret != "" {
|
||||
ctx = metadata.AppendToOutgoingContext(ctx, "x-command-secret", sCommandServerSecret)
|
||||
}
|
||||
return streamer(ctx, desc, cc, method, opts...)
|
||||
}
|
||||
|
||||
func (c *CommandClient) grpcDial() (*grpc.ClientConn, error) {
|
||||
var target string
|
||||
if sCommandServerListenPort == 0 {
|
||||
target = "unix://" + filepath.Join(sBasePath, "command.sock")
|
||||
func (c *CommandClient) directConnect() (net.Conn, error) {
|
||||
if !sTVOS {
|
||||
return net.DialUnix("unix", nil, &net.UnixAddr{
|
||||
Name: filepath.Join(sBasePath, "command.sock"),
|
||||
Net: "unix",
|
||||
})
|
||||
} else {
|
||||
target = net.JoinHostPort("127.0.0.1", strconv.Itoa(int(sCommandServerListenPort)))
|
||||
return net.Dial("tcp", "127.0.0.1:8964")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) directConnectWithRetry() (net.Conn, error) {
|
||||
var (
|
||||
conn *grpc.ClientConn
|
||||
conn net.Conn
|
||||
err error
|
||||
)
|
||||
clientOptions := []grpc.DialOption{
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithUnaryInterceptor(unaryClientAuthInterceptor),
|
||||
grpc.WithStreamInterceptor(streamClientAuthInterceptor),
|
||||
}
|
||||
for i := 0; i < 10; i++ {
|
||||
conn, err = grpc.NewClient(target, clientOptions...)
|
||||
conn, err = c.directConnect()
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
@@ -114,367 +72,79 @@ func (c *CommandClient) grpcDial() (*grpc.ClientConn, error) {
|
||||
}
|
||||
|
||||
func (c *CommandClient) Connect() error {
|
||||
c.clientMutex.Lock()
|
||||
common.Close(common.PtrOrNil(c.grpcConn))
|
||||
|
||||
conn, err := c.grpcDial()
|
||||
common.Close(c.conn)
|
||||
conn, err := c.directConnectWithRetry()
|
||||
if err != nil {
|
||||
c.clientMutex.Unlock()
|
||||
return err
|
||||
}
|
||||
c.grpcConn = conn
|
||||
c.grpcClient = daemon.NewStartedServiceClient(conn)
|
||||
c.ctx, c.cancel = context.WithCancel(context.Background())
|
||||
c.clientMutex.Unlock()
|
||||
|
||||
c.handler.Connected()
|
||||
for _, command := range c.options.commands {
|
||||
switch command {
|
||||
case CommandLog:
|
||||
go c.handleLogStream()
|
||||
case CommandStatus:
|
||||
go c.handleStatusStream()
|
||||
case CommandGroup:
|
||||
go c.handleGroupStream()
|
||||
case CommandClashMode:
|
||||
go c.handleClashModeStream()
|
||||
case CommandConnections:
|
||||
go c.handleConnectionsStream()
|
||||
default:
|
||||
return E.New("unknown command: ", command)
|
||||
c.conn = conn
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(c.options.Command))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch c.options.Command {
|
||||
case CommandLog:
|
||||
err = binary.Write(conn, binary.BigEndian, c.options.StatusInterval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "write interval")
|
||||
}
|
||||
c.handler.Connected()
|
||||
go c.handleLogConn(conn)
|
||||
case CommandStatus:
|
||||
err = binary.Write(conn, binary.BigEndian, c.options.StatusInterval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "write interval")
|
||||
}
|
||||
c.handler.Connected()
|
||||
go c.handleStatusConn(conn)
|
||||
case CommandGroup:
|
||||
err = binary.Write(conn, binary.BigEndian, c.options.StatusInterval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "write interval")
|
||||
}
|
||||
c.handler.Connected()
|
||||
go c.handleGroupConn(conn)
|
||||
case CommandClashMode:
|
||||
var (
|
||||
modeList []string
|
||||
currentMode string
|
||||
)
|
||||
modeList, currentMode, err = readClashModeList(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if sFixAndroidStack {
|
||||
go func() {
|
||||
c.handler.Connected()
|
||||
c.handler.InitializeClashMode(newIterator(modeList), currentMode)
|
||||
if len(modeList) == 0 {
|
||||
conn.Close()
|
||||
c.handler.Disconnected(os.ErrInvalid.Error())
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
c.handler.Connected()
|
||||
c.handler.InitializeClashMode(newIterator(modeList), currentMode)
|
||||
if len(modeList) == 0 {
|
||||
conn.Close()
|
||||
c.handler.Disconnected(os.ErrInvalid.Error())
|
||||
}
|
||||
}
|
||||
if len(modeList) == 0 {
|
||||
return nil
|
||||
}
|
||||
go c.handleModeConn(conn)
|
||||
case CommandConnections:
|
||||
err = binary.Write(conn, binary.BigEndian, c.options.StatusInterval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "write interval")
|
||||
}
|
||||
c.handler.Connected()
|
||||
go c.handleConnectionsConn(conn)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) Disconnect() error {
|
||||
c.clientMutex.Lock()
|
||||
defer c.clientMutex.Unlock()
|
||||
if c.cancel != nil {
|
||||
c.cancel()
|
||||
}
|
||||
return common.Close(common.PtrOrNil(c.grpcConn))
|
||||
}
|
||||
|
||||
func (c *CommandClient) getClientForCall() (daemon.StartedServiceClient, error) {
|
||||
c.clientMutex.RLock()
|
||||
if c.grpcClient != nil {
|
||||
defer c.clientMutex.RUnlock()
|
||||
return c.grpcClient, nil
|
||||
}
|
||||
c.clientMutex.RUnlock()
|
||||
|
||||
c.clientMutex.Lock()
|
||||
defer c.clientMutex.Unlock()
|
||||
|
||||
if c.grpcClient != nil {
|
||||
return c.grpcClient, nil
|
||||
}
|
||||
|
||||
conn, err := c.grpcDial()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.grpcConn = conn
|
||||
c.grpcClient = daemon.NewStartedServiceClient(conn)
|
||||
if c.ctx == nil {
|
||||
c.ctx, c.cancel = context.WithCancel(context.Background())
|
||||
}
|
||||
return c.grpcClient, nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) getStreamContext() (daemon.StartedServiceClient, context.Context) {
|
||||
c.clientMutex.RLock()
|
||||
defer c.clientMutex.RUnlock()
|
||||
return c.grpcClient, c.ctx
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleLogStream() {
|
||||
client, ctx := c.getStreamContext()
|
||||
stream, err := client.SubscribeLog(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
defaultLogLevel, err := client.GetDefaultLogLevel(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.SetDefaultLogLevel(int32(defaultLogLevel.Level))
|
||||
for {
|
||||
logMessage, err := stream.Recv()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
if logMessage.Reset_ {
|
||||
c.handler.ClearLogs()
|
||||
}
|
||||
var messages []*LogEntry
|
||||
for _, msg := range logMessage.Messages {
|
||||
messages = append(messages, &LogEntry{
|
||||
Level: int32(msg.Level),
|
||||
Message: msg.Message,
|
||||
})
|
||||
}
|
||||
c.handler.WriteLogs(newIterator(messages))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleStatusStream() {
|
||||
client, ctx := c.getStreamContext()
|
||||
interval := c.options.StatusInterval
|
||||
|
||||
stream, err := client.SubscribeStatus(ctx, &daemon.SubscribeStatusRequest{
|
||||
Interval: interval,
|
||||
})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
status, err := stream.Recv()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.WriteStatus(StatusMessageFromGRPC(status))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleGroupStream() {
|
||||
client, ctx := c.getStreamContext()
|
||||
|
||||
stream, err := client.SubscribeGroups(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
groups, err := stream.Recv()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.WriteGroups(OutboundGroupIteratorFromGRPC(groups))
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleClashModeStream() {
|
||||
client, ctx := c.getStreamContext()
|
||||
|
||||
modeStatus, err := client.GetClashModeStatus(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if sFixAndroidStack {
|
||||
go func() {
|
||||
c.handler.InitializeClashMode(newIterator(modeStatus.ModeList), modeStatus.CurrentMode)
|
||||
if len(modeStatus.ModeList) == 0 {
|
||||
c.handler.Disconnected(os.ErrInvalid.Error())
|
||||
}
|
||||
}()
|
||||
} else {
|
||||
c.handler.InitializeClashMode(newIterator(modeStatus.ModeList), modeStatus.CurrentMode)
|
||||
if len(modeStatus.ModeList) == 0 {
|
||||
c.handler.Disconnected(os.ErrInvalid.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if len(modeStatus.ModeList) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
stream, err := client.SubscribeClashMode(ctx, &emptypb.Empty{})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
mode, err := stream.Recv()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.UpdateClashMode(mode.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleConnectionsStream() {
|
||||
client, ctx := c.getStreamContext()
|
||||
interval := c.options.StatusInterval
|
||||
|
||||
stream, err := client.SubscribeConnections(ctx, &daemon.SubscribeConnectionsRequest{
|
||||
Interval: interval,
|
||||
})
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
var connections Connections
|
||||
for {
|
||||
conns, err := stream.Recv()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
connections.input = ConnectionsFromGRPC(conns)
|
||||
c.handler.WriteConnections(&connections)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) SelectOutbound(groupTag string, outboundTag string) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SelectOutbound(context.Background(), &daemon.SelectOutboundRequest{
|
||||
GroupTag: groupTag,
|
||||
OutboundTag: outboundTag,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) URLTest(groupTag string) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.URLTest(context.Background(), &daemon.URLTestRequest{
|
||||
OutboundTag: groupTag,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) SetClashMode(newMode string) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SetClashMode(context.Background(), &daemon.ClashMode{
|
||||
Mode: newMode,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) CloseConnection(connId string) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.CloseConnection(context.Background(), &daemon.CloseConnectionRequest{
|
||||
Id: connId,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) CloseConnections() error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.CloseAllConnections(context.Background(), &emptypb.Empty{})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) ServiceReload() error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.ReloadService(context.Background(), &emptypb.Empty{})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) ServiceClose() error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.StopService(context.Background(), &emptypb.Empty{})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) ClearLogs() error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.ClearLogs(context.Background(), &emptypb.Empty{})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) GetSystemProxyStatus() (*SystemProxyStatus, error) {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
status, err := client.GetSystemProxyStatus(context.Background(), &emptypb.Empty{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return SystemProxyStatusFromGRPC(status), nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) SetSystemProxyEnabled(isEnabled bool) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SetSystemProxyEnabled(context.Background(), &daemon.SetSystemProxyEnabledRequest{
|
||||
Enabled: isEnabled,
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *CommandClient) GetDeprecatedNotes() (DeprecatedNoteIterator, error) {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
warnings, err := client.GetDeprecatedWarnings(context.Background(), &emptypb.Empty{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var notes []*DeprecatedNote
|
||||
for _, warning := range warnings.Warnings {
|
||||
notes = append(notes, &DeprecatedNote{
|
||||
Description: warning.Message,
|
||||
MigrationLink: warning.MigrationLink,
|
||||
})
|
||||
}
|
||||
return newIterator(notes), nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) SetGroupExpand(groupTag string, isExpand bool) error {
|
||||
client, err := c.getClientForCall()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = client.SetGroupExpand(context.Background(), &daemon.SetGroupExpandRequest{
|
||||
GroupTag: groupTag,
|
||||
IsExpand: isExpand,
|
||||
})
|
||||
return err
|
||||
return common.Close(c.conn)
|
||||
}
|
||||
|
||||
54
experimental/libbox/command_close_connection.go
Normal file
54
experimental/libbox/command_close_connection.go
Normal file
@@ -0,0 +1,54 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
"github.com/sagernet/sing/common/binary"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
func (c *CommandClient) CloseConnection(connId string) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandCloseConnection))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writer := bufio.NewWriter(conn)
|
||||
err = varbin.Write(writer, binary.BigEndian, connId)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleCloseConnection(conn net.Conn) error {
|
||||
reader := bufio.NewReader(conn)
|
||||
var connId string
|
||||
err := varbin.Read(reader, binary.BigEndian, &connId)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read connection id")
|
||||
}
|
||||
service := s.service
|
||||
if service == nil {
|
||||
return writeError(conn, E.New("service not ready"))
|
||||
}
|
||||
targetConn := service.clashServer.(*clashapi.Server).TrafficManager().Connection(uuid.FromStringOrNil(connId))
|
||||
if targetConn == nil {
|
||||
return writeError(conn, E.New("connection already closed"))
|
||||
}
|
||||
targetConn.Close()
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
269
experimental/libbox/command_connections.go
Normal file
269
experimental/libbox/command_connections.go
Normal file
@@ -0,0 +1,269 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"net"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
|
||||
"github.com/sagernet/sing/common/binary"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
|
||||
"github.com/gofrs/uuid/v5"
|
||||
)
|
||||
|
||||
func (c *CommandClient) handleConnectionsConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
reader := bufio.NewReader(conn)
|
||||
var (
|
||||
rawConnections []Connection
|
||||
connections Connections
|
||||
)
|
||||
for {
|
||||
rawConnections = nil
|
||||
err := varbin.Read(reader, binary.BigEndian, &rawConnections)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
connections.input = rawConnections
|
||||
c.handler.WriteConnections(&connections)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleConnectionsConn(conn net.Conn) error {
|
||||
var interval int64
|
||||
err := binary.Read(conn, binary.BigEndian, &interval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read interval")
|
||||
}
|
||||
ticker := time.NewTicker(time.Duration(interval))
|
||||
defer ticker.Stop()
|
||||
ctx := connKeepAlive(conn)
|
||||
var trafficManager *trafficontrol.Manager
|
||||
for {
|
||||
service := s.service
|
||||
if service != nil {
|
||||
trafficManager = service.clashServer.(*clashapi.Server).TrafficManager()
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
var (
|
||||
connections = make(map[uuid.UUID]*Connection)
|
||||
outConnections []Connection
|
||||
)
|
||||
writer := bufio.NewWriter(conn)
|
||||
for {
|
||||
outConnections = outConnections[:0]
|
||||
for _, connection := range trafficManager.Connections() {
|
||||
outConnections = append(outConnections, newConnection(connections, connection, false))
|
||||
}
|
||||
for _, connection := range trafficManager.ClosedConnections() {
|
||||
outConnections = append(outConnections, newConnection(connections, connection, true))
|
||||
}
|
||||
err = varbin.Write(writer, binary.BigEndian, outConnections)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
ConnectionStateAll = iota
|
||||
ConnectionStateActive
|
||||
ConnectionStateClosed
|
||||
)
|
||||
|
||||
type Connections struct {
|
||||
input []Connection
|
||||
filtered []Connection
|
||||
}
|
||||
|
||||
func (c *Connections) FilterState(state int32) {
|
||||
c.filtered = c.filtered[:0]
|
||||
switch state {
|
||||
case ConnectionStateAll:
|
||||
c.filtered = append(c.filtered, c.input...)
|
||||
case ConnectionStateActive:
|
||||
for _, connection := range c.input {
|
||||
if connection.ClosedAt == 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
}
|
||||
}
|
||||
case ConnectionStateClosed:
|
||||
for _, connection := range c.input {
|
||||
if connection.ClosedAt != 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Connections) SortByDate() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
if x.CreatedAt < y.CreatedAt {
|
||||
return 1
|
||||
} else if x.CreatedAt > y.CreatedAt {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTraffic() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
xTraffic := x.Uplink + x.Downlink
|
||||
yTraffic := y.Uplink + y.Downlink
|
||||
if xTraffic < yTraffic {
|
||||
return 1
|
||||
} else if xTraffic > yTraffic {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTrafficTotal() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
xTraffic := x.UplinkTotal + x.DownlinkTotal
|
||||
yTraffic := y.UplinkTotal + y.DownlinkTotal
|
||||
if xTraffic < yTraffic {
|
||||
return 1
|
||||
} else if xTraffic > yTraffic {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) Iterator() ConnectionIterator {
|
||||
return newPtrIterator(c.filtered)
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
ID string
|
||||
Inbound string
|
||||
InboundType string
|
||||
IPVersion int32
|
||||
Network string
|
||||
Source string
|
||||
Destination string
|
||||
Domain string
|
||||
Protocol string
|
||||
User string
|
||||
FromOutbound string
|
||||
CreatedAt int64
|
||||
ClosedAt int64
|
||||
Uplink int64
|
||||
Downlink int64
|
||||
UplinkTotal int64
|
||||
DownlinkTotal int64
|
||||
Rule string
|
||||
Outbound string
|
||||
OutboundType string
|
||||
ChainList []string
|
||||
}
|
||||
|
||||
func (c *Connection) Chain() StringIterator {
|
||||
return newIterator(c.ChainList)
|
||||
}
|
||||
|
||||
func (c *Connection) DisplayDestination() string {
|
||||
destination := M.ParseSocksaddr(c.Destination)
|
||||
if destination.IsIP() && c.Domain != "" {
|
||||
destination = M.Socksaddr{
|
||||
Fqdn: c.Domain,
|
||||
Port: destination.Port,
|
||||
}
|
||||
return destination.String()
|
||||
}
|
||||
return c.Destination
|
||||
}
|
||||
|
||||
type ConnectionIterator interface {
|
||||
Next() *Connection
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
func newConnection(connections map[uuid.UUID]*Connection, metadata trafficontrol.TrackerMetadata, isClosed bool) Connection {
|
||||
if oldConnection, loaded := connections[metadata.ID]; loaded {
|
||||
if isClosed {
|
||||
if oldConnection.ClosedAt == 0 {
|
||||
oldConnection.Uplink = 0
|
||||
oldConnection.Downlink = 0
|
||||
oldConnection.ClosedAt = metadata.ClosedAt.UnixMilli()
|
||||
}
|
||||
return *oldConnection
|
||||
}
|
||||
lastUplink := oldConnection.UplinkTotal
|
||||
lastDownlink := oldConnection.DownlinkTotal
|
||||
uplinkTotal := metadata.Upload.Load()
|
||||
downlinkTotal := metadata.Download.Load()
|
||||
oldConnection.Uplink = uplinkTotal - lastUplink
|
||||
oldConnection.Downlink = downlinkTotal - lastDownlink
|
||||
oldConnection.UplinkTotal = uplinkTotal
|
||||
oldConnection.DownlinkTotal = downlinkTotal
|
||||
return *oldConnection
|
||||
}
|
||||
var rule string
|
||||
if metadata.Rule != nil {
|
||||
rule = metadata.Rule.String()
|
||||
}
|
||||
uplinkTotal := metadata.Upload.Load()
|
||||
downlinkTotal := metadata.Download.Load()
|
||||
uplink := uplinkTotal
|
||||
downlink := downlinkTotal
|
||||
var closedAt int64
|
||||
if !metadata.ClosedAt.IsZero() {
|
||||
closedAt = metadata.ClosedAt.UnixMilli()
|
||||
uplink = 0
|
||||
downlink = 0
|
||||
}
|
||||
connection := Connection{
|
||||
ID: metadata.ID.String(),
|
||||
Inbound: metadata.Metadata.Inbound,
|
||||
InboundType: metadata.Metadata.InboundType,
|
||||
IPVersion: int32(metadata.Metadata.IPVersion),
|
||||
Network: metadata.Metadata.Network,
|
||||
Source: metadata.Metadata.Source.String(),
|
||||
Destination: metadata.Metadata.Destination.String(),
|
||||
Domain: metadata.Metadata.Domain,
|
||||
Protocol: metadata.Metadata.Protocol,
|
||||
User: metadata.Metadata.User,
|
||||
FromOutbound: metadata.Metadata.Outbound,
|
||||
CreatedAt: metadata.CreatedAt.UnixMilli(),
|
||||
ClosedAt: closedAt,
|
||||
Uplink: uplink,
|
||||
Downlink: downlink,
|
||||
UplinkTotal: uplinkTotal,
|
||||
DownlinkTotal: downlinkTotal,
|
||||
Rule: rule,
|
||||
Outbound: metadata.Outbound,
|
||||
OutboundType: metadata.OutboundType,
|
||||
ChainList: metadata.Chain,
|
||||
}
|
||||
connections[metadata.ID] = &connection
|
||||
return connection
|
||||
}
|
||||
28
experimental/libbox/command_conntrack.go
Normal file
28
experimental/libbox/command_conntrack.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
runtimeDebug "runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/common/conntrack"
|
||||
)
|
||||
|
||||
func (c *CommandClient) CloseConnections() error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
return binary.Write(conn, binary.BigEndian, uint8(CommandCloseConnections))
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleCloseConnections(conn net.Conn) error {
|
||||
conntrack.Close()
|
||||
go func() {
|
||||
time.Sleep(time.Second)
|
||||
runtimeDebug.FreeOSMemory()
|
||||
}()
|
||||
return nil
|
||||
}
|
||||
46
experimental/libbox/command_deprecated_report.go
Normal file
46
experimental/libbox/command_deprecated_report.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
"github.com/sagernet/sing/service"
|
||||
)
|
||||
|
||||
func (c *CommandClient) GetDeprecatedNotes() (DeprecatedNoteIterator, error) {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandGetDeprecatedNotes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = readError(conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var features []deprecated.Note
|
||||
err = varbin.Read(conn, binary.BigEndian, &features)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newIterator(common.Map(features, func(it deprecated.Note) *DeprecatedNote { return (*DeprecatedNote)(&it) })), nil
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleGetDeprecatedNotes(conn net.Conn) error {
|
||||
boxService := s.service
|
||||
if boxService == nil {
|
||||
return writeError(conn, E.New("service not ready"))
|
||||
}
|
||||
err := writeError(conn, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return varbin.Write(conn, binary.BigEndian, service.FromContext[deprecated.Manager](boxService.ctx).(*deprecatedManager).Get())
|
||||
}
|
||||
198
experimental/libbox/command_group.go
Normal file
198
experimental/libbox/command_group.go
Normal file
@@ -0,0 +1,198 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
"github.com/sagernet/sing-box/protocol/group"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
"github.com/sagernet/sing/service"
|
||||
)
|
||||
|
||||
func (c *CommandClient) handleGroupConn(conn net.Conn) {
|
||||
defer conn.Close()
|
||||
|
||||
for {
|
||||
groups, err := readGroups(conn)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.WriteGroups(groups)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleGroupConn(conn net.Conn) error {
|
||||
var interval int64
|
||||
err := binary.Read(conn, binary.BigEndian, &interval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read interval")
|
||||
}
|
||||
ticker := time.NewTicker(time.Duration(interval))
|
||||
defer ticker.Stop()
|
||||
ctx := connKeepAlive(conn)
|
||||
writer := bufio.NewWriter(conn)
|
||||
for {
|
||||
service := s.service
|
||||
if service != nil {
|
||||
err = writeGroups(writer, service)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
err = binary.Write(writer, binary.BigEndian, uint16(0))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-s.urlTestUpdate:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type OutboundGroup struct {
|
||||
Tag string
|
||||
Type string
|
||||
Selectable bool
|
||||
Selected string
|
||||
IsExpand bool
|
||||
ItemList []*OutboundGroupItem
|
||||
}
|
||||
|
||||
func (g *OutboundGroup) GetItems() OutboundGroupItemIterator {
|
||||
return newIterator(g.ItemList)
|
||||
}
|
||||
|
||||
type OutboundGroupIterator interface {
|
||||
Next() *OutboundGroup
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
type OutboundGroupItem struct {
|
||||
Tag string
|
||||
Type string
|
||||
URLTestTime int64
|
||||
URLTestDelay int32
|
||||
}
|
||||
|
||||
type OutboundGroupItemIterator interface {
|
||||
Next() *OutboundGroupItem
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
func readGroups(reader io.Reader) (OutboundGroupIterator, error) {
|
||||
groups, err := varbin.ReadValue[[]*OutboundGroup](reader, binary.BigEndian)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newIterator(groups), nil
|
||||
}
|
||||
|
||||
func writeGroups(writer io.Writer, boxService *BoxService) error {
|
||||
historyStorage := service.PtrFromContext[urltest.HistoryStorage](boxService.ctx)
|
||||
cacheFile := service.FromContext[adapter.CacheFile](boxService.ctx)
|
||||
outbounds := boxService.instance.Outbound().Outbounds()
|
||||
var iGroups []adapter.OutboundGroup
|
||||
for _, it := range outbounds {
|
||||
if group, isGroup := it.(adapter.OutboundGroup); isGroup {
|
||||
iGroups = append(iGroups, group)
|
||||
}
|
||||
}
|
||||
var groups []OutboundGroup
|
||||
for _, iGroup := range iGroups {
|
||||
var outboundGroup OutboundGroup
|
||||
outboundGroup.Tag = iGroup.Tag()
|
||||
outboundGroup.Type = iGroup.Type()
|
||||
_, outboundGroup.Selectable = iGroup.(*group.Selector)
|
||||
outboundGroup.Selected = iGroup.Now()
|
||||
if cacheFile != nil {
|
||||
if isExpand, loaded := cacheFile.LoadGroupExpand(outboundGroup.Tag); loaded {
|
||||
outboundGroup.IsExpand = isExpand
|
||||
}
|
||||
}
|
||||
|
||||
for _, itemTag := range iGroup.All() {
|
||||
itemOutbound, isLoaded := boxService.instance.Outbound().Outbound(itemTag)
|
||||
if !isLoaded {
|
||||
continue
|
||||
}
|
||||
|
||||
var item OutboundGroupItem
|
||||
item.Tag = itemTag
|
||||
item.Type = itemOutbound.Type()
|
||||
if history := historyStorage.LoadURLTestHistory(adapter.OutboundTag(itemOutbound)); history != nil {
|
||||
item.URLTestTime = history.Time.Unix()
|
||||
item.URLTestDelay = int32(history.Delay)
|
||||
}
|
||||
outboundGroup.ItemList = append(outboundGroup.ItemList, &item)
|
||||
}
|
||||
if len(outboundGroup.ItemList) < 2 {
|
||||
continue
|
||||
}
|
||||
groups = append(groups, outboundGroup)
|
||||
}
|
||||
return varbin.Write(writer, binary.BigEndian, groups)
|
||||
}
|
||||
|
||||
func (c *CommandClient) SetGroupExpand(groupTag string, isExpand bool) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandGroupExpand))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(conn, binary.BigEndian, groupTag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = binary.Write(conn, binary.BigEndian, isExpand)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleSetGroupExpand(conn net.Conn) error {
|
||||
groupTag, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var isExpand bool
|
||||
err = binary.Read(conn, binary.BigEndian, &isExpand)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serviceNow := s.service
|
||||
if serviceNow == nil {
|
||||
return writeError(conn, E.New("service not ready"))
|
||||
}
|
||||
cacheFile := service.FromContext[adapter.CacheFile](serviceNow.ctx)
|
||||
if cacheFile != nil {
|
||||
err = cacheFile.StoreGroupExpand(groupTag, isExpand)
|
||||
if err != nil {
|
||||
return writeError(conn, err)
|
||||
}
|
||||
}
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
160
experimental/libbox/command_log.go
Normal file
160
experimental/libbox/command_log.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing/common/binary"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
func (s *CommandServer) ResetLog() {
|
||||
s.access.Lock()
|
||||
defer s.access.Unlock()
|
||||
s.savedLines.Init()
|
||||
select {
|
||||
case s.logReset <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) WriteMessage(message string) {
|
||||
s.subscriber.Emit(message)
|
||||
s.access.Lock()
|
||||
s.savedLines.PushBack(message)
|
||||
if s.savedLines.Len() > s.maxLines {
|
||||
s.savedLines.Remove(s.savedLines.Front())
|
||||
}
|
||||
s.access.Unlock()
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleLogConn(conn net.Conn) error {
|
||||
var (
|
||||
interval int64
|
||||
timer *time.Timer
|
||||
)
|
||||
err := binary.Read(conn, binary.BigEndian, &interval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read interval")
|
||||
}
|
||||
timer = time.NewTimer(time.Duration(interval))
|
||||
if !timer.Stop() {
|
||||
<-timer.C
|
||||
}
|
||||
var savedLines []string
|
||||
s.access.Lock()
|
||||
savedLines = make([]string, 0, s.savedLines.Len())
|
||||
for element := s.savedLines.Front(); element != nil; element = element.Next() {
|
||||
savedLines = append(savedLines, element.Value)
|
||||
}
|
||||
s.access.Unlock()
|
||||
subscription, done, err := s.observer.Subscribe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer s.observer.UnSubscribe(subscription)
|
||||
writer := bufio.NewWriter(conn)
|
||||
select {
|
||||
case <-s.logReset:
|
||||
err = writer.WriteByte(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
}
|
||||
if len(savedLines) > 0 {
|
||||
err = writer.WriteByte(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(writer, binary.BigEndian, savedLines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ctx := connKeepAlive(conn)
|
||||
var logLines []string
|
||||
for {
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-s.logReset:
|
||||
err = writer.WriteByte(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case <-done:
|
||||
return nil
|
||||
case logLine := <-subscription:
|
||||
logLines = logLines[:0]
|
||||
logLines = append(logLines, logLine)
|
||||
timer.Reset(time.Duration(interval))
|
||||
loopLogs:
|
||||
for {
|
||||
select {
|
||||
case logLine = <-subscription:
|
||||
logLines = append(logLines, logLine)
|
||||
case <-timer.C:
|
||||
break loopLogs
|
||||
}
|
||||
}
|
||||
err = writer.WriteByte(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(writer, binary.BigEndian, logLines)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleLogConn(conn net.Conn) {
|
||||
reader := bufio.NewReader(conn)
|
||||
for {
|
||||
messageType, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
var messages []string
|
||||
switch messageType {
|
||||
case 0:
|
||||
err = varbin.Read(reader, binary.BigEndian, &messages)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.WriteLogs(newIterator(messages))
|
||||
case 1:
|
||||
c.handler.ClearLogs()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func connKeepAlive(reader io.Reader) context.Context {
|
||||
ctx, cancel := context.WithCancelCause(context.Background())
|
||||
go func() {
|
||||
for {
|
||||
_, err := reader.Read(make([]byte, 1))
|
||||
if err != nil {
|
||||
cancel(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
return ctx
|
||||
}
|
||||
59
experimental/libbox/command_power.go
Normal file
59
experimental/libbox/command_power.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
func (c *CommandClient) ServiceReload() error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandServiceReload))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleServiceReload(conn net.Conn) error {
|
||||
rErr := s.handler.ServiceReload()
|
||||
err := binary.Write(conn, binary.BigEndian, rErr != nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rErr != nil {
|
||||
return varbin.Write(conn, binary.BigEndian, rErr.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) ServiceClose() error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandServiceClose))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleServiceClose(conn net.Conn) error {
|
||||
rErr := s.service.Close()
|
||||
s.handler.PostServiceClose()
|
||||
err := binary.Write(conn, binary.BigEndian, rErr != nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if rErr != nil {
|
||||
return varbin.Write(conn, binary.BigEndian, rErr.Error())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
58
experimental/libbox/command_select.go
Normal file
58
experimental/libbox/command_select.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
|
||||
"github.com/sagernet/sing-box/protocol/group"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
func (c *CommandClient) SelectOutbound(groupTag string, outboundTag string) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandSelectOutbound))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(conn, binary.BigEndian, groupTag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(conn, binary.BigEndian, outboundTag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleSelectOutbound(conn net.Conn) error {
|
||||
groupTag, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
outboundTag, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service := s.service
|
||||
if service == nil {
|
||||
return writeError(conn, E.New("service not ready"))
|
||||
}
|
||||
outboundGroup, isLoaded := service.instance.Outbound().Outbound(groupTag)
|
||||
if !isLoaded {
|
||||
return writeError(conn, E.New("selector not found: ", groupTag))
|
||||
}
|
||||
selector, isSelector := outboundGroup.(*group.Selector)
|
||||
if !isSelector {
|
||||
return writeError(conn, E.New("outbound is not a selector: ", groupTag))
|
||||
}
|
||||
if !selector.SelectOutbound(outboundTag) {
|
||||
return writeError(conn, E.New("outbound not found in selector: ", outboundTag))
|
||||
}
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
@@ -1,266 +1,182 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"time"
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/debug"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/observable"
|
||||
"github.com/sagernet/sing/common/x/list"
|
||||
"github.com/sagernet/sing/service"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type CommandServer struct {
|
||||
*daemon.StartedService
|
||||
handler CommandServerHandler
|
||||
platformInterface PlatformInterface
|
||||
platformWrapper *platformInterfaceWrapper
|
||||
grpcServer *grpc.Server
|
||||
listener net.Listener
|
||||
endPauseTimer *time.Timer
|
||||
listener net.Listener
|
||||
handler CommandServerHandler
|
||||
|
||||
access sync.Mutex
|
||||
savedLines list.List[string]
|
||||
maxLines int
|
||||
subscriber *observable.Subscriber[string]
|
||||
observer *observable.Observer[string]
|
||||
service *BoxService
|
||||
|
||||
// These channels only work with a single client. if multi-client support is needed, replace with Subscriber/Observer
|
||||
urlTestUpdate chan struct{}
|
||||
modeUpdate chan struct{}
|
||||
logReset chan struct{}
|
||||
|
||||
closedConnections []Connection
|
||||
}
|
||||
|
||||
type CommandServerHandler interface {
|
||||
ServiceStop() error
|
||||
ServiceReload() error
|
||||
GetSystemProxyStatus() (*SystemProxyStatus, error)
|
||||
SetSystemProxyEnabled(enabled bool) error
|
||||
WriteDebugMessage(message string)
|
||||
PostServiceClose()
|
||||
GetSystemProxyStatus() *SystemProxyStatus
|
||||
SetSystemProxyEnabled(isEnabled bool) error
|
||||
}
|
||||
|
||||
func NewCommandServer(handler CommandServerHandler, platformInterface PlatformInterface) (*CommandServer, error) {
|
||||
ctx := BaseContext(platformInterface)
|
||||
platformWrapper := &platformInterfaceWrapper{
|
||||
iif: platformInterface,
|
||||
useProcFS: platformInterface.UseProcFS(),
|
||||
}
|
||||
service.MustRegister[adapter.PlatformInterface](ctx, platformWrapper)
|
||||
func NewCommandServer(handler CommandServerHandler, maxLines int32) *CommandServer {
|
||||
server := &CommandServer{
|
||||
handler: handler,
|
||||
platformInterface: platformInterface,
|
||||
platformWrapper: platformWrapper,
|
||||
handler: handler,
|
||||
maxLines: int(maxLines),
|
||||
subscriber: observable.NewSubscriber[string](128),
|
||||
urlTestUpdate: make(chan struct{}, 1),
|
||||
modeUpdate: make(chan struct{}, 1),
|
||||
logReset: make(chan struct{}, 1),
|
||||
}
|
||||
server.StartedService = daemon.NewStartedService(daemon.ServiceOptions{
|
||||
Context: ctx,
|
||||
// Platform: platformWrapper,
|
||||
Handler: (*platformHandler)(server),
|
||||
Debug: sDebug,
|
||||
LogMaxLines: sLogMaxLines,
|
||||
// WorkingDirectory: sWorkingPath,
|
||||
// TempDirectory: sTempPath,
|
||||
// UserID: sUserID,
|
||||
// GroupID: sGroupID,
|
||||
// SystemProxyEnabled: false,
|
||||
})
|
||||
return server, nil
|
||||
server.observer = observable.NewObserver[string](server.subscriber, 64)
|
||||
return server
|
||||
}
|
||||
|
||||
func unaryAuthInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {
|
||||
if sCommandServerSecret == "" {
|
||||
return handler(ctx, req)
|
||||
func (s *CommandServer) SetService(newService *BoxService) {
|
||||
if newService != nil {
|
||||
service.PtrFromContext[urltest.HistoryStorage](newService.ctx).SetHook(s.urlTestUpdate)
|
||||
newService.clashServer.(*clashapi.Server).SetModeUpdateHook(s.modeUpdate)
|
||||
}
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing metadata")
|
||||
}
|
||||
values := md.Get("x-command-secret")
|
||||
if len(values) == 0 {
|
||||
return nil, status.Error(codes.Unauthenticated, "missing authentication secret")
|
||||
}
|
||||
if values[0] != sCommandServerSecret {
|
||||
return nil, status.Error(codes.Unauthenticated, "invalid authentication secret")
|
||||
}
|
||||
return handler(ctx, req)
|
||||
s.service = newService
|
||||
s.notifyURLTestUpdate()
|
||||
}
|
||||
|
||||
func streamAuthInterceptor(srv any, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
|
||||
if sCommandServerSecret == "" {
|
||||
return handler(srv, ss)
|
||||
func (s *CommandServer) notifyURLTestUpdate() {
|
||||
select {
|
||||
case s.urlTestUpdate <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
md, ok := metadata.FromIncomingContext(ss.Context())
|
||||
if !ok {
|
||||
return status.Error(codes.Unauthenticated, "missing metadata")
|
||||
}
|
||||
values := md.Get("x-command-secret")
|
||||
if len(values) == 0 {
|
||||
return status.Error(codes.Unauthenticated, "missing authentication secret")
|
||||
}
|
||||
if values[0] != sCommandServerSecret {
|
||||
return status.Error(codes.Unauthenticated, "invalid authentication secret")
|
||||
}
|
||||
return handler(srv, ss)
|
||||
}
|
||||
|
||||
func (s *CommandServer) Start() error {
|
||||
var (
|
||||
listener net.Listener
|
||||
err error
|
||||
)
|
||||
if sCommandServerListenPort == 0 {
|
||||
sockPath := filepath.Join(sBasePath, "command.sock")
|
||||
os.Remove(sockPath)
|
||||
for i := 0; i < 30; i++ {
|
||||
listener, err = net.ListenUnix("unix", &net.UnixAddr{
|
||||
Name: sockPath,
|
||||
Net: "unix",
|
||||
})
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
if !errors.Is(err, syscall.EROFS) {
|
||||
break
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
if err != nil {
|
||||
return E.Cause(err, "listen command server")
|
||||
}
|
||||
if sUserID != os.Getuid() {
|
||||
err = os.Chown(sockPath, sUserID, sGroupID)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
os.Remove(sockPath)
|
||||
return E.Cause(err, "chown")
|
||||
}
|
||||
}
|
||||
if !sTVOS {
|
||||
return s.listenUNIX()
|
||||
} else {
|
||||
listener, err = net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(sCommandServerListenPort))))
|
||||
if err != nil {
|
||||
return E.Cause(err, "listen command server")
|
||||
}
|
||||
return s.listenTCP()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) listenUNIX() error {
|
||||
sockPath := filepath.Join(sBasePath, "command.sock")
|
||||
os.Remove(sockPath)
|
||||
listener, err := net.ListenUnix("unix", &net.UnixAddr{
|
||||
Name: sockPath,
|
||||
Net: "unix",
|
||||
})
|
||||
if err != nil {
|
||||
return E.Cause(err, "listen ", sockPath)
|
||||
}
|
||||
err = os.Chown(sockPath, sUserID, sGroupID)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
os.Remove(sockPath)
|
||||
return E.Cause(err, "chown")
|
||||
}
|
||||
s.listener = listener
|
||||
serverOptions := []grpc.ServerOption{
|
||||
grpc.UnaryInterceptor(unaryAuthInterceptor),
|
||||
grpc.StreamInterceptor(streamAuthInterceptor),
|
||||
}
|
||||
s.grpcServer = grpc.NewServer(serverOptions...)
|
||||
daemon.RegisterStartedServiceServer(s.grpcServer, s.StartedService)
|
||||
go s.grpcServer.Serve(listener)
|
||||
go s.loopConnection(listener)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CommandServer) Close() {
|
||||
if s.grpcServer != nil {
|
||||
s.grpcServer.Stop()
|
||||
}
|
||||
common.Close(s.listener)
|
||||
}
|
||||
|
||||
type OverrideOptions struct {
|
||||
AutoRedirect bool
|
||||
IncludePackage StringIterator
|
||||
ExcludePackage StringIterator
|
||||
}
|
||||
|
||||
func (s *CommandServer) StartOrReloadService(configContent string, options *OverrideOptions) error {
|
||||
return s.StartedService.StartOrReloadService(configContent, &daemon.OverrideOptions{
|
||||
AutoRedirect: options.AutoRedirect,
|
||||
IncludePackage: iteratorToArray(options.IncludePackage),
|
||||
ExcludePackage: iteratorToArray(options.ExcludePackage),
|
||||
})
|
||||
}
|
||||
|
||||
func (s *CommandServer) CloseService() error {
|
||||
return s.StartedService.CloseService()
|
||||
}
|
||||
|
||||
func (s *CommandServer) WriteMessage(level int32, message string) {
|
||||
s.StartedService.WriteMessage(log.Level(level), message)
|
||||
}
|
||||
|
||||
func (s *CommandServer) SetError(message string) {
|
||||
s.StartedService.SetError(E.New(message))
|
||||
}
|
||||
|
||||
func (s *CommandServer) NeedWIFIState() bool {
|
||||
instance := s.StartedService.Instance()
|
||||
if instance == nil || instance.Box() == nil {
|
||||
return false
|
||||
}
|
||||
return instance.Box().Network().NeedWIFIState()
|
||||
}
|
||||
|
||||
func (s *CommandServer) Pause() {
|
||||
instance := s.StartedService.Instance()
|
||||
if instance == nil || instance.PauseManager() == nil {
|
||||
return
|
||||
}
|
||||
instance.PauseManager().DevicePause()
|
||||
if C.IsIos {
|
||||
if s.endPauseTimer == nil {
|
||||
s.endPauseTimer = time.AfterFunc(time.Minute, instance.PauseManager().DeviceWake)
|
||||
} else {
|
||||
s.endPauseTimer.Reset(time.Minute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) Wake() {
|
||||
instance := s.StartedService.Instance()
|
||||
if instance == nil || instance.PauseManager() == nil {
|
||||
return
|
||||
}
|
||||
if !C.IsIos {
|
||||
instance.PauseManager().DeviceWake()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) ResetNetwork() {
|
||||
instance := s.StartedService.Instance()
|
||||
if instance == nil || instance.Box() == nil {
|
||||
return
|
||||
}
|
||||
instance.Box().Router().ResetNetwork()
|
||||
}
|
||||
|
||||
func (s *CommandServer) UpdateWIFIState() {
|
||||
instance := s.StartedService.Instance()
|
||||
if instance == nil || instance.Box() == nil {
|
||||
return
|
||||
}
|
||||
instance.Box().Network().UpdateWIFIState()
|
||||
}
|
||||
|
||||
type platformHandler CommandServer
|
||||
|
||||
func (h *platformHandler) ServiceStop() error {
|
||||
return (*CommandServer)(h).handler.ServiceStop()
|
||||
}
|
||||
|
||||
func (h *platformHandler) ServiceReload() error {
|
||||
return (*CommandServer)(h).handler.ServiceReload()
|
||||
}
|
||||
|
||||
func (h *platformHandler) SystemProxyStatus() (*daemon.SystemProxyStatus, error) {
|
||||
status, err := (*CommandServer)(h).handler.GetSystemProxyStatus()
|
||||
func (s *CommandServer) listenTCP() error {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:8964")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return E.Cause(err, "listen")
|
||||
}
|
||||
return &daemon.SystemProxyStatus{
|
||||
Enabled: status.Enabled,
|
||||
Available: status.Available,
|
||||
}, nil
|
||||
s.listener = listener
|
||||
go s.loopConnection(listener)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *platformHandler) SetSystemProxyEnabled(enabled bool) error {
|
||||
return (*CommandServer)(h).handler.SetSystemProxyEnabled(enabled)
|
||||
func (s *CommandServer) Close() error {
|
||||
return common.Close(
|
||||
s.listener,
|
||||
s.observer,
|
||||
)
|
||||
}
|
||||
|
||||
func (h *platformHandler) WriteDebugMessage(message string) {
|
||||
(*CommandServer)(h).handler.WriteDebugMessage(message)
|
||||
func (s *CommandServer) loopConnection(listener net.Listener) {
|
||||
for {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go func() {
|
||||
hErr := s.handleConnection(conn)
|
||||
if hErr != nil && !E.IsClosed(err) {
|
||||
if debug.Enabled {
|
||||
log.Warn("log-server: process connection: ", hErr)
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleConnection(conn net.Conn) error {
|
||||
defer conn.Close()
|
||||
var command uint8
|
||||
err := binary.Read(conn, binary.BigEndian, &command)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read command")
|
||||
}
|
||||
switch int32(command) {
|
||||
case CommandLog:
|
||||
return s.handleLogConn(conn)
|
||||
case CommandStatus:
|
||||
return s.handleStatusConn(conn)
|
||||
case CommandServiceReload:
|
||||
return s.handleServiceReload(conn)
|
||||
case CommandServiceClose:
|
||||
return s.handleServiceClose(conn)
|
||||
case CommandCloseConnections:
|
||||
return s.handleCloseConnections(conn)
|
||||
case CommandGroup:
|
||||
return s.handleGroupConn(conn)
|
||||
case CommandSelectOutbound:
|
||||
return s.handleSelectOutbound(conn)
|
||||
case CommandURLTest:
|
||||
return s.handleURLTest(conn)
|
||||
case CommandGroupExpand:
|
||||
return s.handleSetGroupExpand(conn)
|
||||
case CommandClashMode:
|
||||
return s.handleModeConn(conn)
|
||||
case CommandSetClashMode:
|
||||
return s.handleSetClashMode(conn)
|
||||
case CommandGetSystemProxyStatus:
|
||||
return s.handleGetSystemProxyStatus(conn)
|
||||
case CommandSetSystemProxyEnabled:
|
||||
return s.handleSetSystemProxyEnabled(conn)
|
||||
case CommandConnections:
|
||||
return s.handleConnectionsConn(conn)
|
||||
case CommandCloseConnection:
|
||||
return s.handleCloseConnection(conn)
|
||||
case CommandGetDeprecatedNotes:
|
||||
return s.handleGetDeprecatedNotes(conn)
|
||||
default:
|
||||
return E.New("unknown command: ", command)
|
||||
}
|
||||
}
|
||||
|
||||
39
experimental/libbox/command_shared.go
Normal file
39
experimental/libbox/command_shared.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
)
|
||||
|
||||
func readError(reader io.Reader) error {
|
||||
var hasError bool
|
||||
err := binary.Read(reader, binary.BigEndian, &hasError)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if hasError {
|
||||
errorMessage, err := varbin.ReadValue[string](reader, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return E.New(errorMessage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeError(writer io.Writer, wErr error) error {
|
||||
err := binary.Write(writer, binary.BigEndian, wErr != nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wErr != nil {
|
||||
err = varbin.Write(writer, binary.BigEndian, wErr.Error())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
85
experimental/libbox/command_status.go
Normal file
85
experimental/libbox/command_status.go
Normal file
@@ -0,0 +1,85 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/common/conntrack"
|
||||
"github.com/sagernet/sing-box/experimental/clashapi"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/memory"
|
||||
)
|
||||
|
||||
type StatusMessage struct {
|
||||
Memory int64
|
||||
Goroutines int32
|
||||
ConnectionsIn int32
|
||||
ConnectionsOut int32
|
||||
TrafficAvailable bool
|
||||
Uplink int64
|
||||
Downlink int64
|
||||
UplinkTotal int64
|
||||
DownlinkTotal int64
|
||||
}
|
||||
|
||||
func (s *CommandServer) readStatus() StatusMessage {
|
||||
var message StatusMessage
|
||||
message.Memory = int64(memory.Inuse())
|
||||
message.Goroutines = int32(runtime.NumGoroutine())
|
||||
message.ConnectionsOut = int32(conntrack.Count())
|
||||
|
||||
if s.service != nil {
|
||||
message.TrafficAvailable = true
|
||||
trafficManager := s.service.clashServer.(*clashapi.Server).TrafficManager()
|
||||
message.UplinkTotal, message.DownlinkTotal = trafficManager.Total()
|
||||
message.ConnectionsIn = int32(trafficManager.ConnectionsLen())
|
||||
}
|
||||
|
||||
return message
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleStatusConn(conn net.Conn) error {
|
||||
var interval int64
|
||||
err := binary.Read(conn, binary.BigEndian, &interval)
|
||||
if err != nil {
|
||||
return E.Cause(err, "read interval")
|
||||
}
|
||||
ticker := time.NewTicker(time.Duration(interval))
|
||||
defer ticker.Stop()
|
||||
ctx := connKeepAlive(conn)
|
||||
status := s.readStatus()
|
||||
uploadTotal := status.UplinkTotal
|
||||
downloadTotal := status.DownlinkTotal
|
||||
for {
|
||||
err = binary.Write(conn, binary.BigEndian, status)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-ticker.C:
|
||||
}
|
||||
status = s.readStatus()
|
||||
upload := status.UplinkTotal - uploadTotal
|
||||
download := status.DownlinkTotal - downloadTotal
|
||||
uploadTotal = status.UplinkTotal
|
||||
downloadTotal = status.DownlinkTotal
|
||||
status.Uplink = upload
|
||||
status.Downlink = download
|
||||
}
|
||||
}
|
||||
|
||||
func (c *CommandClient) handleStatusConn(conn net.Conn) {
|
||||
for {
|
||||
var message StatusMessage
|
||||
err := binary.Read(conn, binary.BigEndian, &message)
|
||||
if err != nil {
|
||||
c.handler.Disconnected(err.Error())
|
||||
return
|
||||
}
|
||||
c.handler.WriteStatus(&message)
|
||||
}
|
||||
}
|
||||
80
experimental/libbox/command_system_proxy.go
Normal file
80
experimental/libbox/command_system_proxy.go
Normal file
@@ -0,0 +1,80 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
)
|
||||
|
||||
type SystemProxyStatus struct {
|
||||
Available bool
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
func (c *CommandClient) GetSystemProxyStatus() (*SystemProxyStatus, error) {
|
||||
conn, err := c.directConnectWithRetry()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandGetSystemProxyStatus))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var status SystemProxyStatus
|
||||
err = binary.Read(conn, binary.BigEndian, &status.Available)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if status.Available {
|
||||
err = binary.Read(conn, binary.BigEndian, &status.Enabled)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleGetSystemProxyStatus(conn net.Conn) error {
|
||||
status := s.handler.GetSystemProxyStatus()
|
||||
err := binary.Write(conn, binary.BigEndian, status.Available)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if status.Available {
|
||||
err = binary.Write(conn, binary.BigEndian, status.Enabled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *CommandClient) SetSystemProxyEnabled(isEnabled bool) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandSetSystemProxyEnabled))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = binary.Write(conn, binary.BigEndian, isEnabled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleSetSystemProxyEnabled(conn net.Conn) error {
|
||||
var isEnabled bool
|
||||
err := binary.Read(conn, binary.BigEndian, &isEnabled)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.handler.SetSystemProxyEnabled(isEnabled)
|
||||
if err != nil {
|
||||
return writeError(conn, err)
|
||||
}
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
@@ -1,276 +0,0 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/sagernet/sing-box/daemon"
|
||||
M "github.com/sagernet/sing/common/metadata"
|
||||
)
|
||||
|
||||
type StatusMessage struct {
|
||||
Memory int64
|
||||
Goroutines int32
|
||||
ConnectionsIn int32
|
||||
ConnectionsOut int32
|
||||
TrafficAvailable bool
|
||||
Uplink int64
|
||||
Downlink int64
|
||||
UplinkTotal int64
|
||||
DownlinkTotal int64
|
||||
}
|
||||
|
||||
type SystemProxyStatus struct {
|
||||
Available bool
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
type OutboundGroup struct {
|
||||
Tag string
|
||||
Type string
|
||||
Selectable bool
|
||||
Selected string
|
||||
IsExpand bool
|
||||
ItemList []*OutboundGroupItem
|
||||
}
|
||||
|
||||
func (g *OutboundGroup) GetItems() OutboundGroupItemIterator {
|
||||
return newIterator(g.ItemList)
|
||||
}
|
||||
|
||||
type OutboundGroupIterator interface {
|
||||
Next() *OutboundGroup
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
type OutboundGroupItem struct {
|
||||
Tag string
|
||||
Type string
|
||||
URLTestTime int64
|
||||
URLTestDelay int32
|
||||
}
|
||||
|
||||
type OutboundGroupItemIterator interface {
|
||||
Next() *OutboundGroupItem
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
const (
|
||||
ConnectionStateAll = iota
|
||||
ConnectionStateActive
|
||||
ConnectionStateClosed
|
||||
)
|
||||
|
||||
type Connections struct {
|
||||
input []Connection
|
||||
filtered []Connection
|
||||
}
|
||||
|
||||
func (c *Connections) FilterState(state int32) {
|
||||
c.filtered = c.filtered[:0]
|
||||
switch state {
|
||||
case ConnectionStateAll:
|
||||
c.filtered = append(c.filtered, c.input...)
|
||||
case ConnectionStateActive:
|
||||
for _, connection := range c.input {
|
||||
if connection.ClosedAt == 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
}
|
||||
}
|
||||
case ConnectionStateClosed:
|
||||
for _, connection := range c.input {
|
||||
if connection.ClosedAt != 0 {
|
||||
c.filtered = append(c.filtered, connection)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Connections) SortByDate() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
if x.CreatedAt < y.CreatedAt {
|
||||
return 1
|
||||
} else if x.CreatedAt > y.CreatedAt {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTraffic() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
xTraffic := x.Uplink + x.Downlink
|
||||
yTraffic := y.Uplink + y.Downlink
|
||||
if xTraffic < yTraffic {
|
||||
return 1
|
||||
} else if xTraffic > yTraffic {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) SortByTrafficTotal() {
|
||||
slices.SortStableFunc(c.filtered, func(x, y Connection) int {
|
||||
xTraffic := x.UplinkTotal + x.DownlinkTotal
|
||||
yTraffic := y.UplinkTotal + y.DownlinkTotal
|
||||
if xTraffic < yTraffic {
|
||||
return 1
|
||||
} else if xTraffic > yTraffic {
|
||||
return -1
|
||||
} else {
|
||||
return strings.Compare(y.ID, x.ID)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Connections) Iterator() ConnectionIterator {
|
||||
return newPtrIterator(c.filtered)
|
||||
}
|
||||
|
||||
type Connection struct {
|
||||
ID string
|
||||
Inbound string
|
||||
InboundType string
|
||||
IPVersion int32
|
||||
Network string
|
||||
Source string
|
||||
Destination string
|
||||
Domain string
|
||||
Protocol string
|
||||
User string
|
||||
FromOutbound string
|
||||
CreatedAt int64
|
||||
ClosedAt int64
|
||||
Uplink int64
|
||||
Downlink int64
|
||||
UplinkTotal int64
|
||||
DownlinkTotal int64
|
||||
Rule string
|
||||
Outbound string
|
||||
OutboundType string
|
||||
ChainList []string
|
||||
}
|
||||
|
||||
func (c *Connection) Chain() StringIterator {
|
||||
return newIterator(c.ChainList)
|
||||
}
|
||||
|
||||
func (c *Connection) DisplayDestination() string {
|
||||
destination := M.ParseSocksaddr(c.Destination)
|
||||
if destination.IsIP() && c.Domain != "" {
|
||||
destination = M.Socksaddr{
|
||||
Fqdn: c.Domain,
|
||||
Port: destination.Port,
|
||||
}
|
||||
return destination.String()
|
||||
}
|
||||
return c.Destination
|
||||
}
|
||||
|
||||
type ConnectionIterator interface {
|
||||
Next() *Connection
|
||||
HasNext() bool
|
||||
}
|
||||
|
||||
func StatusMessageFromGRPC(status *daemon.Status) *StatusMessage {
|
||||
if status == nil {
|
||||
return nil
|
||||
}
|
||||
return &StatusMessage{
|
||||
Memory: int64(status.Memory),
|
||||
Goroutines: status.Goroutines,
|
||||
ConnectionsIn: status.ConnectionsIn,
|
||||
ConnectionsOut: status.ConnectionsOut,
|
||||
TrafficAvailable: status.TrafficAvailable,
|
||||
Uplink: status.Uplink,
|
||||
Downlink: status.Downlink,
|
||||
UplinkTotal: status.UplinkTotal,
|
||||
DownlinkTotal: status.DownlinkTotal,
|
||||
}
|
||||
}
|
||||
|
||||
func OutboundGroupIteratorFromGRPC(groups *daemon.Groups) OutboundGroupIterator {
|
||||
if groups == nil || len(groups.Group) == 0 {
|
||||
return newIterator([]*OutboundGroup{})
|
||||
}
|
||||
var libboxGroups []*OutboundGroup
|
||||
for _, g := range groups.Group {
|
||||
libboxGroup := &OutboundGroup{
|
||||
Tag: g.Tag,
|
||||
Type: g.Type,
|
||||
Selectable: g.Selectable,
|
||||
Selected: g.Selected,
|
||||
IsExpand: g.IsExpand,
|
||||
}
|
||||
for _, item := range g.Items {
|
||||
libboxGroup.ItemList = append(libboxGroup.ItemList, &OutboundGroupItem{
|
||||
Tag: item.Tag,
|
||||
Type: item.Type,
|
||||
URLTestTime: item.UrlTestTime,
|
||||
URLTestDelay: item.UrlTestDelay,
|
||||
})
|
||||
}
|
||||
libboxGroups = append(libboxGroups, libboxGroup)
|
||||
}
|
||||
return newIterator(libboxGroups)
|
||||
}
|
||||
|
||||
func ConnectionFromGRPC(conn *daemon.Connection) Connection {
|
||||
return Connection{
|
||||
ID: conn.Id,
|
||||
Inbound: conn.Inbound,
|
||||
InboundType: conn.InboundType,
|
||||
IPVersion: conn.IpVersion,
|
||||
Network: conn.Network,
|
||||
Source: conn.Source,
|
||||
Destination: conn.Destination,
|
||||
Domain: conn.Domain,
|
||||
Protocol: conn.Protocol,
|
||||
User: conn.User,
|
||||
FromOutbound: conn.FromOutbound,
|
||||
CreatedAt: conn.CreatedAt,
|
||||
ClosedAt: conn.ClosedAt,
|
||||
Uplink: conn.Uplink,
|
||||
Downlink: conn.Downlink,
|
||||
UplinkTotal: conn.UplinkTotal,
|
||||
DownlinkTotal: conn.DownlinkTotal,
|
||||
Rule: conn.Rule,
|
||||
Outbound: conn.Outbound,
|
||||
OutboundType: conn.OutboundType,
|
||||
ChainList: conn.ChainList,
|
||||
}
|
||||
}
|
||||
|
||||
func ConnectionsFromGRPC(connections *daemon.Connections) []Connection {
|
||||
if connections == nil || len(connections.Connections) == 0 {
|
||||
return nil
|
||||
}
|
||||
var libboxConnections []Connection
|
||||
for _, conn := range connections.Connections {
|
||||
libboxConnections = append(libboxConnections, ConnectionFromGRPC(conn))
|
||||
}
|
||||
return libboxConnections
|
||||
}
|
||||
|
||||
func SystemProxyStatusFromGRPC(status *daemon.SystemProxyStatus) *SystemProxyStatus {
|
||||
if status == nil {
|
||||
return nil
|
||||
}
|
||||
return &SystemProxyStatus{
|
||||
Available: status.Available,
|
||||
Enabled: status.Enabled,
|
||||
}
|
||||
}
|
||||
|
||||
func SystemProxyStatusToGRPC(status *SystemProxyStatus) *daemon.SystemProxyStatus {
|
||||
if status == nil {
|
||||
return nil
|
||||
}
|
||||
return &daemon.SystemProxyStatus{
|
||||
Available: status.Available,
|
||||
Enabled: status.Enabled,
|
||||
}
|
||||
}
|
||||
86
experimental/libbox/command_urltest.go
Normal file
86
experimental/libbox/command_urltest.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
"github.com/sagernet/sing-box/protocol/group"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/batch"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/varbin"
|
||||
"github.com/sagernet/sing/service"
|
||||
)
|
||||
|
||||
func (c *CommandClient) URLTest(groupTag string) error {
|
||||
conn, err := c.directConnect()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
err = binary.Write(conn, binary.BigEndian, uint8(CommandURLTest))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = varbin.Write(conn, binary.BigEndian, groupTag)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return readError(conn)
|
||||
}
|
||||
|
||||
func (s *CommandServer) handleURLTest(conn net.Conn) error {
|
||||
groupTag, err := varbin.ReadValue[string](conn, binary.BigEndian)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serviceNow := s.service
|
||||
if serviceNow == nil {
|
||||
return nil
|
||||
}
|
||||
abstractOutboundGroup, isLoaded := serviceNow.instance.Outbound().Outbound(groupTag)
|
||||
if !isLoaded {
|
||||
return writeError(conn, E.New("outbound group not found: ", groupTag))
|
||||
}
|
||||
outboundGroup, isOutboundGroup := abstractOutboundGroup.(adapter.OutboundGroup)
|
||||
if !isOutboundGroup {
|
||||
return writeError(conn, E.New("outbound is not a group: ", groupTag))
|
||||
}
|
||||
urlTest, isURLTest := abstractOutboundGroup.(*group.URLTest)
|
||||
if isURLTest {
|
||||
go urlTest.CheckOutbounds()
|
||||
} else {
|
||||
historyStorage := service.PtrFromContext[urltest.HistoryStorage](serviceNow.ctx)
|
||||
outbounds := common.Filter(common.Map(outboundGroup.All(), func(it string) adapter.Outbound {
|
||||
itOutbound, _ := serviceNow.instance.Outbound().Outbound(it)
|
||||
return itOutbound
|
||||
}), func(it adapter.Outbound) bool {
|
||||
if it == nil {
|
||||
return false
|
||||
}
|
||||
_, isGroup := it.(adapter.OutboundGroup)
|
||||
return !isGroup
|
||||
})
|
||||
b, _ := batch.New(serviceNow.ctx, batch.WithConcurrencyNum[any](10))
|
||||
for _, detour := range outbounds {
|
||||
outboundToTest := detour
|
||||
outboundTag := outboundToTest.Tag()
|
||||
b.Go(outboundTag, func() (any, error) {
|
||||
t, err := urltest.URLTest(serviceNow.ctx, "", outboundToTest)
|
||||
if err != nil {
|
||||
historyStorage.DeleteURLTestHistory(outboundTag)
|
||||
} else {
|
||||
historyStorage.StoreURLTestHistory(outboundTag, &adapter.URLTestHistory{
|
||||
Time: time.Now(),
|
||||
Delay: t,
|
||||
})
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
}
|
||||
}
|
||||
return writeError(conn, nil)
|
||||
}
|
||||
@@ -3,16 +3,19 @@ package libbox
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"net/netip"
|
||||
"os"
|
||||
|
||||
box "github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/process"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/dns"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/include"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
tun "github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/json"
|
||||
@@ -52,7 +55,7 @@ func CheckConfig(configContent string) error {
|
||||
}
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
ctx = service.ContextWith[adapter.PlatformInterface](ctx, (*platformInterfaceStub)(nil))
|
||||
ctx = service.ContextWith[platform.Interface](ctx, (*platformInterfaceStub)(nil))
|
||||
instance, err := box.New(box.Options{
|
||||
Context: ctx,
|
||||
Options: options,
|
||||
@@ -77,11 +80,7 @@ func (s *platformInterfaceStub) AutoDetectInterfaceControl(fd int) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformInterface() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) OpenInterface(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error) {
|
||||
func (s *platformInterfaceStub) OpenTun(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error) {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
@@ -93,11 +92,7 @@ func (s *platformInterfaceStub) CreateDefaultInterfaceMonitor(logger logger.Logg
|
||||
return (*interfaceMonitorStub)(nil)
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformNetworkInterfaces() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
|
||||
func (s *platformInterfaceStub) Interfaces() ([]adapter.NetworkInterface, error) {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
@@ -105,17 +100,13 @@ func (s *platformInterfaceStub) UnderNetworkExtension() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) NetworkExtensionIncludeAllNetworks() bool {
|
||||
func (s *platformInterfaceStub) IncludeAllNetworks() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) ClearDNSCache() {
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) RequestPermissionForWIFIState() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformWIFIMonitor() bool {
|
||||
return false
|
||||
}
|
||||
@@ -128,27 +119,11 @@ func (s *platformInterfaceStub) SystemCertificates() []string {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformConnectionOwnerFinder() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) FindConnectionOwner(request *adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
|
||||
func (s *platformInterfaceStub) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*process.Info, error) {
|
||||
return nil, os.ErrInvalid
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformNotification() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) SendNotification(notification *adapter.Notification) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) UsePlatformLocalDNSTransport() bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *platformInterfaceStub) LocalDNSTransport() dns.TransportConstructorFunc[option.LocalDNSServerOptions] {
|
||||
func (s *platformInterfaceStub) SendNotification(notification *platform.Notification) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,33 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing/common"
|
||||
)
|
||||
|
||||
var _ deprecated.Manager = (*deprecatedManager)(nil)
|
||||
|
||||
type deprecatedManager struct {
|
||||
access sync.Mutex
|
||||
notes []deprecated.Note
|
||||
}
|
||||
|
||||
func (m *deprecatedManager) ReportDeprecated(feature deprecated.Note) {
|
||||
m.access.Lock()
|
||||
defer m.access.Unlock()
|
||||
m.notes = common.Uniq(append(m.notes, feature))
|
||||
}
|
||||
|
||||
func (m *deprecatedManager) Get() []deprecated.Note {
|
||||
m.access.Lock()
|
||||
defer m.access.Unlock()
|
||||
notes := m.notes
|
||||
m.notes = nil
|
||||
return notes
|
||||
}
|
||||
|
||||
var _ = deprecated.Note(DeprecatedNote{})
|
||||
|
||||
type DeprecatedNote struct {
|
||||
|
||||
@@ -77,27 +77,22 @@ func NewHTTPClient() HTTPClient {
|
||||
}
|
||||
|
||||
func (c *httpClient) ModernTLS() {
|
||||
c.setTLSVersion(tls.VersionTLS12, 0, func(suite *tls.CipherSuite) bool { return true })
|
||||
c.tls.MinVersion = tls.VersionTLS12
|
||||
c.tls.CipherSuites = common.Map(tls.CipherSuites(), func(it *tls.CipherSuite) uint16 { return it.ID })
|
||||
}
|
||||
|
||||
func (c *httpClient) RestrictedTLS() {
|
||||
c.setTLSVersion(tls.VersionTLS13, 0, func(suite *tls.CipherSuite) bool {
|
||||
return common.Contains(suite.SupportedVersions, uint16(tls.VersionTLS13))
|
||||
})
|
||||
}
|
||||
|
||||
func (c *httpClient) setTLSVersion(minVersion, maxVersion uint16, filter func(*tls.CipherSuite) bool) {
|
||||
c.tls.MinVersion = minVersion
|
||||
if maxVersion != 0 {
|
||||
c.tls.MaxVersion = maxVersion
|
||||
}
|
||||
c.tls.CipherSuites = common.Map(common.Filter(tls.CipherSuites(), filter), func(it *tls.CipherSuite) uint16 {
|
||||
c.tls.MinVersion = tls.VersionTLS13
|
||||
c.tls.CipherSuites = common.Map(common.Filter(tls.CipherSuites(), func(it *tls.CipherSuite) bool {
|
||||
return common.Contains(it.SupportedVersions, uint16(tls.VersionTLS13))
|
||||
}), func(it *tls.CipherSuite) uint16 {
|
||||
return it.ID
|
||||
})
|
||||
}
|
||||
|
||||
func (c *httpClient) PinnedTLS12() {
|
||||
c.setTLSVersion(tls.VersionTLS12, tls.VersionTLS12, func(suite *tls.CipherSuite) bool { return true })
|
||||
c.tls.MinVersion = tls.VersionTLS12
|
||||
c.tls.MaxVersion = tls.VersionTLS12
|
||||
}
|
||||
|
||||
func (c *httpClient) PinnedSHA256(sumHex string) {
|
||||
@@ -183,7 +178,9 @@ func (r *httpRequest) SetUserAgent(userAgent string) {
|
||||
}
|
||||
|
||||
func (r *httpRequest) SetContent(content []byte) {
|
||||
r.request.Body = io.NopCloser(bytes.NewReader(content))
|
||||
buffer := bytes.Buffer{}
|
||||
buffer.Write(content)
|
||||
r.request.Body = io.NopCloser(bytes.NewReader(buffer.Bytes()))
|
||||
r.request.ContentLength = int64(len(content))
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,6 @@ type StringIterator interface {
|
||||
Next() string
|
||||
}
|
||||
|
||||
type Int32Iterator interface {
|
||||
Len() int32
|
||||
HasNext() bool
|
||||
Next() int32
|
||||
}
|
||||
|
||||
var _ StringIterator = (*iterator[string])(nil)
|
||||
|
||||
type iterator[T any] struct {
|
||||
|
||||
@@ -5,10 +5,11 @@ package libbox
|
||||
import (
|
||||
"os"
|
||||
"runtime"
|
||||
"runtime/debug"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
var crashOutputFile *os.File
|
||||
var stderrFile *os.File
|
||||
|
||||
func RedirectStderr(path string) error {
|
||||
if stats, err := os.Stat(path); err == nil && stats.Size() > 0 {
|
||||
@@ -26,12 +27,12 @@ func RedirectStderr(path string) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
err = debug.SetCrashOutput(outputFile, debug.CrashOptions{})
|
||||
err = unix.Dup2(int(outputFile.Fd()), int(os.Stderr.Fd()))
|
||||
if err != nil {
|
||||
outputFile.Close()
|
||||
os.Remove(outputFile.Name())
|
||||
return err
|
||||
}
|
||||
crashOutputFile = outputFile
|
||||
stderrFile = outputFile
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
tun "github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
|
||||
@@ -10,6 +10,7 @@ type PlatformInterface interface {
|
||||
UsePlatformAutoDetectInterfaceControl() bool
|
||||
AutoDetectInterfaceControl(fd int32) error
|
||||
OpenTun(options TunOptions) (int32, error)
|
||||
WriteLog(message string)
|
||||
UseProcFS() bool
|
||||
FindConnectionOwner(ipProtocol int32, sourceAddress string, sourcePort int32, destinationAddress string, destinationPort int32) (int32, error)
|
||||
PackageNameByUid(uid int32) (string, error)
|
||||
@@ -25,6 +26,11 @@ type PlatformInterface interface {
|
||||
SendNotification(notification *Notification) error
|
||||
}
|
||||
|
||||
type TunInterface interface {
|
||||
FileDescriptor() int32
|
||||
Close() error
|
||||
}
|
||||
|
||||
type InterfaceUpdateListener interface {
|
||||
UpdateDefaultInterface(interfaceName string, interfaceIndex int32, isExpensive bool, isConstrained bool)
|
||||
}
|
||||
|
||||
36
experimental/libbox/platform/interface.go
Normal file
36
experimental/libbox/platform/interface.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package platform
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/process"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
)
|
||||
|
||||
type Interface interface {
|
||||
Initialize(networkManager adapter.NetworkManager) error
|
||||
UsePlatformAutoDetectInterfaceControl() bool
|
||||
AutoDetectInterfaceControl(fd int) error
|
||||
OpenTun(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error)
|
||||
CreateDefaultInterfaceMonitor(logger logger.Logger) tun.DefaultInterfaceMonitor
|
||||
Interfaces() ([]adapter.NetworkInterface, error)
|
||||
UnderNetworkExtension() bool
|
||||
IncludeAllNetworks() bool
|
||||
ClearDNSCache()
|
||||
UsePlatformWIFIMonitor() bool
|
||||
ReadWIFIState() adapter.WIFIState
|
||||
SystemCertificates() []string
|
||||
process.Searcher
|
||||
SendNotification(notification *Notification) error
|
||||
}
|
||||
|
||||
type Notification struct {
|
||||
Identifier string
|
||||
TypeName string
|
||||
TypeID int32
|
||||
Title string
|
||||
Subtitle string
|
||||
Body string
|
||||
OpenURL string
|
||||
}
|
||||
@@ -1,28 +1,123 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"net"
|
||||
"context"
|
||||
"net/netip"
|
||||
"os"
|
||||
"runtime"
|
||||
"strconv"
|
||||
runtimeDebug "runtime/debug"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/sagernet/sing-box"
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/common/process"
|
||||
"github.com/sagernet/sing-box/common/urltest"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/internal/procfs"
|
||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
tun "github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common"
|
||||
"github.com/sagernet/sing/common/control"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
"github.com/sagernet/sing/common/logger"
|
||||
N "github.com/sagernet/sing/common/network"
|
||||
"github.com/sagernet/sing/service"
|
||||
"github.com/sagernet/sing/service/pause"
|
||||
)
|
||||
|
||||
var _ adapter.PlatformInterface = (*platformInterfaceWrapper)(nil)
|
||||
type BoxService struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
urlTestHistoryStorage adapter.URLTestHistoryStorage
|
||||
instance *box.Box
|
||||
clashServer adapter.ClashServer
|
||||
pauseManager pause.Manager
|
||||
|
||||
iOSPauseFields
|
||||
}
|
||||
|
||||
func NewService(configContent string, platformInterface PlatformInterface) (*BoxService, error) {
|
||||
ctx := BaseContext(platformInterface)
|
||||
service.MustRegister[deprecated.Manager](ctx, new(deprecatedManager))
|
||||
options, err := parseConfig(ctx, configContent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runtimeDebug.FreeOSMemory()
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
urlTestHistoryStorage := urltest.NewHistoryStorage()
|
||||
ctx = service.ContextWithPtr(ctx, urlTestHistoryStorage)
|
||||
platformWrapper := &platformInterfaceWrapper{
|
||||
iif: platformInterface,
|
||||
useProcFS: platformInterface.UseProcFS(),
|
||||
}
|
||||
service.MustRegister[platform.Interface](ctx, platformWrapper)
|
||||
instance, err := box.New(box.Options{
|
||||
Context: ctx,
|
||||
Options: options,
|
||||
PlatformLogWriter: platformWrapper,
|
||||
})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, E.Cause(err, "create service")
|
||||
}
|
||||
runtimeDebug.FreeOSMemory()
|
||||
return &BoxService{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
instance: instance,
|
||||
urlTestHistoryStorage: urlTestHistoryStorage,
|
||||
pauseManager: service.FromContext[pause.Manager](ctx),
|
||||
clashServer: service.FromContext[adapter.ClashServer](ctx),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *BoxService) Start() error {
|
||||
if sFixAndroidStack {
|
||||
var err error
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
err = s.instance.Start()
|
||||
close(done)
|
||||
}()
|
||||
<-done
|
||||
return err
|
||||
} else {
|
||||
return s.instance.Start()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BoxService) Close() error {
|
||||
s.cancel()
|
||||
s.urlTestHistoryStorage.Close()
|
||||
var err error
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
err = s.instance.Close()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
return err
|
||||
case <-time.After(C.FatalStopTimeout):
|
||||
os.Exit(1)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BoxService) NeedWIFIState() bool {
|
||||
return s.instance.Network().NeedWIFIState()
|
||||
}
|
||||
|
||||
var (
|
||||
_ platform.Interface = (*platformInterfaceWrapper)(nil)
|
||||
_ log.PlatformWriter = (*platformInterfaceWrapper)(nil)
|
||||
)
|
||||
|
||||
type platformInterfaceWrapper struct {
|
||||
iif PlatformInterface
|
||||
@@ -48,11 +143,7 @@ func (w *platformInterfaceWrapper) AutoDetectInterfaceControl(fd int) error {
|
||||
return w.iif.AutoDetectInterfaceControl(int32(fd))
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformInterface() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) OpenInterface(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error) {
|
||||
func (w *platformInterfaceWrapper) OpenTun(options *tun.Options, platformOptions option.TunPlatformOptions) (tun.Tun, error) {
|
||||
if len(options.IncludeUID) > 0 || len(options.ExcludeUID) > 0 {
|
||||
return nil, E.New("platform: unsupported uid options")
|
||||
}
|
||||
@@ -81,10 +172,6 @@ func (w *platformInterfaceWrapper) OpenInterface(options *tun.Options, platformO
|
||||
return tun.New(*options)
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformDefaultInterfaceMonitor() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) CreateDefaultInterfaceMonitor(logger logger.Logger) tun.DefaultInterfaceMonitor {
|
||||
return &platformDefaultInterfaceMonitor{
|
||||
platformInterfaceWrapper: w,
|
||||
@@ -92,11 +179,7 @@ func (w *platformInterfaceWrapper) CreateDefaultInterfaceMonitor(logger logger.L
|
||||
}
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformNetworkInterfaces() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) NetworkInterfaces() ([]adapter.NetworkInterface, error) {
|
||||
func (w *platformInterfaceWrapper) Interfaces() ([]adapter.NetworkInterface, error) {
|
||||
interfaceIterator, err := w.iif.GetInterfaces()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -133,7 +216,7 @@ func (w *platformInterfaceWrapper) UnderNetworkExtension() bool {
|
||||
return w.iif.UnderNetworkExtension()
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) NetworkExtensionIncludeAllNetworks() bool {
|
||||
func (w *platformInterfaceWrapper) IncludeAllNetworks() bool {
|
||||
return w.iif.IncludeAllNetworks()
|
||||
}
|
||||
|
||||
@@ -141,10 +224,6 @@ func (w *platformInterfaceWrapper) ClearDNSCache() {
|
||||
w.iif.ClearDNSCache()
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) RequestPermissionForWIFIState() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformWIFIMonitor() bool {
|
||||
return true
|
||||
}
|
||||
@@ -161,82 +240,41 @@ func (w *platformInterfaceWrapper) SystemCertificates() []string {
|
||||
return iteratorToArray[string](w.iif.SystemCertificates())
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformConnectionOwnerFinder() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) FindConnectionOwner(request *adapter.FindConnectionOwnerRequest) (*adapter.ConnectionOwner, error) {
|
||||
func (w *platformInterfaceWrapper) FindProcessInfo(ctx context.Context, network string, source netip.AddrPort, destination netip.AddrPort) (*process.Info, error) {
|
||||
var uid int32
|
||||
if w.useProcFS {
|
||||
var source netip.AddrPort
|
||||
var destination netip.AddrPort
|
||||
sourceAddr, _ := netip.ParseAddr(request.SourceAddress)
|
||||
source = netip.AddrPortFrom(sourceAddr, uint16(request.SourcePort))
|
||||
destAddr, _ := netip.ParseAddr(request.DestinationAddress)
|
||||
destination = netip.AddrPortFrom(destAddr, uint16(request.DestinationPort))
|
||||
|
||||
var network string
|
||||
switch request.IpProtocol {
|
||||
case int32(syscall.IPPROTO_TCP):
|
||||
network = "tcp"
|
||||
case int32(syscall.IPPROTO_UDP):
|
||||
network = "udp"
|
||||
default:
|
||||
return nil, E.New("unknown protocol: ", request.IpProtocol)
|
||||
}
|
||||
|
||||
uid = procfs.ResolveSocketByProcSearch(network, source, destination)
|
||||
if uid == -1 {
|
||||
return nil, E.New("procfs: not found")
|
||||
}
|
||||
} else {
|
||||
var ipProtocol int32
|
||||
switch N.NetworkName(network) {
|
||||
case N.NetworkTCP:
|
||||
ipProtocol = syscall.IPPROTO_TCP
|
||||
case N.NetworkUDP:
|
||||
ipProtocol = syscall.IPPROTO_UDP
|
||||
default:
|
||||
return nil, E.New("unknown network: ", network)
|
||||
}
|
||||
var err error
|
||||
uid, err = w.iif.FindConnectionOwner(request.IpProtocol, request.SourceAddress, request.SourcePort, request.DestinationAddress, request.DestinationPort)
|
||||
uid, err = w.iif.FindConnectionOwner(ipProtocol, source.Addr().String(), int32(source.Port()), destination.Addr().String(), int32(destination.Port()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
packageName, _ := w.iif.PackageNameByUid(uid)
|
||||
return &adapter.ConnectionOwner{
|
||||
UserId: uid,
|
||||
AndroidPackageName: packageName,
|
||||
}, nil
|
||||
return &process.Info{UserId: uid, PackageName: packageName}, nil
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) DisableColors() bool {
|
||||
return runtime.GOOS != "android"
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) UsePlatformNotification() bool {
|
||||
return true
|
||||
func (w *platformInterfaceWrapper) WriteMessage(level log.Level, message string) {
|
||||
w.iif.WriteLog(message)
|
||||
}
|
||||
|
||||
func (w *platformInterfaceWrapper) SendNotification(notification *adapter.Notification) error {
|
||||
func (w *platformInterfaceWrapper) SendNotification(notification *platform.Notification) error {
|
||||
return w.iif.SendNotification((*Notification)(notification))
|
||||
}
|
||||
|
||||
func AvailablePort(startPort int32) (int32, error) {
|
||||
for port := int(startPort); ; port++ {
|
||||
if port > 65535 {
|
||||
return 0, E.New("no available port found")
|
||||
}
|
||||
listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(int(port))))
|
||||
if err != nil {
|
||||
if errors.Is(err, syscall.EADDRINUSE) {
|
||||
continue
|
||||
}
|
||||
return 0, E.Cause(err, "find available port")
|
||||
}
|
||||
err = listener.Close()
|
||||
if err != nil {
|
||||
return 0, E.Cause(err, "close listener")
|
||||
}
|
||||
return int32(port), nil
|
||||
}
|
||||
}
|
||||
|
||||
func RandomHex(length int32) *StringBox {
|
||||
bytes := make([]byte, length)
|
||||
common.Must1(rand.Read(bytes))
|
||||
return wrapString(hex.EncodeToString(bytes))
|
||||
}
|
||||
|
||||
32
experimental/libbox/service_error.go
Normal file
32
experimental/libbox/service_error.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func serviceErrorPath() string {
|
||||
return filepath.Join(sWorkingPath, "network_extension_error")
|
||||
}
|
||||
|
||||
func ClearServiceError() {
|
||||
os.Remove(serviceErrorPath())
|
||||
}
|
||||
|
||||
func ReadServiceError() (*StringBox, error) {
|
||||
data, err := os.ReadFile(serviceErrorPath())
|
||||
if err == nil {
|
||||
os.Remove(serviceErrorPath())
|
||||
}
|
||||
return wrapString(string(data)), err
|
||||
}
|
||||
|
||||
func WriteServiceError(message string) error {
|
||||
errorFile, err := os.Create(serviceErrorPath())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
errorFile.WriteString(message)
|
||||
errorFile.Chown(sUserID, sGroupID)
|
||||
return errorFile.Close()
|
||||
}
|
||||
36
experimental/libbox/service_pause.go
Normal file
36
experimental/libbox/service_pause.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package libbox
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
)
|
||||
|
||||
type iOSPauseFields struct {
|
||||
endPauseTimer *time.Timer
|
||||
}
|
||||
|
||||
func (s *BoxService) Pause() {
|
||||
s.pauseManager.DevicePause()
|
||||
if C.IsIos {
|
||||
if s.endPauseTimer == nil {
|
||||
s.endPauseTimer = time.AfterFunc(time.Minute, s.pauseManager.DeviceWake)
|
||||
} else {
|
||||
s.endPauseTimer.Reset(time.Minute)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BoxService) Wake() {
|
||||
if !C.IsIos {
|
||||
s.pauseManager.DeviceWake()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *BoxService) ResetNetwork() {
|
||||
s.instance.Router().ResetNetwork()
|
||||
}
|
||||
|
||||
func (s *BoxService) UpdateWIFIState() {
|
||||
s.instance.Network().UpdateWIFIState()
|
||||
}
|
||||
@@ -2,7 +2,9 @@ package libbox
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"runtime/debug"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
@@ -12,53 +14,55 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
sBasePath string
|
||||
sWorkingPath string
|
||||
sTempPath string
|
||||
sUserID int
|
||||
sGroupID int
|
||||
sFixAndroidStack bool
|
||||
sCommandServerListenPort uint16
|
||||
sCommandServerSecret string
|
||||
sLogMaxLines int
|
||||
sDebug bool
|
||||
sBasePath string
|
||||
sWorkingPath string
|
||||
sTempPath string
|
||||
sUserID int
|
||||
sGroupID int
|
||||
sTVOS bool
|
||||
sFixAndroidStack bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
debug.SetPanicOnFault(true)
|
||||
debug.SetTraceback("all")
|
||||
}
|
||||
|
||||
type SetupOptions struct {
|
||||
BasePath string
|
||||
WorkingPath string
|
||||
TempPath string
|
||||
FixAndroidStack bool
|
||||
CommandServerListenPort int32
|
||||
CommandServerSecret string
|
||||
LogMaxLines int
|
||||
Debug bool
|
||||
BasePath string
|
||||
WorkingPath string
|
||||
TempPath string
|
||||
Username string
|
||||
IsTVOS bool
|
||||
FixAndroidStack bool
|
||||
}
|
||||
|
||||
func Setup(options *SetupOptions) error {
|
||||
sBasePath = options.BasePath
|
||||
sWorkingPath = options.WorkingPath
|
||||
sTempPath = options.TempPath
|
||||
|
||||
sUserID = os.Getuid()
|
||||
sGroupID = os.Getgid()
|
||||
if options.Username != "" {
|
||||
sUser, err := user.Lookup(options.Username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sUserID, _ = strconv.Atoi(sUser.Uid)
|
||||
sGroupID, _ = strconv.Atoi(sUser.Gid)
|
||||
} else {
|
||||
sUserID = os.Getuid()
|
||||
sGroupID = os.Getgid()
|
||||
}
|
||||
sTVOS = options.IsTVOS
|
||||
|
||||
// TODO: remove after fixed
|
||||
// https://github.com/golang/go/issues/68760
|
||||
sFixAndroidStack = options.FixAndroidStack
|
||||
|
||||
sCommandServerListenPort = uint16(options.CommandServerListenPort)
|
||||
sCommandServerSecret = options.CommandServerSecret
|
||||
sLogMaxLines = options.LogMaxLines
|
||||
sDebug = options.Debug
|
||||
|
||||
os.MkdirAll(sWorkingPath, 0o777)
|
||||
os.MkdirAll(sTempPath, 0o777)
|
||||
if options.Username != "" {
|
||||
os.Chown(sWorkingPath, sUserID, sGroupID)
|
||||
os.Chown(sTempPath, sUserID, sGroupID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import (
|
||||
"net/netip"
|
||||
|
||||
"github.com/sagernet/sing-box/option"
|
||||
tun "github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing-tun"
|
||||
"github.com/sagernet/sing/common"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
54
go.mod
54
go.mod
@@ -21,24 +21,23 @@ require (
|
||||
github.com/metacubex/utls v1.8.3
|
||||
github.com/mholt/acmez/v3 v3.1.2
|
||||
github.com/miekg/dns v1.1.67
|
||||
github.com/openai/openai-go/v3 v3.13.0
|
||||
github.com/oschwald/maxminddb-golang v1.13.1
|
||||
github.com/sagernet/asc-go v0.0.0-20241217030726-d563060fe4e1
|
||||
github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a
|
||||
github.com/sagernet/cors v1.2.1
|
||||
github.com/sagernet/cronet-go v0.0.0-20251219080614-460b6a5fb79d
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251219080614-460b6a5fb79d
|
||||
github.com/sagernet/cronet-go v0.0.0-20251209141152-67502c396ef4
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251209141601-d8f29fa5b269
|
||||
github.com/sagernet/fswatch v0.1.1
|
||||
github.com/sagernet/gomobile v0.1.10
|
||||
github.com/sagernet/gomobile v0.1.8
|
||||
github.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.3
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.1
|
||||
github.com/sagernet/sing v0.8.0-beta.6.0.20251207063731-56fd482ce1c6
|
||||
github.com/sagernet/sing-mux v0.3.3
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5.0.20251218085114-6968f531a8c0
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5
|
||||
github.com/sagernet/sing-shadowsocks v0.2.8
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.1
|
||||
github.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11.0.20251201004738-e9e3fbf0c15e
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11
|
||||
github.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1
|
||||
github.com/sagernet/smux v1.5.34-mod.2
|
||||
github.com/sagernet/tailscale v1.86.5-sing-box-1.13-mod.4
|
||||
@@ -76,7 +75,6 @@ require (
|
||||
github.com/dblohm7/wingoes v0.0.0-20240119213807-a09d6be7affa // indirect
|
||||
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1 // indirect
|
||||
github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e // indirect
|
||||
github.com/ebitengine/purego v0.9.1 // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
|
||||
github.com/gaissmai/bart v0.18.0 // indirect
|
||||
@@ -108,28 +106,24 @@ require (
|
||||
github.com/prometheus-community/pro-bing v0.4.0 // indirect
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/safchain/ethtool v0.3.0 // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251219080137-fbc9bf07b76b // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/windows_386 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251209141152-67502c396ef4 // indirect
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a // indirect
|
||||
github.com/sagernet/nftables v0.3.0-beta.4 // indirect
|
||||
github.com/spf13/pflag v1.0.6 // indirect
|
||||
|
||||
108
go.sum
108
go.sum
@@ -41,8 +41,6 @@ github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1 h1:CaO/zOnF8VvUfEbhRatPcwKVWamvbY
|
||||
github.com/dgrijalva/jwt-go/v4 v4.0.0-preview1/go.mod h1:+hnT3ywWDTAFrW5aE+u2Sa/wT555ZqwoCS+pk3p6ry4=
|
||||
github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e h1:vUmf0yezR0y7jJ5pceLHthLaYf4bA5T14B6q39S4q2Q=
|
||||
github.com/digitalocean/go-smbios v0.0.0-20180907143718-390a4f403a8e/go.mod h1:YTIHhz/QFSYnu/EhlF2SpU2Uk+32abacUYA5ZPljz1A=
|
||||
github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=
|
||||
github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
|
||||
@@ -132,8 +130,6 @@ github.com/mitchellh/go-ps v1.0.0 h1:i6ampVEEF4wQFF+bkYfwYgY+F/uYJDktmvLPf7qIgjc
|
||||
github.com/mitchellh/go-ps v1.0.0/go.mod h1:J4lOc8z8yJs6vUwklHw2XEIiT4z4C40KtWVN3nvg8Pg=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 h1:zYyBkD/k9seD2A7fsi6Oo2LfFZAehjjQMERAvZLEDnQ=
|
||||
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/openai/openai-go/v3 v3.13.0 h1:arSFmVHcBHNVYG5iqspPJrLoin0Qqn2JcCLWWcTcM1Q=
|
||||
github.com/openai/openai-go/v3 v3.13.0/go.mod h1:cdufnVK14cWcT9qA1rRtrXx4FTRsgbDPW7Ia7SS5cZo=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1 h1:G3wwjdN9JmIK2o/ermkHM+98oX5fS+k5MbwsmL4MRQE=
|
||||
github.com/oschwald/maxminddb-golang v1.13.1/go.mod h1:K4pgV9N/GcK694KSTmVSDTODk4IsCNThNdTmnaBZ/F8=
|
||||
github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ=
|
||||
@@ -154,81 +150,73 @@ github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a h1:+NkI2670SQpQWvkk
|
||||
github.com/sagernet/bbolt v0.0.0-20231014093535-ea5cb2fe9f0a/go.mod h1:63s7jpZqcDAIpj8oI/1v4Izok+npJOHACFCU6+huCkM=
|
||||
github.com/sagernet/cors v1.2.1 h1:Cv5Z8y9YSD6Gm+qSpNrL3LO4lD3eQVvbFYJSG7JCMHQ=
|
||||
github.com/sagernet/cors v1.2.1/go.mod h1:O64VyOjjhrkLmQIjF4KGRrJO/5dVXFdpEmCW/eISRAI=
|
||||
github.com/sagernet/cronet-go v0.0.0-20251219080614-460b6a5fb79d h1:Wfs4UEnHE3d0hHHG1NedCCwU2lUVlsgKblBGuOps8k4=
|
||||
github.com/sagernet/cronet-go v0.0.0-20251219080614-460b6a5fb79d/go.mod h1:hwFHBEjjthyEquDULbr4c4ucMedp8Drb6Jvm2kt/0Bw=
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251219080614-460b6a5fb79d h1:DZy1I3zKP5bRaFGDYStZWAXrtlxn3W4ONbFUD027sw8=
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251219080614-460b6a5fb79d/go.mod h1:eKeQLIddaQGZD2/jc0t+AdTnHve3Yo+uMujwgNOCfz0=
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251219080137-fbc9bf07b76b h1:+WRqXRiHEom7+lZUEA4qPVfNQB7Rx4++6JEN8cd5CgQ=
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:XXDwdjX/T8xftoeJxQmbBoYXZp8MAPFR2CwbFuTpEtw=
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251219080137-fbc9bf07b76b h1:ofD/ZwijuG5ccz0afLcvbfssIG+q/Bp8A2sziYYlJ28=
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:iNiUGoLtnr8/JTuVNj7XJbmpOAp2C6+B81KDrPxwaZM=
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251219080137-fbc9bf07b76b h1:m3Hv8Hs6x6JdFNe93nzh1XhdZ7DmkfOKheloDmQmGQo=
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:19ILNUOGIzRdOqa2mq+iY0JoHxuieB7/lnjYeaA2vEc=
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:gA8bzjowa5Lmih+hBjjh6xsjghmGTIojKNtPzVDG93A=
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:JxzGyQf94Cr6sBShKqODGDyRUlESfJK/Njcz9Lz6qMQ=
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251219080137-fbc9bf07b76b h1:0ASeUCDj66dAHaCU/HkgbuSm/1co+yHbrq13BokW/us=
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:KN+9T9TBycGOLzmKU4QdcHAJEj6Nlx48ifnlTvvHMvs=
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:NsbDT3L2pLS0Qsh0MPEn+IPkL33XoL7eFs56EA0jBeo=
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:kojvtUc29KKnk8hs2QIANynVR59921SnGWA9kXohHc0=
|
||||
github.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b h1:hIMIG2AuF3n9yelPvfUB3jyW2vWJnPiJfhE3hGUGJDk=
|
||||
github.com/sagernet/cronet-go/lib/ios_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:hkQzRE5GDbaH1/ioqYh0Taho4L6i0yLRCVEZ5xHz5M0=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:/l1dS38ijnn0IHtAdFH3Y8cahAGw6ii0TYow0jUNBGM=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:tzVJFTOm66UxLxy6K0ZN5Ic2PC79e+sKKnt+V9puEa4=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b h1:m29qbSNfdNuTYEgTkph9TQUIyu7wIrY3PAvbgl23OjA=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:M/pN6m3j0HFU6/y83n0HU6GLYys3tYdr/xTE8hVEGMo=
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251219080137-fbc9bf07b76b h1:mmOPED30mKTr0DucTYQeJBHtjAgvBO7huwdG3gL6Gyw=
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:cGh5hO6eljCo6KMQ/Cel8Xgq4+etL0awZLRBDVG1EZQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251219080137-fbc9bf07b76b h1:y7V2c5QwMY07ME/M+cI/W1ZNw2QFT2oMw99GaPtK0MY=
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:JFE0/cxaKkx0wqPMZU7MgaplQlU0zudv82dROJjClKU=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251219080137-fbc9bf07b76b h1:txNHLfT1miemCZgCrtrA+eTbGfsfN46wHIpOShALNzI=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:vU8VftFeSt7fURCa3JXD6+k6ss1YAX+idQjPvHmJ2tI=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251219080137-fbc9bf07b76b h1:FVPZ3TKAoIeM1hTCqUn0D7gHx6rDkKqhx+E8yaYNbXI=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:vCe4OUuL+XOUge9v3MyTD45BnuAXiH+DkjN9quDXJzQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251219080137-fbc9bf07b76b h1:4ei7Sz97XCFXh+FUi2cKGHrhqD0A8lxdjZxST7NzDrQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:w9amBWrvjtohQzBGCKJ7LCh22LhTIJs4sE7cYaKQzM0=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:W0SrTDGPaKfcgjiZDkYeWqpICeVkwydaa228znP4q2c=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:TqlsFtcYS/etTeck46kHBeT8Le0Igw1Q/AV88UnMS3s=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251219080137-fbc9bf07b76b h1:WD7V83I/FDatR0zXq6gSxh8gGZCD+fUZjLb1f+OVuF0=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:B6Qd0vys8sv9OKVRN6J9RqDzYRGE938Fb2zrYdBDyTQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251219080137-fbc9bf07b76b h1:M1V7j6Bke+v9aXeEK/NcWqoPwl84h97fmL3XSJJmNJw=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:3tXMMFY7AHugOVBZ5Al7cL7JKsnFOe5bMVr0hZPk3ow=
|
||||
github.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b h1:DmLB0sgGw7vNao08a7NJ0xMJbZpeL49rAphknfRRs5I=
|
||||
github.com/sagernet/cronet-go/lib/tvos_amd64_simulator v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:aaX0YGl8nhGmfRWI8bc3BtDjY8Vzx6O0cS/e1uqxDq4=
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:j8tKUY2VVnK/RxIvX75G/nLGu53to6LaDRH/NTzyLDw=
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:EdzMKA96xITc42QEI+ct4SwqX8Dn3ltKK8wzdkLWpSc=
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b h1:+1hjEBE2hUGUxDKtNg+gBYYCHXPQao273PjimC67v38=
|
||||
github.com/sagernet/cronet-go/lib/tvos_arm64_simulator v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:qix4kv1TTAJ5tY4lJ9vjhe9EY4mM+B7H5giOhbxDVcc=
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251219080137-fbc9bf07b76b h1:22Jx/y6cz2lVeUwbN/lmNOUjhEWYpohGEYpW/zdDcBk=
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:lm9w/oCCRyBiUa3G8lDQTT8x/ONUvgVR2iV9fVzUZB8=
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251219080137-fbc9bf07b76b h1:7juUKsCbreYSP8gALPf45kut0zdSpZXrk2TLIwQ2zOo=
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251219080137-fbc9bf07b76b/go.mod h1:n34YyLgapgjWdKa0IoeczjAFCwD3/dxbsH5sucKw0bw=
|
||||
github.com/sagernet/cronet-go v0.0.0-20251209141152-67502c396ef4 h1:BfitgSppBdvn5gqwRLNA5Nhu67YvZxQKM9n3b1j1dgI=
|
||||
github.com/sagernet/cronet-go v0.0.0-20251209141152-67502c396ef4/go.mod h1:l5IZJLEWpDGJbrF0qBHgxAVBPsAxKOLa1BYDh6B2sdI=
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251209141601-d8f29fa5b269 h1:dA79nNuqhUIGcw7DP3ifRXtJq39rE/UWZPfmQ6QS40w=
|
||||
github.com/sagernet/cronet-go/all v0.0.0-20251209141601-d8f29fa5b269/go.mod h1:iLjzAv2hALBTxeC10i99ludp7jU6U3dw/yXbn0x3Ek8=
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251209141152-67502c396ef4 h1:eN1EtBxDDOvWW7Q0+a1UzBcnYs6u2EqgHgLYOPFwHSE=
|
||||
github.com/sagernet/cronet-go/lib/android_386 v0.0.0-20251209141152-67502c396ef4/go.mod h1:XXDwdjX/T8xftoeJxQmbBoYXZp8MAPFR2CwbFuTpEtw=
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251209141152-67502c396ef4 h1:mQSHDat1i4Q5/+CvvRGTAAvT2vaYtci671/v5nC4FIM=
|
||||
github.com/sagernet/cronet-go/lib/android_amd64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:iNiUGoLtnr8/JTuVNj7XJbmpOAp2C6+B81KDrPxwaZM=
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251209141152-67502c396ef4 h1:TLVfFFNvGEPBZzFUecr1r32A0hsS6oeiEQWVQlDys+g=
|
||||
github.com/sagernet/cronet-go/lib/android_arm v0.0.0-20251209141152-67502c396ef4/go.mod h1:19ILNUOGIzRdOqa2mq+iY0JoHxuieB7/lnjYeaA2vEc=
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251209141152-67502c396ef4 h1:fCk6J6Shm+47s21JIpZuKLA0GD29HsGmUOCB3QkM7wc=
|
||||
github.com/sagernet/cronet-go/lib/android_arm64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:JxzGyQf94Cr6sBShKqODGDyRUlESfJK/Njcz9Lz6qMQ=
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251209141152-67502c396ef4 h1:lFaYkrltdVGtHoTtcTGCNP0lwGnwcCvZxJOCOyMtVcg=
|
||||
github.com/sagernet/cronet-go/lib/darwin_amd64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:KN+9T9TBycGOLzmKU4QdcHAJEj6Nlx48ifnlTvvHMvs=
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251209141152-67502c396ef4 h1:AdaoXuHTt5PnXUyDR/jcz2lBoA0osvOvORH9zUkTYtw=
|
||||
github.com/sagernet/cronet-go/lib/darwin_arm64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:kojvtUc29KKnk8hs2QIANynVR59921SnGWA9kXohHc0=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251209141152-67502c396ef4 h1:d5qnUEz2E3GBiZTf0FcUx6zH70rxqHN6rKifhv3ww0g=
|
||||
github.com/sagernet/cronet-go/lib/ios_arm64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:tzVJFTOm66UxLxy6K0ZN5Ic2PC79e+sKKnt+V9puEa4=
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251209141152-67502c396ef4 h1:SBgtdbs/VPOlKZmh+ieSvg1FAhqZgah27u9U1TNqzLk=
|
||||
github.com/sagernet/cronet-go/lib/linux_386 v0.0.0-20251209141152-67502c396ef4/go.mod h1:cGh5hO6eljCo6KMQ/Cel8Xgq4+etL0awZLRBDVG1EZQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251209141152-67502c396ef4 h1:N4hzsQK1RMT/1cZdlVXgWJLnThM1SqSd8xKqMGVe2BM=
|
||||
github.com/sagernet/cronet-go/lib/linux_386_musl v0.0.0-20251209141152-67502c396ef4/go.mod h1:JFE0/cxaKkx0wqPMZU7MgaplQlU0zudv82dROJjClKU=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251209141152-67502c396ef4 h1:nnms0N+jFr78znmeTXNEZT3oa9M7QNJ3BZyKlh6xxPU=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:vU8VftFeSt7fURCa3JXD6+k6ss1YAX+idQjPvHmJ2tI=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251209141152-67502c396ef4 h1:tQsiwZZO13yXPVG10FRKRvABMzVMta3HTMEyrKGVitg=
|
||||
github.com/sagernet/cronet-go/lib/linux_amd64_musl v0.0.0-20251209141152-67502c396ef4/go.mod h1:vCe4OUuL+XOUge9v3MyTD45BnuAXiH+DkjN9quDXJzQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251209141152-67502c396ef4 h1:/FAmfFm+22TIYAabODI6INOF6XgVoKiJrvo4JJk1QHI=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm v0.0.0-20251209141152-67502c396ef4/go.mod h1:w9amBWrvjtohQzBGCKJ7LCh22LhTIJs4sE7cYaKQzM0=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251209141152-67502c396ef4 h1:c/mtA2g+ScCBGBfa26hakxAVXurD4nhFW/RI0yb4KVM=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:TqlsFtcYS/etTeck46kHBeT8Le0Igw1Q/AV88UnMS3s=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251209141152-67502c396ef4 h1:iRq0SWRDfCf1sKN9R4+5EHWYak0Zfla5li0jhRwBCBA=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm64_musl v0.0.0-20251209141152-67502c396ef4/go.mod h1:B6Qd0vys8sv9OKVRN6J9RqDzYRGE938Fb2zrYdBDyTQ=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251209141152-67502c396ef4 h1:GAQrA1S/cSNxmEeIcQU3jLVbPAU0GlJAM2iDcsKpphA=
|
||||
github.com/sagernet/cronet-go/lib/linux_arm_musl v0.0.0-20251209141152-67502c396ef4/go.mod h1:3tXMMFY7AHugOVBZ5Al7cL7JKsnFOe5bMVr0hZPk3ow=
|
||||
github.com/sagernet/cronet-go/lib/windows_386 v0.0.0-20251209141152-67502c396ef4 h1:Wix35ah7sy4oLTp06kjIqIX0CvtL2o05LXgaZLdDmzg=
|
||||
github.com/sagernet/cronet-go/lib/windows_386 v0.0.0-20251209141152-67502c396ef4/go.mod h1:rnS7D+ULJX2PrP0Cy+05GS0mRZ2PP6+gVSroZKt8fjk=
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251209141152-67502c396ef4 h1:RA5r4IkF/Zvlq+4CwuWqZkb7xt3Fpj2HYUkzcSae1fQ=
|
||||
github.com/sagernet/cronet-go/lib/windows_amd64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:lm9w/oCCRyBiUa3G8lDQTT8x/ONUvgVR2iV9fVzUZB8=
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251209141152-67502c396ef4 h1:7lD3/vGXsmyfOuZN17yZe2u/UFVmOJpb9J7vz/cD0b8=
|
||||
github.com/sagernet/cronet-go/lib/windows_arm64 v0.0.0-20251209141152-67502c396ef4/go.mod h1:n34YyLgapgjWdKa0IoeczjAFCwD3/dxbsH5sucKw0bw=
|
||||
github.com/sagernet/fswatch v0.1.1 h1:YqID+93B7VRfqIH3PArW/XpJv5H4OLEVWDfProGoRQs=
|
||||
github.com/sagernet/fswatch v0.1.1/go.mod h1:nz85laH0mkQqJfaOrqPpkwtU1znMFNVTpT/5oRsVz/o=
|
||||
github.com/sagernet/gomobile v0.1.10 h1:ElqZ0OVDvyQlU91MU0C9cfU0FrILBbc65+NOKzZ1t0c=
|
||||
github.com/sagernet/gomobile v0.1.10/go.mod h1:A8l3FlHi2D/+mfcd4HHvk5DGFPW/ShFb9jHP5VmSiDY=
|
||||
github.com/sagernet/gomobile v0.1.8 h1:vXgoN0pjsMONAaYCTdsKBX2T1kxuS7sbT/mZ7PElGoo=
|
||||
github.com/sagernet/gomobile v0.1.8/go.mod h1:A8l3FlHi2D/+mfcd4HHvk5DGFPW/ShFb9jHP5VmSiDY=
|
||||
github.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1 h1:AzCE2RhBjLJ4WIWc/GejpNh+z30d5H1hwaB0nD9eY3o=
|
||||
github.com/sagernet/gvisor v0.0.0-20250811.0-sing-box-mod.1/go.mod h1:NJKBtm9nVEK3iyOYWsUlrDQuoGh4zJ4KOPhSYVidvQ4=
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a h1:ObwtHN2VpqE0ZNjr6sGeT00J8uU7JF4cNUdb44/Duis=
|
||||
github.com/sagernet/netlink v0.0.0-20240612041022-b9a21c07ac6a/go.mod h1:xLnfdiJbSp8rNqYEdIW/6eDO4mVoogml14Bh2hSiFpM=
|
||||
github.com/sagernet/nftables v0.3.0-beta.4 h1:kbULlAwAC3jvdGAC1P5Fa3GSxVwQJibNenDW2zaXr8I=
|
||||
github.com/sagernet/nftables v0.3.0-beta.4/go.mod h1:OQXAjvjNGGFxaTgVCSTRIhYB5/llyVDeapVoENYBDS8=
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.3 h1:Rah/tDukrowqlznHQgXD4E9/yEsVsEMIxBZzS2NorGc=
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.3/go.mod h1:OqILvS182CyOol5zNNo6bguvOGgXzV459+chpRaUC+4=
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.1 h1:6fhKbfA0b7L1CVekayV1g87uJFtMXFE0rFXR48SRrWI=
|
||||
github.com/sagernet/quic-go v0.57.1-sing-box-mod.1/go.mod h1:OqILvS182CyOol5zNNo6bguvOGgXzV459+chpRaUC+4=
|
||||
github.com/sagernet/sing v0.6.9/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
|
||||
github.com/sagernet/sing v0.8.0-beta.6.0.20251207063731-56fd482ce1c6 h1:EYaDzllFzNYnzQ9xH/ieSAXct4wQ8pD45kgNMo7RPZc=
|
||||
github.com/sagernet/sing v0.8.0-beta.6.0.20251207063731-56fd482ce1c6/go.mod h1:ARkL0gM13/Iv5VCZmci/NuoOlePoIsW0m7BWfln/Hak=
|
||||
github.com/sagernet/sing-mux v0.3.3 h1:YFgt9plMWzH994BMZLmyKL37PdIVaIilwP0Jg+EcLfw=
|
||||
github.com/sagernet/sing-mux v0.3.3/go.mod h1:pht8iFY4c9Xltj7rhVd208npkNaeCxzyXCgulDPLUDA=
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5.0.20251218085114-6968f531a8c0 h1:YNXy008FFkVwfNjCR8GlVTlHbBXPwv8Y4ytDnSFUSDo=
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5.0.20251218085114-6968f531a8c0/go.mod h1:Y3YVjPutLHLQvYjGtUFH+w8YmM4MTd19NDzxLZGNGIs=
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5 h1:kZfRLmsPxAgl0usZUgomDurLn7ZZ26lJWIpGow9ZWR4=
|
||||
github.com/sagernet/sing-quic v0.6.0-beta.5/go.mod h1:9D9GANrK33NjWCe1VkU5L5+8MxU39WrduBSmHuHz8GA=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.8 h1:PURj5PRoAkqeHh2ZW205RWzN9E9RtKCVCzByXruQWfE=
|
||||
github.com/sagernet/sing-shadowsocks v0.2.8/go.mod h1:lo7TWEMDcN5/h5B8S0ew+r78ZODn6SwVaFhvB6H+PTI=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.1 h1:dWV9OXCeFPuYGHb6IRqlSptVnSzOelnqqs2gQ2/Qioo=
|
||||
github.com/sagernet/sing-shadowsocks2 v0.2.1/go.mod h1:RnXS0lExcDAovvDeniJ4IKa2IuChrdipolPYWBv9hWQ=
|
||||
github.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11 h1:tK+75l64tm9WvEFrYRE1t0YxoFdWQqw/h7Uhzj0vJ+w=
|
||||
github.com/sagernet/sing-shadowtls v0.2.1-0.20250503051639-fcd445d33c11/go.mod h1:sWqKnGlMipCHaGsw1sTTlimyUpgzP4WP3pjhCsYt9oA=
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11.0.20251201004738-e9e3fbf0c15e h1:ZEv+9vy7vC1vbr3LfwZGx3JAOkl/w4+hnGamHw4W36M=
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11.0.20251201004738-e9e3fbf0c15e/go.mod h1:eWETzl4AwaxGKiZTpDIDVJLTBz9cfIdoZwaZY1jlSjg=
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11 h1:xVi8VcVkvz2o+3v1PLv5MOkFpiVCwjLjucVlmigDi5c=
|
||||
github.com/sagernet/sing-tun v0.8.0-beta.11/go.mod h1:eWETzl4AwaxGKiZTpDIDVJLTBz9cfIdoZwaZY1jlSjg=
|
||||
github.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1 h1:aSwUNYUkVyVvdmBSufR8/nRFonwJeKSIROxHcm5br9o=
|
||||
github.com/sagernet/sing-vmess v0.2.8-0.20250909125414-3aed155119a1/go.mod h1:P11scgTxMxVVQ8dlM27yNm3Cro40mD0+gHbnqrNGDuY=
|
||||
github.com/sagernet/smux v1.5.34-mod.2 h1:gkmBjIjlJ2zQKpLigOkFur5kBKdV6bNRoFu2WkltRQ4=
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
//go:build with_ocm
|
||||
|
||||
package include
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing-box/adapter/service"
|
||||
"github.com/sagernet/sing-box/service/ocm"
|
||||
)
|
||||
|
||||
func registerOCMService(registry *service.Registry) {
|
||||
ocm.RegisterService(registry)
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//go:build !with_ocm
|
||||
|
||||
package include
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/sagernet/sing-box/adapter"
|
||||
"github.com/sagernet/sing-box/adapter/service"
|
||||
C "github.com/sagernet/sing-box/constant"
|
||||
"github.com/sagernet/sing-box/log"
|
||||
"github.com/sagernet/sing-box/option"
|
||||
E "github.com/sagernet/sing/common/exceptions"
|
||||
)
|
||||
|
||||
func registerOCMService(registry *service.Registry) {
|
||||
service.Register[option.OCMServiceOptions](registry, C.TypeOCM, func(ctx context.Context, logger log.ContextLogger, tag string, options option.OCMServiceOptions) (adapter.Service, error) {
|
||||
return nil, E.New(`OCM is not included in this build, rebuild with -tags with_ocm`)
|
||||
})
|
||||
}
|
||||
@@ -44,7 +44,7 @@ func registerQUICInbounds(registry *inbound.Registry) {
|
||||
inbound.Register[option.Hysteria2InboundOptions](registry, C.TypeHysteria2, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.Hysteria2InboundOptions) (adapter.Inbound, error) {
|
||||
return nil, C.ErrQUICNotIncluded
|
||||
})
|
||||
naive.ConfigureHTTP3ListenerFunc = func(ctx context.Context, logger logger.Logger, listener *listener.Listener, handler http.Handler, tlsConfig tls.ServerConfig, options option.NaiveInboundOptions) (io.Closer, error) {
|
||||
naive.ConfigureHTTP3ListenerFunc = func(listener *listener.Listener, handler http.Handler, tlsConfig tls.ServerConfig, logger logger.Logger) (io.Closer, error) {
|
||||
return nil, C.ErrQUICNotIncluded
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,6 @@ func ServiceRegistry() *service.Registry {
|
||||
|
||||
registerDERPService(registry)
|
||||
registerCCMService(registry)
|
||||
registerOCMService(registry)
|
||||
|
||||
return registry
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ func NewDefaultFactory(
|
||||
level: LevelTrace,
|
||||
subscriber: observable.NewSubscriber[Entry](128),
|
||||
}
|
||||
/*if platformWriter != nil {
|
||||
if platformWriter != nil {
|
||||
factory.platformFormatter.DisableColors = platformWriter.DisableColors()
|
||||
}*/
|
||||
}
|
||||
if needObservable {
|
||||
factory.observer = observable.NewObserver[Entry](factory.subscriber, 64)
|
||||
}
|
||||
@@ -111,30 +111,28 @@ type observableLogger struct {
|
||||
|
||||
func (l *observableLogger) Log(ctx context.Context, level Level, args []any) {
|
||||
level = OverrideLevelFromContext(level, ctx)
|
||||
if level > l.level && l.platformWriter == nil {
|
||||
if level > l.level {
|
||||
return
|
||||
}
|
||||
nowTime := time.Now()
|
||||
if level <= l.level {
|
||||
if l.needObservable {
|
||||
message, messageSimple := l.formatter.FormatWithSimple(ctx, level, l.tag, F.ToString(args...), nowTime)
|
||||
if level == LevelPanic {
|
||||
panic(message)
|
||||
}
|
||||
l.writer.Write([]byte(message))
|
||||
if level == LevelFatal {
|
||||
os.Exit(1)
|
||||
}
|
||||
l.subscriber.Emit(Entry{level, messageSimple})
|
||||
} else {
|
||||
message := l.formatter.Format(ctx, level, l.tag, F.ToString(args...), nowTime)
|
||||
if level == LevelPanic {
|
||||
panic(message)
|
||||
}
|
||||
l.writer.Write([]byte(message))
|
||||
if level == LevelFatal {
|
||||
os.Exit(1)
|
||||
}
|
||||
if l.needObservable {
|
||||
message, messageSimple := l.formatter.FormatWithSimple(ctx, level, l.tag, F.ToString(args...), nowTime)
|
||||
if level == LevelPanic {
|
||||
panic(message)
|
||||
}
|
||||
l.writer.Write([]byte(message))
|
||||
if level == LevelFatal {
|
||||
os.Exit(1)
|
||||
}
|
||||
l.subscriber.Emit(Entry{level, messageSimple})
|
||||
} else {
|
||||
message := l.formatter.Format(ctx, level, l.tag, F.ToString(args...), nowTime)
|
||||
if level == LevelPanic {
|
||||
panic(message)
|
||||
}
|
||||
l.writer.Write([]byte(message))
|
||||
if level == LevelFatal {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
if l.platformWriter != nil {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package log
|
||||
|
||||
type PlatformWriter interface {
|
||||
DisableColors() bool
|
||||
WriteMessage(level Level, message string)
|
||||
}
|
||||
|
||||
@@ -158,7 +158,6 @@ nav:
|
||||
- Shadowsocks: configuration/outbound/shadowsocks.md
|
||||
- VMess: configuration/outbound/vmess.md
|
||||
- Trojan: configuration/outbound/trojan.md
|
||||
- Naive: configuration/outbound/naive.md
|
||||
- WireGuard: configuration/outbound/wireguard.md
|
||||
- Hysteria: configuration/outbound/hysteria.md
|
||||
- ShadowTLS: configuration/outbound/shadowtls.md
|
||||
@@ -176,8 +175,6 @@ nav:
|
||||
- DERP: configuration/service/derp.md
|
||||
- Resolved: configuration/service/resolved.md
|
||||
- SSM API: configuration/service/ssm-api.md
|
||||
- CCM: configuration/service/ccm.md
|
||||
- OCM: configuration/service/ocm.md
|
||||
markdown_extensions:
|
||||
- pymdownx.inlinehilite
|
||||
- pymdownx.snippets
|
||||
|
||||
@@ -5,33 +5,19 @@ import (
|
||||
"github.com/sagernet/sing/common/json/badoption"
|
||||
)
|
||||
|
||||
type QuicheCongestionControl string
|
||||
|
||||
const (
|
||||
QuicheCongestionControlDefault QuicheCongestionControl = ""
|
||||
QuicheCongestionControlBBR QuicheCongestionControl = "TBBR"
|
||||
QuicheCongestionControlBBRv2 QuicheCongestionControl = "B2ON"
|
||||
QuicheCongestionControlCubic QuicheCongestionControl = "QBIC"
|
||||
QuicheCongestionControlReno QuicheCongestionControl = "RENO"
|
||||
)
|
||||
|
||||
type NaiveInboundOptions struct {
|
||||
ListenOptions
|
||||
Users []auth.User `json:"users,omitempty"`
|
||||
Network NetworkList `json:"network,omitempty"`
|
||||
QUICCongestionControl string `json:"quic_congestion_control,omitempty"`
|
||||
Users []auth.User `json:"users,omitempty"`
|
||||
Network NetworkList `json:"network,omitempty"`
|
||||
InboundTLSOptionsContainer
|
||||
}
|
||||
|
||||
type NaiveOutboundOptions struct {
|
||||
DialerOptions
|
||||
ServerOptions
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
InsecureConcurrency int `json:"insecure_concurrency,omitempty"`
|
||||
ExtraHeaders badoption.HTTPHeader `json:"extra_headers,omitempty"`
|
||||
UDPOverTCP *UDPOverTCPOptions `json:"udp_over_tcp,omitempty"`
|
||||
QUIC bool `json:"quic,omitempty"`
|
||||
QUICCongestionControl string `json:"quic_congestion_control,omitempty"`
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
InsecureConcurrency int `json:"insecure_concurrency,omitempty"`
|
||||
ExtraHeaders badoption.HTTPHeader `json:"extra_headers,omitempty"`
|
||||
OutboundTLSOptionsContainer
|
||||
}
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
package option
|
||||
|
||||
import (
|
||||
"github.com/sagernet/sing/common/json/badoption"
|
||||
)
|
||||
|
||||
type OCMServiceOptions struct {
|
||||
ListenOptions
|
||||
InboundTLSOptionsContainer
|
||||
CredentialPath string `json:"credential_path,omitempty"`
|
||||
Users []OCMUser `json:"users,omitempty"`
|
||||
Headers badoption.HTTPHeader `json:"headers,omitempty"`
|
||||
Detour string `json:"detour,omitempty"`
|
||||
UsagesPath string `json:"usages_path,omitempty"`
|
||||
}
|
||||
|
||||
type OCMUser struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
Token string `json:"token,omitempty"`
|
||||
}
|
||||
@@ -215,10 +215,9 @@ type InboundECHOptions struct {
|
||||
}
|
||||
|
||||
type OutboundECHOptions struct {
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
Config badoption.Listable[string] `json:"config,omitempty"`
|
||||
ConfigPath string `json:"config_path,omitempty"`
|
||||
QueryServerName string `json:"query_server_name,omitempty"`
|
||||
Enabled bool `json:"enabled,omitempty"`
|
||||
Config badoption.Listable[string] `json:"config,omitempty"`
|
||||
ConfigPath string `json:"config_path,omitempty"`
|
||||
|
||||
// Deprecated: not supported by stdlib
|
||||
PQSignatureSchemesEnabled bool `json:"pq_signature_schemes_enabled,omitempty"`
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user