diff --git a/README.md b/README.md index 8c5db99..60465b3 100644 --- a/README.md +++ b/README.md @@ -8,16 +8,18 @@ Step-by-step setup guide (in Russian): [docs/SETUP.md](docs/SETUP.md) ## How it works -Two tunnel modes are available: **DC** (DataChannel) and **Video** (VP8 data encoding). +Two tunnel modes are available: **DC** (DataChannel) and **Video** (VP8 data encoding). The recommended setup is **headless on both ends** - pure Go (Pion) talks to the platform's SFU directly, no browser. ChaCha20 obfuscation, configurable VP8 pacing, and the LiveKit/WB Stream backend are headless-only features. + +A legacy browser path (Android `WebView` joiner against an Electron desktop creator with JS hooks) still works for VK DC, but it's slower, can't obfuscate, and is being phased out. New deployments should use headless. ### DC mode -Browser-based. JavaScript hooks intercept RTCPeerConnection on the call page, create a DataChannel alongside the call's built-in channels, and use it as a bidirectional data pipe. +Pion opens a SCTP DataChannel on the publisher PC and tunnels TCP/UDP through it. Frames pass through the platform's SFU like any other DataChannel payload. + -- **VK Call** - Negotiated DataChannel id:2 (alongside VK's animoji channel id:1). Data flows through VK's SFU ``` -Joiner (censored, Android) Creator (free internet, desktop) +Joiner (censored, Android/iOS/Linux) Creator (free internet) All apps | @@ -27,70 +29,33 @@ tun2socks (IP -> TCP) | SOCKS5 proxy (Go, :1080) | -WebSocket (:9000) - | -WebView (call page) Electron (call page) +Headless joiner (Pion) Headless creator (Pion) | | -DataChannel <----- SFU -----> DataChannel - | - WebSocket (:9000) - | - Go relay - | - Internet -``` - -### Video mode - -Go-based. Pion (Go WebRTC library) connects directly to the platform's TURN/SFU servers, bypassing the browser's WebRTC stack entirely. Data is encoded inside VP8 video frames. - -- **VK Call** - Single PeerConnection, data flows through VK's SFU -- **Telemost** - Dual PeerConnection (pub/sub), SFU architecture - -The JS hook replaces `RTCPeerConnection` with a `MockPeerConnection` that forwards all SDP/ICE operations to the local Pion server via WebSocket. Pion creates the real PeerConnection with the platform's TURN servers. - -**VP8 data encoding:** -- Data frames: `[0xFF marker][4B length][payload]` - sent as VP8 video samples -- Keepalive frames: valid VP8 interframes (17 bytes) at 25fps, keyframe every 60th frame. Keeps the video track alive so the SFU/TURN does not disconnect -- The `0xFF` marker byte distinguishes data from real VP8 (keyframe first byte has bit0=0, interframe has bit0=1, so `0xFF` never appears naturally) -- On the receiving side, RTP packets are reassembled into full frames. First byte `0xFF` = extract data, otherwise = keepalive, ignore - -**Multiplexing protocol** over the VP8 tunnel: `[4B frame length][4B connID][1B msgType][payload]` -- Message types: Connect, ConnectOK, ConnectErr, Data, Close, UDP, UDPReply -- Multiple TCP/UDP connections are multiplexed into a single VP8 video stream - -``` -Joiner (censored, Android) Creator (free internet, desktop) - -All apps - | -VpnService (captures all traffic) - | -tun2socks (IP -> TCP) - | -SOCKS5 proxy (Go, :1080) - | -VP8 data tunnel (Pion) VP8 data tunnel (Pion) - | | -MockPC (WebView) MockPC (Electron) - | | -Pion WebRTC <------ SFU ------> Pion WebRTC +DataChannel <------- SFU -------> DataChannel | Relay bridge | Internet ``` -Traffic goes through the platform's SFU servers which are whitelisted. To the network firewall it looks like a normal video call. +### Video mode + +Same pipeline as DC mode, but the tunnel rides on a published VP8 video track instead of a SCTP DataChannel. Useful when the SFU rate-limits DataChannels but lets RTP through (e.g. Telemost), and platform-mandatory in some cases (WB Stream's publisher track is always video). Tunnel framing and the multiplex layer above it are the same as DC mode. + +Traffic goes through the platform's SFU, which is on the government whitelist. To DPI it looks like a normal video call. ## Components -- `hooks/` - JavaScript hooks for DC, Video, and Headless modes (VK and Telemost) -- `relay/` - Go relay: SOCKS5 proxy, WebSocket server, VP8 video tunnel, headless joiner, connection multiplexing -- `headless/vk/` - Headless VK creator: creates calls via API, Pion DataChannel tunnel, no browser -- `headless/telemost/` - Headless Telemost creator: same approach for Yandex Telemost -- `android-app/` - Android joiner app (WebView/headless + VpnService + Go relay) -- `creator-app/` - Electron desktop creator app +- `relay/` - Go relay shared by both ends: SOCKS5 proxy, tun2socks plumbing, DC/VP8 tunnel, ChaCha20 obfuscator, connection multiplexer, gomobile/iOS bindings +- `headless/vk/` - Headless VK creator: creates or joins a call via the VK HTTP API, Pion DC/VP8 tunnel, no browser +- `headless/telemost/` - Headless Telemost (Yandex) creator with the same model +- `headless/wbstream/` - Headless WB Stream creator (LiveKit-backed, anonymous guest tokens) +- `headless/wbstream-joiner/` - Desktop WB Stream joiner (counterpart to the creator, used for tests and Linux clients) +- `headless/tests/` - End-to-end smoke tests for each platform +- `android-app/` - Android joiner: VpnService + tun2socks + headless Pion (primary path); also retains a `WebView` fallback for the legacy browser flow +- `ios-proxy-app/` - iOS joiner: SOCKS5 + headless Pion via the gomobile xcframework +- `creator-app/` - Electron desktop creator app: GUI front-end that can run either the legacy browser path or spawn the headless Go binaries; suitable for both interactive use and deployments +- `hooks/` - JavaScript hooks for the legacy browser path (DC and Video modes, VK and Telemost). Headless does not use JS hooks. ## Download @@ -108,13 +73,15 @@ Download and run the Electron app from [GitHub Releases](../../releases). It bun **Important:** The call must be created from within the Creator app. Joining an existing call from the app will not work - the JS hooks must be present from the moment the call starts. -### Joiner side (censored, Android) +### Joiner side (censored, Android/iOS/Linux) -1. Download and install `whitelist-bypass.apk` from [GitHub Releases](../../releases) -2. Select tunnel mode (DC or Video) -3. Paste the call link and tap GO -4. The app joins the call, establishes the tunnel, starts VPN -5. All device traffic flows through the call +Three forms are available; pick whichever fits the device: + +- **Android** - install `whitelist-bypass.apk` from [Releases](../../releases). Allow the VPN prompt on first launch. Paste the join link and tap GO; system-wide traffic flows through the call. +- **iOS** - install `whitelist-bypass-proxy.ipa` from [Releases](../../releases) (sideload via AltStore / Sideloadly / your dev account). Exposes a local SOCKS5 proxy only - no system VPN. To proxy the whole device, point any SOCKS5-capable VPN app (Shadowrocket, Streisand, ...) at the SOCKS5 endpoint the app shows; or set the proxy per app (Telegram has built-in support). +- **Linux desktop** - run `headless-wbstream-joiner --room --socks-port 1080`; exposes a SOCKS5 proxy on the given port for whatever you point at it. Useful for servers and Linux clients. + +The full step-by-step (Russian) covers each platform in detail: see [docs/SETUP.md](docs/SETUP.md). ## Building from source @@ -137,7 +104,7 @@ Download and run the Electron app from [GitHub Releases](../../releases). It bun ./build-go.sh # Go .aar, relay binary, headless creators ./copy-hooks.sh # Copy JS hooks to android assets ./build-app.sh # Android APK -./build-headless.sh # Headless creator binaries only +./build-headless.sh # Headless binaries only ./build-creator.sh # Creator Electron app (all platforms) ./build-ios.sh # Go .xcframework for iOS ``` @@ -163,6 +130,7 @@ Output in `prebuilts/`: | `WhitelistBypass Creator-*-ia32.exe` | Windows x86 | | `WhitelistBypass Creator-*.AppImage` | Linux x64 | | `whitelist-bypass.apk` | Android | +| `whitelist-bypass-proxy.ipa` | iOS, unsigned | | `headless-vk-creator-linux-x64` | Linux x64 | | `headless-vk-creator-linux-ia32` | Linux x86 | | `headless-telemost-creator-linux-x64` | Linux x64 | @@ -178,53 +146,68 @@ docker compose -f docker-build/docker-compose.yml up This will build all components (creator-app, headless, android app) into the `prebuild` folder (except the macOS creator) -### Relay - -``` -relay --mode [--ws-port 9000] [--socks-port 1080] -``` - -- `--mode` - required: `joiner`, `creator`, `vk-video-joiner`, `vk-video-creator`, `telemost-video-joiner`, `telemost-video-creator` -- `--ws-port` - WebSocket port for browser/hook connection (default 9000) -- `--socks-port` - SOCKS5 proxy port, joiner modes only (default 1080) - -The Go relay is split into platform-specific files: -- `relay/mobile/mobile.go` - Shared networking code (SOCKS5, WebSocket, framing) -- `relay/mobile/tun_android.go` - Android-only: tun2socks + fdsan fix (CGo) -- `relay/mobile/tun_stub.go` - Desktop stub (no tun2socks needed) - -This allows cross-compiling the relay for macOS/Windows/Linux without CGo or Android NDK. - ### Headless creators Pure Go creators that create calls via API without a browser. No Electron, no JS hooks - Go Pion PeerConnection handles the DataChannel tunnel directly. ```sh -# VK -cd headless/vk && go build -o headless-vk-creator . -./headless-vk-creator --cookies cookies.json [--peer-id ] [--resources ] [--write-file call-vk] - -# Telemost -cd headless/telemost && go build -o headless-telemost . -./headless-telemost --cookies cookies-yandex.json [--resources ] [--write-file call-telemost] +./build-headless.sh ``` -- `--cookies` - path to cookies exported as JSON (`[{"name":"..","value":".."},...]`) -- `--peer-id` - VK peer_id for the call (VK only, optional) -- `--resources` - resource mode (see below) -- `--write-file` - path to file where the active call link is appended (one link per line, created if missing) +Three binaries are produced: -**Resource modes:** +```sh +./headless/vk/headless-vk-creator --cookies cookies-vk.json +./headless/telemost/headless-telemost-creator --cookies cookies-telemost.json +./headless/wbstream/headless-wbstream-creator +``` -| Mode | read-buf | max-dc-buf | mem-limit | Use case | +WB Stream uses anonymous guest tokens, so no cookies are required. VK and Telemost expect cookies exported from the desktop creator app (`VK Cookies` / `Yandex Cookies` buttons) as JSON `[{"name":"..","value":".."},...]`. + +#### Common flags + +| Flag | VK | TM | WB | Description | |---|---|---|---|---| -| `moderate` | 16KB | 1MB | 64MB | Low memory environments, VPS | -| `default` | 32KB | 4MB | 128MB | General use | -| `unlimited` | 64KB | 8MB | 256MB | Maximum throughput | +| `--cookies ` | yes | yes | - | path to cookies JSON | +| `--cookie-string ` | yes | yes | - | raw cookie string `name=val; name=val` | +| `--write-file ` | yes | yes | yes | append the active join link to this file (one link per line) | +| `--resources ` | yes | yes | yes | `default` / `moderate` / `unlimited` / `custom` (see below) | +| `--read-buf ` | yes | yes | yes | DC/RTP read buffer; only consulted with `--resources custom` | +| `--max-dc-buf ` | yes | - | - | DataChannel `BufferedAmountLowThreshold`; only with `--resources custom` | +| `--mem-limit ` | yes | yes | yes | Go soft memory limit (`debug.SetMemoryLimit`); only with `--resources custom` | -- `read-buf` - TCP read buffer size. Smaller = more frequent backpressure checks, less bursty memory -- `max-dc-buf` - pauses TCP reads when DataChannel buffered amount exceeds this. Prevents SCTP pending queue from growing unbounded -- `mem-limit` - Go runtime soft memory limit (`debug.SetMemoryLimit`), makes GC more aggressive near the cap +#### Joining an existing call + +By default each binary creates a fresh call. To attach to an existing one (server restarts without invalidating the link, multiple shaped sessions, ...): + +| Creator | Flag | Value | +|---|---|---| +| VK | `--vk-link ` | `https://vk.com/call/join/` | +| Telemost | `--tm-link ` | `https://telemost.yandex.ru/j/` | +| WB Stream | `--room ` | `wbstream://` or just the UUID | + +Mutually exclusive with the call-creation flags (`--peer-id` for VK; the others have no creation flag). + +#### Resource modes + +| Mode | `read-buf` | `max-dc-buf` (VK) | `mem-limit` | +|---|---|---|---| +| `moderate` | 16 KB | 1 MB | 64 MB | +| `default` | 32 KB | 4 MB | 128 MB | +| `unlimited`| 64 KB | 8 MB | 256 MB | +| `custom` | from `--read-buf` | from `--max-dc-buf` | from `--mem-limit` | + +`custom` falls back to `unlimited` defaults for any flag left unset, so partial overrides work: + +```sh +./headless-vk-creator --cookies cookies-vk.json --vk-link https://vk.com/call/join/ \ + --resources custom --read-buf 65536 --max-dc-buf 8388608 --mem-limit 268435456 \ + --write-file /var/run/whitelist-bypass/call.txt +``` + +- `read-buf` - TCP/DC read buffer size. Smaller = more frequent backpressure checks, less bursty memory +- `max-dc-buf` - pauses TCP reads when the DataChannel buffered amount exceeds this; only wired in VK (Pion `BufferedAmountLowThreshold`) +- `mem-limit` - Go runtime soft memory limit; makes GC more aggressive near the cap ## License diff --git a/docs/SETUP.md b/docs/SETUP.md index 1603499..4174340 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -16,7 +16,9 @@ - **Creator** (сторона со свободным интернетом) - десктоп или headless на сервере - **Joiner** (сторона с цензурой) - Android или iOS -Два режима туннеля: **DC** (DataChannel, только VK) и **Video** (VP8, VK и Telemost). Режим должен совпадать на Creator и Joiner. +Два режима туннеля: **DC** (DataChannel) и **Video** (VP8). Headless creator автоматически подстраивается под режим, выбранный joiner-ом, при каждом новом подключении. В legacy браузерном пути такого нет - нельзя создать DC в VK и подключиться по видео. + +> **Рекомендуется headless с обеих сторон** - там есть обфускация траффика, настраиваемый VP8 pacing и WB Stream. Старый браузерный путь (Android `WebView` против Electron-creator с JS-хуками) ещё работает, но медленнее, без обфускации и постепенно выводится из эксплуатации. ## Creator (десктоп) @@ -57,25 +59,60 @@ # Telemost ./headless-telemost-creator --cookies cookies-yandex.json + +# WB Stream (анонимный гостевой токен, куки не нужны) +./headless-wbstream-creator ``` После запуска Creator создаст звонок и выведет ссылку в лог. Ссылку нужно передать на Joiner. +### Подключение к существующему звонку + +Чтобы не пересоздавать звонок при перезапуске, передайте существующую ссылку: + +```sh +./headless-vk-creator --cookies cookies.json --vk-link https://vk.com/call/join/ +./headless-telemost-creator --cookies cookies-yandex.json --tm-link https://telemost.yandex.ru/j/ +./headless-wbstream-creator --room wbstream:// +``` + ### Флаги -| Флаг | Описание | -|---|---| -| `--cookies ` | Путь к файлу с куками (JSON) | -| `--cookie-string ` | Куки строкой (`name=val; name=val`) | -| `--peer-id ` | VK peer_id (только VK, опционально) | -| `--resources ` | Режим ресурсов: `moderate`, `default`, `unlimited` | -| `--write-file ` | Файл, куда записывается активная ссылка на звонок | +| Флаг | VK | TM | WB | Описание | +|---|---|---|---|---| +| `--cookies ` | да | да | - | Путь к файлу с куками (JSON) | +| `--cookie-string ` | да | да | - | Куки строкой (`name=val; name=val`) | +| `--peer-id ` | да | - | - | VK peer_id для нового звонка | +| `--vk-link ` | да | - | - | Подключиться к существующему VK звонку | +| `--tm-link ` | - | да | - | Подключиться к существующей Telemost конференции | +| `--room ` | - | - | да | Подключиться к существующей WB Stream комнате | +| `--resources ` | да | да | да | `default` / `moderate` / `unlimited` / `custom` | +| `--read-buf ` | да | да | да | Размер read-буфера, только с `--resources custom` | +| `--max-dc-buf ` | да | - | - | Порог `BufferedAmountLowThreshold` DC, только с `--resources custom` | +| `--mem-limit ` | да | да | да | Soft memory limit Go рантайма, только с `--resources custom` | +| `--write-file ` | да | да | да | Файл, куда записывается активная ссылка на звонок | ### Режимы ресурсов -- **moderate** - для VPS с малым объемом RAM (64MB лимит) -- **default** - для обычного использования (128MB лимит) -- **unlimited** - максимальная пропускная способность (256MB лимит, может работать нестабильно из-за congestion control) +| Режим | `read-buf` | `max-dc-buf` (VK) | `mem-limit` | Когда использовать | +|---|---|---|---|---| +| `moderate` | 16 KB | 1 MB | 64 MB | VPS с малой RAM | +| `default` | 32 KB | 4 MB | 128 MB | Обычное использование | +| `unlimited`| 64 KB | 8 MB | 256 MB | Максимум пропускной способности (может троттлить из-за congestion control) | +| `custom` | из `--read-buf` | из `--max-dc-buf` | из `--mem-limit` | Тонкая настройка | + +В режиме `custom` любой не указанный флаг использует значения из `unlimited`. Пример с явной настройкой всех буферов: + +```sh +./headless-vk-creator \ + --cookies cookies.json \ + --vk-link https://vk.com/call/join/ \ + --write-file /var/run/whitelist-bypass/call.txt \ + --resources custom \ + --read-buf 65536 \ + --max-dc-buf 8388608 \ + --mem-limit 268435456 +``` ## Бот VK diff --git a/headless/telemost/main.go b/headless/telemost/main.go index 6dc39cd..e81dbcb 100644 --- a/headless/telemost/main.go +++ b/headless/telemost/main.go @@ -160,6 +160,22 @@ func getConnection(cookieStr, confURL string, cfg TMConfig) (*ConnInfo, error) { }, nil } +func joinExistingConference(cookieStr, conferenceURI string, cfg TMConfig) (*ConnInfo, error) { + conferenceURI = strings.TrimSpace(conferenceURI) + if conferenceURI == "" { + return nil, fmt.Errorf("empty -tm-link") + } + log.Printf("[auth] Joining existing conference: %s", conferenceURI) + info, err := getConnection(cookieStr, url.QueryEscape(conferenceURI), cfg) + if err != nil { + return nil, err + } + info.ConferenceURI = conferenceURI + log.Printf("[auth] peer_id=%s room_id=%s", info.PeerID, info.RoomID) + log.Printf("[auth] media_server=%s", info.MediaServerURL) + return info, nil +} + func createAndJoinCall(cookieStr string, cfg TMConfig) (*ConnInfo, error) { log.Println("[auth] Creating conference...") r, status, err := tmRequest("POST", "/conferences?next_gen_media_platform_allowed=true", @@ -635,7 +651,10 @@ func extractUfrag(candidate string) string { func main() { cookiesPath := flag.String("cookies", "", "path to cookies-yandex.json") cookieString := flag.String("cookie-string", "", "raw cookie string") - resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited") + tmLink := flag.String("tm-link", "", "Telemost conference URI to join an existing conference") + resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited, custom") + customReadBuf := flag.Int("read-buf", 0, "read buffer size, used with -resources custom") + customMemLimit := flag.Int64("mem-limit", 0, "memory limit in bytes, used with -resources custom") writeFile := flag.String("write-file", "", "path to file where active call link is appended") flag.Parse() @@ -651,8 +670,17 @@ func main() { case "unlimited": readBuf = common.RTPBufSize memLimit = 256 << 20 + case "custom": + readBuf = *customReadBuf + if readBuf == 0 { + readBuf = common.RTPBufSize + } + memLimit = *customMemLimit + if memLimit == 0 { + memLimit = 256 << 20 + } default: - log.Fatalf("[config] unknown resources mode: %s", *resources) + log.Fatalf("[config] unknown resources mode: %s (use moderate, default, unlimited, custom)", *resources) } if memLimit > 0 { debug.SetMemoryLimit(memLimit) @@ -680,9 +708,17 @@ func main() { log.Fatalf("[config] %v", err) } - connInfo, err := createAndJoinCall(cookieStr, cfg) - if err != nil { - log.Fatalf("Failed to create call: %v", err) + var connInfo *ConnInfo + if *tmLink != "" { + connInfo, err = joinExistingConference(cookieStr, *tmLink, cfg) + if err != nil { + log.Fatalf("Failed to join existing conference: %v", err) + } + } else { + connInfo, err = createAndJoinCall(cookieStr, cfg) + if err != nil { + log.Fatalf("Failed to create call: %v", err) + } } if *writeFile != "" { diff --git a/headless/tests/test-telemost-join-existing.sh b/headless/tests/test-telemost-join-existing.sh new file mode 100755 index 0000000..517b6f8 --- /dev/null +++ b/headless/tests/test-telemost-join-existing.sh @@ -0,0 +1,93 @@ +#!/bin/sh +# Smoke test for headless-telemost-creator -tm-link: create a conference, +# then a second creator joins the same conference URI. +# +# Usage: ./test-telemost-join-existing.sh + +set -u + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +CREATOR="$ROOT/headless/telemost/headless-telemost-creator" +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +COOKIES="$1" +SETTLE_TIMEOUT=30 + +[ -x "$CREATOR" ] || { echo "FAIL: $CREATOR not built, run ./build-headless.sh" >&2; exit 2; } +[ -f "$COOKIES" ] || { echo "FAIL: cookies not found at: $COOKIES" >&2; exit 2; } +echo "cookies: $COOKIES" + +PHASE1_LOG=$(mktemp -t tm-create.XXXXXX.log) +PHASE2_LOG=$(mktemp -t tm-join.XXXXXX.log) +P1_PID="" +P2_PID="" + +cleanup() { + [ -n "$P2_PID" ] && kill "$P2_PID" 2>/dev/null + [ -n "$P1_PID" ] && kill "$P1_PID" 2>/dev/null + wait 2>/dev/null +} +trap cleanup EXIT INT TERM + +echo "=== phase 1: create conference ===" +"$CREATOR" -cookies "$COOKIES" > "$PHASE1_LOG" 2>&1 & +P1_PID=$! + +waited=0 +JOIN_LINK="" +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + JOIN_LINK=$(grep -m1 -oE "https://telemost\.yandex\.[a-z]+/j/[A-Za-z0-9_-]+" "$PHASE1_LOG" | head -1) + [ -n "$JOIN_LINK" ] && break + if ! kill -0 "$P1_PID" 2>/dev/null; then + echo "FAIL: phase 1 process died" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 + fi + sleep 1 + waited=$((waited + 1)) +done + +if [ -z "$JOIN_LINK" ]; then + echo "FAIL: phase 1 did not print join_link within ${SETTLE_TIMEOUT}s" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 +fi +echo "phase 1 join_link: $JOIN_LINK" + +sleep 3 + +echo "" +echo "=== phase 2: join existing conference via -tm-link ===" +"$CREATOR" -cookies "$COOKIES" -tm-link "$JOIN_LINK" > "$PHASE2_LOG" 2>&1 & +P2_PID=$! + +waited=0 +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + if grep -q "media_server=" "$PHASE2_LOG"; then + break + fi + if grep -qE "Failed to join existing conference|empty conference URI" "$PHASE2_LOG"; then + break + fi + if ! kill -0 "$P2_PID" 2>/dev/null; then + break + fi + sleep 1 + waited=$((waited + 1)) +done + +echo "" +echo "--- phase 2 log tail ---" +tail -25 "$PHASE2_LOG" + +if grep -q "media_server=" "$PHASE2_LOG" && grep -q "Joining existing conference" "$PHASE2_LOG"; then + echo "" + echo "PASS: phase 2 joined the existing conference" + exit 0 +fi + +echo "" +echo "FAIL: phase 2 did not reach media_server stage" >&2 +exit 1 diff --git a/headless/tests/test-vk-join-existing.sh b/headless/tests/test-vk-join-existing.sh new file mode 100755 index 0000000..9017688 --- /dev/null +++ b/headless/tests/test-vk-join-existing.sh @@ -0,0 +1,93 @@ +#!/bin/sh +# Smoke test for -vk-link: create a call, then join it via the new flag. +# +# Usage: ./test-vk-join-existing.sh + +set -u + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +CREATOR="$ROOT/headless/vk/headless-vk-creator" +if [ $# -lt 1 ]; then + echo "Usage: $0 " >&2 + exit 2 +fi +COOKIES="$1" +SETTLE_TIMEOUT=25 + +[ -x "$CREATOR" ] || { echo "FAIL: $CREATOR not built, run ./build-headless.sh" >&2; exit 2; } +[ -f "$COOKIES" ] || { echo "FAIL: cookies not found at: $COOKIES" >&2; exit 2; } +echo "cookies: $COOKIES" + +PHASE1_LOG=$(mktemp -t vk-create.XXXXXX.log) +PHASE2_LOG=$(mktemp -t vk-join.XXXXXX.log) +P1_PID="" +P2_PID="" + +cleanup() { + [ -n "$P2_PID" ] && kill "$P2_PID" 2>/dev/null + [ -n "$P1_PID" ] && kill "$P1_PID" 2>/dev/null + wait 2>/dev/null +} +trap cleanup EXIT INT TERM + +echo "=== phase 1: create call ===" +"$CREATOR" -cookies "$COOKIES" > "$PHASE1_LOG" 2>&1 & +P1_PID=$! + +waited=0 +JOIN_LINK="" +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + JOIN_LINK=$(grep -m1 -oE "https://vk\.com/call/join/[A-Za-z0-9_-]+" "$PHASE1_LOG") + [ -n "$JOIN_LINK" ] && break + if ! kill -0 "$P1_PID" 2>/dev/null; then + echo "FAIL: phase 1 process died" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 + fi + sleep 1 + waited=$((waited + 1)) +done + +if [ -z "$JOIN_LINK" ]; then + echo "FAIL: phase 1 did not print join_link within ${SETTLE_TIMEOUT}s" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 +fi +echo "phase 1 join_link: $JOIN_LINK" + +# Wait a beat so the call is fully joined on VK's side before phase 2 starts. +sleep 3 + +echo "" +echo "=== phase 2: join existing call via -vk-link ===" +"$CREATOR" -cookies "$COOKIES" -vk-link "$JOIN_LINK" > "$PHASE2_LOG" 2>&1 & +P2_PID=$! + +waited=0 +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + if grep -q "vk-ws] Connected" "$PHASE2_LOG"; then + break + fi + if grep -qE "Failed to join existing call|empty WS endpoint|empty session_key" "$PHASE2_LOG"; then + break + fi + if ! kill -0 "$P2_PID" 2>/dev/null; then + break + fi + sleep 1 + waited=$((waited + 1)) +done + +echo "" +echo "--- phase 2 log tail ---" +tail -25 "$PHASE2_LOG" + +if grep -q "vk-ws] Connected" "$PHASE2_LOG"; then + echo "" + echo "PASS: phase 2 joined the existing call (got vk-ws connection)" + exit 0 +fi + +echo "" +echo "FAIL: phase 2 did not reach vk-ws connection" >&2 +exit 1 diff --git a/headless/tests/test-wbstream-join-existing.sh b/headless/tests/test-wbstream-join-existing.sh new file mode 100755 index 0000000..b9e1da6 --- /dev/null +++ b/headless/tests/test-wbstream-join-existing.sh @@ -0,0 +1,87 @@ +#!/bin/sh +# Smoke test for headless-wbstream-creator -room: create a room, then a second +# creator joins the same room id. + +set -u + +ROOT="$(cd "$(dirname "$0")/../.." && pwd)" +CREATOR="$ROOT/headless/wbstream/headless-wbstream-creator" +SETTLE_TIMEOUT=25 + +[ -x "$CREATOR" ] || { echo "FAIL: $CREATOR not built (run ./build-headless.sh)" >&2; exit 2; } + +PHASE1_LOG=$(mktemp -t wb-create.XXXXXX.log) +PHASE2_LOG=$(mktemp -t wb-join.XXXXXX.log) +P1_PID="" +P2_PID="" + +cleanup() { + [ -n "$P2_PID" ] && kill "$P2_PID" 2>/dev/null + [ -n "$P1_PID" ] && kill "$P1_PID" 2>/dev/null + wait 2>/dev/null +} +trap cleanup EXIT INT TERM + +echo "=== phase 1: create room ===" +"$CREATOR" > "$PHASE1_LOG" 2>&1 & +P1_PID=$! + +waited=0 +JOIN_LINK="" +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + JOIN_LINK=$(grep -m1 -oE "wbstream://[A-Za-z0-9-]+" "$PHASE1_LOG" | head -1) + [ -n "$JOIN_LINK" ] && break + if ! kill -0 "$P1_PID" 2>/dev/null; then + echo "FAIL: phase 1 process died" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 + fi + sleep 1 + waited=$((waited + 1)) +done + +if [ -z "$JOIN_LINK" ]; then + echo "FAIL: phase 1 did not print join_link within ${SETTLE_TIMEOUT}s" >&2 + tail -20 "$PHASE1_LOG" >&2 + exit 1 +fi +echo "phase 1 join_link: $JOIN_LINK" + +sleep 3 + +echo "" +echo "=== phase 2: join existing room via -room ===" +"$CREATOR" -room "$JOIN_LINK" > "$PHASE2_LOG" 2>&1 & +P2_PID=$! + +waited=0 +while [ "$waited" -lt "$SETTLE_TIMEOUT" ]; do + if grep -q "\[lk\] join: room=" "$PHASE2_LOG"; then + break + fi + if grep -qE "Failed to|register guest|create room" "$PHASE2_LOG" | grep -qiE "error|failed"; then + break + fi + if ! kill -0 "$P2_PID" 2>/dev/null; then + break + fi + sleep 1 + waited=$((waited + 1)) +done + +echo "" +echo "--- phase 2 log tail ---" +tail -25 "$PHASE2_LOG" + +phase2_room=$(grep -m1 -oE "room=[a-f0-9-]+" "$PHASE2_LOG" | head -1 | cut -d= -f2) +expected_room=$(echo "$JOIN_LINK" | sed 's|wbstream://||') + +if [ "$phase2_room" = "$expected_room" ]; then + echo "" + echo "PASS: phase 2 joined room $phase2_room" + exit 0 +fi + +echo "" +echo "FAIL: phase 2 did not join the expected room (got '$phase2_room', wanted '$expected_room')" >&2 +exit 1 diff --git a/headless/vk/main.go b/headless/vk/main.go index a871890..d53e4dc 100644 --- a/headless/vk/main.go +++ b/headless/vk/main.go @@ -207,6 +207,47 @@ func authAndJoin(cookieStr, okJoinLink string, cfg VKConfig) (*JoinResponse, err return &joinResp, nil } +func joinExistingCall(cookieStr, vkLink string, cfg VKConfig) (*CallInfo, error) { + if cfg.AppID == "" || cfg.APIVersion == "" { + return nil, fmt.Errorf("config incomplete: app_id=%q api=%q", cfg.AppID, cfg.APIVersion) + } + token := extractJoinToken(vkLink) + if token == "" { + return nil, fmt.Errorf("could not extract join token from %q", vkLink) + } + log.Printf("[auth] Joining existing call token=%s", token) + joinResp, err := authAndJoin(cookieStr, token, cfg) + if err != nil { + return nil, err + } + return &CallInfo{ + JoinLink: vkLink, + OKJoinLink: token, + TurnServer: joinResp.TurnServer, + StunServer: joinResp.StunServer, + WSEndpoint: joinResp.Endpoint, + }, nil +} + +func extractJoinToken(link string) string { + link = strings.TrimSpace(link) + if link == "" { + return "" + } + if u, err := url.Parse(link); err == nil && u.Scheme != "" { + path := strings.Trim(u.Path, "/") + if path != "" { + parts := strings.Split(path, "/") + return parts[len(parts)-1] + } + } + if !strings.ContainsAny(link, "/?&=") { + return link + } + parts := strings.Split(strings.TrimRight(link, "/"), "/") + return parts[len(parts)-1] +} + func createAndJoinCall(cookieStr, peerId string, cfg VKConfig) (*CallInfo, error) { if cfg.AppID == "" || cfg.APIVersion == "" { return nil, fmt.Errorf("config incomplete: app_id=%q api=%q", cfg.AppID, cfg.APIVersion) @@ -532,8 +573,12 @@ func (b *Bridge) run(callInfo *CallInfo, cookieStr string, cfg VKConfig) { func main() { cookiesPath := flag.String("cookies", "", "path to cookies.json") cookieString := flag.String("cookie-string", "", "raw cookie string (name=val; name=val)") - peerId := flag.String("peer-id", "", "VK peer_id for the call") - resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited") + peerId := flag.String("peer-id", "", "VK peer_id for a new call") + vkLink := flag.String("vk-link", "", "VK call link to join an existing call") + resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited, custom") + customReadBuf := flag.Int("read-buf", 0, "read buffer size, used with -resources custom") + customMaxDCBuf := flag.Int("max-dc-buf", 0, "max DC buffer size in bytes, used with -resources custom") + customMemLimit := flag.Int64("mem-limit", 0, "memory limit in bytes, used with -resources custom") writeFile := flag.String("write-file", "", "path to file where active call link is appended") flag.Parse() @@ -553,8 +598,21 @@ func main() { readBuf = common.RTPBufSize maxDCBuf = 8 * 1024 * 1024 memLimit = 256 * 1024 * 1024 + case "custom": + readBuf = *customReadBuf + if readBuf == 0 { + readBuf = common.RTPBufSize + } + maxDCBuf = uint64(*customMaxDCBuf) + if maxDCBuf == 0 { + maxDCBuf = 8 * 1024 * 1024 + } + memLimit = *customMemLimit + if memLimit == 0 { + memLimit = 256 * 1024 * 1024 + } default: - log.Fatalf("[config] unknown resources mode: %s (use moderate, default, unlimited)", *resources) + log.Fatalf("[config] unknown resources mode: %s (use moderate, default, unlimited, custom)", *resources) } if memLimit > 0 { debug.SetMemoryLimit(memLimit) @@ -581,9 +639,20 @@ func main() { log.Fatalf("[config] %v", err) } - callInfo, err := createAndJoinCall(cookieStr, *peerId, cfg) - if err != nil { - log.Fatalf("Failed to create call: %v", err) + if *vkLink != "" && *peerId != "" { + log.Fatalf("[config] -vk-link and -peer-id are mutually exclusive") + } + var callInfo *CallInfo + if *vkLink != "" { + callInfo, err = joinExistingCall(cookieStr, *vkLink, cfg) + if err != nil { + log.Fatalf("Failed to join existing call: %v", err) + } + } else { + callInfo, err = createAndJoinCall(cookieStr, *peerId, cfg) + if err != nil { + log.Fatalf("Failed to create call: %v", err) + } } if *writeFile != "" { diff --git a/headless/wbstream/main.go b/headless/wbstream/main.go index 2526d2b..0a9f57e 100644 --- a/headless/wbstream/main.go +++ b/headless/wbstream/main.go @@ -18,26 +18,41 @@ import ( func main() { roomFlag := flag.String("room", "", "WB Stream room id or wbstream:// (empty = create new)") displayName := flag.String("name", "Headless", "display name in the room") - resources := flag.String("resources", "default", "resource mode: moderate, default, unlimited") + resources := flag.String("resources", "default", "resource mode: default, moderate, unlimited, custom") + customReadBuf := flag.Int("read-buf", 0, "DC read buffer size in bytes, used with -resources custom") + customMemLimit := flag.Int64("mem-limit", 0, "memory limit in bytes, used with -resources custom") writeFile := flag.String("write-file", "", "path to file where active room id is appended") flag.Parse() + var readBuf int var memLimit int64 switch *resources { case "moderate": + readBuf = 16384 memLimit = 64 << 20 case "default": + readBuf = common.DCBufSize memLimit = 128 << 20 case "unlimited": + readBuf = common.RTPBufSize memLimit = 256 << 20 + case "custom": + readBuf = *customReadBuf + if readBuf == 0 { + readBuf = common.RTPBufSize + } + memLimit = *customMemLimit + if memLimit == 0 { + memLimit = 256 << 20 + } default: - log.Fatalf("[config] unknown resources mode: %s", *resources) + log.Fatalf("[config] unknown resources mode: %s (use moderate, default, unlimited, custom)", *resources) } if memLimit > 0 { debug.SetMemoryLimit(memLimit) } common.MaskingEnabled = true - log.Printf("[config] resources=%s mem-limit=%d", *resources, memLimit) + log.Printf("[config] resources=%s read-buf=%d mem-limit=%d", *resources, readBuf, memLimit) requestedRoom := strings.TrimPrefix(strings.TrimSpace(*roomFlag), "wbstream://") roomID, roomToken, accessToken, err := wbstream.AuthAndGetToken(nil, requestedRoom, *displayName) @@ -69,19 +84,20 @@ func main() { LogFn: log.Printf, RoomID: roomID, AccessToken: accessToken, + ReadBuf: readBuf, }) var activeBridge *tunnel.RelayBridge sess.OnConnected = func(tun tunnel.DataTunnel) { if activeBridge != nil { activeBridge.Reset() } - readBuf := common.VP8BufSize + bridgeReadBuf := common.VP8BufSize mode := "video" if _, ok := tun.(*tunnel.DCTunnel); ok { - readBuf = common.DCBufSize + bridgeReadBuf = readBuf mode = "dc" } - activeBridge = tunnel.NewRelayBridge(tun, "creator", readBuf, log.Printf) + activeBridge = tunnel.NewRelayBridge(tun, "creator", bridgeReadBuf, log.Printf) fmt.Printf("\n TUNNEL CONNECTED (mode=%s)\n", mode) } sess.OnPeerRestart = func() { diff --git a/relay/wbstream/session.go b/relay/wbstream/session.go index 9d8ae7d..bf31586 100644 --- a/relay/wbstream/session.go +++ b/relay/wbstream/session.go @@ -42,6 +42,7 @@ type SessionConfig struct { VP8Batch int RoomID string AccessToken string + ReadBuf int } type Session struct { @@ -222,7 +223,11 @@ func (s *Session) maybeStartDCTunnel() { } readWrapped := newDataPacketWrapper(subRaw, livekit.DataPacketKindReliable) writeWrapped := newDataPacketWrapper(pubRaw, livekit.DataPacketKindReliable) - dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.cfg.Obfuscator, common.DCBufSize, s.cfg.LogFn) + readBuf := s.cfg.ReadBuf + if readBuf == 0 { + readBuf = common.DCBufSize + } + dctun := tunnel.NewChunkedDCTunnelFromRaw(readWrapped, writeWrapped, s.cfg.Obfuscator, readBuf, s.cfg.LogFn) if dctun == nil { return }