mirror of
https://github.com/SagerNet/sing-box.git
synced 2026-04-13 20:28:32 +10:00
Compare commits
9 Commits
dev-ts
...
v1.10.0-al
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c646fd6b2c | ||
|
|
468d78da49 | ||
|
|
61705e8a93 | ||
|
|
f62add5954 | ||
|
|
72ee3b35ae | ||
|
|
aa2975474f | ||
|
|
c82f460d95 | ||
|
|
8ec7c239cd | ||
|
|
8b2792df40 |
599
.github/workflows/build.yml
vendored
599
.github/workflows/build.yml
vendored
@@ -1,599 +0,0 @@
|
|||||||
name: Build
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
version:
|
|
||||||
description: "Version name"
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
build:
|
|
||||||
description: "Build type"
|
|
||||||
required: true
|
|
||||||
type: choice
|
|
||||||
default: "All"
|
|
||||||
options:
|
|
||||||
- All
|
|
||||||
- Binary
|
|
||||||
- Android
|
|
||||||
- Apple
|
|
||||||
- app-store
|
|
||||||
- iOS
|
|
||||||
- macOS
|
|
||||||
- tvOS
|
|
||||||
- macOS-standalone
|
|
||||||
- publish-android
|
|
||||||
push:
|
|
||||||
branches:
|
|
||||||
- main-next
|
|
||||||
- dev-next
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event_name }}-${{ inputs.build }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
calculate_version:
|
|
||||||
name: Calculate version
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
outputs:
|
|
||||||
version: ${{ steps.outputs.outputs.version }}
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: ^1.23
|
|
||||||
- name: Check input version
|
|
||||||
if: github.event_name == 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
echo "version=${{ inputs.version }}"
|
|
||||||
echo "version=${{ inputs.version }}" >> "$GITHUB_ENV"
|
|
||||||
- name: Calculate version
|
|
||||||
if: github.event_name != 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/read_tag --nightly
|
|
||||||
- name: Set outputs
|
|
||||||
id: outputs
|
|
||||||
run: |-
|
|
||||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
|
||||||
build:
|
|
||||||
name: Build binary
|
|
||||||
if: github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Binary'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- calculate_version
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- name: linux_386
|
|
||||||
goos: linux
|
|
||||||
goarch: 386
|
|
||||||
- name: linux_amd64
|
|
||||||
goos: linux
|
|
||||||
goarch: amd64
|
|
||||||
- name: linux_arm64
|
|
||||||
goos: linux
|
|
||||||
goarch: arm64
|
|
||||||
- name: linux_arm
|
|
||||||
goos: linux
|
|
||||||
goarch: arm
|
|
||||||
goarm: 6
|
|
||||||
- name: linux_arm_v7
|
|
||||||
goos: linux
|
|
||||||
goarch: arm
|
|
||||||
goarm: 7
|
|
||||||
- name: linux_s390x
|
|
||||||
goos: linux
|
|
||||||
goarch: s390x
|
|
||||||
- name: linux_riscv64
|
|
||||||
goos: linux
|
|
||||||
goarch: riscv64
|
|
||||||
- name: linux_mips64le
|
|
||||||
goos: linux
|
|
||||||
goarch: mips64le
|
|
||||||
- name: windows_amd64
|
|
||||||
goos: windows
|
|
||||||
goarch: amd64
|
|
||||||
require_legacy_go: true
|
|
||||||
- name: windows_386
|
|
||||||
goos: windows
|
|
||||||
goarch: 386
|
|
||||||
require_legacy_go: true
|
|
||||||
- name: windows_arm64
|
|
||||||
goos: windows
|
|
||||||
goarch: arm64
|
|
||||||
- name: darwin_arm64
|
|
||||||
goos: darwin
|
|
||||||
goarch: arm64
|
|
||||||
- name: darwin_amd64
|
|
||||||
goos: darwin
|
|
||||||
goarch: amd64
|
|
||||||
require_legacy_go: true
|
|
||||||
- name: android_arm64
|
|
||||||
goos: android
|
|
||||||
goarch: arm64
|
|
||||||
- name: android_arm
|
|
||||||
goos: android
|
|
||||||
goarch: arm
|
|
||||||
goarm: 7
|
|
||||||
- name: android_amd64
|
|
||||||
goos: android
|
|
||||||
goarch: amd64
|
|
||||||
- name: android_386
|
|
||||||
goos: android
|
|
||||||
goarch: 386
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: ^1.23
|
|
||||||
- name: Cache legacy Go
|
|
||||||
if: matrix.require_legacy_go
|
|
||||||
id: cache-legacy-go
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/go/go1.20.14
|
|
||||||
key: go120
|
|
||||||
- name: Setup legacy Go
|
|
||||||
if: matrix.require_legacy_go == 'true' && steps.cache-legacy-go.outputs.cache-hit != 'true'
|
|
||||||
run: |-
|
|
||||||
wget https://dl.google.com/go/go1.20.14.linux-amd64.tar.gz
|
|
||||||
tar -xzf go1.20.14.linux-amd64.tar.gz
|
|
||||||
mv go $HOME/go/go1.20.14
|
|
||||||
- name: Setup Android NDK
|
|
||||||
if: matrix.goos == 'android'
|
|
||||||
uses: nttld/setup-ndk@v1
|
|
||||||
with:
|
|
||||||
ndk-version: r28-beta2
|
|
||||||
local-cache: true
|
|
||||||
- name: Setup Goreleaser
|
|
||||||
uses: goreleaser/goreleaser-action@v6
|
|
||||||
with:
|
|
||||||
distribution: goreleaser-pro
|
|
||||||
version: latest
|
|
||||||
install-only: true
|
|
||||||
- name: Extract signing key
|
|
||||||
run: |-
|
|
||||||
mkdir -p $HOME/.gnupg
|
|
||||||
cat > $HOME/.gnupg/sagernet.key <<EOF
|
|
||||||
${{ secrets.GPG_KEY }}
|
|
||||||
EOF
|
|
||||||
echo "HOME=$HOME" >> "$GITHUB_ENV"
|
|
||||||
- name: Set tag
|
|
||||||
run: |-
|
|
||||||
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.goos != 'android'
|
|
||||||
run: |-
|
|
||||||
goreleaser release --clean --split
|
|
||||||
env:
|
|
||||||
GOOS: ${{ matrix.goos }}
|
|
||||||
GOARCH: ${{ matrix.goarch }}
|
|
||||||
GOPATH: ${{ env.HOME }}/go
|
|
||||||
GOARM: ${{ matrix.goarm }}
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
|
||||||
NFPM_KEY_PATH: ${{ env.HOME }}/.gnupg/sagernet.key
|
|
||||||
NFPM_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
|
|
||||||
- name: Build Android
|
|
||||||
if: matrix.goos == 'android'
|
|
||||||
run: |-
|
|
||||||
go install -v ./cmd/internal/build
|
|
||||||
GOOS=$BUILD_GOOS GOARCH=$BUILD_GOARCH build goreleaser release --clean --split
|
|
||||||
env:
|
|
||||||
BUILD_GOOS: ${{ matrix.goos }}
|
|
||||||
BUILD_GOARCH: ${{ matrix.goarch }}
|
|
||||||
GOARM: ${{ matrix.goarm }}
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
|
||||||
NFPM_KEY_PATH: ${{ env.HOME }}/.gnupg/sagernet.key
|
|
||||||
NFPM_PASSPHRASE: ${{ secrets.GPG_PASSPHRASE }}
|
|
||||||
- name: Upload artifact
|
|
||||||
if: github.event_name == 'workflow_dispatch'
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: binary-${{ matrix.name }}
|
|
||||||
path: 'dist'
|
|
||||||
build_android:
|
|
||||||
name: Build Android
|
|
||||||
if: github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Android'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- calculate_version
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
submodules: 'recursive'
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: ^1.23
|
|
||||||
- name: Setup Android NDK
|
|
||||||
id: setup-ndk
|
|
||||||
uses: nttld/setup-ndk@v1
|
|
||||||
with:
|
|
||||||
ndk-version: r28-beta2
|
|
||||||
- name: Setup OpenJDK
|
|
||||||
run: |-
|
|
||||||
sudo apt update && sudo apt install -y openjdk-17-jdk-headless
|
|
||||||
/usr/lib/jvm/java-17-openjdk-amd64/bin/java --version
|
|
||||||
- name: Set tag
|
|
||||||
run: |-
|
|
||||||
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 library
|
|
||||||
run: |-
|
|
||||||
make lib_install
|
|
||||||
export PATH="$PATH:$(go env GOPATH)/bin"
|
|
||||||
make lib_android
|
|
||||||
env:
|
|
||||||
JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
- name: Checkout main branch
|
|
||||||
if: github.ref == 'refs/heads/main-next' && github.event_name != 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
cd clients/android
|
|
||||||
git checkout main
|
|
||||||
- name: Checkout dev branch
|
|
||||||
if: github.ref == 'refs/heads/dev-next'
|
|
||||||
run: |-
|
|
||||||
cd clients/android
|
|
||||||
git checkout dev
|
|
||||||
- name: Gradle cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.gradle
|
|
||||||
key: gradle-${{ hashFiles('**/*.gradle') }}
|
|
||||||
- name: Build
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/update_android_version --ci
|
|
||||||
mkdir clients/android/app/libs
|
|
||||||
cp libbox.aar clients/android/app/libs
|
|
||||||
cd clients/android
|
|
||||||
./gradlew :app:assemblePlayRelease :app:assembleOtherRelease
|
|
||||||
env:
|
|
||||||
JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
LOCAL_PROPERTIES: ${{ secrets.LOCAL_PROPERTIES }}
|
|
||||||
- name: Prepare upload
|
|
||||||
if: github.event_name == 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
mkdir -p dist/release
|
|
||||||
cp clients/android/app/build/outputs/apk/play/release/*.apk dist/release
|
|
||||||
cp clients/android/app/build/outputs/apk/other/release/*-universal.apk dist/release
|
|
||||||
- name: Upload artifact
|
|
||||||
if: github.event_name == 'workflow_dispatch'
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: binary-android-apks
|
|
||||||
path: 'dist'
|
|
||||||
publish_android:
|
|
||||||
name: Publish Android
|
|
||||||
if: github.event_name == 'workflow_dispatch' && inputs.build == 'publish-android'
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- calculate_version
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
submodules: 'recursive'
|
|
||||||
- name: Setup Go
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: ^1.23
|
|
||||||
- name: Setup Android NDK
|
|
||||||
id: setup-ndk
|
|
||||||
uses: nttld/setup-ndk@v1
|
|
||||||
with:
|
|
||||||
ndk-version: r28-beta2
|
|
||||||
- name: Setup OpenJDK
|
|
||||||
run: |-
|
|
||||||
sudo apt update && sudo apt install -y openjdk-17-jdk-headless
|
|
||||||
/usr/lib/jvm/java-17-openjdk-amd64/bin/java --version
|
|
||||||
- name: Set tag
|
|
||||||
run: |-
|
|
||||||
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 library
|
|
||||||
run: |-
|
|
||||||
make lib_install
|
|
||||||
export PATH="$PATH:$(go env GOPATH)/bin"
|
|
||||||
make lib_android
|
|
||||||
env:
|
|
||||||
JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
- name: Checkout main branch
|
|
||||||
if: github.ref == 'refs/heads/main-next' && github.event_name != 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
cd clients/android
|
|
||||||
git checkout main
|
|
||||||
- name: Checkout dev branch
|
|
||||||
if: github.ref == 'refs/heads/dev-next'
|
|
||||||
run: |-
|
|
||||||
cd clients/android
|
|
||||||
git checkout dev
|
|
||||||
- name: Gradle cache
|
|
||||||
uses: actions/cache@v4
|
|
||||||
with:
|
|
||||||
path: ~/.gradle
|
|
||||||
key: gradle-${{ hashFiles('**/*.gradle') }}
|
|
||||||
- name: Build
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/update_android_version --ci
|
|
||||||
mkdir clients/android/app/libs
|
|
||||||
cp libbox.aar clients/android/app/libs
|
|
||||||
cd clients/android
|
|
||||||
echo -n "$SERVICE_ACCOUNT_CREDENTIALS" | base64 --decode > service-account-credentials.json
|
|
||||||
./gradlew :app:publishPlayReleaseBundle
|
|
||||||
env:
|
|
||||||
JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
|
|
||||||
ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }}
|
|
||||||
LOCAL_PROPERTIES: ${{ secrets.LOCAL_PROPERTIES }}
|
|
||||||
SERVICE_ACCOUNT_CREDENTIALS: ${{ secrets.SERVICE_ACCOUNT_CREDENTIALS }}
|
|
||||||
build_apple:
|
|
||||||
name: Build Apple clients
|
|
||||||
runs-on: macos-15
|
|
||||||
needs:
|
|
||||||
- calculate_version
|
|
||||||
strategy:
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- name: iOS
|
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Apple' || inputs.build == 'app-store'|| inputs.build == 'iOS' }}
|
|
||||||
platform: ios
|
|
||||||
scheme: SFI
|
|
||||||
destination: 'generic/platform=iOS'
|
|
||||||
archive: build/SFI.xcarchive
|
|
||||||
upload: SFI/Upload.plist
|
|
||||||
- name: macOS
|
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Apple' || inputs.build == 'app-store'|| inputs.build == 'macOS' }}
|
|
||||||
platform: macos
|
|
||||||
scheme: SFM
|
|
||||||
destination: 'generic/platform=macOS'
|
|
||||||
archive: build/SFM.xcarchive
|
|
||||||
upload: SFI/Upload.plist
|
|
||||||
- name: tvOS
|
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Apple' || inputs.build == 'app-store'|| inputs.build == 'tvOS' }}
|
|
||||||
platform: tvos
|
|
||||||
scheme: SFT
|
|
||||||
destination: 'generic/platform=tvOS'
|
|
||||||
archive: build/SFT.xcarchive
|
|
||||||
upload: SFI/Upload.plist
|
|
||||||
- name: macOS-standalone
|
|
||||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Apple' || inputs.build == 'macOS-standalone' }}
|
|
||||||
platform: macos
|
|
||||||
scheme: SFM.System
|
|
||||||
destination: 'generic/platform=macOS'
|
|
||||||
archive: build/SFM.System.xcarchive
|
|
||||||
export: SFM.System/Export.plist
|
|
||||||
export_path: build/SFM.System
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
if: matrix.if
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
submodules: 'recursive'
|
|
||||||
- name: Setup Go
|
|
||||||
if: matrix.if
|
|
||||||
uses: actions/setup-go@v5
|
|
||||||
with:
|
|
||||||
go-version: ^1.23
|
|
||||||
- name: Setup Xcode stable
|
|
||||||
if: matrix.if && github.ref == 'refs/heads/main-next'
|
|
||||||
run: |-
|
|
||||||
sudo xcode-select -s /Applications/Xcode_16.2.app
|
|
||||||
- name: Setup Xcode beta
|
|
||||||
if: matrix.if && github.ref == 'refs/heads/dev-next'
|
|
||||||
run: |-
|
|
||||||
sudo xcode-select -s /Applications/Xcode_16.2.app
|
|
||||||
- name: Set tag
|
|
||||||
if: matrix.if
|
|
||||||
run: |-
|
|
||||||
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
|
|
||||||
echo "VERSION=${{ needs.calculate_version.outputs.version }}" >> "$GITHUB_ENV"
|
|
||||||
- name: Checkout main branch
|
|
||||||
if: matrix.if && github.ref == 'refs/heads/main-next' && github.event_name != 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
cd clients/apple
|
|
||||||
git checkout main
|
|
||||||
- name: Checkout dev branch
|
|
||||||
if: matrix.if && github.ref == 'refs/heads/dev-next'
|
|
||||||
run: |-
|
|
||||||
cd clients/apple
|
|
||||||
git checkout dev
|
|
||||||
- name: Setup certificates
|
|
||||||
if: matrix.if
|
|
||||||
run: |-
|
|
||||||
CERTIFICATE_PATH=$RUNNER_TEMP/Certificates.p12
|
|
||||||
KEYCHAIN_PATH=$RUNNER_TEMP/certificates.keychain-db
|
|
||||||
echo -n "$CERTIFICATES_P12" | base64 --decode -o $CERTIFICATE_PATH
|
|
||||||
security create-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
|
||||||
security set-keychain-settings -lut 21600 $KEYCHAIN_PATH
|
|
||||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
|
||||||
security import $CERTIFICATE_PATH -P "$P12_PASSWORD" -A -t cert -f pkcs12 -k $KEYCHAIN_PATH
|
|
||||||
security set-key-partition-list -S apple-tool:,apple: -k "$KEYCHAIN_PASSWORD" $KEYCHAIN_PATH
|
|
||||||
security list-keychain -d user -s $KEYCHAIN_PATH
|
|
||||||
|
|
||||||
PROFILES_ZIP_PATH=$RUNNER_TEMP/Profiles.zip
|
|
||||||
echo -n "$PROVISIONING_PROFILES" | base64 --decode -o $PROFILES_ZIP_PATH
|
|
||||||
|
|
||||||
PROFILES_PATH="$HOME/Library/MobileDevice/Provisioning Profiles"
|
|
||||||
mkdir -p "$PROFILES_PATH"
|
|
||||||
unzip $PROFILES_ZIP_PATH -d "$PROFILES_PATH"
|
|
||||||
|
|
||||||
ASC_KEY_PATH=$RUNNER_TEMP/Key.p12
|
|
||||||
echo -n "$ASC_KEY" | base64 --decode -o $ASC_KEY_PATH
|
|
||||||
|
|
||||||
xcrun notarytool store-credentials "notarytool-password" \
|
|
||||||
--key $ASC_KEY_PATH \
|
|
||||||
--key-id $ASC_KEY_ID \
|
|
||||||
--issuer $ASC_KEY_ISSUER_ID
|
|
||||||
|
|
||||||
echo "ASC_KEY_PATH=$ASC_KEY_PATH" >> "$GITHUB_ENV"
|
|
||||||
echo "ASC_KEY_ID=$ASC_KEY_ID" >> "$GITHUB_ENV"
|
|
||||||
echo "ASC_KEY_ISSUER_ID=$ASC_KEY_ISSUER_ID" >> "$GITHUB_ENV"
|
|
||||||
env:
|
|
||||||
CERTIFICATES_P12: ${{ secrets.CERTIFICATES_P12 }}
|
|
||||||
P12_PASSWORD: ${{ secrets.P12_PASSWORD }}
|
|
||||||
KEYCHAIN_PASSWORD: ${{ secrets.P12_PASSWORD }}
|
|
||||||
PROVISIONING_PROFILES: ${{ secrets.PROVISIONING_PROFILES }}
|
|
||||||
ASC_KEY: ${{ secrets.ASC_KEY }}
|
|
||||||
ASC_KEY_ID: ${{ secrets.ASC_KEY_ID }}
|
|
||||||
ASC_KEY_ISSUER_ID: ${{ secrets.ASC_KEY_ISSUER_ID }}
|
|
||||||
- name: Build library
|
|
||||||
if: matrix.if
|
|
||||||
run: |-
|
|
||||||
make lib_install
|
|
||||||
export PATH="$PATH:$(go env GOPATH)/bin"
|
|
||||||
go run ./cmd/internal/build_libbox -target apple -platform ${{ matrix.platform }}
|
|
||||||
mv Libbox.xcframework clients/apple
|
|
||||||
- name: Update macOS version
|
|
||||||
if: matrix.if && matrix.name == 'macOS' && github.event_name == 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
MACOS_PROJECT_VERSION=$(go run -v ./cmd/internal/app_store_connect next_macos_project_version)
|
|
||||||
echo "MACOS_PROJECT_VERSION=$MACOS_PROJECT_VERSION"
|
|
||||||
echo "MACOS_PROJECT_VERSION=$MACOS_PROJECT_VERSION" >> "$GITHUB_ENV"
|
|
||||||
- name: Build
|
|
||||||
if: matrix.if
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/update_apple_version --ci
|
|
||||||
cd clients/apple
|
|
||||||
xcodebuild archive \
|
|
||||||
-scheme "${{ matrix.scheme }}" \
|
|
||||||
-configuration Release \
|
|
||||||
-destination "${{ matrix.destination }}" \
|
|
||||||
-archivePath "${{ matrix.archive }}" \
|
|
||||||
-allowProvisioningUpdates \
|
|
||||||
-authenticationKeyPath $ASC_KEY_PATH \
|
|
||||||
-authenticationKeyID $ASC_KEY_ID \
|
|
||||||
-authenticationKeyIssuerID $ASC_KEY_ISSUER_ID
|
|
||||||
- name: Upload to App Store Connect
|
|
||||||
if: matrix.if && matrix.name != 'macOS-standalone' && github.event_name == 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/app_store_connect cancel_app_store ${{ matrix.platform }}
|
|
||||||
cd clients/apple
|
|
||||||
xcodebuild -exportArchive \
|
|
||||||
-archivePath "${{ matrix.archive }}" \
|
|
||||||
-exportOptionsPlist ${{ matrix.upload }} \
|
|
||||||
-allowProvisioningUpdates \
|
|
||||||
-authenticationKeyPath $ASC_KEY_PATH \
|
|
||||||
-authenticationKeyID $ASC_KEY_ID \
|
|
||||||
-authenticationKeyIssuerID $ASC_KEY_ISSUER_ID
|
|
||||||
- name: Publish to TestFlight
|
|
||||||
if: matrix.if && matrix.name != 'macOS-standalone' && github.event_name == 'workflow_dispatch' && github.ref =='refs/heads/dev-next'
|
|
||||||
run: |-
|
|
||||||
go run -v ./cmd/internal/app_store_connect publish_testflight ${{ matrix.platform }}
|
|
||||||
- name: Build image
|
|
||||||
if: matrix.if && matrix.name == 'macOS-standalone' && github.event_name == 'workflow_dispatch'
|
|
||||||
run: |-
|
|
||||||
pushd clients/apple
|
|
||||||
xcodebuild -exportArchive \
|
|
||||||
-archivePath "${{ matrix.archive }}" \
|
|
||||||
-exportOptionsPlist ${{ matrix.export }} \
|
|
||||||
-exportPath "${{ matrix.export_path }}"
|
|
||||||
brew install create-dmg
|
|
||||||
create-dmg \
|
|
||||||
--volname "sing-box" \
|
|
||||||
--volicon "${{ matrix.export_path }}/SFM.app/Contents/Resources/AppIcon.icns" \
|
|
||||||
--icon "SFM.app" 0 0 \
|
|
||||||
--hide-extension "SFM.app" \
|
|
||||||
--app-drop-link 0 0 \
|
|
||||||
--skip-jenkins \
|
|
||||||
SFM.dmg "${{ matrix.export_path }}/SFM.app"
|
|
||||||
xcrun notarytool submit "SFM.dmg" --wait --keychain-profile "notarytool-password"
|
|
||||||
cd "${{ matrix.archive }}"
|
|
||||||
zip -r SFM.dSYMs.zip dSYMs
|
|
||||||
popd
|
|
||||||
|
|
||||||
mkdir -p dist/release
|
|
||||||
cp clients/apple/SFM.dmg "dist/release/SFM-${VERSION}-universal.dmg"
|
|
||||||
cp "clients/apple/${{ matrix.archive }}/SFM.dSYMs.zip" "dist/release/SFM-${VERSION}-universal.dSYMs.zip"
|
|
||||||
- name: Upload image
|
|
||||||
if: matrix.if && matrix.name == 'macOS-standalone' && github.event_name == 'workflow_dispatch'
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: binary-macos-dmg
|
|
||||||
path: 'dist'
|
|
||||||
upload:
|
|
||||||
name: Upload builds
|
|
||||||
if: always() && github.event_name == 'workflow_dispatch' && (inputs.build == 'All' || inputs.build == 'Binary' || inputs.build == 'Android' || inputs.build == 'Apple' || inputs.build == 'macOS-standalone')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- calculate_version
|
|
||||||
- build
|
|
||||||
- build_android
|
|
||||||
- build_apple
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Setup Goreleaser
|
|
||||||
uses: goreleaser/goreleaser-action@v6
|
|
||||||
with:
|
|
||||||
distribution: goreleaser-pro
|
|
||||||
version: latest
|
|
||||||
install-only: true
|
|
||||||
- name: Cache ghr
|
|
||||||
uses: actions/cache@v4
|
|
||||||
id: cache-ghr
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
~/go/bin/ghr
|
|
||||||
key: ghr
|
|
||||||
- name: Setup ghr
|
|
||||||
if: steps.cache-ghr.outputs.cache-hit != 'true'
|
|
||||||
run: |-
|
|
||||||
cd $HOME
|
|
||||||
git clone https://github.com/nekohasekai/ghr ghr
|
|
||||||
cd ghr
|
|
||||||
go install -v .
|
|
||||||
- name: Set tag
|
|
||||||
run: |-
|
|
||||||
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
|
|
||||||
echo "VERSION=${{ needs.calculate_version.outputs.version }}" >> "$GITHUB_ENV"
|
|
||||||
- name: Download builds
|
|
||||||
uses: actions/download-artifact@v4
|
|
||||||
with:
|
|
||||||
path: dist
|
|
||||||
merge-multiple: true
|
|
||||||
- name: Merge builds
|
|
||||||
if: github.event_name != 'workflow_dispatch' || inputs.build == 'All' || inputs.build == 'Binary'
|
|
||||||
run: |-
|
|
||||||
goreleaser continue --merge --skip publish
|
|
||||||
mkdir -p dist/release
|
|
||||||
mv dist/*/sing-box*{tar.gz,zip,deb,rpm,_amd64.pkg.tar.zst,_arm64.pkg.tar.zst} dist/release
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}
|
|
||||||
- name: Upload builds
|
|
||||||
if: ${{ env.PUBLISHED == 'false' }}
|
|
||||||
run: |-
|
|
||||||
export PATH="$PATH:$HOME/go/bin"
|
|
||||||
ghr --replace --draft --prerelease -p 5 "v${VERSION}" dist/release
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: Replace builds
|
|
||||||
if: ${{ env.PUBLISHED != 'false' }}
|
|
||||||
run: |-
|
|
||||||
export PATH="$PATH:$HOME/go/bin"
|
|
||||||
ghr --replace -p 5 "v${VERSION}" dist/release
|
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
200
.github/workflows/debug.yml
vendored
Normal file
200
.github/workflows/debug.yml
vendored
Normal file
@@ -0,0 +1,200 @@
|
|||||||
|
name: Debug build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches:
|
||||||
|
- stable-next
|
||||||
|
- main-next
|
||||||
|
- dev-next
|
||||||
|
paths-ignore:
|
||||||
|
- '**.md'
|
||||||
|
- '.github/**'
|
||||||
|
- '!.github/workflows/debug.yml'
|
||||||
|
pull_request:
|
||||||
|
branches:
|
||||||
|
- stable-next
|
||||||
|
- main-next
|
||||||
|
- dev-next
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Debug build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ^1.22
|
||||||
|
continue-on-error: true
|
||||||
|
- name: Run Test
|
||||||
|
run: |
|
||||||
|
go test -v ./...
|
||||||
|
build_go120:
|
||||||
|
name: Debug build (Go 1.20)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ~1.20
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/go/pkg/mod
|
||||||
|
key: go120-${{ hashFiles('**/go.sum') }}
|
||||||
|
- name: Run Test
|
||||||
|
run: make ci_build_go120
|
||||||
|
build_go121:
|
||||||
|
name: Debug build (Go 1.21)
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ~1.21
|
||||||
|
- name: Cache go module
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/go/pkg/mod
|
||||||
|
key: go121-${{ hashFiles('**/go.sum') }}
|
||||||
|
- name: Run Test
|
||||||
|
run: make ci_build
|
||||||
|
cross:
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
# windows
|
||||||
|
- name: windows-amd64
|
||||||
|
goos: windows
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v1
|
||||||
|
- name: windows-amd64-v3
|
||||||
|
goos: windows
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v3
|
||||||
|
- name: windows-386
|
||||||
|
goos: windows
|
||||||
|
goarch: 386
|
||||||
|
- name: windows-arm64
|
||||||
|
goos: windows
|
||||||
|
goarch: arm64
|
||||||
|
- name: windows-arm32v7
|
||||||
|
goos: windows
|
||||||
|
goarch: arm
|
||||||
|
goarm: 7
|
||||||
|
|
||||||
|
# linux
|
||||||
|
- name: linux-amd64
|
||||||
|
goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v1
|
||||||
|
- name: linux-amd64-v3
|
||||||
|
goos: linux
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v3
|
||||||
|
- name: linux-386
|
||||||
|
goos: linux
|
||||||
|
goarch: 386
|
||||||
|
- name: linux-arm64
|
||||||
|
goos: linux
|
||||||
|
goarch: arm64
|
||||||
|
- name: linux-armv5
|
||||||
|
goos: linux
|
||||||
|
goarch: arm
|
||||||
|
goarm: 5
|
||||||
|
- name: linux-armv6
|
||||||
|
goos: linux
|
||||||
|
goarch: arm
|
||||||
|
goarm: 6
|
||||||
|
- name: linux-armv7
|
||||||
|
goos: linux
|
||||||
|
goarch: arm
|
||||||
|
goarm: 7
|
||||||
|
- name: linux-mips-softfloat
|
||||||
|
goos: linux
|
||||||
|
goarch: mips
|
||||||
|
gomips: softfloat
|
||||||
|
- name: linux-mips-hardfloat
|
||||||
|
goos: linux
|
||||||
|
goarch: mips
|
||||||
|
gomips: hardfloat
|
||||||
|
- name: linux-mipsel-softfloat
|
||||||
|
goos: linux
|
||||||
|
goarch: mipsle
|
||||||
|
gomips: softfloat
|
||||||
|
- name: linux-mipsel-hardfloat
|
||||||
|
goos: linux
|
||||||
|
goarch: mipsle
|
||||||
|
gomips: hardfloat
|
||||||
|
- name: linux-mips64
|
||||||
|
goos: linux
|
||||||
|
goarch: mips64
|
||||||
|
- name: linux-mips64el
|
||||||
|
goos: linux
|
||||||
|
goarch: mips64le
|
||||||
|
- name: linux-s390x
|
||||||
|
goos: linux
|
||||||
|
goarch: s390x
|
||||||
|
# darwin
|
||||||
|
- name: darwin-amd64
|
||||||
|
goos: darwin
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v1
|
||||||
|
- name: darwin-amd64-v3
|
||||||
|
goos: darwin
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v3
|
||||||
|
- name: darwin-arm64
|
||||||
|
goos: darwin
|
||||||
|
goarch: arm64
|
||||||
|
# freebsd
|
||||||
|
- name: freebsd-amd64
|
||||||
|
goos: freebsd
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v1
|
||||||
|
- name: freebsd-amd64-v3
|
||||||
|
goos: freebsd
|
||||||
|
goarch: amd64
|
||||||
|
goamd64: v3
|
||||||
|
- name: freebsd-386
|
||||||
|
goos: freebsd
|
||||||
|
goarch: 386
|
||||||
|
- name: freebsd-arm64
|
||||||
|
goos: freebsd
|
||||||
|
goarch: arm64
|
||||||
|
fail-fast: true
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
GOOS: ${{ matrix.goos }}
|
||||||
|
GOARCH: ${{ matrix.goarch }}
|
||||||
|
GOAMD64: ${{ matrix.goamd64 }}
|
||||||
|
GOARM: ${{ matrix.goarm }}
|
||||||
|
GOMIPS: ${{ matrix.gomips }}
|
||||||
|
CGO_ENABLED: 0
|
||||||
|
TAGS: with_clash_api,with_quic
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
- name: Setup Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: ^1.21
|
||||||
|
- name: Build
|
||||||
|
id: build
|
||||||
|
run: make
|
||||||
121
.github/workflows/docker.yml
vendored
121
.github/workflows/docker.yml
vendored
@@ -1,93 +1,16 @@
|
|||||||
name: Publish Docker Images
|
name: Build Docker Images
|
||||||
|
|
||||||
on:
|
on:
|
||||||
release:
|
release:
|
||||||
types:
|
types:
|
||||||
- published
|
- released
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
tag:
|
tag:
|
||||||
description: "The tag version you want to build"
|
description: "The tag version you want to build"
|
||||||
|
|
||||||
env:
|
|
||||||
REGISTRY_IMAGE: ghcr.io/sagernet/sing-box
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
strategy:
|
|
||||||
fail-fast: true
|
|
||||||
matrix:
|
|
||||||
platform:
|
|
||||||
- linux/amd64
|
|
||||||
- linux/arm/v6
|
|
||||||
- linux/arm/v7
|
|
||||||
- linux/arm64
|
|
||||||
- linux/386
|
|
||||||
- linux/ppc64le
|
|
||||||
- linux/riscv64
|
|
||||||
- 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@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
|
||||||
with:
|
|
||||||
ref: ${{ steps.ref.outputs.ref }}
|
|
||||||
fetch-depth: 0
|
|
||||||
- name: Prepare
|
|
||||||
run: |
|
|
||||||
platform=${{ matrix.platform }}
|
|
||||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
|
||||||
- name: Setup QEMU
|
|
||||||
uses: docker/setup-qemu-action@v3
|
|
||||||
- name: Setup Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
- name: Login to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v3
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{ github.repository_owner }}
|
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
- name: Docker meta
|
|
||||||
id: meta
|
|
||||||
uses: docker/metadata-action@v5
|
|
||||||
with:
|
|
||||||
images: ${{ env.REGISTRY_IMAGE }}
|
|
||||||
- name: Build and push by digest
|
|
||||||
id: build
|
|
||||||
uses: docker/build-push-action@v6
|
|
||||||
with:
|
|
||||||
platforms: ${{ matrix.platform }}
|
|
||||||
context: .
|
|
||||||
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
|
|
||||||
run: |
|
|
||||||
mkdir -p /tmp/digests
|
|
||||||
digest="${{ steps.build.outputs.digest }}"
|
|
||||||
touch "/tmp/digests/${digest#sha256:}"
|
|
||||||
- name: Upload digest
|
|
||||||
uses: actions/upload-artifact@v4
|
|
||||||
with:
|
|
||||||
name: digests-${{ env.PLATFORM_PAIR }}
|
|
||||||
path: /tmp/digests/*
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 1
|
|
||||||
merge:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
needs:
|
|
||||||
- build
|
|
||||||
steps:
|
steps:
|
||||||
- name: Get commit to build
|
- name: Get commit to build
|
||||||
id: ref
|
id: ref
|
||||||
@@ -106,28 +29,34 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
echo "latest=$latest"
|
echo "latest=$latest"
|
||||||
echo "latest=$latest" >> $GITHUB_OUTPUT
|
echo "latest=$latest" >> $GITHUB_OUTPUT
|
||||||
- name: Download digests
|
- name: Checkout
|
||||||
uses: actions/download-artifact@v4
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
with:
|
with:
|
||||||
path: /tmp/digests
|
ref: ${{ steps.ref.outputs.ref }}
|
||||||
pattern: digests-*
|
- name: Setup Docker Buildx
|
||||||
merge-multiple: true
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
uses: docker/setup-buildx-action@v3
|
||||||
|
- name: Setup QEMU for Docker Buildx
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@v3
|
uses: docker/login-action@v3
|
||||||
with:
|
with:
|
||||||
registry: ghcr.io
|
registry: ghcr.io
|
||||||
username: ${{ github.repository_owner }}
|
username: ${{ github.repository_owner }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Create manifest list and push
|
- name: Docker metadata
|
||||||
working-directory: /tmp/digests
|
id: metadata
|
||||||
run: |
|
uses: docker/metadata-action@v5
|
||||||
docker buildx imagetools create \
|
with:
|
||||||
-t "${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.latest }}" \
|
images: ghcr.io/sagernet/sing-box
|
||||||
-t "${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.ref }}" \
|
- name: Build and release Docker images
|
||||||
$(printf '${{ env.REGISTRY_IMAGE }}@sha256:%s ' *)
|
uses: docker/build-push-action@v5
|
||||||
- name: Inspect image
|
with:
|
||||||
run: |
|
platforms: linux/386,linux/amd64,linux/arm64,linux/s390x
|
||||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.latest }}
|
context: .
|
||||||
docker buildx imagetools inspect ${{ env.REGISTRY_IMAGE }}:${{ steps.ref.outputs.ref }}
|
target: dist
|
||||||
|
build-args: |
|
||||||
|
BUILDKIT_CONTEXT_KEEP_GIT_DIR=1
|
||||||
|
tags: |
|
||||||
|
ghcr.io/sagernet/sing-box:${{ steps.ref.outputs.latest }}
|
||||||
|
ghcr.io/sagernet/sing-box:${{ steps.ref.outputs.ref }}
|
||||||
|
push: true
|
||||||
|
|||||||
4
.github/workflows/lint.yml
vendored
4
.github/workflows/lint.yml
vendored
@@ -22,13 +22,13 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ^1.23
|
go-version: ^1.22
|
||||||
- name: golangci-lint
|
- name: golangci-lint
|
||||||
uses: golangci/golangci-lint-action@v6
|
uses: golangci/golangci-lint-action@v6
|
||||||
with:
|
with:
|
||||||
|
|||||||
5
.github/workflows/linux.yml
vendored
5
.github/workflows/linux.yml
vendored
@@ -10,18 +10,19 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@eef61447b9ff4aafe5dcd4e0bbf5d482be7e7871 # v4
|
uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
- name: Setup Go
|
- name: Setup Go
|
||||||
uses: actions/setup-go@v5
|
uses: actions/setup-go@v5
|
||||||
with:
|
with:
|
||||||
go-version: ^1.23
|
go-version: ^1.22
|
||||||
- name: Extract signing key
|
- name: Extract signing key
|
||||||
run: |-
|
run: |-
|
||||||
mkdir -p $HOME/.gnupg
|
mkdir -p $HOME/.gnupg
|
||||||
cat > $HOME/.gnupg/sagernet.key <<EOF
|
cat > $HOME/.gnupg/sagernet.key <<EOF
|
||||||
${{ secrets.GPG_KEY }}
|
${{ secrets.GPG_KEY }}
|
||||||
|
echo "HOME=$HOME" >> "$GITHUB_ENV"
|
||||||
EOF
|
EOF
|
||||||
echo "HOME=$HOME" >> "$GITHUB_ENV"
|
echo "HOME=$HOME" >> "$GITHUB_ENV"
|
||||||
- name: Publish release
|
- name: Publish release
|
||||||
|
|||||||
3
.github/workflows/stale.yml
vendored
3
.github/workflows/stale.yml
vendored
@@ -12,5 +12,4 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
stale-issue-message: 'This issue is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 5 days'
|
||||||
days-before-stale: 60
|
days-before-stale: 60
|
||||||
days-before-close: 5
|
days-before-close: 5
|
||||||
exempt-issue-labels: 'bug,enhancement'
|
|
||||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -14,5 +14,3 @@
|
|||||||
/*.xcframework/
|
/*.xcframework/
|
||||||
.DS_Store
|
.DS_Store
|
||||||
/config.d/
|
/config.d/
|
||||||
/venv/
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,14 @@ linters:
|
|||||||
- gci
|
- gci
|
||||||
- staticcheck
|
- staticcheck
|
||||||
- paralleltest
|
- paralleltest
|
||||||
- ineffassign
|
|
||||||
|
run:
|
||||||
|
skip-dirs:
|
||||||
|
- transport/simple-obfs
|
||||||
|
- transport/clashssr
|
||||||
|
- transport/cloudflaretls
|
||||||
|
- transport/shadowtls/tls
|
||||||
|
- transport/shadowtls/tls_go119
|
||||||
|
|
||||||
linters-settings:
|
linters-settings:
|
||||||
gci:
|
gci:
|
||||||
@@ -16,24 +23,4 @@ linters-settings:
|
|||||||
- prefix(github.com/sagernet/)
|
- prefix(github.com/sagernet/)
|
||||||
- default
|
- default
|
||||||
staticcheck:
|
staticcheck:
|
||||||
checks:
|
go: '1.20'
|
||||||
- all
|
|
||||||
- -SA1003
|
|
||||||
|
|
||||||
run:
|
|
||||||
go: "1.23"
|
|
||||||
build-tags:
|
|
||||||
- with_gvisor
|
|
||||||
- with_quic
|
|
||||||
- with_dhcp
|
|
||||||
- with_wireguard
|
|
||||||
- with_ech
|
|
||||||
- with_utls
|
|
||||||
- with_reality_server
|
|
||||||
- with_acme
|
|
||||||
- with_clash_api
|
|
||||||
- badlinkname
|
|
||||||
|
|
||||||
issues:
|
|
||||||
exclude-dirs:
|
|
||||||
- transport/simple-obfs
|
|
||||||
|
|||||||
@@ -6,10 +6,7 @@ builds:
|
|||||||
- -v
|
- -v
|
||||||
- -trimpath
|
- -trimpath
|
||||||
ldflags:
|
ldflags:
|
||||||
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }}
|
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }} -s -w -buildid=
|
||||||
- -s
|
|
||||||
- -buildid=
|
|
||||||
- -checklinkname=0
|
|
||||||
tags:
|
tags:
|
||||||
- with_gvisor
|
- with_gvisor
|
||||||
- with_quic
|
- with_quic
|
||||||
@@ -29,7 +26,6 @@ builds:
|
|||||||
- linux_arm_7
|
- linux_arm_7
|
||||||
- linux_s390x
|
- linux_s390x
|
||||||
- linux_riscv64
|
- linux_riscv64
|
||||||
- linux_mips64le
|
|
||||||
mod_timestamp: '{{ .CommitTimestamp }}'
|
mod_timestamp: '{{ .CommitTimestamp }}'
|
||||||
snapshot:
|
snapshot:
|
||||||
name_template: "{{ .Version }}.{{ .ShortCommit }}"
|
name_template: "{{ .Version }}.{{ .ShortCommit }}"
|
||||||
@@ -52,19 +48,10 @@ nfpms:
|
|||||||
- src: release/config/config.json
|
- src: release/config/config.json
|
||||||
dst: /etc/sing-box/config.json
|
dst: /etc/sing-box/config.json
|
||||||
type: config
|
type: config
|
||||||
|
|
||||||
- src: release/config/sing-box.service
|
- src: release/config/sing-box.service
|
||||||
dst: /usr/lib/systemd/system/sing-box.service
|
dst: /usr/lib/systemd/system/sing-box.service
|
||||||
- src: release/config/sing-box@.service
|
- src: release/config/sing-box@.service
|
||||||
dst: /usr/lib/systemd/system/sing-box@.service
|
dst: /usr/lib/systemd/system/sing-box@.service
|
||||||
|
|
||||||
- src: release/completions/sing-box.bash
|
|
||||||
dst: /usr/share/bash-completion/completions/sing-box.bash
|
|
||||||
- src: release/completions/sing-box.fish
|
|
||||||
dst: /usr/share/fish/vendor_completions.d/sing-box.fish
|
|
||||||
- src: release/completions/sing-box.zsh
|
|
||||||
dst: /usr/share/zsh/site-functions/_sing-box
|
|
||||||
|
|
||||||
- src: LICENSE
|
- src: LICENSE
|
||||||
dst: /usr/share/licenses/sing-box/LICENSE
|
dst: /usr/share/licenses/sing-box/LICENSE
|
||||||
deb:
|
deb:
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
version: 2
|
|
||||||
project_name: sing-box
|
project_name: sing-box
|
||||||
builds:
|
builds:
|
||||||
- &template
|
- &template
|
||||||
@@ -8,10 +7,7 @@ builds:
|
|||||||
- -v
|
- -v
|
||||||
- -trimpath
|
- -trimpath
|
||||||
ldflags:
|
ldflags:
|
||||||
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }}
|
- -X github.com/sagernet/sing-box/constant.Version={{ .Version }} -s -w -buildid=
|
||||||
- -s
|
|
||||||
- -buildid=
|
|
||||||
- -checklinkname=0
|
|
||||||
tags:
|
tags:
|
||||||
- with_gvisor
|
- with_gvisor
|
||||||
- with_quic
|
- with_quic
|
||||||
@@ -27,13 +23,13 @@ builds:
|
|||||||
targets:
|
targets:
|
||||||
- linux_386
|
- linux_386
|
||||||
- linux_amd64_v1
|
- linux_amd64_v1
|
||||||
|
- linux_amd64_v3
|
||||||
- linux_arm64
|
- linux_arm64
|
||||||
- linux_arm_6
|
|
||||||
- linux_arm_7
|
- linux_arm_7
|
||||||
- linux_s390x
|
- linux_s390x
|
||||||
- linux_riscv64
|
- linux_riscv64
|
||||||
- linux_mips64le
|
|
||||||
- windows_amd64_v1
|
- windows_amd64_v1
|
||||||
|
- windows_amd64_v3
|
||||||
- windows_386
|
- windows_386
|
||||||
- windows_arm64
|
- windows_arm64
|
||||||
- darwin_amd64_v1
|
- darwin_amd64_v1
|
||||||
@@ -90,6 +86,8 @@ builds:
|
|||||||
- android_arm64
|
- android_arm64
|
||||||
- android_386
|
- android_386
|
||||||
- android_amd64
|
- android_amd64
|
||||||
|
snapshot:
|
||||||
|
name_template: "{{ .Version }}.{{ .ShortCommit }}"
|
||||||
archives:
|
archives:
|
||||||
- &template
|
- &template
|
||||||
id: archive
|
id: archive
|
||||||
@@ -103,7 +101,7 @@ archives:
|
|||||||
wrap_in_directory: true
|
wrap_in_directory: true
|
||||||
files:
|
files:
|
||||||
- LICENSE
|
- LICENSE
|
||||||
name_template: '{{ .ProjectName }}-{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ if and .Mips (not (eq .Mips "hardfloat")) }}_{{ .Mips }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
|
name_template: '{{ .ProjectName }}-{{ .Version }}-{{ .Os }}-{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
|
||||||
- id: archive-legacy
|
- id: archive-legacy
|
||||||
<<: *template
|
<<: *template
|
||||||
builds:
|
builds:
|
||||||
@@ -112,7 +110,7 @@ archives:
|
|||||||
nfpms:
|
nfpms:
|
||||||
- id: package
|
- id: package
|
||||||
package_name: sing-box
|
package_name: sing-box
|
||||||
file_name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ if and .Mips (not (eq .Mips "hardfloat")) }}_{{ .Mips }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
|
file_name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ with .Arm }}v{{ . }}{{ end }}{{ with .Mips }}_{{ . }}{{ end }}{{ if not (eq .Amd64 "v1") }}{{ .Amd64 }}{{ end }}'
|
||||||
builds:
|
builds:
|
||||||
- main
|
- main
|
||||||
homepage: https://sing-box.sagernet.org/
|
homepage: https://sing-box.sagernet.org/
|
||||||
@@ -123,26 +121,15 @@ nfpms:
|
|||||||
- deb
|
- deb
|
||||||
- rpm
|
- rpm
|
||||||
- archlinux
|
- archlinux
|
||||||
# - apk
|
|
||||||
# - ipk
|
|
||||||
priority: extra
|
priority: extra
|
||||||
contents:
|
contents:
|
||||||
- src: release/config/config.json
|
- src: release/config/config.json
|
||||||
dst: /etc/sing-box/config.json
|
dst: /etc/sing-box/config.json
|
||||||
type: config
|
type: config
|
||||||
|
|
||||||
- src: release/config/sing-box.service
|
- src: release/config/sing-box.service
|
||||||
dst: /usr/lib/systemd/system/sing-box.service
|
dst: /usr/lib/systemd/system/sing-box.service
|
||||||
- src: release/config/sing-box@.service
|
- src: release/config/sing-box@.service
|
||||||
dst: /usr/lib/systemd/system/sing-box@.service
|
dst: /usr/lib/systemd/system/sing-box@.service
|
||||||
|
|
||||||
- src: release/completions/sing-box.bash
|
|
||||||
dst: /usr/share/bash-completion/completions/sing-box.bash
|
|
||||||
- src: release/completions/sing-box.fish
|
|
||||||
dst: /usr/share/fish/vendor_completions.d/sing-box.fish
|
|
||||||
- src: release/completions/sing-box.zsh
|
|
||||||
dst: /usr/share/zsh/site-functions/_sing-box
|
|
||||||
|
|
||||||
- src: LICENSE
|
- src: LICENSE
|
||||||
dst: /usr/share/licenses/sing-box/LICENSE
|
dst: /usr/share/licenses/sing-box/LICENSE
|
||||||
deb:
|
deb:
|
||||||
@@ -154,34 +141,13 @@ nfpms:
|
|||||||
signature:
|
signature:
|
||||||
key_file: "{{ .Env.NFPM_KEY_PATH }}"
|
key_file: "{{ .Env.NFPM_KEY_PATH }}"
|
||||||
overrides:
|
overrides:
|
||||||
apk:
|
deb:
|
||||||
contents:
|
conflicts:
|
||||||
- src: release/config/config.json
|
- sing-box-beta
|
||||||
dst: /etc/sing-box/config.json
|
rpm:
|
||||||
type: config
|
conflicts:
|
||||||
|
- sing-box-beta
|
||||||
|
|
||||||
- src: release/config/sing-box.initd
|
|
||||||
dst: /etc/init.d/sing-box
|
|
||||||
|
|
||||||
- src: release/completions/sing-box.bash
|
|
||||||
dst: /usr/share/bash-completion/completions/sing-box.bash
|
|
||||||
- src: release/completions/sing-box.fish
|
|
||||||
dst: /usr/share/fish/vendor_completions.d/sing-box.fish
|
|
||||||
- src: release/completions/sing-box.zsh
|
|
||||||
dst: /usr/share/zsh/site-functions/_sing-box
|
|
||||||
|
|
||||||
- src: LICENSE
|
|
||||||
dst: /usr/share/licenses/sing-box/LICENSE
|
|
||||||
ipk:
|
|
||||||
contents:
|
|
||||||
- src: release/config/config.json
|
|
||||||
dst: /etc/sing-box/config.json
|
|
||||||
type: config
|
|
||||||
|
|
||||||
- src: release/config/openwrt.init
|
|
||||||
dst: /etc/init.d/sing-box
|
|
||||||
- src: release/config/openwrt.conf
|
|
||||||
dst: /etc/config/sing-box
|
|
||||||
source:
|
source:
|
||||||
enabled: false
|
enabled: false
|
||||||
name_template: '{{ .ProjectName }}-{{ .Version }}.source'
|
name_template: '{{ .ProjectName }}-{{ .Version }}.source'
|
||||||
@@ -201,6 +167,4 @@ release:
|
|||||||
ids:
|
ids:
|
||||||
- archive
|
- archive
|
||||||
- package
|
- package
|
||||||
skip_upload: true
|
skip_upload: true
|
||||||
partial:
|
|
||||||
by: target
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS builder
|
FROM --platform=$BUILDPLATFORM golang:1.22-alpine AS builder
|
||||||
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
|
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
|
||||||
COPY . /go/src/github.com/sagernet/sing-box
|
COPY . /go/src/github.com/sagernet/sing-box
|
||||||
WORKDIR /go/src/github.com/sagernet/sing-box
|
WORKDIR /go/src/github.com/sagernet/sing-box
|
||||||
@@ -15,13 +15,13 @@ RUN set -ex \
|
|||||||
&& go build -v -trimpath -tags \
|
&& go build -v -trimpath -tags \
|
||||||
"with_gvisor,with_quic,with_dhcp,with_wireguard,with_ech,with_utls,with_reality_server,with_acme,with_clash_api" \
|
"with_gvisor,with_quic,with_dhcp,with_wireguard,with_ech,with_utls,with_reality_server,with_acme,with_clash_api" \
|
||||||
-o /go/bin/sing-box \
|
-o /go/bin/sing-box \
|
||||||
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=$VERSION\" -s -w -buildid= -checklinkname=0" \
|
-ldflags "-X \"github.com/sagernet/sing-box/constant.Version=$VERSION\" -s -w -buildid=" \
|
||||||
./cmd/sing-box
|
./cmd/sing-box
|
||||||
FROM --platform=$TARGETPLATFORM alpine AS dist
|
FROM --platform=$TARGETPLATFORM alpine AS dist
|
||||||
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
|
LABEL maintainer="nekohasekai <contact-git@sekai.icu>"
|
||||||
RUN set -ex \
|
RUN set -ex \
|
||||||
&& apk upgrade \
|
&& apk upgrade \
|
||||||
&& apk add bash tzdata ca-certificates nftables \
|
&& apk add bash tzdata ca-certificates \
|
||||||
&& rm -rf /var/cache/apk/*
|
&& rm -rf /var/cache/apk/*
|
||||||
COPY --from=builder /go/bin/sing-box /usr/local/bin/sing-box
|
COPY --from=builder /go/bin/sing-box /usr/local/bin/sing-box
|
||||||
ENTRYPOINT ["sing-box"]
|
ENTRYPOINT ["sing-box"]
|
||||||
|
|||||||
118
Makefile
118
Makefile
@@ -2,15 +2,14 @@ NAME = sing-box
|
|||||||
COMMIT = $(shell git rev-parse --short HEAD)
|
COMMIT = $(shell git rev-parse --short HEAD)
|
||||||
TAGS_GO120 = with_gvisor,with_dhcp,with_wireguard,with_reality_server,with_clash_api,with_quic,with_utls
|
TAGS_GO120 = with_gvisor,with_dhcp,with_wireguard,with_reality_server,with_clash_api,with_quic,with_utls
|
||||||
TAGS_GO121 = with_ech
|
TAGS_GO121 = with_ech
|
||||||
TAGS_GO123 = with_tailscale,badlinkname
|
TAGS ?= $(TAGS_GO118),$(TAGS_GO120),$(TAGS_GO121)
|
||||||
TAGS ?= $(TAGS_GO118),$(TAGS_GO120),$(TAGS_GO121),$(TAGS_GO123)
|
|
||||||
TAGS_TEST ?= with_gvisor,with_quic,with_wireguard,with_grpc,with_ech,with_utls,with_reality_server
|
TAGS_TEST ?= with_gvisor,with_quic,with_wireguard,with_grpc,with_ech,with_utls,with_reality_server
|
||||||
|
|
||||||
GOHOSTOS = $(shell go env GOHOSTOS)
|
GOHOSTOS = $(shell go env GOHOSTOS)
|
||||||
GOHOSTARCH = $(shell go env GOHOSTARCH)
|
GOHOSTARCH = $(shell go env GOHOSTARCH)
|
||||||
VERSION=$(shell CGO_ENABLED=0 GOOS=$(GOHOSTOS) GOARCH=$(GOHOSTARCH) go run ./cmd/internal/read_tag)
|
VERSION=$(shell CGO_ENABLED=0 GOOS=$(GOHOSTOS) GOARCH=$(GOHOSTARCH) go run ./cmd/internal/read_tag)
|
||||||
|
|
||||||
PARAMS = -v -trimpath -ldflags "-X 'github.com/sagernet/sing-box/constant.Version=$(VERSION)' -s -w -buildid= -checklinkname=0"
|
PARAMS = -v -trimpath -ldflags "-X 'github.com/sagernet/sing-box/constant.Version=$(VERSION)' -s -w -buildid="
|
||||||
MAIN_PARAMS = $(PARAMS) -tags $(TAGS)
|
MAIN_PARAMS = $(PARAMS) -tags $(TAGS)
|
||||||
MAIN = ./cmd/sing-box
|
MAIN = ./cmd/sing-box
|
||||||
PREFIX ?= $(shell go env GOPATH)
|
PREFIX ?= $(shell go env GOPATH)
|
||||||
@@ -28,9 +27,6 @@ ci_build:
|
|||||||
go build $(PARAMS) $(MAIN)
|
go build $(PARAMS) $(MAIN)
|
||||||
go build $(MAIN_PARAMS) $(MAIN)
|
go build $(MAIN_PARAMS) $(MAIN)
|
||||||
|
|
||||||
generate_completions:
|
|
||||||
go run -v --tags $(TAGS),generate,generate_completions $(MAIN)
|
|
||||||
|
|
||||||
install:
|
install:
|
||||||
go build -o $(PREFIX)/bin/$(NAME) $(MAIN_PARAMS) $(MAIN)
|
go build -o $(PREFIX)/bin/$(NAME) $(MAIN_PARAMS) $(MAIN)
|
||||||
|
|
||||||
@@ -70,9 +66,10 @@ release:
|
|||||||
dist/*.deb \
|
dist/*.deb \
|
||||||
dist/*.rpm \
|
dist/*.rpm \
|
||||||
dist/*_amd64.pkg.tar.zst \
|
dist/*_amd64.pkg.tar.zst \
|
||||||
|
dist/*_amd64v3.pkg.tar.zst \
|
||||||
dist/*_arm64.pkg.tar.zst \
|
dist/*_arm64.pkg.tar.zst \
|
||||||
dist/release
|
dist/release
|
||||||
ghr --replace --draft --prerelease -p 5 "v${VERSION}" dist/release
|
ghr --replace --draft --prerelease -p 3 "v${VERSION}" dist/release
|
||||||
rm -r dist/release
|
rm -r dist/release
|
||||||
|
|
||||||
release_repo:
|
release_repo:
|
||||||
@@ -91,21 +88,21 @@ upload_android:
|
|||||||
mkdir -p dist/release_android
|
mkdir -p dist/release_android
|
||||||
cp ../sing-box-for-android/app/build/outputs/apk/play/release/*.apk dist/release_android
|
cp ../sing-box-for-android/app/build/outputs/apk/play/release/*.apk dist/release_android
|
||||||
cp ../sing-box-for-android/app/build/outputs/apk/other/release/*-universal.apk dist/release_android
|
cp ../sing-box-for-android/app/build/outputs/apk/other/release/*-universal.apk dist/release_android
|
||||||
ghr --replace --draft --prerelease -p 5 "v${VERSION}" dist/release_android
|
ghr --replace --draft --prerelease -p 3 "v${VERSION}" dist/release_android
|
||||||
rm -rf dist/release_android
|
rm -rf dist/release_android
|
||||||
|
|
||||||
release_android: lib_android update_android_version build_android upload_android
|
release_android: lib_android update_android_version build_android upload_android
|
||||||
|
|
||||||
publish_android:
|
publish_android:
|
||||||
cd ../sing-box-for-android && ./gradlew :app:publishPlayReleaseBundle && ./gradlew --stop
|
cd ../sing-box-for-android && ./gradlew :app:publishPlayReleaseBundle
|
||||||
|
|
||||||
|
publish_android_appcenter:
|
||||||
|
cd ../sing-box-for-android && ./gradlew :app:appCenterAssembleAndUploadPlayRelease
|
||||||
|
|
||||||
# TODO: find why and remove `-destination 'generic/platform=iOS'`
|
|
||||||
# TODO: remove xcode clean when fix control widget fixed
|
|
||||||
build_ios:
|
build_ios:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
rm -rf build/SFI.xcarchive && \
|
rm -rf build/SFI.xcarchive && \
|
||||||
xcodebuild clean -scheme SFI && \
|
xcodebuild archive -scheme SFI -configuration Release -archivePath build/SFI.xcarchive
|
||||||
xcodebuild archive -scheme SFI -configuration Release -destination 'generic/platform=iOS' -archivePath build/SFI.xcarchive -allowProvisioningUpdates
|
|
||||||
|
|
||||||
upload_ios_app_store:
|
upload_ios_app_store:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
@@ -116,89 +113,58 @@ release_ios: build_ios upload_ios_app_store
|
|||||||
build_macos:
|
build_macos:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
rm -rf build/SFM.xcarchive && \
|
rm -rf build/SFM.xcarchive && \
|
||||||
xcodebuild archive -scheme SFM -configuration Release -archivePath build/SFM.xcarchive -allowProvisioningUpdates
|
xcodebuild archive -scheme SFM -configuration Release -archivePath build/SFM.xcarchive
|
||||||
|
|
||||||
upload_macos_app_store:
|
upload_macos_app_store:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
xcodebuild -exportArchive -archivePath build/SFM.xcarchive -exportOptionsPlist SFI/Upload.plist -allowProvisioningUpdates
|
xcodebuild -exportArchive -archivePath build/SFM.xcarchive -exportOptionsPlist SFI/Upload.plist -allowProvisioningUpdates
|
||||||
|
|
||||||
release_macos: build_macos upload_macos_app_store
|
release_macos: build_macos upload_macos_app_store
|
||||||
|
|
||||||
build_macos_standalone:
|
build_macos_independent:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
rm -rf build/SFM.System.xcarchive && \
|
rm -rf build/SFT.System.xcarchive && \
|
||||||
xcodebuild archive -scheme SFM.System -configuration Release -archivePath build/SFM.System.xcarchive -allowProvisioningUpdates
|
xcodebuild archive -scheme SFM.System -configuration Release -archivePath build/SFM.System.xcarchive
|
||||||
|
|
||||||
build_macos_dmg:
|
notarize_macos_independent:
|
||||||
|
cd ../sing-box-for-apple && \
|
||||||
|
xcodebuild -exportArchive -archivePath "build/SFM.System.xcarchive" -exportOptionsPlist SFM.System/Upload.plist -allowProvisioningUpdates
|
||||||
|
|
||||||
|
wait_notarize_macos_independent:
|
||||||
|
sleep 60
|
||||||
|
|
||||||
|
export_macos_independent:
|
||||||
rm -rf dist/SFM
|
rm -rf dist/SFM
|
||||||
mkdir -p dist/SFM
|
mkdir -p dist/SFM
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
rm -rf build/SFM.System && \
|
xcodebuild -exportNotarizedApp -archivePath build/SFM.System.xcarchive -exportPath "../sing-box/dist/SFM"
|
||||||
rm -rf build/SFM.dmg && \
|
|
||||||
xcodebuild -exportArchive \
|
|
||||||
-archivePath "build/SFM.System.xcarchive" \
|
|
||||||
-exportOptionsPlist SFM.System/Export.plist -allowProvisioningUpdates \
|
|
||||||
-exportPath "build/SFM.System" && \
|
|
||||||
create-dmg \
|
|
||||||
--volname "sing-box" \
|
|
||||||
--volicon "build/SFM.System/SFM.app/Contents/Resources/AppIcon.icns" \
|
|
||||||
--icon "SFM.app" 0 0 \
|
|
||||||
--hide-extension "SFM.app" \
|
|
||||||
--app-drop-link 0 0 \
|
|
||||||
--skip-jenkins \
|
|
||||||
"../sing-box/dist/SFM/SFM.dmg" "build/SFM.System/SFM.app"
|
|
||||||
|
|
||||||
notarize_macos_dmg:
|
upload_macos_independent:
|
||||||
xcrun notarytool submit "dist/SFM/SFM.dmg" --wait \
|
|
||||||
--keychain-profile "notarytool-password" \
|
|
||||||
--no-s3-acceleration
|
|
||||||
|
|
||||||
upload_macos_dmg:
|
|
||||||
cd dist/SFM && \
|
cd dist/SFM && \
|
||||||
cp SFM.dmg "SFM-${VERSION}-universal.dmg" && \
|
rm -f *.zip && \
|
||||||
ghr --replace --draft --prerelease "v${VERSION}" "SFM-${VERSION}-universal.dmg"
|
zip -ry "SFM-${VERSION}-universal.zip" SFM.app && \
|
||||||
|
ghr --replace --draft --prerelease "v${VERSION}" *.zip
|
||||||
|
|
||||||
upload_macos_dsyms:
|
release_macos_independent: build_macos_independent notarize_macos_independent wait_notarize_macos_independent export_macos_independent upload_macos_independent
|
||||||
pushd ../sing-box-for-apple/build/SFM.System.xcarchive && \
|
|
||||||
zip -r SFM.dSYMs.zip dSYMs && \
|
|
||||||
mv SFM.dSYMs.zip ../../../sing-box/dist/SFM && \
|
|
||||||
popd && \
|
|
||||||
cd dist/SFM && \
|
|
||||||
cp SFM.dSYMs.zip "SFM-${VERSION}-universal.dSYMs.zip" && \
|
|
||||||
ghr --replace --draft --prerelease "v${VERSION}" "SFM-${VERSION}-universal.dSYMs.zip"
|
|
||||||
|
|
||||||
release_macos_standalone: build_macos_standalone build_macos_dmg notarize_macos_dmg upload_macos_dmg upload_macos_dsyms
|
|
||||||
|
|
||||||
build_tvos:
|
build_tvos:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
rm -rf build/SFT.xcarchive && \
|
rm -rf build/SFT.xcarchive && \
|
||||||
xcodebuild archive -scheme SFT -configuration Release -archivePath build/SFT.xcarchive -allowProvisioningUpdates
|
xcodebuild archive -scheme SFT -configuration Release -archivePath build/SFT.xcarchive
|
||||||
|
|
||||||
upload_tvos_app_store:
|
upload_tvos_app_store:
|
||||||
cd ../sing-box-for-apple && \
|
cd ../sing-box-for-apple && \
|
||||||
xcodebuild -exportArchive -archivePath "build/SFT.xcarchive" -exportOptionsPlist SFI/Upload.plist -allowProvisioningUpdates
|
xcodebuild -exportArchive -archivePath "build/SFT.xcarchive" -exportOptionsPlist SFI/Upload.plist -allowProvisioningUpdates
|
||||||
|
|
||||||
release_tvos: build_tvos upload_tvos_app_store
|
release_tvos: build_tvos upload_tvos_app_store
|
||||||
|
|
||||||
update_apple_version:
|
update_apple_version:
|
||||||
go run ./cmd/internal/update_apple_version
|
go run ./cmd/internal/update_apple_version
|
||||||
|
|
||||||
update_macos_version:
|
release_apple: lib_ios update_apple_version release_ios release_macos release_tvos release_macos_independent
|
||||||
MACOS_PROJECT_VERSION=$(shell go run -v ./cmd/internal/app_store_connect next_macos_project_version) go run ./cmd/internal/update_apple_version
|
|
||||||
|
|
||||||
release_apple: lib_ios update_apple_version release_ios release_macos release_tvos release_macos_standalone
|
|
||||||
|
|
||||||
release_apple_beta: update_apple_version release_ios release_macos release_tvos
|
release_apple_beta: update_apple_version release_ios release_macos release_tvos
|
||||||
|
|
||||||
publish_testflight:
|
|
||||||
go run -v ./cmd/internal/app_store_connect publish_testflight
|
|
||||||
|
|
||||||
prepare_app_store:
|
|
||||||
go run -v ./cmd/internal/app_store_connect prepare_app_store
|
|
||||||
|
|
||||||
publish_app_store:
|
|
||||||
go run -v ./cmd/internal/app_store_connect publish_app_store
|
|
||||||
|
|
||||||
test:
|
test:
|
||||||
@go test -v ./... && \
|
@go test -v ./... && \
|
||||||
cd test && \
|
cd test && \
|
||||||
@@ -214,33 +180,25 @@ test_stdio:
|
|||||||
lib_android:
|
lib_android:
|
||||||
go run ./cmd/internal/build_libbox -target android
|
go run ./cmd/internal/build_libbox -target android
|
||||||
|
|
||||||
lib_android_debug:
|
|
||||||
go run ./cmd/internal/build_libbox -target android -debug
|
|
||||||
|
|
||||||
lib_apple:
|
|
||||||
go run ./cmd/internal/build_libbox -target apple
|
|
||||||
|
|
||||||
lib_ios:
|
lib_ios:
|
||||||
go run ./cmd/internal/build_libbox -target apple -platform ios -debug
|
go run ./cmd/internal/build_libbox -target ios
|
||||||
|
|
||||||
lib:
|
lib:
|
||||||
go run ./cmd/internal/build_libbox -target android
|
go run ./cmd/internal/build_libbox -target android
|
||||||
go run ./cmd/internal/build_libbox -target ios
|
go run ./cmd/internal/build_libbox -target ios
|
||||||
|
|
||||||
lib_install:
|
lib_install:
|
||||||
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.4
|
go install -v github.com/sagernet/gomobile/cmd/gomobile@v0.1.3
|
||||||
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.4
|
go install -v github.com/sagernet/gomobile/cmd/gobind@v0.1.3
|
||||||
|
|
||||||
docs:
|
docs:
|
||||||
venv/bin/mkdocs serve
|
mkdocs serve
|
||||||
|
|
||||||
publish_docs:
|
publish_docs:
|
||||||
venv/bin/mkdocs gh-deploy -m "Update" --force --ignore-version --no-history
|
mkdocs gh-deploy -m "Update" --force --ignore-version --no-history
|
||||||
|
|
||||||
docs_install:
|
docs_install:
|
||||||
python -m venv venv
|
pip install --force-reinstall mkdocs-material=="9.*" mkdocs-static-i18n=="1.2.*"
|
||||||
source ./venv/bin/activate && pip install --force-reinstall mkdocs-material=="9.*" mkdocs-static-i18n=="1.2.*"
|
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
rm -rf bin dist sing-box
|
rm -rf bin dist sing-box
|
||||||
rm -f $(shell go env GOPATH)/sing-box
|
rm -f $(shell go env GOPATH)/sing-box
|
||||||
|
|||||||
@@ -8,6 +8,10 @@ The universal proxy platform.
|
|||||||
|
|
||||||
https://sing-box.sagernet.org
|
https://sing-box.sagernet.org
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
https://community.sagernet.org/c/sing-box/
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
104
adapter/conn_router.go
Normal file
104
adapter/conn_router.go
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
package adapter
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing/common/logger"
|
||||||
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConnectionRouter interface {
|
||||||
|
RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
|
RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRouteHandler(
|
||||||
|
metadata InboundContext,
|
||||||
|
router ConnectionRouter,
|
||||||
|
logger logger.ContextLogger,
|
||||||
|
) UpstreamHandlerAdapter {
|
||||||
|
return &routeHandlerWrapper{
|
||||||
|
metadata: metadata,
|
||||||
|
router: router,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRouteContextHandler(
|
||||||
|
router ConnectionRouter,
|
||||||
|
logger logger.ContextLogger,
|
||||||
|
) UpstreamHandlerAdapter {
|
||||||
|
return &routeContextHandlerWrapper{
|
||||||
|
router: router,
|
||||||
|
logger: logger,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ UpstreamHandlerAdapter = (*routeHandlerWrapper)(nil)
|
||||||
|
|
||||||
|
type routeHandlerWrapper struct {
|
||||||
|
metadata InboundContext
|
||||||
|
router ConnectionRouter
|
||||||
|
logger logger.ContextLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
|
myMetadata := w.metadata
|
||||||
|
if metadata.Source.IsValid() {
|
||||||
|
myMetadata.Source = metadata.Source
|
||||||
|
}
|
||||||
|
if metadata.Destination.IsValid() {
|
||||||
|
myMetadata.Destination = metadata.Destination
|
||||||
|
}
|
||||||
|
return w.router.RouteConnection(ctx, conn, myMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
|
myMetadata := w.metadata
|
||||||
|
if metadata.Source.IsValid() {
|
||||||
|
myMetadata.Source = metadata.Source
|
||||||
|
}
|
||||||
|
if metadata.Destination.IsValid() {
|
||||||
|
myMetadata.Destination = metadata.Destination
|
||||||
|
}
|
||||||
|
return w.router.RoutePacketConnection(ctx, conn, myMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeHandlerWrapper) NewError(ctx context.Context, err error) {
|
||||||
|
w.logger.ErrorContext(ctx, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var _ UpstreamHandlerAdapter = (*routeContextHandlerWrapper)(nil)
|
||||||
|
|
||||||
|
type routeContextHandlerWrapper struct {
|
||||||
|
router ConnectionRouter
|
||||||
|
logger logger.ContextLogger
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
|
myMetadata := ContextFrom(ctx)
|
||||||
|
if metadata.Source.IsValid() {
|
||||||
|
myMetadata.Source = metadata.Source
|
||||||
|
}
|
||||||
|
if metadata.Destination.IsValid() {
|
||||||
|
myMetadata.Destination = metadata.Destination
|
||||||
|
}
|
||||||
|
return w.router.RouteConnection(ctx, conn, *myMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
|
myMetadata := ContextFrom(ctx)
|
||||||
|
if metadata.Source.IsValid() {
|
||||||
|
myMetadata.Source = metadata.Source
|
||||||
|
}
|
||||||
|
if metadata.Destination.IsValid() {
|
||||||
|
myMetadata.Destination = metadata.Destination
|
||||||
|
}
|
||||||
|
return w.router.RoutePacketConnection(ctx, conn, *myMetadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (w *routeContextHandlerWrapper) NewError(ctx context.Context, err error) {
|
||||||
|
w.logger.ErrorContext(ctx, err)
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConnectionManager interface {
|
|
||||||
Lifecycle
|
|
||||||
NewConnection(ctx context.Context, this N.Dialer, conn net.Conn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
|
||||||
NewPacketConnection(ctx context.Context, this N.Dialer, conn N.PacketConn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/netip"
|
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
"github.com/sagernet/sing/common/logger"
|
|
||||||
|
|
||||||
"github.com/miekg/dns"
|
|
||||||
)
|
|
||||||
|
|
||||||
type DNSRouter interface {
|
|
||||||
Lifecycle
|
|
||||||
Exchange(ctx context.Context, message *dns.Msg, options DNSQueryOptions) (*dns.Msg, error)
|
|
||||||
Lookup(ctx context.Context, domain string, options DNSQueryOptions) ([]netip.Addr, error)
|
|
||||||
ClearCache()
|
|
||||||
LookupReverseMapping(ip netip.Addr) (string, bool)
|
|
||||||
ResetNetwork()
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSClient interface {
|
|
||||||
Start()
|
|
||||||
Exchange(ctx context.Context, transport DNSTransport, message *dns.Msg, options DNSQueryOptions, responseChecker func(responseAddrs []netip.Addr) bool) (*dns.Msg, error)
|
|
||||||
Lookup(ctx context.Context, transport DNSTransport, domain string, options DNSQueryOptions, responseChecker func(responseAddrs []netip.Addr) bool) ([]netip.Addr, error)
|
|
||||||
LookupCache(domain string, strategy C.DomainStrategy) ([]netip.Addr, bool)
|
|
||||||
ExchangeCache(ctx context.Context, message *dns.Msg) (*dns.Msg, bool)
|
|
||||||
ClearCache()
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSQueryOptions struct {
|
|
||||||
Transport DNSTransport
|
|
||||||
Strategy C.DomainStrategy
|
|
||||||
DisableCache bool
|
|
||||||
RewriteTTL *uint32
|
|
||||||
ClientSubnet netip.Prefix
|
|
||||||
}
|
|
||||||
|
|
||||||
type RDRCStore interface {
|
|
||||||
LoadRDRC(transportName string, qName string, qType uint16) (rejected bool)
|
|
||||||
SaveRDRC(transportName string, qName string, qType uint16) error
|
|
||||||
SaveRDRCAsync(transportName string, qName string, qType uint16, logger logger.Logger)
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSTransport interface {
|
|
||||||
Type() string
|
|
||||||
Tag() string
|
|
||||||
Dependencies() []string
|
|
||||||
Reset()
|
|
||||||
Exchange(ctx context.Context, message *dns.Msg) (*dns.Msg, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type LegacyDNSTransport interface {
|
|
||||||
LegacyStrategy() C.DomainStrategy
|
|
||||||
LegacyClientSubnet() netip.Prefix
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSTransportRegistry interface {
|
|
||||||
option.DNSTransportOptionsRegistry
|
|
||||||
CreateDNSTransport(ctx context.Context, logger log.ContextLogger, tag string, transportType string, options any) (DNSTransport, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSTransportManager interface {
|
|
||||||
Lifecycle
|
|
||||||
Transports() []DNSTransport
|
|
||||||
Transport(tag string) (DNSTransport, bool)
|
|
||||||
Default() DNSTransport
|
|
||||||
FakeIP() FakeIPTransport
|
|
||||||
Remove(tag string) error
|
|
||||||
Create(ctx context.Context, logger log.ContextLogger, tag string, outboundType string, options any) error
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Endpoint interface {
|
|
||||||
Lifecycle
|
|
||||||
Type() string
|
|
||||||
Tag() string
|
|
||||||
Outbound
|
|
||||||
}
|
|
||||||
|
|
||||||
type EndpointRegistry interface {
|
|
||||||
option.EndpointOptionsRegistry
|
|
||||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, endpointType string, options any) (Endpoint, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type EndpointManager interface {
|
|
||||||
Lifecycle
|
|
||||||
Endpoints() []Endpoint
|
|
||||||
Get(tag string) (Endpoint, bool)
|
|
||||||
Remove(tag string) error
|
|
||||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, endpointType string, options any) error
|
|
||||||
}
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
package endpoint
|
|
||||||
|
|
||||||
import "github.com/sagernet/sing-box/option"
|
|
||||||
|
|
||||||
type Adapter struct {
|
|
||||||
endpointType string
|
|
||||||
endpointTag string
|
|
||||||
network []string
|
|
||||||
dependencies []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAdapter(endpointType string, endpointTag string, network []string, dependencies []string) Adapter {
|
|
||||||
return Adapter{
|
|
||||||
endpointType: endpointType,
|
|
||||||
endpointTag: endpointTag,
|
|
||||||
network: network,
|
|
||||||
dependencies: dependencies,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAdapterWithDialerOptions(endpointType string, endpointTag string, network []string, dialOptions option.DialerOptions) Adapter {
|
|
||||||
var dependencies []string
|
|
||||||
if dialOptions.Detour != "" {
|
|
||||||
dependencies = []string{dialOptions.Detour}
|
|
||||||
}
|
|
||||||
return NewAdapter(endpointType, endpointTag, network, dependencies)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Type() string {
|
|
||||||
return a.endpointType
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Tag() string {
|
|
||||||
return a.endpointTag
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Network() []string {
|
|
||||||
return a.network
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Dependencies() []string {
|
|
||||||
return a.dependencies
|
|
||||||
}
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
package endpoint
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"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/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ adapter.EndpointManager = (*Manager)(nil)
|
|
||||||
|
|
||||||
type Manager struct {
|
|
||||||
logger log.ContextLogger
|
|
||||||
registry adapter.EndpointRegistry
|
|
||||||
access sync.Mutex
|
|
||||||
started bool
|
|
||||||
stage adapter.StartStage
|
|
||||||
endpoints []adapter.Endpoint
|
|
||||||
endpointByTag map[string]adapter.Endpoint
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewManager(logger log.ContextLogger, registry adapter.EndpointRegistry) *Manager {
|
|
||||||
return &Manager{
|
|
||||||
logger: logger,
|
|
||||||
registry: registry,
|
|
||||||
endpointByTag: make(map[string]adapter.Endpoint),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Start(stage adapter.StartStage) error {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if m.started && m.stage >= stage {
|
|
||||||
panic("already started")
|
|
||||||
}
|
|
||||||
m.started = true
|
|
||||||
m.stage = stage
|
|
||||||
if stage == adapter.StartStateStart {
|
|
||||||
// started with outbound manager
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
for _, endpoint := range m.endpoints {
|
|
||||||
err := adapter.LegacyStart(endpoint, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " endpoint/", endpoint.Type(), "[", endpoint.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Close() error {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if !m.started {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
m.started = false
|
|
||||||
endpoints := m.endpoints
|
|
||||||
m.endpoints = nil
|
|
||||||
monitor := taskmonitor.New(m.logger, C.StopTimeout)
|
|
||||||
var err error
|
|
||||||
for _, endpoint := range endpoints {
|
|
||||||
monitor.Start("close endpoint/", endpoint.Type(), "[", endpoint.Tag(), "]")
|
|
||||||
err = E.Append(err, endpoint.Close(), func(err error) error {
|
|
||||||
return E.Cause(err, "close endpoint/", endpoint.Type(), "[", endpoint.Tag(), "]")
|
|
||||||
})
|
|
||||||
monitor.Finish()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Endpoints() []adapter.Endpoint {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
return m.endpoints
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Get(tag string) (adapter.Endpoint, bool) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
endpoint, found := m.endpointByTag[tag]
|
|
||||||
return endpoint, found
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Remove(tag string) error {
|
|
||||||
m.access.Lock()
|
|
||||||
endpoint, found := m.endpointByTag[tag]
|
|
||||||
if !found {
|
|
||||||
m.access.Unlock()
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
delete(m.endpointByTag, tag)
|
|
||||||
index := common.Index(m.endpoints, func(it adapter.Endpoint) bool {
|
|
||||||
return it == endpoint
|
|
||||||
})
|
|
||||||
if index == -1 {
|
|
||||||
panic("invalid endpoint index")
|
|
||||||
}
|
|
||||||
m.endpoints = append(m.endpoints[:index], m.endpoints[index+1:]...)
|
|
||||||
started := m.started
|
|
||||||
m.access.Unlock()
|
|
||||||
if started {
|
|
||||||
return endpoint.Close()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Create(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, outboundType string, options any) error {
|
|
||||||
endpoint, err := m.registry.Create(ctx, router, logger, tag, outboundType, options)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if m.started {
|
|
||||||
for _, stage := range adapter.ListStartStages {
|
|
||||||
err = adapter.LegacyStart(endpoint, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " endpoint/", endpoint.Type(), "[", endpoint.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if existsEndpoint, loaded := m.endpointByTag[tag]; loaded {
|
|
||||||
if m.started {
|
|
||||||
err = existsEndpoint.Close()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "close endpoint/", existsEndpoint.Type(), "[", existsEndpoint.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
existsIndex := common.Index(m.endpoints, func(it adapter.Endpoint) bool {
|
|
||||||
return it == existsEndpoint
|
|
||||||
})
|
|
||||||
if existsIndex == -1 {
|
|
||||||
panic("invalid endpoint index")
|
|
||||||
}
|
|
||||||
m.endpoints = append(m.endpoints[:existsIndex], m.endpoints[existsIndex+1:]...)
|
|
||||||
}
|
|
||||||
m.endpoints = append(m.endpoints, endpoint)
|
|
||||||
m.endpointByTag[tag] = endpoint
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
package endpoint
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConstructorFunc[T any] func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options T) (adapter.Endpoint, error)
|
|
||||||
|
|
||||||
func Register[Options any](registry *Registry, outboundType string, constructor ConstructorFunc[Options]) {
|
|
||||||
registry.register(outboundType, func() any {
|
|
||||||
return new(Options)
|
|
||||||
}, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, rawOptions any) (adapter.Endpoint, error) {
|
|
||||||
var options *Options
|
|
||||||
if rawOptions != nil {
|
|
||||||
options = rawOptions.(*Options)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, common.PtrValueOrDefault(options))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ adapter.EndpointRegistry = (*Registry)(nil)
|
|
||||||
|
|
||||||
type (
|
|
||||||
optionsConstructorFunc func() any
|
|
||||||
constructorFunc func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options any) (adapter.Endpoint, error)
|
|
||||||
)
|
|
||||||
|
|
||||||
type Registry struct {
|
|
||||||
access sync.Mutex
|
|
||||||
optionsType map[string]optionsConstructorFunc
|
|
||||||
constructor map[string]constructorFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry() *Registry {
|
|
||||||
return &Registry{
|
|
||||||
optionsType: make(map[string]optionsConstructorFunc),
|
|
||||||
constructor: make(map[string]constructorFunc),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) CreateOptions(outboundType string) (any, bool) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
optionsConstructor, loaded := m.optionsType[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return optionsConstructor(), true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) Create(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, outboundType string, options any) (adapter.Endpoint, error) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
constructor, loaded := m.constructor[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, E.New("outbound type not found: " + outboundType)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) register(outboundType string, optionsConstructor optionsConstructorFunc, constructor constructorFunc) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
m.optionsType[outboundType] = optionsConstructor
|
|
||||||
m.constructor[outboundType] = constructor
|
|
||||||
}
|
|
||||||
@@ -4,33 +4,35 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"io"
|
||||||
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/urltest"
|
"github.com/sagernet/sing-box/common/urltest"
|
||||||
"github.com/sagernet/sing/common/varbin"
|
"github.com/sagernet/sing-dns"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/sing/common/rw"
|
||||||
)
|
)
|
||||||
|
|
||||||
type ClashServer interface {
|
type ClashServer interface {
|
||||||
LifecycleService
|
Service
|
||||||
ConnectionTracker
|
PreStarter
|
||||||
Mode() string
|
Mode() string
|
||||||
ModeList() []string
|
ModeList() []string
|
||||||
HistoryStorage() *urltest.HistoryStorage
|
HistoryStorage() *urltest.HistoryStorage
|
||||||
}
|
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule) (net.Conn, Tracker)
|
||||||
|
RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext, matchedRule Rule) (N.PacketConn, Tracker)
|
||||||
type V2RayServer interface {
|
|
||||||
LifecycleService
|
|
||||||
StatsService() ConnectionTracker
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type CacheFile interface {
|
type CacheFile interface {
|
||||||
LifecycleService
|
Service
|
||||||
|
PreStarter
|
||||||
|
|
||||||
StoreFakeIP() bool
|
StoreFakeIP() bool
|
||||||
FakeIPStorage
|
FakeIPStorage
|
||||||
|
|
||||||
StoreRDRC() bool
|
StoreRDRC() bool
|
||||||
RDRCStore
|
dns.RDRCStore
|
||||||
|
|
||||||
LoadMode() string
|
LoadMode() string
|
||||||
StoreMode(mode string) error
|
StoreMode(mode string) error
|
||||||
@@ -54,15 +56,16 @@ func (s *SavedRuleSet) MarshalBinary() ([]byte, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
err = varbin.Write(&buffer, binary.BigEndian, s.Content)
|
err = rw.WriteUVariant(&buffer, uint64(len(s.Content)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
buffer.Write(s.Content)
|
||||||
err = binary.Write(&buffer, binary.BigEndian, s.LastUpdated.Unix())
|
err = binary.Write(&buffer, binary.BigEndian, s.LastUpdated.Unix())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
err = varbin.Write(&buffer, binary.BigEndian, s.LastEtag)
|
err = rw.WriteVString(&buffer, s.LastEtag)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -76,7 +79,12 @@ func (s *SavedRuleSet) UnmarshalBinary(data []byte) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = varbin.Read(reader, binary.BigEndian, &s.Content)
|
contentLen, err := rw.ReadUVariant(reader)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.Content = make([]byte, contentLen)
|
||||||
|
_, err = io.ReadFull(reader, s.Content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -86,13 +94,17 @@ func (s *SavedRuleSet) UnmarshalBinary(data []byte) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
s.LastUpdated = time.Unix(lastUpdated, 0)
|
s.LastUpdated = time.Unix(lastUpdated, 0)
|
||||||
err = varbin.Read(reader, binary.BigEndian, &s.LastEtag)
|
s.LastEtag, err = rw.ReadVString(reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Tracker interface {
|
||||||
|
Leave()
|
||||||
|
}
|
||||||
|
|
||||||
type OutboundGroup interface {
|
type OutboundGroup interface {
|
||||||
Outbound
|
Outbound
|
||||||
Now() string
|
Now() string
|
||||||
@@ -110,3 +122,13 @@ func OutboundTag(detour Outbound) string {
|
|||||||
}
|
}
|
||||||
return detour.Tag()
|
return detour.Tag()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type V2RayServer interface {
|
||||||
|
Service
|
||||||
|
StatsService() V2RayStatsService
|
||||||
|
}
|
||||||
|
|
||||||
|
type V2RayStatsService interface {
|
||||||
|
RoutedConnection(inbound string, outbound string, user string, conn net.Conn) net.Conn
|
||||||
|
RoutedPacketConnection(inbound string, outbound string, user string, conn N.PacketConn) N.PacketConn
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ package adapter
|
|||||||
import (
|
import (
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-dns"
|
||||||
"github.com/sagernet/sing/common/logger"
|
"github.com/sagernet/sing/common/logger"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -26,6 +27,6 @@ type FakeIPStorage interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type FakeIPTransport interface {
|
type FakeIPTransport interface {
|
||||||
DNSTransport
|
dns.Transport
|
||||||
Store() FakeIPStore
|
Store() FakeIPStore
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,56 +6,27 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing/common/buf"
|
"github.com/sagernet/sing/common/buf"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Deprecated
|
|
||||||
type ConnectionHandler interface {
|
type ConnectionHandler interface {
|
||||||
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionHandlerEx interface {
|
|
||||||
NewConnectionEx(ctx context.Context, conn net.Conn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use PacketHandlerEx instead
|
|
||||||
type PacketHandler interface {
|
type PacketHandler interface {
|
||||||
NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata InboundContext) error
|
NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, metadata InboundContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type PacketHandlerEx interface {
|
|
||||||
NewPacketEx(buffer *buf.Buffer, source M.Socksaddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use OOBPacketHandlerEx instead
|
|
||||||
type OOBPacketHandler interface {
|
type OOBPacketHandler interface {
|
||||||
NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, oob []byte, metadata InboundContext) error
|
NewPacket(ctx context.Context, conn N.PacketConn, buffer *buf.Buffer, oob []byte, metadata InboundContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type OOBPacketHandlerEx interface {
|
|
||||||
NewPacketEx(buffer *buf.Buffer, oob []byte, source M.Socksaddr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated
|
|
||||||
type PacketConnectionHandler interface {
|
type PacketConnectionHandler interface {
|
||||||
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type PacketConnectionHandlerEx interface {
|
|
||||||
NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use TCPConnectionHandlerEx instead
|
|
||||||
//
|
|
||||||
//nolint:staticcheck
|
|
||||||
type UpstreamHandlerAdapter interface {
|
type UpstreamHandlerAdapter interface {
|
||||||
N.TCPConnectionHandler
|
N.TCPConnectionHandler
|
||||||
N.UDPConnectionHandler
|
N.UDPConnectionHandler
|
||||||
E.Handler
|
E.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
type UpstreamHandlerAdapterEx interface {
|
|
||||||
N.TCPConnectionHandlerEx
|
|
||||||
N.UDPConnectionHandlerEx
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,43 +2,26 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/process"
|
"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"
|
"github.com/sagernet/sing-box/option"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Inbound interface {
|
type Inbound interface {
|
||||||
Lifecycle
|
Service
|
||||||
Type() string
|
Type() string
|
||||||
Tag() string
|
Tag() string
|
||||||
}
|
}
|
||||||
|
|
||||||
type TCPInjectableInbound interface {
|
type InjectableInbound interface {
|
||||||
Inbound
|
Inbound
|
||||||
ConnectionHandlerEx
|
Network() []string
|
||||||
}
|
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
|
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
type UDPInjectableInbound interface {
|
|
||||||
Inbound
|
|
||||||
PacketConnectionHandlerEx
|
|
||||||
}
|
|
||||||
|
|
||||||
type InboundRegistry interface {
|
|
||||||
option.InboundOptionsRegistry
|
|
||||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, inboundType string, options any) (Inbound, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type InboundManager interface {
|
|
||||||
Lifecycle
|
|
||||||
Inbounds() []Inbound
|
|
||||||
Get(tag string) (Inbound, bool)
|
|
||||||
Remove(tag string) error
|
|
||||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, inboundType string, options any) error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type InboundContext struct {
|
type InboundContext struct {
|
||||||
@@ -48,35 +31,17 @@ type InboundContext struct {
|
|||||||
Network string
|
Network string
|
||||||
Source M.Socksaddr
|
Source M.Socksaddr
|
||||||
Destination M.Socksaddr
|
Destination M.Socksaddr
|
||||||
|
Domain string
|
||||||
|
Protocol string
|
||||||
User string
|
User string
|
||||||
Outbound string
|
Outbound string
|
||||||
|
|
||||||
// sniffer
|
|
||||||
|
|
||||||
Protocol string
|
|
||||||
Domain string
|
|
||||||
Client string
|
|
||||||
SniffContext any
|
|
||||||
|
|
||||||
// cache
|
// cache
|
||||||
|
|
||||||
// Deprecated: implement in rule action
|
InboundDetour string
|
||||||
InboundDetour string
|
LastInbound string
|
||||||
LastInbound string
|
OriginDestination M.Socksaddr
|
||||||
OriginDestination M.Socksaddr
|
InboundOptions option.InboundOptions
|
||||||
RouteOriginalDestination M.Socksaddr
|
|
||||||
// Deprecated: to be removed
|
|
||||||
//nolint:staticcheck
|
|
||||||
InboundOptions option.InboundOptions
|
|
||||||
UDPDisableDomainUnmapping bool
|
|
||||||
UDPConnect bool
|
|
||||||
UDPTimeout time.Duration
|
|
||||||
|
|
||||||
NetworkStrategy *C.NetworkStrategy
|
|
||||||
NetworkType []C.InterfaceType
|
|
||||||
FallbackNetworkType []C.InterfaceType
|
|
||||||
FallbackDelay time.Duration
|
|
||||||
|
|
||||||
DestinationAddresses []netip.Addr
|
DestinationAddresses []netip.Addr
|
||||||
SourceGeoIPCode string
|
SourceGeoIPCode string
|
||||||
GeoIPCode string
|
GeoIPCode string
|
||||||
@@ -86,9 +51,7 @@ type InboundContext struct {
|
|||||||
|
|
||||||
// rule cache
|
// rule cache
|
||||||
|
|
||||||
IPCIDRMatchSource bool
|
IPCIDRMatchSource bool
|
||||||
IPCIDRAcceptEmpty bool
|
|
||||||
|
|
||||||
SourceAddressMatch bool
|
SourceAddressMatch bool
|
||||||
SourcePortMatch bool
|
SourcePortMatch bool
|
||||||
DestinationAddressMatch bool
|
DestinationAddressMatch bool
|
||||||
@@ -99,7 +62,6 @@ type InboundContext struct {
|
|||||||
|
|
||||||
func (c *InboundContext) ResetRuleCache() {
|
func (c *InboundContext) ResetRuleCache() {
|
||||||
c.IPCIDRMatchSource = false
|
c.IPCIDRMatchSource = false
|
||||||
c.IPCIDRAcceptEmpty = false
|
|
||||||
c.SourceAddressMatch = false
|
c.SourceAddressMatch = false
|
||||||
c.SourcePortMatch = false
|
c.SourcePortMatch = false
|
||||||
c.DestinationAddressMatch = false
|
c.DestinationAddressMatch = false
|
||||||
@@ -121,6 +83,15 @@ func ContextFrom(ctx context.Context) *InboundContext {
|
|||||||
return metadata.(*InboundContext)
|
return metadata.(*InboundContext)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func AppendContext(ctx context.Context) (context.Context, *InboundContext) {
|
||||||
|
metadata := ContextFrom(ctx)
|
||||||
|
if metadata != nil {
|
||||||
|
return ctx, metadata
|
||||||
|
}
|
||||||
|
metadata = new(InboundContext)
|
||||||
|
return WithContext(ctx, metadata), metadata
|
||||||
|
}
|
||||||
|
|
||||||
func ExtendContext(ctx context.Context) (context.Context, *InboundContext) {
|
func ExtendContext(ctx context.Context) (context.Context, *InboundContext) {
|
||||||
var newMetadata InboundContext
|
var newMetadata InboundContext
|
||||||
if metadata := ContextFrom(ctx); metadata != nil {
|
if metadata := ContextFrom(ctx); metadata != nil {
|
||||||
|
|||||||
@@ -1,21 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
type Adapter struct {
|
|
||||||
inboundType string
|
|
||||||
inboundTag string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAdapter(inboundType string, inboundTag string) Adapter {
|
|
||||||
return Adapter{
|
|
||||||
inboundType: inboundType,
|
|
||||||
inboundTag: inboundTag,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Type() string {
|
|
||||||
return a.inboundType
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Tag() string {
|
|
||||||
return a.inboundTag
|
|
||||||
}
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"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/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ adapter.InboundManager = (*Manager)(nil)
|
|
||||||
|
|
||||||
type Manager struct {
|
|
||||||
logger log.ContextLogger
|
|
||||||
registry adapter.InboundRegistry
|
|
||||||
endpoint adapter.EndpointManager
|
|
||||||
access sync.Mutex
|
|
||||||
started bool
|
|
||||||
stage adapter.StartStage
|
|
||||||
inbounds []adapter.Inbound
|
|
||||||
inboundByTag map[string]adapter.Inbound
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewManager(logger log.ContextLogger, registry adapter.InboundRegistry, endpoint adapter.EndpointManager) *Manager {
|
|
||||||
return &Manager{
|
|
||||||
logger: logger,
|
|
||||||
registry: registry,
|
|
||||||
endpoint: endpoint,
|
|
||||||
inboundByTag: make(map[string]adapter.Inbound),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Start(stage adapter.StartStage) error {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if m.started && m.stage >= stage {
|
|
||||||
panic("already started")
|
|
||||||
}
|
|
||||||
m.started = true
|
|
||||||
m.stage = stage
|
|
||||||
for _, inbound := range m.inbounds {
|
|
||||||
err := adapter.LegacyStart(inbound, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " inbound/", inbound.Type(), "[", inbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Close() error {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if !m.started {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
m.started = false
|
|
||||||
inbounds := m.inbounds
|
|
||||||
m.inbounds = nil
|
|
||||||
monitor := taskmonitor.New(m.logger, C.StopTimeout)
|
|
||||||
var err error
|
|
||||||
for _, inbound := range inbounds {
|
|
||||||
monitor.Start("close inbound/", inbound.Type(), "[", inbound.Tag(), "]")
|
|
||||||
err = E.Append(err, inbound.Close(), func(err error) error {
|
|
||||||
return E.Cause(err, "close inbound/", inbound.Type(), "[", inbound.Tag(), "]")
|
|
||||||
})
|
|
||||||
monitor.Finish()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Inbounds() []adapter.Inbound {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
return m.inbounds
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Get(tag string) (adapter.Inbound, bool) {
|
|
||||||
m.access.Lock()
|
|
||||||
inbound, found := m.inboundByTag[tag]
|
|
||||||
m.access.Unlock()
|
|
||||||
if found {
|
|
||||||
return inbound, true
|
|
||||||
}
|
|
||||||
return m.endpoint.Get(tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Remove(tag string) error {
|
|
||||||
m.access.Lock()
|
|
||||||
inbound, found := m.inboundByTag[tag]
|
|
||||||
if !found {
|
|
||||||
m.access.Unlock()
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
delete(m.inboundByTag, tag)
|
|
||||||
index := common.Index(m.inbounds, func(it adapter.Inbound) bool {
|
|
||||||
return it == inbound
|
|
||||||
})
|
|
||||||
if index == -1 {
|
|
||||||
panic("invalid inbound index")
|
|
||||||
}
|
|
||||||
m.inbounds = append(m.inbounds[:index], m.inbounds[index+1:]...)
|
|
||||||
started := m.started
|
|
||||||
m.access.Unlock()
|
|
||||||
if started {
|
|
||||||
return inbound.Close()
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Create(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, outboundType string, options any) error {
|
|
||||||
inbound, err := m.registry.Create(ctx, router, logger, tag, outboundType, options)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if m.started {
|
|
||||||
for _, stage := range adapter.ListStartStages {
|
|
||||||
err = adapter.LegacyStart(inbound, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " inbound/", inbound.Type(), "[", inbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if existsInbound, loaded := m.inboundByTag[tag]; loaded {
|
|
||||||
if m.started {
|
|
||||||
err = existsInbound.Close()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "close inbound/", existsInbound.Type(), "[", existsInbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
existsIndex := common.Index(m.inbounds, func(it adapter.Inbound) bool {
|
|
||||||
return it == existsInbound
|
|
||||||
})
|
|
||||||
if existsIndex == -1 {
|
|
||||||
panic("invalid inbound index")
|
|
||||||
}
|
|
||||||
m.inbounds = append(m.inbounds[:existsIndex], m.inbounds[existsIndex+1:]...)
|
|
||||||
}
|
|
||||||
m.inbounds = append(m.inbounds, inbound)
|
|
||||||
m.inboundByTag[tag] = inbound
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
package inbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConstructorFunc[T any] func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options T) (adapter.Inbound, error)
|
|
||||||
|
|
||||||
func Register[Options any](registry *Registry, outboundType string, constructor ConstructorFunc[Options]) {
|
|
||||||
registry.register(outboundType, func() any {
|
|
||||||
return new(Options)
|
|
||||||
}, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, rawOptions any) (adapter.Inbound, error) {
|
|
||||||
var options *Options
|
|
||||||
if rawOptions != nil {
|
|
||||||
options = rawOptions.(*Options)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, common.PtrValueOrDefault(options))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ adapter.InboundRegistry = (*Registry)(nil)
|
|
||||||
|
|
||||||
type (
|
|
||||||
optionsConstructorFunc func() any
|
|
||||||
constructorFunc func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options any) (adapter.Inbound, error)
|
|
||||||
)
|
|
||||||
|
|
||||||
type Registry struct {
|
|
||||||
access sync.Mutex
|
|
||||||
optionsType map[string]optionsConstructorFunc
|
|
||||||
constructor map[string]constructorFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry() *Registry {
|
|
||||||
return &Registry{
|
|
||||||
optionsType: make(map[string]optionsConstructorFunc),
|
|
||||||
constructor: make(map[string]constructorFunc),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) CreateOptions(outboundType string) (any, bool) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
optionsConstructor, loaded := m.optionsType[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return optionsConstructor(), true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) Create(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, outboundType string, options any) (adapter.Inbound, error) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
constructor, loaded := m.constructor[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, E.New("outbound type not found: " + outboundType)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Registry) register(outboundType string, optionsConstructor optionsConstructorFunc, constructor constructorFunc) {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
m.optionsType[outboundType] = optionsConstructor
|
|
||||||
m.constructor[outboundType] = constructor
|
|
||||||
}
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
|
|
||||||
type StartStage uint8
|
|
||||||
|
|
||||||
const (
|
|
||||||
StartStateInitialize StartStage = iota
|
|
||||||
StartStateStart
|
|
||||||
StartStatePostStart
|
|
||||||
StartStateStarted
|
|
||||||
)
|
|
||||||
|
|
||||||
var ListStartStages = []StartStage{
|
|
||||||
StartStateInitialize,
|
|
||||||
StartStateStart,
|
|
||||||
StartStatePostStart,
|
|
||||||
StartStateStarted,
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s StartStage) String() string {
|
|
||||||
switch s {
|
|
||||||
case StartStateInitialize:
|
|
||||||
return "initialize"
|
|
||||||
case StartStateStart:
|
|
||||||
return "start"
|
|
||||||
case StartStatePostStart:
|
|
||||||
return "post-start"
|
|
||||||
case StartStateStarted:
|
|
||||||
return "finish-start"
|
|
||||||
default:
|
|
||||||
panic("unknown stage")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Lifecycle interface {
|
|
||||||
Start(stage StartStage) error
|
|
||||||
Close() error
|
|
||||||
}
|
|
||||||
|
|
||||||
type LifecycleService interface {
|
|
||||||
Name() string
|
|
||||||
Lifecycle
|
|
||||||
}
|
|
||||||
|
|
||||||
func Start(stage StartStage, services ...Lifecycle) error {
|
|
||||||
for _, service := range services {
|
|
||||||
err := service.Start(stage)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func StartNamed(stage StartStage, services []LifecycleService) error {
|
|
||||||
for _, service := range services {
|
|
||||||
err := service.Start(stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage.String(), " ", service.Name())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
func LegacyStart(starter any, stage StartStage) error {
|
|
||||||
if lifecycle, isLifecycle := starter.(Lifecycle); isLifecycle {
|
|
||||||
return lifecycle.Start(stage)
|
|
||||||
}
|
|
||||||
switch stage {
|
|
||||||
case StartStateInitialize:
|
|
||||||
if preStarter, isPreStarter := starter.(interface {
|
|
||||||
PreStart() error
|
|
||||||
}); isPreStarter {
|
|
||||||
return preStarter.PreStart()
|
|
||||||
}
|
|
||||||
case StartStateStart:
|
|
||||||
if starter, isStarter := starter.(interface {
|
|
||||||
Start() error
|
|
||||||
}); isStarter {
|
|
||||||
return starter.Start()
|
|
||||||
}
|
|
||||||
case StartStateStarted:
|
|
||||||
if postStarter, isPostStarter := starter.(interface {
|
|
||||||
PostStart() error
|
|
||||||
}); isPostStarter {
|
|
||||||
return postStarter.PostStart()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type lifecycleServiceWrapper struct {
|
|
||||||
Service
|
|
||||||
name string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewLifecycleService(service Service, name string) LifecycleService {
|
|
||||||
return &lifecycleServiceWrapper{
|
|
||||||
Service: service,
|
|
||||||
name: name,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *lifecycleServiceWrapper) Name() string {
|
|
||||||
return l.name
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *lifecycleServiceWrapper) Start(stage StartStage) error {
|
|
||||||
return LegacyStart(l.Service, stage)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *lifecycleServiceWrapper) Close() error {
|
|
||||||
return l.Service.Close()
|
|
||||||
}
|
|
||||||
@@ -1,54 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-tun"
|
|
||||||
"github.com/sagernet/sing/common/control"
|
|
||||||
)
|
|
||||||
|
|
||||||
type NetworkManager interface {
|
|
||||||
Lifecycle
|
|
||||||
InterfaceFinder() control.InterfaceFinder
|
|
||||||
UpdateInterfaces() error
|
|
||||||
DefaultNetworkInterface() *NetworkInterface
|
|
||||||
NetworkInterfaces() []NetworkInterface
|
|
||||||
AutoDetectInterface() bool
|
|
||||||
AutoDetectInterfaceFunc() control.Func
|
|
||||||
ProtectFunc() control.Func
|
|
||||||
DefaultOptions() NetworkOptions
|
|
||||||
RegisterAutoRedirectOutputMark(mark uint32) error
|
|
||||||
AutoRedirectOutputMark() uint32
|
|
||||||
NetworkMonitor() tun.NetworkUpdateMonitor
|
|
||||||
InterfaceMonitor() tun.DefaultInterfaceMonitor
|
|
||||||
PackageManager() tun.PackageManager
|
|
||||||
WIFIState() WIFIState
|
|
||||||
ResetNetwork()
|
|
||||||
}
|
|
||||||
|
|
||||||
type NetworkOptions struct {
|
|
||||||
NetworkStrategy *C.NetworkStrategy
|
|
||||||
NetworkType []C.InterfaceType
|
|
||||||
FallbackNetworkType []C.InterfaceType
|
|
||||||
FallbackDelay time.Duration
|
|
||||||
BindInterface string
|
|
||||||
RoutingMark uint32
|
|
||||||
}
|
|
||||||
|
|
||||||
type InterfaceUpdateListener interface {
|
|
||||||
InterfaceUpdated()
|
|
||||||
}
|
|
||||||
|
|
||||||
type WIFIState struct {
|
|
||||||
SSID string
|
|
||||||
BSSID string
|
|
||||||
}
|
|
||||||
|
|
||||||
type NetworkInterface struct {
|
|
||||||
control.Interface
|
|
||||||
Type C.InterfaceType
|
|
||||||
DNSServers []string
|
|
||||||
Expensive bool
|
|
||||||
Constrained bool
|
|
||||||
}
|
|
||||||
@@ -2,9 +2,8 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -16,18 +15,6 @@ type Outbound interface {
|
|||||||
Network() []string
|
Network() []string
|
||||||
Dependencies() []string
|
Dependencies() []string
|
||||||
N.Dialer
|
N.Dialer
|
||||||
}
|
NewConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
|
NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
type OutboundRegistry interface {
|
|
||||||
option.OutboundOptionsRegistry
|
|
||||||
CreateOutbound(ctx context.Context, router Router, logger log.ContextLogger, tag string, outboundType string, options any) (Outbound, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type OutboundManager interface {
|
|
||||||
Lifecycle
|
|
||||||
Outbounds() []Outbound
|
|
||||||
Outbound(tag string) (Outbound, bool)
|
|
||||||
Default() Outbound
|
|
||||||
Remove(tag string) error
|
|
||||||
Create(ctx context.Context, router Router, logger log.ContextLogger, tag string, outboundType string, options any) error
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Adapter struct {
|
|
||||||
outboundType string
|
|
||||||
outboundTag string
|
|
||||||
network []string
|
|
||||||
dependencies []string
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAdapter(outboundType string, outboundTag string, network []string, dependencies []string) Adapter {
|
|
||||||
return Adapter{
|
|
||||||
outboundType: outboundType,
|
|
||||||
outboundTag: outboundTag,
|
|
||||||
network: network,
|
|
||||||
dependencies: dependencies,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewAdapterWithDialerOptions(outboundType string, outboundTag string, network []string, dialOptions option.DialerOptions) Adapter {
|
|
||||||
var dependencies []string
|
|
||||||
if dialOptions.Detour != "" {
|
|
||||||
dependencies = []string{dialOptions.Detour}
|
|
||||||
}
|
|
||||||
return NewAdapter(outboundType, outboundTag, network, dependencies)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Type() string {
|
|
||||||
return a.outboundType
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Tag() string {
|
|
||||||
return a.outboundTag
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Network() []string {
|
|
||||||
return a.network
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *Adapter) Dependencies() []string {
|
|
||||||
return a.dependencies
|
|
||||||
}
|
|
||||||
@@ -1,287 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"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/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
"github.com/sagernet/sing/common/logger"
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ adapter.OutboundManager = (*Manager)(nil)
|
|
||||||
|
|
||||||
type Manager struct {
|
|
||||||
logger log.ContextLogger
|
|
||||||
registry adapter.OutboundRegistry
|
|
||||||
endpoint adapter.EndpointManager
|
|
||||||
defaultTag string
|
|
||||||
access sync.RWMutex
|
|
||||||
started bool
|
|
||||||
stage adapter.StartStage
|
|
||||||
outbounds []adapter.Outbound
|
|
||||||
outboundByTag map[string]adapter.Outbound
|
|
||||||
dependByTag map[string][]string
|
|
||||||
defaultOutbound adapter.Outbound
|
|
||||||
defaultOutboundFallback adapter.Outbound
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewManager(logger logger.ContextLogger, registry adapter.OutboundRegistry, endpoint adapter.EndpointManager, defaultTag string) *Manager {
|
|
||||||
return &Manager{
|
|
||||||
logger: logger,
|
|
||||||
registry: registry,
|
|
||||||
endpoint: endpoint,
|
|
||||||
defaultTag: defaultTag,
|
|
||||||
outboundByTag: make(map[string]adapter.Outbound),
|
|
||||||
dependByTag: make(map[string][]string),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Initialize(defaultOutboundFallback adapter.Outbound) {
|
|
||||||
m.defaultOutboundFallback = defaultOutboundFallback
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Start(stage adapter.StartStage) error {
|
|
||||||
m.access.Lock()
|
|
||||||
if m.started && m.stage >= stage {
|
|
||||||
panic("already started")
|
|
||||||
}
|
|
||||||
m.started = true
|
|
||||||
m.stage = stage
|
|
||||||
outbounds := m.outbounds
|
|
||||||
m.access.Unlock()
|
|
||||||
if stage == adapter.StartStateStart {
|
|
||||||
if m.defaultTag != "" && m.defaultOutbound == nil {
|
|
||||||
defaultEndpoint, loaded := m.endpoint.Get(m.defaultTag)
|
|
||||||
if !loaded {
|
|
||||||
return E.New("default outbound not found: ", m.defaultTag)
|
|
||||||
}
|
|
||||||
m.defaultOutbound = defaultEndpoint
|
|
||||||
}
|
|
||||||
return m.startOutbounds(append(outbounds, common.Map(m.endpoint.Endpoints(), func(it adapter.Endpoint) adapter.Outbound { return it })...))
|
|
||||||
} else {
|
|
||||||
for _, outbound := range outbounds {
|
|
||||||
err := adapter.LegacyStart(outbound, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " outbound/", outbound.Type(), "[", outbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) startOutbounds(outbounds []adapter.Outbound) error {
|
|
||||||
monitor := taskmonitor.New(m.logger, C.StartTimeout)
|
|
||||||
started := make(map[string]bool)
|
|
||||||
for {
|
|
||||||
canContinue := false
|
|
||||||
startOne:
|
|
||||||
for _, outboundToStart := range outbounds {
|
|
||||||
outboundTag := outboundToStart.Tag()
|
|
||||||
if started[outboundTag] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
dependencies := outboundToStart.Dependencies()
|
|
||||||
for _, dependency := range dependencies {
|
|
||||||
if !started[dependency] {
|
|
||||||
continue startOne
|
|
||||||
}
|
|
||||||
}
|
|
||||||
started[outboundTag] = true
|
|
||||||
canContinue = true
|
|
||||||
if starter, isStarter := outboundToStart.(adapter.Lifecycle); isStarter {
|
|
||||||
monitor.Start("start outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
|
||||||
err := starter.Start(adapter.StartStateStart)
|
|
||||||
monitor.Finish()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "start outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
|
||||||
}
|
|
||||||
} else if starter, isStarter := outboundToStart.(interface {
|
|
||||||
Start() error
|
|
||||||
}); isStarter {
|
|
||||||
monitor.Start("start outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
|
||||||
err := starter.Start()
|
|
||||||
monitor.Finish()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "start outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(started) == len(outbounds) {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if canContinue {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
currentOutbound := common.Find(outbounds, func(it adapter.Outbound) bool {
|
|
||||||
return !started[it.Tag()]
|
|
||||||
})
|
|
||||||
var lintOutbound func(oTree []string, oCurrent adapter.Outbound) error
|
|
||||||
lintOutbound = func(oTree []string, oCurrent adapter.Outbound) error {
|
|
||||||
problemOutboundTag := common.Find(oCurrent.Dependencies(), func(it string) bool {
|
|
||||||
return !started[it]
|
|
||||||
})
|
|
||||||
if common.Contains(oTree, problemOutboundTag) {
|
|
||||||
return E.New("circular outbound dependency: ", strings.Join(oTree, " -> "), " -> ", problemOutboundTag)
|
|
||||||
}
|
|
||||||
m.access.Lock()
|
|
||||||
problemOutbound := m.outboundByTag[problemOutboundTag]
|
|
||||||
m.access.Unlock()
|
|
||||||
if problemOutbound == nil {
|
|
||||||
return E.New("dependency[", problemOutboundTag, "] not found for outbound[", oCurrent.Tag(), "]")
|
|
||||||
}
|
|
||||||
return lintOutbound(append(oTree, problemOutboundTag), problemOutbound)
|
|
||||||
}
|
|
||||||
return lintOutbound([]string{currentOutbound.Tag()}, currentOutbound)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Close() error {
|
|
||||||
monitor := taskmonitor.New(m.logger, C.StopTimeout)
|
|
||||||
m.access.Lock()
|
|
||||||
if !m.started {
|
|
||||||
m.access.Unlock()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
m.started = false
|
|
||||||
outbounds := m.outbounds
|
|
||||||
m.outbounds = nil
|
|
||||||
m.access.Unlock()
|
|
||||||
var err error
|
|
||||||
for _, outbound := range outbounds {
|
|
||||||
if closer, isCloser := outbound.(io.Closer); isCloser {
|
|
||||||
monitor.Start("close outbound/", outbound.Type(), "[", outbound.Tag(), "]")
|
|
||||||
err = E.Append(err, closer.Close(), func(err error) error {
|
|
||||||
return E.Cause(err, "close outbound/", outbound.Type(), "[", outbound.Tag(), "]")
|
|
||||||
})
|
|
||||||
monitor.Finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Outbounds() []adapter.Outbound {
|
|
||||||
m.access.RLock()
|
|
||||||
defer m.access.RUnlock()
|
|
||||||
return m.outbounds
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Outbound(tag string) (adapter.Outbound, bool) {
|
|
||||||
m.access.RLock()
|
|
||||||
outbound, found := m.outboundByTag[tag]
|
|
||||||
m.access.RUnlock()
|
|
||||||
if found {
|
|
||||||
return outbound, true
|
|
||||||
}
|
|
||||||
return m.endpoint.Get(tag)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Default() adapter.Outbound {
|
|
||||||
m.access.RLock()
|
|
||||||
defer m.access.RUnlock()
|
|
||||||
if m.defaultOutbound != nil {
|
|
||||||
return m.defaultOutbound
|
|
||||||
} else {
|
|
||||||
return m.defaultOutboundFallback
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Remove(tag string) error {
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
outbound, found := m.outboundByTag[tag]
|
|
||||||
if !found {
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
delete(m.outboundByTag, tag)
|
|
||||||
index := common.Index(m.outbounds, func(it adapter.Outbound) bool {
|
|
||||||
return it == outbound
|
|
||||||
})
|
|
||||||
if index == -1 {
|
|
||||||
panic("invalid inbound index")
|
|
||||||
}
|
|
||||||
m.outbounds = append(m.outbounds[:index], m.outbounds[index+1:]...)
|
|
||||||
started := m.started
|
|
||||||
if m.defaultOutbound == outbound {
|
|
||||||
if len(m.outbounds) > 0 {
|
|
||||||
m.defaultOutbound = m.outbounds[0]
|
|
||||||
m.logger.Info("updated default outbound to ", m.defaultOutbound.Tag())
|
|
||||||
} else {
|
|
||||||
m.defaultOutbound = nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
dependBy := m.dependByTag[tag]
|
|
||||||
if len(dependBy) > 0 {
|
|
||||||
return E.New("outbound[", tag, "] is depended by ", strings.Join(dependBy, ", "))
|
|
||||||
}
|
|
||||||
dependencies := outbound.Dependencies()
|
|
||||||
for _, dependency := range dependencies {
|
|
||||||
if len(m.dependByTag[dependency]) == 1 {
|
|
||||||
delete(m.dependByTag, dependency)
|
|
||||||
} else {
|
|
||||||
m.dependByTag[dependency] = common.Filter(m.dependByTag[dependency], func(it string) bool {
|
|
||||||
return it != tag
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if started {
|
|
||||||
return common.Close(outbound)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Manager) Create(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, inboundType string, options any) error {
|
|
||||||
if tag == "" {
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
outbound, err := m.registry.CreateOutbound(ctx, router, logger, tag, inboundType, options)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
m.access.Lock()
|
|
||||||
defer m.access.Unlock()
|
|
||||||
if m.started {
|
|
||||||
for _, stage := range adapter.ListStartStages {
|
|
||||||
err = adapter.LegacyStart(outbound, stage)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, stage, " outbound/", outbound.Type(), "[", outbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if existsOutbound, loaded := m.outboundByTag[tag]; loaded {
|
|
||||||
if m.started {
|
|
||||||
err = common.Close(existsOutbound)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "close outbound/", existsOutbound.Type(), "[", existsOutbound.Tag(), "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
existsIndex := common.Index(m.outbounds, func(it adapter.Outbound) bool {
|
|
||||||
return it == existsOutbound
|
|
||||||
})
|
|
||||||
if existsIndex == -1 {
|
|
||||||
panic("invalid inbound index")
|
|
||||||
}
|
|
||||||
m.outbounds = append(m.outbounds[:existsIndex], m.outbounds[existsIndex+1:]...)
|
|
||||||
}
|
|
||||||
m.outbounds = append(m.outbounds, outbound)
|
|
||||||
m.outboundByTag[tag] = outbound
|
|
||||||
dependencies := outbound.Dependencies()
|
|
||||||
for _, dependency := range dependencies {
|
|
||||||
m.dependByTag[dependency] = append(m.dependByTag[dependency], tag)
|
|
||||||
}
|
|
||||||
if tag == m.defaultTag || (m.defaultTag == "" && m.defaultOutbound == nil) {
|
|
||||||
m.defaultOutbound = outbound
|
|
||||||
if m.started {
|
|
||||||
m.logger.Info("updated default outbound to ", outbound.Tag())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
package outbound
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"sync"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ConstructorFunc[T any] func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options T) (adapter.Outbound, error)
|
|
||||||
|
|
||||||
func Register[Options any](registry *Registry, outboundType string, constructor ConstructorFunc[Options]) {
|
|
||||||
registry.register(outboundType, func() any {
|
|
||||||
return new(Options)
|
|
||||||
}, func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, rawOptions any) (adapter.Outbound, error) {
|
|
||||||
var options *Options
|
|
||||||
if rawOptions != nil {
|
|
||||||
options = rawOptions.(*Options)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, common.PtrValueOrDefault(options))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ adapter.OutboundRegistry = (*Registry)(nil)
|
|
||||||
|
|
||||||
type (
|
|
||||||
optionsConstructorFunc func() any
|
|
||||||
constructorFunc func(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options any) (adapter.Outbound, error)
|
|
||||||
)
|
|
||||||
|
|
||||||
type Registry struct {
|
|
||||||
access sync.Mutex
|
|
||||||
optionsType map[string]optionsConstructorFunc
|
|
||||||
constructors map[string]constructorFunc
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRegistry() *Registry {
|
|
||||||
return &Registry{
|
|
||||||
optionsType: make(map[string]optionsConstructorFunc),
|
|
||||||
constructors: make(map[string]constructorFunc),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) CreateOptions(outboundType string) (any, bool) {
|
|
||||||
r.access.Lock()
|
|
||||||
defer r.access.Unlock()
|
|
||||||
optionsConstructor, loaded := r.optionsType[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return optionsConstructor(), true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) CreateOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, outboundType string, options any) (adapter.Outbound, error) {
|
|
||||||
r.access.Lock()
|
|
||||||
defer r.access.Unlock()
|
|
||||||
constructor, loaded := r.constructors[outboundType]
|
|
||||||
if !loaded {
|
|
||||||
return nil, E.New("outbound type not found: " + outboundType)
|
|
||||||
}
|
|
||||||
return constructor(ctx, router, logger, tag, options)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Registry) register(outboundType string, optionsConstructor optionsConstructorFunc, constructor constructorFunc) {
|
|
||||||
r.access.Lock()
|
|
||||||
defer r.access.Unlock()
|
|
||||||
r.optionsType[outboundType] = optionsConstructor
|
|
||||||
r.constructors[outboundType] = constructor
|
|
||||||
}
|
|
||||||
@@ -1 +1,9 @@
|
|||||||
package adapter
|
package adapter
|
||||||
|
|
||||||
|
type PreStarter interface {
|
||||||
|
PreStart() error
|
||||||
|
}
|
||||||
|
|
||||||
|
type PostStarter interface {
|
||||||
|
PostStart() error
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,103 +2,118 @@ package adapter
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"net/netip"
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
"github.com/sagernet/sing-box/common/geoip"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
"github.com/sagernet/sing-dns"
|
||||||
|
"github.com/sagernet/sing-tun"
|
||||||
|
"github.com/sagernet/sing/common/control"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/sing/common/x/list"
|
"github.com/sagernet/sing/service"
|
||||||
|
|
||||||
"go4.org/netipx"
|
mdns "github.com/miekg/dns"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Router interface {
|
type Router interface {
|
||||||
Lifecycle
|
Service
|
||||||
|
PreStarter
|
||||||
|
PostStarter
|
||||||
|
|
||||||
|
Outbounds() []Outbound
|
||||||
|
Outbound(tag string) (Outbound, bool)
|
||||||
|
DefaultOutbound(network string) (Outbound, error)
|
||||||
|
|
||||||
|
FakeIPStore() FakeIPStore
|
||||||
|
|
||||||
ConnectionRouter
|
ConnectionRouter
|
||||||
PreMatch(metadata InboundContext) error
|
|
||||||
ConnectionRouterEx
|
GeoIPReader() *geoip.Reader
|
||||||
|
LoadGeosite(code string) (Rule, error)
|
||||||
|
|
||||||
RuleSet(tag string) (RuleSet, bool)
|
RuleSet(tag string) (RuleSet, bool)
|
||||||
|
|
||||||
NeedWIFIState() bool
|
NeedWIFIState() bool
|
||||||
|
|
||||||
|
Exchange(ctx context.Context, message *mdns.Msg) (*mdns.Msg, error)
|
||||||
|
Lookup(ctx context.Context, domain string, strategy dns.DomainStrategy) ([]netip.Addr, error)
|
||||||
|
LookupDefault(ctx context.Context, domain string) ([]netip.Addr, error)
|
||||||
|
ClearDNSCache()
|
||||||
|
|
||||||
|
InterfaceFinder() control.InterfaceFinder
|
||||||
|
UpdateInterfaces() error
|
||||||
|
DefaultInterface() string
|
||||||
|
AutoDetectInterface() bool
|
||||||
|
AutoDetectInterfaceFunc() control.Func
|
||||||
|
DefaultMark() int
|
||||||
|
NetworkMonitor() tun.NetworkUpdateMonitor
|
||||||
|
InterfaceMonitor() tun.DefaultInterfaceMonitor
|
||||||
|
PackageManager() tun.PackageManager
|
||||||
|
WIFIState() WIFIState
|
||||||
Rules() []Rule
|
Rules() []Rule
|
||||||
SetTracker(tracker ConnectionTracker)
|
|
||||||
ResetNetwork()
|
ClashServer() ClashServer
|
||||||
|
SetClashServer(server ClashServer)
|
||||||
|
|
||||||
|
V2RayServer() V2RayServer
|
||||||
|
SetV2RayServer(server V2RayServer)
|
||||||
|
|
||||||
|
ResetNetwork() error
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionTracker interface {
|
func ContextWithRouter(ctx context.Context, router Router) context.Context {
|
||||||
RoutedConnection(ctx context.Context, conn net.Conn, metadata InboundContext, matchedRule Rule, matchOutbound Outbound) net.Conn
|
return service.ContextWith(ctx, router)
|
||||||
RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext, matchedRule Rule, matchOutbound Outbound) N.PacketConn
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
func RouterFromContext(ctx context.Context) Router {
|
||||||
type ConnectionRouter interface {
|
return service.FromContext[Router](ctx)
|
||||||
RouteConnection(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
|
||||||
RoutePacketConnection(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConnectionRouterEx interface {
|
type HeadlessRule interface {
|
||||||
ConnectionRouter
|
Match(metadata *InboundContext) bool
|
||||||
RouteConnectionEx(ctx context.Context, conn net.Conn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
String() string
|
||||||
RoutePacketConnectionEx(ctx context.Context, conn N.PacketConn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
}
|
||||||
|
|
||||||
|
type Rule interface {
|
||||||
|
HeadlessRule
|
||||||
|
Service
|
||||||
|
Type() string
|
||||||
|
UpdateGeosite() error
|
||||||
|
Outbound() string
|
||||||
|
}
|
||||||
|
|
||||||
|
type DNSRule interface {
|
||||||
|
Rule
|
||||||
|
DisableCache() bool
|
||||||
|
RewriteTTL() *uint32
|
||||||
|
ClientSubnet() *netip.Prefix
|
||||||
|
WithAddressLimit() bool
|
||||||
|
MatchAddressLimit(metadata *InboundContext) bool
|
||||||
}
|
}
|
||||||
|
|
||||||
type RuleSet interface {
|
type RuleSet interface {
|
||||||
Name() string
|
StartContext(ctx context.Context, startContext RuleSetStartContext) error
|
||||||
StartContext(ctx context.Context, startContext *HTTPStartContext) error
|
|
||||||
PostStart() error
|
|
||||||
Metadata() RuleSetMetadata
|
Metadata() RuleSetMetadata
|
||||||
ExtractIPSet() []*netipx.IPSet
|
|
||||||
IncRef()
|
|
||||||
DecRef()
|
|
||||||
Cleanup()
|
|
||||||
RegisterCallback(callback RuleSetUpdateCallback) *list.Element[RuleSetUpdateCallback]
|
|
||||||
UnregisterCallback(element *list.Element[RuleSetUpdateCallback])
|
|
||||||
Close() error
|
Close() error
|
||||||
HeadlessRule
|
HeadlessRule
|
||||||
}
|
}
|
||||||
|
|
||||||
type RuleSetUpdateCallback func(it RuleSet)
|
|
||||||
|
|
||||||
type RuleSetMetadata struct {
|
type RuleSetMetadata struct {
|
||||||
ContainsProcessRule bool
|
ContainsProcessRule bool
|
||||||
ContainsWIFIRule bool
|
ContainsWIFIRule bool
|
||||||
ContainsIPCIDRRule bool
|
ContainsIPCIDRRule bool
|
||||||
}
|
}
|
||||||
type HTTPStartContext struct {
|
|
||||||
access sync.Mutex
|
type RuleSetStartContext interface {
|
||||||
httpClientCache map[string]*http.Client
|
HTTPClient(detour string, dialer N.Dialer) *http.Client
|
||||||
|
Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHTTPStartContext() *HTTPStartContext {
|
type InterfaceUpdateListener interface {
|
||||||
return &HTTPStartContext{
|
InterfaceUpdated()
|
||||||
httpClientCache: make(map[string]*http.Client),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *HTTPStartContext) HTTPClient(detour string, dialer N.Dialer) *http.Client {
|
type WIFIState struct {
|
||||||
c.access.Lock()
|
SSID string
|
||||||
defer c.access.Unlock()
|
BSSID string
|
||||||
if httpClient, loaded := c.httpClientCache[detour]; loaded {
|
|
||||||
return httpClient
|
|
||||||
}
|
|
||||||
httpClient := &http.Client{
|
|
||||||
Transport: &http.Transport{
|
|
||||||
ForceAttemptHTTP2: true,
|
|
||||||
TLSHandshakeTimeout: C.TCPTimeout,
|
|
||||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
|
||||||
return dialer.DialContext(ctx, network, M.ParseSocksaddr(addr))
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
c.httpClientCache[detour] = httpClient
|
|
||||||
return httpClient
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *HTTPStartContext) Close() {
|
|
||||||
c.access.Lock()
|
|
||||||
defer c.access.Unlock()
|
|
||||||
for _, client := range c.httpClientCache {
|
|
||||||
client.CloseIdleConnections()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,37 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
)
|
|
||||||
|
|
||||||
type HeadlessRule interface {
|
|
||||||
Match(metadata *InboundContext) bool
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
type Rule interface {
|
|
||||||
HeadlessRule
|
|
||||||
Service
|
|
||||||
Type() string
|
|
||||||
Action() RuleAction
|
|
||||||
}
|
|
||||||
|
|
||||||
type DNSRule interface {
|
|
||||||
Rule
|
|
||||||
WithAddressLimit() bool
|
|
||||||
MatchAddressLimit(metadata *InboundContext) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleAction interface {
|
|
||||||
Type() string
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
func IsFinalAction(action RuleAction) bool {
|
|
||||||
switch action.Type() {
|
|
||||||
case C.RuleActionTypeSniff, C.RuleActionTypeResolve:
|
|
||||||
return false
|
|
||||||
default:
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,165 +4,112 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
type (
|
type (
|
||||||
ConnectionHandlerFuncEx = func(ctx context.Context, conn net.Conn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
ConnectionHandlerFunc = func(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
||||||
PacketConnectionHandlerFuncEx = func(ctx context.Context, conn N.PacketConn, metadata InboundContext, onClose N.CloseHandlerFunc)
|
PacketConnectionHandlerFunc = func(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
||||||
)
|
)
|
||||||
|
|
||||||
func NewUpstreamHandlerEx(
|
func NewUpstreamHandler(
|
||||||
metadata InboundContext,
|
metadata InboundContext,
|
||||||
connectionHandler ConnectionHandlerFuncEx,
|
connectionHandler ConnectionHandlerFunc,
|
||||||
packetHandler PacketConnectionHandlerFuncEx,
|
packetHandler PacketConnectionHandlerFunc,
|
||||||
) UpstreamHandlerAdapterEx {
|
errorHandler E.Handler,
|
||||||
return &myUpstreamHandlerWrapperEx{
|
) UpstreamHandlerAdapter {
|
||||||
|
return &myUpstreamHandlerWrapper{
|
||||||
metadata: metadata,
|
metadata: metadata,
|
||||||
connectionHandler: connectionHandler,
|
connectionHandler: connectionHandler,
|
||||||
packetHandler: packetHandler,
|
packetHandler: packetHandler,
|
||||||
|
errorHandler: errorHandler,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapterEx = (*myUpstreamHandlerWrapperEx)(nil)
|
var _ UpstreamHandlerAdapter = (*myUpstreamHandlerWrapper)(nil)
|
||||||
|
|
||||||
type myUpstreamHandlerWrapperEx struct {
|
type myUpstreamHandlerWrapper struct {
|
||||||
metadata InboundContext
|
metadata InboundContext
|
||||||
connectionHandler ConnectionHandlerFuncEx
|
connectionHandler ConnectionHandlerFunc
|
||||||
packetHandler PacketConnectionHandlerFuncEx
|
packetHandler PacketConnectionHandlerFunc
|
||||||
|
errorHandler E.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamHandlerWrapperEx) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
myMetadata := w.metadata
|
myMetadata := w.metadata
|
||||||
if source.IsValid() {
|
if metadata.Source.IsValid() {
|
||||||
myMetadata.Source = source
|
myMetadata.Source = metadata.Source
|
||||||
}
|
}
|
||||||
if destination.IsValid() {
|
if metadata.Destination.IsValid() {
|
||||||
myMetadata.Destination = destination
|
myMetadata.Destination = metadata.Destination
|
||||||
}
|
}
|
||||||
w.connectionHandler(ctx, conn, myMetadata, onClose)
|
return w.connectionHandler(ctx, conn, myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamHandlerWrapperEx) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
myMetadata := w.metadata
|
myMetadata := w.metadata
|
||||||
if source.IsValid() {
|
if metadata.Source.IsValid() {
|
||||||
myMetadata.Source = source
|
myMetadata.Source = metadata.Source
|
||||||
}
|
}
|
||||||
if destination.IsValid() {
|
if metadata.Destination.IsValid() {
|
||||||
myMetadata.Destination = destination
|
myMetadata.Destination = metadata.Destination
|
||||||
}
|
}
|
||||||
w.packetHandler(ctx, conn, myMetadata, onClose)
|
return w.packetHandler(ctx, conn, myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapterEx = (*myUpstreamContextHandlerWrapperEx)(nil)
|
func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) {
|
||||||
|
w.errorHandler.NewError(ctx, err)
|
||||||
type myUpstreamContextHandlerWrapperEx struct {
|
|
||||||
connectionHandler ConnectionHandlerFuncEx
|
|
||||||
packetHandler PacketConnectionHandlerFuncEx
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUpstreamContextHandlerEx(
|
func UpstreamMetadata(metadata InboundContext) M.Metadata {
|
||||||
connectionHandler ConnectionHandlerFuncEx,
|
return M.Metadata{
|
||||||
packetHandler PacketConnectionHandlerFuncEx,
|
Source: metadata.Source,
|
||||||
) UpstreamHandlerAdapterEx {
|
Destination: metadata.Destination,
|
||||||
return &myUpstreamContextHandlerWrapperEx{
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type myUpstreamContextHandlerWrapper struct {
|
||||||
|
connectionHandler ConnectionHandlerFunc
|
||||||
|
packetHandler PacketConnectionHandlerFunc
|
||||||
|
errorHandler E.Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUpstreamContextHandler(
|
||||||
|
connectionHandler ConnectionHandlerFunc,
|
||||||
|
packetHandler PacketConnectionHandlerFunc,
|
||||||
|
errorHandler E.Handler,
|
||||||
|
) UpstreamHandlerAdapter {
|
||||||
|
return &myUpstreamContextHandlerWrapper{
|
||||||
connectionHandler: connectionHandler,
|
connectionHandler: connectionHandler,
|
||||||
packetHandler: packetHandler,
|
packetHandler: packetHandler,
|
||||||
|
errorHandler: errorHandler,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamContextHandlerWrapperEx) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
||||||
myMetadata := ContextFrom(ctx)
|
myMetadata := ContextFrom(ctx)
|
||||||
if source.IsValid() {
|
if metadata.Source.IsValid() {
|
||||||
myMetadata.Source = source
|
myMetadata.Source = metadata.Source
|
||||||
}
|
}
|
||||||
if destination.IsValid() {
|
if metadata.Destination.IsValid() {
|
||||||
myMetadata.Destination = destination
|
myMetadata.Destination = metadata.Destination
|
||||||
}
|
}
|
||||||
w.connectionHandler(ctx, conn, *myMetadata, onClose)
|
return w.connectionHandler(ctx, conn, *myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (w *myUpstreamContextHandlerWrapperEx) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
||||||
myMetadata := ContextFrom(ctx)
|
myMetadata := ContextFrom(ctx)
|
||||||
if source.IsValid() {
|
if metadata.Source.IsValid() {
|
||||||
myMetadata.Source = source
|
myMetadata.Source = metadata.Source
|
||||||
}
|
}
|
||||||
if destination.IsValid() {
|
if metadata.Destination.IsValid() {
|
||||||
myMetadata.Destination = destination
|
myMetadata.Destination = metadata.Destination
|
||||||
}
|
}
|
||||||
w.packetHandler(ctx, conn, *myMetadata, onClose)
|
return w.packetHandler(ctx, conn, *myMetadata)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewRouteHandlerEx(
|
func (w *myUpstreamContextHandlerWrapper) NewError(ctx context.Context, err error) {
|
||||||
metadata InboundContext,
|
w.errorHandler.NewError(ctx, err)
|
||||||
router ConnectionRouterEx,
|
|
||||||
) UpstreamHandlerAdapterEx {
|
|
||||||
return &routeHandlerWrapperEx{
|
|
||||||
metadata: metadata,
|
|
||||||
router: router,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapterEx = (*routeHandlerWrapperEx)(nil)
|
|
||||||
|
|
||||||
type routeHandlerWrapperEx struct {
|
|
||||||
metadata InboundContext
|
|
||||||
router ConnectionRouterEx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *routeHandlerWrapperEx) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
|
||||||
if source.IsValid() {
|
|
||||||
r.metadata.Source = source
|
|
||||||
}
|
|
||||||
if destination.IsValid() {
|
|
||||||
r.metadata.Destination = destination
|
|
||||||
}
|
|
||||||
r.router.RouteConnectionEx(ctx, conn, r.metadata, onClose)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *routeHandlerWrapperEx) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
|
||||||
if source.IsValid() {
|
|
||||||
r.metadata.Source = source
|
|
||||||
}
|
|
||||||
if destination.IsValid() {
|
|
||||||
r.metadata.Destination = destination
|
|
||||||
}
|
|
||||||
r.router.RoutePacketConnectionEx(ctx, conn, r.metadata, onClose)
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewRouteContextHandlerEx(
|
|
||||||
router ConnectionRouterEx,
|
|
||||||
) UpstreamHandlerAdapterEx {
|
|
||||||
return &routeContextHandlerWrapperEx{
|
|
||||||
router: router,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapterEx = (*routeContextHandlerWrapperEx)(nil)
|
|
||||||
|
|
||||||
type routeContextHandlerWrapperEx struct {
|
|
||||||
router ConnectionRouterEx
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *routeContextHandlerWrapperEx) NewConnectionEx(ctx context.Context, conn net.Conn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
|
||||||
metadata := ContextFrom(ctx)
|
|
||||||
if source.IsValid() {
|
|
||||||
metadata.Source = source
|
|
||||||
}
|
|
||||||
if destination.IsValid() {
|
|
||||||
metadata.Destination = destination
|
|
||||||
}
|
|
||||||
r.router.RouteConnectionEx(ctx, conn, *metadata, onClose)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *routeContextHandlerWrapperEx) NewPacketConnectionEx(ctx context.Context, conn N.PacketConn, source M.Socksaddr, destination M.Socksaddr, onClose N.CloseHandlerFunc) {
|
|
||||||
metadata := ContextFrom(ctx)
|
|
||||||
if source.IsValid() {
|
|
||||||
metadata.Source = source
|
|
||||||
}
|
|
||||||
if destination.IsValid() {
|
|
||||||
metadata.Destination = destination
|
|
||||||
}
|
|
||||||
r.router.RoutePacketConnectionEx(ctx, conn, *metadata, onClose)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,234 +0,0 @@
|
|||||||
package adapter
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
"github.com/sagernet/sing/common/logger"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type (
|
|
||||||
// Deprecated
|
|
||||||
ConnectionHandlerFunc = func(ctx context.Context, conn net.Conn, metadata InboundContext) error
|
|
||||||
// Deprecated
|
|
||||||
PacketConnectionHandlerFunc = func(ctx context.Context, conn N.PacketConn, metadata InboundContext) error
|
|
||||||
)
|
|
||||||
|
|
||||||
// Deprecated
|
|
||||||
//
|
|
||||||
//nolint:staticcheck
|
|
||||||
func NewUpstreamHandler(
|
|
||||||
metadata InboundContext,
|
|
||||||
connectionHandler ConnectionHandlerFunc,
|
|
||||||
packetHandler PacketConnectionHandlerFunc,
|
|
||||||
errorHandler E.Handler,
|
|
||||||
) UpstreamHandlerAdapter {
|
|
||||||
return &myUpstreamHandlerWrapper{
|
|
||||||
metadata: metadata,
|
|
||||||
connectionHandler: connectionHandler,
|
|
||||||
packetHandler: packetHandler,
|
|
||||||
errorHandler: errorHandler,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapter = (*myUpstreamHandlerWrapper)(nil)
|
|
||||||
|
|
||||||
// Deprecated: use myUpstreamHandlerWrapperEx instead.
|
|
||||||
//
|
|
||||||
//nolint:staticcheck
|
|
||||||
type myUpstreamHandlerWrapper struct {
|
|
||||||
metadata InboundContext
|
|
||||||
connectionHandler ConnectionHandlerFunc
|
|
||||||
packetHandler PacketConnectionHandlerFunc
|
|
||||||
errorHandler E.Handler
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use myUpstreamHandlerWrapperEx instead.
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
|
||||||
myMetadata := w.metadata
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.connectionHandler(ctx, conn, myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use myUpstreamHandlerWrapperEx instead.
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
|
||||||
myMetadata := w.metadata
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.packetHandler(ctx, conn, myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: use myUpstreamHandlerWrapperEx instead.
|
|
||||||
func (w *myUpstreamHandlerWrapper) NewError(ctx context.Context, err error) {
|
|
||||||
w.errorHandler.NewError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: removed
|
|
||||||
func UpstreamMetadata(metadata InboundContext) M.Metadata {
|
|
||||||
return M.Metadata{
|
|
||||||
Source: metadata.Source,
|
|
||||||
Destination: metadata.Destination,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use NewUpstreamContextHandlerEx instead.
|
|
||||||
type myUpstreamContextHandlerWrapper struct {
|
|
||||||
connectionHandler ConnectionHandlerFunc
|
|
||||||
packetHandler PacketConnectionHandlerFunc
|
|
||||||
errorHandler E.Handler
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use NewUpstreamContextHandlerEx instead.
|
|
||||||
func NewUpstreamContextHandler(
|
|
||||||
connectionHandler ConnectionHandlerFunc,
|
|
||||||
packetHandler PacketConnectionHandlerFunc,
|
|
||||||
errorHandler E.Handler,
|
|
||||||
) UpstreamHandlerAdapter {
|
|
||||||
return &myUpstreamContextHandlerWrapper{
|
|
||||||
connectionHandler: connectionHandler,
|
|
||||||
packetHandler: packetHandler,
|
|
||||||
errorHandler: errorHandler,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use NewUpstreamContextHandlerEx instead.
|
|
||||||
func (w *myUpstreamContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
|
||||||
myMetadata := ContextFrom(ctx)
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.connectionHandler(ctx, conn, *myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use NewUpstreamContextHandlerEx instead.
|
|
||||||
func (w *myUpstreamContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
|
||||||
myMetadata := ContextFrom(ctx)
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.packetHandler(ctx, conn, *myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use NewUpstreamContextHandlerEx instead.
|
|
||||||
func (w *myUpstreamContextHandlerWrapper) NewError(ctx context.Context, err error) {
|
|
||||||
w.errorHandler.NewError(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func NewRouteHandler(
|
|
||||||
metadata InboundContext,
|
|
||||||
router ConnectionRouter,
|
|
||||||
logger logger.ContextLogger,
|
|
||||||
) UpstreamHandlerAdapter {
|
|
||||||
return &routeHandlerWrapper{
|
|
||||||
metadata: metadata,
|
|
||||||
router: router,
|
|
||||||
logger: logger,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func NewRouteContextHandler(
|
|
||||||
router ConnectionRouter,
|
|
||||||
logger logger.ContextLogger,
|
|
||||||
) UpstreamHandlerAdapter {
|
|
||||||
return &routeContextHandlerWrapper{
|
|
||||||
router: router,
|
|
||||||
logger: logger,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapter = (*routeHandlerWrapper)(nil)
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
//
|
|
||||||
//nolint:staticcheck
|
|
||||||
type routeHandlerWrapper struct {
|
|
||||||
metadata InboundContext
|
|
||||||
router ConnectionRouter
|
|
||||||
logger logger.ContextLogger
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
|
||||||
myMetadata := w.metadata
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.router.RouteConnection(ctx, conn, myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
|
||||||
myMetadata := w.metadata
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.router.RoutePacketConnection(ctx, conn, myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeHandlerWrapper) NewError(ctx context.Context, err error) {
|
|
||||||
w.logger.ErrorContext(ctx, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var _ UpstreamHandlerAdapter = (*routeContextHandlerWrapper)(nil)
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
type routeContextHandlerWrapper struct {
|
|
||||||
router ConnectionRouter
|
|
||||||
logger logger.ContextLogger
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeContextHandlerWrapper) NewConnection(ctx context.Context, conn net.Conn, metadata M.Metadata) error {
|
|
||||||
myMetadata := ContextFrom(ctx)
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.router.RouteConnection(ctx, conn, *myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeContextHandlerWrapper) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata M.Metadata) error {
|
|
||||||
myMetadata := ContextFrom(ctx)
|
|
||||||
if metadata.Source.IsValid() {
|
|
||||||
myMetadata.Source = metadata.Source
|
|
||||||
}
|
|
||||||
if metadata.Destination.IsValid() {
|
|
||||||
myMetadata.Destination = metadata.Destination
|
|
||||||
}
|
|
||||||
return w.router.RoutePacketConnection(ctx, conn, *myMetadata)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Deprecated: Use ConnectionRouterEx instead.
|
|
||||||
func (w *routeContextHandlerWrapper) NewError(ctx context.Context, err error) {
|
|
||||||
w.logger.ErrorContext(ctx, err)
|
|
||||||
}
|
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -15,10 +16,10 @@ type V2RayServerTransport interface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type V2RayServerTransportHandler interface {
|
type V2RayServerTransportHandler interface {
|
||||||
N.TCPConnectionHandlerEx
|
N.TCPConnectionHandler
|
||||||
|
E.Handler
|
||||||
}
|
}
|
||||||
|
|
||||||
type V2RayClientTransport interface {
|
type V2RayClientTransport interface {
|
||||||
DialContext(ctx context.Context) (net.Conn, error)
|
DialContext(ctx context.Context) (net.Conn, error)
|
||||||
Close() error
|
|
||||||
}
|
}
|
||||||
|
|||||||
451
box.go
451
box.go
@@ -9,26 +9,19 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/adapter/endpoint"
|
|
||||||
"github.com/sagernet/sing-box/adapter/inbound"
|
|
||||||
"github.com/sagernet/sing-box/adapter/outbound"
|
|
||||||
"github.com/sagernet/sing-box/common/dialer"
|
|
||||||
"github.com/sagernet/sing-box/common/taskmonitor"
|
"github.com/sagernet/sing-box/common/taskmonitor"
|
||||||
"github.com/sagernet/sing-box/common/tls"
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
"github.com/sagernet/sing-box/dns"
|
|
||||||
"github.com/sagernet/sing-box/dns/transport/local"
|
|
||||||
"github.com/sagernet/sing-box/experimental"
|
"github.com/sagernet/sing-box/experimental"
|
||||||
"github.com/sagernet/sing-box/experimental/cachefile"
|
"github.com/sagernet/sing-box/experimental/cachefile"
|
||||||
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
"github.com/sagernet/sing-box/experimental/libbox/platform"
|
||||||
|
"github.com/sagernet/sing-box/inbound"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
"github.com/sagernet/sing-box/protocol/direct"
|
"github.com/sagernet/sing-box/outbound"
|
||||||
"github.com/sagernet/sing-box/route"
|
"github.com/sagernet/sing-box/route"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
F "github.com/sagernet/sing/common/format"
|
F "github.com/sagernet/sing/common/format"
|
||||||
"github.com/sagernet/sing/common/ntp"
|
|
||||||
"github.com/sagernet/sing/service"
|
"github.com/sagernet/sing/service"
|
||||||
"github.com/sagernet/sing/service/pause"
|
"github.com/sagernet/sing/service/pause"
|
||||||
)
|
)
|
||||||
@@ -37,55 +30,24 @@ var _ adapter.Service = (*Box)(nil)
|
|||||||
|
|
||||||
type Box struct {
|
type Box struct {
|
||||||
createdAt time.Time
|
createdAt time.Time
|
||||||
|
router adapter.Router
|
||||||
|
inbounds []adapter.Inbound
|
||||||
|
outbounds []adapter.Outbound
|
||||||
logFactory log.Factory
|
logFactory log.Factory
|
||||||
logger log.ContextLogger
|
logger log.ContextLogger
|
||||||
network *route.NetworkManager
|
preServices1 map[string]adapter.Service
|
||||||
endpoint *endpoint.Manager
|
preServices2 map[string]adapter.Service
|
||||||
inbound *inbound.Manager
|
postServices map[string]adapter.Service
|
||||||
outbound *outbound.Manager
|
|
||||||
dnsTransport *dns.TransportManager
|
|
||||||
dnsRouter *dns.Router
|
|
||||||
connection *route.ConnectionManager
|
|
||||||
router *route.Router
|
|
||||||
services []adapter.LifecycleService
|
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
}
|
}
|
||||||
|
|
||||||
type Options struct {
|
type Options struct {
|
||||||
option.Options
|
option.Options
|
||||||
Context context.Context
|
Context context.Context
|
||||||
|
PlatformInterface platform.Interface
|
||||||
PlatformLogWriter log.PlatformWriter
|
PlatformLogWriter log.PlatformWriter
|
||||||
}
|
}
|
||||||
|
|
||||||
func Context(
|
|
||||||
ctx context.Context,
|
|
||||||
inboundRegistry adapter.InboundRegistry,
|
|
||||||
outboundRegistry adapter.OutboundRegistry,
|
|
||||||
endpointRegistry adapter.EndpointRegistry,
|
|
||||||
dnsTransportRegistry adapter.DNSTransportRegistry,
|
|
||||||
) context.Context {
|
|
||||||
if service.FromContext[option.InboundOptionsRegistry](ctx) == nil ||
|
|
||||||
service.FromContext[adapter.InboundRegistry](ctx) == nil {
|
|
||||||
ctx = service.ContextWith[option.InboundOptionsRegistry](ctx, inboundRegistry)
|
|
||||||
ctx = service.ContextWith[adapter.InboundRegistry](ctx, inboundRegistry)
|
|
||||||
}
|
|
||||||
if service.FromContext[option.OutboundOptionsRegistry](ctx) == nil ||
|
|
||||||
service.FromContext[adapter.OutboundRegistry](ctx) == nil {
|
|
||||||
ctx = service.ContextWith[option.OutboundOptionsRegistry](ctx, outboundRegistry)
|
|
||||||
ctx = service.ContextWith[adapter.OutboundRegistry](ctx, outboundRegistry)
|
|
||||||
}
|
|
||||||
if service.FromContext[option.EndpointOptionsRegistry](ctx) == nil ||
|
|
||||||
service.FromContext[adapter.EndpointRegistry](ctx) == nil {
|
|
||||||
ctx = service.ContextWith[option.EndpointOptionsRegistry](ctx, endpointRegistry)
|
|
||||||
ctx = service.ContextWith[adapter.EndpointRegistry](ctx, endpointRegistry)
|
|
||||||
}
|
|
||||||
if service.FromContext[adapter.DNSTransportRegistry](ctx) == nil {
|
|
||||||
ctx = service.ContextWith[option.DNSTransportOptionsRegistry](ctx, dnsTransportRegistry)
|
|
||||||
ctx = service.ContextWith[adapter.DNSTransportRegistry](ctx, dnsTransportRegistry)
|
|
||||||
}
|
|
||||||
return ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(options Options) (*Box, error) {
|
func New(options Options) (*Box, error) {
|
||||||
createdAt := time.Now()
|
createdAt := time.Now()
|
||||||
ctx := options.Context
|
ctx := options.Context
|
||||||
@@ -93,22 +55,6 @@ func New(options Options) (*Box, error) {
|
|||||||
ctx = context.Background()
|
ctx = context.Background()
|
||||||
}
|
}
|
||||||
ctx = service.ContextWithDefaultRegistry(ctx)
|
ctx = service.ContextWithDefaultRegistry(ctx)
|
||||||
|
|
||||||
endpointRegistry := service.FromContext[adapter.EndpointRegistry](ctx)
|
|
||||||
inboundRegistry := service.FromContext[adapter.InboundRegistry](ctx)
|
|
||||||
outboundRegistry := service.FromContext[adapter.OutboundRegistry](ctx)
|
|
||||||
dnsTransportRegistry := service.FromContext[adapter.DNSTransportRegistry](ctx)
|
|
||||||
|
|
||||||
if endpointRegistry == nil {
|
|
||||||
return nil, E.New("missing endpoint registry in context")
|
|
||||||
}
|
|
||||||
if inboundRegistry == nil {
|
|
||||||
return nil, E.New("missing inbound registry in context")
|
|
||||||
}
|
|
||||||
if outboundRegistry == nil {
|
|
||||||
return nil, E.New("missing outbound registry in context")
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx = pause.WithDefaultManager(ctx)
|
ctx = pause.WithDefaultManager(ctx)
|
||||||
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
|
experimentalOptions := common.PtrValueOrDefault(options.Experimental)
|
||||||
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
|
applyDebugOptions(common.PtrValueOrDefault(experimentalOptions.Debug))
|
||||||
@@ -124,9 +70,8 @@ func New(options Options) (*Box, error) {
|
|||||||
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
|
if experimentalOptions.V2RayAPI != nil && experimentalOptions.V2RayAPI.Listen != "" {
|
||||||
needV2RayAPI = true
|
needV2RayAPI = true
|
||||||
}
|
}
|
||||||
platformInterface := service.FromContext[platform.Interface](ctx)
|
|
||||||
var defaultLogWriter io.Writer
|
var defaultLogWriter io.Writer
|
||||||
if platformInterface != nil {
|
if options.PlatformInterface != nil {
|
||||||
defaultLogWriter = io.Discard
|
defaultLogWriter = io.Discard
|
||||||
}
|
}
|
||||||
logFactory, err := log.New(log.Options{
|
logFactory, err := log.New(log.Options{
|
||||||
@@ -140,203 +85,114 @@ func New(options Options) (*Box, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create log factory")
|
return nil, E.Cause(err, "create log factory")
|
||||||
}
|
}
|
||||||
|
router, err := route.NewRouter(
|
||||||
routeOptions := common.PtrValueOrDefault(options.Route)
|
ctx,
|
||||||
dnsOptions := common.PtrValueOrDefault(options.DNS)
|
logFactory,
|
||||||
endpointManager := endpoint.NewManager(logFactory.NewLogger("endpoint"), endpointRegistry)
|
common.PtrValueOrDefault(options.Route),
|
||||||
inboundManager := inbound.NewManager(logFactory.NewLogger("inbound"), inboundRegistry, endpointManager)
|
common.PtrValueOrDefault(options.DNS),
|
||||||
outboundManager := outbound.NewManager(logFactory.NewLogger("outbound"), outboundRegistry, endpointManager, routeOptions.Final)
|
common.PtrValueOrDefault(options.NTP),
|
||||||
dnsTransportManager := dns.NewTransportManager(logFactory.NewLogger("dns/transport"), dnsTransportRegistry, outboundManager, dnsOptions.Final)
|
options.Inbounds,
|
||||||
service.MustRegister[adapter.EndpointManager](ctx, endpointManager)
|
options.PlatformInterface,
|
||||||
service.MustRegister[adapter.InboundManager](ctx, inboundManager)
|
)
|
||||||
service.MustRegister[adapter.OutboundManager](ctx, outboundManager)
|
|
||||||
service.MustRegister[adapter.DNSTransportManager](ctx, dnsTransportManager)
|
|
||||||
dnsRouter := dns.NewRouter(ctx, logFactory, dnsOptions)
|
|
||||||
service.MustRegister[adapter.DNSRouter](ctx, dnsRouter)
|
|
||||||
networkManager, err := route.NewNetworkManager(ctx, logFactory.NewLogger("network"), routeOptions)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "initialize network manager")
|
return nil, E.Cause(err, "parse route options")
|
||||||
}
|
|
||||||
service.MustRegister[adapter.NetworkManager](ctx, networkManager)
|
|
||||||
connectionManager := route.NewConnectionManager(logFactory.NewLogger("connection"))
|
|
||||||
service.MustRegister[adapter.ConnectionManager](ctx, connectionManager)
|
|
||||||
router := route.NewRouter(ctx, logFactory, routeOptions, dnsOptions)
|
|
||||||
service.MustRegister[adapter.Router](ctx, router)
|
|
||||||
err = router.Initialize(routeOptions.Rules, routeOptions.RuleSet)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "initialize router")
|
|
||||||
}
|
|
||||||
ntpOptions := common.PtrValueOrDefault(options.NTP)
|
|
||||||
var timeService *tls.TimeServiceWrapper
|
|
||||||
if ntpOptions.Enabled {
|
|
||||||
timeService = new(tls.TimeServiceWrapper)
|
|
||||||
service.MustRegister[ntp.TimeService](ctx, timeService)
|
|
||||||
}
|
|
||||||
for i, transportOptions := range dnsOptions.Servers {
|
|
||||||
var tag string
|
|
||||||
if transportOptions.Tag != "" {
|
|
||||||
tag = transportOptions.Tag
|
|
||||||
} else {
|
|
||||||
tag = F.ToString(i)
|
|
||||||
}
|
|
||||||
err = dnsTransportManager.Create(
|
|
||||||
ctx,
|
|
||||||
logFactory.NewLogger(F.ToString("dns/", transportOptions.Type, "[", tag, "]")),
|
|
||||||
tag,
|
|
||||||
transportOptions.Type,
|
|
||||||
transportOptions.Options,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "initialize inbound[", i, "]")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = dnsRouter.Initialize(dnsOptions.Rules)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "initialize dns router")
|
|
||||||
}
|
|
||||||
for i, endpointOptions := range options.Endpoints {
|
|
||||||
var tag string
|
|
||||||
if endpointOptions.Tag != "" {
|
|
||||||
tag = endpointOptions.Tag
|
|
||||||
} else {
|
|
||||||
tag = F.ToString(i)
|
|
||||||
}
|
|
||||||
err = endpointManager.Create(
|
|
||||||
ctx,
|
|
||||||
router,
|
|
||||||
logFactory.NewLogger(F.ToString("endpoint/", endpointOptions.Type, "[", tag, "]")),
|
|
||||||
tag,
|
|
||||||
endpointOptions.Type,
|
|
||||||
endpointOptions.Options,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "initialize inbound[", i, "]")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
inbounds := make([]adapter.Inbound, 0, len(options.Inbounds))
|
||||||
|
outbounds := make([]adapter.Outbound, 0, len(options.Outbounds))
|
||||||
for i, inboundOptions := range options.Inbounds {
|
for i, inboundOptions := range options.Inbounds {
|
||||||
|
var in adapter.Inbound
|
||||||
var tag string
|
var tag string
|
||||||
if inboundOptions.Tag != "" {
|
if inboundOptions.Tag != "" {
|
||||||
tag = inboundOptions.Tag
|
tag = inboundOptions.Tag
|
||||||
} else {
|
} else {
|
||||||
tag = F.ToString(i)
|
tag = F.ToString(i)
|
||||||
}
|
}
|
||||||
err = inboundManager.Create(
|
in, err = inbound.New(
|
||||||
ctx,
|
ctx,
|
||||||
router,
|
router,
|
||||||
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
|
logFactory.NewLogger(F.ToString("inbound/", inboundOptions.Type, "[", tag, "]")),
|
||||||
tag,
|
tag,
|
||||||
inboundOptions.Type,
|
inboundOptions,
|
||||||
inboundOptions.Options,
|
options.PlatformInterface,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "initialize inbound[", i, "]")
|
return nil, E.Cause(err, "parse inbound[", i, "]")
|
||||||
}
|
}
|
||||||
|
inbounds = append(inbounds, in)
|
||||||
}
|
}
|
||||||
for i, outboundOptions := range options.Outbounds {
|
for i, outboundOptions := range options.Outbounds {
|
||||||
|
var out adapter.Outbound
|
||||||
var tag string
|
var tag string
|
||||||
if outboundOptions.Tag != "" {
|
if outboundOptions.Tag != "" {
|
||||||
tag = outboundOptions.Tag
|
tag = outboundOptions.Tag
|
||||||
} else {
|
} else {
|
||||||
tag = F.ToString(i)
|
tag = F.ToString(i)
|
||||||
}
|
}
|
||||||
outboundCtx := ctx
|
out, err = outbound.New(
|
||||||
if tag != "" {
|
ctx,
|
||||||
// TODO: remove this
|
|
||||||
outboundCtx = adapter.WithContext(outboundCtx, &adapter.InboundContext{
|
|
||||||
Outbound: tag,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
err = outboundManager.Create(
|
|
||||||
outboundCtx,
|
|
||||||
router,
|
router,
|
||||||
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
|
logFactory.NewLogger(F.ToString("outbound/", outboundOptions.Type, "[", tag, "]")),
|
||||||
tag,
|
tag,
|
||||||
outboundOptions.Type,
|
outboundOptions)
|
||||||
outboundOptions.Options,
|
|
||||||
)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "initialize outbound[", i, "]")
|
return nil, E.Cause(err, "parse outbound[", i, "]")
|
||||||
}
|
}
|
||||||
|
outbounds = append(outbounds, out)
|
||||||
}
|
}
|
||||||
outboundManager.Initialize(common.Must1(
|
err = router.Initialize(inbounds, outbounds, func() adapter.Outbound {
|
||||||
direct.NewOutbound(
|
out, oErr := outbound.New(ctx, router, logFactory.NewLogger("outbound/direct"), "direct", option.Outbound{Type: "direct", Tag: "default"})
|
||||||
ctx,
|
common.Must(oErr)
|
||||||
router,
|
outbounds = append(outbounds, out)
|
||||||
logFactory.NewLogger("outbound/direct"),
|
return out
|
||||||
"direct",
|
})
|
||||||
option.DirectOutboundOptions{},
|
if err != nil {
|
||||||
),
|
return nil, err
|
||||||
))
|
}
|
||||||
dnsTransportManager.Initialize(common.Must1(
|
if options.PlatformInterface != nil {
|
||||||
local.NewTransport(
|
err = options.PlatformInterface.Initialize(ctx, router)
|
||||||
ctx,
|
|
||||||
logFactory.NewLogger("dns/local"),
|
|
||||||
"local",
|
|
||||||
option.LocalDNSServerOptions{},
|
|
||||||
)))
|
|
||||||
if platformInterface != nil {
|
|
||||||
err = platformInterface.Initialize(networkManager)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "initialize platform interface")
|
return nil, E.Cause(err, "initialize platform interface")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var services []adapter.LifecycleService
|
preServices1 := make(map[string]adapter.Service)
|
||||||
|
preServices2 := make(map[string]adapter.Service)
|
||||||
|
postServices := make(map[string]adapter.Service)
|
||||||
if needCacheFile {
|
if needCacheFile {
|
||||||
cacheFile := cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
|
cacheFile := service.FromContext[adapter.CacheFile](ctx)
|
||||||
service.MustRegister[adapter.CacheFile](ctx, cacheFile)
|
if cacheFile == nil {
|
||||||
services = append(services, cacheFile)
|
cacheFile = cachefile.New(ctx, common.PtrValueOrDefault(experimentalOptions.CacheFile))
|
||||||
|
service.MustRegister[adapter.CacheFile](ctx, cacheFile)
|
||||||
|
}
|
||||||
|
preServices1["cache file"] = cacheFile
|
||||||
}
|
}
|
||||||
if needClashAPI {
|
if needClashAPI {
|
||||||
clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI)
|
clashAPIOptions := common.PtrValueOrDefault(experimentalOptions.ClashAPI)
|
||||||
clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
|
clashAPIOptions.ModeList = experimental.CalculateClashModeList(options.Options)
|
||||||
clashServer, err := experimental.NewClashServer(ctx, logFactory.(log.ObservableFactory), clashAPIOptions)
|
clashServer, err := experimental.NewClashServer(ctx, router, logFactory.(log.ObservableFactory), clashAPIOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create clash-server")
|
return nil, E.Cause(err, "create clash api server")
|
||||||
}
|
}
|
||||||
router.SetTracker(clashServer)
|
router.SetClashServer(clashServer)
|
||||||
service.MustRegister[adapter.ClashServer](ctx, clashServer)
|
preServices2["clash api"] = clashServer
|
||||||
services = append(services, clashServer)
|
|
||||||
}
|
}
|
||||||
if needV2RayAPI {
|
if needV2RayAPI {
|
||||||
v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
|
v2rayServer, err := experimental.NewV2RayServer(logFactory.NewLogger("v2ray-api"), common.PtrValueOrDefault(experimentalOptions.V2RayAPI))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create v2ray-server")
|
return nil, E.Cause(err, "create v2ray api server")
|
||||||
}
|
}
|
||||||
if v2rayServer.StatsService() != nil {
|
router.SetV2RayServer(v2rayServer)
|
||||||
router.SetTracker(v2rayServer.StatsService())
|
preServices2["v2ray api"] = v2rayServer
|
||||||
services = append(services, v2rayServer)
|
|
||||||
service.MustRegister[adapter.V2RayServer](ctx, v2rayServer)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ntpOptions.Enabled {
|
|
||||||
ntpDialer, err := dialer.New(ctx, ntpOptions.DialerOptions, ntpOptions.ServerIsDomain())
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "create NTP service")
|
|
||||||
}
|
|
||||||
ntpService := ntp.NewService(ntp.Options{
|
|
||||||
Context: ctx,
|
|
||||||
Dialer: ntpDialer,
|
|
||||||
Logger: logFactory.NewLogger("ntp"),
|
|
||||||
Server: ntpOptions.ServerOptions.Build(),
|
|
||||||
Interval: time.Duration(ntpOptions.Interval),
|
|
||||||
WriteToSystem: ntpOptions.WriteToSystem,
|
|
||||||
})
|
|
||||||
timeService.TimeService = ntpService
|
|
||||||
services = append(services, adapter.NewLifecycleService(ntpService, "ntp service"))
|
|
||||||
}
|
}
|
||||||
return &Box{
|
return &Box{
|
||||||
network: networkManager,
|
|
||||||
endpoint: endpointManager,
|
|
||||||
inbound: inboundManager,
|
|
||||||
outbound: outboundManager,
|
|
||||||
dnsTransport: dnsTransportManager,
|
|
||||||
dnsRouter: dnsRouter,
|
|
||||||
connection: connectionManager,
|
|
||||||
router: router,
|
router: router,
|
||||||
|
inbounds: inbounds,
|
||||||
|
outbounds: outbounds,
|
||||||
createdAt: createdAt,
|
createdAt: createdAt,
|
||||||
logFactory: logFactory,
|
logFactory: logFactory,
|
||||||
logger: logFactory.Logger(),
|
logger: logFactory.Logger(),
|
||||||
services: services,
|
preServices1: preServices1,
|
||||||
|
preServices2: preServices2,
|
||||||
|
postServices: postServices,
|
||||||
done: make(chan struct{}),
|
done: make(chan struct{}),
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
@@ -348,7 +204,7 @@ func (s *Box) PreStart() error {
|
|||||||
defer func() {
|
defer func() {
|
||||||
v := recover()
|
v := recover()
|
||||||
if v != nil {
|
if v != nil {
|
||||||
println(err.Error())
|
log.Error(E.Cause(err, "origin error"))
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
panic("panic on early close: " + fmt.Sprint(v))
|
panic("panic on early close: " + fmt.Sprint(v))
|
||||||
}
|
}
|
||||||
@@ -367,9 +223,9 @@ func (s *Box) Start() error {
|
|||||||
defer func() {
|
defer func() {
|
||||||
v := recover()
|
v := recover()
|
||||||
if v != nil {
|
if v != nil {
|
||||||
println(err.Error())
|
log.Error(E.Cause(err, "origin error"))
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
println("panic on early start: " + fmt.Sprint(v))
|
panic("panic on early close: " + fmt.Sprint(v))
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
s.Close()
|
s.Close()
|
||||||
@@ -387,19 +243,35 @@ func (s *Box) preStart() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "start logger")
|
return E.Cause(err, "start logger")
|
||||||
}
|
}
|
||||||
err = adapter.StartNamed(adapter.StartStateInitialize, s.services) // cache-file clash-api v2ray-api
|
for serviceName, service := range s.preServices1 {
|
||||||
|
if preService, isPreService := service.(adapter.PreStarter); isPreService {
|
||||||
|
monitor.Start("pre-start ", serviceName)
|
||||||
|
err := preService.PreStart()
|
||||||
|
monitor.Finish()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "pre-start ", serviceName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for serviceName, service := range s.preServices2 {
|
||||||
|
if preService, isPreService := service.(adapter.PreStarter); isPreService {
|
||||||
|
monitor.Start("pre-start ", serviceName)
|
||||||
|
err := preService.PreStart()
|
||||||
|
monitor.Finish()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "pre-start ", serviceName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
err = s.router.PreStart()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "pre-start router")
|
||||||
|
}
|
||||||
|
err = s.startOutbounds()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = adapter.Start(adapter.StartStateInitialize, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint)
|
return s.router.Start()
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = adapter.Start(adapter.StartStateStart, s.outbound, s.dnsTransport, s.dnsRouter, s.network, s.connection, s.router)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Box) start() error {
|
func (s *Box) start() error {
|
||||||
@@ -407,35 +279,50 @@ func (s *Box) start() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = adapter.StartNamed(adapter.StartStateStart, s.services)
|
for serviceName, service := range s.preServices1 {
|
||||||
if err != nil {
|
err = service.Start()
|
||||||
return err
|
if err != nil {
|
||||||
|
return E.Cause(err, "start ", serviceName)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err = s.inbound.Start(adapter.StartStateStart)
|
for serviceName, service := range s.preServices2 {
|
||||||
if err != nil {
|
err = service.Start()
|
||||||
return err
|
if err != nil {
|
||||||
|
return E.Cause(err, "start ", serviceName)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err = adapter.Start(adapter.StartStateStart, s.endpoint)
|
for i, in := range s.inbounds {
|
||||||
if err != nil {
|
var tag string
|
||||||
return err
|
if in.Tag() == "" {
|
||||||
|
tag = F.ToString(i)
|
||||||
|
} else {
|
||||||
|
tag = in.Tag()
|
||||||
|
}
|
||||||
|
err = in.Start()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "initialize inbound/", in.Type(), "[", tag, "]")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err = adapter.Start(adapter.StartStatePostStart, s.outbound, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.inbound, s.endpoint)
|
return s.postStart()
|
||||||
if err != nil {
|
}
|
||||||
return err
|
|
||||||
|
func (s *Box) postStart() error {
|
||||||
|
for serviceName, service := range s.postServices {
|
||||||
|
err := service.Start()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "start ", serviceName)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err = adapter.StartNamed(adapter.StartStatePostStart, s.services)
|
for _, outbound := range s.outbounds {
|
||||||
if err != nil {
|
if lateOutbound, isLateOutbound := outbound.(adapter.PostStarter); isLateOutbound {
|
||||||
return err
|
err := lateOutbound.PostStart()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "post-start outbound/", outbound.Tag())
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
err = adapter.Start(adapter.StartStateStarted, s.network, s.dnsTransport, s.dnsRouter, s.connection, s.router, s.outbound, s.inbound, s.endpoint)
|
|
||||||
if err != nil {
|
return s.router.PostStart()
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = adapter.StartNamed(adapter.StartStateStarted, s.services)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Box) Close() error {
|
func (s *Box) Close() error {
|
||||||
@@ -445,32 +332,58 @@ func (s *Box) Close() error {
|
|||||||
default:
|
default:
|
||||||
close(s.done)
|
close(s.done)
|
||||||
}
|
}
|
||||||
err := common.Close(
|
monitor := taskmonitor.New(s.logger, C.StopTimeout)
|
||||||
s.inbound, s.outbound, s.router, s.connection, s.dnsRouter, s.dnsTransport, s.network,
|
var errors error
|
||||||
)
|
for serviceName, service := range s.postServices {
|
||||||
for _, lifecycleService := range s.services {
|
monitor.Start("close ", serviceName)
|
||||||
err = E.Append(err, lifecycleService.Close(), func(err error) error {
|
errors = E.Append(errors, service.Close(), func(err error) error {
|
||||||
return E.Cause(err, "close ", lifecycleService.Name())
|
return E.Cause(err, "close ", serviceName)
|
||||||
|
})
|
||||||
|
monitor.Finish()
|
||||||
|
}
|
||||||
|
for i, in := range s.inbounds {
|
||||||
|
monitor.Start("close inbound/", in.Type(), "[", i, "]")
|
||||||
|
errors = E.Append(errors, in.Close(), func(err error) error {
|
||||||
|
return E.Cause(err, "close inbound/", in.Type(), "[", i, "]")
|
||||||
|
})
|
||||||
|
monitor.Finish()
|
||||||
|
}
|
||||||
|
for i, out := range s.outbounds {
|
||||||
|
monitor.Start("close outbound/", out.Type(), "[", i, "]")
|
||||||
|
errors = E.Append(errors, common.Close(out), func(err error) error {
|
||||||
|
return E.Cause(err, "close outbound/", out.Type(), "[", i, "]")
|
||||||
|
})
|
||||||
|
monitor.Finish()
|
||||||
|
}
|
||||||
|
monitor.Start("close router")
|
||||||
|
if err := common.Close(s.router); err != nil {
|
||||||
|
errors = E.Append(errors, err, func(err error) error {
|
||||||
|
return E.Cause(err, "close router")
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
err = E.Append(err, s.logFactory.Close(), func(err error) error {
|
monitor.Finish()
|
||||||
return E.Cause(err, "close logger")
|
for serviceName, service := range s.preServices1 {
|
||||||
})
|
monitor.Start("close ", serviceName)
|
||||||
return err
|
errors = E.Append(errors, service.Close(), func(err error) error {
|
||||||
}
|
return E.Cause(err, "close ", serviceName)
|
||||||
|
})
|
||||||
func (s *Box) Network() adapter.NetworkManager {
|
monitor.Finish()
|
||||||
return s.network
|
}
|
||||||
|
for serviceName, service := range s.preServices2 {
|
||||||
|
monitor.Start("close ", serviceName)
|
||||||
|
errors = E.Append(errors, service.Close(), func(err error) error {
|
||||||
|
return E.Cause(err, "close ", serviceName)
|
||||||
|
})
|
||||||
|
monitor.Finish()
|
||||||
|
}
|
||||||
|
if err := common.Close(s.logFactory); err != nil {
|
||||||
|
errors = E.Append(errors, err, func(err error) error {
|
||||||
|
return E.Cause(err, "close logger")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return errors
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Box) Router() adapter.Router {
|
func (s *Box) Router() adapter.Router {
|
||||||
return s.router
|
return s.router
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Box) Inbound() adapter.InboundManager {
|
|
||||||
return s.inbound
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Box) Outbound() adapter.OutboundManager {
|
|
||||||
return s.outbound
|
|
||||||
}
|
|
||||||
|
|||||||
83
box_outbound.go
Normal file
83
box_outbound.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package box
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/adapter"
|
||||||
|
"github.com/sagernet/sing-box/common/taskmonitor"
|
||||||
|
C "github.com/sagernet/sing-box/constant"
|
||||||
|
"github.com/sagernet/sing/common"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
|
F "github.com/sagernet/sing/common/format"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (s *Box) startOutbounds() error {
|
||||||
|
monitor := taskmonitor.New(s.logger, C.StartTimeout)
|
||||||
|
outboundTags := make(map[adapter.Outbound]string)
|
||||||
|
outbounds := make(map[string]adapter.Outbound)
|
||||||
|
for i, outboundToStart := range s.outbounds {
|
||||||
|
var outboundTag string
|
||||||
|
if outboundToStart.Tag() == "" {
|
||||||
|
outboundTag = F.ToString(i)
|
||||||
|
} else {
|
||||||
|
outboundTag = outboundToStart.Tag()
|
||||||
|
}
|
||||||
|
if _, exists := outbounds[outboundTag]; exists {
|
||||||
|
return E.New("outbound tag ", outboundTag, " duplicated")
|
||||||
|
}
|
||||||
|
outboundTags[outboundToStart] = outboundTag
|
||||||
|
outbounds[outboundTag] = outboundToStart
|
||||||
|
}
|
||||||
|
started := make(map[string]bool)
|
||||||
|
for {
|
||||||
|
canContinue := false
|
||||||
|
startOne:
|
||||||
|
for _, outboundToStart := range s.outbounds {
|
||||||
|
outboundTag := outboundTags[outboundToStart]
|
||||||
|
if started[outboundTag] {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
dependencies := outboundToStart.Dependencies()
|
||||||
|
for _, dependency := range dependencies {
|
||||||
|
if !started[dependency] {
|
||||||
|
continue startOne
|
||||||
|
}
|
||||||
|
}
|
||||||
|
started[outboundTag] = true
|
||||||
|
canContinue = true
|
||||||
|
if starter, isStarter := outboundToStart.(common.Starter); isStarter {
|
||||||
|
monitor.Start("initialize outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
||||||
|
err := starter.Start()
|
||||||
|
monitor.Finish()
|
||||||
|
if err != nil {
|
||||||
|
return E.Cause(err, "initialize outbound/", outboundToStart.Type(), "[", outboundTag, "]")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(started) == len(s.outbounds) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if canContinue {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
currentOutbound := common.Find(s.outbounds, func(it adapter.Outbound) bool {
|
||||||
|
return !started[outboundTags[it]]
|
||||||
|
})
|
||||||
|
var lintOutbound func(oTree []string, oCurrent adapter.Outbound) error
|
||||||
|
lintOutbound = func(oTree []string, oCurrent adapter.Outbound) error {
|
||||||
|
problemOutboundTag := common.Find(oCurrent.Dependencies(), func(it string) bool {
|
||||||
|
return !started[it]
|
||||||
|
})
|
||||||
|
if common.Contains(oTree, problemOutboundTag) {
|
||||||
|
return E.New("circular outbound dependency: ", strings.Join(oTree, " -> "), " -> ", problemOutboundTag)
|
||||||
|
}
|
||||||
|
problemOutbound := outbounds[problemOutboundTag]
|
||||||
|
if problemOutbound == nil {
|
||||||
|
return E.New("dependency[", problemOutboundTag, "] not found for outbound[", outboundTags[oCurrent], "]")
|
||||||
|
}
|
||||||
|
return lintOutbound(append(oTree, problemOutboundTag), problemOutbound)
|
||||||
|
}
|
||||||
|
return lintOutbound([]string{outboundTags[currentOutbound]}, currentOutbound)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Submodule clients/android updated: b17fb6d857...00e3a80875
Submodule clients/apple updated: 64a4614aca...0cbe335cbb
@@ -1,445 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net/http"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/asc-go/asc"
|
|
||||||
"github.com/sagernet/sing-box/cmd/internal/build_shared"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
F "github.com/sagernet/sing/common/format"
|
|
||||||
)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
ctx := context.Background()
|
|
||||||
switch os.Args[1] {
|
|
||||||
case "next_macos_project_version":
|
|
||||||
err := fetchMacOSVersion(ctx)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
case "publish_testflight":
|
|
||||||
err := publishTestflight(ctx)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
case "cancel_app_store":
|
|
||||||
err := cancelAppStore(ctx, os.Args[2])
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
case "prepare_app_store":
|
|
||||||
err := prepareAppStore(ctx)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
case "publish_app_store":
|
|
||||||
err := publishAppStore(ctx)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
log.Fatal("unknown action: ", os.Args[1])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const (
|
|
||||||
appID = "6673731168"
|
|
||||||
groupID = "5c5f3b78-b7a0-40c0-bcad-e6ef87bbefda"
|
|
||||||
)
|
|
||||||
|
|
||||||
func createClient(expireDuration time.Duration) *asc.Client {
|
|
||||||
privateKey, err := os.ReadFile(os.Getenv("ASC_KEY_PATH"))
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
tokenConfig, err := asc.NewTokenConfig(os.Getenv("ASC_KEY_ID"), os.Getenv("ASC_KEY_ISSUER_ID"), expireDuration, privateKey)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
return asc.NewClient(tokenConfig.Client())
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchMacOSVersion(ctx context.Context) error {
|
|
||||||
client := createClient(time.Minute)
|
|
||||||
versions, _, err := client.Apps.ListAppStoreVersionsForApp(ctx, appID, &asc.ListAppStoreVersionsQuery{
|
|
||||||
FilterPlatform: []string{"MAC_OS"},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var versionID string
|
|
||||||
findVersion:
|
|
||||||
for _, version := range versions.Data {
|
|
||||||
switch *version.Attributes.AppStoreState {
|
|
||||||
case asc.AppStoreVersionStateReadyForSale,
|
|
||||||
asc.AppStoreVersionStatePendingDeveloperRelease:
|
|
||||||
versionID = version.ID
|
|
||||||
break findVersion
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if versionID == "" {
|
|
||||||
return E.New("no version found")
|
|
||||||
}
|
|
||||||
latestBuild, _, err := client.Builds.GetBuildForAppStoreVersion(ctx, versionID, &asc.GetBuildForAppStoreVersionQuery{})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
versionInt, err := strconv.Atoi(*latestBuild.Data.Attributes.Version)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "parse version code")
|
|
||||||
}
|
|
||||||
os.Stdout.WriteString(F.ToString(versionInt+1, "\n"))
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func publishTestflight(ctx context.Context) error {
|
|
||||||
tagVersion, err := build_shared.ReadTagVersion()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
tag := tagVersion.VersionString()
|
|
||||||
client := createClient(10 * time.Minute)
|
|
||||||
|
|
||||||
log.Info(tag, " list build IDs")
|
|
||||||
buildIDsResponse, _, err := client.TestFlight.ListBuildIDsForBetaGroup(ctx, groupID, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
buildIDs := common.Map(buildIDsResponse.Data, func(it asc.RelationshipData) string {
|
|
||||||
return it.ID
|
|
||||||
})
|
|
||||||
var platforms []asc.Platform
|
|
||||||
if len(os.Args) == 3 {
|
|
||||||
switch os.Args[2] {
|
|
||||||
case "ios":
|
|
||||||
platforms = []asc.Platform{asc.PlatformIOS}
|
|
||||||
case "macos":
|
|
||||||
platforms = []asc.Platform{asc.PlatformMACOS}
|
|
||||||
case "tvos":
|
|
||||||
platforms = []asc.Platform{asc.PlatformTVOS}
|
|
||||||
default:
|
|
||||||
return E.New("unknown platform: ", os.Args[2])
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
platforms = []asc.Platform{
|
|
||||||
asc.PlatformIOS,
|
|
||||||
asc.PlatformMACOS,
|
|
||||||
asc.PlatformTVOS,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, platform := range platforms {
|
|
||||||
log.Info(string(platform), " list builds")
|
|
||||||
for {
|
|
||||||
builds, _, err := client.Builds.ListBuilds(ctx, &asc.ListBuildsQuery{
|
|
||||||
FilterApp: []string{appID},
|
|
||||||
FilterPreReleaseVersionPlatform: []string{string(platform)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
build := builds.Data[0]
|
|
||||||
if common.Contains(buildIDs, build.ID) || time.Since(build.Attributes.UploadedDate.Time) > 5*time.Minute {
|
|
||||||
log.Info(string(platform), " ", tag, " waiting for process")
|
|
||||||
time.Sleep(15 * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if *build.Attributes.ProcessingState != "VALID" {
|
|
||||||
log.Info(string(platform), " ", tag, " waiting for process: ", *build.Attributes.ProcessingState)
|
|
||||||
time.Sleep(15 * time.Second)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " list localizations")
|
|
||||||
localizations, _, err := client.TestFlight.ListBetaBuildLocalizationsForBuild(ctx, build.ID, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
localization := common.Find(localizations.Data, func(it asc.BetaBuildLocalization) bool {
|
|
||||||
return *it.Attributes.Locale == "en-US"
|
|
||||||
})
|
|
||||||
if localization.ID == "" {
|
|
||||||
log.Fatal(string(platform), " ", tag, " no en-US localization found")
|
|
||||||
}
|
|
||||||
if localization.Attributes == nil || localization.Attributes.WhatsNew == nil || *localization.Attributes.WhatsNew == "" {
|
|
||||||
log.Info(string(platform), " ", tag, " update localization")
|
|
||||||
_, _, err = client.TestFlight.UpdateBetaBuildLocalization(ctx, localization.ID, common.Ptr(
|
|
||||||
F.ToString("sing-box ", tagVersion.String()),
|
|
||||||
))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " publish")
|
|
||||||
response, err := client.TestFlight.AddBuildsToBetaGroup(ctx, groupID, []string{build.ID})
|
|
||||||
if response != nil && response.StatusCode == http.StatusUnprocessableEntity {
|
|
||||||
log.Info("waiting for process")
|
|
||||||
time.Sleep(15 * time.Second)
|
|
||||||
continue
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " list submissions")
|
|
||||||
betaSubmissions, _, err := client.TestFlight.ListBetaAppReviewSubmissions(ctx, &asc.ListBetaAppReviewSubmissionsQuery{
|
|
||||||
FilterBuild: []string{build.ID},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if len(betaSubmissions.Data) == 0 {
|
|
||||||
log.Info(string(platform), " ", tag, " create submission")
|
|
||||||
_, _, err = client.TestFlight.CreateBetaAppReviewSubmission(ctx, build.ID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func cancelAppStore(ctx context.Context, platform string) error {
|
|
||||||
switch platform {
|
|
||||||
case "ios":
|
|
||||||
platform = string(asc.PlatformIOS)
|
|
||||||
case "macos":
|
|
||||||
platform = string(asc.PlatformMACOS)
|
|
||||||
case "tvos":
|
|
||||||
platform = string(asc.PlatformTVOS)
|
|
||||||
}
|
|
||||||
tag, err := build_shared.ReadTag()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
client := createClient(time.Minute)
|
|
||||||
for {
|
|
||||||
log.Info(platform, " list versions")
|
|
||||||
versions, response, err := client.Apps.ListAppStoreVersionsForApp(ctx, appID, &asc.ListAppStoreVersionsQuery{
|
|
||||||
FilterPlatform: []string{string(platform)},
|
|
||||||
})
|
|
||||||
if isRetryable(response) {
|
|
||||||
continue
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
version := common.Find(versions.Data, func(it asc.AppStoreVersion) bool {
|
|
||||||
return *it.Attributes.VersionString == tag
|
|
||||||
})
|
|
||||||
if version.ID == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
log.Info(platform, " ", tag, " get submission")
|
|
||||||
submission, response, err := client.Submission.GetAppStoreVersionSubmissionForAppStoreVersion(ctx, version.ID, nil)
|
|
||||||
if response != nil && response.StatusCode == http.StatusNotFound {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if isRetryable(response) {
|
|
||||||
continue
|
|
||||||
} else if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
log.Info(platform, " ", tag, " delete submission")
|
|
||||||
_, err = client.Submission.DeleteSubmission(ctx, submission.Data.ID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func prepareAppStore(ctx context.Context) error {
|
|
||||||
tag, err := build_shared.ReadTag()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
client := createClient(time.Minute)
|
|
||||||
for _, platform := range []asc.Platform{
|
|
||||||
asc.PlatformIOS,
|
|
||||||
asc.PlatformMACOS,
|
|
||||||
asc.PlatformTVOS,
|
|
||||||
} {
|
|
||||||
log.Info(string(platform), " list versions")
|
|
||||||
versions, _, err := client.Apps.ListAppStoreVersionsForApp(ctx, appID, &asc.ListAppStoreVersionsQuery{
|
|
||||||
FilterPlatform: []string{string(platform)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
version := common.Find(versions.Data, func(it asc.AppStoreVersion) bool {
|
|
||||||
return *it.Attributes.VersionString == tag
|
|
||||||
})
|
|
||||||
log.Info(string(platform), " ", tag, " list builds")
|
|
||||||
builds, _, err := client.Builds.ListBuilds(ctx, &asc.ListBuildsQuery{
|
|
||||||
FilterApp: []string{appID},
|
|
||||||
FilterPreReleaseVersionPlatform: []string{string(platform)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if len(builds.Data) == 0 {
|
|
||||||
log.Fatal(platform, " ", tag, " no build found")
|
|
||||||
}
|
|
||||||
buildID := common.Ptr(builds.Data[0].ID)
|
|
||||||
if version.ID == "" {
|
|
||||||
log.Info(string(platform), " ", tag, " create version")
|
|
||||||
newVersion, _, err := client.Apps.CreateAppStoreVersion(ctx, asc.AppStoreVersionCreateRequestAttributes{
|
|
||||||
Platform: platform,
|
|
||||||
VersionString: tag,
|
|
||||||
}, appID, buildID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
version = newVersion.Data
|
|
||||||
|
|
||||||
} else {
|
|
||||||
log.Info(string(platform), " ", tag, " check build")
|
|
||||||
currentBuild, response, err := client.Apps.GetBuildIDForAppStoreVersion(ctx, version.ID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if response.StatusCode != http.StatusOK || currentBuild.Data.ID != *buildID {
|
|
||||||
switch *version.Attributes.AppStoreState {
|
|
||||||
case asc.AppStoreVersionStatePrepareForSubmission,
|
|
||||||
asc.AppStoreVersionStateRejected,
|
|
||||||
asc.AppStoreVersionStateDeveloperRejected:
|
|
||||||
case asc.AppStoreVersionStateWaitingForReview,
|
|
||||||
asc.AppStoreVersionStateInReview,
|
|
||||||
asc.AppStoreVersionStatePendingDeveloperRelease:
|
|
||||||
submission, _, err := client.Submission.GetAppStoreVersionSubmissionForAppStoreVersion(ctx, version.ID, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if submission != nil {
|
|
||||||
log.Info(string(platform), " ", tag, " delete submission")
|
|
||||||
_, err = client.Submission.DeleteSubmission(ctx, submission.Data.ID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
time.Sleep(5 * time.Second)
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
log.Fatal(string(platform), " ", tag, " unknown state ", string(*version.Attributes.AppStoreState))
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " update build")
|
|
||||||
response, err = client.Apps.UpdateBuildForAppStoreVersion(ctx, version.ID, buildID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if response.StatusCode != http.StatusNoContent {
|
|
||||||
response.Write(os.Stderr)
|
|
||||||
log.Fatal(string(platform), " ", tag, " unexpected response: ", response.Status)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
switch *version.Attributes.AppStoreState {
|
|
||||||
case asc.AppStoreVersionStatePrepareForSubmission,
|
|
||||||
asc.AppStoreVersionStateRejected,
|
|
||||||
asc.AppStoreVersionStateDeveloperRejected:
|
|
||||||
case asc.AppStoreVersionStateWaitingForReview,
|
|
||||||
asc.AppStoreVersionStateInReview,
|
|
||||||
asc.AppStoreVersionStatePendingDeveloperRelease:
|
|
||||||
continue
|
|
||||||
default:
|
|
||||||
log.Fatal(string(platform), " ", tag, " unknown state ", string(*version.Attributes.AppStoreState))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " list localization")
|
|
||||||
localizations, _, err := client.Apps.ListLocalizationsForAppStoreVersion(ctx, version.ID, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
localization := common.Find(localizations.Data, func(it asc.AppStoreVersionLocalization) bool {
|
|
||||||
return *it.Attributes.Locale == "en-US"
|
|
||||||
})
|
|
||||||
if localization.ID == "" {
|
|
||||||
log.Info(string(platform), " ", tag, " no en-US localization found")
|
|
||||||
}
|
|
||||||
if localization.Attributes == nil || localization.Attributes.WhatsNew == nil || *localization.Attributes.WhatsNew == "" {
|
|
||||||
log.Info(string(platform), " ", tag, " update localization")
|
|
||||||
_, _, err = client.Apps.UpdateAppStoreVersionLocalization(ctx, localization.ID, &asc.AppStoreVersionLocalizationUpdateRequestAttributes{
|
|
||||||
PromotionalText: common.Ptr("Yet another distribution for sing-box, the universal proxy platform."),
|
|
||||||
WhatsNew: common.Ptr(F.ToString("sing-box ", tag, ": Fixes and improvements.")),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Info(string(platform), " ", tag, " create submission")
|
|
||||||
fixSubmit:
|
|
||||||
for {
|
|
||||||
_, response, err := client.Submission.CreateSubmission(ctx, version.ID)
|
|
||||||
if err != nil {
|
|
||||||
switch response.StatusCode {
|
|
||||||
case http.StatusInternalServerError:
|
|
||||||
continue
|
|
||||||
default:
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
switch response.StatusCode {
|
|
||||||
case http.StatusCreated:
|
|
||||||
break fixSubmit
|
|
||||||
default:
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func publishAppStore(ctx context.Context) error {
|
|
||||||
tag, err := build_shared.ReadTag()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
client := createClient(time.Minute)
|
|
||||||
for _, platform := range []asc.Platform{
|
|
||||||
asc.PlatformIOS,
|
|
||||||
asc.PlatformMACOS,
|
|
||||||
asc.PlatformTVOS,
|
|
||||||
} {
|
|
||||||
log.Info(string(platform), " list versions")
|
|
||||||
versions, _, err := client.Apps.ListAppStoreVersionsForApp(ctx, appID, &asc.ListAppStoreVersionsQuery{
|
|
||||||
FilterPlatform: []string{string(platform)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
version := common.Find(versions.Data, func(it asc.AppStoreVersion) bool {
|
|
||||||
return *it.Attributes.VersionString == tag
|
|
||||||
})
|
|
||||||
switch *version.Attributes.AppStoreState {
|
|
||||||
case asc.AppStoreVersionStatePrepareForSubmission, asc.AppStoreVersionStateDeveloperRejected:
|
|
||||||
log.Fatal(string(platform), " ", tag, " not submitted")
|
|
||||||
case asc.AppStoreVersionStateWaitingForReview,
|
|
||||||
asc.AppStoreVersionStateInReview:
|
|
||||||
log.Warn(string(platform), " ", tag, " waiting for review")
|
|
||||||
continue
|
|
||||||
case asc.AppStoreVersionStatePendingDeveloperRelease:
|
|
||||||
default:
|
|
||||||
log.Fatal(string(platform), " ", tag, " unknown state ", string(*version.Attributes.AppStoreState))
|
|
||||||
}
|
|
||||||
_, _, err = client.Publishing.CreatePhasedRelease(ctx, common.Ptr(asc.PhasedReleaseStateComplete), version.ID)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func isRetryable(response *asc.Response) bool {
|
|
||||||
if response == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
switch response.StatusCode {
|
|
||||||
case http.StatusInternalServerError, http.StatusUnprocessableEntity:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -10,21 +10,17 @@ import (
|
|||||||
_ "github.com/sagernet/gomobile"
|
_ "github.com/sagernet/gomobile"
|
||||||
"github.com/sagernet/sing-box/cmd/internal/build_shared"
|
"github.com/sagernet/sing-box/cmd/internal/build_shared"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
"github.com/sagernet/sing/common/rw"
|
"github.com/sagernet/sing/common/rw"
|
||||||
"github.com/sagernet/sing/common/shell"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
debugEnabled bool
|
debugEnabled bool
|
||||||
target string
|
target string
|
||||||
platform string
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
flag.BoolVar(&debugEnabled, "debug", false, "enable debug")
|
flag.BoolVar(&debugEnabled, "debug", false, "enable debug")
|
||||||
flag.StringVar(&target, "target", "android", "target platform")
|
flag.StringVar(&target, "target", "android", "target platform")
|
||||||
flag.StringVar(&platform, "platform", "", "specify platform")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
@@ -35,8 +31,8 @@ func main() {
|
|||||||
switch target {
|
switch target {
|
||||||
case "android":
|
case "android":
|
||||||
buildAndroid()
|
buildAndroid()
|
||||||
case "apple":
|
case "ios":
|
||||||
buildApple()
|
buildiOS()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,10 +51,10 @@ func init() {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
currentTag = "unknown"
|
currentTag = "unknown"
|
||||||
}
|
}
|
||||||
sharedFlags = append(sharedFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -s -w -buildid= -checklinkname=0")
|
sharedFlags = append(sharedFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag+" -s -w -buildid=")
|
||||||
debugFlags = append(debugFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag)
|
debugFlags = append(debugFlags, "-ldflags", "-X github.com/sagernet/sing-box/constant.Version="+currentTag)
|
||||||
|
|
||||||
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api", "with_tailscale")
|
sharedTags = append(sharedTags, "with_gvisor", "with_quic", "with_wireguard", "with_ech", "with_utls", "with_clash_api")
|
||||||
iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack")
|
iosTags = append(iosTags, "with_dhcp", "with_low_memory", "with_conntrack")
|
||||||
debugTags = append(debugTags, "debug")
|
debugTags = append(debugTags, "debug")
|
||||||
}
|
}
|
||||||
@@ -66,35 +62,9 @@ func init() {
|
|||||||
func buildAndroid() {
|
func buildAndroid() {
|
||||||
build_shared.FindSDK()
|
build_shared.FindSDK()
|
||||||
|
|
||||||
var javaPath string
|
|
||||||
javaHome := os.Getenv("JAVA_HOME")
|
|
||||||
if javaHome == "" {
|
|
||||||
javaPath = "java"
|
|
||||||
} else {
|
|
||||||
javaPath = filepath.Join(javaHome, "bin", "java")
|
|
||||||
}
|
|
||||||
|
|
||||||
javaVersion, err := shell.Exec(javaPath, "--version").ReadOutput()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(E.Cause(err, "check java version"))
|
|
||||||
}
|
|
||||||
if !strings.Contains(javaVersion, "openjdk 17") {
|
|
||||||
log.Fatal("java version should be openjdk 17")
|
|
||||||
}
|
|
||||||
|
|
||||||
var bindTarget string
|
|
||||||
if platform != "" {
|
|
||||||
bindTarget = platform
|
|
||||||
} else if debugEnabled {
|
|
||||||
bindTarget = "android/arm64"
|
|
||||||
} else {
|
|
||||||
bindTarget = "android"
|
|
||||||
}
|
|
||||||
|
|
||||||
args := []string{
|
args := []string{
|
||||||
"bind",
|
"bind",
|
||||||
"-v",
|
"-v",
|
||||||
"-target", bindTarget,
|
|
||||||
"-androidapi", "21",
|
"-androidapi", "21",
|
||||||
"-javapkg=io.nekohasekai",
|
"-javapkg=io.nekohasekai",
|
||||||
"-libname=box",
|
"-libname=box",
|
||||||
@@ -116,14 +86,14 @@ func buildAndroid() {
|
|||||||
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
|
command := exec.Command(build_shared.GoBinPath+"/gomobile", args...)
|
||||||
command.Stdout = os.Stdout
|
command.Stdout = os.Stdout
|
||||||
command.Stderr = os.Stderr
|
command.Stderr = os.Stderr
|
||||||
err = command.Run()
|
err := command.Run()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
const name = "libbox.aar"
|
const name = "libbox.aar"
|
||||||
copyPath := filepath.Join("..", "sing-box-for-android", "app", "libs")
|
copyPath := filepath.Join("..", "sing-box-for-android", "app", "libs")
|
||||||
if rw.IsDir(copyPath) {
|
if rw.FileExists(copyPath) {
|
||||||
copyPath, _ = filepath.Abs(copyPath)
|
copyPath, _ = filepath.Abs(copyPath)
|
||||||
err = rw.CopyFile(name, filepath.Join(copyPath, name))
|
err = rw.CopyFile(name, filepath.Join(copyPath, name))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -133,20 +103,11 @@ func buildAndroid() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func buildApple() {
|
func buildiOS() {
|
||||||
var bindTarget string
|
|
||||||
if platform != "" {
|
|
||||||
bindTarget = platform
|
|
||||||
} else if debugEnabled {
|
|
||||||
bindTarget = "ios"
|
|
||||||
} else {
|
|
||||||
bindTarget = "ios,tvos,macos"
|
|
||||||
}
|
|
||||||
|
|
||||||
args := []string{
|
args := []string{
|
||||||
"bind",
|
"bind",
|
||||||
"-v",
|
"-v",
|
||||||
"-target", bindTarget,
|
"-target", "ios,iossimulator,tvos,tvossimulator,macos",
|
||||||
"-libname=box",
|
"-libname=box",
|
||||||
}
|
}
|
||||||
if !debugEnabled {
|
if !debugEnabled {
|
||||||
@@ -173,7 +134,7 @@ func buildApple() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
copyPath := filepath.Join("..", "sing-box-for-apple")
|
copyPath := filepath.Join("..", "sing-box-for-apple")
|
||||||
if rw.IsDir(copyPath) {
|
if rw.FileExists(copyPath) {
|
||||||
targetDir := filepath.Join(copyPath, "Libbox.xcframework")
|
targetDir := filepath.Join(copyPath, "Libbox.xcframework")
|
||||||
targetDir, _ = filepath.Abs(targetDir)
|
targetDir, _ = filepath.Abs(targetDir)
|
||||||
os.RemoveAll(targetDir)
|
os.RemoveAll(targetDir)
|
||||||
|
|||||||
@@ -11,7 +11,9 @@ import (
|
|||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
"github.com/sagernet/sing/common/rw"
|
"github.com/sagernet/sing/common/rw"
|
||||||
|
"github.com/sagernet/sing/common/shell"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -28,7 +30,7 @@ func FindSDK() {
|
|||||||
}
|
}
|
||||||
for _, path := range searchPath {
|
for _, path := range searchPath {
|
||||||
path = os.ExpandEnv(path)
|
path = os.ExpandEnv(path)
|
||||||
if rw.IsFile(filepath.Join(path, "licenses", "android-sdk-license")) {
|
if rw.FileExists(filepath.Join(path, "licenses", "android-sdk-license")) {
|
||||||
androidSDKPath = path
|
androidSDKPath = path
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -40,6 +42,14 @@ func FindSDK() {
|
|||||||
log.Fatal("android NDK not found")
|
log.Fatal("android NDK not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
javaVersion, err := shell.Exec("java", "--version").ReadOutput()
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(E.Cause(err, "check java version"))
|
||||||
|
}
|
||||||
|
if !strings.Contains(javaVersion, "openjdk 17") {
|
||||||
|
log.Fatal("java version should be openjdk 17")
|
||||||
|
}
|
||||||
|
|
||||||
os.Setenv("ANDROID_HOME", androidSDKPath)
|
os.Setenv("ANDROID_HOME", androidSDKPath)
|
||||||
os.Setenv("ANDROID_SDK_HOME", androidSDKPath)
|
os.Setenv("ANDROID_SDK_HOME", androidSDKPath)
|
||||||
os.Setenv("ANDROID_NDK_HOME", androidNDKPath)
|
os.Setenv("ANDROID_NDK_HOME", androidNDKPath)
|
||||||
@@ -48,16 +58,12 @@ func FindSDK() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func findNDK() bool {
|
func findNDK() bool {
|
||||||
const fixedVersion = "28.0.12674087"
|
const fixedVersion = "26.2.11394342"
|
||||||
const versionFile = "source.properties"
|
const versionFile = "source.properties"
|
||||||
if fixedPath := filepath.Join(androidSDKPath, "ndk", fixedVersion); rw.IsFile(filepath.Join(fixedPath, versionFile)) {
|
if fixedPath := filepath.Join(androidSDKPath, "ndk", fixedVersion); rw.FileExists(filepath.Join(fixedPath, versionFile)) {
|
||||||
androidNDKPath = fixedPath
|
androidNDKPath = fixedPath
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
if ndkHomeEnv := os.Getenv("ANDROID_NDK_HOME"); rw.IsFile(filepath.Join(ndkHomeEnv, versionFile)) {
|
|
||||||
androidNDKPath = ndkHomeEnv
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
ndkVersions, err := os.ReadDir(filepath.Join(androidSDKPath, "ndk"))
|
ndkVersions, err := os.ReadDir(filepath.Join(androidSDKPath, "ndk"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return false
|
return false
|
||||||
@@ -80,7 +86,7 @@ func findNDK() bool {
|
|||||||
})
|
})
|
||||||
for _, versionName := range versionNames {
|
for _, versionName := range versionNames {
|
||||||
currentNDKPath := filepath.Join(androidSDKPath, "ndk", versionName)
|
currentNDKPath := filepath.Join(androidSDKPath, "ndk", versionName)
|
||||||
if rw.IsFile(filepath.Join(currentNDKPath, versionFile)) {
|
if rw.FileExists(filepath.Join(androidSDKPath, versionFile)) {
|
||||||
androidNDKPath = currentNDKPath
|
androidNDKPath = currentNDKPath
|
||||||
log.Warn("reproducibility warning: using NDK version " + versionName + " instead of " + fixedVersion)
|
log.Warn("reproducibility warning: using NDK version " + versionName + " instead of " + fixedVersion)
|
||||||
return true
|
return true
|
||||||
@@ -94,11 +100,11 @@ var GoBinPath string
|
|||||||
func FindMobile() {
|
func FindMobile() {
|
||||||
goBin := filepath.Join(build.Default.GOPATH, "bin")
|
goBin := filepath.Join(build.Default.GOPATH, "bin")
|
||||||
if runtime.GOOS == "windows" {
|
if runtime.GOOS == "windows" {
|
||||||
if !rw.IsFile(filepath.Join(goBin, "gobind.exe")) {
|
if !rw.FileExists(filepath.Join(goBin, "gobind.exe")) {
|
||||||
log.Fatal("missing gomobile installation")
|
log.Fatal("missing gomobile installation")
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if !rw.IsFile(filepath.Join(goBin, "gobind")) {
|
if !rw.FileExists(filepath.Join(goBin, "gobind")) {
|
||||||
log.Fatal("missing gomobile installation")
|
log.Fatal("missing gomobile installation")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,11 +20,6 @@ func ReadTag() (string, error) {
|
|||||||
return version.String() + "-" + shortCommit, nil
|
return version.String() + "-" + shortCommit, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func ReadTagVersionRev() (badversion.Version, error) {
|
|
||||||
currentTagRev := common.Must1(shell.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput())
|
|
||||||
return badversion.Parse(currentTagRev[1:]), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ReadTagVersion() (badversion.Version, error) {
|
func ReadTagVersion() (badversion.Version, error) {
|
||||||
currentTag := common.Must1(shell.Exec("git", "describe", "--tags").ReadOutput())
|
currentTag := common.Must1(shell.Exec("git", "describe", "--tags").ReadOutput())
|
||||||
currentTagRev := common.Must1(shell.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput())
|
currentTagRev := common.Must1(shell.Exec("git", "describe", "--tags", "--abbrev=0").ReadOutput())
|
||||||
|
|||||||
@@ -1,62 +1,21 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/cmd/internal/build_shared"
|
"github.com/sagernet/sing-box/cmd/internal/build_shared"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
var nightly bool
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
flag.BoolVar(&nightly, "nightly", false, "Print nightly tag")
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
currentTag, err := build_shared.ReadTag()
|
||||||
if nightly {
|
if err != nil {
|
||||||
version, err := build_shared.ReadTagVersionRev()
|
log.Error(err)
|
||||||
if err != nil {
|
_, err = os.Stdout.WriteString("unknown\n")
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
var versionStr string
|
|
||||||
if version.PreReleaseIdentifier != "" {
|
|
||||||
versionStr = version.VersionString() + "-nightly"
|
|
||||||
} else {
|
|
||||||
version.Patch++
|
|
||||||
versionStr = version.VersionString() + "-nightly"
|
|
||||||
}
|
|
||||||
err = setGitHubEnv("version", versionStr)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
tag, err := build_shared.ReadTag()
|
_, err = os.Stdout.WriteString(currentTag + "\n")
|
||||||
if err != nil {
|
}
|
||||||
log.Error(err)
|
if err != nil {
|
||||||
os.Stdout.WriteString("unknown\n")
|
log.Error(err)
|
||||||
} else {
|
|
||||||
os.Stdout.WriteString(tag + "\n")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setGitHubEnv(name string, value string) error {
|
|
||||||
outputFile, err := os.OpenFile(os.Getenv("GITHUB_ENV"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
_, err = outputFile.WriteString(name + "=" + value + "\n")
|
|
||||||
if err != nil {
|
|
||||||
outputFile.Close()
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = outputFile.Close()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
os.Stderr.WriteString(name + "=" + value + "\n")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"runtime"
|
"runtime"
|
||||||
@@ -13,22 +12,9 @@ import (
|
|||||||
"github.com/sagernet/sing/common"
|
"github.com/sagernet/sing/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
var flagRunInCI bool
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
flag.BoolVar(&flagRunInCI, "ci", false, "Run in CI")
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
newVersion := common.Must1(build_shared.ReadTagVersion())
|
||||||
newVersion := common.Must1(build_shared.ReadTag())
|
androidPath, err := filepath.Abs("../sing-box-for-android")
|
||||||
var androidPath string
|
|
||||||
if flagRunInCI {
|
|
||||||
androidPath = "clients/android"
|
|
||||||
} else {
|
|
||||||
androidPath = "../sing-box-for-android"
|
|
||||||
}
|
|
||||||
androidPath, err := filepath.Abs(androidPath)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -45,10 +31,10 @@ func main() {
|
|||||||
for _, propPair := range propsList {
|
for _, propPair := range propsList {
|
||||||
switch propPair[0] {
|
switch propPair[0] {
|
||||||
case "VERSION_NAME":
|
case "VERSION_NAME":
|
||||||
if propPair[1] != newVersion {
|
if propPair[1] != newVersion.String() {
|
||||||
versionUpdated = true
|
versionUpdated = true
|
||||||
propPair[1] = newVersion
|
propPair[1] = newVersion.String()
|
||||||
log.Info("updated version to ", newVersion)
|
log.Info("updated version to ", newVersion.String())
|
||||||
}
|
}
|
||||||
case "GO_VERSION":
|
case "GO_VERSION":
|
||||||
if propPair[1] != runtime.Version() {
|
if propPair[1] != runtime.Version() {
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"flag"
|
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"regexp"
|
"regexp"
|
||||||
@@ -14,22 +13,9 @@ import (
|
|||||||
"howett.net/plist"
|
"howett.net/plist"
|
||||||
)
|
)
|
||||||
|
|
||||||
var flagRunInCI bool
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
flag.BoolVar(&flagRunInCI, "ci", false, "Run in CI")
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
flag.Parse()
|
|
||||||
newVersion := common.Must1(build_shared.ReadTagVersion())
|
newVersion := common.Must1(build_shared.ReadTagVersion())
|
||||||
var applePath string
|
applePath, err := filepath.Abs("../sing-box-for-apple")
|
||||||
if flagRunInCI {
|
|
||||||
applePath = "clients/apple"
|
|
||||||
} else {
|
|
||||||
applePath = "../sing-box-for-apple"
|
|
||||||
}
|
|
||||||
applePath, err := filepath.Abs(applePath)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -40,8 +26,8 @@ func main() {
|
|||||||
common.Must(decoder.Decode(&project))
|
common.Must(decoder.Decode(&project))
|
||||||
objectsMap := project["objects"].(map[string]any)
|
objectsMap := project["objects"].(map[string]any)
|
||||||
projectContent := string(common.Must1(os.ReadFile("sing-box.xcodeproj/project.pbxproj")))
|
projectContent := string(common.Must1(os.ReadFile("sing-box.xcodeproj/project.pbxproj")))
|
||||||
newContent, updated0 := findAndReplace(objectsMap, projectContent, []string{"io.nekohasekai.sfavt"}, newVersion.VersionString())
|
newContent, updated0 := findAndReplace(objectsMap, projectContent, []string{"io.nekohasekai.sfa"}, newVersion.VersionString())
|
||||||
newContent, updated1 := findAndReplace(objectsMap, newContent, []string{"io.nekohasekai.sfavt.standalone", "io.nekohasekai.sfavt.system"}, newVersion.String())
|
newContent, updated1 := findAndReplace(objectsMap, newContent, []string{"io.nekohasekai.sfa.independent", "io.nekohasekai.sfa.system"}, newVersion.String())
|
||||||
if updated0 || updated1 {
|
if updated0 || updated1 {
|
||||||
log.Info("updated version to ", newVersion.VersionString(), " (", newVersion.String(), ")")
|
log.Info("updated version to ", newVersion.VersionString(), " (", newVersion.String(), ")")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"os"
|
|
||||||
"os/user"
|
|
||||||
"strconv"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box"
|
|
||||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
|
||||||
"github.com/sagernet/sing-box/include"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/service"
|
|
||||||
"github.com/sagernet/sing/service/filemanager"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
globalCtx context.Context
|
|
||||||
configPaths []string
|
|
||||||
configDirectories []string
|
|
||||||
workingDir string
|
|
||||||
disableColor bool
|
|
||||||
)
|
|
||||||
|
|
||||||
var mainCommand = &cobra.Command{
|
|
||||||
Use: "sing-box",
|
|
||||||
PersistentPreRun: preRun,
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
mainCommand.PersistentFlags().StringArrayVarP(&configPaths, "config", "c", nil, "set configuration file path")
|
|
||||||
mainCommand.PersistentFlags().StringArrayVarP(&configDirectories, "config-directory", "C", nil, "set configuration directory path")
|
|
||||||
mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory")
|
|
||||||
mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output")
|
|
||||||
}
|
|
||||||
|
|
||||||
func preRun(cmd *cobra.Command, args []string) {
|
|
||||||
globalCtx = context.Background()
|
|
||||||
sudoUser := os.Getenv("SUDO_USER")
|
|
||||||
sudoUID, _ := strconv.Atoi(os.Getenv("SUDO_UID"))
|
|
||||||
sudoGID, _ := strconv.Atoi(os.Getenv("SUDO_GID"))
|
|
||||||
if sudoUID == 0 && sudoGID == 0 && sudoUser != "" {
|
|
||||||
sudoUserObject, _ := user.Lookup(sudoUser)
|
|
||||||
if sudoUserObject != nil {
|
|
||||||
sudoUID, _ = strconv.Atoi(sudoUserObject.Uid)
|
|
||||||
sudoGID, _ = strconv.Atoi(sudoUserObject.Gid)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if sudoUID > 0 && sudoGID > 0 {
|
|
||||||
globalCtx = filemanager.WithDefault(globalCtx, "", "", sudoUID, sudoGID)
|
|
||||||
}
|
|
||||||
if disableColor {
|
|
||||||
log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger())
|
|
||||||
}
|
|
||||||
if workingDir != "" {
|
|
||||||
_, err := os.Stat(workingDir)
|
|
||||||
if err != nil {
|
|
||||||
filemanager.MkdirAll(globalCtx, workingDir, 0o777)
|
|
||||||
}
|
|
||||||
err = os.Chdir(workingDir)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(configPaths) == 0 && len(configDirectories) == 0 {
|
|
||||||
configPaths = append(configPaths, "config.json")
|
|
||||||
}
|
|
||||||
globalCtx = service.ContextWith(globalCtx, deprecated.NewStderrManager(log.StdLogger()))
|
|
||||||
globalCtx = box.Context(globalCtx, include.InboundRegistry(), include.OutboundRegistry(), include.EndpointRegistry(), include.DNSTransportRegistry())
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,7 @@ func check() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
ctx, cancel := context.WithCancel(globalCtx)
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
instance, err := box.New(box.Options{
|
instance, err := box.New(box.Options{
|
||||||
Context: ctx,
|
Context: ctx,
|
||||||
Options: options,
|
Options: options,
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ func format() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
for _, optionsEntry := range optionsList {
|
for _, optionsEntry := range optionsList {
|
||||||
optionsEntry.options, err = badjson.Omitempty(globalCtx, optionsEntry.options)
|
optionsEntry.options, err = badjson.Omitempty(optionsEntry.options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,7 +87,7 @@ func geoipExport(countryCode string) error {
|
|||||||
headlessRule.IPCIDR = append(headlessRule.IPCIDR, cidr.String())
|
headlessRule.IPCIDR = append(headlessRule.IPCIDR, cidr.String())
|
||||||
}
|
}
|
||||||
var plainRuleSet option.PlainRuleSetCompat
|
var plainRuleSet option.PlainRuleSetCompat
|
||||||
plainRuleSet.Version = C.RuleSetVersion2
|
plainRuleSet.Version = C.RuleSetVersion1
|
||||||
plainRuleSet.Options.Rules = []option.HeadlessRule{
|
plainRuleSet.Options.Rules = []option.HeadlessRule{
|
||||||
{
|
{
|
||||||
Type: C.RuleTypeDefault,
|
Type: C.RuleTypeDefault,
|
||||||
|
|||||||
@@ -70,7 +70,7 @@ func geositeExport(category string) error {
|
|||||||
headlessRule.DomainKeyword = defaultRule.DomainKeyword
|
headlessRule.DomainKeyword = defaultRule.DomainKeyword
|
||||||
headlessRule.DomainRegex = defaultRule.DomainRegex
|
headlessRule.DomainRegex = defaultRule.DomainRegex
|
||||||
var plainRuleSet option.PlainRuleSetCompat
|
var plainRuleSet option.PlainRuleSetCompat
|
||||||
plainRuleSet.Version = C.RuleSetVersion2
|
plainRuleSet.Version = C.RuleSetVersion1
|
||||||
plainRuleSet.Options.Rules = []option.HeadlessRule{
|
plainRuleSet.Options.Rules = []option.HeadlessRule{
|
||||||
{
|
{
|
||||||
Type: C.RuleTypeDefault,
|
Type: C.RuleTypeDefault,
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
var commandMerge = &cobra.Command{
|
var commandMerge = &cobra.Command{
|
||||||
Use: "merge <output-path>",
|
Use: "merge <output>",
|
||||||
Short: "Merge configurations",
|
Short: "Merge configurations",
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
err := merge(args[0])
|
err := merge(args[0])
|
||||||
@@ -54,11 +54,7 @@ func merge(outputPath string) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
err = rw.MkdirParent(outputPath)
|
err = rw.WriteFile(outputPath, buffer.Bytes())
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = os.WriteFile(outputPath, buffer.Bytes(), 0o644)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -68,19 +64,29 @@ func merge(outputPath string) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func mergePathResources(options *option.Options) error {
|
func mergePathResources(options *option.Options) error {
|
||||||
for _, inbound := range options.Inbounds {
|
for index, inbound := range options.Inbounds {
|
||||||
if tlsOptions, containsTLSOptions := inbound.Options.(option.InboundTLSOptionsWrapper); containsTLSOptions {
|
rawOptions, err := inbound.RawOptions()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if tlsOptions, containsTLSOptions := rawOptions.(option.InboundTLSOptionsWrapper); containsTLSOptions {
|
||||||
tlsOptions.ReplaceInboundTLSOptions(mergeTLSInboundOptions(tlsOptions.TakeInboundTLSOptions()))
|
tlsOptions.ReplaceInboundTLSOptions(mergeTLSInboundOptions(tlsOptions.TakeInboundTLSOptions()))
|
||||||
}
|
}
|
||||||
|
options.Inbounds[index] = inbound
|
||||||
}
|
}
|
||||||
for _, outbound := range options.Outbounds {
|
for index, outbound := range options.Outbounds {
|
||||||
|
rawOptions, err := outbound.RawOptions()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
switch outbound.Type {
|
switch outbound.Type {
|
||||||
case C.TypeSSH:
|
case C.TypeSSH:
|
||||||
mergeSSHOutboundOptions(outbound.Options.(*option.SSHOutboundOptions))
|
outbound.SSHOptions = mergeSSHOutboundOptions(outbound.SSHOptions)
|
||||||
}
|
}
|
||||||
if tlsOptions, containsTLSOptions := outbound.Options.(option.OutboundTLSOptionsWrapper); containsTLSOptions {
|
if tlsOptions, containsTLSOptions := rawOptions.(option.OutboundTLSOptionsWrapper); containsTLSOptions {
|
||||||
tlsOptions.ReplaceOutboundTLSOptions(mergeTLSOutboundOptions(tlsOptions.TakeOutboundTLSOptions()))
|
tlsOptions.ReplaceOutboundTLSOptions(mergeTLSOutboundOptions(tlsOptions.TakeOutboundTLSOptions()))
|
||||||
}
|
}
|
||||||
|
options.Outbounds[index] = outbound
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -128,12 +134,13 @@ func mergeTLSOutboundOptions(options *option.OutboundTLSOptions) *option.Outboun
|
|||||||
return options
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
func mergeSSHOutboundOptions(options *option.SSHOutboundOptions) {
|
func mergeSSHOutboundOptions(options option.SSHOutboundOptions) option.SSHOutboundOptions {
|
||||||
if options.PrivateKeyPath != "" {
|
if options.PrivateKeyPath != "" {
|
||||||
if content, err := os.ReadFile(os.ExpandEnv(options.PrivateKeyPath)); err == nil {
|
if content, err := os.ReadFile(os.ExpandEnv(options.PrivateKeyPath)); err == nil {
|
||||||
options.PrivateKey = trimStringArray(strings.Split(string(content), "\n"))
|
options.PrivateKey = trimStringArray(strings.Split(string(content), "\n"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return options
|
||||||
}
|
}
|
||||||
|
|
||||||
func trimStringArray(array []string) []string {
|
func trimStringArray(array []string) []string {
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ import (
|
|||||||
|
|
||||||
var commandRuleSet = &cobra.Command{
|
var commandRuleSet = &cobra.Command{
|
||||||
Use: "rule-set",
|
Use: "rule-set",
|
||||||
Short: "Manage rule-sets",
|
Short: "Manage rule sets",
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ func compileRuleSet(sourcePath string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ruleSet := plainRuleSet.Upgrade()
|
||||||
var outputPath string
|
var outputPath string
|
||||||
if flagRuleSetCompileOutput == flagRuleSetCompileDefaultOutput {
|
if flagRuleSetCompileOutput == flagRuleSetCompileDefaultOutput {
|
||||||
if strings.HasSuffix(sourcePath, ".json") {
|
if strings.HasSuffix(sourcePath, ".json") {
|
||||||
@@ -69,7 +73,7 @@ func compileRuleSet(sourcePath string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = srs.Write(outputFile, plainRuleSet.Options, plainRuleSet.Version)
|
err = srs.Write(outputFile, ruleSet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
outputFile.Close()
|
outputFile.Close()
|
||||||
os.Remove(outputPath)
|
os.Remove(outputPath)
|
||||||
|
|||||||
@@ -1,89 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/cmd/sing-box/internal/convertor/adguard"
|
|
||||||
"github.com/sagernet/sing-box/common/srs"
|
|
||||||
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"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
flagRuleSetConvertType string
|
|
||||||
flagRuleSetConvertOutput string
|
|
||||||
)
|
|
||||||
|
|
||||||
var commandRuleSetConvert = &cobra.Command{
|
|
||||||
Use: "convert [source-path]",
|
|
||||||
Short: "Convert adguard DNS filter to rule-set",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
err := convertRuleSet(args[0])
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
commandRuleSet.AddCommand(commandRuleSetConvert)
|
|
||||||
commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertType, "type", "t", "", "Source type, available: adguard")
|
|
||||||
commandRuleSetConvert.Flags().StringVarP(&flagRuleSetConvertOutput, "output", "o", flagRuleSetCompileDefaultOutput, "Output file")
|
|
||||||
}
|
|
||||||
|
|
||||||
func convertRuleSet(sourcePath string) error {
|
|
||||||
var (
|
|
||||||
reader io.Reader
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if sourcePath == "stdin" {
|
|
||||||
reader = os.Stdin
|
|
||||||
} else {
|
|
||||||
reader, err = os.Open(sourcePath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var rules []option.HeadlessRule
|
|
||||||
switch flagRuleSetConvertType {
|
|
||||||
case "adguard":
|
|
||||||
rules, err = adguard.Convert(reader)
|
|
||||||
case "":
|
|
||||||
return E.New("source type is required")
|
|
||||||
default:
|
|
||||||
return E.New("unsupported source type: ", flagRuleSetConvertType)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var outputPath string
|
|
||||||
if flagRuleSetConvertOutput == flagRuleSetCompileDefaultOutput {
|
|
||||||
if strings.HasSuffix(sourcePath, ".txt") {
|
|
||||||
outputPath = sourcePath[:len(sourcePath)-4] + ".srs"
|
|
||||||
} else {
|
|
||||||
outputPath = sourcePath + ".srs"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
outputPath = flagRuleSetConvertOutput
|
|
||||||
}
|
|
||||||
outputFile, err := os.Create(outputPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer outputFile.Close()
|
|
||||||
err = srs.Write(outputFile, option.PlainRuleSet{Rules: rules}, C.RuleSetVersion2)
|
|
||||||
if err != nil {
|
|
||||||
outputFile.Close()
|
|
||||||
os.Remove(outputPath)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
outputFile.Close()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,77 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/srs"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing/common/json"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
var flagRuleSetDecompileOutput string
|
|
||||||
|
|
||||||
const flagRuleSetDecompileDefaultOutput = "<file_name>.json"
|
|
||||||
|
|
||||||
var commandRuleSetDecompile = &cobra.Command{
|
|
||||||
Use: "decompile [binary-path]",
|
|
||||||
Short: "Decompile rule-set binary to json",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
err := decompileRuleSet(args[0])
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
commandRuleSet.AddCommand(commandRuleSetDecompile)
|
|
||||||
commandRuleSetDecompile.Flags().StringVarP(&flagRuleSetDecompileOutput, "output", "o", flagRuleSetDecompileDefaultOutput, "Output file")
|
|
||||||
}
|
|
||||||
|
|
||||||
func decompileRuleSet(sourcePath string) error {
|
|
||||||
var (
|
|
||||||
reader io.Reader
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if sourcePath == "stdin" {
|
|
||||||
reader = os.Stdin
|
|
||||||
} else {
|
|
||||||
reader, err = os.Open(sourcePath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ruleSet, err := srs.Read(reader, true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
var outputPath string
|
|
||||||
if flagRuleSetDecompileOutput == flagRuleSetDecompileDefaultOutput {
|
|
||||||
if strings.HasSuffix(sourcePath, ".srs") {
|
|
||||||
outputPath = sourcePath[:len(sourcePath)-4] + ".json"
|
|
||||||
} else {
|
|
||||||
outputPath = sourcePath + ".json"
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
outputPath = flagRuleSetDecompileOutput
|
|
||||||
}
|
|
||||||
outputFile, err := os.Create(outputPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
encoder := json.NewEncoder(outputFile)
|
|
||||||
encoder.SetIndent("", " ")
|
|
||||||
err = encoder.Encode(ruleSet)
|
|
||||||
if err != nil {
|
|
||||||
outputFile.Close()
|
|
||||||
os.Remove(outputPath)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
outputFile.Close()
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
@@ -11,11 +10,9 @@ import (
|
|||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
"github.com/sagernet/sing-box/route/rule"
|
"github.com/sagernet/sing-box/route"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
F "github.com/sagernet/sing/common/format"
|
|
||||||
"github.com/sagernet/sing/common/json"
|
"github.com/sagernet/sing/common/json"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
)
|
)
|
||||||
@@ -23,8 +20,8 @@ import (
|
|||||||
var flagRuleSetMatchFormat string
|
var flagRuleSetMatchFormat string
|
||||||
|
|
||||||
var commandRuleSetMatch = &cobra.Command{
|
var commandRuleSetMatch = &cobra.Command{
|
||||||
Use: "match <rule-set path> <IP address/domain>",
|
Use: "match <rule-set path> <domain>",
|
||||||
Short: "Check if an IP address or a domain matches the rule-set",
|
Short: "Check if a domain matches the rule set",
|
||||||
Args: cobra.ExactArgs(2),
|
Args: cobra.ExactArgs(2),
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
Run: func(cmd *cobra.Command, args []string) {
|
||||||
err := ruleSetMatch(args[0], args[1])
|
err := ruleSetMatch(args[0], args[1])
|
||||||
@@ -56,40 +53,33 @@ func ruleSetMatch(sourcePath string, domain string) error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "read rule-set")
|
return E.Cause(err, "read rule-set")
|
||||||
}
|
}
|
||||||
var ruleSet option.PlainRuleSetCompat
|
var plainRuleSet option.PlainRuleSet
|
||||||
switch flagRuleSetMatchFormat {
|
switch flagRuleSetMatchFormat {
|
||||||
case C.RuleSetFormatSource:
|
case C.RuleSetFormatSource:
|
||||||
ruleSet, err = json.UnmarshalExtended[option.PlainRuleSetCompat](content)
|
var compat option.PlainRuleSetCompat
|
||||||
|
compat, err = json.UnmarshalExtended[option.PlainRuleSetCompat](content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
plainRuleSet = compat.Upgrade()
|
||||||
case C.RuleSetFormatBinary:
|
case C.RuleSetFormatBinary:
|
||||||
ruleSet, err = srs.Read(bytes.NewReader(content), false)
|
plainRuleSet, err = srs.Read(bytes.NewReader(content), false)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
return E.New("unknown rule-set format: ", flagRuleSetMatchFormat)
|
return E.New("unknown rule set format: ", flagRuleSetMatchFormat)
|
||||||
}
|
|
||||||
plainRuleSet, err := ruleSet.Upgrade()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ipAddress := M.ParseAddr(domain)
|
|
||||||
var metadata adapter.InboundContext
|
|
||||||
if ipAddress.IsValid() {
|
|
||||||
metadata.Destination = M.SocksaddrFrom(ipAddress, 0)
|
|
||||||
} else {
|
|
||||||
metadata.Domain = domain
|
|
||||||
}
|
}
|
||||||
for i, ruleOptions := range plainRuleSet.Rules {
|
for i, ruleOptions := range plainRuleSet.Rules {
|
||||||
var currentRule adapter.HeadlessRule
|
var currentRule adapter.HeadlessRule
|
||||||
currentRule, err = rule.NewHeadlessRule(context.Background(), ruleOptions)
|
currentRule, err = route.NewHeadlessRule(nil, ruleOptions)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "parse rule_set.rules.[", i, "]")
|
return E.Cause(err, "parse rule_set.rules.[", i, "]")
|
||||||
}
|
}
|
||||||
if currentRule.Match(&metadata) {
|
if currentRule.Match(&adapter.InboundContext{
|
||||||
println(F.ToString("match rules.[", i, "]: ", currentRule))
|
Domain: domain,
|
||||||
|
}) {
|
||||||
|
println("match rules.[", i, "]: "+currentRule.String())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
|
|||||||
@@ -1,162 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"sort"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
"github.com/sagernet/sing/common/json"
|
|
||||||
"github.com/sagernet/sing/common/json/badjson"
|
|
||||||
"github.com/sagernet/sing/common/rw"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
ruleSetPaths []string
|
|
||||||
ruleSetDirectories []string
|
|
||||||
)
|
|
||||||
|
|
||||||
var commandRuleSetMerge = &cobra.Command{
|
|
||||||
Use: "merge <output-path>",
|
|
||||||
Short: "Merge rule-set source files",
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
err := mergeRuleSet(args[0])
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
commandRuleSetMerge.Flags().StringArrayVarP(&ruleSetPaths, "config", "c", nil, "set input rule-set file path")
|
|
||||||
commandRuleSetMerge.Flags().StringArrayVarP(&ruleSetDirectories, "config-directory", "C", nil, "set input rule-set directory path")
|
|
||||||
commandRuleSet.AddCommand(commandRuleSetMerge)
|
|
||||||
}
|
|
||||||
|
|
||||||
type RuleSetEntry struct {
|
|
||||||
content []byte
|
|
||||||
path string
|
|
||||||
options option.PlainRuleSetCompat
|
|
||||||
}
|
|
||||||
|
|
||||||
func readRuleSetAt(path string) (*RuleSetEntry, error) {
|
|
||||||
var (
|
|
||||||
configContent []byte
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if path == "stdin" {
|
|
||||||
configContent, err = io.ReadAll(os.Stdin)
|
|
||||||
} else {
|
|
||||||
configContent, err = os.ReadFile(path)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "read config at ", path)
|
|
||||||
}
|
|
||||||
options, err := json.UnmarshalExtendedContext[option.PlainRuleSetCompat](globalCtx, configContent)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "decode config at ", path)
|
|
||||||
}
|
|
||||||
return &RuleSetEntry{
|
|
||||||
content: configContent,
|
|
||||||
path: path,
|
|
||||||
options: options,
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readRuleSet() ([]*RuleSetEntry, error) {
|
|
||||||
var optionsList []*RuleSetEntry
|
|
||||||
for _, path := range ruleSetPaths {
|
|
||||||
optionsEntry, err := readRuleSetAt(path)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
optionsList = append(optionsList, optionsEntry)
|
|
||||||
}
|
|
||||||
for _, directory := range ruleSetDirectories {
|
|
||||||
entries, err := os.ReadDir(directory)
|
|
||||||
if err != nil {
|
|
||||||
return nil, E.Cause(err, "read rule-set directory at ", directory)
|
|
||||||
}
|
|
||||||
for _, entry := range entries {
|
|
||||||
if !strings.HasSuffix(entry.Name(), ".json") || entry.IsDir() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
optionsEntry, err := readRuleSetAt(filepath.Join(directory, entry.Name()))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
optionsList = append(optionsList, optionsEntry)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Slice(optionsList, func(i, j int) bool {
|
|
||||||
return optionsList[i].path < optionsList[j].path
|
|
||||||
})
|
|
||||||
return optionsList, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func readRuleSetAndMerge() (option.PlainRuleSetCompat, error) {
|
|
||||||
optionsList, err := readRuleSet()
|
|
||||||
if err != nil {
|
|
||||||
return option.PlainRuleSetCompat{}, err
|
|
||||||
}
|
|
||||||
if len(optionsList) == 1 {
|
|
||||||
return optionsList[0].options, nil
|
|
||||||
}
|
|
||||||
var optionVersion uint8
|
|
||||||
for _, options := range optionsList {
|
|
||||||
if optionVersion < options.options.Version {
|
|
||||||
optionVersion = options.options.Version
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var mergedMessage json.RawMessage
|
|
||||||
for _, options := range optionsList {
|
|
||||||
mergedMessage, err = badjson.MergeJSON(globalCtx, options.options.RawMessage, mergedMessage, false)
|
|
||||||
if err != nil {
|
|
||||||
return option.PlainRuleSetCompat{}, E.Cause(err, "merge config at ", options.path)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
mergedOptions, err := json.UnmarshalExtendedContext[option.PlainRuleSetCompat](globalCtx, mergedMessage)
|
|
||||||
if err != nil {
|
|
||||||
return option.PlainRuleSetCompat{}, E.Cause(err, "unmarshal merged config")
|
|
||||||
}
|
|
||||||
mergedOptions.Version = optionVersion
|
|
||||||
return mergedOptions, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func mergeRuleSet(outputPath string) error {
|
|
||||||
mergedOptions, err := readRuleSetAndMerge()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
buffer := new(bytes.Buffer)
|
|
||||||
encoder := json.NewEncoder(buffer)
|
|
||||||
encoder.SetIndent("", " ")
|
|
||||||
err = encoder.Encode(mergedOptions)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "encode config")
|
|
||||||
}
|
|
||||||
if existsContent, err := os.ReadFile(outputPath); err != nil {
|
|
||||||
if string(existsContent) == buffer.String() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
err = rw.MkdirParent(outputPath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = os.WriteFile(outputPath, buffer.Bytes(), 0o644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
outputPath, _ = filepath.Abs(outputPath)
|
|
||||||
os.Stderr.WriteString(outputPath + "\n")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,94 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
|
|
||||||
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"
|
|
||||||
"github.com/sagernet/sing/common/json"
|
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
|
||||||
)
|
|
||||||
|
|
||||||
var commandRuleSetUpgradeFlagWrite bool
|
|
||||||
|
|
||||||
var commandRuleSetUpgrade = &cobra.Command{
|
|
||||||
Use: "upgrade <source-path>",
|
|
||||||
Short: "Upgrade rule-set json",
|
|
||||||
Args: cobra.ExactArgs(1),
|
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
|
||||||
err := upgradeRuleSet(args[0])
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
func init() {
|
|
||||||
commandRuleSetUpgrade.Flags().BoolVarP(&commandRuleSetUpgradeFlagWrite, "write", "w", false, "write result to (source) file instead of stdout")
|
|
||||||
commandRuleSet.AddCommand(commandRuleSetUpgrade)
|
|
||||||
}
|
|
||||||
|
|
||||||
func upgradeRuleSet(sourcePath string) error {
|
|
||||||
var (
|
|
||||||
reader io.Reader
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if sourcePath == "stdin" {
|
|
||||||
reader = os.Stdin
|
|
||||||
} else {
|
|
||||||
reader, err = os.Open(sourcePath)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
content, err := io.ReadAll(reader)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
plainRuleSetCompat, err := json.UnmarshalExtended[option.PlainRuleSetCompat](content)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
switch plainRuleSetCompat.Version {
|
|
||||||
case C.RuleSetVersion1:
|
|
||||||
default:
|
|
||||||
log.Info("already up-to-date")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
plainRuleSet, err := plainRuleSetCompat.Upgrade()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
buffer := new(bytes.Buffer)
|
|
||||||
encoder := json.NewEncoder(buffer)
|
|
||||||
encoder.SetIndent("", " ")
|
|
||||||
err = encoder.Encode(plainRuleSet)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "encode config")
|
|
||||||
}
|
|
||||||
outputPath, _ := filepath.Abs(sourcePath)
|
|
||||||
if !commandRuleSetUpgradeFlagWrite || sourcePath == "stdin" {
|
|
||||||
os.Stdout.WriteString(buffer.String() + "\n")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
if bytes.Equal(content, buffer.Bytes()) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
output, err := os.Create(sourcePath)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "open output")
|
|
||||||
}
|
|
||||||
_, err = output.Write(buffer.Bytes())
|
|
||||||
output.Close()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "write output")
|
|
||||||
}
|
|
||||||
os.Stderr.WriteString(outputPath + "\n")
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -57,7 +57,7 @@ func readConfigAt(path string) (*OptionsEntry, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "read config at ", path)
|
return nil, E.Cause(err, "read config at ", path)
|
||||||
}
|
}
|
||||||
options, err := json.UnmarshalExtendedContext[option.Options](globalCtx, configContent)
|
options, err := json.UnmarshalExtended[option.Options](configContent)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "decode config at ", path)
|
return nil, E.Cause(err, "decode config at ", path)
|
||||||
}
|
}
|
||||||
@@ -109,13 +109,13 @@ func readConfigAndMerge() (option.Options, error) {
|
|||||||
}
|
}
|
||||||
var mergedMessage json.RawMessage
|
var mergedMessage json.RawMessage
|
||||||
for _, options := range optionsList {
|
for _, options := range optionsList {
|
||||||
mergedMessage, err = badjson.MergeJSON(globalCtx, options.options.RawMessage, mergedMessage, false)
|
mergedMessage, err = badjson.MergeJSON(options.options.RawMessage, mergedMessage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return option.Options{}, E.Cause(err, "merge config at ", options.path)
|
return option.Options{}, E.Cause(err, "merge config at ", options.path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var mergedOptions option.Options
|
var mergedOptions option.Options
|
||||||
err = mergedOptions.UnmarshalJSONContext(globalCtx, mergedMessage)
|
err = mergedOptions.UnmarshalJSON(mergedMessage)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return option.Options{}, E.Cause(err, "unmarshal merged config")
|
return option.Options{}, E.Cause(err, "unmarshal merged config")
|
||||||
}
|
}
|
||||||
@@ -188,12 +188,9 @@ func run() error {
|
|||||||
cancel()
|
cancel()
|
||||||
closeCtx, closed := context.WithCancel(context.Background())
|
closeCtx, closed := context.WithCancel(context.Background())
|
||||||
go closeMonitor(closeCtx)
|
go closeMonitor(closeCtx)
|
||||||
err = instance.Close()
|
instance.Close()
|
||||||
closed()
|
closed()
|
||||||
if osSignal != syscall.SIGHUP {
|
if osSignal != syscall.SIGHUP {
|
||||||
if err != nil {
|
|
||||||
log.Error(E.Cause(err, "sing-box did not closed properly"))
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
|||||||
@@ -1,9 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box"
|
"github.com/sagernet/sing-box"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
@@ -26,11 +23,9 @@ func init() {
|
|||||||
func createPreStartedClient() (*box.Box, error) {
|
func createPreStartedClient() (*box.Box, error) {
|
||||||
options, err := readConfigAndMerge()
|
options, err := readConfigAndMerge()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if !(errors.Is(err, os.ErrNotExist) && len(configDirectories) == 0 && len(configPaths) == 1) || configPaths[0] != "config.json" {
|
return nil, err
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
instance, err := box.New(box.Options{Context: globalCtx, Options: options})
|
instance, err := box.New(box.Options{Options: options})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, E.Cause(err, "create service")
|
return nil, E.Cause(err, "create service")
|
||||||
}
|
}
|
||||||
@@ -41,11 +36,11 @@ func createPreStartedClient() (*box.Box, error) {
|
|||||||
return instance, nil
|
return instance, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func createDialer(instance *box.Box, outboundTag string) (N.Dialer, error) {
|
func createDialer(instance *box.Box, network string, outboundTag string) (N.Dialer, error) {
|
||||||
if outboundTag == "" {
|
if outboundTag == "" {
|
||||||
return instance.Outbound().Default(), nil
|
return instance.Router().DefaultOutbound(N.NetworkName(network))
|
||||||
} else {
|
} else {
|
||||||
outbound, loaded := instance.Outbound().Outbound(outboundTag)
|
outbound, loaded := instance.Router().Outbound(outboundTag)
|
||||||
if !loaded {
|
if !loaded {
|
||||||
return nil, E.New("outbound not found: ", outboundTag)
|
return nil, E.New("outbound not found: ", outboundTag)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ func connect(address string) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
defer instance.Close()
|
defer instance.Close()
|
||||||
dialer, err := createDialer(instance, commandToolsFlagOutbound)
|
dialer, err := createDialer(instance, commandConnectFlagNetwork, commandToolsFlagOutbound)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,10 +9,8 @@ import (
|
|||||||
"net/url"
|
"net/url"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -34,10 +32,7 @@ func init() {
|
|||||||
commandTools.AddCommand(commandFetch)
|
commandTools.AddCommand(commandFetch)
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var httpClient *http.Client
|
||||||
httpClient *http.Client
|
|
||||||
http3Client *http.Client
|
|
||||||
)
|
|
||||||
|
|
||||||
func fetch(args []string) error {
|
func fetch(args []string) error {
|
||||||
instance, err := createPreStartedClient()
|
instance, err := createPreStartedClient()
|
||||||
@@ -48,7 +43,7 @@ func fetch(args []string) error {
|
|||||||
httpClient = &http.Client{
|
httpClient = &http.Client{
|
||||||
Transport: &http.Transport{
|
Transport: &http.Transport{
|
||||||
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||||
dialer, err := createDialer(instance, commandToolsFlagOutbound)
|
dialer, err := createDialer(instance, network, commandToolsFlagOutbound)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -58,16 +53,8 @@ func fetch(args []string) error {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
defer httpClient.CloseIdleConnections()
|
defer httpClient.CloseIdleConnections()
|
||||||
if C.WithQUIC {
|
|
||||||
err = initializeHTTP3Client(instance)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer http3Client.CloseIdleConnections()
|
|
||||||
}
|
|
||||||
for _, urlString := range args {
|
for _, urlString := range args {
|
||||||
var parsedURL *url.URL
|
parsedURL, err := url.Parse(urlString)
|
||||||
parsedURL, err = url.Parse(urlString)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -76,27 +63,16 @@ func fetch(args []string) error {
|
|||||||
parsedURL.Scheme = "http"
|
parsedURL.Scheme = "http"
|
||||||
fallthrough
|
fallthrough
|
||||||
case "http", "https":
|
case "http", "https":
|
||||||
err = fetchHTTP(httpClient, parsedURL)
|
err = fetchHTTP(parsedURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
case "http3":
|
|
||||||
if !C.WithQUIC {
|
|
||||||
return C.ErrQUICNotIncluded
|
|
||||||
}
|
|
||||||
parsedURL.Scheme = "https"
|
|
||||||
err = fetchHTTP(http3Client, parsedURL)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return E.New("unsupported scheme: ", parsedURL.Scheme)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func fetchHTTP(httpClient *http.Client, parsedURL *url.URL) error {
|
func fetchHTTP(parsedURL *url.URL) error {
|
||||||
request, err := http.NewRequest("GET", parsedURL.String(), nil)
|
request, err := http.NewRequest("GET", parsedURL.String(), nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
//go:build with_quic
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"crypto/tls"
|
|
||||||
"net/http"
|
|
||||||
|
|
||||||
"github.com/sagernet/quic-go"
|
|
||||||
"github.com/sagernet/quic-go/http3"
|
|
||||||
box "github.com/sagernet/sing-box"
|
|
||||||
"github.com/sagernet/sing/common/bufio"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
func initializeHTTP3Client(instance *box.Box) error {
|
|
||||||
dialer, err := createDialer(instance, commandToolsFlagOutbound)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
http3Client = &http.Client{
|
|
||||||
Transport: &http3.Transport{
|
|
||||||
Dial: func(ctx context.Context, addr string, tlsCfg *tls.Config, cfg *quic.Config) (quic.EarlyConnection, error) {
|
|
||||||
destination := M.ParseSocksaddr(addr)
|
|
||||||
udpConn, dErr := dialer.DialContext(ctx, N.NetworkUDP, destination)
|
|
||||||
if dErr != nil {
|
|
||||||
return nil, dErr
|
|
||||||
}
|
|
||||||
return quic.DialEarly(ctx, bufio.NewUnbindPacketConn(udpConn), udpConn.RemoteAddr(), tlsCfg, cfg)
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
//go:build !with_quic
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/url"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
box "github.com/sagernet/sing-box"
|
|
||||||
)
|
|
||||||
|
|
||||||
func initializeHTTP3Client(instance *box.Box) error {
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
|
|
||||||
func fetchHTTP3(parsedURL *url.URL) error {
|
|
||||||
return os.ErrInvalid
|
|
||||||
}
|
|
||||||
@@ -4,10 +4,12 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"os"
|
"os"
|
||||||
|
|
||||||
|
"github.com/sagernet/sing-box/common/settings"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
C "github.com/sagernet/sing-box/constant"
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
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/ntp"
|
||||||
|
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
@@ -43,7 +45,7 @@ func syncTime() error {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
dialer, err := createDialer(instance, commandToolsFlagOutbound)
|
dialer, err := createDialer(instance, N.NetworkUDP, commandToolsFlagOutbound)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -57,7 +59,7 @@ func syncTime() error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if commandSyncTimeWrite {
|
if commandSyncTimeWrite {
|
||||||
err = ntp.SetSystemTime(response.Time)
|
err = settings.SetSystemTime(response.Time)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return E.Cause(err, "write time to system")
|
return E.Cause(err, "write time to system")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,28 +0,0 @@
|
|||||||
//go:build generate && generate_completions
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import "github.com/sagernet/sing-box/log"
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
err := generateCompletions()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateCompletions() error {
|
|
||||||
err := mainCommand.GenBashCompletionFile("release/completions/sing-box.bash")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = mainCommand.GenFishCompletionFile("release/completions/sing-box.fish", true)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
err = mainCommand.GenZshCompletionFile("release/completions/sing-box.zsh")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,346 +0,0 @@
|
|||||||
package adguard
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bufio"
|
|
||||||
"io"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
)
|
|
||||||
|
|
||||||
type agdguardRuleLine struct {
|
|
||||||
ruleLine string
|
|
||||||
isRawDomain bool
|
|
||||||
isExclude bool
|
|
||||||
isSuffix bool
|
|
||||||
hasStart bool
|
|
||||||
hasEnd bool
|
|
||||||
isRegexp bool
|
|
||||||
isImportant bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func Convert(reader io.Reader) ([]option.HeadlessRule, error) {
|
|
||||||
scanner := bufio.NewScanner(reader)
|
|
||||||
var (
|
|
||||||
ruleLines []agdguardRuleLine
|
|
||||||
ignoredLines int
|
|
||||||
)
|
|
||||||
parseLine:
|
|
||||||
for scanner.Scan() {
|
|
||||||
ruleLine := scanner.Text()
|
|
||||||
if ruleLine == "" || ruleLine[0] == '!' || ruleLine[0] == '#' {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
originRuleLine := ruleLine
|
|
||||||
if M.IsDomainName(ruleLine) {
|
|
||||||
ruleLines = append(ruleLines, agdguardRuleLine{
|
|
||||||
ruleLine: ruleLine,
|
|
||||||
isRawDomain: true,
|
|
||||||
})
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
hostLine, err := parseAdGuardHostLine(ruleLine)
|
|
||||||
if err == nil {
|
|
||||||
if hostLine != "" {
|
|
||||||
ruleLines = append(ruleLines, agdguardRuleLine{
|
|
||||||
ruleLine: hostLine,
|
|
||||||
isRawDomain: true,
|
|
||||||
hasStart: true,
|
|
||||||
hasEnd: true,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(ruleLine, "|") {
|
|
||||||
ruleLine = ruleLine[:len(ruleLine)-1]
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
isExclude bool
|
|
||||||
isSuffix bool
|
|
||||||
hasStart bool
|
|
||||||
hasEnd bool
|
|
||||||
isRegexp bool
|
|
||||||
isImportant bool
|
|
||||||
)
|
|
||||||
if !strings.HasPrefix(ruleLine, "/") && strings.Contains(ruleLine, "$") {
|
|
||||||
params := common.SubstringAfter(ruleLine, "$")
|
|
||||||
for _, param := range strings.Split(params, ",") {
|
|
||||||
paramParts := strings.Split(param, "=")
|
|
||||||
var ignored bool
|
|
||||||
if len(paramParts) > 0 && len(paramParts) <= 2 {
|
|
||||||
switch paramParts[0] {
|
|
||||||
case "app", "network":
|
|
||||||
// maybe support by package_name/process_name
|
|
||||||
case "dnstype":
|
|
||||||
// maybe support by query_type
|
|
||||||
case "important":
|
|
||||||
ignored = true
|
|
||||||
isImportant = true
|
|
||||||
case "dnsrewrite":
|
|
||||||
if len(paramParts) == 2 && M.ParseAddr(paramParts[1]).IsUnspecified() {
|
|
||||||
ignored = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !ignored {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with modifier: ", paramParts[0], ": ", ruleLine)
|
|
||||||
continue parseLine
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ruleLine = common.SubstringBefore(ruleLine, "$")
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(ruleLine, "@@") {
|
|
||||||
ruleLine = ruleLine[2:]
|
|
||||||
isExclude = true
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(ruleLine, "|") {
|
|
||||||
ruleLine = ruleLine[:len(ruleLine)-1]
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(ruleLine, "||") {
|
|
||||||
ruleLine = ruleLine[2:]
|
|
||||||
isSuffix = true
|
|
||||||
} else if strings.HasPrefix(ruleLine, "|") {
|
|
||||||
ruleLine = ruleLine[1:]
|
|
||||||
hasStart = true
|
|
||||||
}
|
|
||||||
if strings.HasSuffix(ruleLine, "^") {
|
|
||||||
ruleLine = ruleLine[:len(ruleLine)-1]
|
|
||||||
hasEnd = true
|
|
||||||
}
|
|
||||||
if strings.HasPrefix(ruleLine, "/") && strings.HasSuffix(ruleLine, "/") {
|
|
||||||
ruleLine = ruleLine[1 : len(ruleLine)-1]
|
|
||||||
if ignoreIPCIDRRegexp(ruleLine) {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with IPCIDR regexp: ", ruleLine)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
isRegexp = true
|
|
||||||
} else {
|
|
||||||
if strings.Contains(ruleLine, "://") {
|
|
||||||
ruleLine = common.SubstringAfter(ruleLine, "://")
|
|
||||||
}
|
|
||||||
if strings.Contains(ruleLine, "/") {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with path: ", ruleLine)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.Contains(ruleLine, "##") {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with element hiding: ", ruleLine)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if strings.Contains(ruleLine, "#$#") {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with element hiding: ", ruleLine)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
var domainCheck string
|
|
||||||
if strings.HasPrefix(ruleLine, ".") || strings.HasPrefix(ruleLine, "-") {
|
|
||||||
domainCheck = "r" + ruleLine
|
|
||||||
} else {
|
|
||||||
domainCheck = ruleLine
|
|
||||||
}
|
|
||||||
if ruleLine == "" {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with empty domain", originRuleLine)
|
|
||||||
continue
|
|
||||||
} else {
|
|
||||||
domainCheck = strings.ReplaceAll(domainCheck, "*", "x")
|
|
||||||
if !M.IsDomainName(domainCheck) {
|
|
||||||
_, ipErr := parseADGuardIPCIDRLine(ruleLine)
|
|
||||||
if ipErr == nil {
|
|
||||||
ignoredLines++
|
|
||||||
log.Debug("ignored unsupported rule with IPCIDR: ", ruleLine)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if M.ParseSocksaddr(domainCheck).Port != 0 {
|
|
||||||
log.Debug("ignored unsupported rule with port: ", ruleLine)
|
|
||||||
} else {
|
|
||||||
log.Debug("ignored unsupported rule with invalid domain: ", ruleLine)
|
|
||||||
}
|
|
||||||
ignoredLines++
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ruleLines = append(ruleLines, agdguardRuleLine{
|
|
||||||
ruleLine: ruleLine,
|
|
||||||
isExclude: isExclude,
|
|
||||||
isSuffix: isSuffix,
|
|
||||||
hasStart: hasStart,
|
|
||||||
hasEnd: hasEnd,
|
|
||||||
isRegexp: isRegexp,
|
|
||||||
isImportant: isImportant,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if len(ruleLines) == 0 {
|
|
||||||
return nil, E.New("AdGuard rule-set is empty or all rules are unsupported")
|
|
||||||
}
|
|
||||||
if common.All(ruleLines, func(it agdguardRuleLine) bool {
|
|
||||||
return it.isRawDomain
|
|
||||||
}) {
|
|
||||||
return []option.HeadlessRule{
|
|
||||||
{
|
|
||||||
Type: C.RuleTypeDefault,
|
|
||||||
DefaultOptions: option.DefaultHeadlessRule{
|
|
||||||
Domain: common.Map(ruleLines, func(it agdguardRuleLine) string {
|
|
||||||
return it.ruleLine
|
|
||||||
}),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}, nil
|
|
||||||
}
|
|
||||||
mapDomain := func(it agdguardRuleLine) string {
|
|
||||||
ruleLine := it.ruleLine
|
|
||||||
if it.isSuffix {
|
|
||||||
ruleLine = "||" + ruleLine
|
|
||||||
} else if it.hasStart {
|
|
||||||
ruleLine = "|" + ruleLine
|
|
||||||
}
|
|
||||||
if it.hasEnd {
|
|
||||||
ruleLine += "^"
|
|
||||||
}
|
|
||||||
return ruleLine
|
|
||||||
}
|
|
||||||
|
|
||||||
importantDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && !it.isRegexp && !it.isExclude }), mapDomain)
|
|
||||||
importantDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && it.isRegexp && !it.isExclude }), mapDomain)
|
|
||||||
importantExcludeDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && !it.isRegexp && it.isExclude }), mapDomain)
|
|
||||||
importantExcludeDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return it.isImportant && it.isRegexp && it.isExclude }), mapDomain)
|
|
||||||
domain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && !it.isRegexp && !it.isExclude }), mapDomain)
|
|
||||||
domainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && it.isRegexp && !it.isExclude }), mapDomain)
|
|
||||||
excludeDomain := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && !it.isRegexp && it.isExclude }), mapDomain)
|
|
||||||
excludeDomainRegex := common.Map(common.Filter(ruleLines, func(it agdguardRuleLine) bool { return !it.isImportant && it.isRegexp && it.isExclude }), mapDomain)
|
|
||||||
currentRule := option.HeadlessRule{
|
|
||||||
Type: C.RuleTypeDefault,
|
|
||||||
DefaultOptions: option.DefaultHeadlessRule{
|
|
||||||
AdGuardDomain: domain,
|
|
||||||
DomainRegex: domainRegex,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
if len(excludeDomain) > 0 || len(excludeDomainRegex) > 0 {
|
|
||||||
currentRule = option.HeadlessRule{
|
|
||||||
Type: C.RuleTypeLogical,
|
|
||||||
LogicalOptions: option.LogicalHeadlessRule{
|
|
||||||
Mode: C.LogicalTypeAnd,
|
|
||||||
Rules: []option.HeadlessRule{
|
|
||||||
{
|
|
||||||
Type: C.RuleTypeDefault,
|
|
||||||
DefaultOptions: option.DefaultHeadlessRule{
|
|
||||||
AdGuardDomain: excludeDomain,
|
|
||||||
DomainRegex: excludeDomainRegex,
|
|
||||||
Invert: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
currentRule,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(importantDomain) > 0 || len(importantDomainRegex) > 0 {
|
|
||||||
currentRule = option.HeadlessRule{
|
|
||||||
Type: C.RuleTypeLogical,
|
|
||||||
LogicalOptions: option.LogicalHeadlessRule{
|
|
||||||
Mode: C.LogicalTypeOr,
|
|
||||||
Rules: []option.HeadlessRule{
|
|
||||||
{
|
|
||||||
Type: C.RuleTypeDefault,
|
|
||||||
DefaultOptions: option.DefaultHeadlessRule{
|
|
||||||
AdGuardDomain: importantDomain,
|
|
||||||
DomainRegex: importantDomainRegex,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
currentRule,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(importantExcludeDomain) > 0 || len(importantExcludeDomainRegex) > 0 {
|
|
||||||
currentRule = option.HeadlessRule{
|
|
||||||
Type: C.RuleTypeLogical,
|
|
||||||
LogicalOptions: option.LogicalHeadlessRule{
|
|
||||||
Mode: C.LogicalTypeAnd,
|
|
||||||
Rules: []option.HeadlessRule{
|
|
||||||
{
|
|
||||||
Type: C.RuleTypeDefault,
|
|
||||||
DefaultOptions: option.DefaultHeadlessRule{
|
|
||||||
AdGuardDomain: importantExcludeDomain,
|
|
||||||
DomainRegex: importantExcludeDomainRegex,
|
|
||||||
Invert: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
currentRule,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
log.Info("parsed rules: ", len(ruleLines), "/", len(ruleLines)+ignoredLines)
|
|
||||||
return []option.HeadlessRule{currentRule}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func ignoreIPCIDRRegexp(ruleLine string) bool {
|
|
||||||
if strings.HasPrefix(ruleLine, "(http?:\\/\\/)") {
|
|
||||||
ruleLine = ruleLine[12:]
|
|
||||||
} else if strings.HasPrefix(ruleLine, "(https?:\\/\\/)") {
|
|
||||||
ruleLine = ruleLine[13:]
|
|
||||||
} else if strings.HasPrefix(ruleLine, "^") {
|
|
||||||
ruleLine = ruleLine[1:]
|
|
||||||
} else {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, parseErr := strconv.ParseUint(common.SubstringBefore(ruleLine, "\\."), 10, 8)
|
|
||||||
return parseErr == nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseAdGuardHostLine(ruleLine string) (string, error) {
|
|
||||||
idx := strings.Index(ruleLine, " ")
|
|
||||||
if idx == -1 {
|
|
||||||
return "", os.ErrInvalid
|
|
||||||
}
|
|
||||||
address, err := netip.ParseAddr(ruleLine[:idx])
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if !address.IsUnspecified() {
|
|
||||||
return "", nil
|
|
||||||
}
|
|
||||||
domain := ruleLine[idx+1:]
|
|
||||||
if !M.IsDomainName(domain) {
|
|
||||||
return "", E.New("invalid domain name: ", domain)
|
|
||||||
}
|
|
||||||
return domain, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseADGuardIPCIDRLine(ruleLine string) (netip.Prefix, error) {
|
|
||||||
var isPrefix bool
|
|
||||||
if strings.HasSuffix(ruleLine, ".") {
|
|
||||||
isPrefix = true
|
|
||||||
ruleLine = ruleLine[:len(ruleLine)-1]
|
|
||||||
}
|
|
||||||
ruleStringParts := strings.Split(ruleLine, ".")
|
|
||||||
if len(ruleStringParts) > 4 || len(ruleStringParts) < 4 && !isPrefix {
|
|
||||||
return netip.Prefix{}, os.ErrInvalid
|
|
||||||
}
|
|
||||||
ruleParts := make([]uint8, 0, len(ruleStringParts))
|
|
||||||
for _, part := range ruleStringParts {
|
|
||||||
rulePart, err := strconv.ParseUint(part, 10, 8)
|
|
||||||
if err != nil {
|
|
||||||
return netip.Prefix{}, err
|
|
||||||
}
|
|
||||||
ruleParts = append(ruleParts, uint8(rulePart))
|
|
||||||
}
|
|
||||||
bitLen := len(ruleParts) * 8
|
|
||||||
for len(ruleParts) < 4 {
|
|
||||||
ruleParts = append(ruleParts, 0)
|
|
||||||
}
|
|
||||||
return netip.PrefixFrom(netip.AddrFrom4(*(*[4]byte)(ruleParts)), bitLen), nil
|
|
||||||
}
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
package adguard
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-box/route/rule"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestConverter(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
rules, err := Convert(strings.NewReader(`
|
|
||||||
||example.org^
|
|
||||||
|example.com^
|
|
||||||
example.net^
|
|
||||||
||example.edu
|
|
||||||
||example.edu.tw^
|
|
||||||
|example.gov
|
|
||||||
example.arpa
|
|
||||||
@@|sagernet.example.org|
|
|
||||||
||sagernet.org^$important
|
|
||||||
@@|sing-box.sagernet.org^$important
|
|
||||||
`))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, rules, 1)
|
|
||||||
rule, err := rule.NewHeadlessRule(context.Background(), rules[0])
|
|
||||||
require.NoError(t, err)
|
|
||||||
matchDomain := []string{
|
|
||||||
"example.org",
|
|
||||||
"www.example.org",
|
|
||||||
"example.com",
|
|
||||||
"example.net",
|
|
||||||
"isexample.net",
|
|
||||||
"www.example.net",
|
|
||||||
"example.edu",
|
|
||||||
"example.edu.cn",
|
|
||||||
"example.edu.tw",
|
|
||||||
"www.example.edu",
|
|
||||||
"www.example.edu.cn",
|
|
||||||
"example.gov",
|
|
||||||
"example.gov.cn",
|
|
||||||
"example.arpa",
|
|
||||||
"www.example.arpa",
|
|
||||||
"isexample.arpa",
|
|
||||||
"example.arpa.cn",
|
|
||||||
"www.example.arpa.cn",
|
|
||||||
"isexample.arpa.cn",
|
|
||||||
"sagernet.org",
|
|
||||||
"www.sagernet.org",
|
|
||||||
}
|
|
||||||
notMatchDomain := []string{
|
|
||||||
"example.org.cn",
|
|
||||||
"notexample.org",
|
|
||||||
"example.com.cn",
|
|
||||||
"www.example.com.cn",
|
|
||||||
"example.net.cn",
|
|
||||||
"notexample.edu",
|
|
||||||
"notexample.edu.cn",
|
|
||||||
"www.example.gov",
|
|
||||||
"notexample.gov",
|
|
||||||
"sagernet.example.org",
|
|
||||||
"sing-box.sagernet.org",
|
|
||||||
}
|
|
||||||
for _, domain := range matchDomain {
|
|
||||||
require.True(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
for _, domain := range notMatchDomain {
|
|
||||||
require.False(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestHosts(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
rules, err := Convert(strings.NewReader(`
|
|
||||||
127.0.0.1 localhost
|
|
||||||
::1 localhost #[IPv6]
|
|
||||||
0.0.0.0 google.com
|
|
||||||
`))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, rules, 1)
|
|
||||||
rule, err := rule.NewHeadlessRule(context.Background(), rules[0])
|
|
||||||
require.NoError(t, err)
|
|
||||||
matchDomain := []string{
|
|
||||||
"google.com",
|
|
||||||
}
|
|
||||||
notMatchDomain := []string{
|
|
||||||
"www.google.com",
|
|
||||||
"notgoogle.com",
|
|
||||||
"localhost",
|
|
||||||
}
|
|
||||||
for _, domain := range matchDomain {
|
|
||||||
require.True(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
for _, domain := range notMatchDomain {
|
|
||||||
require.False(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSimpleHosts(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
rules, err := Convert(strings.NewReader(`
|
|
||||||
example.com
|
|
||||||
www.example.org
|
|
||||||
`))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, rules, 1)
|
|
||||||
rule, err := rule.NewHeadlessRule(context.Background(), rules[0])
|
|
||||||
require.NoError(t, err)
|
|
||||||
matchDomain := []string{
|
|
||||||
"example.com",
|
|
||||||
"www.example.org",
|
|
||||||
}
|
|
||||||
notMatchDomain := []string{
|
|
||||||
"example.com.cn",
|
|
||||||
"www.example.com",
|
|
||||||
"notexample.com",
|
|
||||||
"example.org",
|
|
||||||
}
|
|
||||||
for _, domain := range matchDomain {
|
|
||||||
require.True(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
for _, domain := range notMatchDomain {
|
|
||||||
require.False(t, rule.Match(&adapter.InboundContext{
|
|
||||||
Domain: domain,
|
|
||||||
}), domain)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +1,74 @@
|
|||||||
//go:build !generate
|
|
||||||
|
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import "github.com/sagernet/sing-box/log"
|
import (
|
||||||
|
"context"
|
||||||
|
"os"
|
||||||
|
"os/user"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
_ "github.com/sagernet/sing-box/include"
|
||||||
|
"github.com/sagernet/sing-box/log"
|
||||||
|
"github.com/sagernet/sing/service/filemanager"
|
||||||
|
|
||||||
|
"github.com/spf13/cobra"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
globalCtx context.Context
|
||||||
|
configPaths []string
|
||||||
|
configDirectories []string
|
||||||
|
workingDir string
|
||||||
|
disableColor bool
|
||||||
|
)
|
||||||
|
|
||||||
|
var mainCommand = &cobra.Command{
|
||||||
|
Use: "sing-box",
|
||||||
|
PersistentPreRun: preRun,
|
||||||
|
}
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
mainCommand.PersistentFlags().StringArrayVarP(&configPaths, "config", "c", nil, "set configuration file path")
|
||||||
|
mainCommand.PersistentFlags().StringArrayVarP(&configDirectories, "config-directory", "C", nil, "set configuration directory path")
|
||||||
|
mainCommand.PersistentFlags().StringVarP(&workingDir, "directory", "D", "", "set working directory")
|
||||||
|
mainCommand.PersistentFlags().BoolVarP(&disableColor, "disable-color", "", false, "disable color output")
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
if err := mainCommand.Execute(); err != nil {
|
if err := mainCommand.Execute(); err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func preRun(cmd *cobra.Command, args []string) {
|
||||||
|
globalCtx = context.Background()
|
||||||
|
sudoUser := os.Getenv("SUDO_USER")
|
||||||
|
sudoUID, _ := strconv.Atoi(os.Getenv("SUDO_UID"))
|
||||||
|
sudoGID, _ := strconv.Atoi(os.Getenv("SUDO_GID"))
|
||||||
|
if sudoUID == 0 && sudoGID == 0 && sudoUser != "" {
|
||||||
|
sudoUserObject, _ := user.Lookup(sudoUser)
|
||||||
|
if sudoUserObject != nil {
|
||||||
|
sudoUID, _ = strconv.Atoi(sudoUserObject.Uid)
|
||||||
|
sudoGID, _ = strconv.Atoi(sudoUserObject.Gid)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if sudoUID > 0 && sudoGID > 0 {
|
||||||
|
globalCtx = filemanager.WithDefault(globalCtx, "", "", sudoUID, sudoGID)
|
||||||
|
}
|
||||||
|
if disableColor {
|
||||||
|
log.SetStdLogger(log.NewDefaultFactory(context.Background(), log.Formatter{BaseTime: time.Now(), DisableColors: true}, os.Stderr, "", nil, false).Logger())
|
||||||
|
}
|
||||||
|
if workingDir != "" {
|
||||||
|
_, err := os.Stat(workingDir)
|
||||||
|
if err != nil {
|
||||||
|
filemanager.MkdirAll(globalCtx, workingDir, 0o777)
|
||||||
|
}
|
||||||
|
err = os.Chdir(workingDir)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(configPaths) == 0 && len(configDirectories) == 0 {
|
||||||
|
configPaths = append(configPaths, "config.json")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,133 +2,60 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
"github.com/sagernet/sing-box/common/conntrack"
|
"github.com/sagernet/sing-box/common/conntrack"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
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-box/option"
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/atomic"
|
|
||||||
"github.com/sagernet/sing/common/control"
|
"github.com/sagernet/sing/common/control"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/sing/service"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var _ WireGuardListener = (*DefaultDialer)(nil)
|
||||||
_ ParallelInterfaceDialer = (*DefaultDialer)(nil)
|
|
||||||
_ WireGuardListener = (*DefaultDialer)(nil)
|
|
||||||
)
|
|
||||||
|
|
||||||
type DefaultDialer struct {
|
type DefaultDialer struct {
|
||||||
dialer4 tcpDialer
|
dialer4 tcpDialer
|
||||||
dialer6 tcpDialer
|
dialer6 tcpDialer
|
||||||
udpDialer4 net.Dialer
|
udpDialer4 net.Dialer
|
||||||
udpDialer6 net.Dialer
|
udpDialer6 net.Dialer
|
||||||
udpListener net.ListenConfig
|
udpListener net.ListenConfig
|
||||||
udpAddr4 string
|
udpAddr4 string
|
||||||
udpAddr6 string
|
udpAddr6 string
|
||||||
isWireGuardListener bool
|
isWireGuardListener bool
|
||||||
networkManager adapter.NetworkManager
|
|
||||||
networkStrategy *C.NetworkStrategy
|
|
||||||
defaultNetworkStrategy bool
|
|
||||||
networkType []C.InterfaceType
|
|
||||||
fallbackNetworkType []C.InterfaceType
|
|
||||||
networkFallbackDelay time.Duration
|
|
||||||
networkLastFallback atomic.TypedValue[time.Time]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDialer, error) {
|
func NewDefault(router adapter.Router, options option.DialerOptions) (*DefaultDialer, error) {
|
||||||
networkManager := service.FromContext[adapter.NetworkManager](ctx)
|
var dialer net.Dialer
|
||||||
platformInterface := service.FromContext[platform.Interface](ctx)
|
var listener net.ListenConfig
|
||||||
|
|
||||||
var (
|
|
||||||
dialer net.Dialer
|
|
||||||
listener net.ListenConfig
|
|
||||||
interfaceFinder control.InterfaceFinder
|
|
||||||
networkStrategy *C.NetworkStrategy
|
|
||||||
defaultNetworkStrategy bool
|
|
||||||
networkType []C.InterfaceType
|
|
||||||
fallbackNetworkType []C.InterfaceType
|
|
||||||
networkFallbackDelay time.Duration
|
|
||||||
)
|
|
||||||
if networkManager != nil {
|
|
||||||
interfaceFinder = networkManager.InterfaceFinder()
|
|
||||||
} else {
|
|
||||||
interfaceFinder = control.NewDefaultInterfaceFinder()
|
|
||||||
}
|
|
||||||
if options.BindInterface != "" {
|
if options.BindInterface != "" {
|
||||||
|
var interfaceFinder control.InterfaceFinder
|
||||||
|
if router != nil {
|
||||||
|
interfaceFinder = router.InterfaceFinder()
|
||||||
|
} else {
|
||||||
|
interfaceFinder = control.NewDefaultInterfaceFinder()
|
||||||
|
}
|
||||||
bindFunc := control.BindToInterface(interfaceFinder, options.BindInterface, -1)
|
bindFunc := control.BindToInterface(interfaceFinder, options.BindInterface, -1)
|
||||||
dialer.Control = control.Append(dialer.Control, bindFunc)
|
dialer.Control = control.Append(dialer.Control, bindFunc)
|
||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
listener.Control = control.Append(listener.Control, bindFunc)
|
||||||
|
} else if router != nil && router.AutoDetectInterface() {
|
||||||
|
bindFunc := router.AutoDetectInterfaceFunc()
|
||||||
|
dialer.Control = control.Append(dialer.Control, bindFunc)
|
||||||
|
listener.Control = control.Append(listener.Control, bindFunc)
|
||||||
|
} else if router != nil && router.DefaultInterface() != "" {
|
||||||
|
bindFunc := control.BindToInterface(router.InterfaceFinder(), router.DefaultInterface(), -1)
|
||||||
|
dialer.Control = control.Append(dialer.Control, bindFunc)
|
||||||
|
listener.Control = control.Append(listener.Control, bindFunc)
|
||||||
}
|
}
|
||||||
if options.RoutingMark > 0 {
|
if options.RoutingMark != 0 {
|
||||||
dialer.Control = control.Append(dialer.Control, control.RoutingMark(uint32(options.RoutingMark)))
|
dialer.Control = control.Append(dialer.Control, control.RoutingMark(options.RoutingMark))
|
||||||
listener.Control = control.Append(listener.Control, control.RoutingMark(uint32(options.RoutingMark)))
|
listener.Control = control.Append(listener.Control, control.RoutingMark(options.RoutingMark))
|
||||||
}
|
} else if router != nil && router.DefaultMark() != 0 {
|
||||||
if networkManager != nil {
|
dialer.Control = control.Append(dialer.Control, control.RoutingMark(router.DefaultMark()))
|
||||||
autoRedirectOutputMark := networkManager.AutoRedirectOutputMark()
|
listener.Control = control.Append(listener.Control, control.RoutingMark(router.DefaultMark()))
|
||||||
if autoRedirectOutputMark > 0 {
|
|
||||||
if options.RoutingMark > 0 {
|
|
||||||
return nil, E.New("`routing_mark` is conflict with `tun.auto_redirect` with `tun.route_[_exclude]_address_set")
|
|
||||||
}
|
|
||||||
dialer.Control = control.Append(dialer.Control, control.RoutingMark(autoRedirectOutputMark))
|
|
||||||
listener.Control = control.Append(listener.Control, control.RoutingMark(autoRedirectOutputMark))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
disableDefaultBind := options.BindInterface != "" || options.Inet4BindAddress != nil || options.Inet6BindAddress != nil
|
|
||||||
if disableDefaultBind || options.TCPFastOpen {
|
|
||||||
if options.NetworkStrategy != nil || len(options.NetworkType) > 0 && options.FallbackNetworkType == nil && options.FallbackDelay == 0 {
|
|
||||||
return nil, E.New("`network_strategy` is conflict with `bind_interface`, `inet4_bind_address`, `inet6_bind_address` and `tcp_fast_open`")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if networkManager != nil {
|
|
||||||
defaultOptions := networkManager.DefaultOptions()
|
|
||||||
if !disableDefaultBind {
|
|
||||||
if defaultOptions.BindInterface != "" {
|
|
||||||
bindFunc := control.BindToInterface(networkManager.InterfaceFinder(), defaultOptions.BindInterface, -1)
|
|
||||||
dialer.Control = control.Append(dialer.Control, bindFunc)
|
|
||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
|
||||||
} else if networkManager.AutoDetectInterface() {
|
|
||||||
if platformInterface != nil {
|
|
||||||
networkStrategy = (*C.NetworkStrategy)(options.NetworkStrategy)
|
|
||||||
if networkStrategy == nil {
|
|
||||||
networkStrategy = common.Ptr(C.NetworkStrategyDefault)
|
|
||||||
defaultNetworkStrategy = true
|
|
||||||
}
|
|
||||||
networkType = common.Map(options.NetworkType, option.InterfaceType.Build)
|
|
||||||
fallbackNetworkType = common.Map(options.FallbackNetworkType, option.InterfaceType.Build)
|
|
||||||
if networkStrategy == nil && len(networkType) == 0 && len(fallbackNetworkType) == 0 {
|
|
||||||
networkStrategy = defaultOptions.NetworkStrategy
|
|
||||||
networkType = defaultOptions.NetworkType
|
|
||||||
fallbackNetworkType = defaultOptions.FallbackNetworkType
|
|
||||||
}
|
|
||||||
networkFallbackDelay = time.Duration(options.FallbackDelay)
|
|
||||||
if networkFallbackDelay == 0 && defaultOptions.FallbackDelay != 0 {
|
|
||||||
networkFallbackDelay = defaultOptions.FallbackDelay
|
|
||||||
}
|
|
||||||
bindFunc := networkManager.ProtectFunc()
|
|
||||||
dialer.Control = control.Append(dialer.Control, bindFunc)
|
|
||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
|
||||||
} else {
|
|
||||||
bindFunc := networkManager.AutoDetectInterfaceFunc()
|
|
||||||
dialer.Control = control.Append(dialer.Control, bindFunc)
|
|
||||||
listener.Control = control.Append(listener.Control, bindFunc)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if options.RoutingMark == 0 && defaultOptions.RoutingMark != 0 {
|
|
||||||
dialer.Control = control.Append(dialer.Control, control.RoutingMark(defaultOptions.RoutingMark))
|
|
||||||
listener.Control = control.Append(listener.Control, control.RoutingMark(defaultOptions.RoutingMark))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if options.ReuseAddr {
|
if options.ReuseAddr {
|
||||||
listener.Control = control.Append(listener.Control, control.ReuseAddr())
|
listener.Control = control.Append(listener.Control, control.ReuseAddr())
|
||||||
@@ -140,7 +67,7 @@ func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDial
|
|||||||
if options.ConnectTimeout != 0 {
|
if options.ConnectTimeout != 0 {
|
||||||
dialer.Timeout = time.Duration(options.ConnectTimeout)
|
dialer.Timeout = time.Duration(options.ConnectTimeout)
|
||||||
} else {
|
} else {
|
||||||
dialer.Timeout = C.TCPConnectTimeout
|
dialer.Timeout = C.TCPTimeout
|
||||||
}
|
}
|
||||||
// TODO: Add an option to customize the keep alive period
|
// TODO: Add an option to customize the keep alive period
|
||||||
dialer.KeepAlive = C.TCPKeepAliveInitial
|
dialer.KeepAlive = C.TCPKeepAliveInitial
|
||||||
@@ -161,7 +88,7 @@ func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDial
|
|||||||
udpAddr4 string
|
udpAddr4 string
|
||||||
)
|
)
|
||||||
if options.Inet4BindAddress != nil {
|
if options.Inet4BindAddress != nil {
|
||||||
bindAddr := options.Inet4BindAddress.Build(netip.IPv4Unspecified())
|
bindAddr := options.Inet4BindAddress.Build()
|
||||||
dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
|
dialer4.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
|
||||||
udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
|
udpDialer4.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
|
||||||
udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
|
udpAddr4 = M.SocksaddrFrom(bindAddr, 0).String()
|
||||||
@@ -172,7 +99,7 @@ func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDial
|
|||||||
udpAddr6 string
|
udpAddr6 string
|
||||||
)
|
)
|
||||||
if options.Inet6BindAddress != nil {
|
if options.Inet6BindAddress != nil {
|
||||||
bindAddr := options.Inet6BindAddress.Build(netip.IPv6Unspecified())
|
bindAddr := options.Inet6BindAddress.Build()
|
||||||
dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
|
dialer6.LocalAddr = &net.TCPAddr{IP: bindAddr.AsSlice()}
|
||||||
udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
|
udpDialer6.LocalAddr = &net.UDPAddr{IP: bindAddr.AsSlice()}
|
||||||
udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
|
udpAddr6 = M.SocksaddrFrom(bindAddr, 0).String()
|
||||||
@@ -184,7 +111,7 @@ func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDial
|
|||||||
setMultiPathTCP(&dialer4)
|
setMultiPathTCP(&dialer4)
|
||||||
}
|
}
|
||||||
if options.IsWireGuardListener {
|
if options.IsWireGuardListener {
|
||||||
for _, controlFn := range WgControlFns {
|
for _, controlFn := range wgControlFns {
|
||||||
listener.Control = control.Append(listener.Control, controlFn)
|
listener.Control = control.Append(listener.Control, controlFn)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -197,20 +124,14 @@ func NewDefault(ctx context.Context, options option.DialerOptions) (*DefaultDial
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &DefaultDialer{
|
return &DefaultDialer{
|
||||||
dialer4: tcpDialer4,
|
tcpDialer4,
|
||||||
dialer6: tcpDialer6,
|
tcpDialer6,
|
||||||
udpDialer4: udpDialer4,
|
udpDialer4,
|
||||||
udpDialer6: udpDialer6,
|
udpDialer6,
|
||||||
udpListener: listener,
|
listener,
|
||||||
udpAddr4: udpAddr4,
|
udpAddr4,
|
||||||
udpAddr6: udpAddr6,
|
udpAddr6,
|
||||||
isWireGuardListener: options.IsWireGuardListener,
|
options.IsWireGuardListener,
|
||||||
networkManager: networkManager,
|
|
||||||
networkStrategy: networkStrategy,
|
|
||||||
defaultNetworkStrategy: defaultNetworkStrategy,
|
|
||||||
networkType: networkType,
|
|
||||||
fallbackNetworkType: fallbackNetworkType,
|
|
||||||
networkFallbackDelay: networkFallbackDelay,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,122 +139,33 @@ func (d *DefaultDialer) DialContext(ctx context.Context, network string, address
|
|||||||
if !address.IsValid() {
|
if !address.IsValid() {
|
||||||
return nil, E.New("invalid address")
|
return nil, E.New("invalid address")
|
||||||
}
|
}
|
||||||
if d.networkStrategy == nil {
|
switch N.NetworkName(network) {
|
||||||
switch N.NetworkName(network) {
|
case N.NetworkUDP:
|
||||||
case N.NetworkUDP:
|
|
||||||
if !address.IsIPv6() {
|
|
||||||
return trackConn(d.udpDialer4.DialContext(ctx, network, address.String()))
|
|
||||||
} else {
|
|
||||||
return trackConn(d.udpDialer6.DialContext(ctx, network, address.String()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !address.IsIPv6() {
|
if !address.IsIPv6() {
|
||||||
return trackConn(DialSlowContext(&d.dialer4, ctx, network, address))
|
return trackConn(d.udpDialer4.DialContext(ctx, network, address.String()))
|
||||||
} else {
|
} else {
|
||||||
return trackConn(DialSlowContext(&d.dialer6, ctx, network, address))
|
return trackConn(d.udpDialer6.DialContext(ctx, network, address.String()))
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return d.DialParallelInterface(ctx, network, address, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DefaultDialer) DialParallelInterface(ctx context.Context, network string, address M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
|
|
||||||
if strategy == nil {
|
|
||||||
strategy = d.networkStrategy
|
|
||||||
}
|
|
||||||
if strategy == nil {
|
|
||||||
return d.DialContext(ctx, network, address)
|
|
||||||
}
|
|
||||||
if len(interfaceType) == 0 {
|
|
||||||
interfaceType = d.networkType
|
|
||||||
}
|
|
||||||
if len(fallbackInterfaceType) == 0 {
|
|
||||||
fallbackInterfaceType = d.fallbackNetworkType
|
|
||||||
}
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = d.networkFallbackDelay
|
|
||||||
}
|
|
||||||
var dialer net.Dialer
|
|
||||||
if N.NetworkName(network) == N.NetworkTCP {
|
|
||||||
dialer = dialerFromTCPDialer(d.dialer4)
|
|
||||||
} else {
|
|
||||||
dialer = d.udpDialer4
|
|
||||||
}
|
|
||||||
fastFallback := time.Now().Sub(d.networkLastFallback.Load()) < C.TCPTimeout
|
|
||||||
var (
|
|
||||||
conn net.Conn
|
|
||||||
isPrimary bool
|
|
||||||
err error
|
|
||||||
)
|
|
||||||
if !fastFallback {
|
|
||||||
conn, isPrimary, err = d.dialParallelInterface(ctx, dialer, network, address.String(), *strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
} else {
|
|
||||||
conn, isPrimary, err = d.dialParallelInterfaceFastFallback(ctx, dialer, network, address.String(), *strategy, interfaceType, fallbackInterfaceType, fallbackDelay, d.networkLastFallback.Store)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
// bind interface failed on legacy xiaomi systems
|
|
||||||
if d.defaultNetworkStrategy && errors.Is(err, syscall.EPERM) {
|
|
||||||
d.networkStrategy = nil
|
|
||||||
return d.DialContext(ctx, network, address)
|
|
||||||
} else {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !fastFallback && !isPrimary {
|
if !address.IsIPv6() {
|
||||||
d.networkLastFallback.Store(time.Now())
|
return trackConn(DialSlowContext(&d.dialer4, ctx, network, address))
|
||||||
|
} else {
|
||||||
|
return trackConn(DialSlowContext(&d.dialer6, ctx, network, address))
|
||||||
}
|
}
|
||||||
return trackConn(conn, nil)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
func (d *DefaultDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
if d.networkStrategy == nil {
|
if destination.IsIPv6() {
|
||||||
if destination.IsIPv6() {
|
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6))
|
||||||
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr6))
|
} else if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
|
||||||
} else if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
|
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP+"4", d.udpAddr4))
|
||||||
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP+"4", d.udpAddr4))
|
|
||||||
} else {
|
|
||||||
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4))
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
return d.ListenSerialInterfacePacket(ctx, destination, d.networkStrategy, d.networkType, d.fallbackNetworkType, d.networkFallbackDelay)
|
return trackPacketConn(d.udpListener.ListenPacket(ctx, N.NetworkUDP, d.udpAddr4))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DefaultDialer) ListenSerialInterfacePacket(ctx context.Context, destination M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, error) {
|
|
||||||
if strategy == nil {
|
|
||||||
strategy = d.networkStrategy
|
|
||||||
}
|
|
||||||
if strategy == nil {
|
|
||||||
return d.ListenPacket(ctx, destination)
|
|
||||||
}
|
|
||||||
if len(interfaceType) == 0 {
|
|
||||||
interfaceType = d.networkType
|
|
||||||
}
|
|
||||||
if len(fallbackInterfaceType) == 0 {
|
|
||||||
fallbackInterfaceType = d.fallbackNetworkType
|
|
||||||
}
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = d.networkFallbackDelay
|
|
||||||
}
|
|
||||||
network := N.NetworkUDP
|
|
||||||
if destination.IsIPv4() && !destination.Addr.IsUnspecified() {
|
|
||||||
network += "4"
|
|
||||||
}
|
|
||||||
packetConn, err := d.listenSerialInterfacePacket(ctx, d.udpListener, network, "", *strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
if err != nil {
|
|
||||||
// bind interface failed on legacy xiaomi systems
|
|
||||||
if d.defaultNetworkStrategy && errors.Is(err, syscall.EPERM) {
|
|
||||||
d.networkStrategy = nil
|
|
||||||
return d.ListenPacket(ctx, destination)
|
|
||||||
} else {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return trackPacketConn(packetConn, nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DefaultDialer) ListenPacketCompat(network, address string) (net.PacketConn, error) {
|
func (d *DefaultDialer) ListenPacketCompat(network, address string) (net.PacketConn, error) {
|
||||||
return d.udpListener.ListenPacket(context.Background(), network, address)
|
return trackPacketConn(d.udpListener.ListenPacket(context.Background(), network, address))
|
||||||
}
|
}
|
||||||
|
|
||||||
func trackConn(conn net.Conn, err error) (net.Conn, error) {
|
func trackConn(conn net.Conn, err error) (net.Conn, error) {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ package dialer
|
|||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/metacubex/tfo-go"
|
"github.com/sagernet/tfo-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
type tcpDialer = tfo.Dialer
|
type tcpDialer = tfo.Dialer
|
||||||
@@ -13,7 +13,3 @@ type tcpDialer = tfo.Dialer
|
|||||||
func newTCPDialer(dialer net.Dialer, tfoEnabled bool) (tcpDialer, error) {
|
func newTCPDialer(dialer net.Dialer, tfoEnabled bool) (tcpDialer, error) {
|
||||||
return tfo.Dialer{Dialer: dialer, DisableTFO: !tfoEnabled}, nil
|
return tfo.Dialer{Dialer: dialer, DisableTFO: !tfoEnabled}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialerFromTCPDialer(dialer tcpDialer) net.Dialer {
|
|
||||||
return dialer.Dialer
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -16,7 +16,3 @@ func newTCPDialer(dialer net.Dialer, tfoEnabled bool) (tcpDialer, error) {
|
|||||||
}
|
}
|
||||||
return dialer, nil
|
return dialer, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func dialerFromTCPDialer(dialer tcpDialer) net.Dialer {
|
|
||||||
return dialer
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -1,233 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
"github.com/sagernet/sing/common/control"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (d *DefaultDialer) dialParallelInterface(ctx context.Context, dialer net.Dialer, network string, addr string, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, bool, error) {
|
|
||||||
primaryInterfaces, fallbackInterfaces := selectInterfaces(d.networkManager, strategy, interfaceType, fallbackInterfaceType)
|
|
||||||
if len(primaryInterfaces)+len(fallbackInterfaces) == 0 {
|
|
||||||
return nil, false, E.New("no available network interface")
|
|
||||||
}
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = N.DefaultFallbackDelay
|
|
||||||
}
|
|
||||||
returned := make(chan struct{})
|
|
||||||
defer close(returned)
|
|
||||||
type dialResult struct {
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
primary bool
|
|
||||||
}
|
|
||||||
results := make(chan dialResult) // unbuffered
|
|
||||||
startRacer := func(ctx context.Context, primary bool, iif adapter.NetworkInterface) {
|
|
||||||
perNetDialer := dialer
|
|
||||||
perNetDialer.Control = control.Append(perNetDialer.Control, control.BindToInterface(nil, iif.Name, iif.Index))
|
|
||||||
conn, err := perNetDialer.DialContext(ctx, network, addr)
|
|
||||||
if err != nil {
|
|
||||||
select {
|
|
||||||
case results <- dialResult{error: E.Cause(err, "dial ", iif.Name, " (", iif.Index, ")"), primary: primary}:
|
|
||||||
case <-returned:
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
select {
|
|
||||||
case results <- dialResult{Conn: conn, primary: primary}:
|
|
||||||
case <-returned:
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
primaryCtx, primaryCancel := context.WithCancel(ctx)
|
|
||||||
defer primaryCancel()
|
|
||||||
for _, iif := range primaryInterfaces {
|
|
||||||
go startRacer(primaryCtx, true, iif)
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
fallbackTimer *time.Timer
|
|
||||||
fallbackChan <-chan time.Time
|
|
||||||
)
|
|
||||||
if len(fallbackInterfaces) > 0 {
|
|
||||||
fallbackTimer = time.NewTimer(fallbackDelay)
|
|
||||||
defer fallbackTimer.Stop()
|
|
||||||
fallbackChan = fallbackTimer.C
|
|
||||||
}
|
|
||||||
var errors []error
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-fallbackChan:
|
|
||||||
fallbackCtx, fallbackCancel := context.WithCancel(ctx)
|
|
||||||
defer fallbackCancel()
|
|
||||||
for _, iif := range fallbackInterfaces {
|
|
||||||
go startRacer(fallbackCtx, false, iif)
|
|
||||||
}
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
return res.Conn, res.primary, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, res.error)
|
|
||||||
if len(errors) == len(primaryInterfaces)+len(fallbackInterfaces) {
|
|
||||||
return nil, false, E.Errors(errors...)
|
|
||||||
}
|
|
||||||
if res.primary && fallbackTimer != nil && fallbackTimer.Stop() {
|
|
||||||
fallbackTimer.Reset(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DefaultDialer) dialParallelInterfaceFastFallback(ctx context.Context, dialer net.Dialer, network string, addr string, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration, resetFastFallback func(time.Time)) (net.Conn, bool, error) {
|
|
||||||
primaryInterfaces, fallbackInterfaces := selectInterfaces(d.networkManager, strategy, interfaceType, fallbackInterfaceType)
|
|
||||||
if len(primaryInterfaces)+len(fallbackInterfaces) == 0 {
|
|
||||||
return nil, false, E.New("no available network interface")
|
|
||||||
}
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = N.DefaultFallbackDelay
|
|
||||||
}
|
|
||||||
returned := make(chan struct{})
|
|
||||||
defer close(returned)
|
|
||||||
type dialResult struct {
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
primary bool
|
|
||||||
}
|
|
||||||
startAt := time.Now()
|
|
||||||
results := make(chan dialResult) // unbuffered
|
|
||||||
startRacer := func(ctx context.Context, primary bool, iif adapter.NetworkInterface) {
|
|
||||||
perNetDialer := dialer
|
|
||||||
perNetDialer.Control = control.Append(perNetDialer.Control, control.BindToInterface(nil, iif.Name, iif.Index))
|
|
||||||
conn, err := perNetDialer.DialContext(ctx, network, addr)
|
|
||||||
if err != nil {
|
|
||||||
select {
|
|
||||||
case results <- dialResult{error: E.Cause(err, "dial ", iif.Name, " (", iif.Index, ")"), primary: primary}:
|
|
||||||
case <-returned:
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
select {
|
|
||||||
case results <- dialResult{Conn: conn, primary: primary}:
|
|
||||||
case <-returned:
|
|
||||||
if primary && time.Since(startAt) <= fallbackDelay {
|
|
||||||
resetFastFallback(time.Time{})
|
|
||||||
}
|
|
||||||
conn.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for _, iif := range primaryInterfaces {
|
|
||||||
go startRacer(ctx, true, iif)
|
|
||||||
}
|
|
||||||
fallbackCtx, fallbackCancel := context.WithCancel(ctx)
|
|
||||||
defer fallbackCancel()
|
|
||||||
for _, iif := range fallbackInterfaces {
|
|
||||||
go startRacer(fallbackCtx, false, iif)
|
|
||||||
}
|
|
||||||
var errors []error
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
return res.Conn, res.primary, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, res.error)
|
|
||||||
if len(errors) == len(primaryInterfaces)+len(fallbackInterfaces) {
|
|
||||||
return nil, false, E.Errors(errors...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DefaultDialer) listenSerialInterfacePacket(ctx context.Context, listener net.ListenConfig, network string, addr string, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, error) {
|
|
||||||
primaryInterfaces, fallbackInterfaces := selectInterfaces(d.networkManager, strategy, interfaceType, fallbackInterfaceType)
|
|
||||||
if len(primaryInterfaces)+len(fallbackInterfaces) == 0 {
|
|
||||||
return nil, E.New("no available network interface")
|
|
||||||
}
|
|
||||||
var errors []error
|
|
||||||
for _, primaryInterface := range primaryInterfaces {
|
|
||||||
perNetListener := listener
|
|
||||||
perNetListener.Control = control.Append(perNetListener.Control, control.BindToInterface(nil, primaryInterface.Name, primaryInterface.Index))
|
|
||||||
conn, err := perNetListener.ListenPacket(ctx, network, addr)
|
|
||||||
if err == nil {
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, E.Cause(err, "listen ", primaryInterface.Name, " (", primaryInterface.Index, ")"))
|
|
||||||
}
|
|
||||||
for _, fallbackInterface := range fallbackInterfaces {
|
|
||||||
perNetListener := listener
|
|
||||||
perNetListener.Control = control.Append(perNetListener.Control, control.BindToInterface(nil, fallbackInterface.Name, fallbackInterface.Index))
|
|
||||||
conn, err := perNetListener.ListenPacket(ctx, network, addr)
|
|
||||||
if err == nil {
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, E.Cause(err, "listen ", fallbackInterface.Name, " (", fallbackInterface.Index, ")"))
|
|
||||||
}
|
|
||||||
return nil, E.Errors(errors...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func selectInterfaces(networkManager adapter.NetworkManager, strategy C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType) (primaryInterfaces []adapter.NetworkInterface, fallbackInterfaces []adapter.NetworkInterface) {
|
|
||||||
interfaces := networkManager.NetworkInterfaces()
|
|
||||||
switch strategy {
|
|
||||||
case C.NetworkStrategyDefault:
|
|
||||||
if len(interfaceType) == 0 {
|
|
||||||
defaultIf := networkManager.InterfaceMonitor().DefaultInterface()
|
|
||||||
if defaultIf != nil {
|
|
||||||
for _, iif := range interfaces {
|
|
||||||
if iif.Index == defaultIf.Index {
|
|
||||||
primaryInterfaces = append(primaryInterfaces, iif)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
primaryInterfaces = interfaces
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
primaryInterfaces = common.Filter(interfaces, func(it adapter.NetworkInterface) bool {
|
|
||||||
return common.Contains(interfaceType, it.Type)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
case C.NetworkStrategyHybrid:
|
|
||||||
if len(interfaceType) == 0 {
|
|
||||||
primaryInterfaces = interfaces
|
|
||||||
} else {
|
|
||||||
primaryInterfaces = common.Filter(interfaces, func(it adapter.NetworkInterface) bool {
|
|
||||||
return common.Contains(interfaceType, it.Type)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
case C.NetworkStrategyFallback:
|
|
||||||
if len(interfaceType) == 0 {
|
|
||||||
defaultIf := networkManager.InterfaceMonitor().DefaultInterface()
|
|
||||||
if defaultIf != nil {
|
|
||||||
for _, iif := range interfaces {
|
|
||||||
if iif.Index == defaultIf.Index {
|
|
||||||
primaryInterfaces = append(primaryInterfaces, iif)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
primaryInterfaces = interfaces
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
primaryInterfaces = common.Filter(interfaces, func(it adapter.NetworkInterface) bool {
|
|
||||||
return common.Contains(interfaceType, it.Type)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
if len(fallbackInterfaceType) == 0 {
|
|
||||||
fallbackInterfaces = common.Filter(interfaces, func(it adapter.NetworkInterface) bool {
|
|
||||||
return !common.Any(primaryInterfaces, func(iif adapter.NetworkInterface) bool {
|
|
||||||
return it.Index == iif.Index
|
|
||||||
})
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
fallbackInterfaces = common.Filter(interfaces, func(iif adapter.NetworkInterface) bool {
|
|
||||||
return common.Contains(fallbackInterfaceType, iif.Type)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return primaryInterfaces, fallbackInterfaces
|
|
||||||
}
|
|
||||||
@@ -1,161 +0,0 @@
|
|||||||
package dialer
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
func DialSerialNetwork(ctx context.Context, dialer N.Dialer, network string, destination M.Socksaddr, destinationAddresses []netip.Addr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
|
|
||||||
if len(destinationAddresses) == 0 {
|
|
||||||
if !destination.IsIP() {
|
|
||||||
panic("invalid usage")
|
|
||||||
}
|
|
||||||
destinationAddresses = []netip.Addr{destination.Addr}
|
|
||||||
}
|
|
||||||
if parallelDialer, isParallel := dialer.(ParallelNetworkDialer); isParallel {
|
|
||||||
return parallelDialer.DialParallelNetwork(ctx, network, destination, destinationAddresses, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
}
|
|
||||||
var errors []error
|
|
||||||
if parallelDialer, isParallel := dialer.(ParallelInterfaceDialer); isParallel {
|
|
||||||
for _, address := range destinationAddresses {
|
|
||||||
conn, err := parallelDialer.DialParallelInterface(ctx, network, M.SocksaddrFrom(address, destination.Port), strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
if err == nil {
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for _, address := range destinationAddresses {
|
|
||||||
conn, err := dialer.DialContext(ctx, network, M.SocksaddrFrom(address, destination.Port))
|
|
||||||
if err == nil {
|
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, E.Errors(errors...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func DialParallelNetwork(ctx context.Context, dialer ParallelInterfaceDialer, network string, destination M.Socksaddr, destinationAddresses []netip.Addr, preferIPv6 bool, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
|
|
||||||
if len(destinationAddresses) == 0 {
|
|
||||||
if !destination.IsIP() {
|
|
||||||
panic("invalid usage")
|
|
||||||
}
|
|
||||||
destinationAddresses = []netip.Addr{destination.Addr}
|
|
||||||
}
|
|
||||||
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = N.DefaultFallbackDelay
|
|
||||||
}
|
|
||||||
|
|
||||||
returned := make(chan struct{})
|
|
||||||
defer close(returned)
|
|
||||||
|
|
||||||
addresses4 := common.Filter(destinationAddresses, func(address netip.Addr) bool {
|
|
||||||
return address.Is4() || address.Is4In6()
|
|
||||||
})
|
|
||||||
addresses6 := common.Filter(destinationAddresses, func(address netip.Addr) bool {
|
|
||||||
return address.Is6() && !address.Is4In6()
|
|
||||||
})
|
|
||||||
if len(addresses4) == 0 || len(addresses6) == 0 {
|
|
||||||
return DialSerialNetwork(ctx, dialer, network, destination, destinationAddresses, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
}
|
|
||||||
var primaries, fallbacks []netip.Addr
|
|
||||||
if preferIPv6 {
|
|
||||||
primaries = addresses6
|
|
||||||
fallbacks = addresses4
|
|
||||||
} else {
|
|
||||||
primaries = addresses4
|
|
||||||
fallbacks = addresses6
|
|
||||||
}
|
|
||||||
type dialResult struct {
|
|
||||||
net.Conn
|
|
||||||
error
|
|
||||||
primary bool
|
|
||||||
done bool
|
|
||||||
}
|
|
||||||
results := make(chan dialResult) // unbuffered
|
|
||||||
startRacer := func(ctx context.Context, primary bool) {
|
|
||||||
ras := primaries
|
|
||||||
if !primary {
|
|
||||||
ras = fallbacks
|
|
||||||
}
|
|
||||||
c, err := DialSerialNetwork(ctx, dialer, network, destination, ras, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
select {
|
|
||||||
case results <- dialResult{Conn: c, error: err, primary: primary, done: true}:
|
|
||||||
case <-returned:
|
|
||||||
if c != nil {
|
|
||||||
c.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var primary, fallback dialResult
|
|
||||||
primaryCtx, primaryCancel := context.WithCancel(ctx)
|
|
||||||
defer primaryCancel()
|
|
||||||
go startRacer(primaryCtx, true)
|
|
||||||
fallbackTimer := time.NewTimer(fallbackDelay)
|
|
||||||
defer fallbackTimer.Stop()
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-fallbackTimer.C:
|
|
||||||
fallbackCtx, fallbackCancel := context.WithCancel(ctx)
|
|
||||||
defer fallbackCancel()
|
|
||||||
go startRacer(fallbackCtx, false)
|
|
||||||
|
|
||||||
case res := <-results:
|
|
||||||
if res.error == nil {
|
|
||||||
return res.Conn, nil
|
|
||||||
}
|
|
||||||
if res.primary {
|
|
||||||
primary = res
|
|
||||||
} else {
|
|
||||||
fallback = res
|
|
||||||
}
|
|
||||||
if primary.done && fallback.done {
|
|
||||||
return nil, primary.error
|
|
||||||
}
|
|
||||||
if res.primary && fallbackTimer.Stop() {
|
|
||||||
fallbackTimer.Reset(0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func ListenSerialNetworkPacket(ctx context.Context, dialer N.Dialer, destination M.Socksaddr, destinationAddresses []netip.Addr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, netip.Addr, error) {
|
|
||||||
if len(destinationAddresses) == 0 {
|
|
||||||
if !destination.IsIP() {
|
|
||||||
panic("invalid usage")
|
|
||||||
}
|
|
||||||
destinationAddresses = []netip.Addr{destination.Addr}
|
|
||||||
}
|
|
||||||
if parallelDialer, isParallel := dialer.(ParallelNetworkDialer); isParallel {
|
|
||||||
return parallelDialer.ListenSerialNetworkPacket(ctx, destination, destinationAddresses, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
}
|
|
||||||
var errors []error
|
|
||||||
if parallelDialer, isParallel := dialer.(ParallelInterfaceDialer); isParallel {
|
|
||||||
for _, address := range destinationAddresses {
|
|
||||||
conn, err := parallelDialer.ListenSerialInterfacePacket(ctx, M.SocksaddrFrom(address, destination.Port), strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
if err == nil {
|
|
||||||
return conn, address, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, err)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
for _, address := range destinationAddresses {
|
|
||||||
conn, err := dialer.ListenPacket(ctx, M.SocksaddrFrom(address, destination.Port))
|
|
||||||
if err == nil {
|
|
||||||
return conn, address, nil
|
|
||||||
}
|
|
||||||
errors = append(errors, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil, netip.Addr{}, E.Errors(errors...)
|
|
||||||
}
|
|
||||||
@@ -12,15 +12,15 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type DetourDialer struct {
|
type DetourDialer struct {
|
||||||
outboundManager adapter.OutboundManager
|
router adapter.Router
|
||||||
detour string
|
detour string
|
||||||
dialer N.Dialer
|
dialer N.Dialer
|
||||||
initOnce sync.Once
|
initOnce sync.Once
|
||||||
initErr error
|
initErr error
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDetour(outboundManager adapter.OutboundManager, detour string) N.Dialer {
|
func NewDetour(router adapter.Router, detour string) N.Dialer {
|
||||||
return &DetourDialer{outboundManager: outboundManager, detour: detour}
|
return &DetourDialer{router: router, detour: detour}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DetourDialer) Start() error {
|
func (d *DetourDialer) Start() error {
|
||||||
@@ -31,7 +31,7 @@ func (d *DetourDialer) Start() error {
|
|||||||
func (d *DetourDialer) Dialer() (N.Dialer, error) {
|
func (d *DetourDialer) Dialer() (N.Dialer, error) {
|
||||||
d.initOnce.Do(func() {
|
d.initOnce.Do(func() {
|
||||||
var loaded bool
|
var loaded bool
|
||||||
d.dialer, loaded = d.outboundManager.Outbound(d.detour)
|
d.dialer, loaded = d.router.Outbound(d.detour)
|
||||||
if !loaded {
|
if !loaded {
|
||||||
d.initErr = E.New("outbound detour not found: ", d.detour)
|
d.initErr = E.New("outbound detour not found: ", d.detour)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,103 +1,41 @@
|
|||||||
package dialer
|
package dialer
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/experimental/deprecated"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
"github.com/sagernet/sing-box/option"
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
"github.com/sagernet/sing-dns"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/sing/service"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func New(ctx context.Context, options option.DialerOptions, remoteIsDomain bool) (N.Dialer, error) {
|
func New(router adapter.Router, options option.DialerOptions) (N.Dialer, error) {
|
||||||
if options.IsWireGuardListener {
|
if options.IsWireGuardListener {
|
||||||
return NewDefault(ctx, options)
|
return NewDefault(router, options)
|
||||||
|
}
|
||||||
|
if router == nil {
|
||||||
|
return NewDefault(nil, options)
|
||||||
}
|
}
|
||||||
var (
|
var (
|
||||||
dialer N.Dialer
|
dialer N.Dialer
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
if options.Detour == "" {
|
if options.Detour == "" {
|
||||||
dialer, err = NewDefault(ctx, options)
|
dialer, err = NewDefault(router, options)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
outboundManager := service.FromContext[adapter.OutboundManager](ctx)
|
dialer = NewDetour(router, options.Detour)
|
||||||
if outboundManager == nil {
|
|
||||||
return nil, E.New("missing outbound manager")
|
|
||||||
}
|
|
||||||
dialer = NewDetour(outboundManager, options.Detour)
|
|
||||||
}
|
}
|
||||||
if remoteIsDomain && options.Detour == "" && options.DomainResolver == "" {
|
domainStrategy := dns.DomainStrategy(options.DomainStrategy)
|
||||||
deprecated.Report(ctx, deprecated.OptionMissingDomainResolverInDialOptions)
|
if domainStrategy != dns.DomainStrategyAsIS || options.Detour == "" {
|
||||||
}
|
dialer = NewResolveDialer(
|
||||||
if (options.Detour == "" && remoteIsDomain) || options.DomainResolver != "" {
|
router,
|
||||||
router := service.FromContext[adapter.DNSRouter](ctx)
|
dialer,
|
||||||
if router != nil {
|
options.Detour == "" && !options.TCPFastOpen,
|
||||||
var resolveTransport adapter.DNSTransport
|
domainStrategy,
|
||||||
if options.DomainResolver != "" {
|
time.Duration(options.FallbackDelay))
|
||||||
transport, loaded := service.FromContext[adapter.DNSTransportManager](ctx).Transport(options.DomainResolver)
|
|
||||||
if !loaded {
|
|
||||||
return nil, E.New("DNS server not found: " + options.DomainResolver)
|
|
||||||
}
|
|
||||||
resolveTransport = transport
|
|
||||||
}
|
|
||||||
dialer = NewResolveDialer(
|
|
||||||
router,
|
|
||||||
dialer,
|
|
||||||
options.Detour == "" && !options.TCPFastOpen,
|
|
||||||
resolveTransport,
|
|
||||||
C.DomainStrategy(options.DomainStrategy),
|
|
||||||
time.Duration(options.FallbackDelay))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return dialer, nil
|
return dialer, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDirect(ctx context.Context, options option.DialerOptions) (ParallelInterfaceDialer, error) {
|
|
||||||
if options.Detour != "" {
|
|
||||||
return nil, E.New("`detour` is not supported in direct context")
|
|
||||||
}
|
|
||||||
if options.IsWireGuardListener {
|
|
||||||
return NewDefault(ctx, options)
|
|
||||||
}
|
|
||||||
dialer, err := NewDefault(ctx, options)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var resolveTransport adapter.DNSTransport
|
|
||||||
if options.DomainResolver != "" {
|
|
||||||
transport, loaded := service.FromContext[adapter.DNSTransportManager](ctx).Transport(options.DomainResolver)
|
|
||||||
if !loaded {
|
|
||||||
return nil, E.New("DNS server not found: " + options.DomainResolver)
|
|
||||||
}
|
|
||||||
resolveTransport = transport
|
|
||||||
}
|
|
||||||
return NewResolveParallelInterfaceDialer(
|
|
||||||
service.FromContext[adapter.DNSRouter](ctx),
|
|
||||||
dialer,
|
|
||||||
true,
|
|
||||||
resolveTransport,
|
|
||||||
C.DomainStrategy(options.DomainStrategy),
|
|
||||||
time.Duration(options.FallbackDelay),
|
|
||||||
), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type ParallelInterfaceDialer interface {
|
|
||||||
N.Dialer
|
|
||||||
DialParallelInterface(ctx context.Context, network string, destination M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error)
|
|
||||||
ListenSerialInterfacePacket(ctx context.Context, destination M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
type ParallelNetworkDialer interface {
|
|
||||||
DialParallelNetwork(ctx context.Context, network string, destination M.Socksaddr, destinationAddresses []netip.Addr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error)
|
|
||||||
ListenSerialNetworkPacket(ctx context.Context, destination M.Socksaddr, destinationAddresses []netip.Addr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, netip.Addr, error)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,82 +3,75 @@ package dialer
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"net"
|
"net"
|
||||||
|
"net/netip"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
"github.com/sagernet/sing-box/log"
|
||||||
|
"github.com/sagernet/sing-dns"
|
||||||
"github.com/sagernet/sing/common/bufio"
|
"github.com/sagernet/sing/common/bufio"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
type ResolveDialer struct {
|
||||||
_ N.Dialer = (*resolveDialer)(nil)
|
|
||||||
_ ParallelInterfaceDialer = (*resolveParallelNetworkDialer)(nil)
|
|
||||||
)
|
|
||||||
|
|
||||||
type resolveDialer struct {
|
|
||||||
dialer N.Dialer
|
dialer N.Dialer
|
||||||
parallel bool
|
parallel bool
|
||||||
router adapter.DNSRouter
|
router adapter.Router
|
||||||
transport adapter.DNSTransport
|
strategy dns.DomainStrategy
|
||||||
strategy C.DomainStrategy
|
|
||||||
fallbackDelay time.Duration
|
fallbackDelay time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewResolveDialer(router adapter.DNSRouter, dialer N.Dialer, parallel bool, transport adapter.DNSTransport, strategy C.DomainStrategy, fallbackDelay time.Duration) N.Dialer {
|
func NewResolveDialer(router adapter.Router, dialer N.Dialer, parallel bool, strategy dns.DomainStrategy, fallbackDelay time.Duration) *ResolveDialer {
|
||||||
return &resolveDialer{
|
return &ResolveDialer{
|
||||||
dialer,
|
dialer,
|
||||||
parallel,
|
parallel,
|
||||||
router,
|
router,
|
||||||
transport,
|
|
||||||
strategy,
|
strategy,
|
||||||
fallbackDelay,
|
fallbackDelay,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type resolveParallelNetworkDialer struct {
|
func (d *ResolveDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
resolveDialer
|
|
||||||
dialer ParallelInterfaceDialer
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewResolveParallelInterfaceDialer(router adapter.DNSRouter, dialer ParallelInterfaceDialer, parallel bool, transport adapter.DNSTransport, strategy C.DomainStrategy, fallbackDelay time.Duration) ParallelInterfaceDialer {
|
|
||||||
return &resolveParallelNetworkDialer{
|
|
||||||
resolveDialer{
|
|
||||||
dialer,
|
|
||||||
parallel,
|
|
||||||
router,
|
|
||||||
transport,
|
|
||||||
strategy,
|
|
||||||
fallbackDelay,
|
|
||||||
},
|
|
||||||
dialer,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *resolveDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
|
||||||
if !destination.IsFqdn() {
|
if !destination.IsFqdn() {
|
||||||
return d.dialer.DialContext(ctx, network, destination)
|
return d.dialer.DialContext(ctx, network, destination)
|
||||||
}
|
}
|
||||||
|
ctx, metadata := adapter.ExtendContext(ctx)
|
||||||
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
||||||
addresses, err := d.router.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{Transport: d.transport, Strategy: d.strategy})
|
metadata.Destination = destination
|
||||||
|
metadata.Domain = ""
|
||||||
|
var addresses []netip.Addr
|
||||||
|
var err error
|
||||||
|
if d.strategy == dns.DomainStrategyAsIS {
|
||||||
|
addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
|
||||||
|
} else {
|
||||||
|
addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if d.parallel {
|
if d.parallel {
|
||||||
return N.DialParallel(ctx, d.dialer, network, destination, addresses, d.strategy == C.DomainStrategyPreferIPv6, d.fallbackDelay)
|
return N.DialParallel(ctx, d.dialer, network, destination, addresses, d.strategy == dns.DomainStrategyPreferIPv6, d.fallbackDelay)
|
||||||
} else {
|
} else {
|
||||||
return N.DialSerial(ctx, d.dialer, network, destination, addresses)
|
return N.DialSerial(ctx, d.dialer, network, destination, addresses)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *resolveDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
func (d *ResolveDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
if !destination.IsFqdn() {
|
if !destination.IsFqdn() {
|
||||||
return d.dialer.ListenPacket(ctx, destination)
|
return d.dialer.ListenPacket(ctx, destination)
|
||||||
}
|
}
|
||||||
|
ctx, metadata := adapter.ExtendContext(ctx)
|
||||||
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
||||||
addresses, err := d.router.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{Transport: d.transport, Strategy: d.strategy})
|
metadata.Destination = destination
|
||||||
|
metadata.Domain = ""
|
||||||
|
var addresses []netip.Addr
|
||||||
|
var err error
|
||||||
|
if d.strategy == dns.DomainStrategyAsIS {
|
||||||
|
addresses, err = d.router.LookupDefault(ctx, destination.Fqdn)
|
||||||
|
} else {
|
||||||
|
addresses, err = d.router.Lookup(ctx, destination.Fqdn, d.strategy)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -89,41 +82,6 @@ func (d *resolveDialer) ListenPacket(ctx context.Context, destination M.Socksadd
|
|||||||
return bufio.NewNATPacketConn(bufio.NewPacketConn(conn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
|
return bufio.NewNATPacketConn(bufio.NewPacketConn(conn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *resolveParallelNetworkDialer) DialParallelInterface(ctx context.Context, network string, destination M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.Conn, error) {
|
func (d *ResolveDialer) Upstream() any {
|
||||||
if !destination.IsFqdn() {
|
|
||||||
return d.dialer.DialContext(ctx, network, destination)
|
|
||||||
}
|
|
||||||
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
|
||||||
addresses, err := d.router.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{Transport: d.transport, Strategy: d.strategy})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if fallbackDelay == 0 {
|
|
||||||
fallbackDelay = d.fallbackDelay
|
|
||||||
}
|
|
||||||
if d.parallel {
|
|
||||||
return DialParallelNetwork(ctx, d.dialer, network, destination, addresses, d.strategy == C.DomainStrategyPreferIPv6, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
} else {
|
|
||||||
return DialSerialNetwork(ctx, d.dialer, network, destination, addresses, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *resolveParallelNetworkDialer) ListenSerialInterfacePacket(ctx context.Context, destination M.Socksaddr, strategy *C.NetworkStrategy, interfaceType []C.InterfaceType, fallbackInterfaceType []C.InterfaceType, fallbackDelay time.Duration) (net.PacketConn, error) {
|
|
||||||
if !destination.IsFqdn() {
|
|
||||||
return d.dialer.ListenPacket(ctx, destination)
|
|
||||||
}
|
|
||||||
ctx = log.ContextWithOverrideLevel(ctx, log.LevelDebug)
|
|
||||||
addresses, err := d.router.Lookup(ctx, destination.Fqdn, adapter.DNSQueryOptions{Transport: d.transport, Strategy: d.strategy})
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
conn, destinationAddress, err := ListenSerialNetworkPacket(ctx, d.dialer, destination, addresses, strategy, interfaceType, fallbackInterfaceType, fallbackDelay)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return bufio.NewNATPacketConn(bufio.NewPacketConn(conn), M.SocksaddrFrom(destinationAddress, destination.Port), destination), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *resolveDialer) Upstream() any {
|
|
||||||
return d.dialer
|
return d.dialer
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,27 +7,32 @@ import (
|
|||||||
"github.com/sagernet/sing-box/adapter"
|
"github.com/sagernet/sing-box/adapter"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
"github.com/sagernet/sing/service"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type DefaultOutboundDialer struct {
|
type RouterDialer struct {
|
||||||
outbound adapter.OutboundManager
|
router adapter.Router
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewDefaultOutbound(ctx context.Context) N.Dialer {
|
func NewRouter(router adapter.Router) N.Dialer {
|
||||||
return &DefaultOutboundDialer{
|
return &RouterDialer{router: router}
|
||||||
outbound: service.FromContext[adapter.OutboundManager](ctx),
|
}
|
||||||
|
|
||||||
|
func (d *RouterDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
||||||
|
dialer, err := d.router.DefaultOutbound(network)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
}
|
}
|
||||||
|
return dialer.DialContext(ctx, network, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DefaultOutboundDialer) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
|
func (d *RouterDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
||||||
return d.outbound.Default().DialContext(ctx, network, destination)
|
dialer, err := d.router.DefaultOutbound(N.NetworkUDP)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return dialer.ListenPacket(ctx, destination)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (d *DefaultOutboundDialer) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
|
func (d *RouterDialer) Upstream() any {
|
||||||
return d.outbound.Default().ListenPacket(ctx, destination)
|
return d.router
|
||||||
}
|
|
||||||
|
|
||||||
func (d *DefaultOutboundDialer) Upstream() any {
|
|
||||||
return d.outbound.Default()
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,8 +15,7 @@ import (
|
|||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
M "github.com/sagernet/sing/common/metadata"
|
||||||
N "github.com/sagernet/sing/common/network"
|
N "github.com/sagernet/sing/common/network"
|
||||||
|
"github.com/sagernet/tfo-go"
|
||||||
"github.com/metacubex/tfo-go"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type slowOpenConn struct {
|
type slowOpenConn struct {
|
||||||
|
|||||||
@@ -2,12 +2,8 @@ package dialer
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net"
|
"net"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/control"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type WireGuardListener interface {
|
type WireGuardListener interface {
|
||||||
ListenPacketCompat(network, address string) (net.PacketConn, error)
|
ListenPacketCompat(network, address string) (net.PacketConn, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
var WgControlFns []control.Func
|
|
||||||
|
|||||||
11
common/dialer/wireguard_control.go
Normal file
11
common/dialer/wireguard_control.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
//go:build with_wireguard
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/sagernet/wireguard-go/conn"
|
||||||
|
)
|
||||||
|
|
||||||
|
var _ WireGuardListener = (conn.Listener)(nil)
|
||||||
|
|
||||||
|
var wgControlFns = conn.ControlFns
|
||||||
9
common/dialer/wiregurad_stub.go
Normal file
9
common/dialer/wiregurad_stub.go
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
//go:build !with_wireguard
|
||||||
|
|
||||||
|
package dialer
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/sagernet/sing/common/control"
|
||||||
|
)
|
||||||
|
|
||||||
|
var wgControlFns []control.Func
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
package geosite_test
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/common/geosite"
|
|
||||||
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestGeosite(t *testing.T) {
|
|
||||||
t.Parallel()
|
|
||||||
|
|
||||||
var buffer bytes.Buffer
|
|
||||||
err := geosite.Write(&buffer, map[string][]geosite.Item{
|
|
||||||
"test": {
|
|
||||||
{
|
|
||||||
Type: geosite.RuleTypeDomain,
|
|
||||||
Value: "example.org",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
require.NoError(t, err)
|
|
||||||
reader, codes, err := geosite.NewReader(bytes.NewReader(buffer.Bytes()))
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, []string{"test"}, codes)
|
|
||||||
items, err := reader.Read("test")
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Equal(t, []geosite.Item{{
|
|
||||||
Type: geosite.RuleTypeDomain,
|
|
||||||
Value: "example.org",
|
|
||||||
}}, items)
|
|
||||||
}
|
|
||||||
@@ -1,24 +1,17 @@
|
|||||||
package geosite
|
package geosite
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"encoding/binary"
|
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
|
||||||
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
E "github.com/sagernet/sing/common/exceptions"
|
||||||
"github.com/sagernet/sing/common/varbin"
|
"github.com/sagernet/sing/common/rw"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Reader struct {
|
type Reader struct {
|
||||||
access sync.Mutex
|
reader io.ReadSeeker
|
||||||
reader io.ReadSeeker
|
domainIndex map[string]int
|
||||||
bufferedReader *bufio.Reader
|
domainLength map[string]int
|
||||||
metadataIndex int64
|
|
||||||
domainIndex map[string]int
|
|
||||||
domainLength map[string]int
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Open(path string) (*Reader, []string, error) {
|
func Open(path string) (*Reader, []string, error) {
|
||||||
@@ -26,22 +19,14 @@ func Open(path string) (*Reader, []string, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
reader, codes, err := NewReader(content)
|
reader := &Reader{
|
||||||
|
reader: content,
|
||||||
|
}
|
||||||
|
err = reader.readMetadata()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
content.Close()
|
content.Close()
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
return reader, codes, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func NewReader(readSeeker io.ReadSeeker) (*Reader, []string, error) {
|
|
||||||
reader := &Reader{
|
|
||||||
reader: readSeeker,
|
|
||||||
}
|
|
||||||
err := reader.readMetadata()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, err
|
|
||||||
}
|
|
||||||
codes := make([]string, 0, len(reader.domainIndex))
|
codes := make([]string, 0, len(reader.domainIndex))
|
||||||
for code := range reader.domainIndex {
|
for code := range reader.domainIndex {
|
||||||
codes = append(codes, code)
|
codes = append(codes, code)
|
||||||
@@ -49,23 +34,15 @@ func NewReader(readSeeker io.ReadSeeker) (*Reader, []string, error) {
|
|||||||
return reader, codes, nil
|
return reader, codes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type geositeMetadata struct {
|
|
||||||
Code string
|
|
||||||
Index uint64
|
|
||||||
Length uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *Reader) readMetadata() error {
|
func (r *Reader) readMetadata() error {
|
||||||
counter := &readCounter{Reader: r.reader}
|
version, err := rw.ReadByte(r.reader)
|
||||||
reader := bufio.NewReader(counter)
|
|
||||||
version, err := reader.ReadByte()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if version != 0 {
|
if version != 0 {
|
||||||
return E.New("unknown version")
|
return E.New("unknown version")
|
||||||
}
|
}
|
||||||
entryLength, err := binary.ReadUvarint(reader)
|
entryLength, err := rw.ReadUVariant(r.reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -78,16 +55,16 @@ func (r *Reader) readMetadata() error {
|
|||||||
codeIndex uint64
|
codeIndex uint64
|
||||||
codeLength uint64
|
codeLength uint64
|
||||||
)
|
)
|
||||||
code, err = varbin.ReadValue[string](reader, binary.BigEndian)
|
code, err = rw.ReadVString(r.reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
keys[i] = code
|
keys[i] = code
|
||||||
codeIndex, err = binary.ReadUvarint(reader)
|
codeIndex, err = rw.ReadUVariant(r.reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
codeLength, err = binary.ReadUvarint(reader)
|
codeLength, err = rw.ReadUVariant(r.reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -96,8 +73,6 @@ func (r *Reader) readMetadata() error {
|
|||||||
}
|
}
|
||||||
r.domainIndex = domainIndex
|
r.domainIndex = domainIndex
|
||||||
r.domainLength = domainLength
|
r.domainLength = domainLength
|
||||||
r.metadataIndex = counter.count - int64(reader.Buffered())
|
|
||||||
r.bufferedReader = reader
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -106,32 +81,31 @@ func (r *Reader) Read(code string) ([]Item, error) {
|
|||||||
if !exists {
|
if !exists {
|
||||||
return nil, E.New("code ", code, " not exists!")
|
return nil, E.New("code ", code, " not exists!")
|
||||||
}
|
}
|
||||||
_, err := r.reader.Seek(r.metadataIndex+int64(index), io.SeekStart)
|
_, err := r.reader.Seek(int64(index), io.SeekCurrent)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
r.bufferedReader.Reset(r.reader)
|
counter := &rw.ReadCounter{Reader: r.reader}
|
||||||
itemList := make([]Item, r.domainLength[code])
|
domain := make([]Item, r.domainLength[code])
|
||||||
err = varbin.Read(r.bufferedReader, binary.BigEndian, &itemList)
|
for i := range domain {
|
||||||
if err != nil {
|
var (
|
||||||
return nil, err
|
item Item
|
||||||
|
err error
|
||||||
|
)
|
||||||
|
item.Type, err = rw.ReadByte(counter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
item.Value, err = rw.ReadVString(counter)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
domain[i] = item
|
||||||
}
|
}
|
||||||
return itemList, nil
|
_, err = r.reader.Seek(int64(-index)-counter.Count(), io.SeekCurrent)
|
||||||
|
return domain, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *Reader) Upstream() any {
|
func (r *Reader) Upstream() any {
|
||||||
return r.reader
|
return r.reader
|
||||||
}
|
}
|
||||||
|
|
||||||
type readCounter struct {
|
|
||||||
io.Reader
|
|
||||||
count int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *readCounter) Read(p []byte) (n int, err error) {
|
|
||||||
n, err = r.Reader.Read(p)
|
|
||||||
if n > 0 {
|
|
||||||
atomic.AddInt64(&r.count, int64(n))
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,13 +2,13 @@ package geosite
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"encoding/binary"
|
"io"
|
||||||
"sort"
|
"sort"
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/varbin"
|
"github.com/sagernet/sing/common/rw"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Write(writer varbin.Writer, domains map[string][]Item) error {
|
func Write(writer io.Writer, domains map[string][]Item) error {
|
||||||
keys := make([]string, 0, len(domains))
|
keys := make([]string, 0, len(domains))
|
||||||
for code := range domains {
|
for code := range domains {
|
||||||
keys = append(keys, code)
|
keys = append(keys, code)
|
||||||
@@ -19,34 +19,35 @@ func Write(writer varbin.Writer, domains map[string][]Item) error {
|
|||||||
index := make(map[string]int)
|
index := make(map[string]int)
|
||||||
for _, code := range keys {
|
for _, code := range keys {
|
||||||
index[code] = content.Len()
|
index[code] = content.Len()
|
||||||
for _, item := range domains[code] {
|
for _, domain := range domains[code] {
|
||||||
err := varbin.Write(content, binary.BigEndian, item)
|
content.WriteByte(domain.Type)
|
||||||
|
err := rw.WriteVString(content, domain.Value)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err := writer.WriteByte(0)
|
err := rw.WriteByte(writer, 0)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = varbin.WriteUvarint(writer, uint64(len(keys)))
|
err = rw.WriteUVariant(writer, uint64(len(keys)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, code := range keys {
|
for _, code := range keys {
|
||||||
err = varbin.Write(writer, binary.BigEndian, code)
|
err = rw.WriteVString(writer, code)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = varbin.WriteUvarint(writer, uint64(index[code]))
|
err = rw.WriteUVariant(writer, uint64(index[code]))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = varbin.WriteUvarint(writer, uint64(len(domains[code])))
|
err = rw.WriteUVariant(writer, uint64(len(domains[code])))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
BSD 3-Clause License
|
|
||||||
|
|
||||||
Copyright (c) 2018, Open Systems AG
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright notice, this
|
|
||||||
list of conditions and the following disclaimer.
|
|
||||||
|
|
||||||
* Redistributions in binary form must reproduce the above copyright notice,
|
|
||||||
this list of conditions and the following disclaimer in the documentation
|
|
||||||
and/or other materials provided with the distribution.
|
|
||||||
|
|
||||||
* Neither the name of the copyright holder nor the names of its
|
|
||||||
contributors may be used to endorse or promote products derived from
|
|
||||||
this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
|
||||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
|
||||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
|
||||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
|
||||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
|
||||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
|
||||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
|
||||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
|
||||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
|
||||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
# JA3
|
|
||||||
|
|
||||||
mod from: https://github.com/open-ch/ja3
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
// Copyright (c) 2018, Open Systems AG. All rights reserved.
|
|
||||||
//
|
|
||||||
// Use of this source code is governed by a BSD-style license
|
|
||||||
// that can be found in the LICENSE file in the root of the source
|
|
||||||
// tree.
|
|
||||||
|
|
||||||
package ja3
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
// Error types
|
|
||||||
const (
|
|
||||||
LengthErr string = "length check %v failed"
|
|
||||||
ContentTypeErr string = "content type not matching"
|
|
||||||
VersionErr string = "version check %v failed"
|
|
||||||
HandshakeTypeErr string = "handshake type not matching"
|
|
||||||
SNITypeErr string = "SNI type not supported"
|
|
||||||
)
|
|
||||||
|
|
||||||
// ParseError can be encountered while parsing a segment
|
|
||||||
type ParseError struct {
|
|
||||||
errType string
|
|
||||||
check int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *ParseError) Error() string {
|
|
||||||
if e.errType == LengthErr || e.errType == VersionErr {
|
|
||||||
return fmt.Sprintf(e.errType, e.check)
|
|
||||||
}
|
|
||||||
return fmt.Sprint(e.errType)
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
// Copyright (c) 2018, Open Systems AG. All rights reserved.
|
|
||||||
//
|
|
||||||
// Use of this source code is governed by a BSD-style license
|
|
||||||
// that can be found in the LICENSE file in the root of the source
|
|
||||||
// tree.
|
|
||||||
|
|
||||||
package ja3
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/md5"
|
|
||||||
"encoding/hex"
|
|
||||||
|
|
||||||
"golang.org/x/exp/slices"
|
|
||||||
)
|
|
||||||
|
|
||||||
type ClientHello struct {
|
|
||||||
Version uint16
|
|
||||||
CipherSuites []uint16
|
|
||||||
Extensions []uint16
|
|
||||||
EllipticCurves []uint16
|
|
||||||
EllipticCurvePF []uint8
|
|
||||||
Versions []uint16
|
|
||||||
SignatureAlgorithms []uint16
|
|
||||||
ServerName string
|
|
||||||
ja3ByteString []byte
|
|
||||||
ja3Hash string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *ClientHello) Equals(another *ClientHello, ignoreExtensionsSequence bool) bool {
|
|
||||||
if j.Version != another.Version {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !slices.Equal(j.CipherSuites, another.CipherSuites) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !ignoreExtensionsSequence && !slices.Equal(j.Extensions, another.Extensions) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if ignoreExtensionsSequence && !slices.Equal(j.Extensions, another.sortedExtensions()) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !slices.Equal(j.EllipticCurves, another.EllipticCurves) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !slices.Equal(j.EllipticCurvePF, another.EllipticCurvePF) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if !slices.Equal(j.SignatureAlgorithms, another.SignatureAlgorithms) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *ClientHello) sortedExtensions() []uint16 {
|
|
||||||
extensions := make([]uint16, len(j.Extensions))
|
|
||||||
copy(extensions, j.Extensions)
|
|
||||||
slices.Sort(extensions)
|
|
||||||
return extensions
|
|
||||||
}
|
|
||||||
|
|
||||||
func Compute(payload []byte) (*ClientHello, error) {
|
|
||||||
ja3 := ClientHello{}
|
|
||||||
err := ja3.parseSegment(payload)
|
|
||||||
return &ja3, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *ClientHello) String() string {
|
|
||||||
if j.ja3ByteString == nil {
|
|
||||||
j.marshalJA3()
|
|
||||||
}
|
|
||||||
return string(j.ja3ByteString)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (j *ClientHello) Hash() string {
|
|
||||||
if j.ja3ByteString == nil {
|
|
||||||
j.marshalJA3()
|
|
||||||
}
|
|
||||||
if j.ja3Hash == "" {
|
|
||||||
h := md5.Sum(j.ja3ByteString)
|
|
||||||
j.ja3Hash = hex.EncodeToString(h[:])
|
|
||||||
}
|
|
||||||
return j.ja3Hash
|
|
||||||
}
|
|
||||||
@@ -1,357 +0,0 @@
|
|||||||
// Copyright (c) 2018, Open Systems AG. All rights reserved.
|
|
||||||
//
|
|
||||||
// Use of this source code is governed by a BSD-style license
|
|
||||||
// that can be found in the LICENSE file in the root of the source
|
|
||||||
// tree.
|
|
||||||
|
|
||||||
package ja3
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/binary"
|
|
||||||
"strconv"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// Constants used for parsing
|
|
||||||
recordLayerHeaderLen int = 5
|
|
||||||
handshakeHeaderLen int = 6
|
|
||||||
randomDataLen int = 32
|
|
||||||
sessionIDHeaderLen int = 1
|
|
||||||
cipherSuiteHeaderLen int = 2
|
|
||||||
compressMethodHeaderLen int = 1
|
|
||||||
extensionsHeaderLen int = 2
|
|
||||||
extensionHeaderLen int = 4
|
|
||||||
sniExtensionHeaderLen int = 5
|
|
||||||
ecExtensionHeaderLen int = 2
|
|
||||||
ecpfExtensionHeaderLen int = 1
|
|
||||||
versionExtensionHeaderLen int = 1
|
|
||||||
signatureAlgorithmsExtensionHeaderLen int = 2
|
|
||||||
contentType uint8 = 22
|
|
||||||
handshakeType uint8 = 1
|
|
||||||
sniExtensionType uint16 = 0
|
|
||||||
sniNameDNSHostnameType uint8 = 0
|
|
||||||
ecExtensionType uint16 = 10
|
|
||||||
ecpfExtensionType uint16 = 11
|
|
||||||
versionExtensionType uint16 = 43
|
|
||||||
signatureAlgorithmsExtensionType uint16 = 13
|
|
||||||
|
|
||||||
// Versions
|
|
||||||
// The bitmask covers the versions SSL3.0 to TLS1.2
|
|
||||||
tlsVersionBitmask uint16 = 0xFFFC
|
|
||||||
tls13 uint16 = 0x0304
|
|
||||||
|
|
||||||
// GREASE values
|
|
||||||
// The bitmask covers all GREASE values
|
|
||||||
GreaseBitmask uint16 = 0x0F0F
|
|
||||||
|
|
||||||
// Constants used for marshalling
|
|
||||||
dashByte = byte(45)
|
|
||||||
commaByte = byte(44)
|
|
||||||
)
|
|
||||||
|
|
||||||
// parseSegment to populate the corresponding ClientHello object or return an error
|
|
||||||
func (j *ClientHello) parseSegment(segment []byte) error {
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(segment) < recordLayerHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 1}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if we have "Content Type: Handshake (22)"
|
|
||||||
contType := uint8(segment[0])
|
|
||||||
if contType != contentType {
|
|
||||||
return &ParseError{errType: ContentTypeErr}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if TLS record layer version is supported
|
|
||||||
tlsRecordVersion := uint16(segment[1])<<8 | uint16(segment[2])
|
|
||||||
if tlsRecordVersion&tlsVersionBitmask != 0x0300 && tlsRecordVersion != tls13 {
|
|
||||||
return &ParseError{VersionErr, 1}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that the Handshake is as long as expected from the length field
|
|
||||||
segmentLen := uint16(segment[3])<<8 | uint16(segment[4])
|
|
||||||
if len(segment[recordLayerHeaderLen:]) < int(segmentLen) {
|
|
||||||
return &ParseError{LengthErr, 2}
|
|
||||||
}
|
|
||||||
// Keep the Handshake messege, ignore any additional following record types
|
|
||||||
hs := segment[recordLayerHeaderLen : recordLayerHeaderLen+int(segmentLen)]
|
|
||||||
|
|
||||||
err := j.parseHandshake(hs)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseHandshake body
|
|
||||||
func (j *ClientHello) parseHandshake(hs []byte) error {
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(hs) < handshakeHeaderLen+randomDataLen+sessionIDHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 3}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if we have "Handshake Type: Client Hello (1)"
|
|
||||||
handshType := uint8(hs[0])
|
|
||||||
if handshType != handshakeType {
|
|
||||||
return &ParseError{errType: HandshakeTypeErr}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if actual length of handshake matches (this is a great exclusion criterion for false positives,
|
|
||||||
// as these fields have to match the actual length of the rest of the segment)
|
|
||||||
handshakeLen := uint32(hs[1])<<16 | uint32(hs[2])<<8 | uint32(hs[3])
|
|
||||||
if len(hs[4:]) != int(handshakeLen) {
|
|
||||||
return &ParseError{LengthErr, 4}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if Client Hello version is supported
|
|
||||||
tlsVersion := uint16(hs[4])<<8 | uint16(hs[5])
|
|
||||||
if tlsVersion&tlsVersionBitmask != 0x0300 && tlsVersion != tls13 {
|
|
||||||
return &ParseError{VersionErr, 2}
|
|
||||||
}
|
|
||||||
j.Version = tlsVersion
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
sessionIDLen := uint8(hs[38])
|
|
||||||
if len(hs) < handshakeHeaderLen+randomDataLen+sessionIDHeaderLen+int(sessionIDLen) {
|
|
||||||
return &ParseError{LengthErr, 5}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cipher Suites
|
|
||||||
cs := hs[handshakeHeaderLen+randomDataLen+sessionIDHeaderLen+int(sessionIDLen):]
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(cs) < cipherSuiteHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 6}
|
|
||||||
}
|
|
||||||
|
|
||||||
csLen := uint16(cs[0])<<8 | uint16(cs[1])
|
|
||||||
numCiphers := int(csLen / 2)
|
|
||||||
cipherSuites := make([]uint16, 0, numCiphers)
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(cs) < cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 7}
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < numCiphers; i++ {
|
|
||||||
cipherSuite := uint16(cs[2+i<<1])<<8 | uint16(cs[3+i<<1])
|
|
||||||
cipherSuites = append(cipherSuites, cipherSuite)
|
|
||||||
}
|
|
||||||
j.CipherSuites = cipherSuites
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
compressMethodLen := uint16(cs[cipherSuiteHeaderLen+int(csLen)])
|
|
||||||
if len(cs) < cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen+int(compressMethodLen) {
|
|
||||||
return &ParseError{LengthErr, 8}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extensions
|
|
||||||
exs := cs[cipherSuiteHeaderLen+int(csLen)+compressMethodHeaderLen+int(compressMethodLen):]
|
|
||||||
|
|
||||||
err := j.parseExtensions(exs)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
// parseExtensions of the handshake
|
|
||||||
func (j *ClientHello) parseExtensions(exs []byte) error {
|
|
||||||
// Check for no extensions, this fields header is nonexistent if no body is used
|
|
||||||
if len(exs) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(exs) < extensionsHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 9}
|
|
||||||
}
|
|
||||||
|
|
||||||
exsLen := uint16(exs[0])<<8 | uint16(exs[1])
|
|
||||||
exs = exs[extensionsHeaderLen:]
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(exs) < int(exsLen) {
|
|
||||||
return &ParseError{LengthErr, 10}
|
|
||||||
}
|
|
||||||
|
|
||||||
var sni []byte
|
|
||||||
var extensions, ellipticCurves []uint16
|
|
||||||
var ellipticCurvePF []uint8
|
|
||||||
var versions []uint16
|
|
||||||
var signatureAlgorithms []uint16
|
|
||||||
for len(exs) > 0 {
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(exs) < extensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 11}
|
|
||||||
}
|
|
||||||
|
|
||||||
exType := uint16(exs[0])<<8 | uint16(exs[1])
|
|
||||||
exLen := uint16(exs[2])<<8 | uint16(exs[3])
|
|
||||||
// Ignore any GREASE extensions
|
|
||||||
extensions = append(extensions, exType)
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(exs) < extensionHeaderLen+int(exLen) {
|
|
||||||
return &ParseError{LengthErr, 12}
|
|
||||||
}
|
|
||||||
|
|
||||||
sex := exs[extensionHeaderLen : extensionHeaderLen+int(exLen)]
|
|
||||||
|
|
||||||
switch exType {
|
|
||||||
case sniExtensionType: // Extensions: server_name
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) < sniExtensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 13}
|
|
||||||
}
|
|
||||||
|
|
||||||
sniType := uint8(sex[2])
|
|
||||||
sniLen := uint16(sex[3])<<8 | uint16(sex[4])
|
|
||||||
sex = sex[sniExtensionHeaderLen:]
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) != int(sniLen) {
|
|
||||||
return &ParseError{LengthErr, 14}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch sniType {
|
|
||||||
case sniNameDNSHostnameType:
|
|
||||||
sni = sex
|
|
||||||
default:
|
|
||||||
return &ParseError{errType: SNITypeErr}
|
|
||||||
}
|
|
||||||
case ecExtensionType: // Extensions: supported_groups
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) < ecExtensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 15}
|
|
||||||
}
|
|
||||||
|
|
||||||
ecsLen := uint16(sex[0])<<8 | uint16(sex[1])
|
|
||||||
numCurves := int(ecsLen / 2)
|
|
||||||
ellipticCurves = make([]uint16, 0, numCurves)
|
|
||||||
sex = sex[ecExtensionHeaderLen:]
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) != int(ecsLen) {
|
|
||||||
return &ParseError{LengthErr, 16}
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < numCurves; i++ {
|
|
||||||
ecType := uint16(sex[i*2])<<8 | uint16(sex[1+i*2])
|
|
||||||
ellipticCurves = append(ellipticCurves, ecType)
|
|
||||||
}
|
|
||||||
|
|
||||||
case ecpfExtensionType: // Extensions: ec_point_formats
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) < ecpfExtensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 17}
|
|
||||||
}
|
|
||||||
|
|
||||||
ecpfsLen := uint8(sex[0])
|
|
||||||
numPF := int(ecpfsLen)
|
|
||||||
ellipticCurvePF = make([]uint8, numPF)
|
|
||||||
sex = sex[ecpfExtensionHeaderLen:]
|
|
||||||
|
|
||||||
// Check if we can decode the next fields
|
|
||||||
if len(sex) != numPF {
|
|
||||||
return &ParseError{LengthErr, 18}
|
|
||||||
}
|
|
||||||
|
|
||||||
for i := 0; i < numPF; i++ {
|
|
||||||
ellipticCurvePF[i] = uint8(sex[i])
|
|
||||||
}
|
|
||||||
case versionExtensionType:
|
|
||||||
if len(sex) < versionExtensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 19}
|
|
||||||
}
|
|
||||||
versionsLen := int(sex[0])
|
|
||||||
for i := 0; i < versionsLen; i += 2 {
|
|
||||||
versions = append(versions, binary.BigEndian.Uint16(sex[1:][i:]))
|
|
||||||
}
|
|
||||||
case signatureAlgorithmsExtensionType:
|
|
||||||
if len(sex) < signatureAlgorithmsExtensionHeaderLen {
|
|
||||||
return &ParseError{LengthErr, 20}
|
|
||||||
}
|
|
||||||
ssaLen := binary.BigEndian.Uint16(sex)
|
|
||||||
for i := 0; i < int(ssaLen); i += 2 {
|
|
||||||
signatureAlgorithms = append(signatureAlgorithms, binary.BigEndian.Uint16(sex[2:][i:]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
exs = exs[4+exLen:]
|
|
||||||
}
|
|
||||||
j.ServerName = string(sni)
|
|
||||||
j.Extensions = extensions
|
|
||||||
j.EllipticCurves = ellipticCurves
|
|
||||||
j.EllipticCurvePF = ellipticCurvePF
|
|
||||||
j.Versions = versions
|
|
||||||
j.SignatureAlgorithms = signatureAlgorithms
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// marshalJA3 into a byte string
|
|
||||||
func (j *ClientHello) marshalJA3() {
|
|
||||||
// An uint16 can contain numbers with up to 5 digits and an uint8 can contain numbers with up to 3 digits, but we
|
|
||||||
// also need a byte for each separating character, except at the end.
|
|
||||||
byteStringLen := 6*(1+len(j.CipherSuites)+len(j.Extensions)+len(j.EllipticCurves)) + 4*len(j.EllipticCurvePF) - 1
|
|
||||||
byteString := make([]byte, 0, byteStringLen)
|
|
||||||
|
|
||||||
// Version
|
|
||||||
byteString = strconv.AppendUint(byteString, uint64(j.Version), 10)
|
|
||||||
byteString = append(byteString, commaByte)
|
|
||||||
|
|
||||||
// Cipher Suites
|
|
||||||
if len(j.CipherSuites) != 0 {
|
|
||||||
for _, val := range j.CipherSuites {
|
|
||||||
if val&GreaseBitmask != 0x0A0A {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
byteString = strconv.AppendUint(byteString, uint64(val), 10)
|
|
||||||
byteString = append(byteString, dashByte)
|
|
||||||
}
|
|
||||||
// Replace last dash with a comma
|
|
||||||
byteString[len(byteString)-1] = commaByte
|
|
||||||
} else {
|
|
||||||
byteString = append(byteString, commaByte)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Extensions
|
|
||||||
if len(j.Extensions) != 0 {
|
|
||||||
for _, val := range j.Extensions {
|
|
||||||
if val&GreaseBitmask != 0x0A0A {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
byteString = strconv.AppendUint(byteString, uint64(val), 10)
|
|
||||||
byteString = append(byteString, dashByte)
|
|
||||||
}
|
|
||||||
// Replace last dash with a comma
|
|
||||||
byteString[len(byteString)-1] = commaByte
|
|
||||||
} else {
|
|
||||||
byteString = append(byteString, commaByte)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Elliptic curves
|
|
||||||
if len(j.EllipticCurves) != 0 {
|
|
||||||
for _, val := range j.EllipticCurves {
|
|
||||||
if val&GreaseBitmask != 0x0A0A {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
byteString = strconv.AppendUint(byteString, uint64(val), 10)
|
|
||||||
byteString = append(byteString, dashByte)
|
|
||||||
}
|
|
||||||
// Replace last dash with a comma
|
|
||||||
byteString[len(byteString)-1] = commaByte
|
|
||||||
} else {
|
|
||||||
byteString = append(byteString, commaByte)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ECPF
|
|
||||||
if len(j.EllipticCurvePF) != 0 {
|
|
||||||
for _, val := range j.EllipticCurvePF {
|
|
||||||
byteString = strconv.AppendUint(byteString, uint64(val), 10)
|
|
||||||
byteString = append(byteString, dashByte)
|
|
||||||
}
|
|
||||||
// Remove last dash
|
|
||||||
byteString = byteString[:len(byteString)-1]
|
|
||||||
}
|
|
||||||
|
|
||||||
j.ja3ByteString = byteString
|
|
||||||
}
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
package listener
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"sync/atomic"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
"github.com/sagernet/sing-box/common/settings"
|
|
||||||
"github.com/sagernet/sing-box/option"
|
|
||||||
"github.com/sagernet/sing/common"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
"github.com/sagernet/sing/common/logger"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Listener struct {
|
|
||||||
ctx context.Context
|
|
||||||
logger logger.ContextLogger
|
|
||||||
network []string
|
|
||||||
listenOptions option.ListenOptions
|
|
||||||
connHandler adapter.ConnectionHandlerEx
|
|
||||||
packetHandler adapter.PacketHandlerEx
|
|
||||||
oobPacketHandler adapter.OOBPacketHandlerEx
|
|
||||||
threadUnsafePacketWriter bool
|
|
||||||
disablePacketOutput bool
|
|
||||||
setSystemProxy bool
|
|
||||||
systemProxySOCKS bool
|
|
||||||
|
|
||||||
tcpListener net.Listener
|
|
||||||
systemProxy settings.SystemProxy
|
|
||||||
udpConn *net.UDPConn
|
|
||||||
udpAddr M.Socksaddr
|
|
||||||
packetOutbound chan *N.PacketBuffer
|
|
||||||
packetOutboundClosed chan struct{}
|
|
||||||
shutdown atomic.Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type Options struct {
|
|
||||||
Context context.Context
|
|
||||||
Logger logger.ContextLogger
|
|
||||||
Network []string
|
|
||||||
Listen option.ListenOptions
|
|
||||||
ConnectionHandler adapter.ConnectionHandlerEx
|
|
||||||
PacketHandler adapter.PacketHandlerEx
|
|
||||||
OOBPacketHandler adapter.OOBPacketHandlerEx
|
|
||||||
ThreadUnsafePacketWriter bool
|
|
||||||
DisablePacketOutput bool
|
|
||||||
SetSystemProxy bool
|
|
||||||
SystemProxySOCKS bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func New(
|
|
||||||
options Options,
|
|
||||||
) *Listener {
|
|
||||||
return &Listener{
|
|
||||||
ctx: options.Context,
|
|
||||||
logger: options.Logger,
|
|
||||||
network: options.Network,
|
|
||||||
listenOptions: options.Listen,
|
|
||||||
connHandler: options.ConnectionHandler,
|
|
||||||
packetHandler: options.PacketHandler,
|
|
||||||
oobPacketHandler: options.OOBPacketHandler,
|
|
||||||
threadUnsafePacketWriter: options.ThreadUnsafePacketWriter,
|
|
||||||
disablePacketOutput: options.DisablePacketOutput,
|
|
||||||
setSystemProxy: options.SetSystemProxy,
|
|
||||||
systemProxySOCKS: options.SystemProxySOCKS,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) Start() error {
|
|
||||||
if common.Contains(l.network, N.NetworkTCP) {
|
|
||||||
_, err := l.ListenTCP()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
go l.loopTCPIn()
|
|
||||||
}
|
|
||||||
if common.Contains(l.network, N.NetworkUDP) {
|
|
||||||
_, err := l.ListenUDP()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
l.packetOutboundClosed = make(chan struct{})
|
|
||||||
l.packetOutbound = make(chan *N.PacketBuffer, 64)
|
|
||||||
go l.loopUDPIn()
|
|
||||||
if !l.disablePacketOutput {
|
|
||||||
go l.loopUDPOut()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if l.setSystemProxy {
|
|
||||||
listenPort := M.SocksaddrFromNet(l.tcpListener.Addr()).Port
|
|
||||||
var listenAddrString string
|
|
||||||
listenAddr := l.listenOptions.Listen.Build(netip.IPv4Unspecified())
|
|
||||||
if listenAddr.IsUnspecified() {
|
|
||||||
listenAddrString = "127.0.0.1"
|
|
||||||
} else {
|
|
||||||
listenAddrString = listenAddr.String()
|
|
||||||
}
|
|
||||||
systemProxy, err := settings.NewSystemProxy(l.ctx, M.ParseSocksaddrHostPort(listenAddrString, listenPort), l.systemProxySOCKS)
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "initialize system proxy")
|
|
||||||
}
|
|
||||||
err = systemProxy.Enable()
|
|
||||||
if err != nil {
|
|
||||||
return E.Cause(err, "set system proxy")
|
|
||||||
}
|
|
||||||
l.systemProxy = systemProxy
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) Close() error {
|
|
||||||
l.shutdown.Store(true)
|
|
||||||
var err error
|
|
||||||
if l.systemProxy != nil && l.systemProxy.IsEnabled() {
|
|
||||||
err = l.systemProxy.Disable()
|
|
||||||
}
|
|
||||||
return E.Errors(err, common.Close(
|
|
||||||
l.tcpListener,
|
|
||||||
common.PtrOrNil(l.udpConn),
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) TCPListener() net.Listener {
|
|
||||||
return l.tcpListener
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) UDPConn() *net.UDPConn {
|
|
||||||
return l.udpConn
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) ListenOptions() option.ListenOptions {
|
|
||||||
return l.listenOptions
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
//go:build go1.23
|
|
||||||
|
|
||||||
package listener
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setKeepAliveConfig(listener *net.ListenConfig, idle time.Duration, interval time.Duration) {
|
|
||||||
listener.KeepAliveConfig = net.KeepAliveConfig{
|
|
||||||
Enable: true,
|
|
||||||
Idle: idle,
|
|
||||||
Interval: interval,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
//go:build !go1.23
|
|
||||||
|
|
||||||
package listener
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing/common/control"
|
|
||||||
)
|
|
||||||
|
|
||||||
func setKeepAliveConfig(listener *net.ListenConfig, idle time.Duration, interval time.Duration) {
|
|
||||||
listener.KeepAlive = idle
|
|
||||||
listener.Control = control.Append(listener.Control, control.SetKeepAlivePeriod(idle, interval))
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
package listener
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/sagernet/sing-box/adapter"
|
|
||||||
C "github.com/sagernet/sing-box/constant"
|
|
||||||
"github.com/sagernet/sing-box/log"
|
|
||||||
E "github.com/sagernet/sing/common/exceptions"
|
|
||||||
M "github.com/sagernet/sing/common/metadata"
|
|
||||||
N "github.com/sagernet/sing/common/network"
|
|
||||||
|
|
||||||
"github.com/metacubex/tfo-go"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (l *Listener) ListenTCP() (net.Listener, error) {
|
|
||||||
var err error
|
|
||||||
bindAddr := M.SocksaddrFrom(l.listenOptions.Listen.Build(netip.AddrFrom4([4]byte{127, 0, 0, 1})), l.listenOptions.ListenPort)
|
|
||||||
var tcpListener net.Listener
|
|
||||||
var listenConfig net.ListenConfig
|
|
||||||
if l.listenOptions.TCPKeepAlive >= 0 {
|
|
||||||
keepIdle := time.Duration(l.listenOptions.TCPKeepAlive)
|
|
||||||
if keepIdle == 0 {
|
|
||||||
keepIdle = C.TCPKeepAliveInitial
|
|
||||||
}
|
|
||||||
keepInterval := time.Duration(l.listenOptions.TCPKeepAliveInterval)
|
|
||||||
if keepInterval == 0 {
|
|
||||||
keepInterval = C.TCPKeepAliveInterval
|
|
||||||
}
|
|
||||||
setKeepAliveConfig(&listenConfig, keepIdle, keepInterval)
|
|
||||||
}
|
|
||||||
if l.listenOptions.TCPMultiPath {
|
|
||||||
if !go121Available {
|
|
||||||
return nil, E.New("MultiPath TCP requires go1.21, please recompile your binary.")
|
|
||||||
}
|
|
||||||
setMultiPathTCP(&listenConfig)
|
|
||||||
}
|
|
||||||
if l.listenOptions.TCPFastOpen {
|
|
||||||
var tfoConfig tfo.ListenConfig
|
|
||||||
tfoConfig.ListenConfig = listenConfig
|
|
||||||
tcpListener, err = tfoConfig.Listen(l.ctx, M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.String())
|
|
||||||
} else {
|
|
||||||
tcpListener, err = listenConfig.Listen(l.ctx, M.NetworkFromNetAddr(N.NetworkTCP, bindAddr.Addr), bindAddr.String())
|
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
l.logger.Info("tcp server started at ", tcpListener.Addr())
|
|
||||||
}
|
|
||||||
//nolint:staticcheck
|
|
||||||
if l.listenOptions.ProxyProtocol || l.listenOptions.ProxyProtocolAcceptNoHeader {
|
|
||||||
return nil, E.New("Proxy Protocol is deprecated and removed in sing-box 1.6.0")
|
|
||||||
}
|
|
||||||
l.tcpListener = tcpListener
|
|
||||||
return tcpListener, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (l *Listener) loopTCPIn() {
|
|
||||||
tcpListener := l.tcpListener
|
|
||||||
var metadata adapter.InboundContext
|
|
||||||
for {
|
|
||||||
conn, err := tcpListener.Accept()
|
|
||||||
if err != nil {
|
|
||||||
//nolint:staticcheck
|
|
||||||
if netError, isNetError := err.(net.Error); isNetError && netError.Temporary() {
|
|
||||||
l.logger.Error(err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if l.shutdown.Load() && E.IsClosed(err) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
l.tcpListener.Close()
|
|
||||||
l.logger.Error("tcp listener closed: ", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
//nolint:staticcheck
|
|
||||||
metadata.InboundDetour = l.listenOptions.Detour
|
|
||||||
//nolint:staticcheck
|
|
||||||
metadata.InboundOptions = l.listenOptions.InboundOptions
|
|
||||||
metadata.Source = M.SocksaddrFromNet(conn.RemoteAddr()).Unwrap()
|
|
||||||
metadata.OriginDestination = M.SocksaddrFromNet(conn.LocalAddr()).Unwrap()
|
|
||||||
ctx := log.ContextWithNewID(l.ctx)
|
|
||||||
l.logger.InfoContext(ctx, "inbound connection from ", metadata.Source)
|
|
||||||
go l.connHandler.NewConnectionEx(ctx, conn, metadata, nil)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user