commit 942d0fff43c1c1e3b6ec1b990ab03e889feb5aee Author: samosvalishe Date: Tue Nov 25 11:38:20 2025 +0000 feat: initial commit diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..c913016 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,153 @@ +name: CI + +permissions: + contents: read + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + check: + name: Lint, fmt-check, and tests + runs-on: ubuntu-latest + steps: + - name: Check out code + uses: actions/checkout@v6 + + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version: 'stable' + + - name: Cache Go modules + uses: actions/cache@v5 + with: + path: | + ~/.cache/go-build + # Module cache + ${{ github.workspace }}/pkg/mod + key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }} + restore-keys: | + ${{ runner.os }}-go- + + - name: Run gofmt (check) + run: | + echo "Checking formatting with gofmt..." + fmt_output=$(gofmt -l . || true) + if [ -n "$fmt_output" ]; then + echo "The following files need formatting:" + echo "$fmt_output" + echo "Run 'gofmt -w .' to fix." + exit 1 + fi + + - name: Run golangci-lint + uses: golangci/golangci-lint-action@v9 + with: + version: latest + args: --timeout=5m ./... + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Run tests + run: | + go test ./... -v + + build: + name: Build binaries + runs-on: ubuntu-latest + strategy: + matrix: + include: + - goos: linux + goarch: amd64 + cgo: 0 + - goos: darwin + goarch: arm64 + cgo: 0 + - goos: android + goarch: arm64 + cgo: 1 + api: 21 + - goos: android + goarch: arm + cgo: 1 + api: 21 + # you can add more (android/arm, windows, etc.) later + + steps: + - name: Check out code + uses: actions/checkout@v6 + with: + fetch-tags: true + + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version: 'stable' + + # Install Android NDK for android rows and expose ndk-path output + - name: Setup Android NDK + if: matrix.goos == 'android' + id: setup-ndk + uses: nttld/setup-ndk@v1 + with: + ndk-version: r26d + add-to-path: false + + - name: Build + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + CGO_ENABLED: ${{ matrix.cgo }} + ANDROID_API: ${{ matrix.api }} + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} + run: | + echo "Building for $GOOS/$GOARCH (CGO_ENABLED=$CGO_ENABLED)" + + # If this is an Android build, point CC at the NDK toolchain clang + if [ "$GOOS" = "android" ]; then + if [ -z "$ANDROID_NDK_HOME" ]; then + echo "ANDROID_NDK_HOME is not set – did setup-ndk run?" + exit 1 + fi + + TOOLCHAIN_BIN="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin" + + if [ "$GOARCH" = "arm64" ]; then + export CC="$TOOLCHAIN_BIN/aarch64-linux-android${ANDROID_API}-clang" + elif [ "$GOARCH" = "arm" ]; then + export CC="$TOOLCHAIN_BIN/armv7a-linux-androideabi${ANDROID_API}-clang" + else + echo "Unsupported ANDROID GOARCH=$GOARCH" + exit 1 + fi + + echo "Using Android NDK CC=$CC" + fi + + mkdir -p dist + + ext="" + if [ "$GOOS" = "windows" ]; then + ext=".exe" + fi + + GOOS=$GOOS GOARCH=$GOARCH \ + go build -ldflags "-s -w -checklinkname=0" -trimpath \ + -o "dist/client-${GOOS}-${GOARCH}${ext}" \ + ./client + + GOOS=$GOOS GOARCH=$GOARCH \ + go build -ldflags "-s -w -checklinkname=0" -trimpath \ + -o "dist/server-${GOOS}-${GOARCH}${ext}" \ + ./server + + - name: Upload artifact + uses: actions/upload-artifact@v6 + with: + name: good-turn-${{ matrix.goos }}-${{ matrix.goarch }} + path: dist/** diff --git a/.github/workflows/issues.yml b/.github/workflows/issues.yml new file mode 100644 index 0000000..2eee1c7 --- /dev/null +++ b/.github/workflows/issues.yml @@ -0,0 +1,28 @@ +name: "Close Stale Issues" +on: + schedule: + - cron: "0 0 * * 3" + workflow_dispatch: + +jobs: + stale: + permissions: + issues: write + runs-on: ubuntu-latest + steps: + - uses: actions/stale@997185467fa4f803885201cee163a9f38240193d # v10 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: > + Привет! 👋 +

+ Данный issue давно не обновлялся. Если в течение недели здесь не будет больше активности, issue будет закрыт. +

