style: перевести комментарии на русский, убрать очевидные
This commit is contained in:
1 parent
ada9b949a4
commit
e417dac087
48 files changed
+659
-671
No files matched your search
+3
-3
@@ -25,8 +25,8 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/wire/srtpmimicry"
|
||||
)
|
||||
|
||||
// manualCaptchaSolver bridges the vkauth.ManualSolveFunc contract to the
|
||||
// local captcha bouncer (internal/client/captcha/manual).
|
||||
// manualCaptchaSolver связывает контракт vkauth.ManualSolveFunc
|
||||
// с локальным captcha-обработчиком (internal/client/captcha/manual).
|
||||
func manualCaptchaSolver(ctx context.Context, e *captcha.Error, d net.Dialer) (string, string, error) {
|
||||
if e.RedirectURI != "" {
|
||||
t, err := manualcaptcha.SolveViaProxy(ctx, e.RedirectURI, d)
|
||||
@@ -42,7 +42,7 @@ func manualCaptchaSolver(ctx context.Context, e *captcha.Error, d net.Dialer) (s
|
||||
func main() {
|
||||
cfg, err := config.ParseClient(os.Args[1:], os.Stderr)
|
||||
if err != nil {
|
||||
// logger not built yet — config parse failure is the only pre-logger fatal.
|
||||
// логгер ещё не создан — единственный fatal до его инициализации.
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ import (
|
||||
func main() {
|
||||
cfg, err := config.ParseServer(os.Args[1:], os.Stderr)
|
||||
if err != nil {
|
||||
// logger not built yet — config parse failure is the only pre-logger fatal.
|
||||
// логгер ещё не создан — единственный fatal до его инициализации.
|
||||
log.Fatalf("%v", err)
|
||||
}
|
||||
logger := logx.New(cfg.Log.Debug)
|
||||
|
||||
+15
-19
@@ -5,39 +5,35 @@ import (
|
||||
"net"
|
||||
)
|
||||
|
||||
// TenantID identifies a tenant in a multi-tenant deployment.
|
||||
// The zero value ("") is the [Anonymous] sentinel used in single-tenant mode.
|
||||
// TenantID идентифицирует тенанта в multi-tenant конфигурации.
|
||||
// Нулевое значение ("") — sentinel [Anonymous] для single-tenant режима.
|
||||
type TenantID string
|
||||
|
||||
// Anonymous is the sentinel TenantID used when authentication is disabled
|
||||
// (single-tenant / no-op mode). All call-sites pass this value until a real
|
||||
// Authenticator is wired in.
|
||||
// Anonymous — sentinel TenantID, когда аутентификация выключена
|
||||
// (single-tenant / no-op). Все вызовы передают это значение, пока
|
||||
// настоящий Authenticator не подключён.
|
||||
const Anonymous TenantID = ""
|
||||
|
||||
// Authenticator authenticates an incoming connection and returns the
|
||||
// TenantID it belongs to. Implementations must be safe for concurrent use.
|
||||
// Authenticator аутентифицирует входящее соединение и возвращает TenantID.
|
||||
// Реализации обязаны быть конкурентно безопасны.
|
||||
//
|
||||
// A nil error with [Anonymous] means the connection is accepted in
|
||||
// non-multi-tenant mode. Any non-nil error must be treated as a rejection
|
||||
// and the caller must close conn.
|
||||
// nil ошибка с [Anonymous] означает приём в не-multi-tenant режиме.
|
||||
// Любая не-nil ошибка трактуется как отказ; вызывающий обязан закрыть conn.
|
||||
//
|
||||
// This interface is stream-oriented: it consumes a net.Conn and is intended
|
||||
// for bondserver/tcpfwdserver wiring. UDP-mode auth (when needed) will get
|
||||
// a separate interface taking a token []byte read out-of-band from the
|
||||
// handshake, since udpserver has no per-tenant stream abstraction.
|
||||
// Интерфейс ориентирован на потоки (net.Conn) — для bondserver/tcpfwdserver.
|
||||
// UDP-режиму (если потребуется) нужен отдельный интерфейс с токеном из
|
||||
// out-of-band handshake, т.к. в udpserver нет per-tenant абстракции потока.
|
||||
type Authenticator interface {
|
||||
Authenticate(ctx context.Context, conn net.Conn) (TenantID, error)
|
||||
}
|
||||
|
||||
// NopAuthenticator is a no-op Authenticator that always returns [Anonymous].
|
||||
// It is the default when multi-tenant support is not configured.
|
||||
// NopAuthenticator — no-op Authenticator, всегда возвращает [Anonymous].
|
||||
// Используется по умолчанию, когда multi-tenant не настроен.
|
||||
type NopAuthenticator struct{}
|
||||
|
||||
// compile-time interface check.
|
||||
var _ Authenticator = NopAuthenticator{}
|
||||
|
||||
// Authenticate implements [Authenticator]. It always succeeds and returns
|
||||
// [Anonymous] without inspecting conn or ctx.
|
||||
// Authenticate реализует [Authenticator]: всегда успех и [Anonymous].
|
||||
func (NopAuthenticator) Authenticate(_ context.Context, _ net.Conn) (TenantID, error) {
|
||||
return Anonymous, nil
|
||||
}
|
||||
+16
-17
@@ -1,23 +1,22 @@
|
||||
// Package auth defines the Authenticator interface and tenant identity types
|
||||
// for multi-tenant support.
|
||||
// Package auth определяет интерфейс Authenticator и типы идентификации тенантов
|
||||
// для multi-tenant конфигурации.
|
||||
//
|
||||
// # Current state
|
||||
// # Текущее состояние
|
||||
//
|
||||
// Only the scaffold is present. The [NopAuthenticator] is used everywhere and
|
||||
// returns [Anonymous], preserving existing single-tenant behaviour.
|
||||
// Реализован только каркас. Везде используется [NopAuthenticator] —
|
||||
// возвращает [Anonymous], сохраняя single-tenant поведение.
|
||||
//
|
||||
// # Planned multi-tenant flow
|
||||
// # Планируемый multi-tenant поток
|
||||
//
|
||||
// 1. A real Authenticator (e.g. HMACAuthenticator backed by SQLite) reads a
|
||||
// short token from the first bytes of conn, validates it against a per-tenant
|
||||
// shared secret, and returns the matching [TenantID].
|
||||
// 2. bondserver.Registry uses the TenantID as part of its de-duplication key so
|
||||
// ConnIDs from different tenants never collide.
|
||||
// 3. tcpfwdserver and udpserver resolve connectAddr per-tenant, allowing each
|
||||
// tenant to target a different backend.
|
||||
// 4. Deep-link provisioning delivers per-tenant secrets to mobile clients without
|
||||
// manual configuration.
|
||||
// 1. Реальный Authenticator (например HMACAuthenticator поверх SQLite) читает
|
||||
// короткий токен из первых байт conn, проверяет его против per-tenant
|
||||
// общего секрета и возвращает соответствующий [TenantID].
|
||||
// 2. bondserver.Registry использует TenantID как часть ключа дедупликации —
|
||||
// ConnID разных тенантов не пересекаются.
|
||||
// 3. tcpfwdserver и udpserver резолвят connectAddr per-tenant — каждый тенант
|
||||
// указывает на свой backend.
|
||||
// 4. Deep-link provisioning доставляет per-tenant секреты мобильным клиентам
|
||||
// без ручной настройки.
|
||||
//
|
||||
// None of the items above are implemented yet. See notes/AUTH_PLAN.md for the
|
||||
// detailed design.
|
||||
// Ничего из перечисленного пока не реализовано. См. notes/AUTH_PLAN.md.
|
||||
package auth
|
||||
@@ -25,12 +25,12 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
)
|
||||
|
||||
// Log is the package-level logger. Defaults to no-op; main wires it via
|
||||
// SetLogger so captcha output respects the global -debug flag and levels.
|
||||
// Solve also accepts an explicit logger parameter for callers that want DI.
|
||||
// Log — пакетный логгер. По умолчанию no-op; main устанавливает его через
|
||||
// SetLogger, чтобы captcha-вывод подчинялся глобальному -debug. Solve также
|
||||
// принимает logger параметром для DI.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package. Safe to call once at startup.
|
||||
// SetLogger ставит логгер пакета. Безопасно вызывать один раз при старте.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const (
|
||||
@@ -124,9 +124,9 @@ func (s *captchaSession) logger() logx.Logger {
|
||||
return Log
|
||||
}
|
||||
|
||||
// Solve runs the automatic captcha challenge against VK's captchaNotRobot API
|
||||
// and returns a success token on success. log may be nil, in which case the
|
||||
// package-level Log is used.
|
||||
// Solve запускает авторешение captcha против VK captchaNotRobot API
|
||||
// и возвращает success-токен при успехе. log может быть nil — тогда
|
||||
// используется пакетный Log.
|
||||
func Solve(
|
||||
ctx context.Context,
|
||||
captchaErr *Error,
|
||||
@@ -479,8 +479,8 @@ func solveCaptchaPoW(ctx context.Context, input string, difficulty int) string {
|
||||
return ""
|
||||
}
|
||||
target := strings.Repeat("0", difficulty)
|
||||
// ctx-check every 1024 iterations keeps cancel latency under a few ms
|
||||
// even on weak ARM (was every 4096).
|
||||
// ctx-check каждые 1024 итерации — задержка отмены в пределах нескольких мс
|
||||
// даже на слабом ARM (было 4096).
|
||||
buf := make([]byte, 0, len(input)+20)
|
||||
buf = append(buf, input...)
|
||||
for nonce := 1; nonce <= 10_000_000; nonce++ {
|
||||
|
||||
@@ -5,8 +5,8 @@ import (
|
||||
neturl "net/url"
|
||||
)
|
||||
|
||||
// Error describes a VK API "captcha required" error (error_code 14) and the
|
||||
// fields the solver needs to drive the challenge.
|
||||
// Error описывает ошибку VK API "captcha required" (error_code 14) и поля,
|
||||
// необходимые для решения challenge.
|
||||
type Error struct {
|
||||
ErrorCode int
|
||||
ErrorMsg string
|
||||
@@ -19,8 +19,8 @@ type Error struct {
|
||||
CaptchaAttempt string
|
||||
}
|
||||
|
||||
// ParseError extracts a captcha challenge from a VK API error payload. Returns
|
||||
// nil if required fields are missing.
|
||||
// ParseError извлекает captcha-challenge из payload ошибки VK API.
|
||||
// Возвращает nil, если обязательные поля отсутствуют.
|
||||
func ParseError(errData map[string]any) *Error {
|
||||
codeFloat, ok := errData["error_code"].(float64)
|
||||
if !ok {
|
||||
@@ -104,8 +104,8 @@ func ParseError(errData map[string]any) *Error {
|
||||
}
|
||||
}
|
||||
|
||||
// IsCaptcha reports whether this error represents an actionable captcha
|
||||
// challenge (error_code 14 with both redirect_uri and session_token present).
|
||||
// IsCaptcha сообщает, является ли это actionable captcha-challenge
|
||||
// (error_code 14 с непустыми redirect_uri и session_token).
|
||||
func (e *Error) IsCaptcha() bool {
|
||||
return e.ErrorCode == 14 && e.RedirectURI != "" && e.SessionToken != ""
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
// Package manual implements the manual CAPTCHA solving flow used as a
|
||||
// fallback when the auto solver (internal/client/captcha) fails or when
|
||||
// the user passes -manual-captcha. It runs a local HTTP server on
|
||||
// 127.0.0.1:8765 that proxies the VK CAPTCHA page (rewriting absolute
|
||||
// URLs and gzipping), opens it in the user's browser, and waits for the
|
||||
// token/key produced after the user completes the puzzle.
|
||||
// Package manual реализует ручное решение CAPTCHA — fallback, когда автосолвер
|
||||
// (internal/client/captcha) не справился или пользователь дал -manual-captcha.
|
||||
// Поднимает локальный HTTP-сервер 127.0.0.1:8765, проксирующий страницу VK
|
||||
// CAPTCHA (с переписыванием абсолютных URL и gzip), открывает её в браузере и
|
||||
// ждёт токен/ключ после решения пользователем.
|
||||
package manual
|
||||
|
||||
import (
|
||||
@@ -29,15 +28,15 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
)
|
||||
|
||||
// Debug toggles verbose request/response logging for the proxied browser
|
||||
// traffic. Set from main once cfg is parsed.
|
||||
// Debug включает подробное логирование request/response проксируемого
|
||||
// браузерного трафика. Ставится из main после разбора cfg.
|
||||
var Debug bool
|
||||
|
||||
// Log is the package-level logger; defaults to no-op. main wires it via
|
||||
// SetLogger so manual-captcha output respects -debug and levels.
|
||||
// Log — пакетный логгер; по умолчанию no-op. main устанавливает его через
|
||||
// SetLogger, чтобы вывод подчинялся -debug.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package.
|
||||
// SetLogger ставит логгер пакета.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const captchaListenPort = "8765"
|
||||
@@ -144,7 +143,7 @@ func rewriteProxyRequest(req *http.Request, targetURL *neturl.URL) {
|
||||
req.Host = targetURL.Host
|
||||
|
||||
req.Header.Del("Accept-Encoding")
|
||||
req.Header.Del("TE") // Disable transfer encoding compression
|
||||
req.Header.Del("TE") // отключить transfer encoding compression
|
||||
for _, h := range []string{
|
||||
"X-Requested-With",
|
||||
"X-Android-Package",
|
||||
@@ -196,28 +195,21 @@ func rewriteProxyCookies(header http.Header) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// rewriteHTMLAttrsServerSide переписывает абсолютные и protocol-relative URL
|
||||
// в src/href/action HTML на стороне сервера. URL, совпадающие с upstream origin,
|
||||
// идут на localhost; остальные — через /generic_proxy, чтобы cross-domain
|
||||
// ресурсы (st.vk.com, userapi.com и т.д.) грузились через прокси.
|
||||
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
|
||||
// нормализовать protocol-relative URL в абсолютный по upstream scheme
|
||||
absURL := rawURL
|
||||
if strings.HasPrefix(rawURL, "//") {
|
||||
absURL = targetURL.Scheme + ":" + rawURL
|
||||
@@ -225,11 +217,10 @@ func rewriteHTMLAttrsServerSide(html string, targetURL *neturl.URL) string {
|
||||
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
|
||||
// прочие абсолютные URL → через generic_proxy
|
||||
return "/generic_proxy?proxy_url=" + neturl.QueryEscape(absURL)
|
||||
}
|
||||
|
||||
@@ -282,12 +273,12 @@ func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string {
|
||||
localOrigin := localCaptchaOrigin()
|
||||
upstreamOrigin := targetOrigin(targetURL)
|
||||
|
||||
// Step 1: plain text replacement for the primary upstream origin
|
||||
// Шаг 1: текстовая замена основного 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.
|
||||
// Шаг 2: серверный rewrite остальных абсолютных URL в HTML-атрибутах.
|
||||
// Критично: браузер начинает грузить <script src> / <link href> / <img src>
|
||||
// сразу при парсинге HTML — раньше любых инжектированных JS-перехватов.
|
||||
html = rewriteHTMLAttrsServerSide(html, targetURL)
|
||||
|
||||
script := fmt.Sprintf(`
|
||||
@@ -484,8 +475,8 @@ func rewriteCaptchaHTML(html string, targetURL *neturl.URL) string {
|
||||
</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.
|
||||
// Шаг 3: инжектируем клиентский скрипт как можно раньше — после <head>,
|
||||
// чтобы XHR/fetch-перехваты были активны до любого inline <script> в <head>.
|
||||
switch {
|
||||
case strings.Contains(html, "<head>"):
|
||||
return strings.Replace(html, "<head>", "<head>"+script, 1)
|
||||
@@ -540,8 +531,8 @@ func startCaptchaServer(srv *http.Server, logPrefix string) error {
|
||||
return fmt.Errorf("captcha listeners failed: %s", strings.Join(listenErrs, "; "))
|
||||
}
|
||||
|
||||
// runCaptchaServerAndWait triggers the browser, and waiting gracefully for the solution token.
|
||||
// Returns ctx.Err() if ctx fires before a key arrives; in both cases the HTTP server is shut down.
|
||||
// runCaptchaServerAndWait открывает браузер и ждёт токен решения.
|
||||
// При срабатывании ctx возвращает ctx.Err(); в обоих случаях HTTP-сервер останавливается.
|
||||
func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaURL string, keyCh <-chan string, logPrefix string) (string, error) {
|
||||
srv := &http.Server{Handler: handler}
|
||||
|
||||
@@ -550,8 +541,8 @@ func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaU
|
||||
}
|
||||
|
||||
defer func() {
|
||||
// Best-effort shutdown. On iSH SetDeadline is a no-op and Shutdown may
|
||||
// time out while listeners drain; we still propagate the result.
|
||||
// best-effort shutdown. На iSH SetDeadline — no-op, Shutdown может
|
||||
// таймаутить при сливе listener'ов; результат всё равно прокидываем.
|
||||
shutCtx, shutCancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer shutCancel()
|
||||
if err := srv.Shutdown(shutCtx); err != nil {
|
||||
@@ -577,7 +568,7 @@ func runCaptchaServerAndWait(ctx context.Context, handler http.Handler, captchaU
|
||||
}
|
||||
}
|
||||
|
||||
// notifyKey pushes the key string to the given channel without blocking
|
||||
// notifyKey пушит ключ в канал без блокировки.
|
||||
func notifyKey(keyCh chan<- string, key string) {
|
||||
if key != "" {
|
||||
select {
|
||||
@@ -587,9 +578,8 @@ func notifyKey(keyCh chan<- string, key string) {
|
||||
}
|
||||
}
|
||||
|
||||
// SolveViaHTTP serves a tiny HTML page asking the user to solve the
|
||||
// pictured CAPTCHA, opens it in the browser, and blocks until the key
|
||||
// is posted back.
|
||||
// SolveViaHTTP отдаёт минимальную HTML-страницу для решения картинки CAPTCHA,
|
||||
// открывает её в браузере и блокируется до прихода ключа.
|
||||
func SolveViaHTTP(ctx context.Context, captchaImg string) (string, error) {
|
||||
keyCh := make(chan string, 1)
|
||||
mux := http.NewServeMux()
|
||||
@@ -651,7 +641,7 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
device := parsedBody.Get("device")
|
||||
browserFp := parsedBody.Get("browser_fp")
|
||||
|
||||
// We only save it if device is present. componentDone usually has it.
|
||||
// сохраняем только если есть device. componentDone обычно его содержит.
|
||||
if device != "" && browserFp != "" {
|
||||
sp := browserprofile.Saved{
|
||||
Profile: browserprofile.Profile{
|
||||
@@ -674,10 +664,9 @@ func (t *loggingTransport) RoundTrip(req *http.Request) (*http.Response, error)
|
||||
return t.rt.RoundTrip(req)
|
||||
}
|
||||
|
||||
// SolveViaProxy proxies the VK redirect_uri page through a local HTTP
|
||||
// server, rewriting absolute URLs so the browser stays on
|
||||
// 127.0.0.1:8765 throughout the puzzle, then returns the resulting
|
||||
// auth token.
|
||||
// SolveViaProxy проксирует VK redirect_uri через локальный HTTP-сервер,
|
||||
// переписывая абсолютные URL так, чтобы браузер всё время оставался на
|
||||
// 127.0.0.1:8765; возвращает результирующий auth-токен.
|
||||
func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (string, error) {
|
||||
keyCh := make(chan string, 1)
|
||||
|
||||
@@ -704,7 +693,7 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
|
||||
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
|
||||
// не логируем полный redirect URL — шум в консоли
|
||||
if rewritten, ok := rewriteProxyRedirectLocation(loc, targetURL); ok {
|
||||
res.Header.Set("Location", rewritten)
|
||||
} else {
|
||||
@@ -809,8 +798,8 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
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.
|
||||
// убираем security-заголовки, блокирующие cross-origin загрузку
|
||||
// статики (JS/CSS) при проксировании.
|
||||
for _, h := range []string{
|
||||
"Content-Security-Policy",
|
||||
"Content-Security-Policy-Report-Only",
|
||||
@@ -824,13 +813,13 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
} {
|
||||
res.Header.Del(h)
|
||||
}
|
||||
// Allow the browser to use the resource cross-origin
|
||||
// разрешаем 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.
|
||||
// captchaNotRobot.check уходит на api.vk.ru (другой хост, чем
|
||||
// upstream vk.com), поэтому идёт через /generic_proxy. Извлекаем
|
||||
// success_token здесь — серверный путь работает на iOS даже если
|
||||
// JS-callback в браузере не сработал.
|
||||
if strings.Contains(targetAuthURL, "captchaNotRobot.check") {
|
||||
bodyBytes, readErr := io.ReadAll(res.Body)
|
||||
if readErr == nil {
|
||||
@@ -851,7 +840,7 @@ func SolveViaProxy(ctx context.Context, redirectURI string, dialer net.Dialer) (
|
||||
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
||||
Log.Debugf("[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
|
||||
// не логируем полный redirect URL — шум в консоли
|
||||
http.Redirect(w, r, localCaptchaURLForTarget(targetURL), http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
@@ -872,11 +861,11 @@ func openBrowser(url string) {
|
||||
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.
|
||||
// 'rundll32 url.dll,FileProtocolHandler' надёжнее 'cmd /c start' —
|
||||
// не задействует shell (cmd.exe), нет проблем с '&' и спец-символами.
|
||||
return []browserCommand{
|
||||
{name: "rundll32", args: []string{"url.dll,FileProtocolHandler", url}},
|
||||
// Fallback with empty title argument for 'start' to handle potential quoting issues
|
||||
// fallback с пустым title для 'start' — обход проблем с кавычками
|
||||
{name: "cmd", args: []string{"/c", "start", "", url}},
|
||||
}
|
||||
case "darwin":
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
_ "image/jpeg" // register JPEG decoder for image.Decode
|
||||
_ "image/jpeg" // регистрация JPEG-декодера для image.Decode
|
||||
"math"
|
||||
mathrand "math/rand"
|
||||
"runtime"
|
||||
|
||||
@@ -17,15 +17,15 @@ func sharedDohResolver() *DohResolver {
|
||||
return dohResolverInstance
|
||||
}
|
||||
|
||||
// AppDialer returns the net.Dialer used by tls-client and other HTTP callers.
|
||||
// DNS transport is selected by mode (udp | doh | auto).
|
||||
// AppDialer возвращает net.Dialer для tls-client и других HTTP-вызывающих.
|
||||
// DNS-транспорт выбирается по mode (udp | doh | auto).
|
||||
func AppDialer(mode string) net.Dialer {
|
||||
return buildDialer(mode, sharedDohResolver())
|
||||
}
|
||||
|
||||
// InstallGlobalResolver wires net.DefaultResolver to the same DNS transport
|
||||
// as AppDialer, so third-party libs that build their own http.Client without
|
||||
// our Dialer still use DoH / auto-fallback instead of the OS resolver.
|
||||
// InstallGlobalResolver выставляет net.DefaultResolver на тот же DNS-транспорт,
|
||||
// что и AppDialer — чтобы сторонние библиотеки, собирающие свой http.Client
|
||||
// без нашего Dialer, тоже шли через DoH / auto-fallback, а не OS resolver.
|
||||
func InstallGlobalResolver(mode string) {
|
||||
d := AppDialer(mode)
|
||||
if d.Resolver != nil {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package dnsdial owns DNS resolution and the net.Dialer wired into all
|
||||
// outbound HTTP/TLS clients. Selects between UDP/53, DNS-over-HTTPS, or
|
||||
// auto (UDP probe → sticky DoH fallback) based on Mode.
|
||||
// Package dnsdial владеет DNS-резолвингом и net.Dialer'ом, прокинутым во все
|
||||
// outbound HTTP/TLS клиенты. По Mode выбирает UDP/53, DNS-over-HTTPS или auto
|
||||
// (UDP-probe → sticky DoH fallback).
|
||||
package dnsdial
|
||||
|
||||
import (
|
||||
@@ -21,21 +21,20 @@ import (
|
||||
|
||||
"github.com/samosvalishe/btp/internal/logx"
|
||||
|
||||
// Embedded Mozilla CA roots for CGO_ENABLED=0 builds (Android).
|
||||
// встроенные Mozilla CA roots для CGO_ENABLED=0 сборок (Android).
|
||||
_ "golang.org/x/crypto/x509roots/fallback"
|
||||
)
|
||||
|
||||
// Log is the package-level logger. Defaults to no-op; main wires it via
|
||||
// SetLogger so DNS-mode output respects the global -debug flag and levels.
|
||||
// Log — пакетный логгер. По умолчанию no-op; main устанавливает через SetLogger.
|
||||
var Log logx.Logger = logx.Nop()
|
||||
|
||||
// SetLogger installs a logger for this package.
|
||||
// SetLogger ставит логгер пакета.
|
||||
func SetLogger(l logx.Logger) { Log = logx.OrNop(l) }
|
||||
|
||||
const (
|
||||
dohQueryTimeout = 6 * time.Second
|
||||
// Total budget across all endpoint attempts in forwardRaw. Must be a
|
||||
// multiple of dohQueryTimeout to give every fallback a real chance.
|
||||
// общий бюджет для всех попыток endpoint'ов в forwardRaw. Кратно
|
||||
// dohQueryTimeout — чтобы каждому fallback хватило времени.
|
||||
dohForwardBudget = 25 * time.Second
|
||||
dohMaxResponseBytes = 64 * 1024
|
||||
dohContentType = "application/dns-message"
|
||||
@@ -51,33 +50,31 @@ const (
|
||||
autoUDPBudget = 1500 * time.Millisecond
|
||||
)
|
||||
|
||||
// DohEndpoint describes a single DNS-over-HTTPS server together with the IPs
|
||||
// we bootstrap to — so that resolving the endpoint hostname does not itself
|
||||
// require DNS.
|
||||
// DohEndpoint — один DNS-over-HTTPS сервер с bootstrap-IP, чтобы резолв самого
|
||||
// hostname не требовал DNS.
|
||||
type DohEndpoint struct {
|
||||
URL string
|
||||
Hostname string
|
||||
BootstrapIPs []string
|
||||
}
|
||||
|
||||
// Yandex is tried first because it tends to stay reachable on RU mobile
|
||||
// operators even when international resolvers get blocked; Google and
|
||||
// Cloudflare follow as fallbacks.
|
||||
// Yandex — первый, т.к. остаётся доступен у RU мобильных операторов даже когда
|
||||
// международные резолверы блокируются; Google и Cloudflare — fallback.
|
||||
var defaultDohEndpoints = []DohEndpoint{
|
||||
{"https://common.dot.dns.yandex.net/dns-query", "common.dot.dns.yandex.net", []string{"77.88.8.8", "77.88.8.1"}},
|
||||
{"https://secure.dot.dns.yandex.net/dns-query", "secure.dot.dns.yandex.net", []string{"77.88.8.88", "77.88.8.2"}},
|
||||
{"https://family.dot.dns.yandex.net/dns-query", "family.dot.dns.yandex.net", []string{"77.88.8.7", "77.88.8.3"}},
|
||||
}
|
||||
|
||||
// DohResolver POSTs DNS wire queries to one of several DoH endpoints.
|
||||
// DohResolver делает POST с DNS-wire запросом к одному из DoH endpoint'ов.
|
||||
type DohResolver struct {
|
||||
endpoints []DohEndpoint
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
// NewDohResolver constructs a resolver using defaultDohEndpoints if endpoints
|
||||
// is nil. Endpoint hostnames are dialed by IP using BootstrapIPs, so the DoH
|
||||
// transport never depends on the system resolver.
|
||||
// NewDohResolver конструирует резолвер; если endpoints=nil, берёт
|
||||
// defaultDohEndpoints. Имена endpoint'ов диалятся по BootstrapIPs — DoH-транспорт
|
||||
// не зависит от системного резолвера.
|
||||
func NewDohResolver(endpoints []DohEndpoint) *DohResolver {
|
||||
if len(endpoints) == 0 {
|
||||
endpoints = defaultDohEndpoints
|
||||
@@ -88,14 +85,13 @@ func NewDohResolver(endpoints []DohEndpoint) *DohResolver {
|
||||
}
|
||||
}
|
||||
|
||||
// newDohResolverWithClient is a test hook that skips the bootstrap transport.
|
||||
// newDohResolverWithClient — тестовый hook, минующий bootstrap-транспорт.
|
||||
func newDohResolverWithClient(endpoints []DohEndpoint, client *http.Client) *DohResolver {
|
||||
return &DohResolver{endpoints: endpoints, client: client}
|
||||
}
|
||||
|
||||
// newBootstrapTransport returns an http.Transport whose DialContext only
|
||||
// knows how to reach the configured DoH endpoint hostnames, by mapping each
|
||||
// to its BootstrapIPs.
|
||||
// newBootstrapTransport возвращает http.Transport, чей DialContext знает только
|
||||
// заданные hostname'ы DoH endpoint'ов и резолвит их в BootstrapIPs.
|
||||
func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
bootstrap := make(map[string][]string, len(endpoints))
|
||||
for _, ep := range endpoints {
|
||||
@@ -128,9 +124,9 @@ func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
}
|
||||
return nil, lastErr
|
||||
},
|
||||
// Explicit DialTLSContext ensures SNI = endpoint hostname even when
|
||||
// the underlying TCP dial targets a bootstrap IP. Without this, some
|
||||
// HTTP/2 paths can leak the literal IP as ServerName and fail TLS.
|
||||
// явный DialTLSContext гарантирует SNI = hostname, даже если TCP-dial
|
||||
// идёт на bootstrap-IP. Без этого некоторые HTTP/2 пути сливают
|
||||
// литерал IP как ServerName и TLS падает.
|
||||
DialTLSContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
@@ -164,15 +160,14 @@ func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
|
||||
}
|
||||
}
|
||||
|
||||
// forwardRaw POSTs an opaque DNS-wire query to the configured DoH endpoints
|
||||
// in order and returns the first successful raw response together with the
|
||||
// endpoint that produced it. No parsing — useful for the local forwarder
|
||||
// which needs to pass through whatever the upstream resolver answers
|
||||
// (RESINFO/HTTPS/SVCB/EDNS options/…).
|
||||
// forwardRaw делает POST opaque DNS-wire запроса к настроенным DoH endpoint'ам
|
||||
// по порядку и возвращает первый успешный raw-ответ вместе с endpoint'ом.
|
||||
// Без парсинга — удобно для локального форвардера, который пропускает что бы
|
||||
// upstream ни ответил (RESINFO/HTTPS/SVCB/EDNS options/…).
|
||||
//
|
||||
// Each endpoint gets its own per-attempt deadline (dohQueryTimeout) so a
|
||||
// slow first endpoint does not consume the entire budget and starve the
|
||||
// fallbacks. The parent ctx still bounds the total wait via cancel chain.
|
||||
// Каждому endpoint'у — свой per-attempt deadline (dohQueryTimeout), чтобы
|
||||
// медленный первый не сожрал весь бюджет и не зарезал fallback'и. Parent ctx
|
||||
// всё ещё ограничивает общее ожидание через cancel chain.
|
||||
func (r *DohResolver) forwardRaw(ctx context.Context, query []byte) ([]byte, DohEndpoint, error) {
|
||||
if len(r.endpoints) == 0 {
|
||||
return nil, DohEndpoint{}, errors.New("doh: no endpoints configured")
|
||||
@@ -195,7 +190,7 @@ func (r *DohResolver) forwardRaw(ctx context.Context, query []byte) ([]byte, Doh
|
||||
return nil, DohEndpoint{}, lastErr
|
||||
}
|
||||
|
||||
// postWire performs a single application/dns-message POST to one endpoint.
|
||||
// postWire делает один application/dns-message POST к одному endpoint'у.
|
||||
func (r *DohResolver) postWire(ctx context.Context, ep DohEndpoint, query []byte) ([]byte, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", ep.URL, bytes.NewReader(query))
|
||||
if err != nil {
|
||||
@@ -221,10 +216,10 @@ func (r *DohResolver) postWire(ctx context.Context, ep DohEndpoint, query []byte
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// Go's net.Resolver dials this stub like a regular nameserver, which avoids
|
||||
// the many edge cases of a fake-net.Conn approach (RESINFO probes, EDNS
|
||||
// handshakes, truncation, …). Whatever it reads on UDP/TCP is sent verbatim
|
||||
// to a DoH endpoint and the wire response is sent back to the client.
|
||||
// net.Resolver Go дозванивается до этого stub'а как до обычного nameserver'а —
|
||||
// обходит уйму edge-case'ов fake-net.Conn (RESINFO probes, EDNS handshakes,
|
||||
// truncation, …). Что бы он ни прочитал на UDP/TCP — уходит дословно в DoH
|
||||
// endpoint, ответ отдаётся клиенту.
|
||||
|
||||
type dohForwarder struct {
|
||||
udpAddr string
|
||||
@@ -237,9 +232,9 @@ var (
|
||||
dohForwarderErr error
|
||||
)
|
||||
|
||||
// sharedDohForwarder lazily starts a process-wide forwarder bound to the
|
||||
// supplied resolver. The first caller wins; subsequent callers reuse the
|
||||
// same forwarder regardless of what they pass in.
|
||||
// sharedDohForwarder лениво запускает process-wide форвардер, привязанный к
|
||||
// заданному resolver. Побеждает первый caller; следующие переиспользуют тот же
|
||||
// форвардер независимо от того, что передали.
|
||||
func sharedDohForwarder(r *DohResolver) (*dohForwarder, error) {
|
||||
dohForwarderOnce.Do(func() {
|
||||
dohForwarderInst, dohForwarderErr = startDohForwarder(r)
|
||||
@@ -350,8 +345,8 @@ func handleDohForwarderTCP(conn net.Conn, r *DohResolver) {
|
||||
}
|
||||
}
|
||||
|
||||
// dohForwarderDial returns a Resolver.Dial that connects to the local DoH
|
||||
// forwarder over UDP or TCP (whichever the resolver asked for).
|
||||
// dohForwarderDial возвращает Resolver.Dial, подключающийся к локальному DoH
|
||||
// форвардеру по UDP или TCP (что запросил резолвер).
|
||||
func dohForwarderDial(r *DohResolver) dialFunc {
|
||||
return func(ctx context.Context, network, _ string) (net.Conn, error) {
|
||||
fwd, err := sharedDohForwarder(r)
|
||||
@@ -387,13 +382,13 @@ func init() {
|
||||
|
||||
func udpDNSServers() []string { return *udpDNSServersPtr.Load() }
|
||||
|
||||
// SetUDPDNSServers replaces the default UDP/53 server list. Each entry may be
|
||||
// "ip" or "ip:port" — bare IPs get :53 appended. Empty list keeps the defaults.
|
||||
// Used on Android to inject the carrier's resolver IPs from
|
||||
// LinkProperties.dnsServers, which often work where public DoH/DoT do not.
|
||||
// SetUDPDNSServers заменяет дефолтный список UDP/53 серверов. Каждый элемент —
|
||||
// "ip" или "ip:port"; голые IP получают :53. Пустой список оставляет дефолт.
|
||||
// На Android используется для подсовывания резолверов оператора из
|
||||
// LinkProperties.dnsServers — часто работают там, где публичный DoH/DoT нет.
|
||||
//
|
||||
// Safe to call concurrently with resolver use — the list pointer is swapped
|
||||
// atomically. Existing in-flight dials see whichever snapshot they captured.
|
||||
// Безопасно вызывать конкурентно с использованием резолвера — указатель списка
|
||||
// меняется атомарно. Уже идущие dial видят свой захваченный снимок.
|
||||
func SetUDPDNSServers(servers []string) {
|
||||
if len(servers) == 0 {
|
||||
return
|
||||
@@ -417,9 +412,9 @@ func SetUDPDNSServers(servers []string) {
|
||||
|
||||
type dialFunc = func(context.Context, string, string) (net.Conn, error)
|
||||
|
||||
// buildDialer returns a net.Dialer whose internal Go resolver uses the
|
||||
// chosen DNS transport. In "auto" mode the first total-failure of UDP/53
|
||||
// sticks the process onto DoH for the rest of its lifetime.
|
||||
// buildDialer возвращает net.Dialer, чей внутренний Go-резолвер использует
|
||||
// выбранный DNS-транспорт. В режиме "auto" первый полный отказ UDP/53
|
||||
// залипает процесс на DoH до конца его жизни.
|
||||
func buildDialer(mode string, r *DohResolver) net.Dialer {
|
||||
switch mode {
|
||||
case DNSModeUDP:
|
||||
@@ -433,8 +428,8 @@ func buildDialer(mode string, r *DohResolver) net.Dialer {
|
||||
}
|
||||
}
|
||||
|
||||
// newAppDialer wraps a Resolver.Dial with the timeouts used everywhere in
|
||||
// the app for outbound TCP/HTTP connections.
|
||||
// newAppDialer оборачивает Resolver.Dial таймаутами, используемыми везде в
|
||||
// приложении для outbound TCP/HTTP.
|
||||
func newAppDialer(dial dialFunc) net.Dialer {
|
||||
return net.Dialer{
|
||||
Timeout: appDialerTimeout,
|
||||
@@ -443,7 +438,7 @@ func newAppDialer(dial dialFunc) net.Dialer {
|
||||
}
|
||||
}
|
||||
|
||||
// udpDNSDial picks the first reachable UDP/53 resolver from udpDNSServers.
|
||||
// udpDNSDial берёт первый достижимый UDP/53 резолвер из udpDNSServers.
|
||||
func udpDNSDial(ctx context.Context, _ string, _ string) (net.Conn, error) {
|
||||
var (
|
||||
d net.Dialer
|
||||
@@ -462,14 +457,12 @@ func udpDNSDial(ctx context.Context, _ string, _ string) (net.Conn, error) {
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
// autoDial returns a Dial that probes UDP/53 once with a real DNS round-trip;
|
||||
// if the probe fails it latches onto DoH for the rest of the process. Built
|
||||
// for Android, where the network can flip between Wi-Fi (UDP/53 works) and
|
||||
// mobile (UDP/53 blocked).
|
||||
// autoDial возвращает Dial, который один раз пробит UDP/53 реальным DNS
|
||||
// round-trip'ом; при провале залипает на DoH до конца процесса. Сделано под
|
||||
// Android, где сеть скачет между Wi-Fi (UDP/53 работает) и мобилкой (блок).
|
||||
//
|
||||
// A simple dial-timeout doesn't work for UDP because UDP "dial" is
|
||||
// connectionless and always succeeds instantly. The only way to know whether
|
||||
// UDP/53 actually works is to send a real query and wait for a response.
|
||||
// Просто dial-timeout не годится: UDP "dial" безсоединительный и всегда успешен
|
||||
// мгновенно. Единственный способ узнать — реально отправить запрос и ждать ответ.
|
||||
func autoDial(r *DohResolver) dialFunc {
|
||||
var (
|
||||
probed sync.Once
|
||||
@@ -492,10 +485,9 @@ func autoDial(r *DohResolver) dialFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// udpProbe sends a real DNS A query for a well-known domain via UDP and
|
||||
// checks whether any response arrives within the deadline. We try the first
|
||||
// two servers from udpDNSServers under a shared deadline — if neither
|
||||
// responds, UDP/53 is blocked.
|
||||
// udpProbe шлёт реальный DNS A-запрос к known-домену по UDP и проверяет, придёт
|
||||
// ли ответ до дедлайна. Пробуем первые два сервера из udpDNSServers под общим
|
||||
// deadline — если ни один не ответил, UDP/53 заблокирован.
|
||||
func udpProbe(timeout time.Duration) bool {
|
||||
m := new(dns.Msg)
|
||||
m.SetQuestion("dns.google.", dns.TypeA)
|
||||
|
||||
@@ -17,8 +17,8 @@ type listener struct {
|
||||
fd int
|
||||
}
|
||||
|
||||
// WrapListener overrides the standard net.Listener with a legacy syscall listener
|
||||
// designed specifically for the iSH simulator on iOS, which lacks modern `accept4`.
|
||||
// WrapListener подменяет стандартный net.Listener на legacy-syscall listener,
|
||||
// заточенный под iSH-симулятор на iOS, где нет современного `accept4`.
|
||||
func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
tl, ok := ln.(*net.TCPListener)
|
||||
if !ok {
|
||||
@@ -29,13 +29,14 @@ func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Keep a reference to *os.File so the garbage collector doesn't close the FD.
|
||||
// держим ссылку на *os.File, чтобы GC не закрыл FD.
|
||||
return &listener{Listener: ln, f: f, fd: int(f.Fd())}, nil
|
||||
}
|
||||
|
||||
func (l *listener) 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.
|
||||
// ставим listener-сокет в blocking. Go по умолчанию делает его non-blocking.
|
||||
// Это избавляет от time.Sleep в spin-loop, который триггерит futex_time64 SIGSYS
|
||||
// в современном Go на iSH.
|
||||
if err := syscall.SetNonblock(l.fd, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -44,11 +45,11 @@ func (l *listener) Accept() (net.Conn, error) {
|
||||
addr := make([]byte, 128)
|
||||
addrlen := uintptr(128)
|
||||
|
||||
// i386 network syscalls are multiplexed via socketcall (102).
|
||||
// SYS_ACCEPT is subcall 5.
|
||||
// i386 сетевые syscall'ы мультиплексируются через socketcall (102).
|
||||
// SYS_ACCEPT — 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.
|
||||
// Syscall6 — чтобы хватило регистров аргументов на этой платформе.
|
||||
r1, _, errno := syscall.Syscall6(102, 5, uintptr(unsafe.Pointer(&args)), 0, 0, 0, 0)
|
||||
if errno != 0 {
|
||||
if errno == syscall.EINTR {
|
||||
@@ -62,16 +63,15 @@ func (l *listener) Accept() (net.Conn, error) {
|
||||
_ = 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.
|
||||
// избегаем net.FileConn — она регистрирует fd в Go epoll poller'е, что в
|
||||
// iSH стабильно падает с EEXIST. Возвращаем кастомный blocking net.Conn.
|
||||
conn := &ishConn{fd: nfd}
|
||||
return conn, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (l *listener) Close() error {
|
||||
// Close both the duplicated FD and the original listener.
|
||||
// закрываем и дублированный FD, и оригинальный listener.
|
||||
err1 := l.f.Close()
|
||||
err2 := l.Listener.Close()
|
||||
if err1 != nil {
|
||||
@@ -80,7 +80,7 @@ func (l *listener) Close() error {
|
||||
return err2
|
||||
}
|
||||
|
||||
// ishConn bypasses Go's network poller to prevent EEXIST bugs in iSH
|
||||
// ishConn обходит сетевой poller Go, чтобы не словить EEXIST в iSH.
|
||||
type ishConn struct {
|
||||
fd int
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
//go:build !(linux && 386)
|
||||
|
||||
// Package ish provides a TCP listener shim for iSH (https://ish.app), a
|
||||
// Linux user-mode emulator that runs on iOS. iSH targets linux/386 and lacks
|
||||
// modern accept4 / Go's epoll-based poller, so a sandbox-aware accept loop
|
||||
// is needed there. On every other GOOS/GOARCH WrapListener is a no-op
|
||||
// pass-through.
|
||||
// Package ish — TCP listener shim для iSH (https://ish.app), Linux user-mode
|
||||
// эмулятор на iOS. iSH таргетит linux/386 и не имеет современного accept4 /
|
||||
// epoll-poller Go, поэтому там нужен sandbox-aware accept loop. На любом
|
||||
// другом GOOS/GOARCH WrapListener — no-op passthrough.
|
||||
package ish
|
||||
|
||||
import "net"
|
||||
|
||||
// WrapListener returns ln unchanged on non-iSH platforms.
|
||||
// WrapListener возвращает ln без изменений на не-iSH платформах.
|
||||
func WrapListener(ln net.Listener) (net.Listener, error) {
|
||||
return ln, nil
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package namegen produces random Russian-style display names for
|
||||
// client identities. Name pools are embedded from data/*.txt.
|
||||
// Package namegen генерирует случайные русскоязычные display name'ы для
|
||||
// идентичностей клиента. Пулы имён встроены из data/*.txt.
|
||||
package namegen
|
||||
|
||||
import (
|
||||
@@ -35,10 +35,10 @@ func parseLines(s string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// feminizeSurname converts a Russian male surname to its female form.
|
||||
// Operates on runes since Cyrillic letters are multibyte in UTF-8.
|
||||
// Surnames whose suffixes do not match Russian patterns are returned
|
||||
// unchanged (covers foreign / meme surnames).
|
||||
// feminizeSurname переводит мужскую фамилию в женскую форму.
|
||||
// Работает по рунам — кириллица многобайтовая в UTF-8.
|
||||
// Фамилии с не-русскими суффиксами возвращаются без изменений
|
||||
// (иностранные / мемные).
|
||||
func feminizeSurname(surname string) string {
|
||||
rs := []rune(surname)
|
||||
n := len(rs)
|
||||
@@ -54,11 +54,11 @@ func feminizeSurname(surname string) string {
|
||||
return surname
|
||||
}
|
||||
|
||||
// SurnameProbability is the chance that Generate returns a name with a surname.
|
||||
// SurnameProbability — вероятность того, что Generate вернёт имя с фамилией.
|
||||
const SurnameProbability = 0.7
|
||||
|
||||
// Generate returns a random "FirstName" or "FirstName LastName".
|
||||
// Gender is chosen uniformly; surnames are feminized for female names.
|
||||
// Generate возвращает случайное "Имя" или "Имя Фамилия".
|
||||
// Пол выбирается равномерно; женские фамилии феминизируются.
|
||||
func Generate() string {
|
||||
isFemale := rand.IntN(2) == 0
|
||||
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// DefaultAutoSolve drives the in-page widget flow. It loads a saved real
|
||||
// browser profile when available so the captcha origin sees consistent
|
||||
// fingerprints across the page load and the solve POST.
|
||||
// DefaultAutoSolve запускает in-page widget flow. Загружает сохранённый профиль
|
||||
// браузера, если доступен, — капча видит стабильные fingerprints на этапе
|
||||
// загрузки страницы и POST-запроса.
|
||||
func DefaultAutoSolve(
|
||||
ctx context.Context,
|
||||
captchaErr *captcha.Error,
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
// StreamCredentialsCache holds the resolved TURN creds for a group of streams
|
||||
// plus auth-error tracking for invalidation decisions.
|
||||
// StreamCredentialsCache хранит TURN-реквизиты для группы потоков
|
||||
// и счётчик ошибок для решений об инвалидации.
|
||||
type StreamCredentialsCache struct {
|
||||
creds TurnCredentials
|
||||
mutex sync.RWMutex
|
||||
@@ -15,7 +15,7 @@ type StreamCredentialsCache struct {
|
||||
lastErrorTime atomic.Int64
|
||||
}
|
||||
|
||||
// Store maps cache-id (streamID / streamsPerCache) -> StreamCredentialsCache.
|
||||
// Store отображает cache-id (streamID / streamsPerCache) → StreamCredentialsCache.
|
||||
type Store struct {
|
||||
mu sync.RWMutex
|
||||
caches map[int]*StreamCredentialsCache
|
||||
@@ -57,7 +57,7 @@ func (s *Store) Get(streamID int) *StreamCredentialsCache {
|
||||
return cache
|
||||
}
|
||||
|
||||
// Invalidate clears the creds for the given stream's cache and resets error state.
|
||||
// Invalidate сбрасывает реквизиты кэша потока и обнуляет счётчик ошибок.
|
||||
func (c *StreamCredentialsCache) Invalidate() {
|
||||
c.mutex.Lock()
|
||||
c.creds = TurnCredentials{}
|
||||
@@ -67,8 +67,8 @@ func (c *StreamCredentialsCache) Invalidate() {
|
||||
c.lastErrorTime.Store(0)
|
||||
}
|
||||
|
||||
// IsAuthError matches the historical heuristic used by the TURN client: a TURN
|
||||
// allocate failure mentioning auth/401/stale-nonce should trigger cache invalidate.
|
||||
// IsAuthError проверяет ошибку по эвристике TURN-клиента:
|
||||
// auth/401/stale-nonce — признак инвалидации кэша.
|
||||
func IsAuthError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
|
||||
@@ -16,37 +16,38 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// Config configures a Client. Zero values pick safe defaults except for Dialer
|
||||
// (must be set explicitly to preserve the existing custom-DNS behavior).
|
||||
// Config конфигурирует Client. Нулевые значения — безопасные дефолты,
|
||||
// кроме Dialer (должен быть задан явно для кастомного DNS).
|
||||
type Config struct {
|
||||
// Credentials to try in order. nil/empty -> DefaultCredentials.
|
||||
// Credentials для перебора по порядку. nil/empty → DefaultCredentials.
|
||||
Credentials []VKCredentials
|
||||
|
||||
// Dialer used by the HTTP transport for VK API requests.
|
||||
// Dialer для HTTP-транспорта запросов к VK API.
|
||||
Dialer net.Dialer
|
||||
|
||||
// ManualOnly forces the manual captcha path on the first attempt.
|
||||
// ManualOnly форсирует ручной путь captcha с первой попытки.
|
||||
ManualOnly bool
|
||||
|
||||
// StreamsPerCache is the divisor for streamID -> cacheID. <=0 -> default.
|
||||
// StreamsPerCache — делитель streamID → cacheID. <=0 → дефолт.
|
||||
StreamsPerCache int
|
||||
|
||||
// StreamsAlive returns the count of currently-connected streams; used to
|
||||
// decide whether an exhausted captcha is fatal vs throttleable. nil -> 1.
|
||||
// StreamsAlive возвращает число подключённых потоков; используется для
|
||||
// решения, является ли исчерпанная captcha фатальной или только throttle.
|
||||
// nil → 1.
|
||||
StreamsAlive func() int32
|
||||
|
||||
// AutoSolver / ManualSolver are pluggable captcha solvers. nil values
|
||||
// disable that path (the flow will fall through to the next attempt).
|
||||
// AutoSolver / ManualSolver — подключаемые решалки captcha. nil отключает
|
||||
// соответствующий путь (поток переходит к следующей попытке).
|
||||
AutoSolver AutoSolveFunc
|
||||
ManualSolver ManualSolveFunc
|
||||
|
||||
// Log is the leveled logger. nil -> no-op.
|
||||
// Log — уровневый логгер. nil → no-op.
|
||||
Log logx.Logger
|
||||
}
|
||||
|
||||
// Client is the VK auth + creds-cache facade used by callers. It owns the
|
||||
// per-stream-group cache, the global request throttle, the captcha lockout
|
||||
// timer, and the auth-error counter used to invalidate stale TURN creds.
|
||||
// Client — фасад VK-аутентификации и кэша реквизитов. Владеет кэшем группы
|
||||
// потоков, глобальным throttle запросов, таймером блокировки captcha и счётчиком
|
||||
// ошибок аутентификации для инвалидации устаревших TURN-реквизитов.
|
||||
type Client struct {
|
||||
credentials []VKCredentials
|
||||
dialer net.Dialer
|
||||
@@ -63,17 +64,16 @@ type Client struct {
|
||||
fetchMu sync.Mutex
|
||||
lastFetchTime time.Time
|
||||
|
||||
// tokenChain is the per-creds 4-step fetcher. Production wires this to
|
||||
// (*Client).getTokenChain; tests inject a fake.
|
||||
// tokenChain — 4-шаговый получатель токена для пары credentials.
|
||||
// В prod подключён (*Client).getTokenChain; тесты подменяют fake.
|
||||
tokenChain tokenChainFn
|
||||
|
||||
// minFetchInterval gates back-to-back VK requests. Tests can lower this.
|
||||
// minFetchIntervalFn ограничивает частоту запросов к VK. Тесты снижают.
|
||||
minFetchIntervalFn func() time.Duration
|
||||
}
|
||||
|
||||
type tokenChainFn func(ctx context.Context, link string, streamID int, creds VKCredentials, jar tlsclient.CookieJar) (string, string, []string, error)
|
||||
|
||||
// New builds a Client from cfg.
|
||||
func New(cfg Config) *Client {
|
||||
c := &Client{
|
||||
credentials: cfg.Credentials,
|
||||
@@ -101,8 +101,8 @@ func New(cfg Config) *Client {
|
||||
return c
|
||||
}
|
||||
|
||||
// GetCredentials returns (username, password, server-addr) suitable for a TURN
|
||||
// allocate, fetching from VK (with throttle + cache) only when needed.
|
||||
// GetCredentials возвращает (username, password, server-addr) для TURN-allocate,
|
||||
// обращаясь к VK (с throttle + кэшем) только при необходимости.
|
||||
func (c *Client) GetCredentials(ctx context.Context, link string, streamID int) (string, string, string, error) {
|
||||
cache := c.store.Get(streamID)
|
||||
cacheID := c.store.CacheID(streamID)
|
||||
@@ -142,9 +142,9 @@ func (c *Client) GetCredentials(ctx context.Context, link string, streamID int)
|
||||
return user, pass, addr, nil
|
||||
}
|
||||
|
||||
// HandleAuthError increments the auth-error counter for the stream's cache and
|
||||
// invalidates when the threshold is reached within the rolling window.
|
||||
// Returns true when the cache was invalidated.
|
||||
// HandleAuthError увеличивает счётчик ошибок аутентификации кэша потока и
|
||||
// инвалидирует кэш при достижении порога внутри скользящего окна.
|
||||
// Возвращает true при инвалидации.
|
||||
func (c *Client) HandleAuthError(streamID int) bool {
|
||||
cache := c.store.Get(streamID)
|
||||
cacheID := c.store.CacheID(streamID)
|
||||
@@ -167,28 +167,27 @@ func (c *Client) HandleAuthError(streamID int) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// ResetErrors zeroes the auth-error counter (call on successful allocate).
|
||||
// ResetErrors обнуляет счётчик ошибок аутентификации (вызывать при успешном allocate).
|
||||
func (c *Client) ResetErrors(streamID int) {
|
||||
c.store.Get(streamID).errorCount.Store(0)
|
||||
}
|
||||
|
||||
// LockoutUntilUnix returns the unix-second deadline the global captcha lockout
|
||||
// is set to, or 0 when no lockout is active.
|
||||
// LockoutUntilUnix возвращает unix-секунду дедлайна глобальной блокировки captcha
|
||||
// или 0, если блокировки нет.
|
||||
func (c *Client) LockoutUntilUnix() int64 {
|
||||
return c.lockout.Load()
|
||||
}
|
||||
|
||||
// IsAuthError mirrors the package-level IsAuthError as a method so callers can
|
||||
// program against a small interface.
|
||||
// IsAuthError оборачивает пакетный IsAuthError как метод для работы через интерфейс.
|
||||
func (c *Client) IsAuthError(err error) bool { return IsAuthError(err) }
|
||||
|
||||
// engageLockout arms the global captcha lockout for d from now.
|
||||
// engageLockout устанавливает глобальную блокировку captcha на d с момента вызова.
|
||||
func (c *Client) engageLockout(d time.Duration) {
|
||||
c.lockout.Store(time.Now().Add(d).Unix())
|
||||
}
|
||||
|
||||
// fetchSerialized enforces the 3s + jitter inter-request gap and then performs
|
||||
// the try-all-credentials fetch.
|
||||
// fetchSerialized соблюдает интервал 3s+jitter между запросами, затем
|
||||
// выполняет перебор всех credentials.
|
||||
func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int) (string, string, []string, error) {
|
||||
c.fetchMu.Lock()
|
||||
defer c.fetchMu.Unlock()
|
||||
@@ -208,7 +207,7 @@ func (c *Client) fetchSerialized(ctx context.Context, link string, streamID int)
|
||||
return c.fetch(ctx, link, streamID)
|
||||
}
|
||||
|
||||
// fetch loops over c.credentials, returning on first success or terminal error.
|
||||
// fetch перебирает c.credentials, возвращая первый успех или терминальную ошибку.
|
||||
func (c *Client) fetch(ctx context.Context, link string, streamID int) (string, string, []string, error) {
|
||||
if time.Now().Unix() < c.lockout.Load() {
|
||||
return "", "", nil, fmt.Errorf("%w: %w", ErrCaptchaWaitRequired, ErrLockoutActive)
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// CaptchaSolveMode selects between auto-solving and manual-browser fallback.
|
||||
// CaptchaSolveMode — выбор между автоматическим решением и ручным браузерным fallback.
|
||||
type CaptchaSolveMode int
|
||||
|
||||
const (
|
||||
@@ -18,8 +18,8 @@ const (
|
||||
CaptchaSolveModeManual
|
||||
)
|
||||
|
||||
// CaptchaSolveModeForAttempt picks the solver to use on a given retry attempt.
|
||||
// Returns (mode, true) when a mode is available, (_, false) when exhausted.
|
||||
// CaptchaSolveModeForAttempt выбирает решалку для конкретной попытки retry.
|
||||
// Возвращает (mode, true) если режим доступен, (_, false) если исчерпан.
|
||||
func CaptchaSolveModeForAttempt(attempt int, manualOnly bool) (CaptchaSolveMode, bool) {
|
||||
if manualOnly {
|
||||
return CaptchaSolveModeManual, attempt == 0
|
||||
@@ -44,8 +44,8 @@ func CaptchaSolveModeLabel(mode CaptchaSolveMode) string {
|
||||
}
|
||||
}
|
||||
|
||||
// AutoSolveFunc returns a success_token for the captcha when solvable via the
|
||||
// in-page widget flow. Implementations must respect ctx cancellation.
|
||||
// AutoSolveFunc возвращает success_token для captcha через in-page widget flow.
|
||||
// Реализации обязаны соблюдать отмену ctx.
|
||||
type AutoSolveFunc func(
|
||||
ctx context.Context,
|
||||
captchaErr *captcha.Error,
|
||||
@@ -54,9 +54,9 @@ type AutoSolveFunc func(
|
||||
profile browserprofile.Profile,
|
||||
) (token string, err error)
|
||||
|
||||
// ManualSolveFunc opens the local browser-based fallback. Returns either a
|
||||
// success_token (token != "") or a captcha_key, depending on which path the
|
||||
// VK error exposed.
|
||||
// ManualSolveFunc открывает локальный браузерный fallback. Возвращает либо
|
||||
// success_token (token != ""), либо captcha_key — в зависимости от пути
|
||||
// ошибки VK.
|
||||
type ManualSolveFunc func(
|
||||
ctx context.Context,
|
||||
captchaErr *captcha.Error,
|
||||
|
||||
@@ -12,9 +12,9 @@ import (
|
||||
"github.com/bogdanfinn/tls-client/profiles"
|
||||
)
|
||||
|
||||
// getTokenChain walks the 4-step VK token exchange for one client_id/secret
|
||||
// pair and returns the resulting TURN allocate triple. Captcha errors trigger
|
||||
// the configured auto/manual solver chain.
|
||||
// getTokenChain выполняет 4-шаговый обмен токенами VK для одной пары client_id/secret
|
||||
// и возвращает тройку TURN-allocate. Ошибки captcha запускают настроенную цепочку
|
||||
// auto/manual solver.
|
||||
func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, creds VKCredentials, jar tlsclient.CookieJar) (string, string, []string, error) {
|
||||
profile := browserprofile.Profile{
|
||||
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
|
||||
@@ -38,7 +38,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
|
||||
c.log.Infof("[STREAM %d] [VK Auth] Connecting Identity - Name: %s | User-Agent: %s", streamID, name, profile.UserAgent)
|
||||
|
||||
// Step 1: anonymous app token.
|
||||
// Шаг 1: анонимный app-токен.
|
||||
token1, err := c.fetchAnonToken(ctx, httpClient, profile, creds)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
@@ -46,7 +46,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
|
||||
vkDelayRandom(100, 150)
|
||||
|
||||
// Step 1a: getCallPreview warmup (non-fatal).
|
||||
// Шаг 1a: прогрев getCallPreview (не критично).
|
||||
previewData := fmt.Sprintf("vk_join_link=https://vk.com/call/join/%s&fields=photo_200&access_token=%s", link, token1)
|
||||
if _, prevErr := c.doRequest(ctx, httpClient, profile, previewData,
|
||||
"https://api.vk.ru/method/calls.getCallPreview?v=5.275&client_id="+creds.ClientID); prevErr != nil {
|
||||
@@ -55,7 +55,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
|
||||
vkDelayRandom(200, 400)
|
||||
|
||||
// Step 2: anonymous call token (captcha may trigger here).
|
||||
// Шаг 2: анонимный call-токен (здесь может сработать captcha).
|
||||
token2, err := c.fetchCallToken(ctx, httpClient, profile, streamID, link, escapedName, token1, creds)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
@@ -63,7 +63,7 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
|
||||
vkDelayRandom(100, 150)
|
||||
|
||||
// Step 3: ok.ru session_key.
|
||||
// Шаг 3: ok.ru session_key.
|
||||
sessionKey, err := c.fetchOkRuSession(ctx, httpClient, profile)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
@@ -71,6 +71,6 @@ func (c *Client) getTokenChain(ctx context.Context, link string, streamID int, c
|
||||
|
||||
vkDelayRandom(100, 150)
|
||||
|
||||
// Step 4: TURN credentials.
|
||||
// Шаг 4: TURN-реквизиты.
|
||||
return c.fetchTurnCreds(ctx, httpClient, profile, streamID, link, token2, sessionKey)
|
||||
}
|
||||
@@ -9,8 +9,8 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// fetchAnonToken performs step 1 of the token chain: it exchanges the app
|
||||
// client_id/client_secret for an anonymous access token from login.vk.ru.
|
||||
// fetchAnonToken — шаг 1 цепочки: обменивает app client_id/client_secret
|
||||
// на анонимный access token из login.vk.ru.
|
||||
func (c *Client) fetchAnonToken(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile, creds VKCredentials) (string, error) {
|
||||
data := fmt.Sprintf("client_id=%s&token_type=messages&client_secret=%s&version=1&app_id=%s",
|
||||
creds.ClientID, creds.ClientSecret, creds.ClientID)
|
||||
|
||||
@@ -13,9 +13,8 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// fetchCallToken performs step 2 of the token chain: it calls
|
||||
// calls.getAnonymousToken and drives the captcha-retry loop until a call token
|
||||
// is returned or all solve modes are exhausted.
|
||||
// fetchCallToken — шаг 2 цепочки: вызывает calls.getAnonymousToken и ведёт
|
||||
// цикл retry captcha до получения call-токена или исчерпания всех режимов решения.
|
||||
func (c *Client) fetchCallToken(
|
||||
ctx context.Context,
|
||||
httpClient tlsclient.HttpClient,
|
||||
@@ -59,8 +58,8 @@ func (c *Client) fetchCallToken(
|
||||
}
|
||||
}
|
||||
|
||||
// solveCaptcha drives one captcha solve attempt and returns the POST body for
|
||||
// the next retry, or an error when all modes are exhausted.
|
||||
// solveCaptcha выполняет одну попытку решения captcha и возвращает тело POST
|
||||
// для следующего retry или ошибку при исчерпании всех режимов.
|
||||
func (c *Client) solveCaptcha(
|
||||
ctx context.Context,
|
||||
httpClient tlsclient.HttpClient,
|
||||
@@ -105,9 +104,9 @@ func (c *Client) solveCaptcha(
|
||||
break
|
||||
}
|
||||
c.log.Infof("[STREAM %d] [Captcha] Triggering manual captcha fallback", streamID)
|
||||
// Manual solver gets its own 3-min budget so a tight parent deadline
|
||||
// doesn't cut user solve time. Parent cancellation (app shutdown) still
|
||||
// propagates so the goroutine doesn't outlive the process.
|
||||
// Ручной решалке выделяется свой 3-минутный бюджет — жёсткий parent-deadline
|
||||
// не обрезает время пользователя. Отмена parent (завершение приложения)
|
||||
// всё равно propagate, горутина не переживает процесс.
|
||||
manualCtx, manualCancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
|
||||
type manualRes struct {
|
||||
@@ -168,7 +167,7 @@ func (c *Client) solveCaptcha(
|
||||
return buildCaptchaRetryData(link, escapedName, token1, captchaErr, successToken, captchaKey), nil
|
||||
}
|
||||
|
||||
// buildCaptchaRetryData constructs the POST body for the next captcha attempt.
|
||||
// buildCaptchaRetryData формирует тело POST для следующей попытки captcha.
|
||||
func buildCaptchaRetryData(link, escapedName, token1 string, captchaErr *captcha.Error, successToken, captchaKey string) string {
|
||||
if captchaKey != "" {
|
||||
return fmt.Sprintf(
|
||||
|
||||
@@ -10,9 +10,8 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// fetchTurnCreds performs step 4 of the token chain: it calls
|
||||
// vchat.joinConversationByLink and extracts the TURN username, credential, and
|
||||
// address list from the response.
|
||||
// fetchTurnCreds — шаг 4 цепочки: вызывает vchat.joinConversationByLink
|
||||
// и извлекает TURN username, credential и список адресов из ответа.
|
||||
func (c *Client) fetchTurnCreds(
|
||||
ctx context.Context,
|
||||
httpClient tlsclient.HttpClient,
|
||||
|
||||
@@ -11,8 +11,8 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// fetchOkRuSession performs step 3 of the token chain: it obtains an anonymous
|
||||
// ok.ru session_key via auth.anonymLogin.
|
||||
// fetchOkRuSession — шаг 3 цепочки: получает анонимный ok.ru session_key
|
||||
// через auth.anonymLogin.
|
||||
func (c *Client) fetchOkRuSession(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile) (string, error) {
|
||||
sessionData := fmt.Sprintf(`{"version":2,"device_id":"%s","client_version":1.1,"client_type":"SDK_JS"}`, uuid.New())
|
||||
data := fmt.Sprintf("session_data=%s&method=auth.anonymLogin&format=JSON&application_key=CGMMEJLGDIHBABABA",
|
||||
|
||||
@@ -14,8 +14,8 @@ import (
|
||||
tlsclient "github.com/bogdanfinn/tls-client"
|
||||
)
|
||||
|
||||
// doRequest sends a POST form request to url using the given tls client and
|
||||
// browser profile, and unmarshals the JSON response body.
|
||||
// doRequest отправляет POST form-запрос по url через tls-клиент с браузерным
|
||||
// профилем и десериализует JSON-тело ответа.
|
||||
func (c *Client) doRequest(ctx context.Context, httpClient tlsclient.HttpClient, profile browserprofile.Profile, data, url string) (map[string]any, error) {
|
||||
parsedURL, err := neturl.Parse(url)
|
||||
if err != nil {
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// VKCredentials is one app_id/app_secret pair used to obtain anonymous tokens.
|
||||
// VKCredentials — пара app_id/app_secret для получения анонимных токенов.
|
||||
type VKCredentials struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
}
|
||||
|
||||
// TurnCredentials is the resolved TURN allocation for a stream group.
|
||||
// TurnCredentials — разрешённые TURN-реквизиты для группы потоков.
|
||||
type TurnCredentials struct {
|
||||
Username string
|
||||
Password string
|
||||
@@ -20,7 +20,7 @@ type TurnCredentials struct {
|
||||
Link string
|
||||
}
|
||||
|
||||
// DefaultCredentials mirrors the public VK SDK app IDs the client tries in order.
|
||||
// DefaultCredentials — публичные app_id VK SDK; клиент перебирает по порядку.
|
||||
var DefaultCredentials = []VKCredentials{
|
||||
{ClientID: "6287487", ClientSecret: "QbYic1K3lEV5kTGiqlq2"}, // VK_WEB_APP_ID
|
||||
{ClientID: "7879029", ClientSecret: "aR5NKGmm03GYrCiNKsaw"}, // VK_MVK_APP_ID
|
||||
@@ -38,8 +38,7 @@ const (
|
||||
DefaultStreamsPerCache = 10
|
||||
)
|
||||
|
||||
// Sentinel errors produced by the auth flow. Callers use errors.Is.
|
||||
// The string forms remain stable for log output.
|
||||
// Sentinel-ошибки auth-потока. Строковые формы стабильны (используются в логах).
|
||||
var (
|
||||
ErrCaptchaWaitRequired = errors.New("CAPTCHA_WAIT_REQUIRED")
|
||||
ErrFatalCaptchaNoStreams = errors.New("FATAL_CAPTCHA_FAILED_NO_STREAMS")
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package vkauth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// VKCredentials — пара app_id/app_secret для получения anonymous-токенов.
|
||||
type VKCredentials struct {
|
||||
ClientID string
|
||||
ClientSecret string
|
||||
}
|
||||
|
||||
// TurnCredentials — резолвленный TURN-allocation для группы потоков.
|
||||
type TurnCredentials struct {
|
||||
Username string
|
||||
Password string
|
||||
ServerAddrs []string
|
||||
ExpiresAt time.Time
|
||||
Link string
|
||||
}
|
||||
|
||||
// DefaultCredentials — публичные VK SDK app ID, которые клиент пробует по порядку.
|
||||
var DefaultCredentials = []VKCredentials{
|
||||
{ClientID: "6287487", ClientSecret: "QbYic1K3lEV5kTGiqlq2"}, // VK_WEB_APP_ID
|
||||
{ClientID: "7879029", ClientSecret: "aR5NKGmm03GYrCiNKsaw"}, // VK_MVK_APP_ID
|
||||
{ClientID: "52461373", ClientSecret: "o557NLIkAErNhakXrQ7A"}, // VK_WEB_VKVIDEO_APP_ID
|
||||
{ClientID: "52649896", ClientSecret: "WStp4ihWG4l3nmXZgIbC"}, // VK_MVK_VKVIDEO_APP_ID
|
||||
{ClientID: "51781872", ClientSecret: "IjjCNl4L4Tf5QZEXIHKK"}, // VK_ID_AUTH_APP
|
||||
}
|
||||
|
||||
const (
|
||||
CredentialLifetime = 10 * time.Minute
|
||||
CacheSafetyMargin = 60 * time.Second
|
||||
MaxCacheErrors = 3
|
||||
ErrorWindow = 10 * time.Second
|
||||
|
||||
DefaultStreamsPerCache = 10
|
||||
)
|
||||
|
||||
// Sentinel errors produced by the auth flow. Callers use errors.Is.
|
||||
// The string forms remain stable for log output.
|
||||
var (
|
||||
ErrCaptchaWaitRequired = errors.New("CAPTCHA_WAIT_REQUIRED")
|
||||
ErrFatalCaptchaNoStreams = errors.New("FATAL_CAPTCHA_FAILED_NO_STREAMS")
|
||||
ErrLockoutActive = errors.New("global lockout active")
|
||||
)
|
||||
+38
-38
@@ -1,11 +1,11 @@
|
||||
// Package config parses CLI flags for the client and server binaries.
|
||||
// Package config парсит CLI-флаги клиента и сервера.
|
||||
//
|
||||
// Parse* functions are side-effect free: they validate inputs and decode the
|
||||
// wrap key, but do not touch the network, DNS, or process state. main() is
|
||||
// responsible for wiring those side effects after Parse* returns.
|
||||
// Функции Parse* без побочных эффектов: валидируют ввод и декодируют wrap-ключ,
|
||||
// но не трогают сеть, DNS и состояние процесса. Подключение этих эффектов —
|
||||
// ответственность main() после возврата Parse*.
|
||||
//
|
||||
// Options are grouped by domain (TURN, Obf, Proxy, VK, DNS, Log) so the struct
|
||||
// shape mirrors the conceptual layers of the proxy.
|
||||
// Опции сгруппированы по доменам (TURN, Obf, Proxy, VK, DNS, Log) — структура
|
||||
// зеркалит концептуальные слои прокси.
|
||||
package config
|
||||
|
||||
import (
|
||||
@@ -26,66 +26,66 @@ const (
|
||||
defaultStreamsPerCache = 10
|
||||
)
|
||||
|
||||
// ProxyMode selects the app-layer payload carried over the TURN tunnel.
|
||||
// On the client it can be all three; on the server only UDP / TCPFwd
|
||||
// (bond is auto-detected per stream by the magic prefix).
|
||||
// ProxyMode выбирает payload прикладного уровня, который идёт через TURN-туннель.
|
||||
// На клиенте доступны все три; на сервере только UDP / TCPFwd
|
||||
// (bond определяется автоматически per-stream по magic-префиксу).
|
||||
type ProxyMode string
|
||||
|
||||
const (
|
||||
ProxyModeUDP ProxyMode = "udp" // -vless=false: UDP packet relay (WireGuard)
|
||||
ProxyModeTCPFwd ProxyMode = "tcpfwd" // -vless=true: TCP forwarder over smux
|
||||
ProxyModeTCPFwdBond ProxyMode = "tcpfwd-bond" // -vless=true -vless-bond=true: bonded TCP across N smux sessions
|
||||
ProxyModeUDP ProxyMode = "udp" // -vless=false: UDP-релей пакетов (WireGuard)
|
||||
ProxyModeTCPFwd ProxyMode = "tcpfwd" // -vless=true: TCP-форвардер через smux
|
||||
ProxyModeTCPFwdBond ProxyMode = "tcpfwd-bond" // -vless=true -vless-bond=true: bond TCP по N smux-сессиям
|
||||
)
|
||||
|
||||
// TURNOpts groups TURN-server-side options (where and how to reach TURN).
|
||||
// TURNOpts — опции TURN-сервера (куда и как подключаться).
|
||||
type TURNOpts struct {
|
||||
Host string // -turn: override the TURN server IP/host
|
||||
Port string // -port: override the TURN port
|
||||
UDP bool // -udp: dial TURN via UDP (default: TCP/TLS)
|
||||
N int // -n: number of TURN streams (client only)
|
||||
Host string // -turn: переопределить IP/host TURN-сервера
|
||||
Port string // -port: переопределить порт TURN
|
||||
UDP bool // -udp: подключение к TURN по UDP (по умолчанию TCP/TLS)
|
||||
N int // -n: число TURN-потоков (только клиент)
|
||||
}
|
||||
|
||||
// ObfOpts groups TURN-payload obfuscation options (SRTP-mimicry wrap).
|
||||
// ObfOpts — опции обфускации TURN-payload (SRTP-mimicry wrap).
|
||||
type ObfOpts struct {
|
||||
WrapMode bool // -wrap: enable SRTP-mimicry AEAD wrap on TURN payload
|
||||
WrapKey []byte // -wrap-key (decoded): 32-byte shared key; nil unless WrapMode
|
||||
GenWrapKey bool // -gen-wrap-key: print a fresh key and exit
|
||||
WrapMode bool // -wrap: включить SRTP-mimicry AEAD-обёртку
|
||||
WrapKey []byte // -wrap-key (декодированный): 32-байтовый общий ключ; nil если WrapMode=false
|
||||
GenWrapKey bool // -gen-wrap-key: напечатать новый ключ и выйти
|
||||
}
|
||||
|
||||
// ProxyOpts groups app-layer proxy options.
|
||||
// ProxyOpts — опции прокси прикладного уровня.
|
||||
type ProxyOpts struct {
|
||||
Mode ProxyMode // udp | tcpfwd | tcpfwd-bond (server: udp | tcpfwd)
|
||||
Listen string // -listen: local bind addr (client: WG/TCP entry; server: TURN entry)
|
||||
Connect string // -connect: upstream backend addr (server only)
|
||||
Peer string // -peer: server-side proxy addr the client dials (client only)
|
||||
Mode ProxyMode // udp | tcpfwd | tcpfwd-bond (сервер: udp | tcpfwd)
|
||||
Listen string // -listen: локальный bind (клиент: WG/TCP entry; сервер: TURN entry)
|
||||
Connect string // -connect: backend (только сервер)
|
||||
Peer string // -peer: адрес серверного прокси, куда дозванивается клиент (только клиент)
|
||||
}
|
||||
|
||||
// VKOpts groups VK-credentials and captcha options (client only).
|
||||
// VKOpts — опции VK-учёток и captcha (только клиент).
|
||||
type VKOpts struct {
|
||||
Link string // -vk-link (sanitized to the join-code suffix)
|
||||
Link string // -vk-link (нормализован до join-кода)
|
||||
StreamsPerCred int // -streams-per-cred
|
||||
ManualCaptcha bool // -manual-captcha
|
||||
}
|
||||
|
||||
// DNSOpts groups DNS-resolution options (client only).
|
||||
// DNSOpts — опции DNS-резолвинга (только клиент).
|
||||
type DNSOpts struct {
|
||||
Mode string // -dns: udp | doh | auto
|
||||
Servers []string // -dns-servers (comma-split); nil when flag empty
|
||||
Servers []string // -dns-servers (через запятую); nil если флаг пуст
|
||||
}
|
||||
|
||||
// LogOpts groups logging options.
|
||||
// LogOpts — опции логирования.
|
||||
type LogOpts struct {
|
||||
Debug bool // -debug
|
||||
}
|
||||
|
||||
// KCPOpts groups KCP tunnel options. Both sides of a tunnel must agree on
|
||||
// Profile and FEC; values currently come from VK_TURN_KCP_* env vars.
|
||||
// KCPOpts — опции KCP-туннеля. Обе стороны должны согласовать Profile и FEC;
|
||||
// значения берутся из переменных окружения VK_TURN_KCP_*.
|
||||
type KCPOpts struct {
|
||||
Profile kcptun.Profile
|
||||
FEC kcptun.FEC
|
||||
}
|
||||
|
||||
// Client holds parsed and validated client CLI options.
|
||||
// Client — разобранные и провалидированные CLI-опции клиента.
|
||||
type Client struct {
|
||||
TURN TURNOpts
|
||||
Obf ObfOpts
|
||||
@@ -96,7 +96,7 @@ type Client struct {
|
||||
KCP KCPOpts
|
||||
}
|
||||
|
||||
// Server holds parsed and validated server CLI options.
|
||||
// Server — разобранные и провалидированные CLI-опции сервера.
|
||||
type Server struct {
|
||||
Obf ObfOpts
|
||||
Proxy ProxyOpts
|
||||
@@ -104,8 +104,8 @@ type Server struct {
|
||||
KCP KCPOpts
|
||||
}
|
||||
|
||||
// ParseClient parses args (excluding program name) into a Client.
|
||||
// On flag.ErrHelp it returns (nil, flag.ErrHelp) so the caller can exit cleanly.
|
||||
// ParseClient разбирает args (без имени программы) в Client.
|
||||
// При flag.ErrHelp возвращает (nil, flag.ErrHelp) — вызывающий выходит штатно.
|
||||
func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
fs := flag.NewFlagSet("client", flag.ContinueOnError)
|
||||
if errOut != nil {
|
||||
@@ -207,7 +207,7 @@ func ParseClient(args []string, errOut io.Writer) (*Client, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// ParseServer parses args (excluding program name) into a Server.
|
||||
// ParseServer разбирает args (без имени программы) в Server.
|
||||
func ParseServer(args []string, errOut io.Writer) (*Server, error) {
|
||||
fs := flag.NewFlagSet("server", flag.ContinueOnError)
|
||||
if errOut != nil {
|
||||
|
||||
+12
-13
@@ -1,20 +1,20 @@
|
||||
// Package logx is a minimal leveled logger over stdlib log. Callers receive a
|
||||
// Logger and call Debugf/Infof/Warnf/Errorf directly; Debugf is gated by a
|
||||
// debug flag, the other levels always print via stdlib log.
|
||||
// Package logx — минимальный уровневый логгер поверх stdlib log.
|
||||
// Вызывающий получает Logger и зовёт Debugf/Infof/Warnf/Errorf;
|
||||
// Debugf управляется debug-флагом, остальные уровни всегда пишут.
|
||||
package logx
|
||||
|
||||
import "log"
|
||||
|
||||
// Logger is the leveled-log interface used across the proxy. Debugf is gated by
|
||||
// the constructor's debug flag; the other levels always print via stdlib log.
|
||||
// Logger — интерфейс уровневого логирования.
|
||||
// Debugf гейтится debug-флагом конструктора; остальные уровни печатают всегда.
|
||||
type Logger interface {
|
||||
Debugf(format string, v ...any)
|
||||
Infof(format string, v ...any)
|
||||
Warnf(format string, v ...any)
|
||||
Errorf(format string, v ...any)
|
||||
// DebugEnabled reports whether Debugf will produce output. Hot paths
|
||||
// (stats counters, condition-gated branches) use this to skip work the
|
||||
// logger would discard anyway.
|
||||
// DebugEnabled сообщает, будет ли Debugf писать вывод. Hot-path
|
||||
// (счётчики статистики, условные ветки) используют это, чтобы не
|
||||
// делать работу, результат которой логгер всё равно отбросит.
|
||||
DebugEnabled() bool
|
||||
}
|
||||
|
||||
@@ -22,13 +22,12 @@ type stdLogger struct {
|
||||
debug bool
|
||||
}
|
||||
|
||||
// New returns a Logger that prints via stdlib log. If debug is false, Debugf is
|
||||
// a no-op.
|
||||
// New возвращает Logger поверх stdlib log. При debug=false Debugf — no-op.
|
||||
func New(debug bool) Logger {
|
||||
return &stdLogger{debug: debug}
|
||||
}
|
||||
|
||||
// Nop returns a Logger whose every method discards its input. Useful in tests.
|
||||
// Nop возвращает Logger, отбрасывающий весь вывод. Полезно в тестах.
|
||||
func Nop() Logger { return nopLogger{} }
|
||||
|
||||
func (l *stdLogger) Debugf(format string, v ...any) {
|
||||
@@ -41,8 +40,8 @@ func (l *stdLogger) Warnf(format string, v ...any) { log.Printf("[WARN] "+forma
|
||||
func (l *stdLogger) Errorf(format string, v ...any) { log.Printf("[ERROR] "+format, v...) }
|
||||
func (l *stdLogger) DebugEnabled() bool { return l.debug }
|
||||
|
||||
// OrNop returns l if non-nil, else a Nop logger. Use in package constructors
|
||||
// that accept a nullable Logger.
|
||||
// OrNop возвращает l, если он не nil, иначе Nop. Используется в конструкторах
|
||||
// пакетов, принимающих nullable Logger.
|
||||
func OrNop(l Logger) Logger {
|
||||
if l == nil {
|
||||
return Nop()
|
||||
|
||||
+14
-15
@@ -1,7 +1,7 @@
|
||||
// Package netconn holds small net.Conn / transport.Net adapters used by both
|
||||
// client and server: a passthrough transport.Net (for pion turn),
|
||||
// ConnectedUDPConn (Write-only WriteTo on a dialed UDPConn), and
|
||||
// SplitFirstWriteConn (DPI evasion via first-segment split).
|
||||
// Package netconn — мелкие net.Conn / transport.Net адаптеры для клиента
|
||||
// и сервера: passthrough transport.Net (для pion turn), ConnectedUDPConn
|
||||
// (WriteTo поверх dialed UDPConn) и SplitFirstWriteConn (обход DPI через
|
||||
// разбиение первого сегмента).
|
||||
package netconn
|
||||
|
||||
import (
|
||||
@@ -14,10 +14,10 @@ import (
|
||||
"github.com/pion/transport/v4"
|
||||
)
|
||||
|
||||
// DirectNet implements transport.Net by delegating to the std net package.
|
||||
// DirectNet реализует transport.Net через стандартный net.
|
||||
type DirectNet struct{}
|
||||
|
||||
// New returns a transport.Net that delegates to the standard net package.
|
||||
// New возвращает transport.Net поверх стандартного net.
|
||||
func New() transport.Net {
|
||||
return DirectNet{}
|
||||
}
|
||||
@@ -110,22 +110,21 @@ func (l directTCPListener) AcceptTCP() (transport.TCPConn, error) {
|
||||
return l.TCPListener.AcceptTCP()
|
||||
}
|
||||
|
||||
// ConnectedUDPConn lets a dialed (connected) *net.UDPConn satisfy
|
||||
// net.PacketConn semantics: WriteTo ignores the destination since the kernel
|
||||
// already has it from connect().
|
||||
// ConnectedUDPConn адаптирует dialed (connected) *net.UDPConn к семантике
|
||||
// net.PacketConn: WriteTo игнорирует адрес, т.к. ядро уже знает его из connect().
|
||||
type ConnectedUDPConn struct {
|
||||
*net.UDPConn
|
||||
}
|
||||
|
||||
// WriteTo discards the addr (UDP is already connected) and writes p.
|
||||
// WriteTo игнорирует addr (UDP уже connected) и пишет p.
|
||||
func (c *ConnectedUDPConn) WriteTo(p []byte, _ net.Addr) (int, error) {
|
||||
return c.Write(p)
|
||||
}
|
||||
|
||||
// SplitFirstWriteConn wraps a TCP net.Conn and splits the very first Write
|
||||
// into two segments (SplitAt bytes + remainder) with an optional Delay between
|
||||
// them. This breaks DPI rules that match a fixed offset in the first segment
|
||||
// without TCP reassembly (e.g. the STUN magic cookie at offset 4-7).
|
||||
// SplitFirstWriteConn оборачивает TCP net.Conn и разбивает самый первый Write
|
||||
// на два сегмента (SplitAt байт + остаток) с опциональной паузой Delay между ними.
|
||||
// Ломает DPI-правила, матчащие фиксированный offset в первом сегменте без
|
||||
// TCP-реассемблинга (например STUN magic cookie на offset 4-7).
|
||||
type SplitFirstWriteConn struct {
|
||||
net.Conn
|
||||
SplitAt int
|
||||
@@ -133,7 +132,7 @@ type SplitFirstWriteConn struct {
|
||||
done atomic.Bool
|
||||
}
|
||||
|
||||
// Write performs the one-shot split on the first call, then forwards directly.
|
||||
// Write делает one-shot разбиение при первом вызове, далее проксирует напрямую.
|
||||
func (s *SplitFirstWriteConn) Write(b []byte) (int, error) {
|
||||
if s.done.CompareAndSwap(false, true) && len(b) > s.SplitAt {
|
||||
n1, err := s.Conn.Write(b[:s.SplitAt])
|
||||
|
||||
@@ -8,10 +8,10 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// BiCopy runs io.Copy in both directions between c1 and c2, returning
|
||||
// (bytesC1FromC2, bytesC2FromC1). When either copy exits — by EOF, error, or
|
||||
// ctx cancellation — both sides get their deadlines pinned to time.Now() so the
|
||||
// peer goroutine unblocks. Errors are surfaced via errf when non-nil.
|
||||
// BiCopy запускает io.Copy в обе стороны между c1 и c2; возвращает
|
||||
// (bytesC1FromC2, bytesC2FromC1). Как только одна копия завершилась
|
||||
// (EOF/ошибка/cancel) — обоим концам выставляется deadline=time.Now(),
|
||||
// чтобы разблокировать парную горутину. Ошибки уходят в errf, если он не nil.
|
||||
func BiCopy(ctx context.Context, c1, c2 net.Conn, errf func(format string, v ...any)) (int64, int64) {
|
||||
ctx2, cancel := context.WithCancel(ctx)
|
||||
context.AfterFunc(ctx2, func() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package bondclient implements the client side of the bonded VLESS lane:
|
||||
// a single accepted TCP connection striped (round-robin) across all currently
|
||||
// live smux sessions in a tcpfwd.SessionPool. Frame wire-format lives in
|
||||
// internal/wire/bondframe; this package wires the local TCP <-> lanes copy loops.
|
||||
// Package bondclient реализует клиентскую сторону bonded VLESS lane:
|
||||
// одно принятое TCP-соединение, распределённое (round-robin) по всем активным
|
||||
// smux-сессиям в tcpfwd.SessionPool. Wire-формат фреймов — internal/wire/bondframe;
|
||||
// пакет соединяет copy-loop локального TCP ↔ lanes.
|
||||
package bondclient
|
||||
|
||||
import (
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// Deps groups host-process dependencies needed by the bond client.
|
||||
// Deps — зависимости хост-процесса для bond-клиента.
|
||||
type Deps struct {
|
||||
Log logx.Logger
|
||||
}
|
||||
@@ -34,12 +34,12 @@ func (d *Deps) log() logx.Logger {
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// Handler binds Deps and exposes Handle, matching the tcpfwd.BondHandler signature.
|
||||
// Handler связывает Deps и предоставляет Handle под сигнатуру tcpfwd.BondHandler.
|
||||
type Handler struct {
|
||||
Deps Deps
|
||||
}
|
||||
|
||||
// lane is one striped smux stream within a bonded TCP connection.
|
||||
// lane — один smux-поток внутри bonded TCP-соединения.
|
||||
type lane struct {
|
||||
ps *tcpfwd.PooledSession
|
||||
stream *smux.Stream
|
||||
@@ -47,17 +47,17 @@ type lane struct {
|
||||
dead atomic.Bool
|
||||
}
|
||||
|
||||
// Handle stripes the local TCP connection across all live candidate sessions.
|
||||
// Signature matches tcpfwd.BondHandler.
|
||||
// Handle распределяет локальное TCP-соединение по всем активным сессиям-кандидатам.
|
||||
// Сигнатура соответствует tcpfwd.BondHandler.
|
||||
func (h *Handler) Handle(ctx context.Context, tcpConn net.Conn, connID uint64, candidates []*tcpfwd.PooledSession) {
|
||||
defer func() { _ = tcpConn.Close() }()
|
||||
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
defer cancel()
|
||||
|
||||
// Phase 1: open streams on usable sessions. Phase 2: send Hello with the
|
||||
// actual lane count so bondserver.waitForInitialLanes doesn't wait on lanes
|
||||
// that were never opened.
|
||||
// Фаза 1: открыть потоки на доступных сессиях. Фаза 2: отправить Hello с
|
||||
// реальным числом lane — bondserver.waitForInitialLanes не будет ждать
|
||||
// lane, которые не были открыты.
|
||||
type pending struct {
|
||||
ps *tcpfwd.PooledSession
|
||||
stream *smux.Stream
|
||||
@@ -203,10 +203,9 @@ func (h *Handler) copyTCPToBond(ctx context.Context, connID uint64, tcpConn net.
|
||||
}
|
||||
}
|
||||
|
||||
// writeBondFrameToNextLane writes to the next live lane in round-robin order.
|
||||
// Unlike bondserver.writeToNextLane (which loops waiting for new lanes to
|
||||
// attach), the client's lane set is fixed for the lifetime of Handle, so once
|
||||
// all lanes are dead there is nothing to wait for — fail fast.
|
||||
// writeBondFrameToNextLane пишет в следующий живой lane в порядке round-robin.
|
||||
// В отличие от bondserver.writeToNextLane (который ждёт новые lane), набор
|
||||
// lane клиента фиксирован на время жизни Handle — нечего ждать, fail fast.
|
||||
func writeBondFrameToNextLane(ctx context.Context, lanes []*lane, typ byte, seq uint64, data []byte, laneIdx *uint64) (*lane, error) {
|
||||
for range lanes {
|
||||
idx := *laneIdx % uint64(len(lanes))
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package bondserver implements the server side of the bonded VLESS lane:
|
||||
// a single backend TCP connection multiplexed across N smux streams that all
|
||||
// share a ConnID. Frame wire-format lives in internal/wire/bondframe; this package
|
||||
// wires the backend TCP <-> lanes copy loops and the per-ConnID registry.
|
||||
// Package bondserver реализует серверную сторону bonded VLESS lane:
|
||||
// одно backend TCP-соединение, мультиплексированное по N smux-потокам с общим
|
||||
// ConnID. Wire-формат фреймов — internal/wire/bondframe; пакет соединяет
|
||||
// copy-loop backend TCP ↔ lanes и реестр per-ConnID.
|
||||
package bondserver
|
||||
|
||||
import (
|
||||
@@ -18,16 +18,16 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// laneStream is the subset of *smux.Stream that serverLane needs. Defined as
|
||||
// an interface so unit tests can inject in-memory pipes without spinning up a
|
||||
// real smux session.
|
||||
// laneStream — подмножество *smux.Stream, нужное serverLane. Определено как
|
||||
// интерфейс, чтобы юнит-тесты могли подменять in-memory pipe без смоделированной
|
||||
// smux-сессии.
|
||||
type laneStream interface {
|
||||
io.Reader
|
||||
io.Writer
|
||||
SetDeadline(time.Time) error
|
||||
}
|
||||
|
||||
// Deps groups host-process dependencies needed by the bond server.
|
||||
// Deps — зависимости хост-процесса для bond-сервера.
|
||||
type Deps struct {
|
||||
Log logx.Logger
|
||||
}
|
||||
@@ -39,17 +39,16 @@ func (d *Deps) log() logx.Logger {
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// connKey is the composite de-duplication key for the Registry map.
|
||||
// Incorporating TenantID ensures ConnIDs from different tenants never collide,
|
||||
// which is required for multi-tenant deployments. In single-tenant (non-auth)
|
||||
// mode every key has Tenant == auth.Anonymous.
|
||||
// connKey — составной ключ дедупликации для карты Registry.
|
||||
// TenantID в ключе гарантирует, что ConnID разных тенантов никогда не пересекаются
|
||||
// (обязательно для multi-tenant). В single-tenant режиме у всех ключей Tenant == auth.Anonymous.
|
||||
type connKey struct {
|
||||
Tenant auth.TenantID
|
||||
ConnID uint64
|
||||
}
|
||||
|
||||
// Registry deduplicates concurrent lanes that share a (TenantID, ConnID) pair
|
||||
// into a single backend TCP connection.
|
||||
// Registry дедуплицирует одновременные lane с одинаковой парой (TenantID, ConnID)
|
||||
// в одно backend TCP-соединение.
|
||||
type Registry struct {
|
||||
deps Deps
|
||||
|
||||
@@ -57,17 +56,16 @@ type Registry struct {
|
||||
conns map[connKey]*serverConn
|
||||
}
|
||||
|
||||
// NewRegistry creates an empty Registry.
|
||||
func NewRegistry(deps Deps) *Registry {
|
||||
return &Registry{deps: deps, conns: make(map[connKey]*serverConn)}
|
||||
}
|
||||
|
||||
// HandleStreamAfterMagic accepts a smux stream whose first 4 magic bytes have
|
||||
// already been consumed (server-side multiplex pre-peek), reads the Hello,
|
||||
// attaches as a lane, and blocks until the underlying bond connection is done.
|
||||
// HandleStreamAfterMagic принимает smux-поток, у которого первые 4 magic-байта
|
||||
// уже прочитаны (server-side multiplex pre-peek), читает Hello, прикрепляет
|
||||
// lane и блокируется до завершения bond-соединения.
|
||||
//
|
||||
// tenant scopes the de-duplication key. Pass [auth.Anonymous] in single-tenant
|
||||
// deployments; real Authenticator-derived values in multi-tenant mode.
|
||||
// tenant ограничивает ключ дедупликации. В single-tenant — [auth.Anonymous];
|
||||
// в multi-tenant — значение от реального Authenticator.
|
||||
func (r *Registry) HandleStreamAfterMagic(ctx context.Context, tenant auth.TenantID, stream *smux.Stream, connectAddr string, magic [4]byte) {
|
||||
r.handleStream(ctx, tenant, stream, connectAddr, func(rd io.Reader) (bondframe.Hello, error) {
|
||||
return bondframe.ReadHelloAfterMagic(rd, magic)
|
||||
@@ -298,8 +296,8 @@ func (c *serverConn) copyBackendToBond(backendConn net.Conn) {
|
||||
for {
|
||||
n, err := backendConn.Read(buf)
|
||||
if n > 0 {
|
||||
// writeToNextLane is synchronous (WriteFrame returns before lane
|
||||
// switch), so buf[:n] can be passed directly — matches bondclient.
|
||||
// writeToNextLane — синхронная запись (WriteFrame возвращается до
|
||||
// переключения lane), поэтому buf[:n] передаётся напрямую — аналог bondclient.
|
||||
if writeErr := c.writeToNextLane(bondframe.FrameData, seq, buf[:n], &laneIdx); writeErr != nil {
|
||||
c.deps.log().Errorf("[bond %d] lane write data error: %v", c.id, writeErr)
|
||||
return
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package common holds the few helpers shared by udprelay and tcpfwd
|
||||
// (TURN dial + wrap codec construction). The two proxy modes layer DTLS and
|
||||
// srtpmimicry differently, so a full Engine/Handler abstraction is intentionally
|
||||
// avoided — this package only collects what is genuinely identical.
|
||||
// Package common содержит хелперы, общие для udprelay и tcpfwd
|
||||
// (TURN-dial + создание wrap-кодека). Два режима прокси по-разному компонуют DTLS и
|
||||
// srtpmimicry, поэтому полная абстракция Engine/Handler намеренно не вводится —
|
||||
// пакет собирает только действительно идентичный код.
|
||||
package common
|
||||
|
||||
import (
|
||||
@@ -13,13 +13,13 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/wire/srtpmimicry"
|
||||
)
|
||||
|
||||
// GetCredsFunc resolves VK TURN credentials for a (link, streamID) pair.
|
||||
// Matches vkauth.Client.GetCredentials.
|
||||
// GetCredsFunc разрешает VK TURN-реквизиты для пары (link, streamID).
|
||||
// Соответствует vkauth.Client.GetCredentials.
|
||||
type GetCredsFunc func(ctx context.Context, link string, streamID int) (user, pass, rawURL string, err error)
|
||||
|
||||
// DialTURN fetches credentials and opens a TURN stream. The caller is
|
||||
// responsible for closing the returned stream and for any auth-error retry
|
||||
// policy (udprelay) or session-restart policy (tcpfwd).
|
||||
// DialTURN получает реквизиты и открывает TURN-поток. Вызывающий отвечает
|
||||
// за закрытие потока и политику retry при auth-ошибке (udprelay)
|
||||
// или перезапуска сессии (tcpfwd).
|
||||
func DialTURN(ctx context.Context, host, port string, udp bool, peer *net.UDPAddr, link string, streamID int, getCreds GetCredsFunc) (*turndial.Stream, error) {
|
||||
user, pass, rawURL, err := getCreds(ctx, link, streamID)
|
||||
if err != nil {
|
||||
@@ -32,9 +32,8 @@ func DialTURN(ctx context.Context, host, port string, udp bool, peer *net.UDPAdd
|
||||
}, peer, user, pass, rawURL)
|
||||
}
|
||||
|
||||
// NewClientWrap returns a client-side srtpmimicry.Conn if key has the
|
||||
// expected length, otherwise (nil, nil) — wrap disabled. NewConn errors are
|
||||
// propagated so callers can surface them.
|
||||
// NewClientWrap возвращает клиентский srtpmimicry.Conn если key нужной длины,
|
||||
// иначе (nil, nil) — wrap отключён. Ошибки NewConn пробрасываются вызывающему.
|
||||
func NewClientWrap(key []byte) (*srtpmimicry.Conn, error) {
|
||||
if len(key) != srtpmimicry.KeyLen {
|
||||
return nil, nil
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// Package tcpfwd implements VLESS mode: TCP forwarding over a pool of TURN-tunneled
|
||||
// smux sessions. Each accepted local TCP connection is opened as a smux stream
|
||||
// (round-robin across sessions) or, with bond, striped across all live sessions.
|
||||
// Package tcpfwd реализует VLESS-режим: пересылка TCP через пул TURN-туннелированных
|
||||
// smux-сессий. Каждое принятое TCP-соединение открывается как smux-поток
|
||||
// (round-robin по сессиям) или, с bond, распределяется по всем активным сессиям.
|
||||
//
|
||||
// SessionPool/PooledSession are exported so the bond client (internal/proxy/bondclient)
|
||||
// can stripe a single TCP connection across multiple live sessions.
|
||||
// SessionPool/PooledSession экспортированы, чтобы bond-клиент (internal/proxy/bondclient)
|
||||
// мог распределять одно TCP-соединение по нескольким сессиям.
|
||||
package tcpfwd
|
||||
|
||||
import (
|
||||
@@ -13,9 +13,9 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// PooledSession is a single TURN+DTLS+KCP+smux session inside the pool, with
|
||||
// its lifetime counters. Fields are exported so internal/proxy/bondclient can
|
||||
// account per-lane traffic; mutate the atomics via their atomic methods only.
|
||||
// PooledSession — одна TURN+DTLS+KCP+smux сессия в пуле с lifetime-счётчиками.
|
||||
// Поля экспортированы для учёта per-lane трафика в bondclient;
|
||||
// атомики изменять только через их методы.
|
||||
type PooledSession struct {
|
||||
ID int
|
||||
Sess *smux.Session
|
||||
@@ -26,7 +26,7 @@ type PooledSession struct {
|
||||
FromSession atomic.Uint64
|
||||
}
|
||||
|
||||
// SessionPool is a concurrency-safe round-robin pool of live smux sessions.
|
||||
// SessionPool — конкурентно-безопасный round-robin пул активных smux-сессий.
|
||||
type SessionPool struct {
|
||||
mu sync.RWMutex
|
||||
sessions []*PooledSession
|
||||
@@ -37,7 +37,7 @@ type SessionPool struct {
|
||||
ready chan struct{}
|
||||
}
|
||||
|
||||
// Ready returns a channel closed the first time the pool gains a session.
|
||||
// Ready возвращает канал, закрытый при первом появлении сессии в пуле.
|
||||
func (p *SessionPool) Ready() <-chan struct{} {
|
||||
p.mu.Lock()
|
||||
if p.ready == nil {
|
||||
@@ -48,7 +48,7 @@ func (p *SessionPool) Ready() <-chan struct{} {
|
||||
return ch
|
||||
}
|
||||
|
||||
// Add registers a freshly connected session in the pool.
|
||||
// Add регистрирует только что подключённую сессию в пуле.
|
||||
func (p *SessionPool) Add(id int, s *smux.Session) *PooledSession {
|
||||
ps := &PooledSession{ID: id, Sess: s}
|
||||
p.mu.Lock()
|
||||
@@ -62,7 +62,7 @@ func (p *SessionPool) Add(id int, s *smux.Session) *PooledSession {
|
||||
return ps
|
||||
}
|
||||
|
||||
// Remove drops ps from the pool. No-op if not present.
|
||||
// Remove удаляет ps из пула. No-op если не найден.
|
||||
func (p *SessionPool) Remove(ps *PooledSession) {
|
||||
p.mu.Lock()
|
||||
for i, sess := range p.sessions {
|
||||
@@ -74,7 +74,7 @@ func (p *SessionPool) Remove(ps *PooledSession) {
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// Pick returns the next session in round-robin order, or nil if pool is empty.
|
||||
// Pick возвращает следующую сессию в round-robin порядке или nil если пул пуст.
|
||||
func (p *SessionPool) Pick() *PooledSession {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
@@ -86,12 +86,12 @@ func (p *SessionPool) Pick() *PooledSession {
|
||||
return p.sessions[idx]
|
||||
}
|
||||
|
||||
// NextConnID returns a monotonically increasing connection ID.
|
||||
// NextConnID возвращает монотонно возрастающий идентификатор соединения.
|
||||
func (p *SessionPool) NextConnID() uint64 {
|
||||
return p.connCounter.Add(1)
|
||||
}
|
||||
|
||||
// Snapshot returns a copy of all currently-live (non-closed) sessions.
|
||||
// Snapshot возвращает копию всех активных (незакрытых) сессий.
|
||||
func (p *SessionPool) Snapshot() []*PooledSession {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
@@ -104,8 +104,8 @@ func (p *SessionPool) Snapshot() []*PooledSession {
|
||||
return out
|
||||
}
|
||||
|
||||
// Count returns the number of sessions currently in the pool (including any
|
||||
// that may have just closed; use Snapshot for live-only).
|
||||
// Count возвращает число сессий в пуле (включая только что закрытые;
|
||||
// используй Snapshot для live-only).
|
||||
func (p *SessionPool) Count() int {
|
||||
p.mu.RLock()
|
||||
defer p.mu.RUnlock()
|
||||
|
||||
@@ -18,11 +18,10 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// GetCredsFunc is re-exported from common so callers can keep their imports
|
||||
// scoped to this package.
|
||||
// GetCredsFunc реэкспортирован из common, чтобы вызывающие не выходили за пределы импортов пакета.
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// Params is the per-pool TURN/wrap configuration.
|
||||
// Params — конфигурация TURN/wrap для пула.
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -34,12 +33,12 @@ type Params struct {
|
||||
KCPFEC kcptun.FEC
|
||||
}
|
||||
|
||||
// BondHandler stripes one accepted TCP connection across all currently-live
|
||||
// pool sessions. Nil disables bond mode (callers will then use round-robin).
|
||||
// The bond client implementation lives in internal/proxy/bondclient.
|
||||
// BondHandler распределяет одно принятое TCP-соединение по всем активным сессиям пула.
|
||||
// Nil отключает bond-режим (будет round-robin).
|
||||
// Реализация — internal/proxy/bondclient.
|
||||
type BondHandler func(ctx context.Context, tcpConn net.Conn, connID uint64, lanes []*PooledSession)
|
||||
|
||||
// Deps groups host-process dependencies needed by the VLESS loop.
|
||||
// Deps — зависимости хост-процесса для VLESS-цикла.
|
||||
type Deps struct {
|
||||
DTLSDialer *dtlsdial.Dialer
|
||||
Log logx.Logger
|
||||
@@ -53,9 +52,9 @@ func (d *Deps) log() logx.Logger {
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// Run is the VLESS-mode entrypoint. It spawns numSessions maintainers, waits
|
||||
// for at least one to connect, then accepts local TCP connections and forwards
|
||||
// each as a smux stream (round-robin) or bonded across all live sessions.
|
||||
// Run — точка входа VLESS-режима. Запускает numSessions maintainer-горутин, ждёт
|
||||
// первого подключения, затем принимает локальные TCP-соединения и форвардит
|
||||
// каждое как smux-поток (round-robin) или bonded по всем активным сессиям.
|
||||
func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, listenAddr string, numSessions int, useBond bool) error {
|
||||
pool := &SessionPool{}
|
||||
|
||||
@@ -176,9 +175,9 @@ func Run(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, lis
|
||||
}
|
||||
}
|
||||
|
||||
// maintainSession keeps one TURN+DTLS+KCP+smux session alive: 3s backoff on
|
||||
// setup failure, 2s after a successful session disconnects, in both cases
|
||||
// before the next reconnect attempt.
|
||||
// maintainSession поддерживает одну TURN+DTLS+KCP+smux сессию живой:
|
||||
// 3s backoff при ошибке инициализации, 2s после отключения успешной сессии,
|
||||
// в обоих случаях перед следующей попыткой подключения.
|
||||
func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int, pool *SessionPool) {
|
||||
for {
|
||||
select {
|
||||
@@ -223,8 +222,8 @@ func maintainSession(ctx context.Context, deps *Deps, params *Params, peer *net.
|
||||
}
|
||||
}
|
||||
|
||||
// createSmuxSession establishes a full TURN+DTLS+KCP+smux pipeline and returns
|
||||
// the smux session along with a cleanup function (LIFO teardown).
|
||||
// createSmuxSession создаёт полный TURN+DTLS+KCP+smux pipeline и возвращает
|
||||
// smux-сессию вместе с функцией cleanup (LIFO-разрушение).
|
||||
func createSmuxSession(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, id int) (*smux.Session, func(), error) {
|
||||
var cleanupFns []func()
|
||||
cleanup := func() {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package tcpfwdserver implements the server-side VLESS lane: KCP+smux over a
|
||||
// DTLS connection, with each smux stream forwarded as a TCP connection to the
|
||||
// backend (Xray/VLESS). Bond streams are auto-detected by their magic prefix
|
||||
// and dispatched to a bondserver.Registry.
|
||||
// Package tcpfwdserver реализует серверную VLESS lane: KCP+smux поверх
|
||||
// DTLS-соединения, каждый smux-поток форвардится как TCP-соединение к backend
|
||||
// (Xray/VLESS). Bond-потоки автоопределяются по magic-префиксу и диспетчеризуются
|
||||
// в bondserver.Registry.
|
||||
package tcpfwdserver
|
||||
|
||||
import (
|
||||
@@ -21,9 +21,9 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// Handle wraps dtlsConn in KCP+smux and forwards each accepted stream as a TCP
|
||||
// connection to connectAddr. Streams whose first 4 bytes match the bond magic
|
||||
// are handed off to registry.
|
||||
// Handle оборачивает dtlsConn в KCP+smux и форвардит каждый принятый поток как
|
||||
// TCP-соединение к connectAddr. Потоки, чьи первые 4 байта совпадают с bond magic,
|
||||
// передаются в registry.
|
||||
func Handle(ctx context.Context, logger logx.Logger, registry *bondserver.Registry, dtlsConn net.Conn, connectAddr string, kcpProfile kcptun.Profile, kcpFEC kcptun.FEC) {
|
||||
statsCtx, statsCancel := context.WithCancel(ctx)
|
||||
defer statsCancel()
|
||||
@@ -115,8 +115,8 @@ func handleStream(ctx context.Context, logger logx.Logger, registry *bondserver.
|
||||
netconn.BiCopy(ctx, &prefixedConn{Conn: s, prefix: prefix[:]}, backendConn, logger.Debugf)
|
||||
}
|
||||
|
||||
// prefixedConn re-injects the magic-peek prefix on the first reads so the
|
||||
// backend sees the full original byte stream.
|
||||
// prefixedConn повторно вставляет magic-peek prefix при первых чтениях,
|
||||
// чтобы backend видел полный оригинальный поток байт.
|
||||
type prefixedConn struct {
|
||||
net.Conn
|
||||
prefix []byte
|
||||
|
||||
@@ -9,29 +9,28 @@ import (
|
||||
|
||||
const inboundQueueCap = 2000
|
||||
|
||||
// Packet is a pooled UDP datagram carried from the listener to the per-stream
|
||||
// DTLS worker. N is the populated prefix of Data.
|
||||
// Packet — пулированная UDP-датаграмма, передаваемая из listener'а в per-stream
|
||||
// DTLS-воркер. N — заполненный префикс Data.
|
||||
type Packet struct {
|
||||
Data []byte
|
||||
N int
|
||||
}
|
||||
|
||||
// packetPool reuses Packet buffers across the inbound hot path. Buffer size
|
||||
// matches the 2048-byte default the listener loop expects.
|
||||
// packetPool переиспользует Packet-буферы на горячем inbound пути. Размер буфера
|
||||
// соответствует 2048 байт, которые ожидает цикл listener'а.
|
||||
var packetPool = sync.Pool{
|
||||
New: func() any { return &Packet{Data: make([]byte, 2048)} },
|
||||
}
|
||||
|
||||
// runListener reads packets from listenConn, refreshes the active-peer cache,
|
||||
// and posts each packet to inboundChan. Packets are dropped when the channel
|
||||
// is full to keep the read loop wait-free.
|
||||
// runListener читает пакеты из listenConn, обновляет кэш active-peer
|
||||
// и публикует каждый пакет в inboundChan. При переполнении канала пакет
|
||||
// отбрасывается — цикл чтения остаётся wait-free.
|
||||
func runListener(ctx context.Context, listenConn net.PacketConn, activeLocalPeer *atomic.Value, inboundChan chan<- *Packet) {
|
||||
// Pointer-cache for the last seen local peer addr. Avoids the
|
||||
// per-packet addr.String() allocation pair on the hot WG ingest path:
|
||||
// most packets come from the same UDPAddr instance, so a pointer
|
||||
// equality check covers the fast path. The slow path (new instance
|
||||
// from ReadFrom for the same ip:port) does one String compare and
|
||||
// then refreshes the cache.
|
||||
// Pointer-кэш последнего виденного адреса local peer. Позволяет избежать
|
||||
// per-packet аллокации addr.String() на горячем WG ingest пути:
|
||||
// большинство пакетов приходит от одного UDPAddr, поэтому проверка
|
||||
// по указателю покрывает fast path. Медленный путь (новый экземпляр
|
||||
// от ReadFrom для того же ip:port) делает одно String-сравнение и обновляет кэш.
|
||||
var lastAddr net.Addr
|
||||
var lastAddrStr string
|
||||
for {
|
||||
|
||||
@@ -17,11 +17,11 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/wire/srtpmimicry"
|
||||
)
|
||||
|
||||
// DTLSLoop keeps a single DTLS termination alive for streamID, restarting it
|
||||
// on failure with a 10-30s backoff (skipped while a captcha lockout is active
|
||||
// and the prior error was a deadline). connchan is fed a fresh AsyncPacketPipe
|
||||
// half on each attempt; okchan (non-nil only for stream 1) signals the first
|
||||
// successful handshake.
|
||||
// DTLSLoop поддерживает единственное DTLS-подключение для streamID, перезапуская
|
||||
// его при сбое с backoff 10-30s (пропускается при активной captcha-блокировке,
|
||||
// если предыдущая ошибка — дедлайн). connchan получает свежую половину
|
||||
// AsyncPacketPipe на каждой попытке; okchan (non-nil только для потока 1)
|
||||
// сигнализирует о первом успешном handshake.
|
||||
func DTLSLoop(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.PacketConn, inboundChan <-chan *Packet, connchan chan<- net.PacketConn, okchan chan<- struct{}, streamID int) {
|
||||
for {
|
||||
select {
|
||||
@@ -29,9 +29,9 @@ func DTLSLoop(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net
|
||||
return
|
||||
default:
|
||||
err := oneDTLS(ctx, deps, peer, listenConn, inboundChan, connchan, okchan, streamID)
|
||||
// During captcha lockout the handshake deadline fires before
|
||||
// auth retries can succeed; back off briefly to avoid a tight
|
||||
// retry spin until the lockout clears.
|
||||
// При captcha-блокировке дедлайн handshake срабатывает раньше,
|
||||
// чем auth-retry успевает отработать; делаем краткий backoff,
|
||||
// чтобы не крутиться в tight spin до снятия блокировки.
|
||||
if err != nil && time.Now().Unix() < deps.Auth.LockoutUntilUnix() && errors.Is(err, context.DeadlineExceeded) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
@@ -51,9 +51,9 @@ func DTLSLoop(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net
|
||||
}
|
||||
}
|
||||
|
||||
// TURNLoop drives the TURN allocation half. It waits for a fresh conn2 from
|
||||
// the DTLS loop, throttles via t (the global 200ms tick), runs one TURN
|
||||
// session, and reacts to FATAL_CAPTCHA / CAPTCHA_WAIT_REQUIRED accordingly.
|
||||
// TURNLoop ведёт половину TURN-аллокации. Ждёт свежий conn2 от DTLS-цикла,
|
||||
// тормозит через t (глобальный тик 200ms), выполняет одну TURN-сессию
|
||||
// и реагирует на FATAL_CAPTCHA / CAPTCHA_WAIT_REQUIRED соответственно.
|
||||
func TURNLoop(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr, connchan <-chan net.PacketConn, t <-chan time.Time, streamID int) {
|
||||
for {
|
||||
select {
|
||||
@@ -127,9 +127,8 @@ func oneDTLS(ctx context.Context, deps *Deps, peer *net.UDPAddr, listenConn net.
|
||||
defer dtlscancel()
|
||||
|
||||
conn1, conn2 := connutil.AsyncPacketPipe()
|
||||
// TURNLoop may restart oneTURN several times within a single DTLS lifetime,
|
||||
// re-reading conn2 on each restart; keep publishing until the DTLS attempt
|
||||
// itself ends.
|
||||
// TURNLoop может перезапускать oneTURN несколько раз в рамках одного DTLS
|
||||
// соединения, каждый раз перечитывая conn2; публикуем до завершения DTLS.
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
@@ -230,8 +229,8 @@ func oneTURN(ctx context.Context, deps *Deps, params *Params, peer *net.UDPAddr,
|
||||
relayConn := stream.Relay
|
||||
deps.log().Debugf("[STREAM %d] TURN server IP: %s", streamID, stream.ServerUDPAddr.IP)
|
||||
|
||||
// Increment before ResetErrors so concurrent HandleAuthError observers see
|
||||
// the stream as connected before its error counter clears.
|
||||
// Инкремент до ResetErrors — конкурентные наблюдатели HandleAuthError видят
|
||||
// поток подключённым до сброса счётчика ошибок.
|
||||
deps.ConnectedStreams.Add(1)
|
||||
deps.Auth.ResetErrors(streamID)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Package udprelay implements the UDP-mode proxy loop: it terminates DTLS from a
|
||||
// local peer (WireGuard) and relays its packets through a per-stream TURN
|
||||
// allocation back to a remote peer. Run is the entrypoint; it owns the local
|
||||
// listener, the inbound dispatch fan-in, and the per-stream DTLS/TURN loops.
|
||||
// Package udprelay реализует UDP-режим прокси: терминирует DTLS от локального
|
||||
// пира (WireGuard) и ретранслирует пакеты через per-stream TURN-аллокацию
|
||||
// обратно к удалённому пиру. Run — точка входа; владеет локальным listener,
|
||||
// fan-in входящего dispatch и per-stream DTLS/TURN циклами.
|
||||
package udprelay
|
||||
|
||||
import (
|
||||
@@ -18,13 +18,12 @@ import (
|
||||
"github.com/samosvalishe/btp/internal/transport/dtlsdial"
|
||||
)
|
||||
|
||||
// GetCredsFunc is re-exported from common so callers can keep their imports
|
||||
// scoped to this package.
|
||||
// GetCredsFunc реэкспортирован из common, чтобы вызывающие не выходили за пределы импортов пакета.
|
||||
type GetCredsFunc = common.GetCredsFunc
|
||||
|
||||
// AuthHandler is the subset of vkauth.Client this package needs. Defined as
|
||||
// an interface so tests can inject fakes; the production wiring still imports
|
||||
// vkauth for its sentinel errors (ErrFatalCaptchaNoStreams, etc.).
|
||||
// AuthHandler — подмножество vkauth.Client, необходимое пакету. Определено как
|
||||
// интерфейс, чтобы тесты могли подменять fake; prod-код всё равно импортирует
|
||||
// vkauth ради sentinel-ошибок (ErrFatalCaptchaNoStreams и т.д.).
|
||||
type AuthHandler interface {
|
||||
IsAuthError(err error) bool
|
||||
HandleAuthError(streamID int) bool
|
||||
@@ -32,7 +31,7 @@ type AuthHandler interface {
|
||||
LockoutUntilUnix() int64
|
||||
}
|
||||
|
||||
// Params is the per-stream TURN/wrap configuration shared by the DTLS and TURN loops.
|
||||
// Params — per-stream конфигурация TURN/wrap, общая для DTLS и TURN циклов.
|
||||
type Params struct {
|
||||
Host string
|
||||
Port string
|
||||
@@ -42,23 +41,23 @@ type Params struct {
|
||||
GetCreds GetCredsFunc
|
||||
}
|
||||
|
||||
// ErrFatal is returned by Run when a stream encounters a condition that
|
||||
// requires the entire application to exit (e.g. manual captcha solver failed
|
||||
// with no connected streams). Callers should check with errors.Is and call
|
||||
// os.Exit themselves — udprelay does not reach into the host process.
|
||||
// ErrFatal возвращается из Run, когда поток встречает условие, требующее
|
||||
// завершения всего приложения (напр. ручной решатель captcha провалился без
|
||||
// подключённых потоков). Вызывающий должен проверить через errors.Is и вызвать
|
||||
// os.Exit сам — udprelay не вмешивается в хост-процесс.
|
||||
var ErrFatal = errors.New("udprelay: fatal error")
|
||||
|
||||
// Deps groups everything the loops need from the host process. The atomics
|
||||
// are owned by Run and exposed here so DTLSLoop/TURNLoop can share them when
|
||||
// called directly (Run wires them automatically).
|
||||
// Deps объединяет всё, что циклы берут из хост-процесса. Атомики принадлежат
|
||||
// Run и экспонированы здесь, чтобы DTLSLoop/TURNLoop могли разделять их при
|
||||
// прямом вызове (Run подключает их автоматически).
|
||||
type Deps struct {
|
||||
DTLSDialer *dtlsdial.Dialer
|
||||
Auth AuthHandler
|
||||
Log logx.Logger
|
||||
ActiveLocalPeer *atomic.Value
|
||||
ConnectedStreams *atomic.Int32
|
||||
// fatalCh is an internal signalling channel; set by Run, written by
|
||||
// TURNLoop, and drained by Run to propagate the fatal error up.
|
||||
// fatalCh — внутренний сигнальный канал; устанавливается Run, пишется
|
||||
// TURNLoop, читается Run для проброса фатальной ошибки наверх.
|
||||
fatalCh chan error
|
||||
}
|
||||
|
||||
@@ -69,13 +68,13 @@ func (d *Deps) log() logx.Logger {
|
||||
return d.Log
|
||||
}
|
||||
|
||||
// Run is the UDP-mode entrypoint. It binds listenAddr, fans inbound packets
|
||||
// into a shared queue, and spawns numStreams pairs of (DTLSLoop, TURNLoop).
|
||||
// connectedStreams is owned by the caller (vkauth reads it via StreamsAlive)
|
||||
// and incremented/decremented by oneTURN.
|
||||
// Returns after all stream loops exit (i.e. when ctx is cancelled).
|
||||
// If a fatal captcha condition is encountered, Run returns ErrFatal so the
|
||||
// caller can perform os.Exit without udprelay reaching into the host process.
|
||||
// Run — точка входа UDP-режима. Биндит listenAddr, распределяет входящие пакеты
|
||||
// в общую очередь и запускает numStreams пар (DTLSLoop, TURNLoop).
|
||||
// connectedStreams принадлежит вызывающему (vkauth читает через StreamsAlive)
|
||||
// и инкрементируется/декрементируется в oneTURN.
|
||||
// Возвращается после выхода всех потоков (т.е. при отмене ctx).
|
||||
// При фатальном captcha-условии возвращает ErrFatal — вызывающий делает os.Exit
|
||||
// без вмешательства udprelay в хост-процесс.
|
||||
func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, logger logx.Logger, connectedStreams *atomic.Int32, params *Params, peer *net.UDPAddr, listenAddr string, numStreams int) error {
|
||||
listenConn, err := net.ListenPacket("udp", listenAddr)
|
||||
if err != nil {
|
||||
@@ -102,9 +101,9 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
fatalCh: fatalCh,
|
||||
}
|
||||
|
||||
// runCtx is cancelled when a fatal error is detected (via fatalCh), which
|
||||
// propagates cancellation into all stream loops without requiring them to
|
||||
// hold a reference to the host-process cancel function.
|
||||
// runCtx отменяется при обнаружении фатальной ошибки (через fatalCh),
|
||||
// распространяя отмену во все потоковые циклы без необходимости хранить
|
||||
// ссылку на cancel-функцию хост-процесса.
|
||||
runCtx, runCancel := context.WithCancel(ctx)
|
||||
defer runCancel()
|
||||
|
||||
@@ -115,9 +114,9 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
})
|
||||
t := time.Tick(200 * time.Millisecond)
|
||||
|
||||
// Stream 1 gets okchan so it can signal the first successful handshake to
|
||||
// the log. All streams start concurrently — no gate between stream 1 and
|
||||
// the rest, so a slow DTLS handshake on stream 1 never delays streams 2..N.
|
||||
// Поток 1 получает okchan для сигнализации о первом успешном handshake в лог.
|
||||
// Все потоки стартуют одновременно — нет барьера между потоком 1 и остальными,
|
||||
// поэтому медленный DTLS handshake потока 1 не задерживает потоки 2..N.
|
||||
okchan := make(chan struct{}, 1)
|
||||
for i := 0; i < numStreams; i++ {
|
||||
cchan := make(chan net.PacketConn)
|
||||
@@ -134,9 +133,9 @@ func Run(ctx context.Context, dtlsDialer *dtlsdial.Dialer, auth AuthHandler, log
|
||||
})
|
||||
}
|
||||
|
||||
// If a fatal error was sent, cancel remaining goroutines and propagate up.
|
||||
// watcherDone synchronises the watcher goroutine with Run's return so the
|
||||
// fatalErr load happens-after the store.
|
||||
// При фатальной ошибке отменяем остальные горутины и пробрасываем наверх.
|
||||
// watcherDone синхронизирует watcher-горутину с возвратом Run, обеспечивая
|
||||
// happens-after между store и load fatalErr.
|
||||
var fatalErr atomic.Pointer[error]
|
||||
watcherDone := make(chan struct{})
|
||||
go func() {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// Package udpserver implements the server-side UDP relay: a DTLS-terminated
|
||||
// stream is forwarded to a UDP backend (WireGuard) and vice-versa.
|
||||
// Package udpserver реализует серверную UDP-ретрансляцию: DTLS-терминированный
|
||||
// поток форвардится к UDP-backend (WireGuard) и обратно.
|
||||
package udpserver
|
||||
|
||||
import (
|
||||
@@ -18,8 +18,8 @@ const (
|
||||
udpIdleTimeout = 30 * time.Minute
|
||||
)
|
||||
|
||||
// Handle forwards DTLS packets between conn and a UDP backend at connectAddr
|
||||
// until either side closes. Blocks until both copy goroutines exit.
|
||||
// Handle форвардит DTLS-пакеты между conn и UDP-backend на connectAddr
|
||||
// до закрытия любой стороны. Блокируется до выхода обеих copy-горутин.
|
||||
func Handle(ctx context.Context, logger logx.Logger, conn net.Conn, connectAddr string) {
|
||||
serverConn, err := net.Dial("udp", connectAddr)
|
||||
if err != nil {
|
||||
@@ -64,8 +64,8 @@ func Handle(ctx context.Context, logger logx.Logger, conn net.Conn, connectAddr
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
// copyOne reads from src and writes to dst until ctx fires or either side errors.
|
||||
// Each read/write resets an idle timeout so a stuck side closes instead of hanging.
|
||||
// copyOne читает из src и пишет в dst до отмены ctx или ошибки любой стороны.
|
||||
// Каждый read/write сбрасывает idle timeout — зависший конец закрывается, а не висит.
|
||||
func copyOne(ctx context.Context, logger logx.Logger, src, dst net.Conn, count func(int)) {
|
||||
buf := make([]byte, udpRelayBufSize)
|
||||
for {
|
||||
|
||||
+13
-14
@@ -1,5 +1,5 @@
|
||||
// Package stats provides throughput counters and a counting net.Conn wrapper
|
||||
// shared between the client and server binaries.
|
||||
// Package stats — счётчики пропускной способности и обёртка net.Conn
|
||||
// с подсчётом байт. Используется и клиентом, и сервером.
|
||||
package stats
|
||||
|
||||
import (
|
||||
@@ -10,20 +10,20 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Stats tracks tx/rx byte counters. When Enabled is false, Add* are no-ops and
|
||||
// LogEvery returns immediately, matching the original isDebug-gated behavior.
|
||||
// Stats хранит счётчики tx/rx байт. При enabled=false Add* — no-op,
|
||||
// LogEvery возвращается сразу (поведение под isDebug).
|
||||
type Stats struct {
|
||||
tx atomic.Uint64
|
||||
rx atomic.Uint64
|
||||
enabled bool
|
||||
}
|
||||
|
||||
// New returns a Stats with the given enabled flag.
|
||||
// New возвращает Stats с заданным флагом enabled.
|
||||
func New(enabled bool) *Stats {
|
||||
return &Stats{enabled: enabled}
|
||||
}
|
||||
|
||||
// AddTx records n bytes sent.
|
||||
// AddTx учитывает n переданных байт.
|
||||
func (s *Stats) AddTx(n int) {
|
||||
if !s.enabled || n <= 0 {
|
||||
return
|
||||
@@ -31,7 +31,7 @@ func (s *Stats) AddTx(n int) {
|
||||
s.tx.Add(uint64(n))
|
||||
}
|
||||
|
||||
// AddRx records n bytes received.
|
||||
// AddRx учитывает n полученных байт.
|
||||
func (s *Stats) AddRx(n int) {
|
||||
if !s.enabled || n <= 0 {
|
||||
return
|
||||
@@ -39,8 +39,8 @@ func (s *Stats) AddRx(n int) {
|
||||
s.rx.Add(uint64(n))
|
||||
}
|
||||
|
||||
// LogEvery emits a throughput summary every 5s via logf until ctx is canceled.
|
||||
// No-op if Stats is disabled.
|
||||
// LogEvery каждые 5с печатает сводку пропускной способности через logf,
|
||||
// пока не отменён ctx. No-op, если Stats выключен.
|
||||
func (s *Stats) LogEvery(ctx context.Context, logf func(string, ...any), label, txName, rxName string) {
|
||||
if !s.enabled {
|
||||
return
|
||||
@@ -82,7 +82,7 @@ func (s *Stats) LogEvery(ctx context.Context, logf func(string, ...any), label,
|
||||
}
|
||||
}
|
||||
|
||||
// FormatBitsPerSecond renders a bandwidth value from a byte count and interval.
|
||||
// FormatBitsPerSecond форматирует пропускную способность из числа байт и интервала.
|
||||
func FormatBitsPerSecond(bytes uint64, interval time.Duration) string {
|
||||
if interval <= 0 {
|
||||
interval = time.Second
|
||||
@@ -98,7 +98,7 @@ func FormatBitsPerSecond(bytes uint64, interval time.Duration) string {
|
||||
return fmt.Sprintf("%.0f bit/s", bps)
|
||||
}
|
||||
|
||||
// FormatByteCount renders a human-readable byte count.
|
||||
// FormatByteCount форматирует число байт в человекочитаемый вид.
|
||||
func FormatByteCount(bytes uint64) string {
|
||||
if bytes >= 1024*1024 {
|
||||
return fmt.Sprintf("%.2f MiB", float64(bytes)/(1024*1024))
|
||||
@@ -109,20 +109,19 @@ func FormatByteCount(bytes uint64) string {
|
||||
return fmt.Sprintf("%d B", bytes)
|
||||
}
|
||||
|
||||
// CountingConn wraps a net.Conn and accumulates rx/tx byte counters in Stats.
|
||||
// CountingConn оборачивает net.Conn и аккумулирует rx/tx-счётчики в Stats.
|
||||
type CountingConn struct {
|
||||
net.Conn
|
||||
Stats *Stats
|
||||
}
|
||||
|
||||
// Read reads from the underlying conn and updates rx counter.
|
||||
func (c *CountingConn) Read(p []byte) (int, error) {
|
||||
n, err := c.Conn.Read(p)
|
||||
c.Stats.AddRx(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Write writes to the underlying conn and updates tx counter.
|
||||
|
||||
func (c *CountingConn) Write(p []byte) (int, error) {
|
||||
n, err := c.Conn.Write(p)
|
||||
c.Stats.AddTx(n)
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
// DTLS-as-obfuscation note (V2-8):
|
||||
// DTLS как обфускация (V2-8):
|
||||
//
|
||||
// DTLS in this project is used primarily as an *obfuscation* layer, not as a
|
||||
// security boundary. The VK TURN content-filter drops payloads that do not
|
||||
// look like a legitimate DTLS handshake followed by encrypted records, so the
|
||||
// handshake is what gets us through. The encryption it provides is a free
|
||||
// side-effect — we already trust the wrapped tunnel (WireGuard inside UDP
|
||||
// mode, or smux+KCP inside tcpfwd mode) to handle confidentiality and
|
||||
// integrity end-to-end.
|
||||
// DTLS в этом проекте используется прежде всего как слой *обфускации*, а не
|
||||
// как граница безопасности. VK TURN content-filter дропает payload, не
|
||||
// похожий на легитимный DTLS handshake с зашифрованными записями, — именно
|
||||
// handshake пропускает нас. Шифрование — бесплатный побочный эффект; мы уже
|
||||
// доверяем внутреннему туннелю (WireGuard в UDP-режиме или smux+KCP в tcpfwd)
|
||||
// для обеспечения конфиденциальности и целостности end-to-end.
|
||||
//
|
||||
// This is why the older `-no-dtls` / `Direct` flag was removed in V2-0: with
|
||||
// DTLS off, VK drops packets and the proxy effectively does not work in
|
||||
// production. There is no scenario in which disabling DTLS is the right
|
||||
// call against the live VK filter.
|
||||
// Именно поэтому старый флаг `-no-dtls` / `Direct` удалён в V2-0: без DTLS
|
||||
// VK дропает пакеты и прокси фактически не работает в production. Нет
|
||||
// сценария, в котором отключение DTLS против живого VK-фильтра — верное решение.
|
||||
//
|
||||
// Implication for future changes: do not treat the DTLS layer as if it were
|
||||
// security-critical (e.g. it is fine to use self-signed certs, send-only CID,
|
||||
// and no peer-cert validation — those are deliberate, not oversights).
|
||||
// Для будущих изменений: не трактуй DTLS-слой как security-critical
|
||||
// (самоподписанные сертификаты, send-only CID, отсутствие проверки peer-cert —
|
||||
// это намеренно, не упущения).
|
||||
package dtlsdial
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package dtlsdial wraps pion-dtls client setup (self-signed cert, EMS,
|
||||
// AES-128-GCM, send-only CID) plus an optional concurrency gate around the
|
||||
// handshake. Used by the client UDP and VLESS pipelines.
|
||||
// Package dtlsdial оборачивает настройку pion-dtls клиента (self-signed cert, EMS,
|
||||
// AES-128-GCM, send-only CID) плюс опциональный конкурентный gate на handshake.
|
||||
// Используется UDP и VLESS pipeline'ами клиента.
|
||||
package dtlsdial
|
||||
|
||||
import (
|
||||
@@ -14,19 +14,16 @@ import (
|
||||
"github.com/pion/dtls/v3/pkg/crypto/selfsign"
|
||||
)
|
||||
|
||||
// GenerateSelfSignedCert returns a new self-signed TLS certificate for use
|
||||
// as the DTLS identity. It is a thin wrapper around selfsign.GenerateSelfSigned
|
||||
// and exists so both cmd/server and Dialer share one call-site.
|
||||
func GenerateSelfSignedCert() (tls.Certificate, error) {
|
||||
return selfsign.GenerateSelfSigned()
|
||||
}
|
||||
|
||||
// Dialer configures the DTLS client handshake.
|
||||
// Dialer конфигурирует DTLS-handshake клиента.
|
||||
type Dialer struct {
|
||||
// HandshakeTimeout caps the handshake context. Zero means no timeout.
|
||||
// HandshakeTimeout ограничивает контекст handshake. Ноль — без таймаута.
|
||||
HandshakeTimeout time.Duration
|
||||
// HandshakeSem, if non-nil, gates concurrent handshakes (Dial blocks
|
||||
// until a slot is available or ctx fires).
|
||||
// HandshakeSem, если non-nil, ограничивает параллельные handshake
|
||||
// (Dial блокируется до появления слота или отмены ctx).
|
||||
HandshakeSem chan struct{}
|
||||
|
||||
certOnce sync.Once
|
||||
@@ -34,11 +31,10 @@ type Dialer struct {
|
||||
certErr error
|
||||
}
|
||||
|
||||
// Dial acquires the optional handshake slot and performs a DTLS client
|
||||
// handshake over pc to peer. On success returns the connected *dtls.Conn.
|
||||
// Caller closes it. The self-signed cert is generated once per Dialer and
|
||||
// reused across handshakes (DTLS is used here for obfuscation, not auth —
|
||||
// see internal/transport/dtlsdial/doc.go).
|
||||
// Dial захватывает опциональный handshake-слот и выполняет DTLS-handshake
|
||||
// клиента поверх pc к peer. При успехе возвращает *dtls.Conn (закрывает вызывающий).
|
||||
// Self-signed сертификат генерируется один раз на Dialer и переиспользуется
|
||||
// (DTLS здесь — для обфускации, не аутентификации; см. doc.go).
|
||||
func (d *Dialer) Dial(ctx context.Context, pc net.PacketConn, peer *net.UDPAddr) (*dtls.Conn, error) {
|
||||
d.certOnce.Do(func() {
|
||||
d.cert, d.certErr = GenerateSelfSignedCert()
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/xtaci/smux"
|
||||
)
|
||||
|
||||
// Profile holds the tunable KCP parameters. Both sides of a tunnel must agree.
|
||||
// Profile — настраиваемые KCP-параметры. Обе стороны туннеля должны совпадать.
|
||||
type Profile struct {
|
||||
NoDelay int
|
||||
Interval int
|
||||
@@ -23,13 +23,13 @@ type Profile struct {
|
||||
ACKNoDelay bool
|
||||
}
|
||||
|
||||
// FEC controls KCP forward-error-correction shards. Zero values disable FEC.
|
||||
// FEC управляет шардами KCP forward-error-correction. Нулевые значения отключают FEC.
|
||||
type FEC struct {
|
||||
Data int
|
||||
Parity int
|
||||
}
|
||||
|
||||
// DefaultProfile mirrors the historical balanced profile shipped with the proxy.
|
||||
// DefaultProfile — исторический balanced-профиль, поставляемый с прокси.
|
||||
func DefaultProfile() Profile {
|
||||
return Profile{
|
||||
NoDelay: 1,
|
||||
@@ -43,8 +43,8 @@ func DefaultProfile() Profile {
|
||||
}
|
||||
}
|
||||
|
||||
// LoadProfileFromEnv reads VK_TURN_KCP_PROFILE and per-field VK_TURN_KCP_*
|
||||
// overrides. Unknown profile name → DefaultProfile.
|
||||
// LoadProfileFromEnv читает VK_TURN_KCP_PROFILE и per-field переопределения
|
||||
// VK_TURN_KCP_*. Неизвестное имя профиля → DefaultProfile.
|
||||
func LoadProfileFromEnv() Profile {
|
||||
name := strings.ToLower(strings.TrimSpace(os.Getenv("VK_TURN_KCP_PROFILE")))
|
||||
var p Profile
|
||||
@@ -69,8 +69,8 @@ func LoadProfileFromEnv() Profile {
|
||||
return p
|
||||
}
|
||||
|
||||
// LoadFECFromEnv parses VK_TURN_KCP_FEC as "data:parity" (e.g. "10:3").
|
||||
// Empty/invalid → disabled.
|
||||
// LoadFECFromEnv парсит VK_TURN_KCP_FEC как "data:parity" (напр. "10:3").
|
||||
// Пустое/невалидное → отключено.
|
||||
func LoadFECFromEnv() FEC {
|
||||
raw := strings.TrimSpace(os.Getenv("VK_TURN_KCP_FEC"))
|
||||
if raw == "" {
|
||||
@@ -112,8 +112,8 @@ func envBool(name string, fallback bool) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// DtlsPacketConn wraps a net.Conn (DTLS) as a net.PacketConn for KCP.
|
||||
// Each DTLS Read/Write preserves message boundaries (datagram semantics).
|
||||
// DtlsPacketConn оборачивает net.Conn (DTLS) как net.PacketConn для KCP.
|
||||
// Каждый DTLS Read/Write сохраняет границы сообщений (datagram семантика).
|
||||
type DtlsPacketConn struct {
|
||||
conn net.Conn
|
||||
}
|
||||
@@ -151,12 +151,12 @@ 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).
|
||||
// NewKCPOverDTLS создаёт KCP-сессию поверх DTLS-соединения.
|
||||
// isServer: true — серверная сторона (listener), false — клиентская (dialer).
|
||||
func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool, profile Profile, fec FEC) (*kcp.UDPSession, error) {
|
||||
pc := NewDtlsPacketConn(dtlsConn)
|
||||
|
||||
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS already encrypts
|
||||
block, err := kcp.NewNoneBlockCrypt(nil) // DTLS уже шифрует
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -193,7 +193,7 @@ func NewKCPOverDTLS(dtlsConn net.Conn, isServer bool, profile Profile, fec FEC)
|
||||
return sess, nil
|
||||
}
|
||||
|
||||
// DefaultSmuxConfig returns smux config tuned for TURN tunnel.
|
||||
// DefaultSmuxConfig возвращает smux-конфигурацию, настроенную под TURN-туннель.
|
||||
func DefaultSmuxConfig() *smux.Config {
|
||||
cfg := smux.DefaultConfig()
|
||||
cfg.MaxReceiveBuffer = 4 * 1024 * 1024
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// Package turndial centralizes the TURN dial+allocate pipeline shared by
|
||||
// the client UDP (oneTurnConnection) and VLESS (createSmuxSession) modes.
|
||||
// Package turndial централизует TURN dial+allocate pipeline, общий для
|
||||
// UDP (oneTurnConnection) и VLESS (createSmuxSession) режимов клиента.
|
||||
//
|
||||
// One call to Open performs: parse target, apply host/port overrides,
|
||||
// resolve UDP addr, dial UDP-or-TCP (with SplitFirstWriteConn over TCP),
|
||||
// turn.NewClient, Listen, Allocate. Returns the relay PacketConn plus a
|
||||
// Close that tears down the allocation, TURN client, and underlying conn.
|
||||
// Один вызов Open выполняет: парсинг цели, применение host/port override,
|
||||
// резолв UDP-адреса, dial UDP-или-TCP (с SplitFirstWriteConn поверх TCP),
|
||||
// turn.NewClient, Listen, Allocate. Возвращает relay PacketConn и Close,
|
||||
// который разрушает аллокацию, TURN-клиент и транспорт.
|
||||
package turndial
|
||||
|
||||
import (
|
||||
@@ -18,32 +18,29 @@ import (
|
||||
"github.com/pion/turn/v5"
|
||||
)
|
||||
|
||||
// Config configures one Open call.
|
||||
// Config конфигурирует один вызов Open.
|
||||
type Config struct {
|
||||
// HostOverride, if non-empty, replaces the host part returned by the
|
||||
// credentials lookup.
|
||||
// HostOverride, если непустой, заменяет host из lookup credentials.
|
||||
HostOverride string
|
||||
// PortOverride, if non-empty, replaces the port part returned by the
|
||||
// credentials lookup.
|
||||
// PortOverride, если непустой, заменяет port из lookup credentials.
|
||||
PortOverride string
|
||||
// UDP=true dials TURN over UDP; otherwise over TCP via STUNConn.
|
||||
// UDP=true — dial TURN по UDP; иначе по TCP через STUNConn.
|
||||
UDP bool
|
||||
// DialTimeout caps the TCP dial. Zero defaults to 5s.
|
||||
// DialTimeout ограничивает TCP dial. Ноль → 5s.
|
||||
DialTimeout time.Duration
|
||||
}
|
||||
|
||||
// Stream is a live TURN allocation with its dependencies. Close tears
|
||||
// everything down in reverse order.
|
||||
// Stream — активная TURN-аллокация с зависимостями. Close разрушает в обратном порядке.
|
||||
type Stream struct {
|
||||
// Relay is the allocated relay PacketConn returned by turn.Client.Allocate.
|
||||
// Relay — выделенный relay PacketConn из turn.Client.Allocate.
|
||||
Relay net.PacketConn
|
||||
// ServerUDPAddr is the resolved TURN server UDP address (host:port).
|
||||
// ServerUDPAddr — резолвнутый UDP-адрес TURN-сервера (host:port).
|
||||
ServerUDPAddr *net.UDPAddr
|
||||
close func() error
|
||||
}
|
||||
|
||||
// Close releases the allocation, TURN client and underlying transport.
|
||||
// Safe to call once. Returns the first non-nil error (if any).
|
||||
// Close освобождает аллокацию, TURN-клиент и транспорт.
|
||||
// Безопасно вызвать один раз. Возвращает первую non-nil ошибку.
|
||||
func (s *Stream) Close() error {
|
||||
if s == nil || s.close == nil {
|
||||
return nil
|
||||
@@ -51,9 +48,8 @@ func (s *Stream) Close() error {
|
||||
return s.close()
|
||||
}
|
||||
|
||||
// Open dials TURN, creates a turn.Client and allocates a relay. rawAddr is
|
||||
// the host:port returned by the credentials lookup; user/pass are the TURN
|
||||
// long-term credentials.
|
||||
// Open подключается к TURN, создаёт turn.Client и выделяет relay. rawAddr —
|
||||
// host:port из lookup credentials; user/pass — долгосрочные TURN-реквизиты.
|
||||
func Open(ctx context.Context, cfg Config, peer *net.UDPAddr, user, pass, rawAddr string) (*Stream, error) {
|
||||
urlhost, urlport, err := net.SplitHostPort(rawAddr)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package bondframe contains the wire format used by the VLESS bond multi-lane
|
||||
// transport (hello + framed data/FIN). Both the client (initiator) and the
|
||||
// server (acceptor) speak the same encoding.
|
||||
// Package bondframe содержит wire-формат VLESS bond multi-lane transport
|
||||
// (hello + framed data/FIN). Клиент (инициатор) и сервер (акцептор) используют
|
||||
// одинаковую кодировку.
|
||||
package bondframe
|
||||
|
||||
import (
|
||||
@@ -24,21 +24,20 @@ const (
|
||||
LaneAttachTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
// Hello is the per-lane handshake header sent right after a smux stream opens.
|
||||
// Hello — per-lane handshake header, отправляемый сразу после открытия smux-потока.
|
||||
type Hello struct {
|
||||
ConnID uint64
|
||||
LaneIndex uint16
|
||||
LaneCount uint16
|
||||
}
|
||||
|
||||
// Frame is a single bonded data or FIN unit, identified by Seq within a ConnID.
|
||||
// Frame — одна bonded data или FIN единица, идентифицированная Seq внутри ConnID.
|
||||
type Frame struct {
|
||||
Type byte
|
||||
Seq uint64
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// WriteHello encodes and writes a Hello to w using the bond wire format.
|
||||
func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], Magic)
|
||||
@@ -50,8 +49,8 @@ func WriteHello(w io.Writer, connID uint64, laneIndex, laneCount uint16) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadHelloAfterMagic finishes reading a Hello whose first 4 magic bytes have
|
||||
// already been consumed (server pre-peeks the magic to multiplex protocols).
|
||||
// ReadHelloAfterMagic завершает чтение Hello, у которого первые 4 magic-байта
|
||||
// уже прочитаны (сервер pre-peek для мультиплексирования протоколов).
|
||||
func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) {
|
||||
var hdr [17]byte
|
||||
copy(hdr[0:4], magic[:])
|
||||
@@ -61,7 +60,6 @@ func ReadHelloAfterMagic(r io.Reader, magic [4]byte) (Hello, error) {
|
||||
return ParseHelloHeader(hdr[:])
|
||||
}
|
||||
|
||||
// ParseHelloHeader decodes a 17-byte Hello header from hdr.
|
||||
func ParseHelloHeader(hdr []byte) (Hello, error) {
|
||||
if len(hdr) != 17 {
|
||||
return Hello{}, fmt.Errorf("bad bond hello size: %d", len(hdr))
|
||||
@@ -79,7 +77,6 @@ func ParseHelloHeader(hdr []byte) (Hello, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// WriteFrame writes a single Frame to w (header + payload).
|
||||
func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
var hdr [13]byte
|
||||
hdr[0] = typ
|
||||
@@ -95,7 +92,6 @@ func WriteFrame(w io.Writer, typ byte, seq uint64, data []byte) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadFrame reads one Frame from r. Payloads over 4 MiB are rejected.
|
||||
func ReadFrame(r io.Reader) (Frame, error) {
|
||||
var hdr [13]byte
|
||||
if _, err := io.ReadFull(r, hdr[:]); err != nil {
|
||||
@@ -118,11 +114,11 @@ func ReadFrame(r io.Reader) (Frame, error) {
|
||||
return f, nil
|
||||
}
|
||||
|
||||
// PendingCap bounds the per-bond reorder buffer. A peer that emits seq with
|
||||
// permanent gaps cannot grow it past this many frames.
|
||||
// PendingCap ограничивает per-bond буфер переупорядочивания. Пир, генерирующий
|
||||
// seq с постоянными пропусками, не вырастит его больше этого числа фреймов.
|
||||
const PendingCap = 1024
|
||||
|
||||
// ReorderHooks plugs caller-specific logging into Reorder. All fields may be nil.
|
||||
// ReorderHooks подключает caller-специфичное логирование к Reorder. Все поля могут быть nil.
|
||||
type ReorderHooks struct {
|
||||
OnOverflow func(have int)
|
||||
OnUnknownType func(typ byte)
|
||||
@@ -130,12 +126,12 @@ type ReorderHooks struct {
|
||||
OnCloseWrite func(format string, v ...any)
|
||||
}
|
||||
|
||||
// Reorder consumes Frames from recv, writes payloads to dst in Seq order, and
|
||||
// returns the number of fully delivered chunks. It returns when:
|
||||
// - the FIN seq has been reached (CloseWrite is called on dst);
|
||||
// - recv is closed;
|
||||
// - ctx is cancelled;
|
||||
// - an unknown frame type, pending overflow, or write error fires.
|
||||
// Reorder потребляет Frame из recv, пишет payload в dst в порядке Seq и
|
||||
// возвращает число полностью доставленных чанков. Возвращается когда:
|
||||
// - достигнут FIN seq (на dst вызывается CloseWrite);
|
||||
// - recv закрыт;
|
||||
// - ctx отменён;
|
||||
// - неизвестный тип фрейма, переполнение pending или ошибка записи.
|
||||
func Reorder(ctx context.Context, dst net.Conn, recv <-chan Frame, h ReorderHooks) uint64 {
|
||||
pending := make(map[uint64][]byte)
|
||||
var expect uint64
|
||||
@@ -193,10 +189,9 @@ func Reorder(ctx context.Context, dst net.Conn, recv <-chan Frame, h ReorderHook
|
||||
}
|
||||
}
|
||||
|
||||
// CloseWrite half-closes the write side of conn if the underlying type
|
||||
// supports it (TCPConn, smux.Stream, …); otherwise it is a no-op. errf is
|
||||
// invoked with the error if CloseWrite fails; callers typically pass a
|
||||
// debug-gated log func.
|
||||
// CloseWrite полузакрывает write-сторону conn, если базовый тип поддерживает
|
||||
// это (TCPConn, smux.Stream, …); иначе no-op. errf вызывается с ошибкой при
|
||||
// сбое CloseWrite; вызывающие обычно передают debug-gated log func.
|
||||
func CloseWrite(conn net.Conn, errf func(format string, v ...any)) {
|
||||
type closeWriter interface {
|
||||
CloseWrite() error
|
||||
|
||||
@@ -13,8 +13,8 @@ import (
|
||||
pionudp "github.com/pion/transport/v4/udp"
|
||||
)
|
||||
|
||||
// bufPool eliminates per-packet heap allocation on the hot read/write paths
|
||||
// of the server-side wrapped PacketConn.
|
||||
// bufPool устраняет per-packet heap-аллокацию на горячих путях чтения/записи
|
||||
// серверного wrapped PacketConn.
|
||||
var bufPool = sync.Pool{
|
||||
New: func() any {
|
||||
b := make([]byte, 1600+Overhead)
|
||||
@@ -22,7 +22,7 @@ var bufPool = sync.Pool{
|
||||
},
|
||||
}
|
||||
|
||||
// Listen returns a dtls PacketListener that AEAD-wraps every accepted PacketConn.
|
||||
// Listen возвращает dtls PacketListener, AEAD-оборачивающий каждый принятый PacketConn.
|
||||
func Listen(addr *net.UDPAddr, key []byte) (dtlsnet.PacketListener, error) {
|
||||
state, err := NewState(key)
|
||||
if err != nil {
|
||||
@@ -58,8 +58,8 @@ func (l *packetListener) Accept() (net.PacketConn, net.Addr, error) {
|
||||
func (l *packetListener) Close() error { return l.inner.Close() }
|
||||
func (l *packetListener) Addr() net.Addr { return l.inner.Addr() }
|
||||
|
||||
// packetConn is a per-peer net.PacketConn that AEAD-wraps reads and writes
|
||||
// using bufPool to keep the hot path allocation-free.
|
||||
// packetConn — per-peer net.PacketConn, AEAD-оборачивающий чтение/запись
|
||||
// через bufPool для allocation-free горячего пути.
|
||||
type packetConn struct {
|
||||
inner net.PacketConn
|
||||
conn *Conn
|
||||
|
||||
@@ -7,8 +7,9 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// RelayPacketConn wraps a TURN relay PacketConn to direct all writes to a fixed peer.
|
||||
// When Conn is non-nil, packets are wrapped/unwrapped with SRTP-mimicry AEAD.
|
||||
// RelayPacketConn оборачивает TURN relay PacketConn, направляя все записи
|
||||
// фиксированному пиру. Если Conn non-nil, пакеты оборачиваются/разворачиваются
|
||||
// SRTP-mimicry AEAD.
|
||||
type RelayPacketConn struct {
|
||||
Relay net.PacketConn
|
||||
Peer net.Addr
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package srtpmimicry implements an SRTP-mimicry AEAD framing used to bypass
|
||||
// the VK TURN content filter.
|
||||
// Package srtpmimicry реализует AEAD-фрейминг с мимикрией SRTP для обхода
|
||||
// VK TURN content-filter.
|
||||
//
|
||||
// Purpose: obfuscation, not security. DTLS already provides confidentiality
|
||||
// and integrity on the inner channel. This layer exists to make traffic look
|
||||
// like SRTP so the VK content-filter does not drop it; it is not a defense
|
||||
// against an active adversary on its own.
|
||||
// Назначение: обфускация, а не безопасность. DTLS уже обеспечивает
|
||||
// конфиденциальность и целостность внутреннего канала. Этот слой существует,
|
||||
// чтобы трафик выглядел как SRTP — VK content-filter его не дропает;
|
||||
// сам по себе не является защитой от активного противника.
|
||||
//
|
||||
// Wire format:
|
||||
// Wire-формат:
|
||||
//
|
||||
// [12B RTP header | 12B explicit nonce | AEAD ciphertext | 16B tag]
|
||||
//
|
||||
// RTP header (RFC 3550):
|
||||
//
|
||||
// byte 0: 0x80 V=2, P=0, X=0, CC=0
|
||||
// byte 1: 0x6F M=0, PT=111 (opus, typical voice PT)
|
||||
// byte 2-3: seq16 BE monotonic, init random
|
||||
// byte 4-7: ts32 BE monotonic, init random, increments by 960 (20ms @ 48kHz)
|
||||
// byte 8-11: SSRC random per conn, MSB encodes direction
|
||||
// byte 1: 0x6F M=0, PT=111 (opus, типичный voice PT)
|
||||
// byte 2-3: seq16 BE монотонный, init random
|
||||
// byte 4-7: ts32 BE монотонный, init random, шаг 960 (20ms @ 48kHz)
|
||||
// byte 8-11: SSRC random per conn, MSB кодирует направление
|
||||
//
|
||||
// 12B explicit nonce = 4B sessionID || 8B counter (BE). sessionID MSB
|
||||
// matches SSRC MSB (direction bit). counter starts at a random uint64.
|
||||
// AAD = first 24 bytes (RTP header || nonce).
|
||||
// 12B explicit nonce = 4B sessionID || 8B counter (BE). MSB sessionID
|
||||
// совпадает с MSB SSRC (direction bit). counter стартует с random uint64.
|
||||
// AAD = первые 24 байта (RTP header || nonce).
|
||||
//
|
||||
// Wire format is frozen — bit-exact compatibility with deployed peers is required.
|
||||
// Wire-формат заморожен — требуется побитовая совместимость с задеплоенными пирами.
|
||||
package srtpmimicry
|
||||
|
||||
import (
|
||||
@@ -51,11 +51,10 @@ const (
|
||||
tsStep = 960 // 20ms @ 48kHz
|
||||
)
|
||||
|
||||
// MaxWire returns max wire bytes for a given payload size.
|
||||
func MaxWire(payloadLen int) int { return Overhead + payloadLen }
|
||||
|
||||
// State holds an AEAD instance derived from the shared key.
|
||||
// One State can be shared across many Conns (e.g. server-side listener).
|
||||
// State хранит AEAD-экземпляр, выведенный из общего ключа.
|
||||
// Один State может разделяться между многими Conn (напр. server-side listener).
|
||||
type State struct {
|
||||
aead cipher.AEAD
|
||||
}
|
||||
@@ -71,18 +70,17 @@ func NewState(key []byte) (*State, error) {
|
||||
return &State{aead: aead}, nil
|
||||
}
|
||||
|
||||
// Conn carries per-stream RTP state (seq/timestamp/SSRC/counter) plus a
|
||||
// reference to the shared AEAD State.
|
||||
// Conn несёт per-stream RTP-состояние (seq/timestamp/SSRC/counter) и
|
||||
// ссылку на общий AEAD State.
|
||||
type Conn struct {
|
||||
state *State
|
||||
sessionID [4]byte // 4B prefix for nonce; MSB encodes direction
|
||||
ssrc [4]byte // SSRC for RTP header; MSB encodes direction
|
||||
sessionID [4]byte // 4B префикс nonce; MSB кодирует направление
|
||||
ssrc [4]byte // SSRC для RTP header; MSB кодирует направление
|
||||
counter atomic.Uint64
|
||||
seq atomic.Uint32 // RTP sequence (used as uint16)
|
||||
timestamp atomic.Uint32 // RTP timestamp
|
||||
}
|
||||
|
||||
// NewConn allocates a fresh State from key and a Conn bound to it.
|
||||
func NewConn(key []byte, isServer bool) (*Conn, error) {
|
||||
s, err := NewState(key)
|
||||
if err != nil {
|
||||
@@ -91,8 +89,8 @@ func NewConn(key []byte, isServer bool) (*Conn, error) {
|
||||
return NewConnFromState(s, isServer)
|
||||
}
|
||||
|
||||
// NewConnFromState builds a Conn with random per-stream RTP fields,
|
||||
// reusing the supplied State.
|
||||
// NewConnFromState создаёт Conn со случайными per-stream RTP-полями,
|
||||
// переиспользуя переданный State.
|
||||
func NewConnFromState(state *State, isServer bool) (*Conn, error) {
|
||||
if state == nil {
|
||||
return nil, errors.New("wrap: nil state")
|
||||
@@ -123,15 +121,15 @@ func NewConnFromState(state *State, isServer bool) (*Conn, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// WrapInto encodes payload into dst (must be at least MaxWire(len(payload)) bytes)
|
||||
// and returns the number of wire bytes written.
|
||||
// WrapInto кодирует payload в dst (минимум MaxWire(len(payload)) байт)
|
||||
// и возвращает число записанных wire-байт.
|
||||
func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
wireLen := Overhead + len(payload)
|
||||
if len(dst) < wireLen {
|
||||
return 0, errors.New("wrap: dst buffer too small")
|
||||
}
|
||||
|
||||
// RTP header.
|
||||
// RTP-заголовок.
|
||||
dst[0] = rtpVersion
|
||||
dst[1] = rtpPT
|
||||
seq := uint16(c.seq.Add(1) - 1)
|
||||
@@ -140,7 +138,7 @@ func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
binary.BigEndian.PutUint32(dst[4:8], ts)
|
||||
copy(dst[8:12], c.ssrc[:])
|
||||
|
||||
// Explicit nonce.
|
||||
// Явный nonce.
|
||||
noncePos := rtpHdrLen
|
||||
copy(dst[noncePos:noncePos+4], c.sessionID[:])
|
||||
ctr := c.counter.Add(1) - 1
|
||||
@@ -155,9 +153,9 @@ func (c *Conn) WrapInto(dst, payload []byte) (int, error) {
|
||||
return wireLen, nil
|
||||
}
|
||||
|
||||
// Unwrap decodes a wire packet into dst and returns the plaintext length.
|
||||
// Note: the AEAD opens in-place inside wire, so callers must treat wire as
|
||||
// consumed after this call (do not reuse its contents).
|
||||
// Unwrap декодирует wire-пакет в dst и возвращает длину plaintext.
|
||||
// AEAD открывает in-place внутри wire — вызывающий должен считать wire
|
||||
// потреблённым после вызова (содержимое нельзя переиспользовать).
|
||||
func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
|
||||
if len(wire) < Overhead {
|
||||
return 0, errors.New("wrap: packet too short")
|
||||
@@ -177,9 +175,6 @@ func (c *Conn) Unwrap(wire, dst []byte) (int, error) {
|
||||
return len(plain), nil
|
||||
}
|
||||
|
||||
// --- Key helpers ---
|
||||
|
||||
// GenKeyHex returns a fresh hex-encoded random key.
|
||||
func GenKeyHex() (string, error) {
|
||||
key := make([]byte, KeyLen)
|
||||
if _, err := rand.Read(key); err != nil {
|
||||
@@ -188,8 +183,8 @@ func GenKeyHex() (string, error) {
|
||||
return hex.EncodeToString(key), nil
|
||||
}
|
||||
|
||||
// DecodeKey decodes a hex key and validates length when enabled.
|
||||
// When enabled is false, returns (nil, nil).
|
||||
// DecodeKey декодирует hex-ключ и проверяет длину если enabled.
|
||||
// Если enabled=false, возвращает (nil, nil).
|
||||
func DecodeKey(enabled bool, raw string) ([]byte, error) {
|
||||
if !enabled {
|
||||
return nil, nil
|
||||
|
||||
Reference in new issue
Block a user