add upstream proxy support for creator
This commit is contained in:
1 parent
48dcb04c77
commit
000447b77c
21 files changed
+713
-84
No files matched your search
@@ -87,6 +87,13 @@
|
||||
<input type="number" id="vkGroupId" placeholder="123456789">
|
||||
<label for="vkUserId">User IDs (comma-separated)</label>
|
||||
<input type="text" id="vkUserId" placeholder="123456789, 987654321">
|
||||
<h2>Upstream proxy</h2>
|
||||
<label for="upstreamSocks">SOCKS5 host:port</label>
|
||||
<input type="text" id="upstreamSocks" placeholder="127.0.0.1:1080">
|
||||
<label for="upstreamUser">Username</label>
|
||||
<input type="text" id="upstreamUser" placeholder="optional">
|
||||
<label for="upstreamPass">Password</label>
|
||||
<input type="password" id="upstreamPass" placeholder="optional">
|
||||
<div class="popup-buttons">
|
||||
<button class="btn-cancel" id="btnSettingsCancel">Cancel</button>
|
||||
<button class="btn-save" id="btnSettingsSave">Save</button>
|
||||
|
||||
@@ -58,6 +58,7 @@ export enum IPC {
|
||||
CLOSE_TAB = 'close-tab',
|
||||
START_BOT = 'start-bot',
|
||||
STOP_BOT = 'stop-bot',
|
||||
SET_UPSTREAM_PROXY = 'set-upstream-proxy',
|
||||
EXPORT_COOKIES_ZIP = 'export-cookies-zip',
|
||||
RELAY_LOG = 'relay-log',
|
||||
CREATE_BOT_TAB = 'create-bot-tab',
|
||||
|
||||
@@ -4,7 +4,7 @@ import * as fs from 'fs/promises';
|
||||
import { TabManager } from './tab-manager';
|
||||
import { BotManager } from '../bot/bot-manager';
|
||||
import { IPC } from '../constants';
|
||||
import { TunnelMode, Platform, BotSettings, HeadlessStartArgs } from '../types';
|
||||
import { TunnelMode, Platform, BotSettings, HeadlessStartArgs, UpstreamProxy } from '../types';
|
||||
|
||||
export function registerIpcHandlers(tabManager: TabManager): void {
|
||||
ipcMain.handle(IPC.GET_HOOK_CODE, async (_e, tabId: string, url: string) => {
|
||||
@@ -86,6 +86,10 @@ export function registerIpcHandlers(tabManager: TabManager): void {
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
ipcMain.handle(IPC.SET_UPSTREAM_PROXY, (_e, proxy: UpstreamProxy) => {
|
||||
tabManager.setUpstreamProxy(proxy);
|
||||
});
|
||||
|
||||
ipcMain.handle(IPC.SEND_BOT_CALL_LINK, (_e, tabId: string, link: string) => {
|
||||
tabManager.sendBotCallLink(tabId, link);
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
CallStatus,
|
||||
HeadlessStartArgs,
|
||||
HeadlessMode,
|
||||
UpstreamProxy,
|
||||
} from '../types';
|
||||
import {
|
||||
INITIAL_PORT_BASE,
|
||||
@@ -51,6 +52,7 @@ export class TabManager {
|
||||
private headlessWBStreamPath: string;
|
||||
private headlessDionPath: string;
|
||||
private hooksDir: string;
|
||||
private upstreamProxy: UpstreamProxy = { socks: '', user: '', pass: '' };
|
||||
|
||||
constructor() {
|
||||
this.relayPath = resolveResourcePath(
|
||||
@@ -213,6 +215,21 @@ export class TabManager {
|
||||
this._botManager.sendMessage(tab.peerId, link);
|
||||
}
|
||||
|
||||
setUpstreamProxy(proxy: UpstreamProxy): void {
|
||||
this.upstreamProxy = {
|
||||
socks: (proxy?.socks || '').trim(),
|
||||
user: (proxy?.user || '').trim(),
|
||||
pass: (proxy?.pass || '').trim(),
|
||||
};
|
||||
}
|
||||
|
||||
private appendUpstreamArgs(args: string[]): void {
|
||||
if (!this.upstreamProxy.socks) return;
|
||||
args.push('--upstream-socks', this.upstreamProxy.socks);
|
||||
if (this.upstreamProxy.user) args.push('--upstream-user', this.upstreamProxy.user);
|
||||
if (this.upstreamProxy.pass) args.push('--upstream-pass', this.upstreamProxy.pass);
|
||||
}
|
||||
|
||||
startRelay(tabId: string, tab: TabState): void {
|
||||
this.killRelay(tabId, tab);
|
||||
const port = tab.tunnelMode === TunnelMode.PionVideo ? tab.pionPort : tab.dcPort;
|
||||
@@ -222,7 +239,9 @@ export class TabManager {
|
||||
? RelayMode.TelemostVideoCreator
|
||||
: RelayMode.VKVideoCreator;
|
||||
}
|
||||
const proc = spawn(this.relayPath, ['--mode', relayMode, '--ws-port', String(port)], {
|
||||
const relayArgs = ['--mode', relayMode, '--ws-port', String(port)];
|
||||
this.appendUpstreamArgs(relayArgs);
|
||||
const proc = spawn(this.relayPath, relayArgs, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
tab.relay = proc;
|
||||
@@ -351,6 +370,7 @@ export class TabManager {
|
||||
const flag = this.joinFlagFor(platform);
|
||||
if (flag) spawnArgs.push(flag, joinTarget);
|
||||
}
|
||||
this.appendUpstreamArgs(spawnArgs);
|
||||
const proc = spawn(config.binaryPath, spawnArgs, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
|
||||
@@ -23,6 +23,9 @@ import { IPC } from '../constants';
|
||||
stopBot() {
|
||||
return ipcRenderer.invoke(IPC.STOP_BOT);
|
||||
},
|
||||
setUpstreamProxy(proxy: any) {
|
||||
return ipcRenderer.invoke(IPC.SET_UPSTREAM_PROXY, proxy);
|
||||
},
|
||||
onCreateBotTab(cb: (data: any) => void) {
|
||||
ipcRenderer.on(IPC.CREATE_BOT_TAB, (_e, data) => cb(data));
|
||||
},
|
||||
|
||||
@@ -85,6 +85,10 @@ function bindSettingsEvents(): void {
|
||||
tm.botSettings.groupId = (document.getElementById('vkGroupId') as HTMLInputElement).value.trim();
|
||||
tm.botSettings.userId = (document.getElementById('vkUserId') as HTMLInputElement).value.trim();
|
||||
tm.saveBotSettings();
|
||||
tm.upstreamProxy.socks = (document.getElementById('upstreamSocks') as HTMLInputElement).value.trim();
|
||||
tm.upstreamProxy.user = (document.getElementById('upstreamUser') as HTMLInputElement).value.trim();
|
||||
tm.upstreamProxy.pass = (document.getElementById('upstreamPass') as HTMLInputElement).value.trim();
|
||||
tm.saveUpstreamProxy();
|
||||
closeSettings();
|
||||
});
|
||||
}
|
||||
@@ -154,6 +158,9 @@ function openSettings(): void {
|
||||
(document.getElementById('vkToken') as HTMLInputElement).value = tm.botSettings.token;
|
||||
(document.getElementById('vkGroupId') as HTMLInputElement).value = tm.botSettings.groupId;
|
||||
(document.getElementById('vkUserId') as HTMLInputElement).value = tm.botSettings.userId;
|
||||
(document.getElementById('upstreamSocks') as HTMLInputElement).value = tm.upstreamProxy.socks;
|
||||
(document.getElementById('upstreamUser') as HTMLInputElement).value = tm.upstreamProxy.user;
|
||||
(document.getElementById('upstreamPass') as HTMLInputElement).value = tm.upstreamProxy.pass;
|
||||
}
|
||||
|
||||
function closeSettings(): void {
|
||||
@@ -169,6 +176,8 @@ function init(): void {
|
||||
bindLogEvents();
|
||||
bindHeadlessEvents();
|
||||
|
||||
window.bridge.setUpstreamProxy(tm.upstreamProxy);
|
||||
|
||||
window.bridge.onRelayLog((tabId: string, msg: string) => {
|
||||
tm.appendRelayLog(tabId, msg);
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
RendererTab,
|
||||
BotTabData,
|
||||
BotSettings,
|
||||
UpstreamProxy,
|
||||
TunnelMode,
|
||||
Platform,
|
||||
Bridge,
|
||||
@@ -18,6 +19,7 @@ export class RendererTabManager {
|
||||
private nextId = 1;
|
||||
botRunning = false;
|
||||
botSettings: BotSettings;
|
||||
upstreamProxy: UpstreamProxy;
|
||||
private onRender: () => void;
|
||||
|
||||
constructor(onRender: () => void) {
|
||||
@@ -26,6 +28,10 @@ export class RendererTabManager {
|
||||
this.botSettings = saved
|
||||
? JSON.parse(saved)
|
||||
: { token: '', groupId: '', userId: '' };
|
||||
const savedProxy = localStorage.getItem('upstreamProxy');
|
||||
this.upstreamProxy = savedProxy
|
||||
? JSON.parse(savedProxy)
|
||||
: { socks: '', user: '', pass: '' };
|
||||
}
|
||||
|
||||
createTab(): string {
|
||||
@@ -236,6 +242,11 @@ export class RendererTabManager {
|
||||
localStorage.setItem('botSettings', JSON.stringify(this.botSettings));
|
||||
}
|
||||
|
||||
saveUpstreamProxy(): void {
|
||||
localStorage.setItem('upstreamProxy', JSON.stringify(this.upstreamProxy));
|
||||
window.bridge.setUpstreamProxy(this.upstreamProxy);
|
||||
}
|
||||
|
||||
toggleBot(): void {
|
||||
if (!this.botSettings.token || !this.botSettings.groupId) return;
|
||||
this.botRunning = !this.botRunning;
|
||||
|
||||
@@ -65,6 +65,12 @@ export interface BotSettings {
|
||||
userId: string;
|
||||
}
|
||||
|
||||
export interface UpstreamProxy {
|
||||
socks: string;
|
||||
user: string;
|
||||
pass: string;
|
||||
}
|
||||
|
||||
export interface TabConfig {
|
||||
mode: TunnelMode;
|
||||
peerId: number;
|
||||
@@ -144,6 +150,7 @@ export interface Bridge {
|
||||
closeTab(tabId: string): Promise<void>;
|
||||
startBot(settings: BotSettings): Promise<void>;
|
||||
stopBot(): Promise<void>;
|
||||
setUpstreamProxy(proxy: UpstreamProxy): Promise<void>;
|
||||
onCreateBotTab(cb: (data: BotTabData) => void): void;
|
||||
getCallCreatorCode(scriptFile: string): Promise<string>;
|
||||
onBotError(cb: (msg: string) => void): void;
|
||||
|
||||
@@ -96,8 +96,28 @@
|
||||
| `--max-dc-buf <bytes>` | да | - | - | Порог `BufferedAmountLowThreshold` DC, только с `--resources custom` |
|
||||
| `--mem-limit <bytes>` | да | да | да | Soft memory limit Go рантайма, только с `--resources custom` |
|
||||
| `--write-file <path>` | да | да | да | Файл, куда записывается активная ссылка на звонок |
|
||||
| `--upstream-socks <host:port>` | да | да | да | Гнать трафик joiner-а через локальный SOCKS5 прокси, например VPN-клиент |
|
||||
| `--upstream-user <user>` | да | да | да | Логин для upstream SOCKS5 |
|
||||
| `--upstream-pass <pass>` | да | да | да | Пароль для upstream SOCKS5 |
|
||||
| `--version` | да | да | да | Вывести версию и выйти |
|
||||
|
||||
### Выходной трафик через свой VPS
|
||||
|
||||
По умолчанию creator открывает соединения joiner-а напрямую со своего IP. Флаг `--upstream-socks` заставляет creator отправлять **только трафик joiner-а** в локальный SOCKS5 прокси - обычно его поднимает VPN-клиент (xray / sing-box / v2ray и т.п.) рядом с creator. Получается цепочка:
|
||||
|
||||
```
|
||||
joiner (цензура) -> creator (домашний ПК) -> VPN-клиент (тот же ПК) -> VPS -> интернет
|
||||
```
|
||||
|
||||
SOCKS5-инбаунд VPN-клиента должен поддерживать UDP ASSOCIATE (xray / sing-box умеют).
|
||||
|
||||
```sh
|
||||
./headless-telemost-creator \
|
||||
--cookies cookies-yandex.json \
|
||||
--tm-link https://telemost.yandex.ru/j/<id> \
|
||||
--upstream-socks 127.0.0.1:1080
|
||||
```
|
||||
|
||||
### Режимы ресурсов
|
||||
|
||||
| Режим | `read-buf` | `max-dc-buf` (VK) | `mem-limit` | Когда использовать |
|
||||
@@ -296,9 +316,14 @@ docker compose pull && docker compose up -d
|
||||
| `TM_COOKIES` | нет | `/data/cookies-yandex.json` если есть | `--tm-cookies` |
|
||||
| `WB_COOKIES` | нет | `/data/cookies-wbstream.json` если есть | `--wb-cookies` |
|
||||
| `DION_COOKIES` | нет | `/data/cookies-dion.json` если есть | `--dion-cookies` |
|
||||
| `UPSTREAM_SOCKS` | нет | - | `--upstream-socks` |
|
||||
| `UPSTREAM_USER` | нет | - | `--upstream-user` |
|
||||
| `UPSTREAM_PASS` | нет | - | `--upstream-pass` |
|
||||
|
||||
> Если WebRTC-туннель не доходит через сетевой бридж Docker (UDP может отбрасываться), добавьте в `docker-compose.yml` строку `network_mode: host` под сервисом `bot`.
|
||||
|
||||
> `UPSTREAM_SOCKS` гонит трафик joiner-а через локальный SOCKS5 (VPN-клиент), см. [Выходной трафик через свой VPS](#выходной-трафик-через-свой-vps). Внутри контейнера `127.0.0.1` - это сам контейнер, а не хост: чтобы дотянуться до VPN-клиента на хосте, используйте `host.docker.internal:<порт>` и раскомментируйте `extra_hosts` в `docker-compose.yml`, либо поднимите VPN-клиент отдельным сервисом и укажите его имя.
|
||||
|
||||
### Команды
|
||||
|
||||
- `/vk` - запустить `headless-vk-creator`
|
||||
|
||||
@@ -22,6 +22,9 @@ func main() {
|
||||
displayName := flag.String("name", "Headless", "display name in the room")
|
||||
resources := flag.String("resources", "default", "resource mode: moderate, default, unlimited")
|
||||
writeFile := flag.String("write-file", "", "path to file where active slug is appended")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
|
||||
flag.Parse()
|
||||
|
||||
var memLimit int64
|
||||
@@ -111,6 +114,7 @@ func main() {
|
||||
activeBridge.Reset()
|
||||
}
|
||||
activeBridge = tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
activeBridge.SetUpstreamSocks(*upstreamSocks, *upstreamUser, *upstreamPass)
|
||||
activeBridge.MarkReady()
|
||||
fmt.Println("")
|
||||
fmt.Println(" TUNNEL CONNECTED")
|
||||
@@ -165,4 +169,3 @@ func main() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,3 +9,12 @@ VK_USER_IDS=
|
||||
|
||||
# Resource mode passed to spawned creators: default | moderate | unlimited.
|
||||
RESOURCES=default
|
||||
|
||||
# Optional: route the joiner's egress through a local SOCKS5 proxy (a VPN client),
|
||||
# so traffic exits via your VPS instead of this machine's IP. Forwarded to every
|
||||
# spawned creator. Inside the container 127.0.0.1 is the CONTAINER, not the host -
|
||||
# point at host.docker.internal (uncomment extra_hosts in docker-compose.yml) or a
|
||||
# sidecar service name. The SOCKS5 inbound must support UDP ASSOCIATE.
|
||||
UPSTREAM_SOCKS=
|
||||
UPSTREAM_USER=
|
||||
UPSTREAM_PASS=
|
||||
@@ -5,6 +5,10 @@ services:
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
# Uncomment to reach a SOCKS5 VPN client running on the host via
|
||||
# UPSTREAM_SOCKS=host.docker.internal:<port>. On Linux this maps to the host.
|
||||
# extra_hosts:
|
||||
# - "host.docker.internal:host-gateway"
|
||||
volumes:
|
||||
# Cookies for spawned creators. Create empty `[]` files for platforms you
|
||||
# don't use, or remove the corresponding line.
|
||||
|
||||
@@ -35,5 +35,8 @@ set -- \
|
||||
[ -n "$TM_COOKIES" ] && set -- "$@" --tm-cookies "$TM_COOKIES"
|
||||
[ -n "$WB_COOKIES" ] && set -- "$@" --wb-cookies "$WB_COOKIES"
|
||||
[ -n "$DION_COOKIES" ] && set -- "$@" --dion-cookies "$DION_COOKIES"
|
||||
[ -n "${UPSTREAM_SOCKS:-}" ] && set -- "$@" --upstream-socks "$UPSTREAM_SOCKS"
|
||||
[ -n "${UPSTREAM_USER:-}" ] && set -- "$@" --upstream-user "$UPSTREAM_USER"
|
||||
[ -n "${UPSTREAM_PASS:-}" ] && set -- "$@" --upstream-pass "$UPSTREAM_PASS"
|
||||
|
||||
exec /usr/local/bin/headless-vk-bot "$@"
|
||||
+37
-28
@@ -30,7 +30,6 @@ const (
|
||||
|
||||
var clientInstanceID = uuid.New().String()
|
||||
|
||||
|
||||
type ConnInfo struct {
|
||||
ConferenceURI string
|
||||
RoomID string
|
||||
@@ -43,24 +42,27 @@ type ConnInfo struct {
|
||||
}
|
||||
|
||||
type Bridge struct {
|
||||
mu sync.Mutex
|
||||
ws *websocket.Conn
|
||||
relay *SFURelay
|
||||
connInfo *ConnInfo
|
||||
config TMConfig
|
||||
cookieStr string
|
||||
pubSeq int
|
||||
subSeq int
|
||||
peers map[string]string
|
||||
readBuf int
|
||||
activeBridge *tunnel.RelayBridge
|
||||
selfName string
|
||||
mu sync.Mutex
|
||||
ws *websocket.Conn
|
||||
relay *SFURelay
|
||||
connInfo *ConnInfo
|
||||
config TMConfig
|
||||
cookieStr string
|
||||
pubSeq int
|
||||
subSeq int
|
||||
peers map[string]string
|
||||
readBuf int
|
||||
activeBridge *tunnel.RelayBridge
|
||||
selfName string
|
||||
upstreamSocks string
|
||||
upstreamUser string
|
||||
upstreamPass string
|
||||
|
||||
setSlotsKey int
|
||||
initBundleSent bool
|
||||
pendingKicks map[string]chan struct{}
|
||||
boundPeers map[string]bool
|
||||
unboundPeers map[string]bool
|
||||
setSlotsKey int
|
||||
initBundleSent bool
|
||||
pendingKicks map[string]chan struct{}
|
||||
boundPeers map[string]bool
|
||||
unboundPeers map[string]bool
|
||||
}
|
||||
|
||||
func tmRequest(method, path string, body interface{}, cookieStr string, cfg TMConfig) ([]byte, int, error) {
|
||||
@@ -197,13 +199,13 @@ func (b *Bridge) sendHello() {
|
||||
"hello": map[string]interface{}{
|
||||
"participantMeta": map[string]interface{}{"name": "Headless", "role": "SPEAKER", "description": "", "sendAudio": false, "sendVideo": true},
|
||||
"participantAttributes": map[string]interface{}{"name": "Headless", "role": "SPEAKER", "description": ""},
|
||||
"sendAudio": false, "sendVideo": true, "sendSharing": false,
|
||||
"sendAudio": false, "sendVideo": true, "sendSharing": false,
|
||||
"participantId": b.connInfo.PeerID, "roomId": b.connInfo.RoomID,
|
||||
"serviceName": b.connInfo.ServiceName, "credentials": b.connInfo.Credentials,
|
||||
"capabilitiesOffer": tmapi.CapabilitiesOffer,
|
||||
"sdkInfo": map[string]interface{}{"implementation": "browser", "version": b.config.SDKVersion, "userAgent": common.UserAgent, "hwConcurrency": 8},
|
||||
"capabilitiesOffer": tmapi.CapabilitiesOffer,
|
||||
"sdkInfo": map[string]interface{}{"implementation": "browser", "version": b.config.SDKVersion, "userAgent": common.UserAgent, "hwConcurrency": 8},
|
||||
"sdkInitializationId": uuid.New().String(),
|
||||
"disablePublisher": false, "disableSubscriber": false, "disableSubscriberAudio": false,
|
||||
"disablePublisher": false, "disableSubscriber": false, "disableSubscriberAudio": false,
|
||||
},
|
||||
})
|
||||
log.Println("[tm-ws] -> hello")
|
||||
@@ -246,7 +248,7 @@ func (b *Bridge) sendICE(cand *webrtc.ICECandidate, target string, pcSeq int) {
|
||||
"webrtcIceCandidate": map[string]interface{}{
|
||||
"candidate": c.Candidate, "sdpMid": mid,
|
||||
"usernameFragment": extractUfrag(c.Candidate),
|
||||
"sdpMlineIndex": idx, "target": target, "pcSeq": pcSeq,
|
||||
"sdpMlineIndex": idx, "target": target, "pcSeq": pcSeq,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -710,6 +712,7 @@ func (b *Bridge) initRelay() {
|
||||
b.activeBridge.Reset()
|
||||
}
|
||||
b.activeBridge = tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
b.activeBridge.SetUpstreamSocks(b.upstreamSocks, b.upstreamUser, b.upstreamPass)
|
||||
fmt.Print("\n TUNNEL CONNECTED\n")
|
||||
}
|
||||
relay.OnPeerRestart = func() {
|
||||
@@ -885,6 +888,9 @@ func main() {
|
||||
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")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
|
||||
flag.Parse()
|
||||
|
||||
var readBuf int
|
||||
@@ -960,11 +966,14 @@ func main() {
|
||||
}
|
||||
|
||||
bridge := &Bridge{
|
||||
connInfo: connInfo,
|
||||
config: cfg,
|
||||
cookieStr: cookieStr,
|
||||
peers: make(map[string]string),
|
||||
readBuf: readBuf,
|
||||
connInfo: connInfo,
|
||||
config: cfg,
|
||||
cookieStr: cookieStr,
|
||||
peers: make(map[string]string),
|
||||
readBuf: readBuf,
|
||||
upstreamSocks: *upstreamSocks,
|
||||
upstreamUser: *upstreamUser,
|
||||
upstreamPass: *upstreamPass,
|
||||
}
|
||||
bridge.run()
|
||||
}
|
||||
Executable
+149
@@ -0,0 +1,149 @@
|
||||
#!/bin/sh
|
||||
# End-to-end test for creator --upstream-socks, on Telemost.
|
||||
#
|
||||
# A telemost creator JOINS an existing conference (your call link, never created
|
||||
# here) and a telemost joiner joins the same conference to form the tunnel. We run
|
||||
# the pair twice - once with direct egress, once with -upstream-socks - and assert
|
||||
# the joiner's public egress IP CHANGES. A changed IP proves the joiner's traffic
|
||||
# left through the upstream SOCKS5 (your VPN client -> VPS) instead of this host.
|
||||
#
|
||||
# Needs: a real upstream SOCKS5 proxy whose exit IP differs from this machine
|
||||
# (an actual VPN client pointing at a VPS), plus Yandex cookies and a live call link.
|
||||
#
|
||||
# Usage:
|
||||
# UPSTREAM_SOCKS=127.0.0.1:1080 ./test-upstream-socks.sh <cookies-yandex.json> <tm-link>
|
||||
# UPSTREAM_SOCKS=127.0.0.1:1080 UPSTREAM_USER=u UPSTREAM_PASS=p \
|
||||
# ./test-upstream-socks.sh <cookies-yandex.json> https://telemost.yandex.ru/j/<id>
|
||||
|
||||
set -u
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||||
CREATOR="$ROOT/headless/telemost/headless-telemost-creator"
|
||||
JOINER="$ROOT/headless/telemost-joiner/headless-telemost-joiner"
|
||||
SOCKS_PORT=11080
|
||||
IP_URL="https://api.ipify.org"
|
||||
SETTLE_TIMEOUT=45
|
||||
PROBE_TIMEOUT=15
|
||||
|
||||
if [ $# -lt 2 ]; then
|
||||
echo "Usage: UPSTREAM_SOCKS=host:port $0 <cookies-yandex.json> <tm-link>" >&2
|
||||
exit 2
|
||||
fi
|
||||
COOKIES="$1"
|
||||
TM_LINK="$2"
|
||||
|
||||
if [ -z "${UPSTREAM_SOCKS:-}" ]; then
|
||||
echo "FAIL: set UPSTREAM_SOCKS=host:port (a real SOCKS5 proxy / VPN client whose exit IP differs from this host)" >&2
|
||||
exit 2
|
||||
fi
|
||||
[ -x "$CREATOR" ] || { echo "FAIL: missing $CREATOR (run ./build-headless.sh first)" >&2; exit 2; }
|
||||
[ -x "$JOINER" ] || { echo "FAIL: missing $JOINER (run ./build-headless.sh first)" >&2; exit 2; }
|
||||
[ -f "$COOKIES" ] || { echo "FAIL: cookies not found at: $COOKIES" >&2; exit 2; }
|
||||
echo "cookies=$COOKIES tm-link=$TM_LINK upstream=$UPSTREAM_SOCKS"
|
||||
|
||||
CREATOR_PID=""
|
||||
JOINER_PID=""
|
||||
kill_pair() {
|
||||
[ -n "$JOINER_PID" ] && kill "$JOINER_PID" 2>/dev/null
|
||||
[ -n "$CREATOR_PID" ] && kill "$CREATOR_PID" 2>/dev/null
|
||||
wait 2>/dev/null
|
||||
JOINER_PID=""
|
||||
CREATOR_PID=""
|
||||
}
|
||||
trap kill_pair EXIT INT TERM
|
||||
|
||||
# run_chain <label> [extra creator args...] -> prints the joiner's egress IP on stdout
|
||||
run_chain() {
|
||||
label="$1"
|
||||
shift
|
||||
clog=$(mktemp -t up-c.XXXXXX.log)
|
||||
jlog=$(mktemp -t up-j.XXXXXX.log)
|
||||
|
||||
"$CREATOR" -cookies "$COOKIES" -tm-link "$TM_LINK" "$@" >"$clog" 2>&1 &
|
||||
CREATOR_PID=$!
|
||||
|
||||
w=0
|
||||
while [ "$w" -lt "$SETTLE_TIMEOUT" ]; do
|
||||
grep -q "media_server=" "$clog" && break
|
||||
if ! kill -0 "$CREATOR_PID" 2>/dev/null; then
|
||||
echo "FAIL[$label]: creator died before joining the conference" >&2
|
||||
tail -20 "$clog" >&2
|
||||
kill_pair
|
||||
return 1
|
||||
fi
|
||||
sleep 1
|
||||
w=$((w + 1))
|
||||
done
|
||||
if ! grep -q "media_server=" "$clog"; then
|
||||
echo "FAIL[$label]: creator did not join the conference in ${SETTLE_TIMEOUT}s" >&2
|
||||
tail -20 "$clog" >&2
|
||||
kill_pair
|
||||
return 1
|
||||
fi
|
||||
sleep 3
|
||||
|
||||
"$JOINER" -tm-link "$TM_LINK" -socks-port "$SOCKS_PORT" >"$jlog" 2>&1 &
|
||||
JOINER_PID=$!
|
||||
|
||||
w=0
|
||||
while [ "$w" -lt "$SETTLE_TIMEOUT" ]; do
|
||||
grep -q "TUNNEL CONNECTED" "$jlog" && break
|
||||
if ! kill -0 "$JOINER_PID" 2>/dev/null; then
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
w=$((w + 1))
|
||||
done
|
||||
if ! grep -q "TUNNEL CONNECTED" "$jlog"; then
|
||||
echo "FAIL[$label]: joiner never reached TUNNEL CONNECTED in ${SETTLE_TIMEOUT}s" >&2
|
||||
tail -20 "$jlog" >&2
|
||||
kill_pair
|
||||
return 1
|
||||
fi
|
||||
|
||||
w=0
|
||||
while [ "$w" -lt 10 ]; do
|
||||
nc -z 127.0.0.1 "$SOCKS_PORT" 2>/dev/null && break
|
||||
sleep 1
|
||||
w=$((w + 1))
|
||||
done
|
||||
|
||||
ip=$(curl --socks5-hostname "127.0.0.1:$SOCKS_PORT" -m "$PROBE_TIMEOUT" -s "$IP_URL")
|
||||
kill_pair
|
||||
echo "$ip"
|
||||
}
|
||||
|
||||
echo "=== baseline: direct egress ==="
|
||||
DIRECT_IP=$(run_chain direct) || exit 1
|
||||
echo "direct_ip=$DIRECT_IP"
|
||||
|
||||
# Let the fixed SOCKS port free up before the second pair.
|
||||
sleep 2
|
||||
|
||||
echo "=== upstream: -upstream-socks $UPSTREAM_SOCKS ==="
|
||||
set -- -upstream-socks "$UPSTREAM_SOCKS"
|
||||
[ -n "${UPSTREAM_USER:-}" ] && set -- "$@" -upstream-user "$UPSTREAM_USER"
|
||||
[ -n "${UPSTREAM_PASS:-}" ] && set -- "$@" -upstream-pass "$UPSTREAM_PASS"
|
||||
UPSTREAM_IP=$(run_chain upstream "$@") || exit 1
|
||||
echo "upstream_ip=$UPSTREAM_IP"
|
||||
|
||||
case "$DIRECT_IP" in
|
||||
*.*) ;;
|
||||
*)
|
||||
echo "FAIL: no direct egress IP (baseline chain broken)" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
case "$UPSTREAM_IP" in
|
||||
*.*) ;;
|
||||
*)
|
||||
echo "FAIL: no egress IP via upstream - is $UPSTREAM_SOCKS reachable and does its SOCKS5 inbound work?" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ "$DIRECT_IP" = "$UPSTREAM_IP" ]; then
|
||||
echo "FAIL: egress IP unchanged ($UPSTREAM_IP) - joiner traffic did NOT go through the upstream" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "PASS: egress moved from $DIRECT_IP (this host) to $UPSTREAM_IP (via $UPSTREAM_SOCKS)"
|
||||
+31
-12
@@ -70,6 +70,10 @@ type bot struct {
|
||||
sessionsDir string
|
||||
resources string
|
||||
|
||||
upstreamSocks string
|
||||
upstreamUser string
|
||||
upstreamPass string
|
||||
|
||||
server, key, ts string
|
||||
|
||||
mu sync.Mutex
|
||||
@@ -357,6 +361,15 @@ func (b *bot) spawn(platform, joinTarget string) (*session, error) {
|
||||
if joinTarget != "" {
|
||||
args = append(args, joinFlag, joinTarget)
|
||||
}
|
||||
if b.upstreamSocks != "" {
|
||||
args = append(args, "--upstream-socks", b.upstreamSocks)
|
||||
if b.upstreamUser != "" {
|
||||
args = append(args, "--upstream-user", b.upstreamUser)
|
||||
}
|
||||
if b.upstreamPass != "" {
|
||||
args = append(args, "--upstream-pass", b.upstreamPass)
|
||||
}
|
||||
}
|
||||
cmd := exec.Command(bin, args...)
|
||||
if logF != nil {
|
||||
cmd.Stdout = logF
|
||||
@@ -479,6 +492,9 @@ func main() {
|
||||
dionCookies := flag.String("dion-cookies", "", "path to DION cookies JSON")
|
||||
sessionsDir := flag.String("sessions-dir", "", "directory for per-session creator logs (optional)")
|
||||
resources := flag.String("resources", "default", "resource mode forwarded to spawned creators: default, moderate, unlimited")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "forward to spawned creators: route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username forwarded to spawned creators")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password forwarded to spawned creators")
|
||||
flag.Parse()
|
||||
|
||||
switch *resources {
|
||||
@@ -500,18 +516,21 @@ func main() {
|
||||
}
|
||||
|
||||
b := &bot{
|
||||
token: *token,
|
||||
groupID: *groupID,
|
||||
userIDs: allowedUsers,
|
||||
binsDir: *binsDir,
|
||||
vkCookies: *vkCookies,
|
||||
tmCookies: *tmCookies,
|
||||
wbCookies: *wbCookies,
|
||||
dionCookies: *dionCookies,
|
||||
sessionsDir: *sessionsDir,
|
||||
resources: *resources,
|
||||
sessions: map[string]*session{},
|
||||
awaitingJoin: map[int64]bool{},
|
||||
token: *token,
|
||||
groupID: *groupID,
|
||||
userIDs: allowedUsers,
|
||||
binsDir: *binsDir,
|
||||
vkCookies: *vkCookies,
|
||||
tmCookies: *tmCookies,
|
||||
wbCookies: *wbCookies,
|
||||
dionCookies: *dionCookies,
|
||||
sessionsDir: *sessionsDir,
|
||||
resources: *resources,
|
||||
upstreamSocks: *upstreamSocks,
|
||||
upstreamUser: *upstreamUser,
|
||||
upstreamPass: *upstreamPass,
|
||||
sessions: map[string]*session{},
|
||||
awaitingJoin: map[int64]bool{},
|
||||
}
|
||||
|
||||
sig := make(chan os.Signal, 1)
|
||||
|
||||
+5
-1
@@ -581,6 +581,9 @@ func main() {
|
||||
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")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
|
||||
flag.Parse()
|
||||
|
||||
var readBuf int
|
||||
@@ -678,7 +681,8 @@ func main() {
|
||||
ur.maxDCBuf = maxDCBuf
|
||||
ur.SetObfuscator(obf)
|
||||
ur.OnConnected = func(tun *tunnel.VP8DataTunnel) {
|
||||
tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
rb := tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
rb.SetUpstreamSocks(*upstreamSocks, *upstreamUser, *upstreamPass)
|
||||
}
|
||||
return ur
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ func main() {
|
||||
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")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
|
||||
flag.Parse()
|
||||
|
||||
var readBuf int
|
||||
@@ -113,6 +116,7 @@ func main() {
|
||||
mode = "dc"
|
||||
}
|
||||
activeBridge = tunnel.NewRelayBridge(tun, "creator", bridgeReadBuf, log.Printf)
|
||||
activeBridge.SetUpstreamSocks(*upstreamSocks, *upstreamUser, *upstreamPass)
|
||||
activeBridge.SetOnPeerConfig(func(fps, batch, trackCount int) {
|
||||
sess.AdaptTrackCount(trackCount)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,273 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Socks5Upstream struct {
|
||||
Addr string
|
||||
User string
|
||||
Pass string
|
||||
}
|
||||
|
||||
func NewSocks5Upstream(addr, user, pass string) *Socks5Upstream {
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
return &Socks5Upstream{Addr: addr, User: user, Pass: pass}
|
||||
}
|
||||
|
||||
func (u *Socks5Upstream) greet(conn net.Conn) error {
|
||||
method := byte(0x00)
|
||||
if u.User != "" {
|
||||
method = 0x02
|
||||
}
|
||||
if _, err := conn.Write([]byte{0x05, 0x01, method}); err != nil {
|
||||
return err
|
||||
}
|
||||
resp := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, resp); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp[0] != 0x05 {
|
||||
return errors.New("socks5: bad version in method reply")
|
||||
}
|
||||
switch resp[1] {
|
||||
case 0x00:
|
||||
return nil
|
||||
case 0x02:
|
||||
return u.authUserPass(conn)
|
||||
default:
|
||||
return fmt.Errorf("socks5: server rejected offered auth methods (0x%02x)", resp[1])
|
||||
}
|
||||
}
|
||||
|
||||
func (u *Socks5Upstream) authUserPass(conn net.Conn) error {
|
||||
if len(u.User) > 255 || len(u.Pass) > 255 {
|
||||
return errors.New("socks5: username or password too long")
|
||||
}
|
||||
req := []byte{0x01, byte(len(u.User))}
|
||||
req = append(req, u.User...)
|
||||
req = append(req, byte(len(u.Pass)))
|
||||
req = append(req, u.Pass...)
|
||||
if _, err := conn.Write(req); err != nil {
|
||||
return err
|
||||
}
|
||||
resp := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, resp); err != nil {
|
||||
return err
|
||||
}
|
||||
if resp[1] != 0x00 {
|
||||
return errors.New("socks5: username/password auth rejected")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func encodeSocksAddr(hostPort string) ([]byte, error) {
|
||||
host, portStr, err := net.SplitHostPort(hostPort)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("socks5: bad port %q: %w", portStr, err)
|
||||
}
|
||||
var out []byte
|
||||
if ip := net.ParseIP(host); ip != nil {
|
||||
if v4 := ip.To4(); v4 != nil {
|
||||
out = append(out, 0x01)
|
||||
out = append(out, v4...)
|
||||
} else {
|
||||
out = append(out, 0x04)
|
||||
out = append(out, ip.To16()...)
|
||||
}
|
||||
} else {
|
||||
if len(host) > 255 {
|
||||
return nil, errors.New("socks5: hostname too long")
|
||||
}
|
||||
out = append(out, 0x03, byte(len(host)))
|
||||
out = append(out, host...)
|
||||
}
|
||||
out = append(out, byte(port>>8), byte(port))
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func readSocksReply(conn net.Conn) (string, int, error) {
|
||||
head := make([]byte, 4)
|
||||
if _, err := io.ReadFull(conn, head); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
if head[0] != 0x05 {
|
||||
return "", 0, errors.New("socks5: bad version in reply")
|
||||
}
|
||||
if head[1] != 0x00 {
|
||||
return "", 0, fmt.Errorf("socks5: request rejected (0x%02x)", head[1])
|
||||
}
|
||||
var host string
|
||||
switch head[3] {
|
||||
case 0x01:
|
||||
b := make([]byte, net.IPv4len)
|
||||
if _, err := io.ReadFull(conn, b); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
host = net.IP(b).String()
|
||||
case 0x04:
|
||||
b := make([]byte, net.IPv6len)
|
||||
if _, err := io.ReadFull(conn, b); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
host = net.IP(b).String()
|
||||
case 0x03:
|
||||
l := make([]byte, 1)
|
||||
if _, err := io.ReadFull(conn, l); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
b := make([]byte, int(l[0]))
|
||||
if _, err := io.ReadFull(conn, b); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
host = string(b)
|
||||
default:
|
||||
return "", 0, errors.New("socks5: bad address type in reply")
|
||||
}
|
||||
portBytes := make([]byte, 2)
|
||||
if _, err := io.ReadFull(conn, portBytes); err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
return host, int(binary.BigEndian.Uint16(portBytes)), nil
|
||||
}
|
||||
|
||||
func (u *Socks5Upstream) DialTCP(dst string, timeout time.Duration) (net.Conn, error) {
|
||||
addr, err := encodeSocksAddr(dst)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := net.DialTimeout("tcp", u.Addr, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn.SetDeadline(time.Now().Add(timeout))
|
||||
if err := u.greet(conn); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
req := append([]byte{0x05, 0x01, 0x00}, addr...)
|
||||
if _, err := conn.Write(req); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
if _, _, err := readSocksReply(conn); err != nil {
|
||||
conn.Close()
|
||||
return nil, err
|
||||
}
|
||||
conn.SetDeadline(time.Time{})
|
||||
return conn, nil
|
||||
}
|
||||
|
||||
type Socks5UDPSession struct {
|
||||
ctrl net.Conn
|
||||
relay *net.UDPConn
|
||||
}
|
||||
|
||||
func (u *Socks5Upstream) UDPAssociate(timeout time.Duration) (*Socks5UDPSession, error) {
|
||||
ctrl, err := net.DialTimeout("tcp", u.Addr, timeout)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctrl.SetDeadline(time.Now().Add(timeout))
|
||||
if err := u.greet(ctrl); err != nil {
|
||||
ctrl.Close()
|
||||
return nil, err
|
||||
}
|
||||
if _, err := ctrl.Write([]byte{0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0, 0, 0}); err != nil {
|
||||
ctrl.Close()
|
||||
return nil, err
|
||||
}
|
||||
bndHost, bndPort, err := readSocksReply(ctrl)
|
||||
if err != nil {
|
||||
ctrl.Close()
|
||||
return nil, err
|
||||
}
|
||||
ctrl.SetDeadline(time.Time{})
|
||||
target, err := u.relayTarget(bndHost, bndPort)
|
||||
if err != nil {
|
||||
ctrl.Close()
|
||||
return nil, err
|
||||
}
|
||||
relay, err := net.DialUDP("udp", nil, target)
|
||||
if err != nil {
|
||||
ctrl.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &Socks5UDPSession{ctrl: ctrl, relay: relay}, nil
|
||||
}
|
||||
|
||||
func (u *Socks5Upstream) relayTarget(bndHost string, bndPort int) (*net.UDPAddr, error) {
|
||||
host := bndHost
|
||||
if host == "" || host == "0.0.0.0" || host == "::" {
|
||||
h, _, err := net.SplitHostPort(u.Addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
host = h
|
||||
}
|
||||
return net.ResolveUDPAddr("udp", net.JoinHostPort(host, strconv.Itoa(bndPort)))
|
||||
}
|
||||
|
||||
func (s *Socks5UDPSession) WriteTo(data []byte, dst string) error {
|
||||
addr, err := encodeSocksAddr(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pkt := make([]byte, 0, 3+len(addr)+len(data))
|
||||
pkt = append(pkt, 0x00, 0x00, 0x00)
|
||||
pkt = append(pkt, addr...)
|
||||
pkt = append(pkt, data...)
|
||||
_, err = s.relay.Write(pkt)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *Socks5UDPSession) Read(buf []byte) (int, error) {
|
||||
n, err := s.relay.Read(buf)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if n < 4 {
|
||||
return 0, errors.New("socks5: short udp reply")
|
||||
}
|
||||
var header int
|
||||
switch buf[3] {
|
||||
case 0x01:
|
||||
header = 4 + net.IPv4len + 2
|
||||
case 0x04:
|
||||
header = 4 + net.IPv6len + 2
|
||||
case 0x03:
|
||||
if n < 5 {
|
||||
return 0, errors.New("socks5: short udp reply")
|
||||
}
|
||||
header = 4 + 1 + int(buf[4]) + 2
|
||||
default:
|
||||
return 0, errors.New("socks5: bad address type in udp reply")
|
||||
}
|
||||
if n < header {
|
||||
return 0, errors.New("socks5: short udp reply")
|
||||
}
|
||||
payload := n - header
|
||||
copy(buf, buf[header:n])
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func (s *Socks5UDPSession) SetReadDeadline(t time.Time) error {
|
||||
return s.relay.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (s *Socks5UDPSession) Close() error {
|
||||
s.relay.Close()
|
||||
return s.ctrl.Close()
|
||||
}
|
||||
+6
-2
@@ -8,8 +8,8 @@ import (
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/androidbind"
|
||||
"whitelist-bypass/relay/common"
|
||||
"whitelist-bypass/relay/pion"
|
||||
"whitelist-bypass/relay/pion/android"
|
||||
"whitelist-bypass/relay/tunnel"
|
||||
@@ -28,6 +28,9 @@ func main() {
|
||||
socksPort := flag.Int("socks-port", 1080, "SOCKS5 proxy port (joiner mode only)")
|
||||
socksUser := flag.String("socks-user", "", "SOCKS5 proxy username")
|
||||
socksPass := flag.String("socks-pass", "", "SOCKS5 proxy password")
|
||||
upstreamSocks := flag.String("upstream-socks", "", "creator mode: route tunneled egress through this SOCKS5 proxy (host:port), e.g. a local VPN client")
|
||||
upstreamUser := flag.String("upstream-user", "", "upstream SOCKS5 username")
|
||||
upstreamPass := flag.String("upstream-pass", "", "upstream SOCKS5 password")
|
||||
flag.String("local-ip", "", "local IP address (unused, passed via hook)")
|
||||
flag.Parse()
|
||||
|
||||
@@ -61,7 +64,8 @@ func main() {
|
||||
}
|
||||
|
||||
creatorCallback := func(tun tunnel.DataTunnel) {
|
||||
tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
rb := tunnel.NewRelayBridge(tun, "creator", common.VP8BufSize, log.Printf)
|
||||
rb.SetUpstreamSocks(*upstreamSocks, *upstreamUser, *upstreamPass)
|
||||
}
|
||||
|
||||
newPersistentJoinerBridge := func(onConfigAck func()) func(tunnel.DataTunnel) {
|
||||
|
||||
@@ -17,6 +17,41 @@ import (
|
||||
|
||||
const verboseUDPLogging = false
|
||||
|
||||
type creatorUDP struct {
|
||||
direct *net.UDPConn
|
||||
socks *common.Socks5UDPSession
|
||||
}
|
||||
|
||||
func (c *creatorUDP) writePacket(data []byte, dst string) error {
|
||||
if c.socks != nil {
|
||||
return c.socks.WriteTo(data, dst)
|
||||
}
|
||||
c.direct.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
_, err := c.direct.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *creatorUDP) read(buf []byte) (int, error) {
|
||||
if c.socks != nil {
|
||||
return c.socks.Read(buf)
|
||||
}
|
||||
return c.direct.Read(buf)
|
||||
}
|
||||
|
||||
func (c *creatorUDP) setReadDeadline(t time.Time) error {
|
||||
if c.socks != nil {
|
||||
return c.socks.SetReadDeadline(t)
|
||||
}
|
||||
return c.direct.SetReadDeadline(t)
|
||||
}
|
||||
|
||||
func (c *creatorUDP) close() error {
|
||||
if c.socks != nil {
|
||||
return c.socks.Close()
|
||||
}
|
||||
return c.direct.Close()
|
||||
}
|
||||
|
||||
type udpClient struct {
|
||||
udpConn *net.UDPConn
|
||||
clientAddr *net.UDPAddr
|
||||
@@ -39,6 +74,7 @@ type RelayBridge struct {
|
||||
once sync.Once
|
||||
socksUser string
|
||||
socksPass string
|
||||
upstream *common.Socks5Upstream
|
||||
|
||||
persistentListener atomic.Bool
|
||||
listenerMu sync.Mutex
|
||||
@@ -88,6 +124,10 @@ func (rb *RelayBridge) SetPersistentListener(persistent bool) {
|
||||
rb.persistentListener.Store(persistent)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) SetUpstreamSocks(addr, user, pass string) {
|
||||
rb.upstream = common.NewSocks5Upstream(addr, user, pass)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) SwapTunnel(newTunnel DataTunnel) {
|
||||
rb.tunnelMu.Lock()
|
||||
rb.tunnel = newTunnel
|
||||
@@ -130,8 +170,8 @@ func (rb *RelayBridge) closeAll() {
|
||||
rb.udpClients.Range(func(key, value any) bool {
|
||||
udpCount++
|
||||
switch v := value.(type) {
|
||||
case *net.UDPConn:
|
||||
v.Close()
|
||||
case *creatorUDP:
|
||||
v.close()
|
||||
case *udpClient:
|
||||
v.udpConn.Close()
|
||||
}
|
||||
@@ -313,8 +353,8 @@ func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload
|
||||
if uval, ok := rb.udpClients.LoadAndDelete(connID); ok {
|
||||
found = true
|
||||
switch v := uval.(type) {
|
||||
case *net.UDPConn:
|
||||
v.Close()
|
||||
case *creatorUDP:
|
||||
v.close()
|
||||
case *udpClient:
|
||||
v.udpConn.Close()
|
||||
rb.udpSessions.Delete(v.mapKey)
|
||||
@@ -340,46 +380,41 @@ func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
addr := string(payload[1 : 1+addrLen])
|
||||
data := payload[1+addrLen:]
|
||||
|
||||
var conn *net.UDPConn
|
||||
var egress *creatorUDP
|
||||
if val, ok := rb.udpClients.Load(connID); ok {
|
||||
existing, ok := val.(*net.UDPConn)
|
||||
existing, ok := val.(*creatorUDP)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
conn = existing
|
||||
egress = existing
|
||||
} else {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
created, err := rb.dialCreatorUDP(addr)
|
||||
if err != nil {
|
||||
rb.logFn("relay[creator]: UDP %d resolve %s failed: %v", connID, addr, err)
|
||||
rb.logFn("relay[creator]: UDP %d open %s failed: %v", connID, common.MaskAddr(addr), err)
|
||||
return
|
||||
}
|
||||
dialed, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
rb.logFn("relay[creator]: UDP %d dial %s failed: %v", connID, udpAddr.String(), err)
|
||||
return
|
||||
}
|
||||
if actual, loaded := rb.udpClients.LoadOrStore(connID, dialed); loaded {
|
||||
dialed.Close()
|
||||
existing, ok := actual.(*net.UDPConn)
|
||||
if actual, loaded := rb.udpClients.LoadOrStore(connID, created); loaded {
|
||||
created.close()
|
||||
existing, ok := actual.(*creatorUDP)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
conn = existing
|
||||
egress = existing
|
||||
} else {
|
||||
conn = dialed
|
||||
egress = created
|
||||
if verboseUDPLogging {
|
||||
rb.logFn("relay[creator]: UDP %d session opened -> %s payload=%dB", connID, udpAddr.String(), len(data))
|
||||
rb.logFn("relay[creator]: UDP %d session opened -> %s payload=%dB", connID, addr, len(data))
|
||||
}
|
||||
go func(c *net.UDPConn, id uint32, target string) {
|
||||
defer c.Close()
|
||||
go func(e *creatorUDP, id uint32, target string) {
|
||||
defer e.close()
|
||||
defer rb.udpClients.Delete(id)
|
||||
defer rb.send(id, MsgClose, nil)
|
||||
buf := make([]byte, common.UDPBufSize)
|
||||
var replies int
|
||||
var totalIn int64
|
||||
for {
|
||||
c.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
n, err := c.Read(buf)
|
||||
e.setReadDeadline(time.Now().Add(60 * time.Second))
|
||||
n, err := e.read(buf)
|
||||
if err != nil {
|
||||
if verboseUDPLogging {
|
||||
rb.logFn("relay[creator]: UDP %d session %s closed after %d replies, %dB in: %v", id, target, replies, totalIn, err)
|
||||
@@ -393,28 +428,54 @@ func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
}
|
||||
rb.send(id, MsgUDPReply, buf[:n])
|
||||
}
|
||||
}(conn, connID, udpAddr.String())
|
||||
}(egress, connID, addr)
|
||||
}
|
||||
}
|
||||
|
||||
conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
if err := egress.writePacket(data, addr); err != nil {
|
||||
rb.logFn("relay[creator]: UDP %d write %s failed: %v", connID, common.MaskAddr(addr), err)
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) dialCreatorUDP(addr string) (*creatorUDP, error) {
|
||||
if rb.upstream != nil {
|
||||
sess, err := rb.upstream.UDPAssociate(10 * time.Second)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &creatorUDP{socks: sess}, nil
|
||||
}
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dialed, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &creatorUDP{direct: dialed}, nil
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
||||
rb.logFn("relay: CONNECT %d -> %s", connID, common.MaskAddr(addr))
|
||||
if host, port, splitErr := net.SplitHostPort(addr); splitErr == nil && host != "" && net.ParseIP(host) == nil {
|
||||
dnsStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ips, dnsErr := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
cancel()
|
||||
if dnsErr != nil {
|
||||
rb.logFn("relay: DNS %d %s failed in %s: %v", connID, host, time.Since(dnsStart), dnsErr)
|
||||
} else {
|
||||
rb.logFn("relay: DNS %d %s -> %s port=%s took=%s", connID, host, ipAddrList(ips), port, time.Since(dnsStart))
|
||||
var conn net.Conn
|
||||
var err error
|
||||
if rb.upstream != nil {
|
||||
conn, err = rb.upstream.DialTCP(addr, 10*time.Second)
|
||||
} else {
|
||||
if host, port, splitErr := net.SplitHostPort(addr); splitErr == nil && host != "" && net.ParseIP(host) == nil {
|
||||
dnsStart := time.Now()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
ips, dnsErr := net.DefaultResolver.LookupIPAddr(ctx, host)
|
||||
cancel()
|
||||
if dnsErr != nil {
|
||||
rb.logFn("relay: DNS %d %s failed in %s: %v", connID, host, time.Since(dnsStart), dnsErr)
|
||||
} else {
|
||||
rb.logFn("relay: DNS %d %s -> %s port=%s took=%s", connID, host, ipAddrList(ips), port, time.Since(dnsStart))
|
||||
}
|
||||
}
|
||||
conn, err = net.DialTimeout("tcp", addr, 10*time.Second)
|
||||
}
|
||||
conn, err := net.DialTimeout("tcp", addr, 10e9)
|
||||
if err != nil {
|
||||
rb.logFn("relay: CONNECT %d failed: %s", connID, common.MaskError(err))
|
||||
rb.send(connID, MsgConnectErr, []byte(common.MaskError(err)))
|
||||
@@ -537,7 +598,7 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
}
|
||||
// Dial local/private addresses directly instead of tunneling to the creator,
|
||||
// which cannot reach the joiner's local network. Disabled for now until
|
||||
// there is a real use case for local network access through the proxy. So idk if
|
||||
// there is a real use case for local network access through the proxy. So idk if
|
||||
// this is a bug or a feature
|
||||
// if ip := net.ParseIP(hostOnly); ip != nil && !ip.IsGlobalUnicast() {
|
||||
// rb.logFn("relay: SOCKS local dial %s", common.MaskAddr(host))
|
||||
|
||||
Reference in new issue
Block a user