style: перевести комментарии на русский, убрать очевидные

This commit is contained in:
samosvalishe committed 2026-05-21 12:31:50 +03:00
1 parent ada9b949a4
commit e417dac087
48 files changed
+659 -671

No files matched your search

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