feat: initial commit

This commit is contained in:
samosvalishe committed 2025-11-25 11:38:20 +00:00
commit 942d0fff43
30 files changed
+10458

No files matched your search

+153
View File
@@ -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/**
+28
View File
@@ -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: >
Привет! 👋
<br><br>
Данный issue давно не обновлялся. Если в течение недели здесь не будет больше активности, issue будет закрыт.
<br><br>
Спасибо!
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"
+337
View File
@@ -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 }}
+65
View File
@@ -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$
+21
View File
@@ -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"]
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+417
View File
@@ -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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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=<host-ip>: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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -vk-link "<vk-call-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 <ip-vps>:56000 -yandex-link "<telemost-link>"
```
## Флаги Клиента
| Флаг | По умолчанию | Описание |
| --- | --- | --- |
| `-listen` | `127.0.0.1:9000` | локальный адрес для WireGuard или Xray клиента |
| `-peer` | обязательный | адрес VK TURN Proxy server на VPS, например `<ip-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 <ip-vps>:56000 -vk-link "<vk-call-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).
<a href="https://www.star-history.com/?repos=cacggghp%2Fvk-turn-proxy&type=date&legend=top-left">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=cacggghp/vk-turn-proxy&type=date&theme=dark&legend=top-left" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=cacggghp/vk-turn-proxy&type=date&legend=top-left" />
<img alt="Star History Chart" src="https://api.star-history.com/chart?repos=cacggghp/vk-turn-proxy&type=date&legend=top-left" />
</picture>
</a>
+575
View File
@@ -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)
}
}
+606
View File
@@ -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)
}
+135
View File
@@ -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 }
+10
View File
@@ -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
}
+3065
View File
File diff suppressed because it is too large. Load diff
+61
View File
@@ -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")
}
})
}
+864
View File
@@ -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 <script> tags to extract their content.
var htmlScriptContentRe = regexp.MustCompile(`(?is)(<script[^>]*>)(.*?)(</script>)`)
// htmlStyleContentRe matches <style> tags to extract their content.
var htmlStyleContentRe = regexp.MustCompile(`(?is)(<style[^>]*>)(.*?)(</style>)`)
// 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 <script src> / <link href> / <img src>
// resources immediately as it parses HTML — before any injected JS can intercept them.
html = rewriteHTMLAttrsServerSide(html, targetURL)
script := fmt.Sprintf(`
<script>
(function() {
var localOrigin = %q;
var upstreamOrigin = %q;
function rewriteUrl(urlStr) {
if (!urlStr || typeof urlStr !== 'string') return urlStr;
if (urlStr.indexOf(localOrigin) === 0) return urlStr;
if (urlStr.indexOf(upstreamOrigin) === 0) return localOrigin + urlStr.slice(upstreamOrigin.length);
if (urlStr.indexOf('//') === 0) {
return '/generic_proxy?proxy_url=' + encodeURIComponent(window.location.protocol + urlStr);
}
if (urlStr.indexOf('http://') === 0 || urlStr.indexOf('https://') === 0) {
return '/generic_proxy?proxy_url=' + encodeURIComponent(urlStr);
}
return urlStr;
}
function rewriteElementAttr(el, attr) {
if (!el || !el.getAttribute) return;
var value = el.getAttribute(attr);
if (!value) return;
var rewritten = rewriteUrl(value);
if (rewritten !== value) {
el.setAttribute(attr, rewritten);
}
}
function rewriteDocument(root) {
if (!root || !root.querySelectorAll) return;
root.querySelectorAll('[href]').forEach(function(el) { rewriteElementAttr(el, 'href'); });
root.querySelectorAll('[src]').forEach(function(el) { rewriteElementAttr(el, 'src'); });
root.querySelectorAll('form[action]').forEach(function(el) { rewriteElementAttr(el, 'action'); });
}
function handleSuccessToken(token) {
if (!token) return;
console.log('Captcha solved, sending token to proxy...');
var body = 'token=' + encodeURIComponent(token);
// sendBeacon is the most reliable on mobile Safari:
// it's fire-and-forget and works even if the page navigates away.
if (navigator && navigator.sendBeacon) {
var blob = new Blob([body], {type: 'application/x-www-form-urlencoded'});
var sent = navigator.sendBeacon('/local-captcha-result', blob);
if (sent) {
console.log('Token sent via sendBeacon');
showDone();
return;
}
}
// Fallback: fetch
fetch('/local-captcha-result', {
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
body: body
}).then(function(r) {
console.log('Proxy acknowledged token');
showDone();
}).catch(function(e) {
console.error('Fetch failed, trying form submit...', e);
// Last resort: form POST (navigates the page)
var form = document.createElement('form');
form.method = 'POST';
form.action = '/local-captcha-result';
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'token';
input.value = token;
form.appendChild(input);
document.body.appendChild(form);
form.submit();
});
}
function showDone() {
document.body.innerHTML = '<div style="text-align:center;margin-top:20vh;font-family:sans-serif">' +
'<h2 style="color:#4caf50">✔ Done!</h2>' +
'<p>Captcha solved successfully. You can close this tab now.</p>' +
'</div>';
// On iOS, window.close() often doesn't work, so we just let the user know they are done.
setTimeout(function() { window.close(); }, 1000);
}
var origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
if (arguments[1] && typeof arguments[1] === 'string') {
this._origUrl = arguments[1];
arguments[1] = rewriteUrl(arguments[1]);
}
return origOpen.apply(this, arguments);
};
var origSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
var xhr = this;
if (this._origUrl && this._origUrl.indexOf('captchaNotRobot.check') !== -1) {
xhr.addEventListener('load', function() {
try {
var data = JSON.parse(xhr.responseText);
if (data.response && data.response.success_token) {
handleSuccessToken(data.response.success_token);
}
} catch (e) {}
});
}
return origSend.apply(this, arguments);
};
var origFetch = window.fetch;
if (origFetch) {
window.fetch = function() {
var url = arguments[0];
var isObj = (typeof url === 'object' && url && url.url);
var urlStr = isObj ? url.url : url;
var origUrlStr = urlStr;
if (typeof urlStr === 'string') {
urlStr = rewriteUrl(urlStr);
arguments[0] = urlStr;
}
var p = origFetch.apply(this, arguments);
if (typeof origUrlStr === 'string' && origUrlStr.indexOf('captchaNotRobot.check') !== -1) {
p.then(function(response) {
return response.clone().json();
}).then(function(data) {
if (data.response && data.response.success_token) {
handleSuccessToken(data.response.success_token);
}
}).catch(function() {});
}
return p;
};
}
document.addEventListener('submit', function(event) {
if (event.target && event.target.action) {
event.target.action = rewriteUrl(event.target.action);
}
}, true);
document.addEventListener('click', function(event) {
var target = event.target && event.target.closest ? event.target.closest('a[href]') : null;
if (target && target.href) {
target.href = rewriteUrl(target.href);
}
}, true);
var origFormSubmit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = function() {
if (this.action) {
this.action = rewriteUrl(this.action);
}
return origFormSubmit.apply(this, arguments);
};
var origWindowOpen = window.open;
if (origWindowOpen) {
window.open = function(url) {
if (typeof url === 'string') {
arguments[0] = rewriteUrl(url);
}
return origWindowOpen.apply(this, arguments);
};
}
rewriteDocument(document);
if (document.documentElement && window.MutationObserver) {
new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type === 'attributes' && mutation.target) {
rewriteElementAttr(mutation.target, mutation.attributeName);
return;
}
mutation.addedNodes.forEach(function(node) {
if (node.nodeType === 1) {
rewriteDocument(node);
}
});
});
}).observe(document.documentElement, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['href', 'src', 'action']
});
}
})();
</script>
`, localOrigin, upstreamOrigin)
// Step 3: inject the client-side script as early as possible — at the opening <head> tag
// so that XHR/fetch overrides are active before any inline <script> block in <head> runs.
switch {
case strings.Contains(html, "<head>"):
return strings.Replace(html, "<head>", "<head>"+script, 1)
case strings.Contains(html, "</head>"):
return strings.Replace(html, "</head>", script+"</head>", 1)
case strings.Contains(html, "</body>"):
return strings.Replace(html, "</body>", script+"</body>", 1)
default:
return html + script
}
}
func newCaptchaProxyTransport(dialer *dnsdialer.Dialer) *http.Transport {
transport := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ForceAttemptHTTP2: false,
}
if dialer != nil {
transport.DialContext = dialer.DialContext
}
return transport
}
func startCaptchaServer(srv *http.Server, logPrefix string) error {
var listenErrs []string
var listening bool
for _, addr := range localCaptchaListenAddrs() {
listener, err := net.Listen("tcp", addr)
if err != nil {
listenErrs = append(listenErrs, fmt.Sprintf("%s (%v)", addr, err))
continue
}
listening = true
wrappedListener, err := wrapISHListener(listener)
if err != nil {
log.Printf("%s: failed to wrap listener for iSH: %v", logPrefix, err)
wrappedListener = listener
}
go func(listener net.Listener) {
if err := srv.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Printf("%s: %s", logPrefix, err)
}
}(wrappedListener)
}
if listening {
return nil
}
return fmt.Errorf("captcha listeners failed: %s", strings.Join(listenErrs, "; "))
}
// runCaptchaServerAndWait triggers the browser, and waiting gracefully for the solution token.
func runCaptchaServerAndWait(handler http.Handler, captchaURL string, keyCh <-chan string, logPrefix string) (string, error) {
srv := &http.Server{Handler: handler}
if err := startCaptchaServer(srv, logPrefix); err != nil {
return "", err
}
fmt.Println("\n==============================================")
fmt.Println("ACTION REQUIRED: MANUAL CAPTCHA SOLVING NEEDED")
fmt.Println("If your browser didn't open automatically,")
fmt.Println("manually open this URL: " + localCaptchaOrigin())
fmt.Println("==============================================")
fmt.Println()
log.Printf("[%s] Opening browser...", logPrefix)
openBrowser(captchaURL)
key := <-keyCh
// Best-effort shutdown: the token is already received, so even if
// Shutdown times out (e.g. because ishConn.SetDeadline is a no-op
// on iSH and active connections can't be force-closed), we still
// return the token successfully.
shutCtx, shutCancel := context.WithTimeout(context.Background(), 3*time.Second)
defer shutCancel()
if err := srv.Shutdown(shutCtx); err != nil {
log.Printf("%s: shutdown warning (token already received): %v", logPrefix, err)
}
return key, nil
}
// notifyKey pushes the key string to the given channel without blocking
func notifyKey(keyCh chan<- string, key string) {
if key != "" {
select {
case keyCh <- key:
default:
}
}
}
func solveCaptchaViaHTTP(captchaImg string) (string, error) {
keyCh := make(chan string, 1)
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = fmt.Fprintf(w, `<!DOCTYPE html>
<html><head>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>body{font-family:sans-serif;text-align:center;padding:20px}
img{max-width:100%%;margin:16px 0}
input{font-size:24px;padding:12px;width:80%%;box-sizing:border-box}
button{font-size:24px;padding:12px 32px;margin-top:12px;cursor:pointer}</style>
</head><body>
<h2>Solve the Captcha</h2>
<img src="%s" alt="captcha"/>
<form onsubmit="fetch('/solve?key='+encodeURIComponent(document.getElementById('k').value)).then(()=>{document.body.innerHTML='<h2>Done!</h2>';setTimeout(function(){window.close();}, 300);});return false;">
<br><input id="k" type="text" autofocus placeholder="Text from image"/>
<br><button type="submit">Submit</button>
</form></body></html>`, captchaImg)
})
mux.HandleFunc("/solve", func(w http.ResponseWriter, r *http.Request) {
notifyKey(keyCh, r.URL.Query().Get("key"))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_, _ = fmt.Fprint(w, `<!DOCTYPE html><html><body><h2>Done!</h2></body></html>`)
})
return runCaptchaServerAndWait(mux, localCaptchaOrigin(), keyCh, "captcha HTTP server error")
}
type loggingTransport struct {
rt http.RoundTripper
}
func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
isCaptchaRequest := req.Body != nil && (strings.Contains(req.URL.Path, "captchaNotRobot.check") || strings.Contains(req.URL.Path, "captchaNotRobot.componentDone"))
if isCaptchaRequest {
b, err := io.ReadAll(req.Body)
if err != nil {
log.Printf("[Captcha Proxy] Failed to read request body: %v", err)
b = nil
}
req.Body = io.NopCloser(bytes.NewReader(b))
if isDebug {
log.Printf("[Captcha Proxy] Real browser sent %s data: %s", req.URL.Path, string(b))
for k, v := range req.Header {
log.Printf("[Captcha Proxy] Header (%s): %s = %s", req.URL.Path, k, strings.Join(v, ", "))
}
}
if strings.Contains(req.URL.Path, "captchaNotRobot.componentDone") || strings.Contains(req.URL.Path, "captchaNotRobot.check") {
parsedBody, err := neturl.ParseQuery(string(b))
if err != nil {
log.Printf("[Captcha Proxy] Failed to parse request body: %v", err)
}
device := parsedBody.Get("device")
browserFp := parsedBody.Get("browser_fp")
// We only save it if device is present. componentDone usually has it.
if device != "" && browserFp != "" {
sp := SavedProfile{
Profile: Profile{
UserAgent: req.Header.Get("User-Agent"),
SecChUa: req.Header.Get("Sec-Ch-Ua"),
SecChUaMobile: req.Header.Get("Sec-Ch-Ua-Mobile"),
SecChUaPlatform: req.Header.Get("Sec-Ch-Ua-Platform"),
},
DeviceJSON: device,
BrowserFp: browserFp,
}
if err := SaveProfileToDisk(sp); err != nil {
log.Printf("[Captcha Proxy] Failed to save browser profile: %v", err)
} else {
log.Printf("[Captcha Proxy] Successfully intercepted and saved real browser profile!")
}
}
}
}
return t.rt.RoundTrip(req)
}
func solveCaptchaViaProxy(redirectURI string, dialer *dnsdialer.Dialer) (string, error) {
keyCh := make(chan string, 1)
targetURL, err := neturl.Parse(redirectURI)
if err != nil {
return "", fmt.Errorf("invalid redirect URI: %v", err)
}
transport := &loggingTransport{rt: newCaptchaProxyTransport(dialer)}
proxy := &httputil.ReverseProxy{
Transport: transport,
Rewrite: func(req *httputil.ProxyRequest) {
rewriteProxyRequest(req.Out, targetURL)
},
ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) {
log.Printf("[Captcha Proxy] ERROR for %s %s: %v", r.Method, r.URL.String(), err)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadGateway)
_, _ = fmt.Fprintf(w, `<!DOCTYPE html><html><body style="font-family:sans-serif;padding:20px"><h2>Captcha proxy error</h2><p>%s %s</p><p>%v</p></body></html>`, r.Method, r.URL.String(), err)
},
ModifyResponse: func(res *http.Response) error {
rewriteProxyCookies(res.Header)
if res.StatusCode >= 300 && res.StatusCode < 400 {
if loc := res.Header.Get("Location"); loc != "" {
// Don't log the full redirect URL to keep console clean
if rewritten, ok := rewriteProxyRedirectLocation(loc, targetURL); ok {
res.Header.Set("Location", rewritten)
} else {
res.Header.Del("Location")
}
}
}
contentType := res.Header.Get("Content-Type")
contentEncoding := res.Header.Get("Content-Encoding")
if isDebug {
log.Printf("[Captcha Proxy] %s %d | Content-Type: %q, Encoding: %q", res.Request.Method, res.StatusCode, contentType, contentEncoding)
}
shouldInspectBody := strings.Contains(contentType, "text/html") ||
strings.Contains(contentType, "application/xhtml+xml") ||
strings.Contains(res.Request.URL.Path, "captchaNotRobot.check")
if !shouldInspectBody {
return nil
}
reader := res.Body
if res.Header.Get("Content-Encoding") == "gzip" {
gzReader, err := gzip.NewReader(res.Body)
if err == nil {
reader = gzReader
defer func() {
if err := gzReader.Close(); err != nil {
log.Printf("failed to close gzip reader: %v", err)
}
}()
}
}
bodyBytes, err := io.ReadAll(reader)
if err != nil {
return err
}
if err := res.Body.Close(); err != nil {
return err
}
if strings.Contains(res.Request.URL.Path, "captchaNotRobot.check") {
notifyKey(keyCh, extractSuccessToken(bodyBytes))
}
if strings.Contains(contentType, "text/html") {
for _, headerName := range []string{
"Content-Security-Policy",
"Content-Security-Policy-Report-Only",
"X-Content-Security-Policy",
"X-WebKit-CSP",
"Cross-Origin-Opener-Policy",
"Cross-Origin-Embedder-Policy",
"Cross-Origin-Resource-Policy",
"X-Frame-Options",
"Strict-Transport-Security",
"Alt-Svc",
} {
res.Header.Del(headerName)
}
bodyBytes = []byte(rewriteCaptchaHTML(string(bodyBytes), targetURL))
res.Header.Del("Content-Encoding")
}
res.Body = io.NopCloser(bytes.NewReader(bodyBytes))
res.ContentLength = int64(len(bodyBytes))
res.Header.Set("Content-Length", fmt.Sprint(len(bodyBytes)))
return nil
},
}
mux := http.NewServeMux()
mux.HandleFunc("/local-captcha-result", func(w http.ResponseWriter, r *http.Request) {
token := r.FormValue("token")
if token != "" {
log.Printf("[Captcha] Received success token from browser (%d bytes)", len(token))
notifyKey(keyCh, token)
} else {
log.Printf("[Captcha] Received empty token from browser")
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "text/plain")
_, _ = fmt.Fprint(w, "ok")
})
mux.HandleFunc("/generic_proxy", func(w http.ResponseWriter, r *http.Request) {
targetAuthURL := r.URL.Query().Get("proxy_url")
targetParsed, err := neturl.Parse(targetAuthURL)
if err != nil || targetParsed.Host == "" {
http.Error(w, "Bad URL", http.StatusBadRequest)
return
}
genericReverse := &httputil.ReverseProxy{
Transport: transport,
Rewrite: func(req *httputil.ProxyRequest) {
req.Out.URL.Path = targetParsed.Path
req.Out.URL.RawQuery = targetParsed.RawQuery
rewriteProxyRequest(req.Out, targetParsed)
},
ModifyResponse: func(res *http.Response) error {
// Strip security headers that can block cross-origin resource loading
// when static assets (JS/CSS) are served through the proxy.
for _, h := range []string{
"Content-Security-Policy",
"Content-Security-Policy-Report-Only",
"X-Content-Security-Policy",
"X-WebKit-CSP",
"Cross-Origin-Opener-Policy",
"Cross-Origin-Embedder-Policy",
"Cross-Origin-Resource-Policy",
"X-Frame-Options",
"Strict-Transport-Security",
} {
res.Header.Del(h)
}
// Allow the browser to use the resource cross-origin
res.Header.Set("Access-Control-Allow-Origin", "*")
// captchaNotRobot.check goes to api.vk.ru (different host from the main
// proxy upstream vk.com), so it is routed through /generic_proxy.
// Extract the success_token here so the server path works on iOS
// even if the browser-side JS callback never fires.
if strings.Contains(targetAuthURL, "captchaNotRobot.check") {
bodyBytes, readErr := io.ReadAll(res.Body)
if readErr == nil {
_ = res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(bodyBytes))
res.ContentLength = int64(len(bodyBytes))
res.Header.Set("Content-Length", fmt.Sprint(len(bodyBytes)))
notifyKey(keyCh, extractSuccessToken(bodyBytes))
}
}
return nil
},
}
genericReverse.ServeHTTP(w, r)
})
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("[Captcha Proxy] HTTP %s %s", r.Method, r.URL.Path)
if r.URL.Path == "/" && targetURL.Path != "" && targetURL.Path != "/" && r.URL.RawQuery == "" {
// Don't log the full redirect URL to keep console clean
http.Redirect(w, r, localCaptchaURLForTarget(targetURL), http.StatusTemporaryRedirect)
return
}
proxy.ServeHTTP(w, r)
})
return runCaptchaServerAndWait(mux, localCaptchaURLForTarget(targetURL), keyCh, "proxy HTTP server error")
}
func openBrowser(url string) {
for _, cmd := range browserOpenCommands(runtime.GOOS, url) {
if err := exec.Command(cmd.name, cmd.args...).Start(); err == nil {
return
}
}
}
func browserOpenCommands(goos string, url string) []browserCommand {
switch goos {
case "windows":
// 'rundll32 url.dll,FileProtocolHandler' is more reliable than 'cmd /c start'
// because it doesn't involve the shell (cmd.exe), avoiding issues with '&' and other special characters.
return []browserCommand{
{name: "rundll32", args: []string{"url.dll,FileProtocolHandler", url}},
// Fallback with empty title argument for 'start' to handle potential quoting issues
{name: "cmd", args: []string{"/c", "start", "", url}},
}
case "darwin":
return []browserCommand{{name: "open", args: []string{url}}}
case "linux":
return []browserCommand{
{name: "xdg-open", args: []string{url}},
{name: "gio", args: []string{"open", url}},
}
case "android":
return []browserCommand{
{name: "termux-open-url", args: []string{url}},
{name: "/system/bin/am", args: []string{"start", "-a", "android.intent.action.VIEW", "-d", url}},
{name: "am", args: []string{"start", "-a", "android.intent.action.VIEW", "-d", url}},
{name: "xdg-open", args: []string{url}},
}
case "ios":
return []browserCommand{
{name: "open", args: []string{url}},
{name: "uiopen", args: []string{url}},
}
}
return nil
}
+65
View File
@@ -0,0 +1,65 @@
package main
import (
"net/url"
"testing"
)
func TestRewriteProxyRedirectLocation(t *testing.T) {
t.Parallel()
targetURL, err := url.Parse("https://id.vk.ru/captcha")
if err != nil {
t.Fatalf("failed to parse target URL: %v", err)
}
testCases := []struct {
name string
location string
want string
ok bool
}{
{
name: "keeps safe relative path",
location: "/captcha?step=2",
want: "/captcha?step=2",
ok: true,
},
{
name: "rewrites same-origin absolute URL",
location: "https://id.vk.ru/captcha?step=2",
want: "http://localhost:8765/captcha?step=2",
ok: true,
},
{
name: "blocks scheme-relative redirect",
location: "//evil.example/captcha",
ok: false,
},
{
name: "blocks slash-backslash redirect",
location: `/\evil.example/captcha`,
ok: false,
},
{
name: "blocks lookalike absolute host",
location: "https://id.vk.ru.evil.example/captcha",
ok: false,
},
}
for _, tc := range testCases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
got, ok := rewriteProxyRedirectLocation(tc.location, targetURL)
if ok != tc.ok {
t.Fatalf("rewriteProxyRedirectLocation() ok = %v, want %v", ok, tc.ok)
}
if got != tc.want {
t.Fatalf("rewriteProxyRedirectLocation() = %q, want %q", got, tc.want)
}
})
}
}
+187
View File
@@ -0,0 +1,187 @@
package main
import (
"fmt"
"math/rand"
"strings"
)
var maleFirstNames = []string{
"Александр",
"Алексей",
"Андрей",
"Антон",
"Арсений",
"Артур",
"Артём",
"Богдан",
"Валерий",
"Василий",
"Виктор",
"Владислав",
"Глеб",
"Григорий",
"Даниил",
"Денис",
"Дмитрий",
"Евгений",
"Егор",
"Иван",
"Игорь",
"Илья",
"Кирилл",
"Леонид",
"Максим",
"Марк",
"Матвей",
"Михаил",
"Никита",
"Николай",
"Олег",
"Павел",
"Пётр",
"Роман",
"Руслан",
"Сергей",
"Станислав",
"Тимофей",
"Фёдор",
}
var femaleFirstNames = []string{
"Алина",
"Алёна",
"Анастасия",
"Ангелина",
"Анна",
"Вера",
"Вероника",
"Виктория",
"Дарья",
"Ева",
"Екатерина",
"Елена",
"Елизавета",
"Ирина",
"Кира",
"Кристина",
"Ксения",
"Любовь",
"Маргарита",
"Марина",
"Мария",
"Милана",
"Надежда",
"Наталья",
"Ольга",
"Полина",
"Светлана",
"София",
"Татьяна",
"Юлия",
"Яна",
}
var lastNames = []string{
"Алексеев",
"Андреев",
"Антонов",
"Баранов",
"Белов",
"Белый",
"Бельский",
"Беляев",
"Борисов",
"Васильев",
"Великий",
"Волков",
"Воробьёв",
"Григорьев",
"Давыдов",
"Егоров",
"Жуков",
"Зайцев",
"Захаров",
"Иванов",
"Калинин",
"Ковалёв",
"Козлов",
"Комаров",
"Крамской",
"Кузнецов",
"Кузьмин",
"Лебедев",
"Макаров",
"Медведев",
"Михайлов",
"Морозов",
"Никитин",
"Николаев",
"Новиков",
"Орлов",
"Островский",
"Павлов",
"Петров",
"Покровский",
"Попов",
"Раевский",
"Романов",
"Семёнов",
"Сергеев",
"Смирнов",
"Соколов",
"Соловьёв",
"Степанов",
"Тарасов",
"Титов",
"Толстой",
"Трубецкой",
"Филиппов",
"Фролов",
"Фёдоров",
"Чайковский",
"Черный",
"Яковлев",
}
// convertToFemaleSurname handles Russian suffix rules
func convertToFemaleSurname(surname string) string {
// Handle adjective-style surnames:
if strings.HasSuffix(surname, "ий") || strings.HasSuffix(surname, "ый") || strings.HasSuffix(surname, "ой") {
return surname[:len(surname)-4] + "ая"
}
// Handle standard possessive surnames:
if strings.HasSuffix(surname, "ов") || strings.HasSuffix(surname, "ев") ||
strings.HasSuffix(surname, "ин") || strings.HasSuffix(surname, "ын") ||
strings.HasSuffix(surname, "ёв") {
return surname + "а"
}
// Foreign or unchangeable
return surname
}
func generateName() string {
// Decide gender first
isFemale := rand.Intn(2) == 0
var fn string
if isFemale {
fn = femaleFirstNames[rand.Intn(len(femaleFirstNames))]
} else {
fn = maleFirstNames[rand.Intn(len(maleFirstNames))]
}
// 70% chance to have a last name
if rand.Float32() < 0.3 {
return fn
}
ln := lastNames[rand.Intn(len(lastNames))]
if isFemale {
ln = convertToFemaleSurname(ln)
}
return fmt.Sprintf("%s %s", fn, ln)
}
+113
View File
@@ -0,0 +1,113 @@
package main
import (
"encoding/json"
"math/rand"
"os"
)
type Profile struct {
UserAgent string
SecChUa string
SecChUaMobile string
SecChUaPlatform string
}
type SavedProfile struct {
Profile
DeviceJSON string
BrowserFp string
}
const profileFile = "vk_profile.json"
func LoadProfileFromDisk() (*SavedProfile, error) {
data, err := os.ReadFile(profileFile)
if err != nil {
return nil, err
}
var sp SavedProfile
if err := json.Unmarshal(data, &sp); err != nil {
return nil, err
}
return &sp, nil
}
func SaveProfileToDisk(sp SavedProfile) error {
data, err := json.MarshalIndent(sp, "", " ")
if err != nil {
return err
}
return os.WriteFile(profileFile, data, 0644)
}
// profiles contain paired User-Agent and Client Hints strings to harden bot detection.
// Used only as a fallback if no saved profile exists (which we shouldn't really use for check anymore).
var profileList = []Profile{
// Windows Chrome
{
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: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Google Chrome";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="144", "Not-A.Brand";v="8", "Google Chrome";v="144"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
// Windows Edge
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Microsoft Edge";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Microsoft Edge";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
// macOS Chrome
{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"macOS"`,
},
{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Google Chrome";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"macOS"`,
},
// Linux Chrome
{
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Linux"`,
},
{
UserAgent: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="144", "Not-A.Brand";v="8", "Google Chrome";v="144"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Linux"`,
},
}
// getRandomProfile returns a paired User-Agent and Client Hints profile.
func getRandomProfile() Profile {
return profileList[rand.Intn(len(profileList))]
}
File diff suppressed because it is too large. Load diff
+278
View File
@@ -0,0 +1,278 @@
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"image"
"image/color"
"image/jpeg"
"reflect"
"testing"
)
func TestParseSliderSteps(t *testing.T) {
t.Parallel()
size, swaps, attempts, err := parseSliderSteps([]int{5, 0, 1, 2, 3, 7})
if err != nil {
t.Fatalf("parseSliderSteps returned error: %v", err)
}
if size != 5 {
t.Fatalf("expected size 5, got %d", size)
}
if attempts != 7 {
t.Fatalf("expected attempts 7, got %d", attempts)
}
expected := []int{0, 1, 2, 3}
if !reflect.DeepEqual(swaps, expected) {
t.Fatalf("expected swaps %v, got %v", expected, swaps)
}
}
func TestParseCaptchaSettingsResponseSupportsJSONStringMap(t *testing.T) {
t.Parallel()
resp := map[string]interface{}{
"response": map[string]interface{}{
"show_captcha_type": "checkbox",
"captcha_settings": `{"slider":"slider-token","sound":"sound-token"}`,
},
}
settings, err := parseCaptchaSettingsResponse(resp)
if err != nil {
t.Fatalf("parseCaptchaSettingsResponse returned error: %v", err)
}
if settings.ShowCaptchaType != "checkbox" {
t.Fatalf("expected show_captcha_type checkbox, got %q", settings.ShowCaptchaType)
}
if settings.SettingsByType["slider"] != "slider-token" {
t.Fatalf("expected slider settings token, got %q", settings.SettingsByType["slider"])
}
if settings.SettingsByType["sound"] != "sound-token" {
t.Fatalf("expected sound settings token, got %q", settings.SettingsByType["sound"])
}
}
func TestParseCaptchaBootstrapHTML(t *testing.T) {
t.Parallel()
html := `
<script>
window.init = {"data":{"show_captcha_type":"checkbox","captcha_settings":[{"type":"slider","settings":"slider-token"},{"type":"sound","settings":"sound-token"}]}};
window.lang = {};
</script>
<script>
const powInput = "abc123";
const difficulty = 3;
</script>`
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)
}
}
+78
View File
@@ -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
}
+66
View File
@@ -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")
}
}
+25
View File
@@ -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
+51
View File
@@ -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
)
+176
View File
@@ -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=
+43
View File
@@ -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
+48
View File
@@ -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
}
+26
View File
@@ -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
+953
View File
@@ -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)
}
}
+99
View File
@@ -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) }
+200
View File
@@ -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
}