+ Спасибо! + close-issue-message: "Issue был закрыт из-за отсутствия активности." + days-before-stale: 120 + days-before-close: 7 + operations-per-run: 1000 + ascending: true + enable-statistics: true + stale-issue-label: "Stale" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..3013fe9 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,337 @@ +name: Release + +permissions: + contents: read + +on: + push: + branches: + - main + workflow_dispatch: + +jobs: + build: + name: Build binaries + runs-on: ubuntu-latest + strategy: + matrix: + include: + - goos: linux + goarch: amd64 + cgo: 0 + - goos: linux + goarch: arm64 + cgo: 0 + - goos: linux + goarch: 386 + cgo: 0 + - goos: linux + goarch: arm + goarm: "7" + cgo: 0 + - goos: linux + goarch: mipsle + gomips: softfloat + cgo: 0 + - goos: linux + goarch: mips + gomips: softfloat + cgo: 0 + - goos: linux + goarch: mips64le + gomips: softfloat + cgo: 0 + - goos: linux + goarch: riscv64 + cgo: 0 + - goos: darwin + goarch: amd64 + cgo: 0 + - goos: darwin + goarch: arm64 + cgo: 0 + - goos: windows + goarch: amd64 + cgo: 0 + - goos: windows + goarch: arm64 + cgo: 0 + - goos: windows + goarch: 386 + cgo: 0 + - goos: android + goarch: arm64 + cgo: 1 + api: 21 + - goos: android + goarch: arm + cgo: 1 + api: 21 + - goos: freebsd + goarch: amd64 + cgo: 0 + + steps: + - name: Check out code + uses: actions/checkout@v6 + + - name: Set up Go + uses: actions/setup-go@v6 + with: + go-version: "1.25.5" + + # Install Android NDK only for android rows + - name: Setup Android NDK + if: matrix.goos == 'android' + id: setup-ndk + uses: nttld/setup-ndk@v1 + with: + ndk-version: r26d + add-to-path: false + + - name: Build + env: + GOOS: ${{ matrix.goos }} + GOARCH: ${{ matrix.goarch }} + GOMIPS: ${{ matrix.gomips }} + GOARM: ${{ matrix.goarm }} + CGO_ENABLED: ${{ matrix.cgo }} + ANDROID_API: ${{ matrix.api }} + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} + VERSION: ${{ github.ref_name }} + run: | + echo "Building for $GOOS/$GOARCH${GOARM:+/arm$GOARM} (CGO_ENABLED=$CGO_ENABLED)" + + if [ "$GOOS" = "android" ]; then + if [ -z "$ANDROID_NDK_HOME" ]; then + echo "ANDROID_NDK_HOME is not set – did setup-ndk run?" + exit 1 + fi + + TOOLCHAIN_BIN="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin" + + if [ "$GOARCH" = "arm64" ]; then + export CC="$TOOLCHAIN_BIN/aarch64-linux-android${ANDROID_API}-clang" + elif [ "$GOARCH" = "arm" ]; then + export CC="$TOOLCHAIN_BIN/armv7a-linux-androideabi${ANDROID_API}-clang" + else + echo "Unsupported ANDROID GOARCH=$GOARCH" + exit 1 + fi + + echo "Using Android NDK CC=$CC" + fi + + mkdir -p dist + + # Set extension for windows + if [ "${GOOS}" = "windows" ]; then + EXT=.exe + else + EXT= + fi + + GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM GOMIPS=$GOMIPS \ + go build -ldflags "-s -w -checklinkname=0" -trimpath \ + -o "dist/client-${GOOS}-${GOARCH}${EXT}" \ + ./client + + GOOS=$GOOS GOARCH=$GOARCH GOARM=$GOARM GOMIPS=$GOMIPS \ + go build -ldflags "-s -w -checklinkname=0" -trimpath \ + -o "dist/server-${GOOS}-${GOARCH}${EXT}" \ + ./server + + - name: Upload artifact + uses: actions/upload-artifact@v6 + with: + name: good-turn-${{ matrix.goos }}-${{ matrix.goarch }} + path: dist/** + + release: + name: Create GitHub Release + needs: build + runs-on: ubuntu-latest + outputs: + should_release: ${{ steps.meta.outputs.should_release }} + tag_name: ${{ steps.meta.outputs.tag_name }} + permissions: + contents: write + steps: + - name: Check out code + uses: actions/checkout@v6 + with: + fetch-depth: 0 + fetch-tags: true + + - name: Download build artifacts + uses: actions/download-artifact@v7 + with: + path: dist + + - name: Prepare release metadata + id: meta + run: | + LATEST_TAG="$(git tag -l | grep -E '^(v)?[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1 || true)" + PREFIX="" + BASE_VERSION="$LATEST_TAG" + + if [ -z "$LATEST_TAG" ]; then + BASE_VERSION="0.0.0" + elif [ "${LATEST_TAG#v}" != "$LATEST_TAG" ]; then + PREFIX="v" + BASE_VERSION="${LATEST_TAG#v}" + fi + + IFS=. read -r MAJOR MINOR PATCH <<< "$BASE_VERSION" + + if [ -n "$LATEST_TAG" ]; then + RANGE="$LATEST_TAG..HEAD" + else + RANGE="HEAD" + fi + + COMMITS="$(git log --no-merges --format='%s' "$RANGE")" + BUMP="" + + if printf '%s\n' "$COMMITS" | grep -Eiq '^break([(:! ]|$)'; then + BUMP="major" + MAJOR=$((MAJOR + 1)) + MINOR=0 + PATCH=0 + elif printf '%s\n' "$COMMITS" | grep -Eiq '^feat([(:! ]|$)'; then + BUMP="minor" + MINOR=$((MINOR + 1)) + PATCH=0 + elif printf '%s\n' "$COMMITS" | grep -Eiq '^fix([(:! ]|$)'; then + BUMP="patch" + PATCH=$((PATCH + 1)) + fi + + NEXT_VERSION="${MAJOR}.${MINOR}.${PATCH}" + NEXT_TAG="${PREFIX}${NEXT_VERSION}" + + { + echo "previous_tag=$LATEST_TAG" + echo "range=$RANGE" + echo "bump=$BUMP" + echo "should_release=$([ -n "$BUMP" ] && echo true || echo false)" + echo "tag_name=$NEXT_TAG" + echo "release_name=$NEXT_TAG" + echo "body_path=release-notes.md" + } >> "$GITHUB_OUTPUT" + + - name: Generate release notes from commit messages + id: notes + if: steps.meta.outputs.should_release == 'true' + env: + PREVIOUS_TAG: ${{ steps.meta.outputs.previous_tag }} + NEXT_TAG: ${{ steps.meta.outputs.tag_name }} + BUMP: ${{ steps.meta.outputs.bump }} + RANGE: ${{ steps.meta.outputs.range }} + run: | + strip_prefix() { + sed -E 's/^(feat|fix|break)([(!:]|[[:space:]])+[[:space:]]*//I' + } + + FEATURES="$(git log --no-merges --format='%s (%h)' "$RANGE" | grep -Ei '^feat([(:! ]|$)' | strip_prefix | LC_ALL=C sort -f || true)" + FIXES="$(git log --no-merges --format='%s (%h)' "$RANGE" | grep -Ei '^fix([(:! ]|$)' | strip_prefix | LC_ALL=C sort -f || true)" + BREAKING="$(git log --no-merges --format='%s (%h)' "$RANGE" | grep -Ei '^break([(:! ]|$)' | strip_prefix | LC_ALL=C sort -f || true)" + + { + echo "body_path=release-notes.md" + } >> "$GITHUB_OUTPUT" + + { + if [ -n "$BREAKING" ]; then + echo "### Breaking Changes" + echo + printf '%s\n' "$BREAKING" | sed 's/^/- /' + echo + fi + + if [ -n "$FEATURES" ]; then + echo "### Features" + echo + printf '%s\n' "$FEATURES" | sed 's/^/- /' + echo + fi + + if [ -n "$FIXES" ]; then + echo "### Bug Fixes" + echo + printf '%s\n' "$FIXES" | sed 's/^/- /' + echo + fi + } > release-notes.md + + - name: Create Release + if: steps.meta.outputs.should_release == 'true' + uses: softprops/action-gh-release@v2 + with: + # upload every file in dist/ including nested files + files: | + dist/** + tag_name: ${{ steps.meta.outputs.tag_name }} + target_commitish: ${{ github.sha }} + name: ${{ steps.meta.outputs.release_name }} + body_path: ${{ steps.meta.outputs.body_path }} + overwrite_files: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Skip release when no semantic commit is found + if: steps.meta.outputs.should_release != 'true' + run: | + echo "No new semantic release created." + echo "Add a commit starting with break, feat, or fix after the latest tag." + + docker: + name: Publish Docker image + needs: release + if: needs.release.outputs.should_release == 'true' + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + steps: + - name: Check out code + uses: actions/checkout@v6 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v4 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v4 + + - name: Prepare image name + id: image + env: + REPOSITORY: ${{ github.repository }} + run: | + echo "name=ghcr.io/$(echo "$REPOSITORY" | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT" + + - name: Log in to GitHub Container Registry + uses: docker/login-action@v4 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Extract Docker metadata + id: meta + uses: docker/metadata-action@v6 + with: + images: ${{ steps.image.outputs.name }} + tags: | + type=raw,value=latest + type=raw,value=${{ needs.release.outputs.tag_name }} + + - name: Build and push Docker image + uses: docker/build-push-action@v7 + with: + context: . + file: ./Dockerfile + platforms: linux/amd64,linux/arm64 + push: true + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..ddbe2fb --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,65 @@ +version: "2" +run: + tests: true +linters: + enable: + - bodyclose + - misspell + - revive + settings: + errcheck: + check-type-assertions: true + check-blank: true + exclude-functions: + - (net.PacketConn).WriteTo + - (net.Conn).Write + - encoding/json.MarshalIndent + - (*github.com/pion/dtls/v3.Conn).SetDeadline + govet: + disable: + - fieldalignment + enable-all: true + revive: + rules: + - name: blank-imports + - name: dot-imports + - name: error-return + - name: error-strings + - name: error-naming + - name: exported + - name: if-return + - name: increment-decrement + - name: var-naming + - name: var-declaration + - name: package-comments + - name: range + - name: receiver-naming + - name: time-naming + - name: unexported-return + - name: indent-error-flow + - name: errorf + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling + paths: + - third_party$ + - builtin$ + - examples$ + rules: + - linters: + - errcheck + source: "doRequest|packetPool\\.Get" +issues: + max-issues-per-linter: 0 + max-same-issues: 0 +formatters: + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..9ba25b1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM golang:1.25-alpine AS builder + +WORKDIR /build + +COPY . . +RUN CGO_ENABLED=0 go build -ldflags="-s -w" -o vk-turn-proxy ./server + +FROM alpine:3.23 + +RUN apk add --no-cache ca-certificates tzdata + +WORKDIR /app + +COPY docker-entrypoint.sh . +COPY --from=builder /build/vk-turn-proxy . +RUN sed -i 's/\r$//' docker-entrypoint.sh && chmod +x docker-entrypoint.sh + +EXPOSE 56000/tcp +EXPOSE 56000/udp + +ENTRYPOINT ["./docker-entrypoint.sh"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..853aea6 --- /dev/null +++ b/README.md @@ -0,0 +1,417 @@ +# VK TURN Proxy + +VK TURN Proxy - клиент и сервер для прокидывания локального UDP/TCP-трафика через TURN-реле, получаемые из ссылки на VK Calls. Типичный сценарий - поднять небольшой `server` на VPS рядом с WireGuard или Xray, а на клиентском устройстве запустить `client`, который слушает локальный адрес вроде `127.0.0.1:9000`. + +> [!CAUTION] +> Проект предназначен для обучения, исследований и администрирования собственных стендов. Используйте его только там, где у вас есть право запускать такой трафик и менять сетевую конфигурацию. + +## Содержание + +- [Как это работает](#как-это-работает) +- [Возможности](#возможности) +- [Что нужно](#что-нужно) +- [Быстрый старт: WireGuard](#быстрый-старт-wireguard) + - [Запуск сервера на VPS](#1-запустите-сервер-на-vps) + - [Настройка WireGuard](#2-настройте-wireguard-на-клиенте) + - [Запуск клиента](#3-запустите-клиент) +- [Android через Termux](#android-через-termux) +- [iOS через iSH](#ios-через-ish) +- [systemd-сервис](#сервер-как-systemd-сервис) +- [Docker](#docker) +- [VLESS / Xray](#vless--xray) +- [WRAP-режим](#wrap-режим) +- [Яндекс Телемост](#яндекс-телемост) +- [Флаги клиента](#флаги-клиента) +- [Флаги сервера](#флаги-сервера) +- [Captcha](#captcha) +- [Сборка из исходников](#сборка-из-исходников) +- [Решение проблем](#решение-проблем) +- [Похожие проекты](#похожие-проекты) +- [Лицензия](#лицензия) + +## Как Это Работает + +Схема для WireGuard: + +```text +WireGuard client -> 127.0.0.1:9000 -> VK TURN Proxy client + -> VK TURN relay -> VK TURN Proxy server на VPS + -> 127.0.0.1:<порт WireGuard> -> WireGuard server +``` + +Клиент берет временные TURN-учетные данные из ссылки VK Calls, открывает одно или несколько соединений к TURN-реле и отправляет через них трафик к вашему `server`. Между `client` и `server` используется DTLS. Для WireGuard сервер пересылает данные в UDP backend, для VLESS/Xray - в TCP backend через KCP и smux. + +## Возможности + +- VK Calls как основной источник TURN-учетных данных. +- TCP или UDP подключение клиента к TURN-реле. +- Несколько параллельных TURN-потоков через `-n`. +- WireGuard/Hysteria-подобный UDP backend. +- VLESS/Xray TCP backend через `-vless`. +- Bonding для VLESS через `-vless-bond`. +- Дополнительная WRAP-обфускация DTLS-пакетов через `-wrap`. +- Автоматическое и ручное прохождение VK captcha. +- Docker-образ для серверной части. + +## Что Нужно + +- VPS с публичным IP. +- На VPS уже должен слушать backend: + - WireGuard: обычно `127.0.0.1:51820/udp`; + - Xray/VLESS: обычно `127.0.0.1:443/tcp`. +- Ссылка на активный VK Calls вида `https://vk.com/call/join/...`. +- На клиенте: WireGuard, Xray или другой локальный клиент, который будет ходить в `127.0.0.1:9000`. + +Ссылку VK Calls лучше создать самостоятельно. Не завершайте звонок для всех, если хотите использовать эту ссылку дальше. + +## Быстрый Старт: WireGuard + +### 1. Запустите Сервер На VPS + +Скачайте бинарник для Linux amd64: + +```bash +curl -L -o server https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/server-linux-amd64 +chmod +x server +``` + +Запустите `server`, указав локальный адрес WireGuard: + +```bash +./server -listen 0.0.0.0:56000 -connect 127.0.0.1:51820 +``` + +Порт `56000/udp` должен быть доступен снаружи. Если WireGuard слушает другой порт, замените `51820`. + +### 2. Настройте WireGuard На Клиенте + +В клиентском конфиге WireGuard замените endpoint сервера на локальный адрес VK TURN Proxy: + +```ini +Endpoint = 127.0.0.1:9000 +MTU = 1280 +``` + +На Android добавьте Termux или приложение-клиент в исключения WireGuard. На Windows, Linux и macOS перед включением WireGuard нужно добавить маршрут до TURN-реле, иначе клиент может попытаться подключаться к TURN уже через сам VPN. + +### 3. Запустите Клиент + +Linux: + +```bash +curl -L -o client https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/client-linux-amd64 +chmod +x client +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" | ./routes.sh +``` + +Windows PowerShell от администратора: + +```powershell +Invoke-WebRequest -Uri https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/client-windows-amd64.exe -OutFile client.exe +.\client.exe -listen 127.0.0.1:9000 -peer :56000 -vk-link "" | .\routes.ps1 +``` + +macOS: + +```bash +curl -L -o client https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/client-darwin-arm64 +chmod +x client +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" | ./routes-macos.sh +``` + +После появления соединения включите WireGuard. + +Если вы скачали только бинарник, но не клонировали репозиторий, возьмите нужный route-скрипт из этого репозитория: `routes.sh`, `routes.ps1` или `routes-macos.sh`. + +## Android Через Termux + +1. Установите Termux из F-Droid. +2. В WireGuard укажите `Endpoint = 127.0.0.1:9000` и `MTU = 1280`. +3. Добавьте Termux в исключения WireGuard. +4. Запустите в Termux: + +```bash +termux-wake-lock +curl -L -o client https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/client-android-arm64 +chmod +x client +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" +``` + +Чтобы снять wake lock: + +```bash +termux-wake-unlock +``` + +## iOS Через iSH + +Это запасной вариант, если нет нативного клиента. + +```bash +apk update +apk add curl +curl -L -o client https://github.com/cacggghp/vk-turn-proxy/releases/latest/download/client-linux-386 +chmod +x client +GOMAXPROCS=1 GODEBUG=asyncpreemptoff=1 ./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" +``` + +Чтобы iSH дольше жил в фоне, можно в начале сессии выполнить: + +```bash +cat /dev/location > /dev/null & +``` + +## Сервер Как systemd-Сервис + +Пример `/etc/systemd/system/vk-turn-proxy.service`: + +```ini +[Unit] +Description=VK TURN Proxy server +After=network.target + +[Service] +Type=simple +ExecStart=/opt/vk-turn-proxy/server -listen 0.0.0.0:56000 -connect 127.0.0.1:51820 +Restart=always +RestartSec=5 +User=nobody +Group=nogroup + +[Install] +WantedBy=multi-user.target +``` + +Применить: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now vk-turn-proxy.service +sudo systemctl status vk-turn-proxy.service +``` + +## Docker + +Образ публикуется в GitHub Container Registry: + +```bash +docker pull ghcr.io/cacggghp/vk-turn-proxy:latest +``` + +Если backend слушает на хосте, удобнее использовать host network: + +```bash +docker run --rm --network host \ + -e CONNECT_ADDR=127.0.0.1:51820 \ + ghcr.io/cacggghp/vk-turn-proxy:latest +``` + +Bridge mode: + +```bash +docker run --rm -p 56000:56000/udp \ + -e CONNECT_ADDR=:51820 \ + ghcr.io/cacggghp/vk-turn-proxy:latest +``` + +Переменные окружения: + +| Переменная | По умолчанию | Описание | +| --- | --- | --- | +| `CONNECT_ADDR` | обязательна | backend, куда сервер пересылает трафик | +| `LISTEN_ADDR` | `0.0.0.0:56000` | адрес прослушивания сервера | +| `VLESS_MODE` | `false` | включает `-vless` | +| `VLESS_BOND` | `false` | включает `-vless-bond` | +| `WRAP_MODE` | `false` | включает `-wrap` | +| `WRAP_KEY` | пусто | ключ для `-wrap-key` | +| `VK_TURN_KCP_PROFILE` | `balanced` | профиль KCP (`fast`, `balanced`, `slow`) | +| `VK_TURN_KCP_MTU` | `1200` | переопределить MTU для KCP | + +Сборка образа вручную: + +```bash +docker build -t vk-turn-proxy . +``` + +## VLESS / Xray + +В режиме `-vless` VK TURN Proxy прокидывает TCP-соединения. На VPS `server` подключается к локальному TCP backend, например к Xray inbound на `127.0.0.1:443`. На клиенте `client` слушает локальный TCP адрес, на который должен смотреть ваш Xray/v2rayN/sing-box клиент. + +Сервер: + +```bash +./server -listen 0.0.0.0:56000 -connect 127.0.0.1:443 -vless +``` + +Клиент: + +```bash +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" -vless +``` + +С bonding: + +```bash +./server -listen 0.0.0.0:56000 -connect 127.0.0.1:443 -vless -vless-bond +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" -vless -vless-bond -n 4 +``` + +## WRAP-Режим + +`-wrap` дополнительно оборачивает DTLS-пакеты ChaCha20-XOR перед отправкой в TURN ChannelData. Ключ должен совпадать на клиенте и сервере. + +Сгенерировать ключ: + +```bash +./server -gen-wrap-key +``` + +Запуск: + +```bash +./server -listen 0.0.0.0:56000 -connect 127.0.0.1:51820 -wrap -wrap-key <64-hex-key> +./client -listen 127.0.0.1:9000 -peer :56000 -vk-link "" -wrap -wrap-key <64-hex-key> +``` + +`-wrap` нельзя использовать вместе с `-no-dtls`. + +## Настройка KCP (VLESS) + +В режиме `-vless` для передачи данных поверх DTLS используется KCP. Его можно настроить через переменные окружения (работает и для клиента, и для сервера): + +| Переменная | Профили / Значения | Описание | +| --- | --- | --- | +| `VK_TURN_KCP_PROFILE` | `fast`, `balanced`, `slow` | Предустановленные режимы работы KCP. | +| `VK_TURN_KCP_MTU` | например, `1200` | Максимальный размер пакета. | + +**Профили:** +- `fast` (или `legacy`): Минимальные задержки, активная переотправка, MTU 1280. +- `balanced` (или `cc`): Оптимальный баланс для большинства сетей, MTU 1200. +- `slow` (или `conservative`): Для очень нестабильных каналов, MTU 1150. + +Для более тонкой настройки доступны переменные: `VK_TURN_KCP_NODELAY`, `VK_TURN_KCP_INTERVAL`, `VK_TURN_KCP_RESEND`, `VK_TURN_KCP_NC`, `VK_TURN_KCP_SNDWND`, `VK_TURN_KCP_RCVWND`, `VK_TURN_KCP_ACK_NODELAY`. + + +## Яндекс Телемост + +Поддержка `-yandex-link` оставлена в коде, но этот режим считается нестабильным и может не работать. Если используете его, обычно нужен `-udp` и ручной TURN IP: + +```bash +./client -udp -turn 5.255.211.241 -listen 127.0.0.1:9000 -peer :56000 -yandex-link "" +``` + +## Флаги Клиента + +| Флаг | По умолчанию | Описание | +| --- | --- | --- | +| `-listen` | `127.0.0.1:9000` | локальный адрес для WireGuard или Xray клиента | +| `-peer` | обязательный | адрес VK TURN Proxy server на VPS, например `:56000` | +| `-vk-link` | пусто | ссылка VK Calls | +| `-yandex-link` | пусто | ссылка Яндекс Телемоста, legacy-режим | +| `-n` | VK: `10`, Yandex: `1` | количество TURN-соединений | +| `-udp` | `false` | подключаться к TURN-реле по UDP вместо TCP | +| `-turn` | из ссылки | переопределить IP TURN-сервера | +| `-port` | из ссылки | переопределить порт TURN-сервера | +| `-vless` | `false` | TCP/VLESS режим | +| `-vless-bond` | `false` | распределять одно TCP-соединение по активным smux-сессиям | +| `-wrap` | `false` | включить WRAP-обфускацию | +| `-wrap-key` | пусто | 32-байтный ключ в hex, 64 символа | +| `-gen-wrap-key` | `false` | напечатать новый WRAP-ключ и выйти | +| `-manual-captcha` | `false` | сразу использовать ручное прохождение captcha | +| `-captcha-solver` | `v2` | авто-решатель captcha: `v1` или `v2` | +| `-streams-per-cred` | `10` | сколько потоков используют один кеш TURN-учетных данных | +| `-debug` | `false` | подробные логи | +| `-no-dtls` | `false` | прямой режим без DTLS, не рекомендуется | + +Нужно указать ровно одну ссылку: `-vk-link` или `-yandex-link`. + +## Флаги Сервера + +| Флаг | По умолчанию | Описание | +| --- | --- | --- | +| `-listen` | `0.0.0.0:56000` | адрес прослушивания | +| `-connect` | обязательный | backend-адрес, например `127.0.0.1:51820` или `127.0.0.1:443` | +| `-vless` | `false` | TCP/VLESS режим | +| `-vless-bond` | `false` | bonding для VLESS | +| `-wrap` | `false` | включить WRAP-обфускацию | +| `-wrap-key` | пусто | 32-байтный ключ в hex, 64 символа | +| `-gen-wrap-key` | `false` | напечатать новый WRAP-ключ и выйти | +| `-debug` | `false` | подробные логи | + +## Captcha + +Для VK Calls клиент умеет автоматически проходить captcha. Если автоматика не сработала, включается ручной сценарий через локальный браузер. Можно сразу запросить ручной режим: + +```bash +./client -manual-captcha -listen 127.0.0.1:9000 -peer :56000 -vk-link "" +``` + +Профиль браузера сохраняется в `vk_profile.json` рядом с бинарником и может помочь последующим запросам выглядеть последовательнее. + +## Сборка Из Исходников + +Нужен Go 1.25.x. + +```bash +go build -o client ./client +go build -o server ./server +go test ./... +``` + +Кросс-сборка примера для Linux amd64: + +```bash +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o server-linux-amd64 ./server +GOOS=linux GOARCH=amd64 CGO_ENABLED=0 go build -trimpath -ldflags "-s -w" -o client-linux-amd64 ./client +``` + +## Решение Проблем + +- Сначала запускайте VK TURN Proxy client, потом включайте WireGuard. +- Если WireGuard забирает весь трафик, добавьте маршрут до IP TURN-реле через `routes.sh`, `routes.ps1` или `routes-macos.sh`. +- Если TCP до TURN не работает, попробуйте `-udp`. +- Если соединение нестабильное, попробуйте уменьшить `-n`, например `-n 1`. +- Если VK просит captcha слишком часто, попробуйте `-manual-captcha`, затем повторите обычный запуск. +- Если клиент зависает на получении TURN-данных, проверьте, что ссылка VK Calls живая и не была завершена для всех. +- Если сервер запущен в Docker bridge mode, `CONNECT_ADDR=127.0.0.1:51820` укажет внутрь контейнера, а не на хост. Используйте host network или IP хоста. +- Если включен `-wrap`, убедитесь, что и клиент, и сервер используют одинаковый `-wrap-key`. + +## Похожие Проекты + +Авторы этого репозитория не отвечают за работу сторонних проектов. + +Server: + +- https://github.com/Urtyom-Alyanov/turn-proxy - реализация на Rust. +- https://github.com/jaykaiperson/lionheart - похожий подход для `stream.wb.ru`. +- https://github.com/kulikov0/whitelist-bypass - проброс через медиасерверы. +- https://github.com/NedgNDG/vk-proxy-auto-installer - автоустановщик VK TURN Proxy. + +Android: + +- https://github.com/samosvalishe/turn-proxy-android +- https://github.com/MYSOREZ/vk-turn-proxy-android +- https://github.com/kiper292/wireguard-turn-android +- https://github.com/WINGS-N/WINGSV +- https://github.com/oxsidee/vkpn +- https://github.com/amurcanov/proxy-turn-vk-android + +iOS: + +- https://github.com/nullcstring/turnbridge + +macOS: + +- https://github.com/denny4-user/vk-turn-proxy-macos-gui + +## Лицензия + +GPL-3.0. См. [LICENSE](LICENSE). + + + + + + Star History Chart + + diff --git a/client/captcha_v2.go b/client/captcha_v2.go new file mode 100644 index 0000000..1a3b925 --- /dev/null +++ b/client/captcha_v2.go @@ -0,0 +1,575 @@ +package main + +import ( + "bytes" + "context" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + mathrand "math/rand" + "regexp" + "strconv" + "strings" + "sync" + "time" + + fhttp "github.com/bogdanfinn/fhttp" + tlsclient "github.com/bogdanfinn/tls-client" +) + +const ( + captchaV2APIVersion = "5.131" + captchaV2ScriptVersion = "1.1.1324" + captchaV2DeviceInfo = `{"screenWidth":1920,"screenHeight":1080,"screenAvailWidth":1920,"screenAvailHeight":1080,"innerWidth":1920,"innerHeight":951,"devicePixelRatio":1,"language":"en-US","languages":["en-US","en"],"webdriver":false,"hardwareConcurrency":8,"notificationsPermission":"denied"}` +) + +var ( + reCaptchaV2PowInput = regexp.MustCompile(`const\s+powInput\s*=\s*"([^"]+)"`) + reCaptchaV2Difficulty = regexp.MustCompile(`const\s+difficulty\s*=\s*(\d+)`) + reCaptchaV2WindowInit = regexp.MustCompile(`(?s)window\.init\s*=\s*(\{.*?})\s*;`) + reCaptchaV2ScriptSrc = regexp.MustCompile(`src="(https://[^"]+not_robot_captcha[^"]+)"`) + reCaptchaV2DebugInfo = regexp.MustCompile(`debug_info:(?:[^"]*\|\|)?"([a-fA-F0-9]{64})"`) + reCaptchaV2Version = regexp.MustCompile(`vkid/([0-9.]*)/not_robot_captcha\.js`) + + errCaptchaV2RateLimit = errors.New("captcha session rate limit reached") + errCaptchaV2Bot = errors.New("captcha bot challenge") + + captchaV2MaxAttempts = 2 + + captchaV2DebugCache sync.Map // scriptURL -> string + captchaV2HeaderOrder = []string{ + "host", + "content-length", + "sec-ch-ua-platform", + "accept-language", + "sec-ch-ua", + "content-type", + "sec-ch-ua-mobile", + "user-agent", + "accept", + "origin", + "sec-fetch-site", + "sec-fetch-mode", + "sec-fetch-dest", + "referer", + "accept-encoding", + "priority", + } + captchaV2PHeaderOrder = []string{":method", ":path", ":authority", ":scheme"} +) + +type captchaV2Init struct { + Data captchaV2InitData `json:"data"` +} + +type captchaV2InitData struct { + ShowCaptchaType string `json:"show_captcha_type"` + CaptchaSettings []captchaV2InitSetting `json:"captcha_settings"` +} + +type captchaV2InitSetting struct { + Type string `json:"type"` + Settings string `json:"settings"` +} + +type captchaV2Page struct { + PowInput string + PowDifficulty int + ScriptURL string + Init *captchaV2Init +} + +type captchaV2Check struct { + Status string + SuccessToken string + ShowType string +} + +type captchaV2ShowTypeError struct { + ShowType string +} + +func (e *captchaV2ShowTypeError) Error() string { + return "captcha show type mismatch: " + e.ShowType +} + +type captchaV2Session struct { + ctx context.Context + client tlsclient.HttpClient + profile Profile + savedProfile *SavedProfile +} + +func solveVkCaptchaV2( + ctx context.Context, + captchaErr *VkCaptchaError, + streamID int, + client tlsclient.HttpClient, + profile Profile, + savedProfile *SavedProfile, +) (string, error) { + if captchaErr == nil || captchaErr.SessionToken == "" { + return "", fmt.Errorf("no session_token in redirect_uri") + } + log.Printf("[STREAM %d] [Captcha] Solving VK Smart Captcha automatically (v2)...", streamID) + + s := &captchaV2Session{ctx: ctx, client: client, profile: profile, savedProfile: savedProfile} + + for attempt := 1; attempt <= captchaV2MaxAttempts; attempt++ { + token, solveErr := s.solveOnce(captchaErr) + if solveErr == nil { + return token, nil + } + log.Printf("[STREAM %d] [Captcha] v2 captcha solve attempt %d failed: %v", streamID, attempt, solveErr) + if errors.Is(solveErr, errCaptchaV2RateLimit) { + return "", solveErr + } + + backoffSteps := attempt + if backoffSteps > 10 { + backoffSteps = 10 + } + timer := time.NewTimer(time.Duration(backoffSteps) * 500 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return "", ctx.Err() + case <-timer.C: + } + } + return "", fmt.Errorf("v2 captcha attempts exhausted") +} + +func (s *captchaV2Session) solveOnce(captchaErr *VkCaptchaError) (string, error) { + html, err := s.fetchCaptchaHTML(captchaErr.RedirectURI) + if err != nil { + return "", err + } + + page, err := parseCaptchaV2Page(html) + if err != nil { + return "", err + } + if page.PowInput == "" { + return "", errors.New("failed to find PoW settings") + } + + sliderSettings := "" + if page.Init != nil { + for _, setting := range page.Init.Data.CaptchaSettings { + if setting.Type == "slider" { + sliderSettings = setting.Settings + } + } + } + if page.Init != nil && page.Init.Data.ShowCaptchaType == "slider" && sliderSettings == "" { + return "", errors.New("failed to find slider captcha settings") + } + + log.Printf("v2 captcha solving pow difficulty=%d", page.PowDifficulty) + hash := solveCaptchaPoWV2(s.ctx, page.PowInput, page.PowDifficulty) + if hash == "" { + return "", errors.New("captcha pow failed") + } + log.Printf("v2 captcha pow solved") + + base := captchaV2BaseValues(captchaErr.SessionToken) + if _, settingsErr := s.captchaRequest("captchaNotRobot.settings", base); settingsErr != nil { + return "", fmt.Errorf("captcha settings failed: %w", settingsErr) + } + + browserFP, err := captchaV2BrowserFP() + if err != nil { + return "", err + } + if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.BrowserFp) != "" { + browserFP = s.savedProfile.BrowserFp + } + + if m := reCaptchaV2Version.FindStringSubmatch(page.ScriptURL); len(m) > 1 { + if m[1] != captchaV2ScriptVersion { + log.Printf("v2 captcha script version drift: known=%s latest=%s", captchaV2ScriptVersion, m[1]) + } + } + + debugInfo, err := s.fetchDebugInfo(page.ScriptURL) + if err != nil { + return "", fmt.Errorf("failed to fetch debug info: %w (script_version=%s)", err, captchaV2ScriptVersion) + } + + showType := "" + if page.Init != nil { + showType = page.Init.Data.ShowCaptchaType + } + var token string + for { + log.Printf("v2 captcha solving show_type=%s", showType) + switch showType { + case "slider": + token, err = s.solveSliderCaptcha(captchaErr.SessionToken, browserFP, hash, sliderSettings, debugInfo) + case "checkbox", "": + token, err = s.solveCheckboxCaptcha(captchaErr.SessionToken, browserFP, hash, debugInfo) + default: + return "", fmt.Errorf("unsupported captcha type: %s", showType) + } + if err == nil { + break + } + if errors.Is(err, errCaptchaV2Bot) && !strings.EqualFold(showType, "slider") && sliderSettings != "" { + log.Printf("v2 captcha checkbox returned BOT, trying slider challenge from page settings") + showType = "slider" + continue + } + var stErr *captchaV2ShowTypeError + if !errors.As(err, &stErr) || stErr.ShowType == "" { + return "", err + } + showType = stErr.ShowType + } + + if _, endErr := s.captchaRequest("captchaNotRobot.endSession", base); endErr != nil { + log.Printf("v2 captcha endSession failed: %v", endErr) + } + return token, nil +} + +func captchaV2BaseValues(sessionToken string) [][2]string { + return [][2]string{ + {"session_token", sessionToken}, + {"domain", "vk.com"}, + {"adFp", ""}, + {"access_token", ""}, + } +} + +func captchaV2BrowserFP() (string, error) { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + return "", fmt.Errorf("browser fp generate: %w", err) + } + return hex.EncodeToString(b), nil +} + +func (s *captchaV2Session) fetchCaptchaHTML(redirectURI string) (string, error) { + body, err := s.doRaw(fhttp.MethodGet, redirectURI, nil, map[string]string{ + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Sec-Fetch-Dest": "document", + "Sec-Fetch-Mode": "navigate", + "Sec-Fetch-Site": "cross-site", + }) + if err != nil { + return "", err + } + return string(body), nil +} + +func (s *captchaV2Session) fetchDebugInfo(scriptURL string) (string, error) { + if cached, ok := captchaV2DebugCache.Load(scriptURL); ok { + if cachedDebugInfo, ok := cached.(string); ok { + return cachedDebugInfo, nil + } + captchaV2DebugCache.Delete(scriptURL) + } + body, err := s.doRaw(fhttp.MethodGet, scriptURL, nil, map[string]string{ + "Accept": "text/javascript,*/*", + "Referer": "https://id.vk.com/", + }) + if err != nil { + return "", err + } + m := reCaptchaV2DebugInfo.FindSubmatch(body) + if len(m) < 2 { + return "", errors.New("debug_info match not found") + } + v := string(m[1]) + captchaV2DebugCache.Store(scriptURL, v) + log.Printf("v2 captcha debug_info fetched url=%s", scriptURL) + return v, nil +} + +func parseCaptchaV2Page(html string) (*captchaV2Page, error) { + page := &captchaV2Page{} + + match := reCaptchaV2WindowInit.FindStringSubmatch(html) + if len(match) < 2 { + return nil, errors.New("captcha init json not found") + } + var init captchaV2Init + if err := json.Unmarshal([]byte(match[1]), &init); err != nil { + return nil, fmt.Errorf("captcha init json parse: %w", err) + } + page.Init = &init + + match = reCaptchaV2ScriptSrc.FindStringSubmatch(html) + if len(match) < 2 { + return nil, errors.New("captcha script url not found") + } + page.ScriptURL = match[1] + + if m := reCaptchaV2PowInput.FindStringSubmatch(html); len(m) >= 2 { + page.PowInput = m[1] + } + if page.PowInput == "" { + return page, nil + } + + match = reCaptchaV2Difficulty.FindStringSubmatch(html) + if len(match) < 2 { + return nil, errors.New("captcha difficulty const not found") + } + difficulty, err := strconv.Atoi(match[1]) + if err != nil || difficulty <= 0 { + return nil, fmt.Errorf("invalid captcha difficulty %q", match[1]) + } + page.PowDifficulty = difficulty + return page, nil +} + +func (s *captchaV2Session) captchaRequest(method string, form [][2]string) (map[string]any, error) { + endpoint := "https://api.vk.ru/method/" + method + "?v=" + captchaV2APIVersion + body, err := s.doRaw(fhttp.MethodPost, endpoint, form, map[string]string{ + "Origin": "https://id.vk.com", + "Referer": "https://id.vk.com/", + "Priority": "u=1, i", + }) + if err != nil { + return nil, err + } + var out map[string]any + if err := json.Unmarshal(body, &out); err != nil { + return nil, fmt.Errorf("captcha api decode: %w", err) + } + return out, nil +} + +func (s *captchaV2Session) performCaptchaCheck( + sessionToken string, + browserFP string, + hash string, + answerJSON string, + cursor string, + debugInfo string, +) (*captchaV2Check, error) { + values := [][2]string{ + {"session_token", sessionToken}, + {"domain", "vk.com"}, + {"adFp", ""}, + {"accelerometer", "[]"}, + {"gyroscope", "[]"}, + {"motion", "[]"}, + {"cursor", cursor}, + {"taps", "[]"}, + {"connectionRtt", "[]"}, + {"connectionDownlink", "[]"}, + {"browser_fp", browserFP}, + {"hash", hash}, + {"answer", base64.StdEncoding.EncodeToString([]byte(answerJSON))}, + {"debug_info", debugInfo}, + {"access_token", ""}, + } + resp, err := s.captchaRequest("captchaNotRobot.check", values) + if err != nil { + return nil, fmt.Errorf("captcha check failed: %w", err) + } + check, err := parseCaptchaV2Check(resp) + if err != nil { + return nil, err + } + if check.ShowType != "" { + log.Printf("v2 captcha check status=%s show_type=%s", check.Status, check.ShowType) + } else { + log.Printf("v2 captcha check status=%s", check.Status) + } + return check, nil +} + +func parseCaptchaV2Check(raw map[string]any) (*captchaV2Check, error) { + resp, ok := raw["response"].(map[string]any) + if !ok { + return nil, fmt.Errorf("invalid captcha check response: %v", raw) + } + out := &captchaV2Check{ + Status: captchaV2StringifyAny(resp["status"]), + SuccessToken: captchaV2StringifyAny(resp["success_token"]), + ShowType: captchaV2StringifyAny(resp["show_captcha_type"]), + } + if out.Status == "" { + return nil, fmt.Errorf("captcha check status missing: %v", raw) + } + return out, nil +} + +func (s *captchaV2Session) solveCheckboxCaptcha( + sessionToken string, + browserFP string, + hash string, + debugInfo string, +) (string, error) { + deviceJSON := captchaV2DeviceInfo + if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" { + deviceJSON = s.savedProfile.DeviceJSON + } + if _, err := s.captchaRequest("captchaNotRobot.componentDone", [][2]string{ + {"session_token", sessionToken}, + {"domain", "vk.com"}, + {"adFp", ""}, + {"browser_fp", browserFP}, + {"device", deviceJSON}, + {"access_token", ""}, + }); err != nil { + return "", fmt.Errorf("captcha componentDone failed: %w", err) + } + + select { + case <-s.ctx.Done(): + return "", s.ctx.Err() + case <-time.After(time.Duration(400+mathrand.Intn(250)) * time.Millisecond): + } + + check, err := s.performCaptchaCheck(sessionToken, browserFP, hash, "{}", "[]", debugInfo) + if err != nil { + return "", err + } + if check.ShowType != "" && !strings.EqualFold(check.ShowType, "checkbox") { + return "", &captchaV2ShowTypeError{ShowType: check.ShowType} + } + if strings.EqualFold(check.Status, "error_limit") { + return "", errCaptchaV2RateLimit + } + if strings.EqualFold(check.Status, "bot") { + return "", fmt.Errorf("%w: checkbox captcha rejected: status=%s", errCaptchaV2Bot, check.Status) + } + if !strings.EqualFold(check.Status, "ok") { + return "", fmt.Errorf("checkbox captcha rejected: status=%s", check.Status) + } + if check.SuccessToken == "" { + return "", errors.New("captcha success token not found") + } + return check.SuccessToken, nil +} + +func solveCaptchaPoWV2(ctx context.Context, input string, difficulty int) string { + if input == "" || difficulty <= 0 { + return "" + } + target := strings.Repeat("0", difficulty) + for nonce := 1; nonce <= 10_000_000; nonce++ { + if nonce%4096 == 0 { + select { + case <-ctx.Done(): + return "" + default: + } + } + sum := sha256.Sum256([]byte(input + strconv.Itoa(nonce))) + hashHex := hex.EncodeToString(sum[:]) + if strings.HasPrefix(hashHex, target) { + return hashHex + } + } + return "" +} + +func (s *captchaV2Session) doRaw( + method string, + endpoint string, + form [][2]string, + extraHeaders map[string]string, +) ([]byte, error) { + var body []byte + if form != nil { + body = []byte(captchaV2EncodeForm(form)) + } + req, err := fhttp.NewRequestWithContext(s.ctx, method, endpoint, bytes.NewReader(body)) + if err != nil { + return nil, err + } + applyBrowserProfileFhttp(req, s.profile) + req.Header.Set("Accept", "*/*") + req.Header.Set("Sec-Fetch-Site", "same-site") + req.Header.Set("Sec-Fetch-Mode", "cors") + req.Header.Set("Sec-Fetch-Dest", "empty") + req.Header.Set("Origin", "https://vk.com") + req.Header.Set("Referer", "https://vk.com/") + if form != nil { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + for k, v := range extraHeaders { + req.Header.Set(k, v) + } + req.Header[fhttp.HeaderOrderKey] = captchaV2HeaderOrder + req.Header[fhttp.PHeaderOrderKey] = captchaV2PHeaderOrder + + resp, err := s.client.Do(req) + if err != nil { + return nil, err + } + defer func() { + if closeErr := resp.Body.Close(); closeErr != nil { + log.Printf("v2 captcha close body: %s", closeErr) + } + }() + return io.ReadAll(resp.Body) +} + +func captchaV2EncodeForm(values [][2]string) string { + if len(values) == 0 { + return "" + } + var sb strings.Builder + for i, kv := range values { + if i > 0 { + sb.WriteByte('&') + } + sb.WriteString(captchaV2QueryEscape(kv[0])) + sb.WriteByte('=') + sb.WriteString(captchaV2QueryEscape(kv[1])) + } + return sb.String() +} + +func captchaV2QueryEscape(s string) string { + const upper = "0123456789ABCDEF" + hexDigits := func(b byte) [3]byte { + return [3]byte{'%', upper[b>>4], upper[b&0xF]} + } + out := make([]byte, 0, len(s)) + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == ' ': + out = append(out, '+') + case ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~': + out = append(out, c) + default: + h := hexDigits(c) + out = append(out, h[:]...) + } + } + return string(out) +} + +func captchaV2StringifyAny(value any) string { + switch v := value.(type) { + case nil: + return "" + case string: + return v + case float64: + return strconv.FormatFloat(v, 'f', -1, 64) + case bool: + return strconv.FormatBool(v) + default: + data, err := json.Marshal(v) + if err != nil { + return fmt.Sprintf("%v", v) + } + return string(data) + } +} diff --git a/client/captcha_v2_slider.go b/client/captcha_v2_slider.go new file mode 100644 index 0000000..ccea186 --- /dev/null +++ b/client/captcha_v2_slider.go @@ -0,0 +1,606 @@ +package main + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "image" + "image/color" + _ "image/jpeg" + "log" + "math" + mathrand "math/rand" + "runtime" + "sort" + "strconv" + "strings" + "sync" +) + +type sliderPuzzleV2 struct { + Image image.Image + Size int + Swaps []int + Attempts int +} + +type sliderGuessV2 struct { + Index int + Swaps []int + Score int64 + ScoreRGB int64 + ScoreLuma int64 + ScoreText float64 + ConsensusRank int +} + +func (s *captchaV2Session) solveSliderCaptcha( + sessionToken string, + browserFP string, + hash string, + settings string, + debugInfo string, +) (string, error) { + values := [][2]string{ + {"session_token", sessionToken}, + {"domain", "vk.com"}, + {"adFp", ""}, + {"access_token", ""}, + {"captcha_settings", settings}, + } + + resp, err := s.captchaRequest("captchaNotRobot.getContent", values) + if err != nil { + return "", fmt.Errorf("slider getContent failed: %w", err) + } + puzzle, err := parseSliderPuzzleV2(resp) + if err != nil { + return "", err + } + log.Printf("v2 slider puzzle decoded: grid=%d attempts=%d swaps=%d", puzzle.Size, puzzle.Attempts, len(puzzle.Swaps)) + + guesses, err := rankSliderGuessesV2(puzzle.Image, puzzle.Size, puzzle.Swaps) + if err != nil { + return "", err + } + + limit := puzzle.Attempts + if limit > len(guesses) { + limit = len(guesses) + } + if limit <= 0 { + return "", errors.New("slider has no attempts available") + } + log.Printf("v2 slider guesses ranked: total=%d limit=%d", len(guesses), limit) + + deviceJSON := captchaV2DeviceInfo + if s.savedProfile != nil && strings.TrimSpace(s.savedProfile.DeviceJSON) != "" { + deviceJSON = s.savedProfile.DeviceJSON + } + if _, err := s.captchaRequest("captchaNotRobot.componentDone", [][2]string{ + {"session_token", sessionToken}, + {"domain", "vk.com"}, + {"adFp", ""}, + {"access_token", ""}, + {"browser_fp", browserFP}, + {"device", deviceJSON}, + }); err != nil { + return "", fmt.Errorf("captcha componentDone failed: %w", err) + } + + for i := 0; i < limit; i++ { + log.Printf("v2 slider attempt %d/%d (guess #%d)", i+1, limit, guesses[i].Index) + answerData, err := json.Marshal(struct { + Value []int `json:"value"` + }{Value: guesses[i].Swaps}) + if err != nil { + return "", err + } + check, err := s.performCaptchaCheck( + sessionToken, + browserFP, + hash, + string(answerData), + buildSliderCursorV2(guesses[i].Index, len(guesses)), + debugInfo, + ) + if err != nil { + return "", err + } + if strings.EqualFold(check.Status, "ok") { + if check.SuccessToken == "" { + return "", errors.New("captcha success token not found") + } + log.Printf("v2 slider accepted on attempt %d", i+1) + return check.SuccessToken, nil + } + if strings.EqualFold(check.Status, "error_limit") { + return "", errCaptchaV2RateLimit + } + } + return "", errors.New("slider guesses exhausted") +} + +func parseSliderPuzzleV2(raw map[string]any) (*sliderPuzzleV2, error) { + resp, ok := raw["response"].(map[string]any) + if !ok { + return nil, fmt.Errorf("invalid slider content response: %v", raw) + } + status := captchaV2StringifyAny(resp["status"]) + if !strings.EqualFold(status, "ok") { + return nil, fmt.Errorf("slider getContent status: %s", status) + } + rawImage := captchaV2StringifyAny(resp["image"]) + if rawImage == "" { + return nil, errors.New("slider image missing") + } + rawSteps, ok := resp["steps"].([]any) + if !ok { + return nil, errors.New("slider steps missing") + } + steps := make([]int, 0, len(rawSteps)) + for _, item := range rawSteps { + switch v := item.(type) { + case float64: + steps = append(steps, int(v)) + case int: + steps = append(steps, v) + case string: + n, err := strconv.Atoi(strings.TrimSpace(v)) + if err != nil { + return nil, fmt.Errorf("invalid numeric value: %v", item) + } + steps = append(steps, n) + default: + return nil, fmt.Errorf("invalid numeric value: %v", item) + } + } + size, swaps, attempts, err := splitSliderStepsV2(steps) + if err != nil { + return nil, err + } + data, err := base64.StdEncoding.DecodeString(rawImage) + if err != nil { + return nil, fmt.Errorf("decode slider image: %w", err) + } + img, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("decode slider image: %w", err) + } + return &sliderPuzzleV2{Image: img, Size: size, Swaps: swaps, Attempts: attempts}, nil +} + +func splitSliderStepsV2(steps []int) (int, []int, int, error) { + if len(steps) < 3 { + return 0, nil, 0, errors.New("slider steps payload too short") + } + size := steps[0] + if size <= 0 { + return 0, nil, 0, fmt.Errorf("invalid slider size: %d", size) + } + tail := append([]int(nil), steps[1:]...) + attempts := 4 + if len(tail)%2 != 0 { + attempts = tail[len(tail)-1] + tail = tail[:len(tail)-1] + log.Printf("v2 slider payload had odd-length tail; fallback attempts=%d", attempts) + } + if attempts <= 0 { + attempts = 4 + } + if len(tail) == 0 || len(tail)%2 != 0 { + return 0, nil, 0, errors.New("invalid slider swap payload") + } + return size, tail, attempts, nil +} + +func rankSliderGuessesV2(img image.Image, gridSize int, swaps []int) ([]sliderGuessV2, error) { + candidateCount := len(swaps) / 2 + if candidateCount == 0 { + return nil, errors.New("slider has no candidates") + } + + guesses := make([]sliderGuessV2, candidateCount) + for idx := 1; idx <= candidateCount; idx++ { + active := activeSwapsForIndexV2(swaps, idx) + mapping, err := applySliderSwapsV2(gridSize, active) + if err != nil { + return nil, err + } + guesses[idx-1] = sliderGuessV2{Index: idx, Swaps: active} + guesses[idx-1].ScoreLuma = seamScoreLumaV2(img, gridSize, mapping) + } + + lumaOrder := append([]sliderGuessV2(nil), guesses...) + sort.SliceStable(lumaOrder, func(i, j int) bool { + if lumaOrder[i].ScoreLuma == lumaOrder[j].ScoreLuma { + return lumaOrder[i].Index < lumaOrder[j].Index + } + return lumaOrder[i].ScoreLuma < lumaOrder[j].ScoreLuma + }) + lumaRank := make(map[int]int, candidateCount) + for rank, g := range lumaOrder { + lumaRank[g.Index] = rank + } + + stage2Count := candidateCount + if stage2Count > 12 { + stage2Count = 12 + } + stage2Set := make(map[int]struct{}, stage2Count) + for i := 0; i < stage2Count; i++ { + stage2Set[lumaOrder[i].Index] = struct{}{} + } + + type stage2Result struct { + index int + rgb int64 + text float64 + err error + } + jobs := make([]int, 0, stage2Count) + for idx := range stage2Set { + jobs = append(jobs, idx) + } + jobCh := make(chan int, len(jobs)) + resCh := make(chan stage2Result, len(jobs)) + + workers := runtime.NumCPU() + if workers < 1 { + workers = 1 + } + if workers > len(jobs) { + workers = len(jobs) + } + var wg sync.WaitGroup + for w := 0; w < workers; w++ { + wg.Add(1) + go func() { + defer wg.Done() + for index := range jobCh { + mapping, err := applySliderSwapsV2(gridSize, guesses[index-1].Swaps) + if err != nil { + resCh <- stage2Result{index: index, err: err} + continue + } + rgb, text := seamScoreRGBTextV2(img, gridSize, mapping) + resCh <- stage2Result{index: index, rgb: rgb, text: text} + } + }() + } + for _, idx := range jobs { + jobCh <- idx + } + close(jobCh) + wg.Wait() + close(resCh) + for r := range resCh { + if r.err != nil { + return nil, r.err + } + g := &guesses[r.index-1] + g.ScoreRGB = r.rgb + g.ScoreText = r.text + } + + stage2 := make([]sliderGuessV2, 0, stage2Count) + for _, g := range guesses { + if _, ok := stage2Set[g.Index]; ok { + stage2 = append(stage2, g) + } + } + + rgbOrder := append([]sliderGuessV2(nil), stage2...) + sort.SliceStable(rgbOrder, func(i, j int) bool { + if rgbOrder[i].ScoreRGB == rgbOrder[j].ScoreRGB { + return rgbOrder[i].Index < rgbOrder[j].Index + } + return rgbOrder[i].ScoreRGB < rgbOrder[j].ScoreRGB + }) + rgbRank := make(map[int]int, len(rgbOrder)) + for rank, g := range rgbOrder { + rgbRank[g.Index] = rank + } + + textOrder := append([]sliderGuessV2(nil), stage2...) + sort.SliceStable(textOrder, func(i, j int) bool { + if textOrder[i].ScoreText == textOrder[j].ScoreText { + return textOrder[i].Index < textOrder[j].Index + } + return textOrder[i].ScoreText < textOrder[j].ScoreText + }) + textRank := make(map[int]int, len(textOrder)) + for rank, g := range textOrder { + textRank[g.Index] = rank + } + + for i := range guesses { + g := &guesses[i] + g.ConsensusRank = lumaRank[g.Index] + if _, ok := stage2Set[g.Index]; ok { + g.ConsensusRank += rgbRank[g.Index] + textRank[g.Index] + } else { + g.ConsensusRank += candidateCount + } + g.Score = int64(g.ConsensusRank) + } + + sort.SliceStable(guesses, func(i, j int) bool { + if guesses[i].ConsensusRank == guesses[j].ConsensusRank { + if guesses[i].ScoreLuma == guesses[j].ScoreLuma { + return guesses[i].Index < guesses[j].Index + } + return guesses[i].ScoreLuma < guesses[j].ScoreLuma + } + return guesses[i].ConsensusRank < guesses[j].ConsensusRank + }) + return guesses, nil +} + +func activeSwapsForIndexV2(swaps []int, index int) []int { + if index <= 0 { + return []int{} + } + end := index * 2 + if end > len(swaps) { + end = len(swaps) + } + return append([]int(nil), swaps[:end]...) +} + +func applySliderSwapsV2(gridSize int, swaps []int) ([]int, error) { + tileCount := gridSize * gridSize + if tileCount <= 0 { + return nil, fmt.Errorf("invalid slider tile count: %d", tileCount) + } + if len(swaps)%2 != 0 { + return nil, fmt.Errorf("invalid slider swaps length: %d", len(swaps)) + } + mapping := make([]int, tileCount) + for i := range mapping { + mapping[i] = i + } + for i := 0; i < len(swaps); i += 2 { + left := swaps[i] + right := swaps[i+1] + if left < 0 || right < 0 || left >= tileCount || right >= tileCount { + return nil, fmt.Errorf("slider step out of range: %d,%d", left, right) + } + mapping[left], mapping[right] = mapping[right], mapping[left] + } + return mapping, nil +} + +func seamScoreLumaV2(img image.Image, gridSize int, mapping []int) int64 { + bounds := img.Bounds() + var score int64 + for row := 0; row < gridSize; row++ { + for col := 0; col < gridSize-1; col++ { + leftIdx := row*gridSize + col + rightIdx := leftIdx + 1 + leftDst := sliderTileRect(bounds, gridSize, leftIdx) + rightDst := sliderTileRect(bounds, gridSize, rightIdx) + leftSrc := sliderTileRect(bounds, gridSize, mapping[leftIdx]) + rightSrc := sliderTileRect(bounds, gridSize, mapping[rightIdx]) + h := leftDst.Dy() + if rightDst.Dy() < h { + h = rightDst.Dy() + } + for y := 0; y < h; y++ { + yy := leftDst.Min.Y + y + a := sampleLumaMappedV2(img, leftDst, leftSrc, leftDst.Max.X-1, yy) + b := sampleLumaMappedV2(img, rightDst, rightSrc, rightDst.Min.X, yy) + score += int64(absIntV2(int(a) - int(b))) + } + } + } + for row := 0; row < gridSize-1; row++ { + for col := 0; col < gridSize; col++ { + topIdx := row*gridSize + col + bottomIdx := (row+1)*gridSize + col + topDst := sliderTileRect(bounds, gridSize, topIdx) + bottomDst := sliderTileRect(bounds, gridSize, bottomIdx) + topSrc := sliderTileRect(bounds, gridSize, mapping[topIdx]) + bottomSrc := sliderTileRect(bounds, gridSize, mapping[bottomIdx]) + w := topDst.Dx() + if bottomDst.Dx() < w { + w = bottomDst.Dx() + } + for x := 0; x < w; x++ { + xx := topDst.Min.X + x + a := sampleLumaMappedV2(img, topDst, topSrc, xx, topDst.Max.Y-1) + b := sampleLumaMappedV2(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y) + score += int64(absIntV2(int(a) - int(b))) + } + } + } + return score +} + +func seamScoreRGBTextV2(img image.Image, gridSize int, mapping []int) (int64, float64) { + bounds := img.Bounds() + height := float64(bounds.Dy()) + textCenters := []float64{ + float64(bounds.Min.Y) + 0.2*height, + float64(bounds.Min.Y) + 0.5*height, + float64(bounds.Min.Y) + 0.8*height, + } + sigma := height * 0.14 + if sigma < 1.0 { + sigma = 1.0 + } + weight := func(y int) float64 { + yf := float64(y) + best := absFloatV2(yf - textCenters[0]) + for i := 1; i < len(textCenters); i++ { + d := absFloatV2(yf - textCenters[i]) + if d < best { + best = d + } + } + return 1 + 3*math.Exp(-(best*best)/(2*sigma*sigma)) + } + + var rgbScore int64 + var textScore float64 + for row := 0; row < gridSize; row++ { + for col := 0; col < gridSize-1; col++ { + leftIdx := row*gridSize + col + rightIdx := leftIdx + 1 + leftDst := sliderTileRect(bounds, gridSize, leftIdx) + rightDst := sliderTileRect(bounds, gridSize, rightIdx) + leftSrc := sliderTileRect(bounds, gridSize, mapping[leftIdx]) + rightSrc := sliderTileRect(bounds, gridSize, mapping[rightIdx]) + h := leftDst.Dy() + if rightDst.Dy() < h { + h = rightDst.Dy() + } + for y := 0; y < h; y++ { + yy := leftDst.Min.Y + y + l := sampleColorMappedV2(img, leftDst, leftSrc, leftDst.Max.X-1, yy) + r := sampleColorMappedV2(img, rightDst, rightSrc, rightDst.Min.X, yy) + rgbScore += pixelDiff(l, r) + _, _, lb, _ := l.RGBA() + _, _, rb, _ := r.RGBA() + textScore += weight(yy) * float64(absIntV2(int(lb>>8)-int(rb>>8))) + } + } + } + for row := 0; row < gridSize-1; row++ { + for col := 0; col < gridSize; col++ { + topIdx := row*gridSize + col + bottomIdx := (row+1)*gridSize + col + topDst := sliderTileRect(bounds, gridSize, topIdx) + bottomDst := sliderTileRect(bounds, gridSize, bottomIdx) + topSrc := sliderTileRect(bounds, gridSize, mapping[topIdx]) + bottomSrc := sliderTileRect(bounds, gridSize, mapping[bottomIdx]) + w := topDst.Dx() + if bottomDst.Dx() < w { + w = bottomDst.Dx() + } + for x := 0; x < w; x++ { + xx := topDst.Min.X + x + t := sampleColorMappedV2(img, topDst, topSrc, xx, topDst.Max.Y-1) + b := sampleColorMappedV2(img, bottomDst, bottomSrc, xx, bottomDst.Min.Y) + rgbScore += pixelDiff(t, b) + _, _, tb, _ := t.RGBA() + _, _, bb, _ := b.RGBA() + textScore += 0.65 * float64(absIntV2(int(tb>>8)-int(bb>>8))) + } + } + } + return rgbScore, textScore +} + +func sampleColorMappedV2(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) color.Color { + dx := dstRect.Dx() + if dx < 1 { + dx = 1 + } + dy := dstRect.Dy() + if dy < 1 { + dy = 1 + } + sx := srcRect.Min.X + (dstX-dstRect.Min.X)*srcRect.Dx()/dx + sy := srcRect.Min.Y + (dstY-dstRect.Min.Y)*srcRect.Dy()/dy + return img.At(sx, sy) +} + +func sampleLumaMappedV2(img image.Image, dstRect image.Rectangle, srcRect image.Rectangle, dstX int, dstY int) uint8 { + c := sampleColorMappedV2(img, dstRect, srcRect, dstX, dstY) + r, g, b, _ := c.RGBA() + y := (299*(r>>8) + 587*(g>>8) + 114*(b>>8)) / 1000 + return uint8(y) +} + +func absFloatV2(v float64) float64 { + if v < 0 { + return -v + } + return v +} + +func absIntV2(v int) int { + if v < 0 { + return -v + } + return v +} + +func buildSliderCursorV2(candidateIndex int, candidateCount int) string { + if candidateCount <= 0 { + return "[]" + } + if candidateIndex < 1 { + candidateIndex = 1 + } + if candidateIndex > candidateCount { + candidateIndex = candidateCount + } + + type cursorPoint struct { + X int `json:"x"` + Y int `json:"y"` + } + + startX := 570 + mathrand.Intn(40) + startY := 875 + mathrand.Intn(30) + + denom := candidateCount - 1 + if denom < 1 { + denom = 1 + } + baseTargetX := 734 + (937-734)*(candidateIndex-1)/denom + targetX := baseTargetX + mathrand.Intn(10) - 5 + targetY := 655 + mathrand.Intn(14) + + points := make([]cursorPoint, 0, 28) + + for i := 0; i < 1+mathrand.Intn(3); i++ { + points = append(points, cursorPoint{ + X: startX + mathrand.Intn(5) - 2, + Y: startY + mathrand.Intn(5) - 2, + }) + } + + transitSteps := 2 + mathrand.Intn(3) + arcOffX := mathrand.Intn(60) - 30 + arcOffY := -(mathrand.Intn(30) + 10) + for i := 1; i <= transitSteps; i++ { + t := float64(i) / float64(transitSteps+1) + cx := float64(startX+targetX)/2 + float64(arcOffX) + cy := float64(startY+targetY)/2 + float64(arcOffY) + bx := (1-t)*(1-t)*float64(startX) + 2*t*(1-t)*cx + t*t*float64(targetX) + by := (1-t)*(1-t)*float64(startY) + 2*t*(1-t)*cy + t*t*float64(targetY) + jitter := int((1-t)*8) + 2 + points = append(points, cursorPoint{ + X: int(math.Round(bx)) + mathrand.Intn(jitter*2+1) - jitter, + Y: int(math.Round(by)) + mathrand.Intn(jitter*2+1) - jitter, + }) + } + + approachSteps := 4 + mathrand.Intn(4) + prev := points[len(points)-1] + for i := 1; i <= approachSteps; i++ { + t := float64(i) / float64(approachSteps) + ax := prev.X + int(math.Round(t*float64(targetX-prev.X))) + mathrand.Intn(5) - 2 + ay := prev.Y + int(math.Round(t*float64(targetY-prev.Y))) + mathrand.Intn(5) - 2 + points = append(points, cursorPoint{X: ax, Y: ay}) + } + + settleCount := 3 + mathrand.Intn(5) + for i := 0; i < settleCount; i++ { + points = append(points, cursorPoint{ + X: targetX + mathrand.Intn(7) - 3, + Y: targetY + mathrand.Intn(7) - 3, + }) + } + + data, err := json.Marshal(points) + if err != nil { + return "[]" + } + return string(data) +} diff --git a/client/ish_listener_linux_386.go b/client/ish_listener_linux_386.go new file mode 100644 index 0000000..25ab1e2 --- /dev/null +++ b/client/ish_listener_linux_386.go @@ -0,0 +1,135 @@ +//go:build linux && 386 + +package main + +import ( + "io" + "net" + "os" + "syscall" + "time" + "unsafe" +) + +type ishListener struct { + net.Listener + f *os.File + fd int +} + +// wrapISHListener overrides the standard net.Listener with a legacy syscall listener +// designed specifically for the iSH simulator on iOS, which lacks modern `accept4`. +func wrapISHListener(ln net.Listener) (net.Listener, error) { + tl, ok := ln.(*net.TCPListener) + if !ok { + return ln, nil + } + f, err := tl.File() + if err != nil { + return nil, err + } + + // Keep a reference to *os.File so the garbage collector doesn't close the FD. + return &ishListener{Listener: ln, f: f, fd: int(f.Fd())}, nil +} + +func (l *ishListener) Accept() (net.Conn, error) { + // Set the listener socket to blocking mode. Go makes it non-blocking by default. + // This avoids using time.Sleep in a spin-loop, which triggers futex_time64 SIGSYS in modern Go on iSH. + if err := syscall.SetNonblock(l.fd, false); err != nil { + return nil, err + } + + for { + addr := make([]byte, 128) + addrlen := uintptr(128) + + // i386 network syscalls are multiplexed via socketcall (102). + // SYS_ACCEPT is subcall 5. + args := [3]uintptr{uintptr(l.fd), uintptr(unsafe.Pointer(&addr[0])), uintptr(unsafe.Pointer(&addrlen))} + + // Use Syscall6 to ensure we have enough arguments registers for the platform. + r1, _, errno := syscall.Syscall6(102, 5, uintptr(unsafe.Pointer(&args)), 0, 0, 0, 0) + if errno != 0 { + if errno == syscall.EINTR { + continue + } + return nil, errno + } + + nfd := int(r1) + _ = syscall.SetsockoptInt(nfd, syscall.IPPROTO_TCP, syscall.TCP_NODELAY, 1) + _ = syscall.SetsockoptInt(nfd, syscall.SOL_SOCKET, syscall.SO_RCVBUF, 256*1024) + _ = syscall.SetsockoptInt(nfd, syscall.SOL_SOCKET, syscall.SO_SNDBUF, 256*1024) + + // We avoid Go's net.FileConn because it tries to register the fd with Go's epoll poller, + // which in iSH emulator consistency fails with EEXIST (file exists). + // Instead, we return a custom blocking net.Conn wrapper. + conn := &ishConn{fd: nfd} + return conn, nil + } +} + +func (l *ishListener) Close() error { + // Close both the duplicated FD and the original listener. + err1 := l.f.Close() + err2 := l.Listener.Close() + if err1 != nil { + return err1 + } + return err2 +} + +// ishConn bypasses Go's network poller to prevent EEXIST bugs in iSH +type ishConn struct { + fd int +} + +func (c *ishConn) Read(b []byte) (n int, err error) { + for { + n, err = syscall.Read(c.fd, b) + if err == syscall.EINTR { + continue + } + if err != nil { + return n, err + } + if n == 0 { + return 0, os.ErrClosed + } + return n, nil + } +} + +func (c *ishConn) Write(b []byte) (n int, err error) { + for n < len(b) { + written, writeErr := syscall.Write(c.fd, b[n:]) + if writeErr == syscall.EINTR { + continue + } + if writeErr != nil { + return n, writeErr + } + if written == 0 { + return n, io.ErrShortWrite + } + n += written + } + return n, nil +} + +func (c *ishConn) Close() error { + return syscall.Close(c.fd) +} + +func (c *ishConn) LocalAddr() net.Addr { + return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 9000} +} + +func (c *ishConn) RemoteAddr() net.Addr { + return &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 0} +} + +func (c *ishConn) SetDeadline(t time.Time) error { return nil } +func (c *ishConn) SetReadDeadline(t time.Time) error { return nil } +func (c *ishConn) SetWriteDeadline(t time.Time) error { return nil } diff --git a/client/ish_listener_other.go b/client/ish_listener_other.go new file mode 100644 index 0000000..d46659d --- /dev/null +++ b/client/ish_listener_other.go @@ -0,0 +1,10 @@ +//go:build !(linux && 386) + +package main + +import "net" + +// wrapISHListener is a no-op for architectures that don't need the legacy socketcall accept bypass. +func wrapISHListener(ln net.Listener) (net.Listener, error) { + return ln, nil +} diff --git a/client/main.go b/client/main.go new file mode 100644 index 0000000..09628ec --- /dev/null +++ b/client/main.go @@ -0,0 +1,3065 @@ +// SPDX-FileCopyrightText: 2023 The Pion community +// SPDX-License-Identifier: MIT + +package main + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log" + "math/rand" + "net" + "net/http" + neturl "net/url" + "os" + "os/signal" + "strconv" + "strings" + "sync" + "sync/atomic" + "syscall" + "time" + + fhttp "github.com/bogdanfinn/fhttp" + tlsclient "github.com/bogdanfinn/tls-client" + "github.com/bogdanfinn/tls-client/profiles" + + "github.com/bschaatsbergen/dnsdialer" + "github.com/cacggghp/vk-turn-proxy/tcputil" + "github.com/cbeuw/connutil" + "github.com/google/uuid" + "github.com/gorilla/websocket" + "github.com/pion/dtls/v3" + "github.com/pion/dtls/v3/pkg/crypto/selfsign" + "github.com/pion/logging" + "github.com/pion/transport/v4" + "github.com/pion/turn/v5" + "github.com/xtaci/smux" +) + +type getCredsFunc func(ctx context.Context, link string, streamID int) (string, string, string, error) + +type directNet struct{} + +type directDialer struct { + *net.Dialer +} + +type directListenConfig struct { + *net.ListenConfig +} + +// Global state trackers +var ( + activeLocalPeer atomic.Value + globalCaptchaLockout atomic.Int64 + connectedStreams atomic.Int32 + globalAppCancel context.CancelFunc + handshakeSem = make(chan struct{}, 3) + isDebug bool + manualCaptcha bool + autoCaptchaSliderPOC bool + captchaSolverVersion string +) + +func debugf(format string, v ...any) { + if isDebug { + log.Printf(format, v...) + } +} + +type captchaSolveMode int + +const ( + captchaSolveModeAuto captchaSolveMode = iota + captchaSolveModeSliderPOC + captchaSolveModeManual +) + +func captchaSolveModeForAttempt(attempt int, manualOnly bool, enableSliderPOC bool) (captchaSolveMode, bool) { + if manualOnly { + return captchaSolveModeManual, attempt == 0 + } + + switch attempt { + case 0: + return captchaSolveModeAuto, true + case 1: + if enableSliderPOC { + return captchaSolveModeSliderPOC, true + } + return captchaSolveModeManual, true + case 2: + if enableSliderPOC { + return captchaSolveModeManual, true + } + } + + return 0, false +} + +func captchaSolveModeLabel(mode captchaSolveMode) string { + switch mode { + case captchaSolveModeAuto: + return "auto captcha" + case captchaSolveModeSliderPOC: + return "auto captcha slider POC" + case captchaSolveModeManual: + return "manual captcha" + default: + return "captcha" + } +} + +type UDPPacket struct { + Data []byte + N int +} + +var packetPool = sync.Pool{ + New: func() any { return &UDPPacket{Data: make([]byte, 2048)} }, +} + +type throughputStats struct { + tx atomic.Uint64 + rx atomic.Uint64 +} + +func (s *throughputStats) addTx(n int) { + if n > 0 { + s.tx.Add(uint64(n)) + } +} + +func (s *throughputStats) addRx(n int) { + if n > 0 { + s.rx.Add(uint64(n)) + } +} + +func (s *throughputStats) logEvery(ctx context.Context, label, txName, rxName string) { + if !isDebug { + return + } + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + var prevTx, prevRx uint64 + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + tx := s.tx.Load() + rx := s.rx.Load() + deltaTx := tx - prevTx + deltaRx := rx - prevRx + prevTx = tx + prevRx = rx + + if deltaTx == 0 && deltaRx == 0 { + continue + } + + debugf( + "%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s", + label, + txName, + formatBitsPerSecond(deltaTx, 5*time.Second), + rxName, + formatBitsPerSecond(deltaRx, 5*time.Second), + txName, + formatByteCount(tx), + rxName, + formatByteCount(rx), + ) + } + } +} + +func formatBitsPerSecond(bytes uint64, interval time.Duration) string { + if interval <= 0 { + interval = time.Second + } + + bps := float64(bytes*8) / interval.Seconds() + if bps >= 1_000_000 { + return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000) + } + if bps >= 1_000 { + return fmt.Sprintf("%.1f kbit/s", bps/1_000) + } + return fmt.Sprintf("%.0f bit/s", bps) +} + +func formatByteCount(bytes uint64) string { + if bytes >= 1024*1024 { + return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024)) + } + if bytes >= 1024 { + return fmt.Sprintf("%.1f KiB", float64(bytes)/1024) + } + return fmt.Sprintf("%d B", bytes) +} + +type countingConn struct { + net.Conn + stats *throughputStats +} + +func (c *countingConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + c.stats.addRx(n) + return n, err +} + +func (c *countingConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + c.stats.addTx(n) + return n, err +} + +func newDirectNet() transport.Net { + return directNet{} +} + +func (directNet) ListenPacket(network string, address string) (net.PacketConn, error) { + return net.ListenPacket(network, address) +} + +func (directNet) ListenUDP(network string, locAddr *net.UDPAddr) (transport.UDPConn, error) { + return net.ListenUDP(network, locAddr) +} + +func (directNet) ListenTCP(network string, laddr *net.TCPAddr) (transport.TCPListener, error) { + listener, err := net.ListenTCP(network, laddr) + if err != nil { + return nil, err + } + + return directTCPListener{listener}, nil +} + +func (directNet) Dial(network, address string) (net.Conn, error) { + return net.Dial(network, address) +} + +func (directNet) DialUDP(network string, laddr, raddr *net.UDPAddr) (transport.UDPConn, error) { + return net.DialUDP(network, laddr, raddr) +} + +func (directNet) DialTCP(network string, laddr, raddr *net.TCPAddr) (transport.TCPConn, error) { + return net.DialTCP(network, laddr, raddr) +} + +func (directNet) ResolveIPAddr(network, address string) (*net.IPAddr, error) { + return net.ResolveIPAddr(network, address) +} + +func (directNet) ResolveUDPAddr(network, address string) (*net.UDPAddr, error) { + return net.ResolveUDPAddr(network, address) +} + +func (directNet) ResolveTCPAddr(network, address string) (*net.TCPAddr, error) { + return net.ResolveTCPAddr(network, address) +} + +func (directNet) Interfaces() ([]*transport.Interface, error) { + return nil, transport.ErrNotSupported +} + +func (directNet) InterfaceByIndex(index int) (*transport.Interface, error) { + return nil, fmt.Errorf("%w: index=%d", transport.ErrInterfaceNotFound, index) +} + +func (directNet) InterfaceByName(name string) (*transport.Interface, error) { + return nil, fmt.Errorf("%w: %s", transport.ErrInterfaceNotFound, name) +} + +func (directNet) CreateDialer(dialer *net.Dialer) transport.Dialer { + return directDialer{Dialer: dialer} +} + +func (directNet) CreateListenConfig(listenerConfig *net.ListenConfig) transport.ListenConfig { + return directListenConfig{ListenConfig: listenerConfig} +} + +func (d directDialer) Dial(network, address string) (net.Conn, error) { + return d.Dialer.Dial(network, address) +} + +func (d directListenConfig) Listen(ctx context.Context, network, address string) (net.Listener, error) { + return d.ListenConfig.Listen(ctx, network, address) +} + +func (d directListenConfig) ListenPacket(ctx context.Context, network, address string) (net.PacketConn, error) { + return d.ListenConfig.ListenPacket(ctx, network, address) +} + +type directTCPListener struct { + *net.TCPListener +} + +func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) { + return l.TCPListener.AcceptTCP() +} + +// region Helper: HTTP Headers Injection + +// applyBrowserProfile applies consistent User-Agent and Client Hints to bypass WAFs +func applyBrowserProfile(req *http.Request, profile Profile) { + req.Header.Set("User-Agent", profile.UserAgent) + req.Header.Set("sec-ch-ua", profile.SecChUa) + req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile) + req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform) + req.Header.Set("Accept-Language", "en-US,en;q=0.9") + req.Header.Set("DNT", "1") +} + +func applyBrowserProfileFhttp(req *fhttp.Request, profile Profile) { + req.Header.Set("User-Agent", profile.UserAgent) + req.Header.Set("sec-ch-ua", profile.SecChUa) + req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile) + req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform) + req.Header.Set("Accept-Language", "en-US,en;q=0.9") + req.Header.Set("DNT", "1") +} + +func generateBrowserFp(profile Profile) string { + // Fallback logic for generating a fingerprint if no saved profile is available. + // This uses a simple MD5 hash of UA and a fixed resolution. + data := profile.UserAgent + profile.SecChUa + "1536x864x24" + h := md5.Sum([]byte(data)) + return hex.EncodeToString(h[:]) +} + +/* +func generateFakeCursor() string { + startX := 600 + rand.Intn(400) + startY := 300 + rand.Intn(200) + startTime := time.Now().UnixMilli() - int64(rand.Intn(2000)+1000) + var points []string + for i := 0; i < 15+rand.Intn(10); i++ { + startX += rand.Intn(15) - 5 + startY += rand.Intn(15) + 2 + startTime += int64(rand.Intn(40) + 10) + points = append(points, fmt.Sprintf(`{"x":%d,"y":%d,"t":%d}`, startX, startY, startTime)) + } + return "[" + strings.Join(points, ",") + "]" +} + +// generateCheckboxCursor simulates a mouse moving from a random starting position +// towards the VK captcha checkbox area, decelerating as it approaches the target. +// This looks more like a real click than either a stationary cursor or pure random jitter. +func generateCheckboxCursor() string { + type point struct { + X int `json:"x"` + Y int `json:"y"` + T int64 `json:"t"` + } + + // Target is roughly where VK renders the checkbox + targetX := 290 + rand.Intn(20) - 10 + targetY := 437 + rand.Intn(10) - 5 + + // Starting position: somewhere to the upper-right of the checkbox + startX := targetX + 200 + rand.Intn(300) + startY := targetY - 80 - rand.Intn(120) + + steps := 14 + rand.Intn(6) + startTime := time.Now().Add(-time.Duration(400+rand.Intn(600)) * time.Millisecond).UnixMilli() + + points := make([]point, 0, steps) + for i := 0; i < steps; i++ { + // Ease-out: fast at start, slow near target + t := float64(i) / float64(steps-1) + ease := 1 - (1-t)*(1-t) + x := startX + int(float64(targetX-startX)*ease) + rand.Intn(5) - 2 + y := startY + int(float64(targetY-startY)*ease) + rand.Intn(5) - 2 + dt := int64(15 + rand.Intn(25) + int(20*t)) // slower near target + startTime += dt + points = append(points, point{X: x, Y: y, T: startTime}) + } + + data, err := json.Marshal(points) + if err != nil { + return "[]" + } + return string(data) +} +*/ + +func getCustomNetDialer() net.Dialer { + return net.Dialer{ + Timeout: 20 * time.Second, + KeepAlive: 30 * time.Second, + Resolver: &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, network, address string) (net.Conn, error) { + var d net.Dialer + dnsServers := []string{"77.88.8.8:53", "77.88.8.1:53", "8.8.8.8:53", "8.8.4.4:53", "1.1.1.1:53", "1.0.0.1:53"} + var lastErr error + for _, dns := range dnsServers { + conn, err := d.DialContext(ctx, "udp", dns) + if err == nil { + return conn, nil + } + lastErr = err + } + return nil, lastErr + }, + }, + } +} + +// endregion + +// region Automatic Captcha Solver & Authentication + +type VkCaptchaError struct { + ErrorCode int + ErrorMsg string + CaptchaSid string + CaptchaImg string + RedirectURI string + IsSoundCaptchaAvailable bool + SessionToken string + CaptchaTs string + CaptchaAttempt string +} + +func ParseVkCaptchaError(errData map[string]interface{}) *VkCaptchaError { + // Extract error_code + codeFloat, ok := errData["error_code"].(float64) + if !ok { + log.Printf("missing error_code in captcha error data") + return nil + } + code := int(codeFloat) + + // Extract redirect_uri + RedirectURI, ok := errData["redirect_uri"].(string) + if !ok { + log.Printf("missing redirect_uri in captcha error data") + return nil + } + + // Extract captcha_sid + captchaSid, ok := errData["captcha_sid"].(string) + if !ok { + // try numeric + if sidNum, ok2 := errData["captcha_sid"].(float64); ok2 { + captchaSid = fmt.Sprintf("%.0f", sidNum) + } else { + log.Printf("missing captcha_sid in captcha error data") + return nil + } + } + + // Extract captcha_img + captchaImg, ok := errData["captcha_img"].(string) + if !ok { + log.Printf("missing captcha_img in captcha error data") + return nil + } + + // Extract error_msg + errorMsg, ok := errData["error_msg"].(string) + if !ok { + log.Printf("missing error_msg in captcha error data") + return nil + } + + // Extract session token + var sessionToken string + if RedirectURI != "" { + if parsed, err := neturl.Parse(RedirectURI); err == nil { + sessionToken = parsed.Query().Get("session_token") + } else { + log.Printf("failed to parse redirect_uri: %v", err) + return nil + } + } + // Fallback to top-level session_token field if not in redirect_uri + if sessionToken == "" { + if st, stOk := errData["session_token"].(string); stOk { + sessionToken = st + } + } + + // Extract is_sound_captcha_available + isSound, ok := errData["is_sound_captcha_available"].(bool) + if !ok { + isSound = false + } + + // Extract captcha_ts + var captchaTs string + if tsFloat, ok := errData["captcha_ts"].(float64); ok { + captchaTs = fmt.Sprintf("%.0f", tsFloat) + } else if tsStr, ok := errData["captcha_ts"].(string); ok { + captchaTs = tsStr + } + + // Extract captcha_attempt + var captchaAttempt string + if attFloat, ok := errData["captcha_attempt"].(float64); ok { + captchaAttempt = fmt.Sprintf("%.0f", attFloat) + } else if attStr, ok := errData["captcha_attempt"].(string); ok { + captchaAttempt = attStr + } + + // Build VkCaptchaError + return &VkCaptchaError{ + ErrorCode: code, + ErrorMsg: errorMsg, + CaptchaSid: captchaSid, + CaptchaImg: captchaImg, + RedirectURI: RedirectURI, + IsSoundCaptchaAvailable: isSound, + SessionToken: sessionToken, + CaptchaTs: captchaTs, + CaptchaAttempt: captchaAttempt, + } +} + +func (e *VkCaptchaError) IsCaptchaError() bool { + return e.ErrorCode == 14 && e.RedirectURI != "" && e.SessionToken != "" +} + +func solveVkCaptcha(ctx context.Context, captchaErr *VkCaptchaError, streamID int, client tlsclient.HttpClient, profile Profile, useSliderPOC bool) (string, error) { + if useSliderPOC { + log.Printf("[STREAM %d] [Captcha] Solving captcha with slider POC...", streamID) + } else { + log.Printf("[STREAM %d] [Captcha] Solving captcha...", streamID) + } + + if captchaErr.SessionToken == "" { + return "", fmt.Errorf("no session_token in redirect_uri for auto-solve") + } + if captchaErr.RedirectURI == "" { + return "", fmt.Errorf("no redirect_uri for auto-solve") + } + + // Try to load saved profile from disk + var savedProfile *SavedProfile + if sp, err := LoadProfileFromDisk(); err == nil { + log.Printf("[STREAM %d] [Captcha] Using saved real browser profile", streamID) + savedProfile = sp + profile = sp.Profile // Use saved headers/UA + } + + if !useSliderPOC && !strings.EqualFold(captchaSolverVersion, "v1") { + successToken, v2Err := solveVkCaptchaV2(ctx, captchaErr, streamID, client, profile, savedProfile) + if v2Err == nil { + log.Printf("[STREAM %d] [Captcha] v2 solver succeeded", streamID) + return successToken, nil + } + if errors.Is(v2Err, errCaptchaV2RateLimit) { + return "", v2Err + } + log.Printf("[STREAM %d] [Captcha] v2 solver failed, falling back to legacy solver: %v", streamID, v2Err) + } + + bootstrap, err := fetchCaptchaBootstrap(ctx, captchaErr.RedirectURI, client, profile) + if err != nil { + return "", fmt.Errorf("failed to fetch captcha bootstrap: %w", err) + } + + log.Printf("[STREAM %d] [Captcha] PoW input: %s, difficulty: %d", streamID, bootstrap.PowInput, bootstrap.Difficulty) + + hash := solvePoW(bootstrap.PowInput, bootstrap.Difficulty) + log.Printf("[STREAM %d] [Captcha] PoW solved: hash=%s", streamID, hash) + + var successToken string + if useSliderPOC { + successToken, err = callCaptchaNotRobotWithSliderPOC( + ctx, + captchaErr.SessionToken, + hash, + streamID, + client, + profile, + bootstrap.Settings, + savedProfile, // Pass savedProfile if available + ) + } else { + successToken, err = callCaptchaNotRobot(ctx, captchaErr.SessionToken, hash, streamID, client, profile, savedProfile) + } + if err != nil { + return "", fmt.Errorf("captchaNotRobot API failed: %w", err) + } + + log.Printf("[STREAM %d] [Captcha] Success! Got success_token", streamID) + return successToken, nil +} + +func fetchCaptchaBootstrap(ctx context.Context, redirectURI string, client tlsclient.HttpClient, profile Profile) (*captchaBootstrap, error) { + parsedURL, err := neturl.Parse(redirectURI) + if err != nil { + return nil, err + } + domain := parsedURL.Hostname() + + req, err := fhttp.NewRequestWithContext(ctx, "GET", redirectURI, nil) + if err != nil { + return nil, err + } + + req.Host = domain + applyBrowserProfileFhttp(req, profile) + req.Header.Set("Sec-Fetch-Site", "none") + req.Header.Set("Sec-Fetch-Mode", "navigate") + req.Header.Set("Sec-Fetch-Dest", "document") + req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") + + resp, err := client.Do(req) + if err != nil { + return nil, err + } + defer func(Body io.ReadCloser) { + _ = Body.Close() + }(resp.Body) + + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return parseCaptchaBootstrapHTML(string(body)) +} + +func solvePoW(powInput string, difficulty int) string { + target := strings.Repeat("0", difficulty) + for nonce := 1; nonce <= 10000000; nonce++ { + data := powInput + strconv.Itoa(nonce) + hash := sha256.Sum256([]byte(data)) + hexHash := hex.EncodeToString(hash[:]) + if strings.HasPrefix(hexHash, target) { + return hexHash + } + } + return "" +} + +func callCaptchaNotRobot(ctx context.Context, sessionToken, hash string, streamID int, client tlsclient.HttpClient, profile Profile, savedProfile *SavedProfile) (string, error) { + vkReq := func(method string, postData string) (map[string]interface{}, error) { + reqURL := "https://api.vk.ru/method/" + method + "?v=5.131" + parsedURL, err := neturl.Parse(reqURL) + if err != nil { + return nil, fmt.Errorf("parse request URL: %w", err) + } + domain := parsedURL.Hostname() + + req, err := fhttp.NewRequestWithContext(ctx, "POST", reqURL, strings.NewReader(postData)) + if err != nil { + return nil, err + } + + req.Host = domain + applyBrowserProfileFhttp(req, profile) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "*/*") + req.Header.Set("Origin", "https://api.vk.ru") + req.Header.Set("Referer", fmt.Sprintf("https://api.vk.ru/not_robot_captcha?domain=vk.com&session_token=%s&variant=popup&blank=1", sessionToken)) + req.Header.Set("Sec-Fetch-Site", "same-origin") + req.Header.Set("Sec-Fetch-Mode", "cors") + req.Header.Set("Sec-Fetch-Dest", "empty") + + httpResp, err := client.Do(req) + if err != nil { + return nil, err + } + defer func(Body io.ReadCloser) { + _ = Body.Close() + }(httpResp.Body) + + body, err := io.ReadAll(httpResp.Body) + if err != nil { + return nil, err + } + var resp map[string]interface{} + if err := json.Unmarshal(body, &resp); err != nil { + return nil, err + } + return resp, nil + } + + adFpBytes := make([]byte, 16) + for i := range adFpBytes { + adFpBytes[i] = byte(rand.Intn(256)) + } + adFp := base64.RawURLEncoding.EncodeToString(adFpBytes)[:21] + + baseParams := fmt.Sprintf("session_token=%s&domain=vk.com&adFp=%s&access_token=", neturl.QueryEscape(sessionToken), neturl.QueryEscape(adFp)) + + log.Printf("[STREAM %d] [Captcha] Step 1/4: settings", streamID) + if _, err := vkReq("captchaNotRobot.settings", baseParams); err != nil { + return "", fmt.Errorf("settings failed: %w", err) + } + + time.Sleep(200 * time.Millisecond) + + log.Printf("[STREAM %d] [Captcha] Step 2/4: componentDone", streamID) + browserFp := generateBrowserFp(profile) + deviceJSON := buildCaptchaDeviceJSON(profile) + if savedProfile != nil { + browserFp = savedProfile.BrowserFp + deviceJSON = savedProfile.DeviceJSON + } + componentDoneData := baseParams + fmt.Sprintf("&browser_fp=%s&device=%s", browserFp, neturl.QueryEscape(deviceJSON)) + + if _, err := vkReq("captchaNotRobot.componentDone", componentDoneData); err != nil { + return "", fmt.Errorf("componentDone failed: %w", err) + } + + time.Sleep(200 * time.Millisecond) + + log.Printf("[STREAM %d] [Captcha] Step 3/4: check", streamID) + // The real browser sends an empty array for cursor on the first check. + cursorJSON := "[]" + answer := base64.StdEncoding.EncodeToString([]byte("{}")) + + // The real browser sends a static SHA-256 hash for debug_info. + // We use the exact one captured from the real browser's session. + debugInfo := "f3ef768dab7a20f574c6461f34e4257894d2a3c30a53d8727a3edaf7ab70847d" + + connectionRtt := "[250,250,250,250,250]" + connectionDownlink := "[1.45,1.45,1.45,1.45,1.45]" + + checkData := baseParams + fmt.Sprintf( + "&accelerometer=%s&gyroscope=%s&motion=%s&cursor=%s&taps=%s&connectionRtt=%s&connectionDownlink=%s&browser_fp=%s&hash=%s&answer=%s&debug_info=%s", + neturl.QueryEscape("[]"), neturl.QueryEscape("[]"), neturl.QueryEscape("[]"), + neturl.QueryEscape(cursorJSON), neturl.QueryEscape("[]"), neturl.QueryEscape(connectionRtt), + neturl.QueryEscape(connectionDownlink), + browserFp, hash, answer, debugInfo, + ) + + checkResp, err := vkReq("captchaNotRobot.check", checkData) + if err != nil { + return "", fmt.Errorf("check failed: %w", err) + } + + respObj, ok := checkResp["response"].(map[string]interface{}) + if !ok { + return "", fmt.Errorf("invalid check response: %v", checkResp) + } + status, ok := respObj["status"].(string) + if !ok || status != "OK" { + return "", fmt.Errorf("check status: %s", status) + } + successToken, ok := respObj["success_token"].(string) + if !ok || successToken == "" { + return "", fmt.Errorf("success_token not found") + } + + time.Sleep(200 * time.Millisecond) + + log.Printf("[STREAM %d] [Captcha] Step 4/4: endSession", streamID) + _, err = vkReq("captchaNotRobot.endSession", baseParams) + if err != nil { + log.Printf("[STREAM %d] [Captcha] Warning: endSession failed: %v", streamID, err) + } + + return successToken, nil +} + +// endregion + +// region VK Credentials Layer + +type VKCredentials struct { + ClientID string + ClientSecret string +} + +var vkCredentialsList = []VKCredentials{ + {ClientID: "6287487", ClientSecret: "QbYic1K3lEV5kTGiqlq2"}, // VK_WEB_APP_ID + {ClientID: "7879029", ClientSecret: "aR5NKGmm03GYrCiNKsaw"}, // VK_MVK_APP_ID + {ClientID: "52461373", ClientSecret: "o557NLIkAErNhakXrQ7A"}, // VK_WEB_VKVIDEO_APP_ID + {ClientID: "52649896", ClientSecret: "WStp4ihWG4l3nmXZgIbC"}, // VK_MVK_VKVIDEO_APP_ID + {ClientID: "51781872", ClientSecret: "IjjCNl4L4Tf5QZEXIHKK"}, // VK_ID_AUTH_APP +} + +type TurnCredentials struct { + Username string + Password string + ServerAddrs []string + ExpiresAt time.Time + Link string +} + +type StreamCredentialsCache struct { + creds TurnCredentials + mutex sync.RWMutex + errorCount atomic.Int32 + lastErrorTime atomic.Int64 +} + +const ( + credentialLifetime = 10 * time.Minute + cacheSafetyMargin = 60 * time.Second + maxCacheErrors = 3 + errorWindow = 10 * time.Second +) + +var streamsPerCache = 10 + +func getCacheID(streamID int) int { + return streamID / streamsPerCache +} + +func vkDelayRandom(minMs, maxMs int) { + ms := minMs + rand.Intn(maxMs-minMs+1) + time.Sleep(time.Duration(ms) * time.Millisecond) +} + +var credentialsStore = struct { + mu sync.RWMutex + caches map[int]*StreamCredentialsCache +}{ + caches: make(map[int]*StreamCredentialsCache), +} + +func getStreamCache(streamID int) *StreamCredentialsCache { + cacheID := getCacheID(streamID) + + credentialsStore.mu.RLock() + cache, exists := credentialsStore.caches[cacheID] + credentialsStore.mu.RUnlock() + + if exists { + return cache + } + + credentialsStore.mu.Lock() + defer credentialsStore.mu.Unlock() + + if cache, exists = credentialsStore.caches[cacheID]; exists { + return cache + } + + cache = &StreamCredentialsCache{} + credentialsStore.caches[cacheID] = cache + return cache +} + +func isAuthError(err error) bool { + if err == nil { + return false + } + errStr := err.Error() + return strings.Contains(errStr, "401") || + strings.Contains(errStr, "Unauthorized") || + strings.Contains(errStr, "authentication") || + strings.Contains(errStr, "invalid credential") || + strings.Contains(errStr, "stale nonce") +} + +func handleAuthError(streamID int) bool { + cache := getStreamCache(streamID) + cacheID := getCacheID(streamID) + + now := time.Now().Unix() + + if now-cache.lastErrorTime.Load() > int64(errorWindow.Seconds()) { + cache.errorCount.Store(0) + } + + count := cache.errorCount.Add(1) + cache.lastErrorTime.Store(now) + + log.Printf("[STREAM %d] Auth error (cache=%d, count=%d/%d)", streamID, cacheID, count, maxCacheErrors) + + if count >= maxCacheErrors { + log.Printf("[VK Auth] Multiple auth errors detected (%d), invalidating cache %d for stream %d...", count, cacheID, streamID) + cache.invalidate(streamID) + return true + } + return false +} + +func (c *StreamCredentialsCache) invalidate(streamID int) { + c.mutex.Lock() + c.creds = TurnCredentials{} + c.mutex.Unlock() + + c.errorCount.Store(0) + c.lastErrorTime.Store(0) + + log.Printf("[STREAM %d] [VK Auth] Credentials cache invalidated", streamID) +} + +func getVkCredsCached(ctx context.Context, link string, streamID int, dialer *dnsdialer.Dialer) (string, string, string, error) { + cache := getStreamCache(streamID) + cacheID := getCacheID(streamID) + + cache.mutex.RLock() + if cache.creds.Link == link && time.Now().Before(cache.creds.ExpiresAt) && len(cache.creds.ServerAddrs) > 0 { + expires := time.Until(cache.creds.ExpiresAt) + u, p := cache.creds.Username, cache.creds.Password + // Round-robin selection based on streamID + addr := cache.creds.ServerAddrs[streamID%len(cache.creds.ServerAddrs)] + cache.mutex.RUnlock() + if isDebug { + log.Printf("[STREAM %d] [VK Auth] Using cached credentials (cache=%d, expires in %v, server=%s)", streamID, cacheID, expires, addr) + } + return u, p, addr, nil + } + cache.mutex.RUnlock() + + cache.mutex.Lock() + defer cache.mutex.Unlock() + + // Double-check inside lock + if cache.creds.Link == link && time.Now().Before(cache.creds.ExpiresAt) && len(cache.creds.ServerAddrs) > 0 { + addr := cache.creds.ServerAddrs[streamID%len(cache.creds.ServerAddrs)] + return cache.creds.Username, cache.creds.Password, addr, nil + } + + user, pass, addrs, err := fetchVkCredsSerialized(ctx, link, streamID, dialer) + if err != nil { + return "", "", "", err + } + + cache.creds = TurnCredentials{Username: user, Password: pass, ServerAddrs: addrs, ExpiresAt: time.Now().Add(credentialLifetime - cacheSafetyMargin), Link: link} + addr := addrs[streamID%len(addrs)] + return user, pass, addr, nil +} + +var ( + vkRequestMu sync.Mutex + globalLastVkFetchTime time.Time +) + +func fetchVkCredsSerialized(ctx context.Context, link string, streamID int, dialer *dnsdialer.Dialer) (string, string, []string, error) { + vkRequestMu.Lock() + defer vkRequestMu.Unlock() + + // Ensure a minimum cooldown between credential requests to avoid VK rate limits + minInterval := 3*time.Second + time.Duration(rand.Intn(3000))*time.Millisecond + elapsed := time.Since(globalLastVkFetchTime) + + if !globalLastVkFetchTime.IsZero() && elapsed < minInterval { + wait := minInterval - elapsed + log.Printf("[STREAM %d] [VK Auth] Throttling: waiting %v to prevent rate limit...", streamID, wait.Truncate(time.Millisecond)) + select { + case <-ctx.Done(): + return "", "", nil, ctx.Err() + case <-time.After(wait): + } + } + + defer func() { + globalLastVkFetchTime = time.Now() + }() + + return fetchVkCreds(ctx, link, streamID, dialer) +} + +func fetchVkCreds(ctx context.Context, link string, streamID int, dialer *dnsdialer.Dialer) (string, string, []string, error) { + // Check Global Lockout to prevent API bans + if time.Now().Unix() < globalCaptchaLockout.Load() { + return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED: global lockout active") + } + + var lastErr error + jar := tlsclient.NewCookieJar() + + for _, creds := range vkCredentialsList { + log.Printf("[STREAM %d] [VK Auth] Trying credentials: client_id=%s", streamID, creds.ClientID) + + user, pass, addrs, err := getTokenChain(ctx, link, streamID, creds, dialer, jar) + + if err == nil { + log.Printf("[STREAM %d] [VK Auth] Success with client_id=%s", streamID, creds.ClientID) + return user, pass, addrs, nil + } + + lastErr = err + log.Printf("[STREAM %d] [VK Auth] Failed with client_id=%s: %v", streamID, creds.ClientID, err) + + // Hard abort on captcha/fatal conditions instead of trying next creds + if strings.Contains(err.Error(), "CAPTCHA_WAIT_REQUIRED") || strings.Contains(err.Error(), "FATAL_CAPTCHA") { + return "", "", nil, err + } + + if strings.Contains(err.Error(), "error_code:29") || strings.Contains(err.Error(), "error_code: 29") || strings.Contains(err.Error(), "Rate limit") { + log.Printf("[STREAM %d] [VK Auth] Rate limit detected, trying next credentials...", streamID) + } + } + + return "", "", nil, fmt.Errorf("all VK credentials failed: %w", lastErr) +} + +func getTokenChain(ctx context.Context, link string, streamID int, creds VKCredentials, dialer *dnsdialer.Dialer, jar tlsclient.CookieJar) (string, string, []string, error) { + profile := Profile{ + UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36", + SecChUa: `"Not(A:Brand";v="99", "Google Chrome";v="146", "Chromium";v="146"`, + SecChUaMobile: "?0", + SecChUaPlatform: `"Windows"`, + } + + client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(), + tlsclient.WithTimeoutSeconds(20), + tlsclient.WithClientProfile(profiles.Chrome_146), + tlsclient.WithCookieJar(jar), + tlsclient.WithDialer(getCustomNetDialer()), + ) + if err != nil { + return "", "", nil, fmt.Errorf("failed to initialize tls_client: %w", err) + } + + name := generateName() + escapedName := neturl.QueryEscape(name) + + log.Printf("[STREAM %d] [VK Auth] Connecting Identity - Name: %s | User-Agent: %s", streamID, name, profile.UserAgent) + + doRequest := func(data string, url string) (resp map[string]interface{}, err error) { + parsedURL, err := neturl.Parse(url) + if err != nil { + return nil, fmt.Errorf("parse request URL: %w", err) + } + domain := parsedURL.Hostname() + + req, err := fhttp.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer([]byte(data))) + if err != nil { + return nil, err + } + + req.Host = domain + applyBrowserProfileFhttp(req, profile) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + req.Header.Set("Accept", "*/*") + req.Header.Set("Origin", "https://vk.ru") + req.Header.Set("Referer", "https://vk.ru/") + req.Header.Set("Sec-Fetch-Site", "same-site") + req.Header.Set("Sec-Fetch-Mode", "cors") + req.Header.Set("Sec-Fetch-Dest", "empty") + req.Header.Set("Priority", "u=1, i") + + httpResp, err := client.Do(req) + if err != nil { + return nil, err + } + defer func() { + if closeErr := httpResp.Body.Close(); closeErr != nil { + log.Printf("close response body: %s", closeErr) + } + }() + + body, err := io.ReadAll(httpResp.Body) + if err != nil { + return nil, err + } + + err = json.Unmarshal(body, &resp) + if err != nil { + return nil, err + } + return resp, nil + } + + // Token 1 + data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s", creds.ClientID, creds.ClientSecret, creds.ClientID) + resp, err := doRequest(data, "https://login.vk.ru/?act=get_anonym_token") + if err != nil { + return "", "", nil, err + } + dataMap, ok := resp["data"].(map[string]interface{}) + if !ok { + return "", "", nil, fmt.Errorf("unexpected anon token response: %v", resp) + } + token1, ok := dataMap["access_token"].(string) + if !ok { + return "", "", nil, fmt.Errorf("missing access_token in response: %v", resp) + } + + vkDelayRandom(100, 150) + + // Token 1 -> getCallPreview + data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&fields=photo_200&access_token=%s", link, token1) + _, err = doRequest(data, "https://api.vk.ru/method/calls.getCallPreview?v=5.275&client_id="+creds.ClientID) + if err != nil { + log.Printf("[STREAM %d] [VK Auth] Warning: getCallPreview failed: %v", streamID, err) + } + + vkDelayRandom(200, 400) + + // Token 2 + data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&access_token=%s", link, escapedName, token1) + urlAddr := fmt.Sprintf("https://api.vk.ru/method/calls.getAnonymousToken?v=5.275&client_id=%s", creds.ClientID) + + var token2 string + for attempt := 0; ; attempt++ { + resp, err = doRequest(data, urlAddr) + if err != nil { + return "", "", nil, err + } + + if errObj, hasErr := resp["error"].(map[string]interface{}); hasErr { + captchaErr := ParseVkCaptchaError(errObj) + if captchaErr != nil && captchaErr.IsCaptchaError() { + solveMode, hasSolveMode := captchaSolveModeForAttempt(attempt, manualCaptcha, autoCaptchaSliderPOC) + if !hasSolveMode { + log.Printf("[STREAM %d] [Captcha] No more solve modes available (attempt %d)", streamID, attempt+1) + + // Engage global lockout to protect API + globalCaptchaLockout.Store(time.Now().Add(60 * time.Second).Unix()) + + if connectedStreams.Load() == 0 { + log.Printf("[STREAM %d] [FATAL] 0 connected streams and captcha solve modes exhausted.", streamID) + return "", "", nil, fmt.Errorf("FATAL_CAPTCHA_FAILED_NO_STREAMS") + } + + return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED") + } + + var successToken string + var captchaKey string + var solveErr error + + switch solveMode { + case captchaSolveModeAuto: + if captchaErr.SessionToken != "" && captchaErr.RedirectURI != "" { + successToken, solveErr = solveVkCaptcha(ctx, captchaErr, streamID, client, profile, false) + if solveErr != nil { + log.Printf("[STREAM %d] [Captcha] Auto captcha failed: %v", streamID, solveErr) + } + } else { + solveErr = fmt.Errorf("missing fields for auto solve") + } + case captchaSolveModeSliderPOC: + if captchaErr.SessionToken != "" && captchaErr.RedirectURI != "" { + successToken, solveErr = solveVkCaptcha(ctx, captchaErr, streamID, client, profile, true) + if solveErr != nil { + log.Printf("[STREAM %d] [Captcha] Auto captcha slider POC failed: %v", streamID, solveErr) + } + } else { + solveErr = fmt.Errorf("missing fields for slider POC auto solve") + } + case captchaSolveModeManual: + log.Printf("[STREAM %d] [Captcha] Triggering manual captcha fallback...", streamID) + // Use context.Background() so that a short deadline on the parent ctx + // (e.g. the overall auth timeout) doesn't cut the user's solve time short. + manualCtx, manualCancel := context.WithTimeout(context.Background(), 3*time.Minute) + + type manualRes struct { + token string + key string + err error + } + resCh := make(chan manualRes, 1) + + go func() { + var t, k string + var e error + if captchaErr.RedirectURI != "" { + t, e = solveCaptchaViaProxy(captchaErr.RedirectURI, dialer) + } else if captchaErr.CaptchaImg != "" { + k, e = solveCaptchaViaHTTP(captchaErr.CaptchaImg) + } else { + e = fmt.Errorf("no redirect_uri or captcha_img") + } + resCh <- manualRes{t, k, e} + }() + + select { + case res := <-resCh: + successToken = res.token + captchaKey = res.key + solveErr = res.err + // Token may be present even when err != nil (e.g. srv.Shutdown + // timed out on iSH after the token was already received). + // Treat a non-empty token as success regardless of the error. + if successToken != "" || captchaKey != "" { + if solveErr != nil { + log.Printf("[STREAM %d] [Captcha] Token received (ignoring cleanup error: %v)", streamID, solveErr) + solveErr = nil + } + log.Printf("[STREAM %d] [Captcha] Successfully got token from browser", streamID) + } else if solveErr != nil { + log.Printf("[STREAM %d] [Captcha] solveCaptchaViaProxy returned error: %v", streamID, solveErr) + } + case <-manualCtx.Done(): + if manualCtx.Err() == context.DeadlineExceeded { + solveErr = fmt.Errorf("manual captcha timed out after 3m") + } else { + solveErr = fmt.Errorf("manual captcha interrupted: %w", manualCtx.Err()) + } + } + manualCancel() + } + + // If solving failed (auto or manual) or timed out + if solveErr != nil { + log.Printf("[STREAM %d] [Captcha] %s failed (attempt %d): %v", streamID, captchaSolveModeLabel(solveMode), attempt+1, solveErr) + + nextSolveMode, hasNextSolveMode := captchaSolveModeForAttempt(attempt+1, manualCaptcha, autoCaptchaSliderPOC) + if hasNextSolveMode { + log.Printf("[STREAM %d] [Captcha] Falling back to %s...", streamID, captchaSolveModeLabel(nextSolveMode)) + continue + } + + // Engage global lockout to protect API + globalCaptchaLockout.Store(time.Now().Add(60 * time.Second).Unix()) + + // If we have 0 streams alive, this is fatal + if connectedStreams.Load() == 0 { + log.Printf("[STREAM %d] [FATAL] 0 connected streams and manual captcha failed/timed out.", streamID) + return "", "", nil, fmt.Errorf("FATAL_CAPTCHA_FAILED_NO_STREAMS") + } + + return "", "", nil, fmt.Errorf("CAPTCHA_WAIT_REQUIRED") + } + + if captchaErr.CaptchaAttempt == "0" || captchaErr.CaptchaAttempt == "" { + captchaErr.CaptchaAttempt = "1" + } + + if captchaKey != "" { + data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=%s&captcha_sid=%s&access_token=%s", + link, escapedName, neturl.QueryEscape(captchaKey), captchaErr.CaptchaSid, token1) + } else { + data = fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&name=%s&captcha_key=&captcha_sid=%s&is_sound_captcha=0&success_token=%s&captcha_ts=%s&captcha_attempt=%s&access_token=%s", + link, escapedName, captchaErr.CaptchaSid, neturl.QueryEscape(successToken), captchaErr.CaptchaTs, captchaErr.CaptchaAttempt, token1) + } + continue + } + return "", "", nil, fmt.Errorf("VK API error: %v", errObj) + } + + respMap, okLoop := resp["response"].(map[string]interface{}) + if !okLoop { + return "", "", nil, fmt.Errorf("unexpected getAnonymousToken response: %v", resp) + } + token2, okLoop = respMap["token"].(string) + if !okLoop { + return "", "", nil, fmt.Errorf("missing token in response: %v", resp) + } + break + } + + vkDelayRandom(100, 150) + + // Token 3 + sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New()) + data = fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA", neturl.QueryEscape(sessionData)) + resp, err = doRequest(data, "https://calls.okcdn.ru/fb.do") + if err != nil { + return "", "", nil, err + } + token3, ok := resp["session_key"].(string) + if !ok { + return "", "", nil, fmt.Errorf("missing session_key in response: %v", resp) + } + + vkDelayRandom(100, 150) + + // Token 4 -> TURN Creds + data = fmt.Sprintf("joinLink=%s&isVideo=false&protocolVersion=5&capabilities=2F7F&anonymToken=%s&method=vchat.joinConversationByLink&format=JSON&application_key=CGMMEJLGDIHBABABA&session_key=%s", link, token2, token3) + resp, err = doRequest(data, "https://calls.okcdn.ru/fb.do") + if err != nil { + return "", "", nil, err + } + + tsRaw, ok := resp["turn_server"].(map[string]interface{}) + if !ok { + return "", "", nil, fmt.Errorf("missing turn_server in response: %v", resp) + } + user, ok := tsRaw["username"].(string) + if !ok { + return "", "", nil, fmt.Errorf("missing username in turn_server") + } + pass, ok := tsRaw["credential"].(string) + if !ok { + return "", "", nil, fmt.Errorf("missing credential in turn_server") + } + urlsRaw, ok := tsRaw["urls"].([]interface{}) + if !ok || len(urlsRaw) == 0 { + return "", "", nil, fmt.Errorf("missing or empty urls in turn_server") + } + + log.Printf("[STREAM %d] [VK Auth] TURN urls (%d total):", streamID, len(urlsRaw)) + for i, u := range urlsRaw { + log.Printf("[STREAM %d] [VK Auth] [%d] %v", streamID, i, u) + } + + var addresses []string + for _, u := range urlsRaw { + urlStr, ok := u.(string) + if !ok { + continue + } + clean := strings.Split(urlStr, "?")[0] + address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:") + addresses = append(addresses, address) + } + + if len(addresses) == 0 { + return "", "", nil, fmt.Errorf("no valid TURN addresses found") + } + + return user, pass, addresses, nil +} + +// endregion + +func getYandexCreds(link string) (string, string, string, error) { + const telemostConfHost = "cloud-api.yandex.ru" + telemostConfPath := fmt.Sprintf("%s%s%s", "/telemost_front/v2/telemost/conferences/https%3A%2F%2Ftelemost.yandex.ru%2Fj%2F", link, "/connection?next_gen_media_platform_allowed=false") + + profile := getRandomProfile() + name := generateName() + + type ConferenceResponse struct { + URI string `json:"uri"` + RoomID string `json:"room_id"` + PeerID string `json:"peer_id"` + ClientConfiguration struct { + MediaServerURL string `json:"media_server_url"` + } `json:"client_configuration"` + Credentials string `json:"credentials"` + } + + type PartMeta struct { + Name string `json:"name"` + Role string `json:"role"` + Description string `json:"description"` + SendAudio bool `json:"sendAudio"` + SendVideo bool `json:"sendVideo"` + } + + type PartAttrs struct { + Name string `json:"name"` + Role string `json:"role"` + Description string `json:"description"` + } + + type SdkInfo struct { + Implementation string `json:"implementation"` + Version string `json:"version"` + UserAgent string `json:"userAgent"` + HwConcurrency int `json:"hwConcurrency"` + } + + type Capabilities struct { + OfferAnswerMode []string `json:"offerAnswerMode"` + InitialSubscriberOffer []string `json:"initialSubscriberOffer"` + SlotsMode []string `json:"slotsMode"` + SimulcastMode []string `json:"simulcastMode"` + SelfVadStatus []string `json:"selfVadStatus"` + DataChannelSharing []string `json:"dataChannelSharing"` + VideoEncoderConfig []string `json:"videoEncoderConfig"` + DataChannelVideoCodec []string `json:"dataChannelVideoCodec"` + BandwidthLimitationReason []string `json:"bandwidthLimitationReason"` + SdkDefaultDeviceManagement []string `json:"sdkDefaultDeviceManagement"` + JoinOrderLayout []string `json:"joinOrderLayout"` + PinLayout []string `json:"pinLayout"` + SendSelfViewVideoSlot []string `json:"sendSelfViewVideoSlot"` + ServerLayoutTransition []string `json:"serverLayoutTransition"` + SdkPublisherOptimizeBitrate []string `json:"sdkPublisherOptimizeBitrate"` + SdkNetworkLostDetection []string `json:"sdkNetworkLostDetection"` + SdkNetworkPathMonitor []string `json:"sdkNetworkPathMonitor"` + PublisherVp9 []string `json:"publisherVp9"` + SvcMode []string `json:"svcMode"` + SubscriberOfferAsyncAck []string `json:"subscriberOfferAsyncAck"` + SvcModes []string `json:"svcModes"` + ReportTelemetryModes []string `json:"reportTelemetryModes"` + KeepDefaultDevicesModes []string `json:"keepDefaultDevicesModes"` + } + + type HelloPayload struct { + ParticipantMeta PartMeta `json:"participantMeta"` + ParticipantAttributes PartAttrs `json:"participantAttributes"` + SendAudio bool `json:"sendAudio"` + SendVideo bool `json:"sendVideo"` + SendSharing bool `json:"sendSharing"` + ParticipantID string `json:"participantId"` + RoomID string `json:"roomId"` + ServiceName string `json:"serviceName"` + Credentials string `json:"credentials"` + CapabilitiesOffer Capabilities `json:"capabilitiesOffer"` + SdkInfo SdkInfo `json:"sdkInfo"` + SdkInitializationID string `json:"sdkInitializationId"` + DisablePublisher bool `json:"disablePublisher"` + DisableSubscriber bool `json:"disableSubscriber"` + DisableSubscriberAudio bool `json:"disableSubscriberAudio"` + } + + type HelloRequest struct { + UID string `json:"uid"` + Hello HelloPayload `json:"hello"` + } + + type FlexUrls []string + + type WSSResponse struct { + UID string `json:"uid"` + ServerHello struct { + RtcConfiguration struct { + IceServers []struct { + Urls FlexUrls `json:"urls"` + Username string `json:"username,omitempty"` + Credential string `json:"credential,omitempty"` + } `json:"iceServers"` + } `json:"rtcConfiguration"` + } `json:"serverHello"` + } + + type WSSAck struct { + UID string `json:"uid"` + Ack struct { + Status struct { + Code string `json:"code"` + } `json:"status"` + } `json:"ack"` + } + + type WSSData struct { + ParticipantID string + RoomID string + Credentials string + Wss string + } + + endpoint := "https://" + telemostConfHost + telemostConfPath + tr := &http.Transport{ + MaxIdleConns: 100, + MaxIdleConnsPerHost: 100, + IdleConnTimeout: 90 * time.Second, + } + client := &http.Client{ + Timeout: 20 * time.Second, + Transport: tr, + } + defer client.CloseIdleConnections() + req, err := http.NewRequest("GET", endpoint, nil) + if err != nil { + return "", "", "", err + } + + applyBrowserProfile(req, profile) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Referer", "https://telemost.yandex.ru/") + req.Header.Set("Origin", "https://telemost.yandex.ru") + req.Header.Set("Client-Instance-Id", uuid.New().String()) + + resp, err := client.Do(req) + if err != nil { + return "", "", "", err + } + defer func() { + if closeErr := resp.Body.Close(); closeErr != nil { + log.Printf("close response body: %s", closeErr) + } + }() + if resp.StatusCode != http.StatusOK { + readBody, err2 := io.ReadAll(resp.Body) + if err2 != nil { + return "", "", "", fmt.Errorf("GetConference: status=%s (failed to read body: %v)", resp.Status, err2) + } + return "", "", "", fmt.Errorf("GetConference: status=%s body=%s", resp.Status, string(readBody)) + } + + var result ConferenceResponse + if err = json.NewDecoder(resp.Body).Decode(&result); err != nil { + return "", "", "", fmt.Errorf("decode conf: %v", err) + } + data := WSSData{ + ParticipantID: result.PeerID, + RoomID: result.RoomID, + Credentials: result.Credentials, + Wss: result.ClientConfiguration.MediaServerURL, + } + h := http.Header{} + h.Set("Origin", "https://telemost.yandex.ru") + h.Set("User-Agent", profile.UserAgent) + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + dialer := websocket.Dialer{} + var conn *websocket.Conn + conn, resp, err = dialer.DialContext(ctx, data.Wss, h) + if err != nil { + if resp != nil && resp.Body != nil { + _ = resp.Body.Close() + } + return "", "", "", fmt.Errorf("ws dial: %w", err) + } + if resp != nil && resp.Body != nil { + defer func() { _ = resp.Body.Close() }() + } + defer func() { + if closeErr := conn.Close(); closeErr != nil { + log.Printf("close websocket: %s", closeErr) + } + }() + + req1 := HelloRequest{ + UID: uuid.New().String(), + Hello: HelloPayload{ + ParticipantMeta: PartMeta{ + Name: name, + Role: "SPEAKER", + Description: "", + SendAudio: false, + SendVideo: false, + }, + ParticipantAttributes: PartAttrs{ + Name: name, + Role: "SPEAKER", + Description: "", + }, + SendAudio: false, + SendVideo: false, + SendSharing: false, + + ParticipantID: data.ParticipantID, + RoomID: data.RoomID, + ServiceName: "telemost", + Credentials: data.Credentials, + SdkInfo: SdkInfo{ + Implementation: "browser", + Version: "5.15.0", + UserAgent: profile.UserAgent, + HwConcurrency: 4, + }, + SdkInitializationID: uuid.New().String(), + DisablePublisher: false, + DisableSubscriber: false, + DisableSubscriberAudio: false, + CapabilitiesOffer: Capabilities{ + OfferAnswerMode: []string{"SEPARATE"}, + InitialSubscriberOffer: []string{"ON_HELLO"}, + SlotsMode: []string{"FROM_CONTROLLER"}, + SimulcastMode: []string{"DISABLED"}, + SelfVadStatus: []string{"FROM_SERVER"}, + DataChannelSharing: []string{"TO_RTP"}, + VideoEncoderConfig: []string{"NO_CONFIG"}, + DataChannelVideoCodec: []string{"VP8"}, + BandwidthLimitationReason: []string{"BANDWIDTH_REASON_DISABLED"}, + SdkDefaultDeviceManagement: []string{"SDK_DEFAULT_DEVICE_MANAGEMENT_DISABLED"}, + JoinOrderLayout: []string{"JOIN_ORDER_LAYOUT_DISABLED"}, + PinLayout: []string{"PIN_LAYOUT_DISABLED"}, + SendSelfViewVideoSlot: []string{"SEND_SELF_VIEW_VIDEO_SLOT_DISABLED"}, + ServerLayoutTransition: []string{"SERVER_LAYOUT_TRANSITION_DISABLED"}, + SdkPublisherOptimizeBitrate: []string{"SDK_PUBLISHER_OPTIMIZE_BITRATE_DISABLED"}, + SdkNetworkLostDetection: []string{"SDK_NETWORK_LOST_DETECTION_DISABLED"}, + SdkNetworkPathMonitor: []string{"SDK_NETWORK_PATH_MONITOR_DISABLED"}, + PublisherVp9: []string{"PUBLISH_VP9_DISABLED"}, + SvcMode: []string{"SVC_MODE_DISABLED"}, + SubscriberOfferAsyncAck: []string{"SUBSCRIBER_OFFER_ASYNC_ACK_DISABLED"}, + SvcModes: []string{"FALSE"}, + ReportTelemetryModes: []string{"TRUE"}, + KeepDefaultDevicesModes: []string{"TRUE"}, + }, + }, + } + + if isDebug { + b, _ := json.MarshalIndent(req1, "", " ") + log.Printf("Sending HELLO:\n%s", string(b)) + } + + if err := conn.WriteJSON(req1); err != nil { + return "", "", "", fmt.Errorf("ws write: %w", err) + } + + if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil { + return "", "", "", fmt.Errorf("ws set read deadline: %w", err) + } + + for { + _, msg, err := conn.ReadMessage() + if err != nil { + return "", "", "", fmt.Errorf("ws read: %w", err) + } + if isDebug { + s := string(msg) + if len(s) > 800 { + s = s[:800] + "...(truncated)" + } + log.Printf("WSS recv: %s", s) + } + + var ack WSSAck + if err := json.Unmarshal(msg, &ack); err == nil && ack.Ack.Status.Code != "" { + continue + } + + var resp WSSResponse + if err := json.Unmarshal(msg, &resp); err == nil { + ice := resp.ServerHello.RtcConfiguration.IceServers + for _, s := range ice { + for _, u := range s.Urls { + if !strings.HasPrefix(u, "turn:") && !strings.HasPrefix(u, "turns:") { + continue + } + if strings.Contains(u, "transport=tcp") { + continue + } + clean := strings.Split(u, "?")[0] + address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:") + + return s.Username, s.Credential, address, nil + } + } + } + } +} + +func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.Conn, error) { + certificate, err := selfsign.GenerateSelfSigned() + if err != nil { + return nil, err + } + + select { + case handshakeSem <- struct{}{}: + defer func() { <-handshakeSem }() + case <-ctx.Done(): + return nil, ctx.Err() + } + + ctx1, cancel := context.WithTimeout(ctx, 20*time.Second) + defer cancel() + dtlsConn, err := dtls.ClientWithOptions( + conn, + peer, + dtls.WithCertificates(certificate), + dtls.WithInsecureSkipVerify(true), + dtls.WithExtendedMasterSecret(dtls.RequireExtendedMasterSecret), + dtls.WithCipherSuites(dtls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), + dtls.WithConnectionIDGenerator(dtls.OnlySendCIDGenerator()), + ) + if err != nil { + return nil, err + } + + if err := dtlsConn.HandshakeContext(ctx1); err != nil { + return nil, err + } + return dtlsConn, nil +} + +func oneDtlsConnection(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, inboundChan <-chan *UDPPacket, connchan chan<- net.PacketConn, okchan chan<- struct{}, streamID int) error { + time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond) + + dtlsctx, dtlscancel := context.WithCancel(ctx) + defer dtlscancel() + + conn1, conn2 := connutil.AsyncPacketPipe() + go func() { + for { + select { + case <-dtlsctx.Done(): + return + case connchan <- conn2: + } + } + }() + dtlsConn, err1 := dtlsFunc(dtlsctx, conn1, peer) + if err1 != nil { + return fmt.Errorf("failed to connect DTLS: %s", err1) + } + defer func() { + if closeErr := dtlsConn.Close(); closeErr != nil { + log.Printf("[STREAM %d] failed to close DTLS connection: %s", streamID, closeErr) + } + log.Printf("[STREAM %d] Closed DTLS connection\n", streamID) + }() + log.Printf("[STREAM %d] Established DTLS connection!\n", streamID) + + if okchan != nil { + go func() { + select { + case okchan <- struct{}{}: + case <-dtlsctx.Done(): + } + }() + } + + wg := sync.WaitGroup{} + wg.Add(1) + context.AfterFunc(dtlsctx, func() { + if err := dtlsConn.SetDeadline(time.Now()); err != nil { + log.Printf("[STREAM %d] Warning: SetDeadline failed: %v", streamID, err) + } + }) + + go func() { + defer dtlscancel() + for { + select { + case <-dtlsctx.Done(): + return + case pkt := <-inboundChan: + _, _ = dtlsConn.Write(pkt.Data[:pkt.N]) + packetPool.Put(pkt) + } + } + }() + + go func() { + defer wg.Done() + defer dtlscancel() + buf := make([]byte, 1600) + for { + n, err1 := dtlsConn.Read(buf) + if err1 != nil { + return + } + + // Send back to the active WG client + if peerAddr := activeLocalPeer.Load(); peerAddr != nil { + if addr, ok := peerAddr.(net.Addr); ok { + if _, err := listenConn.WriteTo(buf[:n], addr); err != nil { + log.Printf("[STREAM %d] failed to forward packet to local peer: %v", streamID, err) + } + } + } + } + }() + + wg.Wait() + if err := dtlsConn.SetDeadline(time.Time{}); err != nil { + log.Printf("[STREAM %d] Failed to clear DTLS deadline: %s", streamID, err) + } + return nil +} + +type connectedUDPConn struct { + *net.UDPConn +} + +func (c *connectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) { + return c.Write(p) +} + +type turnParams struct { + host string + port string + link string + udp bool + wrapKey []byte + getCreds getCredsFunc +} + +func oneTurnConnection(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, conn2 net.PacketConn, streamID int, c chan<- error) { + time.Sleep(time.Duration(rand.Intn(400)+100) * time.Millisecond) + var err error + defer func() { c <- err }() + user, pass, urlTarget, err1 := turnParams.getCreds(ctx, turnParams.link, streamID) + if err1 != nil { + err = fmt.Errorf("failed to get TURN credentials: %s", err1) + return + } + urlhost, urlport, err1 := net.SplitHostPort(urlTarget) + if err1 != nil { + err = fmt.Errorf("failed to parse TURN server address: %s", err1) + return + } + if turnParams.host != "" { + urlhost = turnParams.host + } + if turnParams.port != "" { + urlport = turnParams.port + } + var turnServerAddr string + turnServerAddr = net.JoinHostPort(urlhost, urlport) + turnServerUDPAddr, err1 := net.ResolveUDPAddr("udp", turnServerAddr) + if err1 != nil { + err = fmt.Errorf("failed to resolve TURN server address: %s", err1) + return + } + turnServerAddr = turnServerUDPAddr.String() + debugf("[STREAM %d] TURN server IP: %s", streamID, turnServerUDPAddr.IP) + var cfg *turn.ClientConfig + var turnConn net.PacketConn + var d net.Dialer + ctx1, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + if turnParams.udp { + conn, err2 := net.DialUDP("udp", nil, turnServerUDPAddr) // nolint: noctx + if err2 != nil { + err = fmt.Errorf("failed to connect to TURN server: %s", err2) + return + } + defer func() { + if err1 = conn.Close(); err1 != nil { + err = fmt.Errorf("failed to close TURN server connection: %s", err1) + return + } + }() + turnConn = &connectedUDPConn{conn} + } else { + conn, err2 := d.DialContext(ctx1, "tcp", turnServerAddr) + if err2 != nil { + err = fmt.Errorf("failed to connect to TURN server: %s", err2) + return + } + defer func() { + if err1 = conn.Close(); err1 != nil { + err = fmt.Errorf("failed to close TURN server connection: %s", err1) + return + } + }() + turnConn = turn.NewSTUNConn(conn) + } + var addrFamily turn.RequestedAddressFamily + if peer.IP.To4() != nil { + addrFamily = turn.RequestedAddressFamilyIPv4 + } else { + addrFamily = turn.RequestedAddressFamilyIPv6 + } + + cfg = &turn.ClientConfig{ + STUNServerAddr: turnServerAddr, + TURNServerAddr: turnServerAddr, + Conn: turnConn, + Net: newDirectNet(), + Username: user, + Password: pass, + RequestedAddressFamily: addrFamily, + LoggerFactory: logging.NewDefaultLoggerFactory(), + } + + client, err1 := turn.NewClient(cfg) + if err1 != nil { + err = fmt.Errorf("failed to create TURN client: %s", err1) + return + } + defer client.Close() + + err1 = client.Listen() + if err1 != nil { + err = fmt.Errorf("failed to listen: %s", err1) + return + } + + relayConn, err1 := client.Allocate() + if err1 != nil { + if isAuthError(err1) { + handleAuthError(streamID) + } + err = fmt.Errorf("failed to allocate: %s", err1) + return + } + + // Reset error count on successful allocation + getStreamCache(streamID).errorCount.Store(0) + + // Safely track active streams globally + connectedStreams.Add(1) + defer func() { + connectedStreams.Add(-1) + if err1 := relayConn.Close(); err1 != nil { + err = fmt.Errorf("failed to close TURN allocated connection: %s", err1) + } + }() + + if isDebug { + log.Printf("[STREAM %d] relayed-address=%s", streamID, relayConn.LocalAddr().String()) + } + + wg := sync.WaitGroup{} + wg.Add(1) + turnctx, turncancel := context.WithCancel(ctx) + stats := &throughputStats{} + go stats.logEvery(turnctx, fmt.Sprintf("[STREAM %d] TURN", streamID), "to-turn", "from-turn") + + context.AfterFunc(turnctx, func() { + if err := relayConn.SetDeadline(time.Now()); err != nil { + log.Printf("Failed to set relay deadline: %s", err) + } + // Do not set conn2 deadline (conn2 can sometimes be listenConn if direct mode is used) + }) + var internalPipeAddr atomic.Value + useWrap := len(turnParams.wrapKey) == wrapKeyLen + + go func() { + defer turncancel() + buf := make([]byte, 1600) + for { + if turnctx.Err() != nil { + return + } + n, addr1, err1 := conn2.ReadFrom(buf) + if err1 != nil { + return + } + if turnctx.Err() != nil { + return + } + + internalPipeAddr.Store(addr1) + + out := buf[:n] + if useWrap { + wrapped, wrapErr := wrapPacket(turnParams.wrapKey, out) + if wrapErr != nil { + log.Printf("[STREAM %d] WRAP failed: %v", streamID, wrapErr) + return + } + out = wrapped + } + + written, err1 := relayConn.WriteTo(out, peer) + stats.addTx(written) + if err1 != nil { + return + } + } + }() + + go func() { + defer wg.Done() + defer turncancel() + readBufLen := 1600 + if useWrap { + readBufLen += wrapNonceLen + } + buf := make([]byte, readBufLen) + plain := make([]byte, 1600) + for { + n, _, err1 := relayConn.ReadFrom(buf) + if err1 != nil { + return + } + addr1 := internalPipeAddr.Load() + if addr1 == nil { + continue + } + + if addr, ok := addr1.(net.Addr); ok { + payload := buf[:n] + if useWrap { + m, wrapErr := unwrapPacket(turnParams.wrapKey, payload, plain) + if wrapErr != nil { + log.Printf("[STREAM %d] UNWRAP failed: %v (n=%d)", streamID, wrapErr, n) + continue + } + payload = plain[:m] + } + stats.addRx(len(payload)) + if _, err := conn2.WriteTo(payload, addr); err != nil { + return + } + } + } + }() + + wg.Wait() + if err := relayConn.SetDeadline(time.Time{}); err != nil { + log.Printf("Failed to clear relay deadline: %s", err) + } +} + +func oneDtlsConnectionLoop(ctx context.Context, peer *net.UDPAddr, listenConn net.PacketConn, inboundChan <-chan *UDPPacket, connchan chan<- net.PacketConn, okchan chan<- struct{}, streamID int) { + for { + select { + case <-ctx.Done(): + return + default: + err := oneDtlsConnection(ctx, peer, listenConn, inboundChan, connchan, okchan, streamID) + if err != nil { + if time.Now().Unix() < globalCaptchaLockout.Load() && strings.Contains(err.Error(), "context deadline exceeded") { + continue + } + select { + case <-ctx.Done(): + return + case <-time.After(time.Duration(10+rand.Intn(20)) * time.Second): + } + } + } + } +} + +func oneTurnConnectionLoop(ctx context.Context, turnParams *turnParams, peer *net.UDPAddr, connchan <-chan net.PacketConn, t <-chan time.Time, streamID int) { + for { + select { + case <-ctx.Done(): + return + case conn2 := <-connchan: + select { + case <-t: + case <-ctx.Done(): + return + } + c := make(chan error) + go oneTurnConnection(ctx, turnParams, peer, conn2, streamID, c) + + if err := <-c; err != nil { + if strings.Contains(err.Error(), "FATAL_CAPTCHA") { + log.Printf("[STREAM %d] Fatal manual captcha error. Shutting down application.", streamID) + if globalAppCancel != nil { + globalAppCancel() + } + return + } + if strings.Contains(err.Error(), "CAPTCHA_WAIT_REQUIRED") { + if !strings.Contains(err.Error(), "global lockout active") { + log.Printf("[STREAM %d] Backing off for 60 seconds to avoid IP ban...", streamID) + select { + case <-ctx.Done(): + return + case <-time.After(60 * time.Second): + } + } else { + lockoutEnd := globalCaptchaLockout.Load() + sleepDuration := time.Until(time.Unix(lockoutEnd, 0)) + if sleepDuration < 0 { + sleepDuration = 5 * time.Second + } + select { + case <-ctx.Done(): + return + case <-time.After(sleepDuration): + } + } + } else { + log.Printf("[STREAM %d] %s", streamID, err) + time.Sleep(2 * time.Second) + } + } + } + } +} + +func setupGlobalResolver() { + dialer := &net.Dialer{ + Timeout: 10 * time.Second, + KeepAlive: 30 * time.Second, + } + dnsServers := []string{"77.88.8.8:53", "77.88.8.1:53", "8.8.8.8:53", "8.8.4.4:53", "1.1.1.1:53", "1.0.0.1:53"} + + net.DefaultResolver = &net.Resolver{ + PreferGo: true, + Dial: func(ctx context.Context, network, address string) (net.Conn, error) { + var lastErr error + for _, dns := range dnsServers { + conn, err := dialer.DialContext(ctx, "udp", dns) + if err == nil { + return conn, nil + } + lastErr = err + } + return nil, lastErr + }, + } +} + +func main() { + setupGlobalResolver() + ctx, cancel := context.WithCancel(context.Background()) + globalAppCancel = cancel + defer cancel() + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT) + go func() { + <-signalChan + log.Printf("Terminating...\n") + cancel() + select { + case <-signalChan: + case <-time.After(5 * time.Second): + } + log.Fatalf("Exit...\n") + }() + + host := flag.String("turn", "", "override TURN server ip") + port := flag.String("port", "", "override TURN port") + listen := flag.String("listen", "127.0.0.1:9000", "listen on ip:port") + vklink := flag.String("vk-link", "", "VK calls invite link \"https://vk.com/call/join/...\"") + yalink := flag.String("yandex-link", "", "Yandex telemost invite link \"https://telemost.yandex.ru/j/...\"") + peerAddr := flag.String("peer", "", "peer server address (host:port)") + n := flag.Int("n", 0, "connections to TURN (default 10 for VK, 1 for Yandex)") + udp := flag.Bool("udp", false, "connect to TURN with UDP") + direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE") + vlessMode := flag.Bool("vless", false, "VLESS mode: forward TCP connections (for VLESS) instead of UDP packets") + vlessBond := flag.Bool("vless-bond", false, "bond one VLESS TCP connection across all active smux sessions") + wrapMode := flag.Bool("wrap", false, "WRAP mode: ChaCha20-XOR obfuscate DTLS packets before they reach TURN ChannelData") + wrapKeyHex := flag.String("wrap-key", "", "32-byte hex-encoded shared key for -wrap (64 hex chars)") + genWrapKey := flag.Bool("gen-wrap-key", false, "print a fresh 64-character hex key for -wrap-key and exit") + streamsPerCredFlag := flag.Int("streams-per-cred", streamsPerCache, "number of TURN streams sharing one VK credential cache") + debugFlag := flag.Bool("debug", false, "enable debug logging") + manualCaptchaFlag := flag.Bool("manual-captcha", false, "skip auto captcha solving, use manual mode immediately") + captchaSolverFlag := flag.String("captcha-solver", "v2", "auto captcha solver implementation: v1|v2") + flag.Parse() + if *genWrapKey { + key, err := genWrapKeyHex() + if err != nil { + log.Panicf("%v", err) + } + fmt.Println(key) + return + } + if *peerAddr == "" { + log.Panicf("Need peer address!") + } + peer, err := net.ResolveUDPAddr("udp", *peerAddr) + if err != nil { + panic(err) + } + if (*vklink == "") == (*yalink == "") { + log.Panicf("Need either vk-link or yandex-link!") + } + if *wrapMode && *direct { + log.Panicf("-wrap requires DTLS; remove -no-dtls") + } + wrapKey, err := decodeWrapKey(*wrapMode, *wrapKeyHex) + if err != nil { + log.Panicf("%v", err) + } + if *wrapMode { + log.Printf("WRAP mode enabled: peer server must use matching -wrap-key") + } + if *streamsPerCredFlag <= 0 { + log.Panicf("-streams-per-cred must be positive") + } + streamsPerCache = *streamsPerCredFlag + + isDebug = *debugFlag + manualCaptcha = *manualCaptchaFlag + captchaSolverVersion = strings.ToLower(strings.TrimSpace(*captchaSolverFlag)) + if captchaSolverVersion != "v1" && captchaSolverVersion != "v2" { + captchaSolverVersion = "v2" + } + autoCaptchaSliderPOC = !manualCaptcha + + var link string + var getCreds getCredsFunc + if *vklink != "" { + parts := strings.Split(*vklink, "join/") + link = parts[len(parts)-1] + + dialer := dnsdialer.New( + dnsdialer.WithResolvers("77.88.8.8:53", "77.88.8.1:53", "8.8.8.8:53", "8.8.4.4:53", "1.1.1.1:53", "1.0.0.1:53"), + dnsdialer.WithStrategy(dnsdialer.Fallback{}), + dnsdialer.WithCache(100, 10*time.Hour, 10*time.Hour), + ) + + getCreds = func(ctx context.Context, s string, streamID int) (string, string, string, error) { + return getVkCredsCached(ctx, s, streamID, dialer) + } + if *n <= 0 { + *n = 10 + } + } else { + parts := strings.Split(*yalink, "j/") + link = parts[len(parts)-1] + getCreds = func(ctx context.Context, s string, streamID int) (string, string, string, error) { + return getYandexCreds(s) + } + if *n <= 0 { + *n = 1 + } + } + if idx := strings.IndexAny(link, "/?#"); idx != -1 { + link = link[:idx] + } + + params := &turnParams{ + host: *host, + port: *port, + link: link, + udp: *udp, + wrapKey: wrapKey, + getCreds: getCreds, + } + + if *vlessMode { + runVLESSMode(ctx, params, peer, *listen, *n, *vlessBond) + return + } + + listenConn, err := net.ListenPacket("udp", *listen) + if err != nil { + log.Panicf("Failed to listen: %s", err) + } + context.AfterFunc(ctx, func() { + if closeErr := listenConn.Close(); closeErr != nil { + log.Printf("Failed to close local connection: %s", closeErr) + } + }) + + numStreams := *n + if numStreams <= 0 { + numStreams = 1 + } + + // Shared Worker Pool Queue for Aggregation + inboundChan := make(chan *UDPPacket, 2000) + + go func() { + for { + pktIface := packetPool.Get() + pkt, ok := pktIface.(*UDPPacket) + if !ok { + log.Printf("packetPool returned unexpected type: %T", pktIface) + continue + } + nRead, addr, err := listenConn.ReadFrom(pkt.Data) + if err != nil { + return + } + + // Save the local WireGuard peer address + current := activeLocalPeer.Load() + if current == nil { + activeLocalPeer.Store(addr) + } else if addrStr, ok := current.(net.Addr); ok { + if addrStr.String() != addr.String() { + activeLocalPeer.Store(addr) + } + } else { + activeLocalPeer.Store(addr) + } + + pkt.N = nRead + + select { + case inboundChan <- pkt: + default: + // Drop the packet only if the global queue is completely full + packetPool.Put(pkt) + } + } + }() + + wg1 := sync.WaitGroup{} + t := time.Tick(200 * time.Millisecond) + + if *direct { + log.Panicf("Direct mode not supported with dispatcher") + } + + okchan := make(chan struct{}) + connchan := make(chan net.PacketConn) + wg1.Add(1) + go func() { + defer wg1.Done() + oneDtlsConnectionLoop(ctx, peer, listenConn, inboundChan, connchan, okchan, 1) + }() + wg1.Add(1) + go func() { + defer wg1.Done() + oneTurnConnectionLoop(ctx, params, peer, connchan, t, 1) + }() + + select { + case <-okchan: + case <-ctx.Done(): + } + + for i := 1; i < numStreams; i++ { + cchan := make(chan net.PacketConn) + wg1.Add(1) + go func(streamID int) { + defer wg1.Done() + oneDtlsConnectionLoop(ctx, peer, listenConn, inboundChan, cchan, nil, streamID) + }(i) + wg1.Add(1) + go func(streamID int) { + defer wg1.Done() + oneTurnConnectionLoop(ctx, params, peer, cchan, t, streamID) + }(i) + } + + wg1.Wait() +} + +// sessionPool manages a pool of smux sessions for round-robin TCP distribution. +type pooledSession struct { + id int + sess *smux.Session + active atomic.Int32 + opened atomic.Uint64 + closed atomic.Uint64 + toSession atomic.Uint64 + fromSession atomic.Uint64 +} + +type sessionPool struct { + mu sync.RWMutex + sessions []*pooledSession + counter atomic.Uint64 + connCounter atomic.Uint64 +} + +func (p *sessionPool) add(id int, s *smux.Session) *pooledSession { + ps := &pooledSession{id: id, sess: s} + p.mu.Lock() + p.sessions = append(p.sessions, ps) + p.mu.Unlock() + return ps +} + +func (p *sessionPool) remove(ps *pooledSession) { + p.mu.Lock() + for i, sess := range p.sessions { + if sess == ps { + p.sessions = append(p.sessions[:i], p.sessions[i+1:]...) + break + } + } + p.mu.Unlock() +} + +func (p *sessionPool) pick() *pooledSession { + p.mu.RLock() + defer p.mu.RUnlock() + n := len(p.sessions) + if n == 0 { + return nil + } + idx := (p.counter.Add(1) - 1) % uint64(n) + return p.sessions[idx] +} + +func (p *sessionPool) nextConnID() uint64 { + return p.connCounter.Add(1) +} + +func (p *sessionPool) snapshot() []*pooledSession { + p.mu.RLock() + defer p.mu.RUnlock() + out := make([]*pooledSession, 0, len(p.sessions)) + for _, ps := range p.sessions { + if !ps.sess.IsClosed() { + out = append(out, ps) + } + } + return out +} + +func (p *sessionPool) count() int { + p.mu.RLock() + defer p.mu.RUnlock() + return len(p.sessions) +} + +const ( + bondVersion = 1 + bondMagic = "VLB1" + + bondFrameData byte = 1 + bondFrameFIN byte = 2 + + bondMaxChunk = 16 * 1024 +) + +type bondFrame struct { + typ byte + seq uint64 + data []byte +} + +type bondClientLane struct { + ps *pooledSession + stream *smux.Stream + mu sync.Mutex + dead atomic.Bool +} + +func writeBondHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error { + var hdr [17]byte + copy(hdr[0:4], bondMagic) + hdr[4] = bondVersion + binary.BigEndian.PutUint64(hdr[5:13], connID) + binary.BigEndian.PutUint16(hdr[13:15], laneIndex) + binary.BigEndian.PutUint16(hdr[15:17], laneCount) + _, err := w.Write(hdr[:]) + return err +} + +func writeBondFrame(w io.Writer, typ byte, seq uint64, data []byte) error { + var hdr [13]byte + hdr[0] = typ + binary.BigEndian.PutUint64(hdr[1:9], seq) + binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) + if _, err := w.Write(hdr[:]); err != nil { + return err + } + if len(data) == 0 { + return nil + } + _, err := w.Write(data) + return err +} + +func readBondFrame(r io.Reader) (bondFrame, error) { + var hdr [13]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return bondFrame{}, err + } + size := binary.BigEndian.Uint32(hdr[9:13]) + if size > 4*1024*1024 { + return bondFrame{}, fmt.Errorf("bond frame too large: %d", size) + } + f := bondFrame{ + typ: hdr[0], + seq: binary.BigEndian.Uint64(hdr[1:9]), + } + if size > 0 { + f.data = make([]byte, size) + if _, err := io.ReadFull(r, f.data); err != nil { + return bondFrame{}, err + } + } + return f, nil +} + +func closeWrite(conn net.Conn) { + type closeWriter interface { + CloseWrite() error + } + if cw, ok := conn.(closeWriter); ok { + if err := cw.CloseWrite(); err != nil && isDebug { + log.Printf("CloseWrite failed: %v", err) + } + } +} + +func handleBondedTCP(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*pooledSession) { + defer func() { _ = tcpConn.Close() }() + + ctx, cancel := context.WithCancel(ctx) + defer cancel() + + lanes := make([]*bondClientLane, 0, len(candidates)) + laneIDs := make([]string, 0, len(candidates)) + for i, ps := range candidates { + if ps.sess.IsClosed() { + continue + } + stream, err := ps.sess.OpenStream() + if err != nil { + log.Printf("[bond %d] session %d open stream error: %s", connID, ps.id, err) + continue + } + if err := writeBondHello(stream, connID, uint16(i), uint16(len(candidates))); err != nil { + log.Printf("[bond %d] session %d hello error: %s", connID, ps.id, err) + _ = stream.Close() + continue + } + ps.opened.Add(1) + ps.active.Add(1) + lanes = append(lanes, &bondClientLane{ps: ps, stream: stream}) + laneIDs = append(laneIDs, strconv.Itoa(ps.id)) + } + + if len(lanes) == 0 { + log.Printf("[bond %d] no usable lanes, rejecting TCP from %s", connID, tcpConn.RemoteAddr()) + return + } + context.AfterFunc(ctx, func() { + now := time.Now() + if err := tcpConn.SetDeadline(now); err != nil && isDebug { + log.Printf("[bond %d] local TCP deadline error: %v", connID, err) + } + for _, lane := range lanes { + if err := lane.stream.SetDeadline(now); err != nil && isDebug { + log.Printf("[bond %d] session %d stream deadline error: %v", connID, lane.ps.id, err) + } + } + }) + + debugf("[bond %d] TCP accept from=%s lanes=%d [%s]", connID, tcpConn.RemoteAddr(), len(lanes), strings.Join(laneIDs, ",")) + defer func() { + for _, lane := range lanes { + _ = lane.stream.Close() + active := lane.ps.active.Add(-1) + closed := lane.ps.closed.Add(1) + debugf("[bond %d] lane session %d close active=%d closed=%d totals: to-session=%s from-session=%s", + connID, lane.ps.id, active, closed, + formatByteCount(lane.ps.toSession.Load()), formatByteCount(lane.ps.fromSession.Load())) + } + }() + + recvCh := make(chan bondFrame, 1024) + var readWG sync.WaitGroup + for _, lane := range lanes { + readWG.Add(1) + go func(l *bondClientLane) { + defer readWG.Done() + for { + f, err := readBondFrame(l.stream) + if err != nil { + l.dead.Store(true) + select { + case <-ctx.Done(): + default: + if err != io.EOF { + debugf("[bond %d] session %d read frame error: %v", connID, l.ps.id, err) + } + } + return + } + if f.typ == bondFrameData { + l.ps.fromSession.Add(uint64(len(f.data))) + } + select { + case recvCh <- f: + case <-ctx.Done(): + return + } + } + }(lane) + } + go func() { + readWG.Wait() + close(recvCh) + }() + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + copyTCPToBond(ctx, connID, tcpConn, lanes) + }() + go func() { + defer wg.Done() + copyBondToTCP(ctx, connID, tcpConn, recvCh) + cancel() + }() + wg.Wait() +} + +func copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.Conn, lanes []*bondClientLane) { + buf := make([]byte, bondMaxChunk) + var seq uint64 + var laneIdx uint64 + for { + n, err := tcpConn.Read(buf) + if n > 0 { + data := make([]byte, n) + copy(data, buf[:n]) + lane, writeErr := writeBondFrameToNextLane(ctx, lanes, bondFrameData, seq, data, &laneIdx) + if writeErr != nil { + log.Printf("[bond %d] write data error: %v", connID, writeErr) + return + } + lane.ps.toSession.Add(uint64(n)) + seq++ + } + if err != nil { + if isDebug && err != io.EOF { + log.Printf("[bond %d] local TCP read finished with error: %v", connID, err) + } + for _, lane := range lanes { + if lane.dead.Load() { + continue + } + lane.mu.Lock() + writeErr := writeBondFrame(lane.stream, bondFrameFIN, seq, nil) + lane.mu.Unlock() + if writeErr != nil && ctx.Err() == nil { + log.Printf("[bond %d] session %d write FIN error: %v", connID, lane.ps.id, writeErr) + } + } + debugf("[bond %d] upload finished chunks=%d", connID, seq) + return + } + select { + case <-ctx.Done(): + return + default: + } + } +} + +func writeBondFrameToNextLane(ctx context.Context, lanes []*bondClientLane, typ byte, seq uint64, data []byte, laneIdx *uint64) (*bondClientLane, error) { + for attempts := 0; attempts < len(lanes); attempts++ { + idx := *laneIdx % uint64(len(lanes)) + *laneIdx++ + lane := lanes[idx] + if lane.dead.Load() { + continue + } + lane.mu.Lock() + err := writeBondFrame(lane.stream, typ, seq, data) + lane.mu.Unlock() + if err == nil { + return lane, nil + } + lane.dead.Store(true) + if ctx.Err() != nil { + return nil, ctx.Err() + } + } + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, fmt.Errorf("no live bond lanes") +} + +func copyBondToTCP(ctx context.Context, connID uint64, tcpConn net.Conn, recvCh <-chan bondFrame) { + pending := make(map[uint64][]byte) + var expect uint64 + var finSeq *uint64 + + for { + if finSeq != nil && expect == *finSeq { + closeWrite(tcpConn) + debugf("[bond %d] download finished chunks=%d", connID, expect) + return + } + + select { + case <-ctx.Done(): + return + case f, ok := <-recvCh: + if !ok { + return + } + switch f.typ { + case bondFrameData: + pending[f.seq] = f.data + case bondFrameFIN: + v := f.seq + if finSeq == nil || v < *finSeq { + finSeq = &v + } + default: + log.Printf("[bond %d] unknown frame type %d", connID, f.typ) + return + } + + for { + data, ok := pending[expect] + if !ok { + break + } + delete(pending, expect) + if len(data) > 0 { + if _, err := tcpConn.Write(data); err != nil { + log.Printf("[bond %d] local TCP write error: %v", connID, err) + return + } + } + expect++ + } + } + } +} + +// runVLESSMode implements TCP forwarding with round-robin across N TURN sessions. +func runVLESSMode(ctx context.Context, tp *turnParams, peer *net.UDPAddr, listenAddr string, numSessions int, bond bool) { + pool := &sessionPool{} + + // Start N session maintainers with staggered startup + var wgMaint sync.WaitGroup + for i := 0; i < numSessions; i++ { + wgMaint.Add(1) + go func(id int) { + defer wgMaint.Done() + select { + case <-ctx.Done(): + return + case <-time.After(time.Duration(id) * 300 * time.Millisecond): + } + maintainVLESSSession(ctx, tp, peer, id, pool) + }(i) + } + + // Wait for at least one session + log.Printf("VLESS mode: waiting for sessions to connect (total: %d)...", numSessions) + for { + select { + case <-ctx.Done(): + wgMaint.Wait() + return + case <-time.After(100 * time.Millisecond): + } + if pool.count() > 0 { + break + } + } + + listener, err := net.Listen("tcp", listenAddr) + if err != nil { + log.Panicf("TCP listen: %s", err) + } + + wrappedListener, err := wrapISHListener(listener) + if err != nil { + log.Printf("Warning: failed to wrap listener: %v", err) + wrappedListener = listener + } + + context.AfterFunc(ctx, func() { _ = wrappedListener.Close() }) + if bond { + log.Printf("VLESS bond mode: listening on %s (striping each TCP connection across active sessions)", listenAddr) + } else { + log.Printf("VLESS mode: listening on %s (round-robin across %d sessions)", listenAddr, numSessions) + } + + var wgConn sync.WaitGroup + for { + tcpConn, err := wrappedListener.Accept() + if err != nil { + select { + case <-ctx.Done(): + wgConn.Wait() + wgMaint.Wait() + return + default: + } + log.Printf("TCP accept error: %s", err) + continue + } + + if bond { + connID := (uint64(time.Now().UnixNano()) << 16) ^ pool.nextConnID() + lanes := pool.snapshot() + if len(lanes) == 0 { + log.Printf("No active sessions, rejecting connection") + _ = tcpConn.Close() + continue + } + + wgConn.Add(1) + go func(tc net.Conn, connID uint64, lanes []*pooledSession) { + defer wgConn.Done() + handleBondedTCP(ctx, tc, connID, lanes) + }(tcpConn, connID, lanes) + continue + } + + ps := pool.pick() + if ps == nil || ps.sess.IsClosed() { + log.Printf("No active sessions, rejecting connection") + _ = tcpConn.Close() + continue + } + + connID := pool.nextConnID() + opened := ps.opened.Add(1) + active := ps.active.Add(1) + debugf("[session %d] TCP accept #%d from=%s active=%d opened=%d pool=%d", + ps.id, connID, tcpConn.RemoteAddr(), active, opened, pool.count()) + + wgConn.Add(1) + go func(tc net.Conn, ps *pooledSession, connID uint64) { + defer wgConn.Done() + defer func() { _ = tc.Close() }() + defer func() { + active := ps.active.Add(-1) + closed := ps.closed.Add(1) + debugf("[session %d] TCP close #%d active=%d closed=%d totals: to-session=%s from-session=%s", + ps.id, connID, active, closed, + formatByteCount(ps.toSession.Load()), formatByteCount(ps.fromSession.Load())) + }() + + stream, err := ps.sess.OpenStream() + if err != nil { + log.Printf("[session %d] smux open stream error for TCP #%d: %s", ps.id, connID, err) + return + } + defer func() { _ = stream.Close() }() + fromSession, toSession := pipe(ctx, tc, stream) + ps.fromSession.Add(uint64(fromSession)) + ps.toSession.Add(uint64(toSession)) + debugf("[session %d] TCP done #%d local<-session=%s local->session=%s", + ps.id, connID, formatByteCount(uint64(fromSession)), formatByteCount(uint64(toSession))) + }(tcpConn, ps, connID) + } +} + +// maintainVLESSSession keeps one TURN+DTLS+KCP+smux session alive, reconnecting on failure. +func maintainVLESSSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, id int, pool *sessionPool) { + for { + select { + case <-ctx.Done(): + return + default: + } + + smuxSess, cleanup, err := createSmuxSession(ctx, tp, peer, id) + if err != nil { + log.Printf("[session %d] setup error: %s, retrying...", id, err) + select { + case <-ctx.Done(): + return + case <-time.After(3 * time.Second): + } + continue + } + + ps := pool.add(id, smuxSess) + log.Printf("[session %d] connected (active: %d)", id, pool.count()) + + for !smuxSess.IsClosed() { + select { + case <-ctx.Done(): + pool.remove(ps) + cleanup() + return + case <-time.After(1 * time.Second): + } + } + + pool.remove(ps) + cleanup() + log.Printf("[session %d] disconnected (active: %d), reconnecting...", id, pool.count()) + + select { + case <-ctx.Done(): + return + case <-time.After(2 * time.Second): + } + } +} + +// createSmuxSession establishes a full TURN+DTLS+KCP+smux pipeline and returns +// the smux session along with a cleanup function to tear down all layers. +func createSmuxSession(ctx context.Context, tp *turnParams, peer *net.UDPAddr, id int) (*smux.Session, func(), error) { + var cleanupFns []func() + cleanup := func() { + for i := len(cleanupFns) - 1; i >= 0; i-- { + cleanupFns[i]() + } + } + + // 1. Get TURN credentials + user, pass, rawURL, err := tp.getCreds(ctx, tp.link, id) + if err != nil { + return nil, nil, fmt.Errorf("get TURN creds: %w", err) + } + urlhost, urlport, err := net.SplitHostPort(rawURL) + if err != nil { + return nil, nil, fmt.Errorf("parse TURN addr: %w", err) + } + if tp.host != "" { + urlhost = tp.host + } + if tp.port != "" { + urlport = tp.port + } + turnServerAddr := net.JoinHostPort(urlhost, urlport) + turnServerUDPAddr, err := net.ResolveUDPAddr("udp", turnServerAddr) + if err != nil { + return nil, nil, fmt.Errorf("resolve TURN addr: %w", err) + } + turnServerAddr = turnServerUDPAddr.String() + debugf("[session %d] TURN server IP: %s", id, turnServerUDPAddr.IP) + + // 2. Connect to TURN server + var turnConn net.PacketConn + ctx1, cancel1 := context.WithTimeout(ctx, 5*time.Second) + defer cancel1() + if tp.udp { + c, err1 := net.DialUDP("udp", nil, turnServerUDPAddr) + if err1 != nil { + return nil, nil, fmt.Errorf("dial TURN (udp): %w", err1) + } + cleanupFns = append(cleanupFns, func() { _ = c.Close() }) + turnConn = &connectedUDPConn{c} + } else { + var d net.Dialer + c, err1 := d.DialContext(ctx1, "tcp", turnServerAddr) + if err1 != nil { + return nil, nil, fmt.Errorf("dial TURN (tcp): %w", err1) + } + cleanupFns = append(cleanupFns, func() { _ = c.Close() }) + turnConn = turn.NewSTUNConn(c) + } + + // 3. Create TURN client and allocate relay + var addrFamily turn.RequestedAddressFamily + if peer.IP.To4() != nil { + addrFamily = turn.RequestedAddressFamilyIPv4 + } else { + addrFamily = turn.RequestedAddressFamilyIPv6 + } + cfg := &turn.ClientConfig{ + STUNServerAddr: turnServerAddr, + TURNServerAddr: turnServerAddr, + Conn: turnConn, + Net: newDirectNet(), + Username: user, + Password: pass, + RequestedAddressFamily: addrFamily, + LoggerFactory: logging.NewDefaultLoggerFactory(), + } + turnClient, err := turn.NewClient(cfg) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("create TURN client: %w", err) + } + cleanupFns = append(cleanupFns, func() { turnClient.Close() }) + if err = turnClient.Listen(); err != nil { + cleanup() + return nil, nil, fmt.Errorf("TURN listen: %w", err) + } + relayConn, err := turnClient.Allocate() + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("TURN allocate: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = relayConn.Close() }) + debugf("relayed-address=%s", relayConn.LocalAddr().String()) + + // 4. Establish DTLS over TURN relay + certificate, err := selfsign.GenerateSelfSigned() + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("generate cert: %w", err) + } + dtlsPC := &relayPacketConn{relay: relayConn, peer: peer, wrapKey: tp.wrapKey} + dtlsConn, err := dtls.ClientWithOptions(dtlsPC, peer, + dtls.WithCertificates(certificate), + dtls.WithInsecureSkipVerify(true), + dtls.WithExtendedMasterSecret(dtls.RequireExtendedMasterSecret), + dtls.WithCipherSuites(dtls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), + dtls.WithConnectionIDGenerator(dtls.OnlySendCIDGenerator()), + ) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("DTLS client create: %w", err) + } + ctx2, cancel2 := context.WithTimeout(ctx, 30*time.Second) + defer cancel2() + if err = dtlsConn.HandshakeContext(ctx2); err != nil { + _ = dtlsConn.Close() + cleanup() + return nil, nil, fmt.Errorf("DTLS handshake: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = dtlsConn.Close() }) + debugf("DTLS connection established") + + // 5. Create KCP session over DTLS + statsCtx, statsCancel := context.WithCancel(ctx) + cleanupFns = append(cleanupFns, statsCancel) + stats := &throughputStats{} + go stats.logEvery(statsCtx, fmt.Sprintf("[session %d] VLESS", id), "to-turn", "from-turn") + + kcpSess, err := tcputil.NewKCPOverDTLS(&countingConn{Conn: dtlsConn, stats: stats}, false) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("KCP session: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = kcpSess.Close() }) + debugf("KCP session established") + + // 6. Create smux client session over KCP + smuxSess, err := smux.Client(kcpSess, tcputil.DefaultSmuxConfig()) + if err != nil { + cleanup() + return nil, nil, fmt.Errorf("smux client: %w", err) + } + cleanupFns = append(cleanupFns, func() { _ = smuxSess.Close() }) + debugf("smux session established") + + return smuxSess, cleanup, nil +} + +// relayPacketConn wraps a TURN relay PacketConn to direct all writes to the peer. +type relayPacketConn struct { + relay net.PacketConn + peer net.Addr + wrapKey []byte +} + +func (r *relayPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { + if len(r.wrapKey) != wrapKeyLen { + return r.relay.ReadFrom(b) + } + buf := make([]byte, len(b)+wrapNonceLen) + n, addr, err := r.relay.ReadFrom(buf) + if err != nil { + return 0, addr, err + } + m, err := unwrapPacket(r.wrapKey, buf[:n], b) + if err != nil { + return 0, addr, err + } + return m, addr, nil +} + +func (r *relayPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) { + if len(r.wrapKey) != wrapKeyLen { + return r.relay.WriteTo(b, r.peer) + } + out, err := wrapPacket(r.wrapKey, b) + if err != nil { + return 0, err + } + if _, err = r.relay.WriteTo(out, r.peer); err != nil { + return 0, err + } + return len(b), nil +} + +func (r *relayPacketConn) Close() error { return r.relay.Close() } +func (r *relayPacketConn) LocalAddr() net.Addr { return r.relay.LocalAddr() } +func (r *relayPacketConn) SetDeadline(t time.Time) error { return r.relay.SetDeadline(t) } +func (r *relayPacketConn) SetReadDeadline(t time.Time) error { return r.relay.SetReadDeadline(t) } +func (r *relayPacketConn) SetWriteDeadline(t time.Time) error { return r.relay.SetWriteDeadline(t) } + +// pipe copies data bidirectionally between two connections. +// It returns bytes copied as c1<-c2 and c2<-c1. +func pipe(ctx context.Context, c1, c2 net.Conn) (int64, int64) { + ctx2, cancel := context.WithCancel(ctx) + context.AfterFunc(ctx2, func() { + if err := c1.SetDeadline(time.Now()); err != nil { + log.Printf("pipe: failed to set deadline c1: %v", err) + } + if err := c2.SetDeadline(time.Now()); err != nil { + log.Printf("pipe: failed to set deadline c2: %v", err) + } + }) + + var wg sync.WaitGroup + var c1FromC2 int64 + var c2FromC1 int64 + wg.Add(2) + go func() { + defer wg.Done() + defer cancel() + n, err := io.Copy(c1, c2) + c1FromC2 = n + if err != nil { + if isDebug { + log.Printf("pipe: c1<-c2 copy error: %v", err) + } + } + }() + go func() { + defer wg.Done() + defer cancel() + n, err := io.Copy(c2, c1) + c2FromC1 = n + if err != nil { + if isDebug { + log.Printf("pipe: c2<-c1 copy error: %v", err) + } + } + }() + wg.Wait() + if err := c1.SetDeadline(time.Time{}); err != nil { + if isDebug { + log.Printf("pipe: failed to reset deadline c1: %v", err) + } + } + if err := c2.SetDeadline(time.Time{}); err != nil { + if isDebug { + log.Printf("pipe: failed to reset deadline c2: %v", err) + } + } + return c1FromC2, c2FromC1 +} diff --git a/client/main_test.go b/client/main_test.go new file mode 100644 index 0000000..e0f2d77 --- /dev/null +++ b/client/main_test.go @@ -0,0 +1,61 @@ +package main + +import "testing" + +func TestCaptchaSolveModeForAttempt(t *testing.T) { + t.Parallel() + + t.Run("default flow", func(t *testing.T) { + t.Parallel() + + mode, ok := captchaSolveModeForAttempt(0, false, true) + if !ok || mode != captchaSolveModeAuto { + t.Fatalf("expected first attempt to use auto captcha, got mode=%v ok=%v", mode, ok) + } + + mode, ok = captchaSolveModeForAttempt(1, false, true) + if !ok || mode != captchaSolveModeSliderPOC { + t.Fatalf("expected second attempt to use slider POC, got mode=%v ok=%v", mode, ok) + } + + mode, ok = captchaSolveModeForAttempt(2, false, true) + if !ok || mode != captchaSolveModeManual { + t.Fatalf("expected third attempt to use manual captcha, got mode=%v ok=%v", mode, ok) + } + + if _, ok = captchaSolveModeForAttempt(3, false, true); ok { + t.Fatal("expected no fourth captcha attempt in default flow") + } + }) + + t.Run("manual only flow", func(t *testing.T) { + t.Parallel() + + mode, ok := captchaSolveModeForAttempt(0, true, true) + if !ok || mode != captchaSolveModeManual { + t.Fatalf("expected manual mode on first attempt, got mode=%v ok=%v", mode, ok) + } + + if _, ok = captchaSolveModeForAttempt(1, true, true); ok { + t.Fatal("expected only one manual captcha attempt when manual mode is forced") + } + }) + + t.Run("flow without slider poc", func(t *testing.T) { + t.Parallel() + + mode, ok := captchaSolveModeForAttempt(0, false, false) + if !ok || mode != captchaSolveModeAuto { + t.Fatalf("expected auto captcha first, got mode=%v ok=%v", mode, ok) + } + + mode, ok = captchaSolveModeForAttempt(1, false, false) + if !ok || mode != captchaSolveModeManual { + t.Fatalf("expected manual captcha second when slider POC is disabled, got mode=%v ok=%v", mode, ok) + } + + if _, ok = captchaSolveModeForAttempt(2, false, false); ok { + t.Fatal("expected only two attempts when slider POC is disabled") + } + }) +} diff --git a/client/manual_captcha.go b/client/manual_captcha.go new file mode 100644 index 0000000..410fcf8 --- /dev/null +++ b/client/manual_captcha.go @@ -0,0 +1,864 @@ +package main + +import ( + "bytes" + "compress/gzip" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net" + "net/http" + "net/http/httputil" + neturl "net/url" + "os/exec" + "regexp" + "runtime" + "strings" + "time" + + "github.com/bschaatsbergen/dnsdialer" +) + +const captchaListenPort = "8765" + +type browserCommand struct { + name string + args []string +} + +func localCaptchaOrigin() string { + return "http://localhost:" + captchaListenPort +} + +func localCaptchaListenAddrs() []string { + return []string{ + "127.0.0.1:" + captchaListenPort, + "[::1]:" + captchaListenPort, + } +} + +func localCaptchaHosts() []string { + return []string{ + "localhost:" + captchaListenPort, + "127.0.0.1:" + captchaListenPort, + "[::1]:" + captchaListenPort, + } +} + +func isLocalCaptchaHost(host string) bool { + for _, localHost := range localCaptchaHosts() { + if strings.EqualFold(host, localHost) { + return true + } + } + return false +} + +func localCaptchaURLForTarget(targetURL *neturl.URL) string { + localURL := &neturl.URL{ + Scheme: "http", + Host: "localhost:" + captchaListenPort, + Path: targetURL.Path, + RawPath: targetURL.RawPath, + RawQuery: targetURL.RawQuery, + } + if localURL.Path == "" { + localURL.Path = "/" + } + return localURL.String() +} + +func targetOrigin(targetURL *neturl.URL) string { + return targetURL.Scheme + "://" + targetURL.Host +} + +func isSafeLocalRedirectPath(raw string) bool { + if raw == "" || raw[0] != '/' { + return false + } + if len(raw) > 1 && (raw[1] == '/' || raw[1] == '\\') { + return false + } + return true +} + +func rewriteProxyRedirectLocation(raw string, targetURL *neturl.URL) (string, bool) { + if isSafeLocalRedirectPath(raw) { + return raw, true + } + + parsed, err := neturl.Parse(raw) + if err != nil { + return "", false + } + if !strings.EqualFold(parsed.Scheme, targetURL.Scheme) || !strings.EqualFold(parsed.Host, targetURL.Host) { + return "", false + } + + return localCaptchaURLForTarget(parsed), true +} + +func rewriteProxyHeaderURL(raw string, targetURL *neturl.URL) string { + if raw == "" { + return raw + } + parsed, err := neturl.Parse(raw) + if err != nil { + return raw + } + if parsed.Scheme != "http" || !isLocalCaptchaHost(parsed.Host) { + return raw + } + parsed.Scheme = targetURL.Scheme + parsed.Host = targetURL.Host + return parsed.String() +} + +func rewriteProxyRequest(req *http.Request, targetURL *neturl.URL) { + req.URL.Scheme = targetURL.Scheme + req.URL.Host = targetURL.Host + if req.URL.Path == "" { + req.URL.Path = targetURL.Path + } + req.Host = targetURL.Host + + req.Header.Del("Accept-Encoding") + req.Header.Del("TE") // Disable transfer encoding compression + for _, headerName := range []string{"Origin", "Referer"} { + if rewritten := rewriteProxyHeaderURL(req.Header.Get(headerName), targetURL); rewritten != "" { + req.Header.Set(headerName, rewritten) + } else { + req.Header.Del(headerName) + } + } +} + +func extractSuccessToken(body []byte) string { + var payload struct { + Response struct { + SuccessToken string `json:"success_token"` + } `json:"response"` + } + if err := json.Unmarshal(body, &payload); err != nil { + return "" + } + return payload.Response.SuccessToken +} + +func rewriteProxyCookies(header http.Header) { + cookies := (&http.Response{Header: header}).Cookies() + if len(cookies) == 0 { + return + } + header.Del("Set-Cookie") + for _, cookie := range cookies { + cookie.Domain = "" + cookie.Secure = false + cookie.Partitioned = false + if cookie.SameSite == http.SameSiteNoneMode || cookie.SameSite == http.SameSiteStrictMode { + cookie.SameSite = http.SameSiteLaxMode + } + header.Add("Set-Cookie", cookie.String()) + } +} + +// htmlURLAttrDoubleRe matches src/href/action attributes with double-quoted absolute or protocol-relative URLs. +var htmlURLAttrDoubleRe = regexp.MustCompile(`(?i)((?:src|href|action)\s*=\s*)"((?:https?:)?//[^"]+)"`) + +// htmlURLAttrSingleRe matches src/href/action attributes with single-quoted absolute or protocol-relative URLs. +var htmlURLAttrSingleRe = regexp.MustCompile(`(?i)((?:src|href|action)\s*=\s*)'((?:https?:)?//[^']+)'`) + +// htmlScriptContentRe matches )`) + +// htmlStyleContentRe matches )`) + +// rewriteHTMLAttrsServerSide rewrites absolute and protocol-relative URLs in src/href/action +// attributes of raw HTML. URLs matching the upstream origin are redirected to localhost; +// all other absolute URLs are routed through /generic_proxy so that cross-domain resources +// (st.vk.com, userapi.com, etc.) load correctly through the proxy. +func rewriteHTMLAttrsServerSide(html string, targetURL *neturl.URL) string { + localOrigin := localCaptchaOrigin() + upstreamOrigin := targetOrigin(targetURL) + + rewriteURL := func(rawURL string) string { + // Normalise protocol-relative URL to absolute using the upstream scheme + absURL := rawURL + if strings.HasPrefix(rawURL, "//") { + absURL = targetURL.Scheme + ":" + rawURL + } + if strings.HasPrefix(absURL, upstreamOrigin) { + return localOrigin + absURL[len(upstreamOrigin):] + } + // Already points to local proxy — leave as-is + if strings.HasPrefix(absURL, localOrigin) { + return rawURL + } + // Any other absolute URL → route through generic_proxy + return "/generic_proxy?proxy_url=" + neturl.QueryEscape(absURL) + } + + var placeholders = make(map[string]string) + + html = htmlScriptContentRe.ReplaceAllStringFunc(html, func(match string) string { + groups := htmlScriptContentRe.FindStringSubmatch(match) + if len(groups) < 4 { + return match + } + id := fmt.Sprintf("@@CONTENT_%d@@", len(placeholders)) + placeholders[id] = groups[2] + return groups[1] + id + groups[3] + }) + + html = htmlStyleContentRe.ReplaceAllStringFunc(html, func(match string) string { + groups := htmlStyleContentRe.FindStringSubmatch(match) + if len(groups) < 4 { + return match + } + id := fmt.Sprintf("@@CONTENT_%d@@", len(placeholders)) + placeholders[id] = groups[2] + return groups[1] + id + groups[3] + }) + + html = htmlURLAttrDoubleRe.ReplaceAllStringFunc(html, func(match string) string { + groups := htmlURLAttrDoubleRe.FindStringSubmatch(match) + if len(groups) < 3 { + return match + } + return groups[1] + `"` + rewriteURL(groups[2]) + `"` + }) + + html = htmlURLAttrSingleRe.ReplaceAllStringFunc(html, func(match string) string { + groups := htmlURLAttrSingleRe.FindStringSubmatch(match) + if len(groups) < 3 { + return match + } + return groups[1] + `'` + rewriteURL(groups[2]) + `'` + }) + + for id, content := range placeholders { + html = strings.Replace(html, id, content, 1) + } + + return html +} + +func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string { + localOrigin := localCaptchaOrigin() + upstreamOrigin := targetOrigin(targetURL) + + // Step 1: plain text replacement for the primary upstream origin + html = strings.ReplaceAll(html, upstreamOrigin, localOrigin) + + // Step 2: rewrite all other absolute URLs in HTML attributes server-side. + // This is critical: the browser begins downloading +`, localOrigin, upstreamOrigin) + + // Step 3: inject the client-side script as early as possible — at the opening tag + // so that XHR/fetch overrides are active before any inline +` + + bootstrap, err := parseCaptchaBootstrapHTML(html) + if err != nil { + t.Fatalf("parseCaptchaBootstrapHTML returned error: %v", err) + } + + if bootstrap.PowInput != "abc123" { + t.Fatalf("expected pow input abc123, got %q", bootstrap.PowInput) + } + if bootstrap.Difficulty != 3 { + t.Fatalf("expected difficulty 3, got %d", bootstrap.Difficulty) + } + if bootstrap.Settings == nil { + t.Fatal("expected bootstrap settings") + } + if bootstrap.Settings.ShowCaptchaType != "checkbox" { + t.Fatalf("expected show_captcha_type checkbox, got %q", bootstrap.Settings.ShowCaptchaType) + } + if bootstrap.Settings.SettingsByType["slider"] != "slider-token" { + t.Fatalf("expected slider token, got %q", bootstrap.Settings.SettingsByType["slider"]) + } +} + +func TestRenderSliderCandidateMatchesSwapLayout(t *testing.T) { + t.Parallel() + + src := image.NewRGBA(image.Rect(0, 0, 20, 20)) + fillRect(src, image.Rect(0, 0, 10, 10), color.RGBA{R: 255, A: 255}) + fillRect(src, image.Rect(10, 0, 20, 10), color.RGBA{G: 255, A: 255}) + fillRect(src, image.Rect(0, 10, 10, 20), color.RGBA{B: 255, A: 255}) + fillRect(src, image.Rect(10, 10, 20, 20), color.RGBA{R: 255, G: 255, A: 255}) + + mapping, err := buildSliderTileMapping(2, []int{0, 1}) + if err != nil { + t.Fatalf("buildSliderTileMapping returned error: %v", err) + } + + rendered, err := renderSliderCandidate(src, 2, mapping) + if err != nil { + t.Fatalf("renderSliderCandidate returned error: %v", err) + } + + assertPixelEquals(t, rendered.At(2, 2), color.RGBA{G: 255, A: 255}) + assertPixelEquals(t, rendered.At(12, 2), color.RGBA{R: 255, A: 255}) + assertPixelEquals(t, rendered.At(2, 12), color.RGBA{B: 255, A: 255}) + assertPixelEquals(t, rendered.At(12, 12), color.RGBA{R: 255, G: 255, A: 255}) +} + +func TestRankSliderCandidatesPrefersMostCoherentImage(t *testing.T) { + t.Parallel() + + src := image.NewRGBA(image.Rect(0, 0, 30, 30)) + for y := 0; y < 30; y++ { + for x := 0; x < 30; x++ { + src.Set(x, y, color.RGBA{ + R: uint8(x * 5), + G: uint8(y * 5), + B: uint8((x + y) * 3), + A: 255, + }) + } + } + + candidates, err := rankSliderCandidates(src, 3, []int{0, 1, 0, 1}) + if err != nil { + t.Fatalf("rankSliderCandidates returned error: %v", err) + } + + if len(candidates) != 2 { + t.Fatalf("expected 2 candidates, got %d", len(candidates)) + } + if candidates[0].Index != 2 { + t.Fatalf("expected solved candidate to rank first, got candidate %d", candidates[0].Index) + } +} + +func TestEncodeSliderAnswer(t *testing.T) { + t.Parallel() + + encoded, err := encodeSliderAnswer([]int{9, 10, 2}) + if err != nil { + t.Fatalf("encodeSliderAnswer returned error: %v", err) + } + + decoded, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + t.Fatalf("failed to decode answer: %v", err) + } + + var payload struct { + Value []int `json:"value"` + } + if err := json.Unmarshal(decoded, &payload); err != nil { + t.Fatalf("failed to unmarshal answer payload: %v", err) + } + + expected := []int{9, 10, 2} + if !reflect.DeepEqual(payload.Value, expected) { + t.Fatalf("expected payload %v, got %v", expected, payload.Value) + } +} + +func TestTrySliderCaptchaCandidates(t *testing.T) { + t.Parallel() + + candidates := []sliderCandidate{ + {Index: 1, ActiveSteps: []int{0, 1}, Score: 10}, + {Index: 2, ActiveSteps: []int{0, 1, 0, 1}, Score: 20}, + } + + t.Run("success on first candidate", func(t *testing.T) { + token, err := trySliderCaptchaCandidates(candidates, 2, func(candidate sliderCandidate) (*captchaCheckResult, error) { + if candidate.Index != 1 { + t.Fatalf("unexpected candidate index %d", candidate.Index) + } + return &captchaCheckResult{Status: "OK", SuccessToken: "token-1"}, nil + }) + if err != nil { + t.Fatalf("trySliderCaptchaCandidates returned error: %v", err) + } + if token != "token-1" { + t.Fatalf("expected token-1, got %s", token) + } + }) + + t.Run("success on later candidate", func(t *testing.T) { + calls := 0 + token, err := trySliderCaptchaCandidates(candidates, 2, func(candidate sliderCandidate) (*captchaCheckResult, error) { + calls++ + if candidate.Index == 1 { + return &captchaCheckResult{Status: "BOT"}, nil + } + return &captchaCheckResult{Status: "OK", SuccessToken: "token-2"}, nil + }) + if err != nil { + t.Fatalf("trySliderCaptchaCandidates returned error: %v", err) + } + if calls != 2 { + t.Fatalf("expected 2 calls, got %d", calls) + } + if token != "token-2" { + t.Fatalf("expected token-2, got %s", token) + } + }) + + t.Run("exhausted candidates", func(t *testing.T) { + _, err := trySliderCaptchaCandidates(candidates, 1, func(candidate sliderCandidate) (*captchaCheckResult, error) { + return &captchaCheckResult{Status: "BOT"}, nil + }) + if err == nil { + t.Fatal("expected error after exhausting ranked candidates") + } + }) +} + +func TestParseSliderCaptchaContentResponse(t *testing.T) { + t.Parallel() + + src := image.NewRGBA(image.Rect(0, 0, 20, 20)) + fillRect(src, src.Bounds(), color.RGBA{R: 12, G: 34, B: 56, A: 255}) + + var buf bytes.Buffer + if err := jpeg.Encode(&buf, src, nil); err != nil { + t.Fatalf("failed to encode jpeg fixture: %v", err) + } + + resp := map[string]interface{}{ + "response": map[string]interface{}{ + "status": "OK", + "extension": "jpeg", + "image": base64.StdEncoding.EncodeToString(buf.Bytes()), + "steps": []interface{}{float64(5), float64(0), float64(1), float64(2), float64(3), float64(6)}, + }, + } + + content, err := parseSliderCaptchaContentResponse(resp) + if err != nil { + t.Fatalf("parseSliderCaptchaContentResponse returned error: %v", err) + } + + if content.Size != 5 { + t.Fatalf("expected size 5, got %d", content.Size) + } + if content.Attempts != 6 { + t.Fatalf("expected attempts 6, got %d", content.Attempts) + } + if len(content.Steps) != 4 { + t.Fatalf("expected 4 swap entries, got %d", len(content.Steps)) + } +} + +func fillRect(img *image.RGBA, rect image.Rectangle, c color.Color) { + for y := rect.Min.Y; y < rect.Max.Y; y++ { + for x := rect.Min.X; x < rect.Max.X; x++ { + img.Set(x, y, c) + } + } +} + +func assertPixelEquals(t *testing.T, actual color.Color, expected color.RGBA) { + t.Helper() + + ar, ag, ab, aa := actual.RGBA() + if ar != uint32(expected.R)*0x101 || ag != uint32(expected.G)*0x101 || ab != uint32(expected.B)*0x101 || aa != uint32(expected.A)*0x101 { + t.Fatalf("expected pixel %+v, got rgba(%d,%d,%d,%d)", expected, ar, ag, ab, aa) + } +} diff --git a/client/wrap.go b/client/wrap.go new file mode 100644 index 0000000..f271e13 --- /dev/null +++ b/client/wrap.go @@ -0,0 +1,78 @@ +// SPDX-License-Identifier: MIT + +package main + +import ( + "crypto/rand" + "encoding/hex" + "errors" + "fmt" + + "golang.org/x/crypto/chacha20" +) + +const ( + wrapNonceLen = 12 + wrapKeyLen = 32 +) + +func genWrapKeyHex() (string, error) { + key := make([]byte, wrapKeyLen) + if _, err := rand.Read(key); err != nil { + return "", fmt.Errorf("wrap: key gen: %w", err) + } + return hex.EncodeToString(key), nil +} + +func decodeWrapKey(enabled bool, raw string) ([]byte, error) { + if !enabled { + return nil, nil + } + if raw == "" { + return nil, errors.New("-wrap requires -wrap-key") + } + key, err := hex.DecodeString(raw) + if err != nil { + return nil, fmt.Errorf("-wrap-key invalid hex: %w", err) + } + if len(key) != wrapKeyLen { + return nil, fmt.Errorf("-wrap-key must decode to %d bytes (got %d)", wrapKeyLen, len(key)) + } + return key, nil +} + +func wrapPacket(key, payload []byte) ([]byte, error) { + if len(key) != wrapKeyLen { + return nil, fmt.Errorf("wrap: key must be %d bytes (got %d)", wrapKeyLen, len(key)) + } + out := make([]byte, wrapNonceLen+len(payload)) + if _, err := rand.Read(out[:wrapNonceLen]); err != nil { + return nil, fmt.Errorf("wrap: nonce gen: %w", err) + } + cipher, err := chacha20.NewUnauthenticatedCipher(key, out[:wrapNonceLen]) + if err != nil { + return nil, fmt.Errorf("wrap: cipher init: %w", err) + } + cipher.XORKeyStream(out[wrapNonceLen:], payload) + return out, nil +} + +func unwrapPacket(key, wire, dst []byte) (int, error) { + if len(key) != wrapKeyLen { + return 0, fmt.Errorf("wrap: key must be %d bytes (got %d)", wrapKeyLen, len(key)) + } + if len(wire) < wrapNonceLen { + return 0, errors.New("wrap: short packet (no nonce)") + } + nonce := wire[:wrapNonceLen] + ciphertext := wire[wrapNonceLen:] + if len(ciphertext) > len(dst) { + return 0, errors.New("wrap: dst buffer too small") + } + cipher, err := chacha20.NewUnauthenticatedCipher(key, nonce) + if err != nil { + return 0, fmt.Errorf("wrap: cipher init: %w", err) + } + cipher.XORKeyStream(dst[:len(ciphertext)], ciphertext) + return len(ciphertext), nil +} diff --git a/client/wrap_test.go b/client/wrap_test.go new file mode 100644 index 0000000..8a0162d --- /dev/null +++ b/client/wrap_test.go @@ -0,0 +1,66 @@ +package main + +import ( + "bytes" + "strings" + "testing" +) + +func TestWrapPacketRoundTrip(t *testing.T) { + key := bytes.Repeat([]byte{0x42}, wrapKeyLen) + payload := []byte("dtls record bytes") + + wire, err := wrapPacket(key, payload) + if err != nil { + t.Fatalf("wrapPacket returned error: %v", err) + } + if len(wire) != len(payload)+wrapNonceLen { + t.Fatalf("wire len = %d, want %d", len(wire), len(payload)+wrapNonceLen) + } + if bytes.Contains(wire, payload) { + t.Fatalf("wrapped packet contains plaintext payload") + } + + dst := make([]byte, len(payload)) + n, err := unwrapPacket(key, wire, dst) + if err != nil { + t.Fatalf("unwrapPacket returned error: %v", err) + } + if n != len(payload) { + t.Fatalf("unwrapped len = %d, want %d", n, len(payload)) + } + if !bytes.Equal(dst[:n], payload) { + t.Fatalf("round trip mismatch: got %q want %q", dst[:n], payload) + } +} + +func TestDecodeWrapKeyRequiresValidKeyWhenEnabled(t *testing.T) { + if key, err := decodeWrapKey(false, ""); err != nil || key != nil { + t.Fatalf("disabled decodeWrapKey = (%v, %v), want (nil, nil)", key, err) + } + + if _, err := decodeWrapKey(true, ""); err == nil { + t.Fatalf("decodeWrapKey accepted empty key") + } + + shortHex := strings.Repeat("ab", wrapKeyLen-1) + if _, err := decodeWrapKey(true, shortHex); err == nil { + t.Fatalf("decodeWrapKey accepted short key") + } + + fullHex := strings.Repeat("ab", wrapKeyLen) + key, err := decodeWrapKey(true, fullHex) + if err != nil { + t.Fatalf("decodeWrapKey returned error: %v", err) + } + if len(key) != wrapKeyLen { + t.Fatalf("decoded key len = %d, want %d", len(key), wrapKeyLen) + } +} + +func TestUnwrapPacketRejectsShortPacket(t *testing.T) { + key := bytes.Repeat([]byte{0x42}, wrapKeyLen) + if _, err := unwrapPacket(key, []byte("short"), make([]byte, 16)); err == nil { + t.Fatalf("unwrapPacket accepted short packet") + } +} diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh new file mode 100644 index 0000000..521dc00 --- /dev/null +++ b/docker-entrypoint.sh @@ -0,0 +1,25 @@ +#!/bin/sh +set -e + +CONNECT="${CONNECT_ADDR:?CONNECT_ADDR is required}" +LISTEN="${LISTEN_ADDR:-0.0.0.0:56000}" + +VLESS_FLAG="" +if [ "${VLESS_MODE}" = "true" ]; then + VLESS_FLAG="-vless" +fi + +BOND_FLAG="" +if [ "${VLESS_BOND}" = "true" ]; then + BOND_FLAG="-vless-bond" +fi + +WRAP_FLAG="" +WRAP_KEY_FLAG="" +if [ "${WRAP_MODE}" = "true" ]; then + WRAP="${WRAP_KEY:?WRAP_KEY is required when WRAP_MODE=true}" + WRAP_FLAG="-wrap" + WRAP_KEY_FLAG="-wrap-key $WRAP" +fi + +exec ./vk-turn-proxy -listen "$LISTEN" -connect "$CONNECT" $VLESS_FLAG $BOND_FLAG $WRAP_FLAG $WRAP_KEY_FLAG diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..e6e5929 --- /dev/null +++ b/go.mod @@ -0,0 +1,51 @@ +module github.com/cacggghp/vk-turn-proxy + +go 1.25.5 + +require ( + github.com/bogdanfinn/fhttp v0.6.8 + github.com/bogdanfinn/tls-client v1.14.0 + github.com/bschaatsbergen/dnsdialer v0.0.0-20251225104348-3e7610e8ea45 + github.com/cbeuw/connutil v1.0.1 + github.com/google/uuid v1.6.0 + github.com/gorilla/websocket v1.5.3 + github.com/pion/dtls/v3 v3.1.2 + github.com/pion/logging v0.2.4 + github.com/pion/transport/v4 v4.0.1 + github.com/pion/turn/v5 v5.0.3 + github.com/xtaci/kcp-go/v5 v5.6.18 + github.com/xtaci/smux v1.5.34 +) + +require ( + github.com/andybalholm/brotli v1.2.1 // indirect + github.com/bdandy/go-errors v1.2.2 // indirect + github.com/bdandy/go-socks4 v1.2.3 // indirect + github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect + github.com/bogdanfinn/utls v1.7.7-barnius // indirect + github.com/bogdanfinn/websocket v1.5.5-barnius // indirect + github.com/google/go-cmp v0.7.0 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/klauspost/compress v1.18.5 // indirect + github.com/klauspost/cpuid/v2 v2.2.9 // indirect + github.com/klauspost/reedsolomon v1.12.4 // indirect + github.com/miekg/dns v1.1.72 // indirect + github.com/pion/randutil v0.1.0 // indirect + github.com/pion/stun/v3 v3.1.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect + github.com/templexxx/cpu v0.1.1 // indirect + github.com/templexxx/xorsimd v0.4.3 // indirect + github.com/tjfoc/gmsm v1.4.1 // indirect + github.com/wlynxg/anet v0.0.5 // indirect + golang.org/x/crypto v0.49.0 // indirect + golang.org/x/mod v0.34.0 // indirect + golang.org/x/net v0.52.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.43.0 // indirect + golang.org/x/text v0.35.0 // indirect + golang.org/x/tools v0.43.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d // indirect + google.golang.org/grpc v1.80.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..aef2d97 --- /dev/null +++ b/go.sum @@ -0,0 +1,176 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro= +github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11Q= +github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= +github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= +github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI= +github.com/bogdanfinn/fhttp v0.6.8 h1:LiQyHOY3i0QoxxNB7nq27/nGNNbtPj0fuBPozhR7Ws4= +github.com/bogdanfinn/fhttp v0.6.8/go.mod h1:A+EKDzMx2hb4IUbMx4TlkoHnaJEiLl8r/1Ss1Y+5e5M= +github.com/bogdanfinn/quic-go-utls v1.0.9-utls h1:tV6eDEiRbRCcepALSzxR94JUVD3N3ACIiRLgyc2Ep8s= +github.com/bogdanfinn/quic-go-utls v1.0.9-utls/go.mod h1:aHph9B9H9yPOt5xnhWKSOum27DJAqpiHzwX+gjvaXcg= +github.com/bogdanfinn/tls-client v1.14.0 h1:vyk7Cn4BIvLAGVuMfb0tP22OqogfO1lYamquQNEZU1A= +github.com/bogdanfinn/tls-client v1.14.0/go.mod h1:LsU6mXVn8MOFDwTkyRfI7V1BZM1p0wf2ZfZsICW/1fM= +github.com/bogdanfinn/utls v1.7.7-barnius h1:OuJ497cc7F3yKNVHRsYPQdGggmk5x6+V5ZlrCR7fOLU= +github.com/bogdanfinn/utls v1.7.7-barnius/go.mod h1:aAK1VZQlpKZClF1WEQeq6kyclbkPq4hz6xTbB5xSlmg= +github.com/bogdanfinn/websocket v1.5.5-barnius h1:bY+qnxpai1qe7Jmjx+Sds/cmOSpuuLoR8x61rWltjOI= +github.com/bogdanfinn/websocket v1.5.5-barnius/go.mod h1:gvvEw6pTKHb7yOiFvIfAFTStQWyrm25BMVCTj5wRSsI= +github.com/bschaatsbergen/dnsdialer v0.0.0-20251225104348-3e7610e8ea45 h1:0b2i5TvZm8FVcuHP1288k+DEu1XM26DtRjcidOxpGXs= +github.com/bschaatsbergen/dnsdialer v0.0.0-20251225104348-3e7610e8ea45/go.mod h1:NU7MdmhQD8Ounc0760w90fL6nxI2lxjlnIaN6qWzNIU= +github.com/cbeuw/connutil v1.0.1 h1:LWuNYjwm7JEDYG/ISAO1TfU4G+q2dA5NhR97eq2roCA= +github.com/cbeuw/connutil v1.0.1/go.mod h1:lKofNtrW7Atmosgp1eNnTt2j2NjA2IkifapgLVI1QtA= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= +github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= +github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= +github.com/klauspost/cpuid/v2 v2.2.9/go.mod h1:rqkxqrZ1EhYM9G+hXH7YdowN5R5RGN6NK4QwQ3WMXF8= +github.com/klauspost/reedsolomon v1.12.4 h1:5aDr3ZGoJbgu/8+j45KtUJxzYm8k08JGtB9Wx1VQ4OA= +github.com/klauspost/reedsolomon v1.12.4/go.mod h1:d3CzOMOt0JXGIFZm1StgkyF14EYr3xneR2rNWo7NcMU= +github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI= +github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs= +github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc= +github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo= +github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8= +github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so= +github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA= +github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8= +github.com/pion/stun/v3 v3.1.2 h1:86IhD8wFn6IDW4b1/0QzoQS+f5PeA8OHHRn8UZW5ErY= +github.com/pion/stun/v3 v3.1.2/go.mod h1:H7gDic7nNwlUL05pbs6T1dtaBehh/KjupxfWw3ZI7cA= +github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o= +github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM= +github.com/pion/turn/v5 v5.0.3 h1:I+Nw0fQgdPWF1SXDj0egWDhCkcff7gWiigdQpOK52Ak= +github.com/pion/turn/v5 v5.0.3/go.mod h1:fs4SogUh/aRGQzonc4Lx3Jp4EU3j3t0PfNDEd9KcD/w= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 h1:YqAladjX7xpA6BM04leXMWAEjS0mTZ5kUU9KRBriQJc= +github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5/go.mod h1:2JjD2zLQYH5HO74y5+aE3remJQvl6q4Sn6aWA2wD1Ng= +github.com/templexxx/cpu v0.1.1 h1:isxHaxBXpYFWnk2DReuKkigaZyrjs2+9ypIdGP4h+HI= +github.com/templexxx/cpu v0.1.1/go.mod h1:w7Tb+7qgcAlIyX4NhLuDKt78AHA5SzPmq0Wj6HiEnnk= +github.com/templexxx/xorsimd v0.4.3 h1:9AQTFHd7Bhk3dIT7Al2XeBX5DWOvsUPZCuhyAtNbHjU= +github.com/templexxx/xorsimd v0.4.3/go.mod h1:oZQcD6RFDisW2Am58dSAGwwL6rHjbzrlu25VDqfWkQg= +github.com/tjfoc/gmsm v1.4.1 h1:aMe1GlZb+0bLjn+cKTPEvvn9oUEBlJitaZiiBwsbgho= +github.com/tjfoc/gmsm v1.4.1/go.mod h1:j4INPkHWMrhJb38G+J6W4Tw0AbuN8Thu3PbdVYhVcTE= +github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU= +github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA= +github.com/xtaci/kcp-go/v5 v5.6.18 h1:7oV4mc272pcnn39/13BB11Bx7hJM4ogMIEokJYVWn4g= +github.com/xtaci/kcp-go/v5 v5.6.18/go.mod h1:75S1AKYYzNUSXIv30h+jPKJYZUwqpfvLshu63nCNSOM= +github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae h1:J0GxkO96kL4WF+AIT3M4mfUVinOCPgf2uUWYFUzN0sM= +github.com/xtaci/lossyconn v0.0.0-20190602105132-8df528c0c9ae/go.mod h1:gXtu8J62kEgmN++bm9BVICuT/e8yiLI2KFobd/TRFsE= +github.com/xtaci/smux v1.5.34 h1:OUA9JaDFHJDT8ZT3ebwLWPAgEfE6sWo2LaTy3anXqwg= +github.com/xtaci/smux v1.5.34/go.mod h1:OMlQbT5vcgl2gb49mFkYo6SMf+zP3rcjcwQz7ZU7IGY= +github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZqKjWU= +github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= +go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= +go.uber.org/mock v0.5.2/go.mod h1:wLlUxC2vVTPTaE3UD51E0BGOAElKrILxhVSDYQLld5o= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201012173705-84dcc777aaee/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.49.0 h1:+Ng2ULVvLHnJ/ZFEq4KdcDd/cfjrrjjNSXNzxg0Y4U4= +golang.org/x/crypto v0.49.0/go.mod h1:ErX4dUh2UM+CFYiXZRTcMpEcN8b/1gxEuv3nODoYtCA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.34.0 h1:xIHgNUUnW6sYkcM5Jleh05DvLOtwc6RitGHbDk4akRI= +golang.org/x/mod v0.34.0/go.mod h1:ykgH52iCZe79kzLLMhyCUzhMci+nQj+0XkbXpNYtVjY= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20211104170005-ce137452f963/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0= +golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI= +golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.35.0 h1:JOVx6vVDFokkpaq1AEptVzLTpDe9KGpj5tR4/X+ybL8= +golang.org/x/text v0.35.0/go.mod h1:khi/HExzZJ2pGnjenulevKNX1W67CUy0AsXcNubPGCA= +golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI= +golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.43.0 h1:12BdW9CeB3Z+J/I/wj34VMl8X+fEXBxVR90JeMX5E7s= +golang.org/x/tools v0.43.0/go.mod h1:uHkMso649BX2cZK6+RpuIPXS3ho2hZo4FVwfoy1vIk0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d h1:wT2n40TBqFY6wiwazVK9/iTWbsQrgk5ZfCSVFLO9LQA= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260406210006-6f92a3bedf2d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM= +google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/routes-macos.sh b/routes-macos.sh new file mode 100644 index 0000000..8a09471 --- /dev/null +++ b/routes-macos.sh @@ -0,0 +1,43 @@ +#!/bin/zsh +set -u + +default_info="$(route -n get default 2>/dev/null || true)" +default_if="$(printf '%s\n' "$default_info" | awk '/interface:/{print $2; exit}')" +gateway="$(printf '%s\n' "$default_info" | awk '/gateway:/{print $2; exit}')" + +if [[ -n "${default_if:-}" && "$default_if" == utun* ]]; then + echo "Default route is currently $default_if. Disconnect WireGuard/VPN first." >&2 + exit 1 +fi + +if [[ -z "${gateway:-}" ]]; then + echo "Could not determine normal default gateway." >&2 + exit 1 +fi + +while IFS= read -r line; do + line="${line//$'\r'/}" + + # Try to extract: + # - plain IPv4 + # - IPv4/CIDR + # - relayed-address=IPv4:port -> use only IPv4 + remote="$(printf '%s\n' "$line" | sed -nE ' + s/.*relayed-address=(([0-9]{1,3}\.){3}[0-9]{1,3}):[0-9]+.*/\1/p + t done + s/^(([0-9]{1,3}\.){3}[0-9]{1,3}\/[0-9]{1,2})$/\1/p + t done + s/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/\1/p + :done + ')" + + [[ -z "$remote" ]] && continue + + if [[ "$remote" == */* ]]; then + sudo route -n delete -net "$remote" >/dev/null 2>&1 || true + sudo route -n add -net "$remote" "$gateway" || true + else + sudo route -n delete -host "$remote" >/dev/null 2>&1 || true + sudo route -n add -host "$remote" "$gateway" || true + fi +done diff --git a/routes.ps1 b/routes.ps1 new file mode 100644 index 0000000..0e34b6c --- /dev/null +++ b/routes.ps1 @@ -0,0 +1,48 @@ +# Получаем default gateway (IPv4) +$gateway = Get-NetRoute ` + -DestinationPrefix "0.0.0.0/0" ` + | Sort-Object RouteMetric ` + | Select-Object -First 1 -ExpandProperty NextHop + +if (-not $gateway) { + Write-Error "Не удалось определить default gateway" + exit 1 +} + +Write-Host "Default gateway: $gateway" + +# Читаем адреса из stdin +$input | ForEach-Object { + $addr = $_.Trim() + if ($addr -eq "") { return } + + if ($addr -notmatch '^\d{1,3}(\.\d{1,3}){3}$') { + Write-Warning "Пропускаем неожиданный ввод: $addr" + return + } + + $prefix = "$addr/32" + $existingRoutes = @(Get-NetRoute ` + -DestinationPrefix $prefix ` + -PolicyStore ActiveStore ` + -ErrorAction SilentlyContinue) + + if ($existingRoutes | Where-Object { $_.NextHop -eq $gateway }) { + Write-Host "Маршрут к $addr через $gateway уже существует" + return + } + + if ($existingRoutes.Count -gt 0) { + Write-Host "Обновляем маршрут к $addr через $gateway" + $existingRoutes | Remove-NetRoute -Confirm:$false -ErrorAction Stop + } else { + Write-Host "Добавляем маршрут к $addr через $gateway" + } + + New-NetRoute ` + -DestinationPrefix $prefix ` + -NextHop $gateway ` + -PolicyStore ActiveStore ` + -ErrorAction Stop | Out-Null +} + diff --git a/routes.sh b/routes.sh new file mode 100644 index 0000000..d660e9c --- /dev/null +++ b/routes.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -euo pipefail + +gateway="$(ip -o -4 route show to default | awk '/via/ {print $3}' | head -1)" +if [[ -z "${gateway}" ]]; then + echo "Could not determine default gateway" >&2 + exit 1 +fi + +ip_cmd=(ip) +if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then + ip_cmd=(sudo ip) +fi + +while IFS= read -r remote; do + remote="${remote%$'\r'}" + [[ -z "$remote" ]] && continue + + if [[ ! "$remote" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then + echo "Skipping unexpected input: $remote" >&2 + continue + fi + + echo "Ensuring route to $remote via $gateway" + "${ip_cmd[@]}" route replace "$remote" via "$gateway" +done diff --git a/server/main.go b/server/main.go new file mode 100644 index 0000000..1ff83f4 --- /dev/null +++ b/server/main.go @@ -0,0 +1,953 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/binary" + "encoding/hex" + "flag" + "fmt" + "io" + "log" + "net" + "os" + "os/signal" + "sync" + "sync/atomic" + "syscall" + "time" + + "github.com/cacggghp/vk-turn-proxy/tcputil" + "github.com/pion/dtls/v3" + "github.com/pion/dtls/v3/pkg/crypto/selfsign" + "github.com/xtaci/smux" +) + +var isDebug bool + +func debugf(format string, v ...any) { + if isDebug { + log.Printf(format, v...) + } +} + +func main() { + listen := flag.String("listen", "0.0.0.0:56000", "listen on ip:port") + connect := flag.String("connect", "", "connect to ip:port") + vlessMode := flag.Bool("vless", false, "VLESS mode: forward TCP connections (for VLESS) instead of UDP packets") + vlessBond := flag.Bool("vless-bond", false, "bond one VLESS TCP connection across all active smux sessions") + wrapMode := flag.Bool("wrap", false, "WRAP mode: ChaCha20-XOR obfuscate DTLS packets before they reach TURN ChannelData") + wrapKeyHex := flag.String("wrap-key", "", "32-byte hex-encoded shared key for -wrap (64 hex chars)") + genWrapKey := flag.Bool("gen-wrap-key", false, "print a fresh 64-character hex key for -wrap-key and exit") + debugFlag := flag.Bool("debug", false, "enable debug logging") + flag.Parse() + isDebug = *debugFlag + + if *genWrapKey { + key := make([]byte, wrapKeyLen) + if _, err := rand.Read(key); err != nil { + log.Panicf("gen-wrap-key: rand.Read: %v", err) + } + fmt.Println(hex.EncodeToString(key)) + return + } + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + signalChan := make(chan os.Signal, 1) + signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT) + go func() { + <-signalChan + log.Printf("Terminating...\n") + cancel() + <-signalChan + log.Fatalf("Exit...\n") + }() + + addr, err := net.ResolveUDPAddr("udp", *listen) + if err != nil { + panic(err) + } + if len(*connect) == 0 { + log.Panicf("server address is required") + } + var wrapKey []byte + if *wrapMode { + if *wrapKeyHex == "" { + log.Panicf("-wrap requires -wrap-key") + } + wrapKey, err = hex.DecodeString(*wrapKeyHex) + if err != nil { + log.Panicf("-wrap-key invalid hex: %v", err) + } + if len(wrapKey) != wrapKeyLen { + log.Panicf("-wrap-key must decode to %d bytes (got %d)", wrapKeyLen, len(wrapKey)) + } + } + log.Printf("Starting server listen=%s connect=%s vless=%t vless-bond=%t wrap=%t bond-autodetect=true", *listen, *connect, *vlessMode, *vlessBond, *wrapMode) + // Generate a certificate and private key to secure the connection + certificate, genErr := selfsign.GenerateSelfSigned() + if genErr != nil { + panic(genErr) + } + + // + // Everything below is the pion-DTLS API! Thanks for using it ❤️. + // + + dtlsOpts := []dtls.ServerOption{ + dtls.WithCertificates(certificate), + dtls.WithExtendedMasterSecret(dtls.RequireExtendedMasterSecret), + dtls.WithCipherSuites(dtls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), + dtls.WithConnectionIDGenerator(dtls.RandomCIDGenerator(8)), + } + var listener net.Listener + if *wrapMode { + log.Printf("WRAP mode enabled: listener only accepts clients with matching -wrap-key") + wrapListener, werr := listenWrapped(addr, wrapKey) + if werr != nil { + panic(werr) + } + listener, err = dtls.NewListenerWithOptions(wrapListener, dtlsOpts...) + } else { + listener, err = dtls.ListenWithOptions("udp", addr, dtlsOpts...) + } + if err != nil { + panic(err) + } + context.AfterFunc(ctx, func() { + if err = listener.Close(); err != nil { + panic(err) + } + }) + + fmt.Println("Listening") + + wg1 := sync.WaitGroup{} + for { + select { + case <-ctx.Done(): + wg1.Wait() + return + default: + } + // Wait for a connection. + conn, err := listener.Accept() + if err != nil { + log.Println(err) + continue + } + wg1.Add(1) + go func(conn net.Conn) { + defer wg1.Done() + defer func() { + if closeErr := conn.Close(); closeErr != nil { + log.Printf("failed to close incoming connection: %s", closeErr) + } + }() + debugf("Connection from %s\n", conn.RemoteAddr()) + + // Perform the handshake with a 30-second timeout + ctx1, cancel1 := context.WithTimeout(ctx, 30*time.Second) + defer cancel1() + + dtlsConn, ok := conn.(*dtls.Conn) + if !ok { + log.Println("Type error: expected *dtls.Conn") + return + } + debugf("Start handshake") + if err := dtlsConn.HandshakeContext(ctx1); err != nil { + log.Printf("Handshake failed: %v", err) + return + } + debugf("Handshake done") + + if *vlessMode { + handleVLESSConnection(ctx, dtlsConn, *connect, *vlessBond) + } else { + handleUDPConnection(ctx, conn, *connect) + } + + debugf("Connection closed: %s\n", conn.RemoteAddr()) + }(conn) + } +} + +type throughputStats struct { + tx atomic.Uint64 + rx atomic.Uint64 +} + +func (s *throughputStats) addTx(n int) { + if n > 0 { + s.tx.Add(uint64(n)) + } +} + +func (s *throughputStats) addRx(n int) { + if n > 0 { + s.rx.Add(uint64(n)) + } +} + +func (s *throughputStats) logEvery(ctx context.Context, label, txName, rxName string) { + if !isDebug { + return + } + + ticker := time.NewTicker(5 * time.Second) + defer ticker.Stop() + + var prevTx, prevRx uint64 + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + tx := s.tx.Load() + rx := s.rx.Load() + deltaTx := tx - prevTx + deltaRx := rx - prevRx + prevTx = tx + prevRx = rx + + if deltaTx == 0 && deltaRx == 0 { + continue + } + + debugf( + "%s throughput: %s=%s %s=%s total_%s=%s total_%s=%s", + label, + txName, + formatBitsPerSecond(deltaTx, 5*time.Second), + rxName, + formatBitsPerSecond(deltaRx, 5*time.Second), + txName, + formatByteCount(tx), + rxName, + formatByteCount(rx), + ) + } + } +} + +func formatBitsPerSecond(bytes uint64, interval time.Duration) string { + if interval <= 0 { + interval = time.Second + } + + bps := float64(bytes*8) / interval.Seconds() + if bps >= 1_000_000 { + return fmt.Sprintf("%.2f Mbit/s", bps/1_000_000) + } + if bps >= 1_000 { + return fmt.Sprintf("%.1f kbit/s", bps/1_000) + } + return fmt.Sprintf("%.0f bit/s", bps) +} + +func formatByteCount(bytes uint64) string { + if bytes >= 1024*1024 { + return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024)) + } + if bytes >= 1024 { + return fmt.Sprintf("%.1f KiB", float64(bytes)/1024) + } + return fmt.Sprintf("%d B", bytes) +} + +type countingConn struct { + net.Conn + stats *throughputStats +} + +func (c *countingConn) Read(p []byte) (int, error) { + n, err := c.Conn.Read(p) + c.stats.addRx(n) + return n, err +} + +func (c *countingConn) Write(p []byte) (int, error) { + n, err := c.Conn.Write(p) + c.stats.addTx(n) + return n, err +} + +const ( + bondVersion = 1 + bondMagic = "VLB1" + + bondFrameData byte = 1 + bondFrameFIN byte = 2 + + bondMaxChunk = 16 * 1024 + + bondLaneAttachTimeout = 300 * time.Millisecond +) + +type bondHello struct { + connID uint64 + laneIndex uint16 + laneCount uint16 +} + +type bondFrame struct { + typ byte + seq uint64 + data []byte +} + +func readBondHelloAfterMagic(r io.Reader, magic [4]byte) (bondHello, error) { + var hdr [17]byte + copy(hdr[0:4], magic[:]) + if _, err := io.ReadFull(r, hdr[4:]); err != nil { + return bondHello{}, err + } + return parseBondHelloHeader(hdr[:]) +} + +func parseBondHelloHeader(hdr []byte) (bondHello, error) { + if len(hdr) != 17 { + return bondHello{}, fmt.Errorf("bad bond hello size: %d", len(hdr)) + } + if string(hdr[0:4]) != bondMagic { + return bondHello{}, fmt.Errorf("bad bond magic") + } + if hdr[4] != bondVersion { + return bondHello{}, fmt.Errorf("unsupported bond version: %d", hdr[4]) + } + return bondHello{ + connID: binary.BigEndian.Uint64(hdr[5:13]), + laneIndex: binary.BigEndian.Uint16(hdr[13:15]), + laneCount: binary.BigEndian.Uint16(hdr[15:17]), + }, nil +} + +func writeBondFrame(w io.Writer, typ byte, seq uint64, data []byte) error { + var hdr [13]byte + hdr[0] = typ + binary.BigEndian.PutUint64(hdr[1:9], seq) + binary.BigEndian.PutUint32(hdr[9:13], uint32(len(data))) + if _, err := w.Write(hdr[:]); err != nil { + return err + } + if len(data) == 0 { + return nil + } + _, err := w.Write(data) + return err +} + +func readBondFrame(r io.Reader) (bondFrame, error) { + var hdr [13]byte + if _, err := io.ReadFull(r, hdr[:]); err != nil { + return bondFrame{}, err + } + size := binary.BigEndian.Uint32(hdr[9:13]) + if size > 4*1024*1024 { + return bondFrame{}, fmt.Errorf("bond frame too large: %d", size) + } + f := bondFrame{ + typ: hdr[0], + seq: binary.BigEndian.Uint64(hdr[1:9]), + } + if size > 0 { + f.data = make([]byte, size) + if _, err := io.ReadFull(r, f.data); err != nil { + return bondFrame{}, err + } + } + return f, nil +} + +func closeWrite(conn net.Conn) { + type closeWriter interface { + CloseWrite() error + } + if cw, ok := conn.(closeWriter); ok { + if err := cw.CloseWrite(); err != nil { + debugf("CloseWrite failed: %v", err) + } + } +} + +type bondServerLane struct { + index uint16 + stream *smux.Stream + mu sync.Mutex +} + +type bondServerConn struct { + id uint64 + connectAddr string + ctx context.Context + cancel context.CancelFunc + done chan struct{} + + lanesMu sync.RWMutex + lanes []*bondServerLane + want uint16 + ready chan struct{} + + recvCh chan bondFrame + once sync.Once +} + +type bondRegistry struct { + mu sync.Mutex + conns map[uint64]*bondServerConn +} + +var globalBondRegistry = &bondRegistry{conns: make(map[uint64]*bondServerConn)} + +func (r *bondRegistry) get(ctx context.Context, id uint64, connectAddr string) *bondServerConn { + r.mu.Lock() + defer r.mu.Unlock() + if c := r.conns[id]; c != nil { + return c + } + connCtx, cancel := context.WithCancel(ctx) + c := &bondServerConn{ + id: id, + connectAddr: connectAddr, + ctx: connCtx, + cancel: cancel, + done: make(chan struct{}), + ready: make(chan struct{}, 1), + recvCh: make(chan bondFrame, 1024), + } + r.conns[id] = c + go func() { + <-c.done + r.mu.Lock() + if r.conns[id] == c { + delete(r.conns, id) + } + r.mu.Unlock() + }() + return c +} + +func (c *bondServerConn) addLane(l *bondServerLane, laneCount uint16) { + c.lanesMu.Lock() + if laneCount > c.want { + c.want = laneCount + } + c.lanes = append(c.lanes, l) + count := len(c.lanes) + c.lanesMu.Unlock() + debugf("[bond %d] lane %d attached (lanes=%d)", c.id, l.index, count) + select { + case c.ready <- struct{}{}: + default: + } + + go c.readLane(l) + c.once.Do(func() { + go c.run() + }) +} + +func (c *bondServerConn) snapshotLanes() []*bondServerLane { + c.lanesMu.RLock() + defer c.lanesMu.RUnlock() + out := make([]*bondServerLane, len(c.lanes)) + copy(out, c.lanes) + return out +} + +func (c *bondServerConn) removeLane(l *bondServerLane) int { + c.lanesMu.Lock() + defer c.lanesMu.Unlock() + for i, lane := range c.lanes { + if lane == l { + c.lanes = append(c.lanes[:i], c.lanes[i+1:]...) + break + } + } + return len(c.lanes) +} + +func (c *bondServerConn) waitForInitialLanes() { + timer := time.NewTimer(bondLaneAttachTimeout) + defer timer.Stop() + for { + c.lanesMu.RLock() + count := len(c.lanes) + want := int(c.want) + c.lanesMu.RUnlock() + if want <= 0 || count >= want { + return + } + select { + case <-c.ctx.Done(): + return + case <-c.ready: + case <-timer.C: + debugf("[bond %d] starting with %d/%d lanes after attach timeout", c.id, count, want) + return + } + } +} + +func (c *bondServerConn) readLane(l *bondServerLane) { + for { + f, err := readBondFrame(l.stream) + if err != nil { + left := c.removeLane(l) + select { + case <-c.ctx.Done(): + default: + if err != io.EOF { + debugf("[bond %d] lane %d read error: %v (lanes=%d)", c.id, l.index, err, left) + } + if left == 0 { + c.cancel() + } + } + return + } + select { + case c.recvCh <- f: + case <-c.ctx.Done(): + return + } + } +} + +func (c *bondServerConn) run() { + defer close(c.done) + defer c.cancel() + + c.waitForInitialLanes() + + backendConn, err := net.DialTimeout("tcp", c.connectAddr, 10*time.Second) + if err != nil { + log.Printf("[bond %d] backend dial error: %s", c.id, err) + return + } + defer func() { + if err := backendConn.Close(); err != nil { + log.Printf("[bond %d] failed to close backend connection: %v", c.id, err) + } + }() + context.AfterFunc(c.ctx, func() { + now := time.Now() + if err := backendConn.SetDeadline(now); err != nil { + log.Printf("[bond %d] backend deadline error: %v", c.id, err) + } + for _, lane := range c.snapshotLanes() { + if err := lane.stream.SetDeadline(now); err != nil { + log.Printf("[bond %d] lane %d deadline error: %v", c.id, lane.index, err) + } + } + }) + debugf("[bond %d] backend connected", c.id) + + var wg sync.WaitGroup + wg.Add(2) + go func() { + defer wg.Done() + c.copyBondToBackend(backendConn) + }() + go func() { + defer wg.Done() + defer c.cancel() + c.copyBackendToBond(backendConn) + }() + wg.Wait() +} + +func (c *bondServerConn) copyBondToBackend(backendConn net.Conn) { + pending := make(map[uint64][]byte) + var expect uint64 + var finSeq *uint64 + + for { + if finSeq != nil && expect == *finSeq { + closeWrite(backendConn) + debugf("[bond %d] upload to backend finished chunks=%d", c.id, expect) + return + } + + select { + case <-c.ctx.Done(): + return + case f := <-c.recvCh: + switch f.typ { + case bondFrameData: + pending[f.seq] = f.data + case bondFrameFIN: + v := f.seq + if finSeq == nil || v < *finSeq { + finSeq = &v + } + default: + log.Printf("[bond %d] unknown frame type %d", c.id, f.typ) + return + } + + for { + data, ok := pending[expect] + if !ok { + break + } + delete(pending, expect) + if len(data) > 0 { + if _, err := backendConn.Write(data); err != nil { + log.Printf("[bond %d] backend write error: %v", c.id, err) + return + } + } + expect++ + } + } + } +} + +func (c *bondServerConn) copyBackendToBond(backendConn net.Conn) { + buf := make([]byte, bondMaxChunk) + var seq uint64 + var laneIdx uint64 + for { + n, err := backendConn.Read(buf) + if n > 0 { + data := make([]byte, n) + copy(data, buf[:n]) + if writeErr := c.writeToNextLane(bondFrameData, seq, data, &laneIdx); writeErr != nil { + log.Printf("[bond %d] lane write data error: %v", c.id, writeErr) + return + } + seq++ + } + if err != nil { + lanes := c.snapshotLanes() + for _, lane := range lanes { + lane.mu.Lock() + writeErr := writeBondFrame(lane.stream, bondFrameFIN, seq, nil) + lane.mu.Unlock() + if writeErr != nil && c.ctx.Err() == nil { + log.Printf("[bond %d] lane %d write FIN error: %v", c.id, lane.index, writeErr) + } + } + debugf("[bond %d] download from backend finished chunks=%d", c.id, seq) + return + } + select { + case <-c.ctx.Done(): + return + default: + } + } +} + +func (c *bondServerConn) writeToNextLane(typ byte, seq uint64, data []byte, laneIdx *uint64) error { + for { + lanes := c.snapshotLanes() + for attempts := 0; attempts < len(lanes); attempts++ { + lane := lanes[*laneIdx%uint64(len(lanes))] + (*laneIdx)++ + lane.mu.Lock() + err := writeBondFrame(lane.stream, typ, seq, data) + lane.mu.Unlock() + if err == nil { + return nil + } + left := c.removeLane(lane) + log.Printf("[bond %d] lane %d write error: %v (lanes=%d)", c.id, lane.index, err, left) + if left == 0 { + return err + } + } + select { + case <-c.ctx.Done(): + return c.ctx.Err() + case <-time.After(10 * time.Millisecond): + } + } +} + +func handleBondServerStreamAfterMagic(ctx context.Context, stream *smux.Stream, connectAddr string, magic [4]byte) { + handleBondServerStreamWithHello(ctx, stream, connectAddr, func(r io.Reader) (bondHello, error) { + return readBondHelloAfterMagic(r, magic) + }) +} + +func handleBondServerStreamWithHello(ctx context.Context, stream *smux.Stream, connectAddr string, readHello func(io.Reader) (bondHello, error)) { + defer func() { + if err := stream.Close(); err != nil && err != smux.ErrGoAway { + log.Printf("failed to close bond smux stream: %v", err) + } + }() + + hello, err := readHello(stream) + if err != nil { + log.Printf("bond hello error: %v", err) + return + } + + conn := globalBondRegistry.get(ctx, hello.connID, connectAddr) + conn.addLane(&bondServerLane{ + index: hello.laneIndex, + stream: stream, + }, hello.laneCount) + + select { + case <-ctx.Done(): + case <-conn.done: + } +} + +type prefixedConn struct { + net.Conn + prefix []byte +} + +func (c *prefixedConn) Read(p []byte) (int, error) { + if len(c.prefix) > 0 { + n := copy(p, c.prefix) + c.prefix = c.prefix[n:] + return n, nil + } + return c.Conn.Read(p) +} + +// handleUDPConnection forwards DTLS packets to a UDP backend (WireGuard). +func handleUDPConnection(ctx context.Context, conn net.Conn, connectAddr string) { + serverConn, err := net.Dial("udp", connectAddr) + if err != nil { + log.Println(err) + return + } + defer func() { + if err = serverConn.Close(); err != nil { + log.Printf("failed to close outgoing connection: %s", err) + } + }() + + var wg sync.WaitGroup + wg.Add(2) + ctx2, cancel2 := context.WithCancel(ctx) + stats := &throughputStats{} + go stats.logEvery( + ctx2, + fmt.Sprintf("[DTLS %s]", conn.RemoteAddr()), + "dtls-to-backend", + "backend-to-dtls", + ) + + context.AfterFunc(ctx2, func() { + if err := conn.SetDeadline(time.Now()); err != nil { + log.Printf("failed to set incoming deadline: %s", err) + } + if err := serverConn.SetDeadline(time.Now()); err != nil { + log.Printf("failed to set outgoing deadline: %s", err) + } + }) + go func() { + defer wg.Done() + defer cancel2() + buf := make([]byte, 1600) + for { + select { + case <-ctx2.Done(): + return + default: + } + if err1 := conn.SetReadDeadline(time.Now().Add(time.Minute * 30)); err1 != nil { + log.Printf("Failed: %s", err1) + return + } + n, err1 := conn.Read(buf) + if err1 != nil { + log.Printf("Failed: %s", err1) + return + } + + if err1 = serverConn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil { + log.Printf("Failed: %s", err1) + return + } + written, err1 := serverConn.Write(buf[:n]) + stats.addTx(written) + if err1 != nil { + log.Printf("Failed: %s", err1) + return + } + } + }() + go func() { + defer wg.Done() + defer cancel2() + buf := make([]byte, 1600) + for { + select { + case <-ctx2.Done(): + return + default: + } + if err1 := serverConn.SetReadDeadline(time.Now().Add(time.Minute * 30)); err1 != nil { + log.Printf("Failed: %s", err1) + return + } + n, err1 := serverConn.Read(buf) + if err1 != nil { + log.Printf("Failed: %s", err1) + return + } + + if err1 = conn.SetWriteDeadline(time.Now().Add(time.Minute * 30)); err1 != nil { + log.Printf("Failed: %s", err1) + return + } + written, err1 := conn.Write(buf[:n]) + stats.addRx(written) + if err1 != nil { + log.Printf("Failed: %s", err1) + return + } + } + }() + wg.Wait() +} + +// handleVLESSConnection creates a KCP+smux session over DTLS and forwards +// each smux stream as a TCP connection to the backend (Xray/VLESS). +func handleVLESSConnection(ctx context.Context, dtlsConn net.Conn, connectAddr string, bond bool) { + // 1. Create KCP session over DTLS + statsCtx, statsCancel := context.WithCancel(ctx) + defer statsCancel() + stats := &throughputStats{} + go stats.logEvery( + statsCtx, + fmt.Sprintf("[VLESS %s]", dtlsConn.RemoteAddr()), + "to-client", + "from-client", + ) + + kcpSess, err := tcputil.NewKCPOverDTLS(&countingConn{Conn: dtlsConn, stats: stats}, true) + if err != nil { + log.Printf("KCP session error: %s", err) + return + } + defer func() { + if closeErr := kcpSess.Close(); closeErr != nil { + log.Printf("failed to close KCP session: %v", closeErr) + } + }() + debugf("KCP session established (server)") + + // 2. Create smux server session over KCP + smuxSess, err := smux.Server(kcpSess, tcputil.DefaultSmuxConfig()) + if err != nil { + log.Printf("smux server error: %s", err) + return + } + defer func() { + if err := smuxSess.Close(); err != nil { + log.Printf("failed to close smux session: %v", err) + } + }() + debugf("smux session established (server)") + + // 3. Accept smux streams and forward to backend via TCP + var wg sync.WaitGroup + for { + stream, err := smuxSess.AcceptStream() + if err != nil { + select { + case <-ctx.Done(): + default: + log.Printf("smux accept error: %s", err) + } + break + } + + wg.Add(1) + go func(s *smux.Stream) { + defer wg.Done() + + var prefix [4]byte + if _, err := io.ReadFull(s, prefix[:]); err != nil { + if err != io.EOF && err != io.ErrUnexpectedEOF { + log.Printf("smux stream prefix read error: %v", err) + } + _ = s.Close() + return + } + if string(prefix[:]) == bondMagic { + debugf("auto-detected bond smux stream") + handleBondServerStreamAfterMagic(ctx, s, connectAddr, prefix) + return + } + if bond { + log.Printf("non-bond smux stream accepted while -vless-bond is enabled") + } + + defer func() { + if err := s.Close(); err != nil && err != smux.ErrGoAway { + log.Printf("failed to close smux stream: %v", err) + } + }() + + // Connect to backend (Xray/VLESS) + backendConn, err := net.DialTimeout("tcp", connectAddr, 10*time.Second) + if err != nil { + log.Printf("backend dial error: %s", err) + return + } + defer func() { + if err := backendConn.Close(); err != nil { + log.Printf("failed to close backend connection: %v", err) + } + }() + + // Bidirectional copy + pipeConn(ctx, &prefixedConn{Conn: s, prefix: prefix[:]}, backendConn) + }(stream) + } + wg.Wait() +} + +// pipeConn copies data bidirectionally between two connections. +func pipeConn(ctx context.Context, c1, c2 net.Conn) { + ctx2, cancel := context.WithCancel(ctx) + defer cancel() + + context.AfterFunc(ctx2, func() { + if err := c1.SetDeadline(time.Now()); err != nil { + debugf("pipeConn: failed to set deadline c1: %v", err) + } + if err := c2.SetDeadline(time.Now()); err != nil { + debugf("pipeConn: failed to set deadline c2: %v", err) + } + }) + + var wg sync.WaitGroup + wg.Add(2) + + go func() { + defer wg.Done() + if _, err := io.Copy(c1, c2); err != nil { + debugf("pipeConn: c1<-c2 copy error: %v", err) + } + }() + + go func() { + defer wg.Done() + if _, err := io.Copy(c2, c1); err != nil { + debugf("pipeConn: c2<-c1 copy error: %v", err) + } + }() + + wg.Wait() + + // Reset deadlines (best-effort; connection may already be closed) + if err := c1.SetDeadline(time.Time{}); err != nil { + debugf("pipeConn: failed to reset deadline c1: %v", err) + } + if err := c2.SetDeadline(time.Time{}); err != nil { + debugf("pipeConn: failed to reset deadline c2: %v", err) + } +} diff --git a/server/wrap.go b/server/wrap.go new file mode 100644 index 0000000..be3d62a --- /dev/null +++ b/server/wrap.go @@ -0,0 +1,99 @@ +// SPDX-License-Identifier: MIT + +package main + +import ( + "crypto/rand" + "errors" + "fmt" + "net" + "time" + + dtlsnet "github.com/pion/dtls/v3/pkg/net" + pionudp "github.com/pion/transport/v4/udp" + "golang.org/x/crypto/chacha20" +) + +const ( + wrapNonceLen = 12 + wrapKeyLen = 32 +) + +func listenWrapped(addr *net.UDPAddr, key []byte) (dtlsnet.PacketListener, error) { + if len(key) != wrapKeyLen { + return nil, fmt.Errorf("wrap: key must be %d bytes (got %d)", wrapKeyLen, len(key)) + } + inner, err := pionudp.Listen("udp", addr) + if err != nil { + return nil, fmt.Errorf("wrap: udp listen: %w", err) + } + return &wrapPacketListener{ + inner: dtlsnet.PacketListenerFromListener(inner), + key: key, + }, nil +} + +type wrapPacketListener struct { + inner dtlsnet.PacketListener + key []byte +} + +func (l *wrapPacketListener) Accept() (net.PacketConn, net.Addr, error) { + pc, addr, err := l.inner.Accept() + if err != nil { + return pc, addr, err + } + return &wrapPacketConn{inner: pc, key: l.key}, addr, nil +} + +func (l *wrapPacketListener) Close() error { return l.inner.Close() } +func (l *wrapPacketListener) Addr() net.Addr { return l.inner.Addr() } + +type wrapPacketConn struct { + inner net.PacketConn + key []byte +} + +func (c *wrapPacketConn) ReadFrom(p []byte) (int, net.Addr, error) { + buf := make([]byte, len(p)+wrapNonceLen) + n, addr, err := c.inner.ReadFrom(buf) + if err != nil { + return 0, addr, err + } + if n < wrapNonceLen { + return 0, addr, errors.New("wrap: short packet (no nonce)") + } + nonce := buf[:wrapNonceLen] + ciphertext := buf[wrapNonceLen:n] + if len(ciphertext) > len(p) { + return 0, addr, errors.New("wrap: read buffer too small") + } + cipher, err := chacha20.NewUnauthenticatedCipher(c.key, nonce) + if err != nil { + return 0, addr, fmt.Errorf("wrap: cipher init: %w", err) + } + cipher.XORKeyStream(p[:len(ciphertext)], ciphertext) + return len(ciphertext), addr, nil +} + +func (c *wrapPacketConn) WriteTo(p []byte, addr net.Addr) (int, error) { + out := make([]byte, wrapNonceLen+len(p)) + if _, err := rand.Read(out[:wrapNonceLen]); err != nil { + return 0, fmt.Errorf("wrap: nonce gen: %w", err) + } + cipher, err := chacha20.NewUnauthenticatedCipher(c.key, out[:wrapNonceLen]) + if err != nil { + return 0, fmt.Errorf("wrap: cipher init: %w", err) + } + cipher.XORKeyStream(out[wrapNonceLen:], p) + if _, err := c.inner.WriteTo(out, addr); err != nil { + return 0, err + } + return len(p), nil +} + +func (c *wrapPacketConn) Close() error { return c.inner.Close() } +func (c *wrapPacketConn) LocalAddr() net.Addr { return c.inner.LocalAddr() } +func (c *wrapPacketConn) SetDeadline(t time.Time) error { return c.inner.SetDeadline(t) } +func (c *wrapPacketConn) SetReadDeadline(t time.Time) error { return c.inner.SetReadDeadline(t) } +func (c *wrapPacketConn) SetWriteDeadline(t time.Time) error { return c.inner.SetWriteDeadline(t) } diff --git a/tcputil/tcputil.go b/tcputil/tcputil.go new file mode 100644 index 0000000..bb2aab2 --- /dev/null +++ b/tcputil/tcputil.go @@ -0,0 +1,200 @@ +package tcputil + +import ( + "net" + "os" + "strconv" + "strings" + "time" + + "github.com/xtaci/kcp-go/v5" + "github.com/xtaci/smux" +) + +type kcpProfile struct { + nodelay int + interval int + resend int + nc int + sndWnd int + rcvWnd int + mtu int + ackNoDelay bool +} + +func selectedKCPProfile() kcpProfile { + profile := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE"))) + var cfg kcpProfile + switch profile { + case "legacy", "fast": + cfg = kcpProfile{ + nodelay: 1, + interval: 10, + resend: 2, + nc: 1, + sndWnd: 4096, + rcvWnd: 4096, + mtu: 1280, + ackNoDelay: true, + } + case "cc", "balanced": + cfg = kcpProfile{ + nodelay: 1, + interval: 20, + resend: 2, + nc: 0, + sndWnd: 512, + rcvWnd: 512, + mtu: 1200, + ackNoDelay: true, + } + case "slow", "conservative": + cfg = kcpProfile{ + nodelay: 0, + interval: 40, + resend: 2, + nc: 0, + sndWnd: 256, + rcvWnd: 256, + mtu: 1150, + ackNoDelay: false, + } + default: + cfg = kcpProfile{ + nodelay: 1, + interval: 20, + resend: 2, + nc: 1, + sndWnd: 512, + rcvWnd: 512, + mtu: 1200, + ackNoDelay: true, + } + } + + cfg.nodelay = envInt("VK_TURN_KCP_NODELAY", cfg.nodelay) + cfg.interval = envInt("VK_TURN_KCP_INTERVAL", cfg.interval) + cfg.resend = envInt("VK_TURN_KCP_RESEND", cfg.resend) + cfg.nc = envInt("VK_TURN_KCP_NC", cfg.nc) + cfg.sndWnd = envInt("VK_TURN_KCP_SNDWND", cfg.sndWnd) + cfg.rcvWnd = envInt("VK_TURN_KCP_RCVWND", cfg.rcvWnd) + cfg.mtu = envInt("VK_TURN_KCP_MTU", cfg.mtu) + cfg.ackNoDelay = envBool("VK_TURN_KCP_ACK_NODELAY", cfg.ackNoDelay) + return cfg +} + +func envInt(name string, fallback int) int { + raw := strings.TrimSpace(os.Getenv(name)) + if raw == "" { + return fallback + } + value, err := strconv.Atoi(raw) + if err != nil { + return fallback + } + return value +} + +func envBool(name string, fallback bool) bool { + raw := strings.ToLower(strings.TrimSpace(os.Getenv(name))) + switch raw { + case "1", "true", "yes", "on": + return true + case "0", "false", "no", "off": + return false + default: + return fallback + } +} + +// DtlsPacketConn wraps a net.Conn (DTLS) as a net.PacketConn for KCP. +// Each DTLS Read/Write preserves message boundaries (datagram semantics). +type DtlsPacketConn struct { + conn net.Conn +} + +func NewDtlsPacketConn(conn net.Conn) *DtlsPacketConn { + return &DtlsPacketConn{conn: conn} +} + +func (d *DtlsPacketConn) ReadFrom(b []byte) (int, net.Addr, error) { + n, err := d.conn.Read(b) + return n, d.conn.RemoteAddr(), err +} + +func (d *DtlsPacketConn) WriteTo(b []byte, _ net.Addr) (int, error) { + return d.conn.Write(b) +} + +func (d *DtlsPacketConn) Close() error { + return d.conn.Close() +} + +func (d *DtlsPacketConn) LocalAddr() net.Addr { + return d.conn.LocalAddr() +} + +func (d *DtlsPacketConn) SetDeadline(t time.Time) error { + return d.conn.SetDeadline(t) +} + +func (d *DtlsPacketConn) SetReadDeadline(t time.Time) error { + return d.conn.SetReadDeadline(t) +} + +func (d *DtlsPacketConn) SetWriteDeadline(t time.Time) error { + return d.conn.SetWriteDeadline(t) +} + +// NewKCPOverDTLS creates a KCP session over a DTLS connection. +// isServer: true for server-side (listener), false for client-side (dialer). +func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool) (*kcp.UDPSession, error) { + pc := NewDtlsPacketConn(dtlsConn) + + block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts + if err != nil { + return nil, err + } + + var sess *kcp.UDPSession + + if isServer { + // Server: listen on the PacketConn and accept one session + var listener *kcp.Listener + listener, err = kcp.ServeConn(block, 0, 0, pc) + if err != nil { + return nil, err + } + if err = listener.SetDeadline(time.Now().Add(30 * time.Second)); err != nil { + return nil, err + } + sess, err = listener.AcceptKCP() + if err != nil { + return nil, err + } + } else { + // Client: dial through the PacketConn + sess, err = kcp.NewConn2(dtlsConn.RemoteAddr(), block, 0, 0, pc) + if err != nil { + return nil, err + } + } + + profile := selectedKCPProfile() + sess.SetNoDelay(profile.nodelay, profile.interval, profile.resend, profile.nc) + sess.SetWindowSize(profile.sndWnd, profile.rcvWnd) + sess.SetMtu(profile.mtu) + sess.SetACKNoDelay(profile.ackNoDelay) + + return sess, nil +} + +// DefaultSmuxConfig returns smux config tuned for TURN tunnel. +func DefaultSmuxConfig() *smux.Config { + cfg := smux.DefaultConfig() + cfg.MaxReceiveBuffer = 4 * 1024 * 1024 + cfg.MaxStreamBuffer = 1 * 1024 * 1024 + cfg.KeepAliveInterval = 10 * time.Second + cfg.KeepAliveTimeout = 30 * time.Second + return cfg +}