refactor: удалить поддержку Yandex Telemost и мёртвый код

Удаляет флаг -yandex-link, getYandexCreds и ветку Telemost из основного
потока клиента. Убрана зависимость gorilla/websocket.

Вычищен мёртвый код, всплывший после удаления:
- browserprofile.ApplyHTTP / Random / profileList
- dnsdial DohResolver.LookupIPAddr / queryIPs / parseAnswer / dohCache
  и их тесты (единственный production-вызыватель — путь forwarder)
- устаревшая строка -captcha-solver в README

Публичные DoH-эндпоинты Yandex оставлены (RU-дружественный fallback, не
связан с Telemost).
This commit is contained in:
samosvalishe committed 2026-05-18 17:24:11 +03:00
1 parent ac3a6031d0
commit ead97d0089
7 files changed
+10 -673

No files matched your search

+2 -14
View File
@@ -294,23 +294,14 @@ docker build -t vk-turn-proxy .
**FEC (Reed-Solomon):** `VK_TURN_KCP_FEC=data:parity` (например, `10:3`) — упреждающая коррекция ошибок. На каждые `data` пакетов добавляется `parity` избыточных, потери до `parity` из `data+parity` восстанавливаются без ретрансмита. Overhead по полосе: `parity/data` (для `10:3` — 30%). Должно совпадать на клиенте и сервере. По умолчанию выключено (`0:0`). Включай только при случайных потерях; при шейпе по полосе FEC ухудшит goodput. **FEC (Reed-Solomon):** `VK_TURN_KCP_FEC=data:parity` (например, `10:3`) — упреждающая коррекция ошибок. На каждые `data` пакетов добавляется `parity` избыточных, потери до `parity` из `data+parity` восстанавливаются без ретрансмита. Overhead по полосе: `parity/data` (для `10:3` — 30%). Должно совпадать на клиенте и сервере. По умолчанию выключено (`0:0`). Включай только при случайных потерях; при шейпе по полосе FEC ухудшит goodput.
## Яндекс Телемост
Поддержка `-yandex-link` оставлена в коде, но этот режим считается нестабильным и может не работать. Если используете его, обычно нужен `-udp` и ручной TURN IP:
```bash
./client -udp -turn 5.255.211.241 -listen 127.0.0.1:9000 -peer <ip-vps>:56000 -yandex-link "<telemost-link>"
```
## Флаги Клиента ## Флаги Клиента
| Флаг | По умолчанию | Описание | | Флаг | По умолчанию | Описание |
| --- | --- | --- | | --- | --- | --- |
| `-listen` | `127.0.0.1:9000` | локальный адрес для WireGuard или Xray клиента | | `-listen` | `127.0.0.1:9000` | локальный адрес для WireGuard или Xray клиента |
| `-peer` | обязательный | адрес VK TURN Proxy server на VPS, например `<ip-vps>:56000` | | `-peer` | обязательный | адрес VK TURN Proxy server на VPS, например `<ip-vps>:56000` |
| `-vk-link` | пусто | ссылка VK Calls | | `-vk-link` | обязательный | ссылка VK Calls |
| `-yandex-link` | пусто | ссылка Яндекс Телемоста, legacy-режим | | `-n` | `10` | количество TURN-соединений |
| `-n` | VK: `10`, Yandex: `1` | количество TURN-соединений |
| `-udp` | `false` | подключаться к TURN-реле по UDP вместо TCP | | `-udp` | `false` | подключаться к TURN-реле по UDP вместо TCP |
| `-turn` | из ссылки | переопределить IP TURN-сервера | | `-turn` | из ссылки | переопределить IP TURN-сервера |
| `-port` | из ссылки | переопределить порт TURN-сервера | | `-port` | из ссылки | переопределить порт TURN-сервера |
@@ -320,13 +311,10 @@ docker build -t vk-turn-proxy .
| `-wrap-key` | пусто | 32-байтный ключ в hex, 64 символа | | `-wrap-key` | пусто | 32-байтный ключ в hex, 64 символа |
| `-gen-wrap-key` | `false` | напечатать новый WRAP-ключ и выйти | | `-gen-wrap-key` | `false` | напечатать новый WRAP-ключ и выйти |
| `-manual-captcha` | `false` | сразу использовать ручное прохождение captcha | | `-manual-captcha` | `false` | сразу использовать ручное прохождение captcha |
| `-captcha-solver` | `v2` | авто-решатель captcha: `v1` или `v2` |
| `-streams-per-cred` | `10` | сколько потоков используют один кеш TURN-учетных данных | | `-streams-per-cred` | `10` | сколько потоков используют один кеш TURN-учетных данных |
| `-debug` | `false` | подробные логи | | `-debug` | `false` | подробные логи |
| `-no-dtls` | `false` | прямой режим без DTLS, не рекомендуется | | `-no-dtls` | `false` | прямой режим без DTLS, не рекомендуется |
Нужно указать ровно одну ссылку: `-vk-link` или `-yandex-link`.
## Флаги Сервера ## Флаги Сервера
| Флаг | По умолчанию | Описание | | Флаг | По умолчанию | Описание |
-73
View File
@@ -2,8 +2,6 @@ package browserprofile
import ( import (
"encoding/json" "encoding/json"
"math/rand"
"net/http"
"os" "os"
fhttp "github.com/bogdanfinn/fhttp" fhttp "github.com/bogdanfinn/fhttp"
@@ -44,15 +42,6 @@ func Save(sp Saved) error {
return os.WriteFile(profileFile, data, 0644) return os.WriteFile(profileFile, data, 0644)
} }
func ApplyHTTP(req *http.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa)
req.Header.Set("sec-ch-ua-mobile", profile.SecChUaMobile)
req.Header.Set("sec-ch-ua-platform", profile.SecChUaPlatform)
req.Header.Set("Accept-Language", "en-US,en;q=0.9")
req.Header.Set("DNT", "1")
}
func ApplyFhttp(req *fhttp.Request, profile Profile) { func ApplyFhttp(req *fhttp.Request, profile Profile) {
req.Header.Set("User-Agent", profile.UserAgent) req.Header.Set("User-Agent", profile.UserAgent)
req.Header.Set("sec-ch-ua", profile.SecChUa) req.Header.Set("sec-ch-ua", profile.SecChUa)
@@ -62,65 +51,3 @@ func ApplyFhttp(req *fhttp.Request, profile Profile) {
req.Header.Set("DNT", "1") req.Header.Set("DNT", "1")
} }
// profiles contain paired User-Agent and Client Hints strings to harden bot detection.
// Used only as a fallback if no saved profile exists.
var profileList = []Profile{
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Google Chrome";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="144", "Not-A.Brand";v="8", "Google Chrome";v="144"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36 Edg/146.0.0.0",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Microsoft Edge";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36 Edg/145.0.0.0",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Microsoft Edge";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Windows"`,
},
{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"macOS"`,
},
{
UserAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="145", "Not-A.Brand";v="99", "Google Chrome";v="145"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"macOS"`,
},
{
UserAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="146", "Not-A.Brand";v="24", "Google Chrome";v="146"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Linux"`,
},
{
UserAgent: "Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
SecChUa: `"Chromium";v="144", "Not-A.Brand";v="8", "Google Chrome";v="144"`,
SecChUaMobile: "?0",
SecChUaPlatform: `"Linux"`,
},
}
func Random() Profile {
return profileList[rand.Intn(len(profileList))]
}
+2 -160
View File
@@ -13,7 +13,6 @@ import (
"log" "log"
"net" "net"
"net/http" "net/http"
"sort"
"strings" "strings"
"sync" "sync"
"sync/atomic" "sync/atomic"
@@ -30,8 +29,6 @@ const (
// Total budget across all endpoint attempts in forwardRaw. Must be a // Total budget across all endpoint attempts in forwardRaw. Must be a
// multiple of dohQueryTimeout to give every fallback a real chance. // multiple of dohQueryTimeout to give every fallback a real chance.
dohForwardBudget = 25 * time.Second dohForwardBudget = 25 * time.Second
dohCacheMinTTL = 10 * time.Second
dohCacheMaxTTL = 1 * time.Hour
dohMaxResponseBytes = 64 * 1024 dohMaxResponseBytes = 64 * 1024
dohContentType = "application/dns-message" dohContentType = "application/dns-message"
@@ -64,11 +61,10 @@ var defaultDohEndpoints = []DohEndpoint{
{"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 resolves hostnames to IPs via DNS-over-HTTPS (RFC 8484). // DohResolver POSTs DNS wire queries to one of several DoH endpoints.
type DohResolver struct { type DohResolver struct {
endpoints []DohEndpoint endpoints []DohEndpoint
client *http.Client client *http.Client
cache *dohCache
} }
// NewDohResolver constructs a resolver using defaultDohEndpoints if endpoints // NewDohResolver constructs a resolver using defaultDohEndpoints if endpoints
@@ -81,13 +77,12 @@ func NewDohResolver(endpoints []DohEndpoint) *DohResolver {
return &DohResolver{ return &DohResolver{
endpoints: endpoints, endpoints: endpoints,
client: &http.Client{Timeout: dohQueryTimeout, Transport: newBootstrapTransport(endpoints)}, client: &http.Client{Timeout: dohQueryTimeout, Transport: newBootstrapTransport(endpoints)},
cache: newDohCache(),
} }
} }
// newDohResolverWithClient is a test hook that skips the bootstrap transport. // newDohResolverWithClient is a test hook that skips the bootstrap transport.
func newDohResolverWithClient(endpoints []DohEndpoint, client *http.Client) *DohResolver { func newDohResolverWithClient(endpoints []DohEndpoint, client *http.Client) *DohResolver {
return &DohResolver{endpoints: endpoints, client: client, cache: newDohCache()} return &DohResolver{endpoints: endpoints, client: client}
} }
// newBootstrapTransport returns an http.Transport whose DialContext only // newBootstrapTransport returns an http.Transport whose DialContext only
@@ -161,119 +156,6 @@ func newBootstrapTransport(endpoints []DohEndpoint) *http.Transport {
} }
} }
// LookupIPAddr resolves host to a combined list of A+AAAA IPs (IPv4 first).
// Cached results bypass the network entirely.
func (r *DohResolver) LookupIPAddr(ctx context.Context, host string) ([]net.IP, error) {
if ip := net.ParseIP(host); ip != nil {
return []net.IP{ip}, nil
}
if ips, ok := r.cache.get(host); ok {
return ips, nil
}
type res struct {
ips []net.IP
ttl time.Duration
err error
}
results := make(chan res, 2)
for _, qt := range [...]uint16{dns.TypeA, dns.TypeAAAA} {
go func(qtype uint16) {
ips, ttl, err := r.queryIPs(ctx, host, qtype)
results <- res{ips, ttl, err}
}(qt)
}
var (
all []net.IP
lastErr error
minTTL = dohCacheMaxTTL
)
for range 2 {
rr := <-results
if rr.err != nil {
lastErr = rr.err
continue
}
all = append(all, rr.ips...)
if rr.ttl > 0 && rr.ttl < minTTL {
minTTL = rr.ttl
}
}
if len(all) == 0 {
if lastErr == nil {
lastErr = fmt.Errorf("doh: no records for %s", host)
}
return nil, lastErr
}
// IPv4 before IPv6 — better compat with mobile IPv4-only CGNAT.
sort.SliceStable(all, func(i, j int) bool {
return (all[i].To4() != nil) && (all[j].To4() == nil)
})
if minTTL < dohCacheMinTTL {
minTTL = dohCacheMinTTL
}
r.cache.set(host, all, minTTL)
return all, nil
}
// queryIPs issues one DoH query for qtype, walking endpoints until one
// succeeds, and parses the wire reply into IPs + min TTL.
func (r *DohResolver) queryIPs(ctx context.Context, host string, qtype uint16) ([]net.IP, time.Duration, error) {
m := new(dns.Msg)
m.SetQuestion(dns.Fqdn(host), qtype)
m.Id = 0 // RFC 8484 §4.1 — zero ID is cache-friendly on shared caches.
m.RecursionDesired = true
wire, err := m.Pack()
if err != nil {
return nil, 0, fmt.Errorf("doh: pack query: %w", err)
}
body, ep, err := r.forwardRaw(ctx, wire)
if err != nil {
return nil, 0, err
}
ips, ttl, err := parseAnswer(body)
if err != nil {
return nil, 0, fmt.Errorf("doh: parse %s: %w", ep.Hostname, err)
}
log.Printf("[DoH] %s %s via %s → %d IPs (ttl %s)", host, dns.TypeToString[qtype], ep.Hostname, len(ips), ttl)
return ips, ttl, nil
}
// parseAnswer decodes a DNS wire reply into A/AAAA records and the minimum TTL.
func parseAnswer(body []byte) ([]net.IP, time.Duration, error) {
reply := new(dns.Msg)
if err := reply.Unpack(body); err != nil {
return nil, 0, fmt.Errorf("unpack: %w", err)
}
if reply.Rcode != dns.RcodeSuccess {
return nil, 0, fmt.Errorf("rcode %s", dns.RcodeToString[reply.Rcode])
}
var (
ips []net.IP
minTTL uint32
)
updateTTL := func(ttl uint32) {
if minTTL == 0 || ttl < minTTL {
minTTL = ttl
}
}
for _, ans := range reply.Answer {
switch a := ans.(type) {
case *dns.A:
ips = append(ips, a.A)
updateTTL(a.Hdr.Ttl)
case *dns.AAAA:
ips = append(ips, a.AAAA)
updateTTL(a.Hdr.Ttl)
}
}
return ips, time.Duration(minTTL) * time.Second, nil
}
// forwardRaw POSTs an opaque DNS-wire query to the configured DoH endpoints // forwardRaw POSTs an opaque DNS-wire query to the configured DoH endpoints
// in order and returns the first successful raw response together with the // in order and returns the first successful raw response together with the
// endpoint that produced it. No parsing — useful for the local forwarder // endpoint that produced it. No parsing — useful for the local forwarder
@@ -331,46 +213,6 @@ func (r *DohResolver) postWire(ctx context.Context, ep DohEndpoint, query []byte
return body, nil return body, nil
} }
type dohCacheEntry struct {
ips []net.IP
expiry time.Time
}
type dohCache struct {
mu sync.RWMutex
m map[string]dohCacheEntry
}
func newDohCache() *dohCache {
return &dohCache{m: make(map[string]dohCacheEntry)}
}
func (c *dohCache) get(host string) ([]net.IP, bool) {
c.mu.RLock()
e, ok := c.m[host]
c.mu.RUnlock()
if !ok || time.Now().After(e.expiry) {
return nil, false
}
out := make([]net.IP, len(e.ips))
copy(out, e.ips)
return out, true
}
func (c *dohCache) set(host string, ips []net.IP, ttl time.Duration) {
if ttl <= 0 {
return
}
if ttl > dohCacheMaxTTL {
ttl = dohCacheMaxTTL
}
cp := make([]net.IP, len(ips))
copy(cp, ips)
c.mu.Lock()
c.m[host] = dohCacheEntry{ips: cp, expiry: time.Now().Add(ttl)}
c.mu.Unlock()
}
// Go's net.Resolver dials this stub like a regular nameserver, which avoids // Go's net.Resolver dials this stub like a regular nameserver, which avoids
// the many edge cases of a fake-net.Conn approach (RESINFO probes, EDNS // the many edge cases of a fake-net.Conn approach (RESINFO probes, EDNS
// handshakes, truncation, …). Whatever it reads on UDP/TCP is sent verbatim // handshakes, truncation, …). Whatever it reads on UDP/TCP is sent verbatim
-96
View File
@@ -6,7 +6,6 @@ import (
"net" "net"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"sync/atomic"
"testing" "testing"
"time" "time"
@@ -59,101 +58,6 @@ func readWire(t *testing.T, r io.Reader) []byte {
return b return b
} }
func TestDohResolver_LookupIPAddr_Success(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
if ct := r.Header.Get("Content-Type"); ct != "application/dns-message" {
t.Errorf("wrong Content-Type: %q", ct)
}
body := readWire(t, r.Body)
w.Header().Set("Content-Type", "application/dns-message")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(dohAnswer(t, body, net.ParseIP("93.184.216.34"), 300)) //nolint:errcheck
}))
defer srv.Close()
r := newDohResolverWithClient(
[]DohEndpoint{{URL: srv.URL, Hostname: "mock", BootstrapIPs: []string{"127.0.0.1"}}},
srv.Client(),
)
ips, err := r.LookupIPAddr(context.Background(), "example.com")
if err != nil {
t.Fatalf("lookup: %v", err)
}
if len(ips) == 0 {
t.Fatalf("no ips returned")
}
if ips[0].String() != "93.184.216.34" {
t.Fatalf("unexpected ip %s", ips[0])
}
// Two concurrent queries fire (A + AAAA), so we expect 2 hits.
if got := hits.Load(); got != 2 {
t.Fatalf("expected 2 HTTP hits, got %d", got)
}
}
func TestDohResolver_Fallback(t *testing.T) {
var firstHits, secondHits atomic.Int32
first := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
firstHits.Add(1)
w.WriteHeader(http.StatusInternalServerError)
}))
defer first.Close()
second := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
secondHits.Add(1)
body := readWire(t, r.Body)
w.Header().Set("Content-Type", "application/dns-message")
_, _ = w.Write(dohAnswer(t, body, net.ParseIP("1.2.3.4"), 300)) //nolint:errcheck
}))
defer second.Close()
r := newDohResolverWithClient(
[]DohEndpoint{
{URL: first.URL, Hostname: "first", BootstrapIPs: []string{"127.0.0.1"}},
{URL: second.URL, Hostname: "second", BootstrapIPs: []string{"127.0.0.1"}},
},
first.Client(),
)
ips, err := r.LookupIPAddr(context.Background(), "example.com")
if err != nil {
t.Fatalf("lookup: %v", err)
}
if len(ips) != 1 || ips[0].String() != "1.2.3.4" {
t.Fatalf("unexpected ips: %v", ips)
}
if firstHits.Load() == 0 || secondHits.Load() == 0 {
t.Fatalf("fallback did not probe both endpoints: first=%d second=%d", firstHits.Load(), secondHits.Load())
}
}
func TestDohResolver_Cache(t *testing.T) {
var hits atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
body := readWire(t, r.Body)
w.Header().Set("Content-Type", "application/dns-message")
_, _ = w.Write(dohAnswer(t, body, net.ParseIP("5.6.7.8"), 300)) //nolint:errcheck
}))
defer srv.Close()
r := newDohResolverWithClient(
[]DohEndpoint{{URL: srv.URL, Hostname: "mock", BootstrapIPs: []string{"127.0.0.1"}}},
srv.Client(),
)
if _, err := r.LookupIPAddr(context.Background(), "example.com"); err != nil {
t.Fatalf("first lookup: %v", err)
}
firstHits := hits.Load()
if _, err := r.LookupIPAddr(context.Background(), "example.com"); err != nil {
t.Fatalf("second lookup: %v", err)
}
if hits.Load() != firstHits {
t.Fatalf("cache miss: expected %d HTTP hits, got %d", firstHits, hits.Load())
}
}
func TestAutoDial_StickyAfterUDPFailure(t *testing.T) { func TestAutoDial_StickyAfterUDPFailure(t *testing.T) {
// DoH backend: always responds with a valid wire-format reply. // DoH backend: always responds with a valid wire-format reply.
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+6 -327
View File
@@ -14,7 +14,6 @@ import (
"log" "log"
"math/rand" "math/rand"
"net" "net"
"net/http"
neturl "net/url" neturl "net/url"
"os" "os"
"os/signal" "os/signal"
@@ -35,7 +34,6 @@ import (
"github.com/cacggghp/vk-turn-proxy/tcputil" "github.com/cacggghp/vk-turn-proxy/tcputil"
"github.com/cbeuw/connutil" "github.com/cbeuw/connutil"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/gorilla/websocket"
"github.com/pion/dtls/v3" "github.com/pion/dtls/v3"
"github.com/pion/dtls/v3/pkg/crypto/selfsign" "github.com/pion/dtls/v3/pkg/crypto/selfsign"
"github.com/pion/logging" "github.com/pion/logging"
@@ -872,311 +870,6 @@ func getTokenChain(ctx context.Context, link string, streamID int, creds VKCrede
// endregion // endregion
func getYandexCreds(link string) (string, string, string, error) {
const telemostConfHost = "cloud-api.yandex.ru"
telemostConfPath := fmt.Sprintf("%s%s%s", "/telemost_front/v2/telemost/conferences/https%3A%2F%2Ftelemost.yandex.ru%2Fj%2F", link, "/connection?next_gen_media_platform_allowed=false")
profile := browserprofile.Random()
name := generateName()
type ConferenceResponse struct {
URI string `json:"uri"`
RoomID string `json:"room_id"`
PeerID string `json:"peer_id"`
ClientConfiguration struct {
MediaServerURL string `json:"media_server_url"`
} `json:"client_configuration"`
Credentials string `json:"credentials"`
}
type PartMeta struct {
Name string `json:"name"`
Role string `json:"role"`
Description string `json:"description"`
SendAudio bool `json:"sendAudio"`
SendVideo bool `json:"sendVideo"`
}
type PartAttrs struct {
Name string `json:"name"`
Role string `json:"role"`
Description string `json:"description"`
}
type SdkInfo struct {
Implementation string `json:"implementation"`
Version string `json:"version"`
UserAgent string `json:"userAgent"`
HwConcurrency int `json:"hwConcurrency"`
}
type Capabilities struct {
OfferAnswerMode []string `json:"offerAnswerMode"`
InitialSubscriberOffer []string `json:"initialSubscriberOffer"`
SlotsMode []string `json:"slotsMode"`
SimulcastMode []string `json:"simulcastMode"`
SelfVadStatus []string `json:"selfVadStatus"`
DataChannelSharing []string `json:"dataChannelSharing"`
VideoEncoderConfig []string `json:"videoEncoderConfig"`
DataChannelVideoCodec []string `json:"dataChannelVideoCodec"`
BandwidthLimitationReason []string `json:"bandwidthLimitationReason"`
SdkDefaultDeviceManagement []string `json:"sdkDefaultDeviceManagement"`
JoinOrderLayout []string `json:"joinOrderLayout"`
PinLayout []string `json:"pinLayout"`
SendSelfViewVideoSlot []string `json:"sendSelfViewVideoSlot"`
ServerLayoutTransition []string `json:"serverLayoutTransition"`
SdkPublisherOptimizeBitrate []string `json:"sdkPublisherOptimizeBitrate"`
SdkNetworkLostDetection []string `json:"sdkNetworkLostDetection"`
SdkNetworkPathMonitor []string `json:"sdkNetworkPathMonitor"`
PublisherVp9 []string `json:"publisherVp9"`
SvcMode []string `json:"svcMode"`
SubscriberOfferAsyncAck []string `json:"subscriberOfferAsyncAck"`
SvcModes []string `json:"svcModes"`
ReportTelemetryModes []string `json:"reportTelemetryModes"`
KeepDefaultDevicesModes []string `json:"keepDefaultDevicesModes"`
}
type HelloPayload struct {
ParticipantMeta PartMeta `json:"participantMeta"`
ParticipantAttributes PartAttrs `json:"participantAttributes"`
SendAudio bool `json:"sendAudio"`
SendVideo bool `json:"sendVideo"`
SendSharing bool `json:"sendSharing"`
ParticipantID string `json:"participantId"`
RoomID string `json:"roomId"`
ServiceName string `json:"serviceName"`
Credentials string `json:"credentials"`
CapabilitiesOffer Capabilities `json:"capabilitiesOffer"`
SdkInfo SdkInfo `json:"sdkInfo"`
SdkInitializationID string `json:"sdkInitializationId"`
DisablePublisher bool `json:"disablePublisher"`
DisableSubscriber bool `json:"disableSubscriber"`
DisableSubscriberAudio bool `json:"disableSubscriberAudio"`
}
type HelloRequest struct {
UID string `json:"uid"`
Hello HelloPayload `json:"hello"`
}
type FlexUrls []string
type WSSResponse struct {
UID string `json:"uid"`
ServerHello struct {
RtcConfiguration struct {
IceServers []struct {
Urls FlexUrls `json:"urls"`
Username string `json:"username,omitempty"`
Credential string `json:"credential,omitempty"`
} `json:"iceServers"`
} `json:"rtcConfiguration"`
} `json:"serverHello"`
}
type WSSAck struct {
UID string `json:"uid"`
Ack struct {
Status struct {
Code string `json:"code"`
} `json:"status"`
} `json:"ack"`
}
type WSSData struct {
ParticipantID string
RoomID string
Credentials string
Wss string
}
endpoint := "https://" + telemostConfHost + telemostConfPath
tr := &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
}
client := &http.Client{
Timeout: 20 * time.Second,
Transport: tr,
}
defer client.CloseIdleConnections()
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return "", "", "", err
}
browserprofile.ApplyHTTP(req, profile)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", "https://telemost.yandex.ru/")
req.Header.Set("Origin", "https://telemost.yandex.ru")
req.Header.Set("Client-Instance-Id", uuid.New().String())
resp, err := client.Do(req)
if err != nil {
return "", "", "", err
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil {
log.Printf("close response body: %s", closeErr)
}
}()
if resp.StatusCode != http.StatusOK {
readBody, err2 := io.ReadAll(resp.Body)
if err2 != nil {
return "", "", "", fmt.Errorf("GetConference: status=%s (failed to read body: %v)", resp.Status, err2)
}
return "", "", "", fmt.Errorf("GetConference: status=%s body=%s", resp.Status, string(readBody))
}
var result ConferenceResponse
if err = json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", "", "", fmt.Errorf("decode conf: %v", err)
}
data := WSSData{
ParticipantID: result.PeerID,
RoomID: result.RoomID,
Credentials: result.Credentials,
Wss: result.ClientConfiguration.MediaServerURL,
}
h := http.Header{}
h.Set("Origin", "https://telemost.yandex.ru")
h.Set("User-Agent", profile.UserAgent)
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
dialer := websocket.Dialer{}
var conn *websocket.Conn
conn, resp, err = dialer.DialContext(ctx, data.Wss, h)
if err != nil {
if resp != nil && resp.Body != nil {
_ = resp.Body.Close()
}
return "", "", "", fmt.Errorf("ws dial: %w", err)
}
if resp != nil && resp.Body != nil {
defer func() { _ = resp.Body.Close() }()
}
defer func() {
if closeErr := conn.Close(); closeErr != nil {
log.Printf("close websocket: %s", closeErr)
}
}()
req1 := HelloRequest{
UID: uuid.New().String(),
Hello: HelloPayload{
ParticipantMeta: PartMeta{
Name: name,
Role: "SPEAKER",
Description: "",
SendAudio: false,
SendVideo: false,
},
ParticipantAttributes: PartAttrs{
Name: name,
Role: "SPEAKER",
Description: "",
},
SendAudio: false,
SendVideo: false,
SendSharing: false,
ParticipantID: data.ParticipantID,
RoomID: data.RoomID,
ServiceName: "telemost",
Credentials: data.Credentials,
SdkInfo: SdkInfo{
Implementation: "browser",
Version: "5.15.0",
UserAgent: profile.UserAgent,
HwConcurrency: 4,
},
SdkInitializationID: uuid.New().String(),
DisablePublisher: false,
DisableSubscriber: false,
DisableSubscriberAudio: false,
CapabilitiesOffer: Capabilities{
OfferAnswerMode: []string{"SEPARATE"},
InitialSubscriberOffer: []string{"ON_HELLO"},
SlotsMode: []string{"FROM_CONTROLLER"},
SimulcastMode: []string{"DISABLED"},
SelfVadStatus: []string{"FROM_SERVER"},
DataChannelSharing: []string{"TO_RTP"},
VideoEncoderConfig: []string{"NO_CONFIG"},
DataChannelVideoCodec: []string{"VP8"},
BandwidthLimitationReason: []string{"BANDWIDTH_REASON_DISABLED"},
SdkDefaultDeviceManagement: []string{"SDK_DEFAULT_DEVICE_MANAGEMENT_DISABLED"},
JoinOrderLayout: []string{"JOIN_ORDER_LAYOUT_DISABLED"},
PinLayout: []string{"PIN_LAYOUT_DISABLED"},
SendSelfViewVideoSlot: []string{"SEND_SELF_VIEW_VIDEO_SLOT_DISABLED"},
ServerLayoutTransition: []string{"SERVER_LAYOUT_TRANSITION_DISABLED"},
SdkPublisherOptimizeBitrate: []string{"SDK_PUBLISHER_OPTIMIZE_BITRATE_DISABLED"},
SdkNetworkLostDetection: []string{"SDK_NETWORK_LOST_DETECTION_DISABLED"},
SdkNetworkPathMonitor: []string{"SDK_NETWORK_PATH_MONITOR_DISABLED"},
PublisherVp9: []string{"PUBLISH_VP9_DISABLED"},
SvcMode: []string{"SVC_MODE_DISABLED"},
SubscriberOfferAsyncAck: []string{"SUBSCRIBER_OFFER_ASYNC_ACK_DISABLED"},
SvcModes: []string{"FALSE"},
ReportTelemetryModes: []string{"TRUE"},
KeepDefaultDevicesModes: []string{"TRUE"},
},
},
}
if isDebug {
b, _ := json.MarshalIndent(req1, "", " ")
log.Printf("Sending HELLO:\n%s", string(b))
}
if err := conn.WriteJSON(req1); err != nil {
return "", "", "", fmt.Errorf("ws write: %w", err)
}
if err := conn.SetReadDeadline(time.Now().Add(15 * time.Second)); err != nil {
return "", "", "", fmt.Errorf("ws set read deadline: %w", err)
}
for {
_, msg, err := conn.ReadMessage()
if err != nil {
return "", "", "", fmt.Errorf("ws read: %w", err)
}
if isDebug {
s := string(msg)
if len(s) > 800 {
s = s[:800] + "...(truncated)"
}
log.Printf("WSS recv: %s", s)
}
var ack WSSAck
if err := json.Unmarshal(msg, &ack); err == nil && ack.Ack.Status.Code != "" {
continue
}
var resp WSSResponse
if err := json.Unmarshal(msg, &resp); err == nil {
ice := resp.ServerHello.RtcConfiguration.IceServers
for _, s := range ice {
for _, u := range s.Urls {
if !strings.HasPrefix(u, "turn:") && !strings.HasPrefix(u, "turns:") {
continue
}
if strings.Contains(u, "transport=tcp") {
continue
}
clean := strings.Split(u, "?")[0]
address := strings.TrimPrefix(strings.TrimPrefix(clean, "turn:"), "turns:")
return s.Username, s.Credential, address, nil
}
}
}
}
}
func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.Conn, error) { func dtlsFunc(ctx context.Context, conn net.PacketConn, peer *net.UDPAddr) (net.Conn, error) {
certificate, err := selfsign.GenerateSelfSigned() certificate, err := selfsign.GenerateSelfSigned()
if err != nil { if err != nil {
@@ -1646,9 +1339,8 @@ func main() {
port := flag.String("port", "", "override TURN port") port := flag.String("port", "", "override TURN port")
listen := flag.String("listen", "127.0.0.1:9000", "listen on ip:port") listen := flag.String("listen", "127.0.0.1:9000", "listen on ip:port")
vklink := flag.String("vk-link", "", "VK calls invite link \"https://vk.com/call/join/...\"") vklink := flag.String("vk-link", "", "VK calls invite link \"https://vk.com/call/join/...\"")
yalink := flag.String("yandex-link", "", "Yandex telemost invite link \"https://telemost.yandex.ru/j/...\"")
peerAddr := flag.String("peer", "", "peer server address (host:port)") peerAddr := flag.String("peer", "", "peer server address (host:port)")
n := flag.Int("n", 0, "connections to TURN (default 10 for VK, 1 for Yandex)") n := flag.Int("n", 10, "connections to TURN")
udp := flag.Bool("udp", false, "connect to TURN with UDP") udp := flag.Bool("udp", false, "connect to TURN with UDP")
direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE") direct := flag.Bool("no-dtls", false, "connect without obfuscation. DO NOT USE")
vlessMode := flag.Bool("vless", false, "VLESS mode: forward TCP connections (for VLESS) instead of UDP packets") vlessMode := flag.Bool("vless", false, "VLESS mode: forward TCP connections (for VLESS) instead of UDP packets")
@@ -1690,8 +1382,8 @@ func main() {
if err != nil { if err != nil {
panic(err) panic(err)
} }
if (*vklink == "") == (*yalink == "") { if *vklink == "" {
log.Panicf("Need either vk-link or yandex-link!") log.Panicf("Need vk-link!")
} }
if *wrapMode && *direct { if *wrapMode && *direct {
log.Panicf("-wrap requires DTLS; remove -no-dtls") log.Panicf("-wrap requires DTLS; remove -no-dtls")
@@ -1711,28 +1403,15 @@ func main() {
isDebug = *debugFlag isDebug = *debugFlag
manualCaptcha = *manualCaptchaFlag manualCaptcha = *manualCaptchaFlag
var link string
var getCreds getCredsFunc
if *vklink != "" {
parts := strings.Split(*vklink, "join/") parts := strings.Split(*vklink, "join/")
link = parts[len(parts)-1] link := parts[len(parts)-1]
getCreds = func(ctx context.Context, s string, streamID int) (string, string, string, error) { getCreds := getCredsFunc(func(ctx context.Context, s string, streamID int) (string, string, string, error) {
return getVkCredsCached(ctx, s, streamID, appDialer) return getVkCredsCached(ctx, s, streamID, appDialer)
} })
if *n <= 0 { if *n <= 0 {
*n = 10 *n = 10
} }
} else {
parts := strings.Split(*yalink, "j/")
link = parts[len(parts)-1]
getCreds = func(ctx context.Context, s string, streamID int) (string, string, string, error) {
return getYandexCreds(s)
}
if *n <= 0 {
*n = 1
}
}
if idx := strings.IndexAny(link, "/?#"); idx != -1 { if idx := strings.IndexAny(link, "/?#"); idx != -1 {
link = link[:idx] link = link[:idx]
} }
-1
View File
@@ -7,7 +7,6 @@ require (
github.com/bogdanfinn/tls-client v1.14.0 github.com/bogdanfinn/tls-client v1.14.0
github.com/cbeuw/connutil v1.0.1 github.com/cbeuw/connutil v1.0.1
github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
github.com/gorilla/websocket v1.5.3
github.com/miekg/dns v1.1.72 github.com/miekg/dns v1.1.72
github.com/pion/dtls/v3 v3.1.2 github.com/pion/dtls/v3 v3.1.2
github.com/pion/logging v0.2.4 github.com/pion/logging v0.2.4
-2
View File
@@ -45,8 +45,6 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE=
github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY= github.com/klauspost/cpuid/v2 v2.2.9 h1:66ze0taIn2H33fBvCkXuv9BmCwDfafmiIVpKV9kKGuY=