V0.1.9 (#26)
* fix: prevent duplicate call link detection (#23) Co-authored-by: Maksim <maksim@MacBook-Pro-Maksim.local> * bot improvements (#25) Co-authored-by: Maksim <maksim@MBP-Maksim.lan> * headless vk video creator * add scroll to logs * allow peer reconnection * add todo about topology changes, kick stale peer to prevent SFU topology * unified relay for headless * remove relay binaries, extend build-go.sh to build them * refactor constants * limit headless resource usage * nuke everyone and yourself at sfu topology changes * add headless for creator * save bot enabled state * increment release version --------- Co-authored-by: Nevenuga <80585376+Nevenuga@users.noreply.github.com> Co-authored-by: Maksim <maksim@MacBook-Pro-Maksim.local> Co-authored-by: Maksim <maksim@MBP-Maksim.lan> Co-authored-by: kulikov <user@Mac.lan>
This commit is contained in:
37 files changed
+2589
-133
No files matched your search
@@ -2,3 +2,7 @@
|
||||
relay/mobile.aar
|
||||
relay/relay-*
|
||||
prebuilts/
|
||||
cookies.json
|
||||
pion-light/
|
||||
headless/headless-creator
|
||||
relay/relay
|
||||
@@ -126,10 +126,12 @@ Download and run the Electron app from [GitHub Releases](../../releases). It bun
|
||||
|
||||
1. Open the app
|
||||
2. Select tunnel mode (DC or Pion Video)
|
||||
3. Click "VK Call" or "Telemost"
|
||||
4. Log in, create a call
|
||||
3. Click "VK" or "Telemost"
|
||||
4. Log in, **create a new call** from the app
|
||||
5. Copy the join link, send it to the joiner
|
||||
|
||||
**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)
|
||||
|
||||
1. Download and install `whitelist-bypass.apk` from [GitHub Releases](../../releases)
|
||||
@@ -189,6 +191,34 @@ The Go relay is split into platform-specific files:
|
||||
|
||||
This allows cross-compiling the relay for macOS/Windows/Linux without CGo or Android NDK.
|
||||
|
||||
### Headless creator
|
||||
|
||||
Pure Go creator that creates VK calls via API without a browser. No Electron, no JS hooks - Go Pion PeerConnection handles the DataChannel tunnel directly.
|
||||
|
||||
```sh
|
||||
# Build
|
||||
cd headless && go build -o headless-creator .
|
||||
|
||||
# Run
|
||||
./headless-creator --cookies cookies.json [--peer-id <vk_peer_id>] [--resources <mode>]
|
||||
```
|
||||
|
||||
- `--cookies` - path to VK cookies exported as JSON (`[{"name":"..","value":".."},...]`). Use the "Export Cookies" button in the Creator app to get this file
|
||||
- `--peer-id` - VK peer_id for the call (optional)
|
||||
- `--resources` - resource mode (see below)
|
||||
|
||||
**Resource modes:**
|
||||
|
||||
| Mode | read-buf | max-dc-buf | mem-limit | Use case |
|
||||
|---|---|---|---|---|
|
||||
| `moderate` | 16KB | 1MB | 64MB | Low memory environments, VPS |
|
||||
| `default` | 32KB | 4MB | 128MB | General use |
|
||||
| `unlimited` | 64KB | 8MB | 256MB | Maximum throughput |
|
||||
|
||||
- `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
|
||||
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
@@ -5,7 +5,7 @@ plugins {
|
||||
|
||||
val versionMajor = 0
|
||||
val versionMinor = 1
|
||||
val versionPatch = 8
|
||||
val versionPatch = 9
|
||||
val versionBuild = System.getenv("BUILD_NUMBER")?.toIntOrNull() ?: 0
|
||||
|
||||
android {
|
||||
|
||||
Binary file not shown.
@@ -1,6 +1,7 @@
|
||||
package bypass.whitelist.ui
|
||||
|
||||
import android.content.Intent
|
||||
import android.text.method.ScrollingMovementMethod
|
||||
import android.widget.TextView
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.core.content.FileProvider
|
||||
@@ -12,6 +13,10 @@ class LogViewController(
|
||||
private val logView: TextView,
|
||||
private val logWriter: LogWriter,
|
||||
) {
|
||||
init {
|
||||
logView.movementMethod = ScrollingMovementMethod.getInstance()
|
||||
}
|
||||
|
||||
fun append(msg: String) {
|
||||
val (line, evicted) = logWriter.append(msg)
|
||||
activity.runOnUiThread {
|
||||
|
||||
Binary file not shown.
Binary file not shown.
+39
-2
@@ -5,6 +5,8 @@ ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
RELAY_DIR="$ROOT/relay"
|
||||
CREATOR_DIR="$ROOT/creator-app"
|
||||
|
||||
HEADLESS_DIR="$ROOT/headless"
|
||||
|
||||
echo "=== Building relay binaries ==="
|
||||
cd "$RELAY_DIR"
|
||||
|
||||
@@ -26,6 +28,28 @@ GOOS=linux GOARCH=386 go build -o relay-linux-ia32 .
|
||||
|
||||
ls -lh relay-darwin relay-windows-*.exe relay-linux-*
|
||||
|
||||
echo ""
|
||||
echo "=== Building headless-creator ==="
|
||||
cd "$HEADLESS_DIR"
|
||||
|
||||
echo "macOS (universal)..."
|
||||
GOOS=darwin GOARCH=amd64 go build -o headless-darwin-amd64 .
|
||||
GOOS=darwin GOARCH=arm64 go build -o headless-darwin-arm64 .
|
||||
lipo -create -output headless-darwin headless-darwin-amd64 headless-darwin-arm64
|
||||
rm headless-darwin-amd64 headless-darwin-arm64
|
||||
|
||||
echo "Windows x64..."
|
||||
GOOS=windows GOARCH=amd64 go build -o headless-windows-x64.exe .
|
||||
echo "Windows x86..."
|
||||
GOOS=windows GOARCH=386 go build -o headless-windows-ia32.exe .
|
||||
|
||||
echo "Linux x64..."
|
||||
GOOS=linux GOARCH=amd64 go build -o headless-linux-x64 .
|
||||
echo "Linux x86..."
|
||||
GOOS=linux GOARCH=386 go build -o headless-linux-ia32 .
|
||||
|
||||
ls -lh headless-darwin headless-windows-*.exe headless-linux-*
|
||||
|
||||
echo ""
|
||||
echo "=== Building Electron apps ==="
|
||||
cd "$CREATOR_DIR"
|
||||
@@ -40,22 +64,35 @@ npx electron-builder --mac
|
||||
echo ""
|
||||
echo "--- Windows x64 ---"
|
||||
cp "$RELAY_DIR/relay-windows-x64.exe" "$RELAY_DIR/relay-bundle.exe"
|
||||
cp "$HEADLESS_DIR/headless-windows-x64.exe" "$HEADLESS_DIR/headless-bundle.exe"
|
||||
npx electron-builder --win --x64
|
||||
|
||||
# Windows x86
|
||||
echo ""
|
||||
echo "--- Windows x86 ---"
|
||||
cp "$RELAY_DIR/relay-windows-ia32.exe" "$RELAY_DIR/relay-bundle.exe"
|
||||
cp "$HEADLESS_DIR/headless-windows-ia32.exe" "$HEADLESS_DIR/headless-bundle.exe"
|
||||
npx electron-builder --win --ia32
|
||||
|
||||
# Linux x64
|
||||
echo ""
|
||||
echo "--- Linux x64 ---"
|
||||
cp "$RELAY_DIR/relay-linux-x64" "$RELAY_DIR/relay-bundle"
|
||||
cp "$HEADLESS_DIR/headless-linux-x64" "$HEADLESS_DIR/headless-bundle"
|
||||
npx electron-builder --linux --x64
|
||||
|
||||
# Cleanup
|
||||
rm -f "$RELAY_DIR/relay-bundle" "$RELAY_DIR/relay-bundle.exe"
|
||||
# Copy standalone headless binaries to prebuilts
|
||||
echo ""
|
||||
echo "=== Copying headless binaries ==="
|
||||
mkdir -p "$ROOT/prebuilts"
|
||||
cp "$HEADLESS_DIR/headless-linux-x64" "$ROOT/prebuilts/headless-creator-linux-x64"
|
||||
cp "$HEADLESS_DIR/headless-linux-ia32" "$ROOT/prebuilts/headless-creator-linux-ia32"
|
||||
|
||||
# Cleanup build artifacts
|
||||
rm -f "$RELAY_DIR"/relay-darwin "$RELAY_DIR"/relay-windows-*.exe "$RELAY_DIR"/relay-linux-*
|
||||
rm -f "$RELAY_DIR"/relay-bundle "$RELAY_DIR"/relay-bundle.exe
|
||||
rm -f "$HEADLESS_DIR"/headless-darwin "$HEADLESS_DIR"/headless-windows-*.exe "$HEADLESS_DIR"/headless-linux-*
|
||||
rm -f "$HEADLESS_DIR"/headless-bundle "$HEADLESS_DIR"/headless-bundle.exe
|
||||
|
||||
echo ""
|
||||
echo "=== Done ==="
|
||||
|
||||
+12
-1
@@ -12,7 +12,8 @@ command -v gomobile >/dev/null || { echo "gomobile not found, run: go install go
|
||||
command -v gobind >/dev/null || { echo "gobind not found, run: go install golang.org/x/mobile/cmd/gobind@latest"; exit 1; }
|
||||
[ -d "$ANDROID_NDK_HOME" ] || { echo "NDK not found at $ANDROID_NDK_HOME"; exit 1; }
|
||||
|
||||
cd "$(dirname "$0")/relay"
|
||||
ROOT="$(cd "$(dirname "$0")" && pwd)"
|
||||
cd "$ROOT/relay"
|
||||
|
||||
echo "Building gomobile .aar..."
|
||||
gomobile bind -v -target=android -androidapi 23 -o mobile.aar ./mobile/ 2>&1
|
||||
@@ -34,3 +35,13 @@ cp ../hooks/video-vk.js ../android-app/app/src/main/assets/video-vk.js
|
||||
cp ../hooks/video-telemost.js ../android-app/app/src/main/assets/video-telemost.js
|
||||
|
||||
echo "Done. .aar size: $(du -h mobile.aar | cut -f1)"
|
||||
|
||||
echo ""
|
||||
echo "Building desktop relay..."
|
||||
go -C "$ROOT/relay" build -o relay .
|
||||
|
||||
echo "Building headless-creator..."
|
||||
go -C "$ROOT/headless" build -o headless-creator .
|
||||
|
||||
echo "Done."
|
||||
ls -lh "$ROOT/relay/relay" "$ROOT/headless/headless-creator"
|
||||
+155
-10
@@ -1,9 +1,69 @@
|
||||
const fetch = require('node-fetch');
|
||||
|
||||
function generateTabId(tabId) {
|
||||
var hash = 0;
|
||||
for (var i = 0; i < tabId.length; i++) {
|
||||
hash = ((hash << 5) - hash) + tabId.charCodeAt(i);
|
||||
hash = hash & hash;
|
||||
}
|
||||
return Math.abs(hash) % 10000;
|
||||
}
|
||||
|
||||
function findTabById(tabsList, shortId) {
|
||||
var targetId = parseInt(shortId, 10);
|
||||
for (var i = 0; i < tabsList.length; i++) {
|
||||
var t = tabsList[i];
|
||||
if (generateTabId(t.id) === targetId) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function createKeyboard() {
|
||||
return {
|
||||
one_time: false,
|
||||
buttons: [
|
||||
[
|
||||
{ action: { type: 'text', label: '📞 VK DC', payload: JSON.stringify({ cmd: 'vk', mode: 'dc' }) } },
|
||||
{ action: { type: 'text', label: '📹 VK Video', payload: JSON.stringify({ cmd: 'vk', mode: 'video' }) } }
|
||||
],
|
||||
[
|
||||
{ action: { type: 'text', label: '📞 TM DC', payload: JSON.stringify({ cmd: 'tm', mode: 'dc' }) } },
|
||||
{ action: { type: 'text', label: '📹 TM Video', payload: JSON.stringify({ cmd: 'tm', mode: 'video' }) } }
|
||||
],
|
||||
[
|
||||
{ action: { type: 'text', label: '📋 Active Tabs', payload: JSON.stringify({ cmd: 'list' }) } }
|
||||
]
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
function createListKeyboard(tabsList) {
|
||||
var buttons = [];
|
||||
for (var i = 0; i < tabsList.length; i++) {
|
||||
var t = tabsList[i];
|
||||
var shortId = generateTabId(t.id);
|
||||
var paddedId = ('000' + shortId).slice(-4);
|
||||
var prefix = t.isBot ? 'bot' : 'user';
|
||||
var status = t.callStatus === 'active' ? '🟢' : '⚪';
|
||||
buttons.push([
|
||||
{ action: { type: 'text', label: prefix + ' ' + t.platform + ' ' + t.mode + ' ' + paddedId + ' ' + status, payload: JSON.stringify({ cmd: 'close', id: t.id }) } }
|
||||
]);
|
||||
}
|
||||
buttons.push([{ action: { type: 'text', label: '◀️ Back', payload: JSON.stringify({ cmd: 'menu' }) } }]);
|
||||
return {
|
||||
one_time: false,
|
||||
buttons: buttons
|
||||
};
|
||||
}
|
||||
|
||||
class BotManager {
|
||||
constructor(settings, onCreateTab) {
|
||||
constructor(settings, onCreateTab, onGetTabs, onCloseTab) {
|
||||
this.settings = settings;
|
||||
this.onCreateTab = onCreateTab;
|
||||
this.onGetTabs = onGetTabs;
|
||||
this.onCloseTab = onCloseTab;
|
||||
this.baseUrl = 'https://api.vk.com/method';
|
||||
this.ts = null;
|
||||
this.key = null;
|
||||
@@ -80,22 +140,70 @@ class BotManager {
|
||||
async handleUpdate(update) {
|
||||
if (update.type === 'message_new') {
|
||||
const message = update.object.message;
|
||||
const text = message.text || '';
|
||||
var text = (message.text || '').trim();
|
||||
const fromId = message.from_id;
|
||||
const peerId = message.peer_id;
|
||||
|
||||
var payload = null;
|
||||
if (message.payload) {
|
||||
try {
|
||||
payload = JSON.parse(message.payload);
|
||||
console.log('[BOT] Payload from button:', payload);
|
||||
} catch (e) {
|
||||
console.log('[BOT] Failed to parse payload:', message.payload);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('[BOT] Message from', fromId, ':', text, 'payload:', payload);
|
||||
|
||||
if (this.settings.userId && fromId.toString() !== this.settings.userId.toString()) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('[BOT] Message from', fromId, ':', text);
|
||||
|
||||
if (text === '/start' || text === 'start') {
|
||||
await this.showMenu(peerId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (payload && payload.cmd) {
|
||||
if (payload.cmd === 'list') {
|
||||
await this.showList(peerId);
|
||||
return;
|
||||
} else if (payload.cmd === 'menu') {
|
||||
await this.showMenu(peerId);
|
||||
return;
|
||||
} else if (payload.cmd === 'close') {
|
||||
if (payload.id) {
|
||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
||||
var foundTab = null;
|
||||
for (var i = 0; i < tabsList.length; i++) {
|
||||
if (tabsList[i].id === payload.id) {
|
||||
foundTab = tabsList[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (foundTab && this.onCloseTab) {
|
||||
var shortId = generateTabId(foundTab.id);
|
||||
var paddedId = ('000' + shortId).slice(-4);
|
||||
this.onCloseTab(foundTab.id);
|
||||
await this.sendMessage(peerId, foundTab.platform + ' ' + foundTab.mode + ' ' + paddedId + ' closed', createKeyboard());
|
||||
return;
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else if (payload.cmd === 'vk') {
|
||||
text = '/vk' + (payload.mode === 'video' ? ' video' : '');
|
||||
} else if (payload.cmd === 'tm') {
|
||||
text = '/tm' + (payload.mode === 'video' ? ' video' : '');
|
||||
}
|
||||
}
|
||||
|
||||
if (text.startsWith('/vk')) {
|
||||
const mode = text.includes('video') ? 'pion-video' : 'dc';
|
||||
console.log('[BOT] Creating VK tab with mode:', mode);
|
||||
|
||||
|
||||
this.onCreateTab({ mode: mode, peerId: peerId, platform: 'vk' });
|
||||
await this.sendMessage(peerId, 'Creating VK call (' + (mode === 'dc' ? 'DC' : 'Video') + ')...');
|
||||
await this.sendMessage(peerId, 'Creating VK call (' + (mode === 'dc' ? 'DC' : 'Video') + ')', createKeyboard());
|
||||
}
|
||||
|
||||
if (text.startsWith('/tm')) {
|
||||
@@ -104,23 +212,60 @@ class BotManager {
|
||||
|
||||
this.onCreateTab({ mode: mode, peerId: peerId, platform: 'telemost' });
|
||||
|
||||
await this.sendMessage(peerId, 'Creating Telemost call (' + (mode === 'dc' ? 'DC' : 'Video') + ')...');
|
||||
await this.sendMessage(peerId, 'Creating Telemost call (' + (mode === 'dc' ? 'DC' : 'Video') + ')', createKeyboard());
|
||||
}
|
||||
|
||||
if (text === '/list') {
|
||||
await this.showList(peerId);
|
||||
}
|
||||
|
||||
if (text.startsWith('/close ')) {
|
||||
var parts = text.split(' ');
|
||||
var targetShortId = parts[1];
|
||||
console.log('[BOT] Close request for ID:', targetShortId, 'from peer:', peerId);
|
||||
|
||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
||||
var foundTab = findTabById(tabsList, targetShortId);
|
||||
|
||||
if (!foundTab) {
|
||||
await this.sendMessage(peerId, 'Tab ' + targetShortId + ' not found', createKeyboard());
|
||||
} else if (this.onCloseTab) {
|
||||
this.onCloseTab(foundTab.id);
|
||||
await this.sendMessage(peerId, foundTab.platform + ' ' + foundTab.mode + ' ' + targetShortId + ' closed', createKeyboard());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(peerId, text) {
|
||||
async sendMessage(peerId, text, keyboard = null) {
|
||||
try {
|
||||
await this.api('messages.send', {
|
||||
var params = {
|
||||
peer_id: peerId,
|
||||
message: text,
|
||||
random_id: Math.floor(Math.random() * 1e9)
|
||||
});
|
||||
};
|
||||
if (keyboard) {
|
||||
params.keyboard = JSON.stringify(keyboard);
|
||||
}
|
||||
await this.api('messages.send', params);
|
||||
console.log('[BOT] Sent message to', peerId);
|
||||
} catch (err) {
|
||||
console.error('[BOT] Send message error:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async showMenu(peerId) {
|
||||
await this.sendMessage(peerId, '🤖 Select mode:', createKeyboard());
|
||||
}
|
||||
|
||||
async showList(peerId) {
|
||||
var tabsList = this.onGetTabs ? this.onGetTabs() : [];
|
||||
if (tabsList.length === 0) {
|
||||
await this.sendMessage(peerId, 'No active tabs', createKeyboard());
|
||||
} else {
|
||||
await this.sendMessage(peerId, 'Select tab to close:', createListKeyboard(tabsList));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BotManager;
|
||||
@@ -0,0 +1,24 @@
|
||||
(function() {
|
||||
if (window.__callCheckerStarted) return;
|
||||
window.__callCheckerStarted = true;
|
||||
|
||||
var tabId = window.__CALL_CHECKER_TAB_ID || 'unknown';
|
||||
|
||||
console.log('[CALL_STATUS] Checker started for ' + tabId);
|
||||
|
||||
const checkCallStatus = () => {
|
||||
var vkBtn = document.querySelector('button[data-testid="calls_call_footer_button_leave_call"]') ||
|
||||
document.querySelector('[data-testid="calls_call_footer_button_leave_call"]');
|
||||
|
||||
var tmBtn = document.querySelector('[data-testid="end-call-alt-button"]') ||
|
||||
document.querySelector('button[data-testid="end-call-alt-button"]');
|
||||
|
||||
var status = (vkBtn || tmBtn) ? 'active' : 'inactive';
|
||||
|
||||
console.log('[CALL_STATUS] ' + tabId + ':' + status);
|
||||
};
|
||||
setTimeout(function() {
|
||||
checkCallStatus();
|
||||
setInterval(checkCallStatus, 10000);
|
||||
}, 10000);
|
||||
})();
|
||||
+129
-13
@@ -61,6 +61,7 @@ body { font-family: -apple-system, sans-serif; background: #1a1a1a; color: #e0e0
|
||||
<div class="tab-add" onclick="addTab()" title="New tab">+</div>
|
||||
</div>
|
||||
<div class="tab-bar-actions">
|
||||
<div class="tab-settings" onclick="copyCookies()" title="Export VK cookies to cookies.json for headless mode" style="cursor:pointer">Export Cookies</div>
|
||||
<div class="tab-settings" onclick="openSettings()" title="Settings">Settings</div>
|
||||
<div class="tab-bot" id="tabBot" onclick="toggleBot()">Bot: Off</div>
|
||||
</div>
|
||||
@@ -68,6 +69,7 @@ body { font-family: -apple-system, sans-serif; background: #1a1a1a; color: #e0e0
|
||||
<div class="toolbar" id="toolbar" style="display:none">
|
||||
<button class="btn-vk" onclick="loadURL('https://vk.com/im')">VK</button>
|
||||
<button class="btn-telemost" onclick="loadURL('https://telemost.yandex.ru/')">Telemost</button>
|
||||
<button class="btn-vk" onclick="startHeadlessVK()" style="opacity:0.8">Headless VK</button>
|
||||
<span style="margin-left:auto;font-size:11px;color:#888">Tunnel:</span>
|
||||
<select id="modeSelect" style="padding:2px 6px;border:1px solid #555;border-radius:6px;font-size:11px;cursor:pointer;font-weight:500;background:#333;color:#e0e0e0;outline:none" onchange="onModeChange(this.value)">
|
||||
<option value="dc">DC</option>
|
||||
@@ -80,6 +82,17 @@ body { font-family: -apple-system, sans-serif; background: #1a1a1a; color: #e0e0
|
||||
<h1>Whitelist Bypass - Creator</h1>
|
||||
<p>Click + to add a tab</p>
|
||||
</div>
|
||||
<div class="headless-info" id="headlessInfo" style="display:none;padding:24px;color:#e0e0e0;font-family:monospace;font-size:14px">
|
||||
<div style="font-size:18px;font-weight:bold;margin-bottom:16px">Headless VK</div>
|
||||
<div id="headlessStatus" style="color:#888">Starting...</div>
|
||||
<div id="headlessCallInfo" style="margin-top:16px;display:none">
|
||||
<div style="margin-bottom:8px"><span style="color:#888">Join link:</span> <a id="headlessJoinLink" href="#" style="color:#4fc3f7;cursor:pointer" onclick="copyToClipboard(this.textContent)"></a></div>
|
||||
<div style="margin-bottom:8px"><span style="color:#888">Short:</span> <a id="headlessShortLink" href="#" style="color:#4fc3f7;cursor:pointer" onclick="copyToClipboard(this.textContent)"></a></div>
|
||||
<div style="margin-bottom:8px"><span style="color:#888">TURN:</span> <span id="headlessTurn"></span></div>
|
||||
<div style="margin-bottom:8px"><span style="color:#888">Protocol:</span> <span id="headlessProtocol"></span></div>
|
||||
</div>
|
||||
<div id="headlessTunnel" style="margin-top:16px;display:none;color:#4caf50;font-weight:bold;font-size:16px">TUNNEL CONNECTED</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="logs" id="logsPanel" style="display:none">
|
||||
<div class="log-panel">
|
||||
@@ -129,11 +142,27 @@ function closeError() {
|
||||
window.bridge.onBotError(function(msg) {
|
||||
showError(msg);
|
||||
botRunning = false;
|
||||
localStorage.setItem('botEnabled', 'false');
|
||||
var btn = document.getElementById('tabBot');
|
||||
btn.textContent = 'Bot: Off';
|
||||
btn.classList.remove('running');
|
||||
});
|
||||
|
||||
function copyCookies() {
|
||||
window.bridge.getCookies('.vk.com').then(function(cookies) {
|
||||
if (!cookies.length) {
|
||||
showError('No VK cookies found.\nPlease log into VK first.');
|
||||
return;
|
||||
}
|
||||
var simple = cookies.map(function(c) { return { name: c.name, value: c.value }; });
|
||||
var blob = new Blob([JSON.stringify(simple, null, 2)], { type: 'application/json' });
|
||||
var link = document.createElement('a');
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = 'cookies.json';
|
||||
link.click();
|
||||
});
|
||||
}
|
||||
|
||||
var tabsState = {}; // tabId -> { wv, mode, relayLogs, hookLogs }
|
||||
var activeTabId = null;
|
||||
var nextTabId = 1;
|
||||
@@ -142,6 +171,14 @@ var botRunning = false;
|
||||
var savedSettings = localStorage.getItem('botSettings');
|
||||
var botSettings = savedSettings ? JSON.parse(savedSettings) : { token: '', groupId: '', userId: '' };
|
||||
|
||||
if (localStorage.getItem('botEnabled') === 'true' && botSettings.token && botSettings.groupId) {
|
||||
botRunning = true;
|
||||
var btn = document.getElementById('tabBot');
|
||||
btn.textContent = 'Bot: On';
|
||||
btn.classList.add('running');
|
||||
window.bridge.startBot(botSettings);
|
||||
}
|
||||
|
||||
function openSettings() {
|
||||
document.getElementById('settingsPopup').classList.add('visible');
|
||||
document.getElementById('vkToken').value = botSettings.token;
|
||||
@@ -168,6 +205,7 @@ function toggleBot() {
|
||||
return;
|
||||
}
|
||||
botRunning = !botRunning;
|
||||
localStorage.setItem('botEnabled', botRunning ? 'true' : 'false');
|
||||
var btn = document.getElementById('tabBot');
|
||||
if (botRunning) {
|
||||
btn.textContent = 'Bot: On';
|
||||
@@ -182,12 +220,20 @@ function toggleBot() {
|
||||
|
||||
function addTab() {
|
||||
var tabId = 'tab-' + (nextTabId++);
|
||||
tabsState[tabId] = { wv: null, url: '', mode: 'dc', relayLogs: '', hookLogs: '', name: '' };
|
||||
tabsState[tabId] = { wv: null, url: '', mode: 'dc', relayLogs: '', hookLogs: '', name: '', isBot: false };
|
||||
window.bridge.startRelay(tabId);
|
||||
renderTabs();
|
||||
selectTab(tabId);
|
||||
}
|
||||
|
||||
function startHeadlessVK() {
|
||||
var tabId = 'tab-' + (nextTabId++);
|
||||
tabsState[tabId] = { wv: null, url: '', mode: 'headless-vk', relayLogs: '', hookLogs: '', name: 'Headless VK', isBot: false, headless: true };
|
||||
window.bridge.startHeadless(tabId);
|
||||
renderTabs();
|
||||
selectTab(tabId);
|
||||
}
|
||||
|
||||
function closeTab(tabId, e) {
|
||||
if (e) e.stopPropagation();
|
||||
var t = tabsState[tabId];
|
||||
@@ -262,7 +308,6 @@ function renderContent() {
|
||||
var welcome = document.getElementById('welcome');
|
||||
var toolbar = document.getElementById('toolbar');
|
||||
var logsPanel = document.getElementById('logsPanel');
|
||||
// Hide all webviews
|
||||
var wvs = content.querySelectorAll('webview');
|
||||
for (var i = 0; i < wvs.length; i++) wvs[i].classList.add('hidden');
|
||||
|
||||
@@ -273,14 +318,33 @@ function renderContent() {
|
||||
return;
|
||||
}
|
||||
welcome.style.display = 'none';
|
||||
toolbar.style.display = 'flex';
|
||||
logsPanel.style.display = 'flex';
|
||||
|
||||
var t = tabsState[activeTabId];
|
||||
document.getElementById('modeSelect').value = t.mode;
|
||||
var headlessInfo = document.getElementById('headlessInfo');
|
||||
if (t.headless) {
|
||||
toolbar.style.display = 'none';
|
||||
headlessInfo.style.display = 'block';
|
||||
document.getElementById('headlessStatus').textContent = t.headlessStatus || 'Starting...';
|
||||
var ci = t.callInfo;
|
||||
if (ci) {
|
||||
document.getElementById('headlessCallInfo').style.display = 'block';
|
||||
document.getElementById('headlessJoinLink').textContent = ci.joinLink || '';
|
||||
document.getElementById('headlessShortLink').textContent = ci.shortLink || '';
|
||||
document.getElementById('headlessTurn').textContent = ci.turn || '';
|
||||
document.getElementById('headlessProtocol').textContent = ci.protocol || '';
|
||||
} else {
|
||||
document.getElementById('headlessCallInfo').style.display = 'none';
|
||||
}
|
||||
document.getElementById('headlessTunnel').style.display = t.tunnelConnected ? 'block' : 'none';
|
||||
} else {
|
||||
toolbar.style.display = 'flex';
|
||||
headlessInfo.style.display = 'none';
|
||||
document.getElementById('modeSelect').value = t.mode;
|
||||
if (t.wv) t.wv.classList.remove('hidden');
|
||||
}
|
||||
document.getElementById('relayLog').textContent = t.relayLogs || '';
|
||||
document.getElementById('hookLog').textContent = t.hookLogs || '';
|
||||
if (t.wv) t.wv.classList.remove('hidden');
|
||||
scrollLogs();
|
||||
}
|
||||
|
||||
@@ -313,7 +377,17 @@ function loadURL(url) {
|
||||
window.bridge.getHookCode(tabId, wv.getURL()).then(function(code) {
|
||||
wv.executeJavaScript(code).catch(function() {});
|
||||
});
|
||||
|
||||
|
||||
window.bridge.getCallCreatorCode('call-checker.js').then(function(checkerCode) {
|
||||
console.log('[UI] Injecting call checker for tab:', tabId);
|
||||
var injectCode = 'window.__CALL_CHECKER_TAB_ID = "' + tabId + '"; ' + checkerCode;
|
||||
wv.executeJavaScript(injectCode).catch(function(err) {
|
||||
console.log('[UI] Call checker inject error:', err);
|
||||
});
|
||||
}).catch(function(err) {
|
||||
console.log('[UI] Failed to get call-checker.js:', err);
|
||||
});
|
||||
|
||||
if (tabsState[tabId] && tabsState[tabId].isBot) {
|
||||
setTimeout(function() {
|
||||
var scriptFile = tabsState[tabId].platform === 'telemost' ? 'tm-call-creator.js' : 'vk-call-creator.js';
|
||||
@@ -331,6 +405,10 @@ function loadURL(url) {
|
||||
window.bridge.getHookCode(tabId, wv.getURL()).then(function(code) {
|
||||
wv.executeJavaScript(code).catch(function() {});
|
||||
});
|
||||
window.bridge.getCallCreatorCode('call-checker.js').then(function(checkerCode) {
|
||||
var injectCode = 'window.__CALL_CHECKER_TAB_ID = "' + tabId + '"; ' + checkerCode;
|
||||
wv.executeJavaScript(injectCode).catch(function() {});
|
||||
});
|
||||
});
|
||||
t.wv = wv;
|
||||
t.url = url;
|
||||
@@ -364,7 +442,6 @@ function saveLogs() {
|
||||
a.click();
|
||||
}
|
||||
|
||||
// Poll hook logs from active tab's webview
|
||||
setInterval(function() {
|
||||
if (!activeTabId || !tabsState[activeTabId] || !tabsState[activeTabId].wv) return;
|
||||
tabsState[activeTabId].wv.executeJavaScript('(window.__hookLogs && window.__hookLogs.length) ? window.__hookLogs.splice(0) : []')
|
||||
@@ -379,10 +456,10 @@ setInterval(function() {
|
||||
}).catch(function() {});
|
||||
}, 500);
|
||||
|
||||
// Relay logs from main process
|
||||
window.bridge.onRelayLog(function(tabId, msg) {
|
||||
if (tabsState[tabId]) {
|
||||
tabsState[tabId].relayLogs += (tabsState[tabId].relayLogs ? '\n' : '') + msg;
|
||||
if (tabsState[tabId].headless) parseHeadlessLog(tabId, msg);
|
||||
}
|
||||
if (tabId === activeTabId) {
|
||||
var el = document.getElementById('relayLog');
|
||||
@@ -392,30 +469,69 @@ window.bridge.onRelayLog(function(tabId, msg) {
|
||||
}
|
||||
});
|
||||
|
||||
// Bot tab creation
|
||||
function parseHeadlessLog(tabId, msg) {
|
||||
var t = tabsState[tabId];
|
||||
if (!t) return;
|
||||
var trimmed = msg.trim();
|
||||
if (trimmed === 'CALL CREATED') {
|
||||
t.callInfo = {};
|
||||
t.headlessStatus = 'Call created';
|
||||
}
|
||||
if (trimmed.indexOf('join_link:') !== -1) {
|
||||
if (!t.callInfo) t.callInfo = {};
|
||||
t.callInfo.joinLink = trimmed.split('join_link:')[1].trim();
|
||||
}
|
||||
if (trimmed.indexOf('short:') !== -1) {
|
||||
if (!t.callInfo) t.callInfo = {};
|
||||
t.callInfo.shortLink = trimmed.split('short:')[1].trim();
|
||||
}
|
||||
if (trimmed.indexOf('TURN:') !== -1) {
|
||||
if (!t.callInfo) t.callInfo = {};
|
||||
t.callInfo.turn = trimmed.split('TURN:')[1].trim();
|
||||
}
|
||||
if (trimmed.indexOf('protocol:') !== -1) {
|
||||
if (!t.callInfo) t.callInfo = {};
|
||||
t.callInfo.protocol = trimmed.split('protocol:')[1].trim();
|
||||
}
|
||||
if (trimmed === 'TUNNEL CONNECTED') {
|
||||
t.tunnelConnected = true;
|
||||
t.headlessStatus = 'Tunnel connected';
|
||||
}
|
||||
if (tabId === activeTabId) renderContent();
|
||||
}
|
||||
|
||||
function copyToClipboard(text) {
|
||||
navigator.clipboard.writeText(text);
|
||||
}
|
||||
|
||||
window.bridge.onCreateBotTab(function(data) {
|
||||
console.log('[BOT] Creating tab:', data);
|
||||
var tabId = data.tabId;
|
||||
var mode = data.mode;
|
||||
var peerId = data.peerId;
|
||||
var platform = data.platform || 'vk';
|
||||
|
||||
|
||||
if (!tabsState[tabId]) {
|
||||
var botName = platform === 'telemost' ? 'Bot-Telemost' : 'Bot-VK';
|
||||
tabsState[tabId] = { wv: null, url: '', mode: mode, relayLogs: '', hookLogs: '', name: botName, isBot: true, peerId: peerId, platform: platform };
|
||||
}
|
||||
|
||||
|
||||
selectTab(tabId);
|
||||
|
||||
|
||||
document.getElementById('modeSelect').value = mode;
|
||||
window.bridge.setTunnelMode(tabId, mode);
|
||||
|
||||
|
||||
if (platform === 'telemost') {
|
||||
loadURL('https://telemost.yandex.ru/');
|
||||
} else {
|
||||
loadURL('https://vk.com/im');
|
||||
}
|
||||
});
|
||||
|
||||
window.bridge.onCloseBotTab(function(data) {
|
||||
console.log('[BOT] Closing tab:', data.tabId);
|
||||
closeTab(data.tabId);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+101
-2
@@ -13,8 +13,15 @@ var logCapture = "if(!window.__logCaptureInstalled){window.__logCaptureInstalled
|
||||
var relayPath = app.isPackaged
|
||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'relay.exe' : 'relay')
|
||||
: path.join(__dirname, '..', 'relay', process.platform === 'win32' ? 'relay.exe' : 'relay');
|
||||
var headlessPath = app.isPackaged
|
||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator')
|
||||
: path.join(__dirname, '..', 'headless', process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator');
|
||||
var headlessPath = app.isPackaged
|
||||
? path.join(process.resourcesPath, process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator')
|
||||
: path.join(__dirname, '..', 'headless', process.platform === 'win32' ? 'headless-creator.exe' : 'headless-creator');
|
||||
|
||||
var tabs = new Map(); // tabId -> { relay, tunnelMode, platform, dcPort, pionPort }
|
||||
var tabs = new Map(); // tabId -> { relay, tunnelMode, platform, dcPort, pionPort, isBot }
|
||||
var callStatusCache = new Map();
|
||||
var nextPortBase = 10000;
|
||||
var mainWindow = null;
|
||||
var botManager = null;
|
||||
@@ -68,6 +75,15 @@ function loadHook(url, tab) {
|
||||
return logCapture + 'window.WS_PORT=' + tab.dcPort + ';' + hook;
|
||||
}
|
||||
|
||||
async function getVKCookieString() {
|
||||
var ses = session.fromPartition('persist:creator');
|
||||
var all = await ses.cookies.get({});
|
||||
var vkCookies = all.filter(function(c) {
|
||||
return c.domain && (c.domain.indexOf('vk.com') !== -1 || c.domain.indexOf('vk.ru') !== -1);
|
||||
});
|
||||
return vkCookies.map(function(c) { return c.name + '=' + c.value; }).join('; ');
|
||||
}
|
||||
|
||||
function startRelay(tab) {
|
||||
killRelay(tab);
|
||||
var port = tab.tunnelMode.startsWith('pion') ? tab.pionPort : tab.dcPort;
|
||||
@@ -205,10 +221,26 @@ function createWindow() {
|
||||
botManager.sendMessage(foundPeerId, 'Call created!\n ' + link);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.indexOf('[CALL_STATUS]') !== -1) {
|
||||
console.log('[MAIN] Received call status:', msg);
|
||||
if (msg.indexOf(':') !== -1) {
|
||||
var parts = msg.split('[CALL_STATUS] ')[1];
|
||||
var colonIndex = parts.indexOf(':');
|
||||
if (colonIndex !== -1) {
|
||||
var tabId = parts.substring(0, colonIndex);
|
||||
var status = parts.substring(colonIndex + 1);
|
||||
callStatusCache.set(tabId, status);
|
||||
console.log('[MAIN] Cached status for', tabId, ':', status);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
wvContents.on('destroyed', function() {
|
||||
var ac = autoclickers.get(wvContents.id);
|
||||
if (ac) { ac.telemost.stop(); ac.vk.stop(); autoclickers.delete(wvContents.id); }
|
||||
callStatusCache.forEach(function(status, tabId) {
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -237,6 +269,38 @@ ipcMain.handle('start-relay', async function(e, tabId) {
|
||||
startRelay(tab);
|
||||
});
|
||||
|
||||
ipcMain.handle('start-headless', async function(e, tabId) {
|
||||
var tab = await getTab(tabId);
|
||||
tab.tunnelMode = 'headless-vk';
|
||||
var cookieStr = await getVKCookieString();
|
||||
if (!cookieStr) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: 'No VK cookies found. Please log into VK first.' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
killRelay(tab);
|
||||
var args = ['--cookie-string', cookieStr, '--resources', 'default'];
|
||||
var proc = spawn(headlessPath, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
tab.relay = proc;
|
||||
var onData = function(data) {
|
||||
data.toString().trim().split('\n').forEach(function(msg) {
|
||||
if (!msg) return;
|
||||
console.log('[headless:' + tabId + ']', msg);
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: msg });
|
||||
}
|
||||
});
|
||||
};
|
||||
proc.stdout.on('data', onData);
|
||||
proc.stderr.on('data', onData);
|
||||
proc.on('close', function(code) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('relay-log', { tabId: tabId, msg: 'Headless exited with code ' + code });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
ipcMain.handle('close-tab', function(e, tabId) {
|
||||
var tab = tabs.get(tabId);
|
||||
if (tab) {
|
||||
@@ -256,11 +320,35 @@ ipcMain.handle('start-bot', function(e, settings) {
|
||||
|
||||
var tabId = 'bot-tab-' + Date.now();
|
||||
var ports = await allocPorts();
|
||||
tabs.set(tabId, { relay: null, tunnelMode: tabConfig.mode, platform: tabConfig.platform || 'vk', dcPort: ports.dc, pionPort: ports.pion, peerId: tabConfig.peerId });
|
||||
tabs.set(tabId, { relay: null, tunnelMode: tabConfig.mode, platform: tabConfig.platform || 'vk', dcPort: ports.dc, pionPort: ports.pion, peerId: tabConfig.peerId, isBot: true });
|
||||
botTabs.add(tabId);
|
||||
|
||||
mainWindow.webContents.send('create-bot-tab', { tabId: tabId, mode: tabConfig.mode, peerId: tabConfig.peerId, platform: tabConfig.platform || 'vk' });
|
||||
console.log('[BOT] Created tab:', tabId, 'mode:', tabConfig.mode, 'platform:', tabConfig.platform, 'peerId:', tabConfig.peerId);
|
||||
}, function() {
|
||||
var result = [];
|
||||
tabs.forEach(function(tab, tabId) {
|
||||
result.push({
|
||||
id: tabId,
|
||||
platform: tab.platform,
|
||||
mode: tab.tunnelMode,
|
||||
isBot: tab.isBot === true,
|
||||
callStatus: callStatusCache.get(tabId) || 'inactive'
|
||||
});
|
||||
});
|
||||
return result;
|
||||
}, function(tabId) {
|
||||
var tab = tabs.get(tabId);
|
||||
if (tab) {
|
||||
killRelay(tab);
|
||||
tabs.delete(tabId);
|
||||
botTabs.delete(tabId);
|
||||
callStatusCache.delete(tabId);
|
||||
console.log('[BOT] Closed tab:', tabId);
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
mainWindow.webContents.send('close-bot-tab', { tabId: tabId });
|
||||
}
|
||||
}
|
||||
});
|
||||
botManager.onError = function(msg) {
|
||||
if (mainWindow && !mainWindow.isDestroyed()) {
|
||||
@@ -279,6 +367,17 @@ ipcMain.handle('stop-bot', function() {
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
ipcMain.handle('get-cookies', async function(e, domain) {
|
||||
var ses = session.fromPartition('persist:creator');
|
||||
var all = await ses.cookies.get({});
|
||||
var vkCookies = all.filter(function(c) {
|
||||
return c.domain && (c.domain.indexOf('vk.com') !== -1 || c.domain.indexOf('vk.ru') !== -1);
|
||||
});
|
||||
console.log('[COOKIES] total:', all.length, 'vk:', vkCookies.length);
|
||||
return vkCookies;
|
||||
});
|
||||
|
||||
|
||||
app.whenReady().then(createWindow);
|
||||
|
||||
app.on('window-all-closed', function() { killAllRelays(); app.quit(); });
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "whitelist-bypass-creator",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.9",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "whitelist-bypass-creator",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.9",
|
||||
"dependencies": {
|
||||
"node-fetch": "^2.7.0"
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "whitelist-bypass-creator",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.9",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"start": "electron .",
|
||||
@@ -29,7 +29,8 @@
|
||||
"target": "dmg",
|
||||
"icon": "resources/icon.icns",
|
||||
"extraResources": [
|
||||
{ "from": "../relay/relay-darwin", "to": "relay" }
|
||||
{ "from": "../relay/relay-darwin", "to": "relay" },
|
||||
{ "from": "../headless/headless-darwin", "to": "headless-creator" }
|
||||
]
|
||||
},
|
||||
"win": {
|
||||
@@ -37,14 +38,16 @@
|
||||
"artifactName": "${productName}-${version}-${arch}.${ext}",
|
||||
"icon": "resources/icon.ico",
|
||||
"extraResources": [
|
||||
{ "from": "../relay/relay-bundle.exe", "to": "relay.exe" }
|
||||
{ "from": "../relay/relay-bundle.exe", "to": "relay.exe" },
|
||||
{ "from": "../headless/headless-bundle.exe", "to": "headless-creator.exe" }
|
||||
]
|
||||
},
|
||||
"linux": {
|
||||
"target": "AppImage",
|
||||
"icon": "resources/icon.png",
|
||||
"extraResources": [
|
||||
{ "from": "../relay/relay-bundle", "to": "relay" }
|
||||
{ "from": "../relay/relay-bundle", "to": "relay" },
|
||||
{ "from": "../headless/headless-bundle", "to": "headless-creator" }
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,5 +10,8 @@ contextBridge.exposeInMainWorld('bridge', {
|
||||
stopBot: function() { return ipcRenderer.invoke('stop-bot'); },
|
||||
onCreateBotTab: function(cb) { ipcRenderer.on('create-bot-tab', function(e, data) { cb(data); }); },
|
||||
getCallCreatorCode: function(scriptFile) { return ipcRenderer.invoke('get-call-creator-code', scriptFile); },
|
||||
onBotError: function(cb) { ipcRenderer.on('bot-error', function(e, msg) { cb(msg); }); }
|
||||
onBotError: function(cb) { ipcRenderer.on('bot-error', function(e, msg) { cb(msg); }); },
|
||||
getCookies: function(domain) { return ipcRenderer.invoke('get-cookies', domain); },
|
||||
startHeadless: function(tabId) { return ipcRenderer.invoke('start-headless', tabId); },
|
||||
onCloseBotTab: function(cb) { ipcRenderer.on('close-bot-tab', function(e, data) { cb(data); }); }
|
||||
});
|
||||
@@ -36,6 +36,8 @@
|
||||
window.fetch = async (...args) => {
|
||||
const res = await origFetch(...args);
|
||||
|
||||
if (window.__CALL_LINK_CAPTURED__) return res;
|
||||
|
||||
try {
|
||||
const clone = res.clone();
|
||||
const text = await clone.text();
|
||||
@@ -52,6 +54,9 @@
|
||||
|
||||
console.log("[BOT] VKCalls: call link:", link);
|
||||
window.__CALL_LINK__ = link;
|
||||
|
||||
window.__CALL_LINK_CAPTURED__ = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,4 +84,4 @@
|
||||
start();
|
||||
}
|
||||
|
||||
})();
|
||||
})();
|
||||
@@ -0,0 +1,3 @@
|
||||
node_modules/
|
||||
jsdom/
|
||||
headless-creator
|
||||
@@ -0,0 +1,138 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type VKConfig struct {
|
||||
AppID string
|
||||
APIVersion string
|
||||
SDKVersion string
|
||||
AppVersion string
|
||||
ProtocolVersion string
|
||||
}
|
||||
|
||||
func fetchConfig() (VKConfig, error) {
|
||||
var cfg VKConfig
|
||||
|
||||
// Discover current bundle URL
|
||||
page, err := httpGet("https://vk.com")
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("failed to fetch vk.com: %w", err)
|
||||
}
|
||||
|
||||
bundleRe := regexp.MustCompile(`https://[a-z0-9.-]+/dist/core_spa/core_spa_vk\.[a-f0-9]+\.js`)
|
||||
bundleURL := bundleRe.FindString(string(page))
|
||||
if bundleURL == "" {
|
||||
snippet := string(page)
|
||||
if len(snippet) > 500 {
|
||||
snippet = snippet[:500]
|
||||
}
|
||||
return cfg, fmt.Errorf("bundle URL not found in page (length: %d): %s", len(page), snippet)
|
||||
}
|
||||
log.Printf("[config] Found bundle: %s", bundleURL)
|
||||
|
||||
bundle, err := httpGet(bundleURL)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("failed to fetch bundle: %w", err)
|
||||
}
|
||||
bundleStr := string(bundle)
|
||||
chunksBase := bundleURL[:strings.LastIndex(bundleURL, "core_spa_vk.")] + "chunks/"
|
||||
|
||||
// Extract app_id and API version from the main bundle
|
||||
if m := regexp.MustCompile(`[,;]u=(\d{7,8}),_=\d{7,8},p=\d{8,9}`).FindStringSubmatch(bundleStr); m != nil {
|
||||
cfg.AppID = m[1]
|
||||
} else {
|
||||
return cfg, fmt.Errorf("app_id not found in bundle")
|
||||
}
|
||||
if m := regexp.MustCompile(`\d+:\(e,t,n\)=>\{"use strict";n\.d\(t,\{m:\(\)=>r\}\);const r="(5\.\d+)"\}`).FindStringSubmatch(bundleStr); m != nil {
|
||||
cfg.APIVersion = m[1]
|
||||
} else {
|
||||
return cfg, fmt.Errorf("apiVersion not found in bundle")
|
||||
}
|
||||
log.Printf("[config] app_id=%s api=%s", cfg.AppID, cfg.APIVersion)
|
||||
|
||||
// Find webCallsBridge chunk
|
||||
bridgeRef := regexp.MustCompile(`core_spa/chunks/webCallsBridge\.([a-f0-9]+)\.js`).FindStringSubmatch(bundleStr)
|
||||
if bridgeRef == nil {
|
||||
return cfg, fmt.Errorf("webCallsBridge chunk not found in bundle")
|
||||
}
|
||||
bridgeURL := chunksBase + "webCallsBridge." + bridgeRef[1] + ".js"
|
||||
bridgeData, err := httpGet(bridgeURL)
|
||||
if err != nil {
|
||||
return cfg, fmt.Errorf("failed to fetch bridge chunk: %w", err)
|
||||
}
|
||||
bridgeStr := string(bridgeData)
|
||||
|
||||
// Extract module IDs imported by the bridge
|
||||
requireRe := regexp.MustCompile(`i\((\d{4,6})\)`)
|
||||
matches := requireRe.FindAllStringSubmatch(bridgeStr, -1)
|
||||
seen := map[string]bool{}
|
||||
var moduleIds []string
|
||||
for _, m := range matches {
|
||||
if !seen[m[1]] {
|
||||
seen[m[1]] = true
|
||||
moduleIds = append(moduleIds, m[1])
|
||||
}
|
||||
}
|
||||
|
||||
// Build chunk ID -> hash map from the bundle
|
||||
chunkMap := map[string]string{}
|
||||
chunkRe := regexp.MustCompile(`(\d+)===e\)return"core_spa/chunks/"\+e\+"\.([a-f0-9]+)\.js"`)
|
||||
for _, m := range chunkRe.FindAllStringSubmatch(bundleStr, -1) {
|
||||
chunkMap[m[1]] = m[2]
|
||||
}
|
||||
|
||||
// Match module IDs to chunk IDs, fetch until sdkVersion found
|
||||
sdkVerRe := regexp.MustCompile(`sdkVersion.{0,40}return\s*"([^"]+)"`)
|
||||
appVerRe := regexp.MustCompile(`appVersion.{0,40}return\s+([0-9.]+)`)
|
||||
protoVerRe := regexp.MustCompile(`protocolVersion.{0,40}return.*?(\d+)`)
|
||||
|
||||
for _, modId := range moduleIds {
|
||||
// try exact match, then with first digit dropped
|
||||
chunkId := modId
|
||||
hash, ok := chunkMap[chunkId]
|
||||
if !ok {
|
||||
chunkId = modId[1:]
|
||||
hash, ok = chunkMap[chunkId]
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
|
||||
chunkURL := fmt.Sprintf("%s%s.%s.js", chunksBase, chunkId, hash)
|
||||
chunkData, err := httpGet(chunkURL)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
chunkStr := string(chunkData)
|
||||
|
||||
sv := sdkVerRe.FindStringSubmatch(chunkStr)
|
||||
if sv == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
log.Printf("[config] Found SDK in chunk %s", chunkId)
|
||||
cfg.SDKVersion = sv[1]
|
||||
if av := appVerRe.FindStringSubmatch(chunkStr); av != nil {
|
||||
cfg.AppVersion = av[1]
|
||||
} else {
|
||||
log.Printf("[config] WARNING: appVersion not found in SDK chunk")
|
||||
}
|
||||
if pv := protoVerRe.FindStringSubmatch(chunkStr); pv != nil {
|
||||
cfg.ProtocolVersion = pv[1]
|
||||
} else {
|
||||
log.Printf("[config] WARNING: protocolVersion not found in SDK chunk")
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
if cfg.SDKVersion == "" {
|
||||
return cfg, fmt.Errorf("sdkVersion not found in any chunk")
|
||||
}
|
||||
log.Printf("[config] sdk=%s app=%s proto=%s", cfg.SDKVersion, cfg.AppVersion, cfg.ProtocolVersion)
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
module headless-creator
|
||||
|
||||
go 1.26.1
|
||||
|
||||
require github.com/gorilla/websocket v1.5.3
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/pion/datachannel v1.6.0 // indirect
|
||||
github.com/pion/dtls/v3 v3.1.2 // indirect
|
||||
github.com/pion/ice/v4 v4.2.2 // indirect
|
||||
github.com/pion/interceptor v0.1.44 // indirect
|
||||
github.com/pion/logging v0.2.4 // indirect
|
||||
github.com/pion/mdns/v2 v2.1.0 // indirect
|
||||
github.com/pion/randutil v0.1.0 // indirect
|
||||
github.com/pion/rtcp v1.2.16 // indirect
|
||||
github.com/pion/rtp v1.10.1 // indirect
|
||||
github.com/pion/sctp v1.9.4 // indirect
|
||||
github.com/pion/sdp/v3 v3.0.18 // indirect
|
||||
github.com/pion/srtp/v3 v3.0.10 // indirect
|
||||
github.com/pion/stun/v3 v3.1.1 // indirect
|
||||
github.com/pion/transport/v4 v4.0.1 // indirect
|
||||
github.com/pion/turn/v4 v4.1.4 // indirect
|
||||
github.com/pion/webrtc/v4 v4.2.11 // indirect
|
||||
github.com/wlynxg/anet v0.0.5 // indirect
|
||||
golang.org/x/crypto v0.48.0 // indirect
|
||||
golang.org/x/net v0.50.0 // indirect
|
||||
golang.org/x/sys v0.41.0 // indirect
|
||||
golang.org/x/time v0.10.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,46 @@
|
||||
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/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/pion/datachannel v1.6.0 h1:XecBlj+cvsxhAMZWFfFcPyUaDZtd7IJvrXqlXD/53i0=
|
||||
github.com/pion/datachannel v1.6.0/go.mod h1:ur+wzYF8mWdC+Mkis5Thosk+u/VOL287apDNEbFpsIk=
|
||||
github.com/pion/dtls/v3 v3.1.2 h1:gqEdOUXLtCGW+afsBLO0LtDD8GnuBBjEy6HRtyofZTc=
|
||||
github.com/pion/dtls/v3 v3.1.2/go.mod h1:Hw/igcX4pdY69z1Hgv5x7wJFrUkdgHwAn/Q/uo7YHRo=
|
||||
github.com/pion/ice/v4 v4.2.2 h1:dQJzzcgTFHDYyV3BoCfjPeX+JEtr58BWPi4PGyo6Vjg=
|
||||
github.com/pion/ice/v4 v4.2.2/go.mod h1:2quLV1S5v1tAx3VvAJaH//KGitRXvo4RKlX6D3tnN+c=
|
||||
github.com/pion/interceptor v0.1.44 h1:sNlZwM8dWXU9JQAkJh8xrarC0Etn8Oolcniukmuy0/I=
|
||||
github.com/pion/interceptor v0.1.44/go.mod h1:4atVlBkcgXuUP+ykQF0qOCGU2j7pQzX2ofvPRFsY5RY=
|
||||
github.com/pion/logging v0.2.4 h1:tTew+7cmQ+Mc1pTBLKH2puKsOvhm32dROumOZ655zB8=
|
||||
github.com/pion/logging v0.2.4/go.mod h1:DffhXTKYdNZU+KtJ5pyQDjvOAh/GsNSyv1lbkFbe3so=
|
||||
github.com/pion/mdns/v2 v2.1.0 h1:3IJ9+Xio6tWYjhN6WwuY142P/1jA0D5ERaIqawg/fOY=
|
||||
github.com/pion/mdns/v2 v2.1.0/go.mod h1:pcez23GdynwcfRU1977qKU0mDxSeucttSHbCSfFOd9A=
|
||||
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
|
||||
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
|
||||
github.com/pion/rtcp v1.2.16 h1:fk1B1dNW4hsI78XUCljZJlC4kZOPk67mNRuQ0fcEkSo=
|
||||
github.com/pion/rtcp v1.2.16/go.mod h1:/as7VKfYbs5NIb4h6muQ35kQF/J0ZVNz2Z3xKoCBYOo=
|
||||
github.com/pion/rtp v1.10.1 h1:xP1prZcCTUuhO2c83XtxyOHJteISg6o8iPsE2acaMtA=
|
||||
github.com/pion/rtp v1.10.1/go.mod h1:rF5nS1GqbR7H/TCpKwylzeq6yDM+MM6k+On5EgeThEM=
|
||||
github.com/pion/sctp v1.9.4 h1:cMxEu0F5tbP4qH07bKf1Zjf4rUih9LIo0qQt424e258=
|
||||
github.com/pion/sctp v1.9.4/go.mod h1:N20Dq6LY+JvJDAh9VVh1JELngb2rQ8dPgds5yBWiPgw=
|
||||
github.com/pion/sdp/v3 v3.0.18 h1:l0bAXazKHpepazVdp+tPYnrsy9dfh7ZbT8DxesH5ZnI=
|
||||
github.com/pion/sdp/v3 v3.0.18/go.mod h1:ZREGo6A9ZygQ9XkqAj5xYCQtQpif0i6Pa81HOiAdqQ8=
|
||||
github.com/pion/srtp/v3 v3.0.10 h1:tFirkpBb3XccP5VEXLi50GqXhv5SKPxqrdlhDCJlZrQ=
|
||||
github.com/pion/srtp/v3 v3.0.10/go.mod h1:3mOTIB0cq9qlbn59V4ozvv9ClW/BSEbRp4cY0VtaR7M=
|
||||
github.com/pion/stun/v3 v3.1.1 h1:CkQxveJ4xGQjulGSROXbXq94TAWu8gIX2dT+ePhUkqw=
|
||||
github.com/pion/stun/v3 v3.1.1/go.mod h1:qC1DfmcCTQjl9PBaMa5wSn3x9IPmKxSdcCsxBcDBndM=
|
||||
github.com/pion/transport/v4 v4.0.1 h1:sdROELU6BZ63Ab7FrOLn13M6YdJLY20wldXW2Cu2k8o=
|
||||
github.com/pion/transport/v4 v4.0.1/go.mod h1:nEuEA4AD5lPdcIegQDpVLgNoDGreqM/YqmEx3ovP4jM=
|
||||
github.com/pion/turn/v4 v4.1.4 h1:EU11yMXKIsK43FhcUnjLlrhE4nboHZq+TXBIi3QpcxQ=
|
||||
github.com/pion/turn/v4 v4.1.4/go.mod h1:ES1DXVFKnOhuDkqn9hn5VJlSWmZPaRJLyBXoOeO/BmQ=
|
||||
github.com/pion/webrtc/v4 v4.2.11 h1:QUX1QZKlNIn4O7U5JxLPGP0sV5RTncZkzu9SPR3jVNU=
|
||||
github.com/pion/webrtc/v4 v4.2.11/go.mod h1:s/rAiyy77GyRFrZMx+Ls6aua26dIBPudH8/ZHYbIRWY=
|
||||
github.com/wlynxg/anet v0.0.5 h1:J3VJGi1gvo0JwZ/P1/Yc/8p63SoW98B5dHkYDmpgvvU=
|
||||
github.com/wlynxg/anet v0.0.5/go.mod h1:eay5PRQr7fIVAMbTbchTnO9gG65Hg/uYGdc7mguHxoA=
|
||||
golang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=
|
||||
golang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=
|
||||
golang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=
|
||||
golang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=
|
||||
golang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=
|
||||
golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/time v0.10.0 h1:3usCWA8tQn0L8+hFJQNgzpWbd89begxN66o1Ojdn5L4=
|
||||
golang.org/x/time v0.10.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
|
||||
@@ -0,0 +1,565 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime/debug"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
const userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
const TopologyDirect = "DIRECT"
|
||||
|
||||
type Cookie struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
|
||||
type CallInfo struct {
|
||||
CallID string
|
||||
JoinLink string
|
||||
ShortLink string
|
||||
OKJoinLink string
|
||||
TurnServer TurnServer
|
||||
StunServer StunServer
|
||||
WSEndpoint string
|
||||
}
|
||||
|
||||
type TurnServer struct {
|
||||
URLs []string `json:"urls"`
|
||||
Username string `json:"username"`
|
||||
Credential string `json:"credential"`
|
||||
}
|
||||
|
||||
type StunServer struct {
|
||||
URLs []string `json:"urls"`
|
||||
}
|
||||
|
||||
func loadCookies(path string) string {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Fatalf("Cannot read cookies: %v", err)
|
||||
}
|
||||
var cookies []Cookie
|
||||
if err := json.Unmarshal(data, &cookies); err != nil {
|
||||
log.Fatalf("Cannot parse cookies: %v", err)
|
||||
}
|
||||
parts := make([]string, len(cookies))
|
||||
for i, c := range cookies {
|
||||
parts[i] = c.Name + "=" + c.Value
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
func httpPost(endpoint string, form url.Values, extraHeaders map[string]string) ([]byte, error) {
|
||||
body := form.Encode()
|
||||
req, err := http.NewRequest("POST", endpoint, strings.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
req.Header.Set("Origin", "https://vk.com")
|
||||
req.Header.Set("Referer", "https://vk.com/")
|
||||
for k, v := range extraHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
func httpGet(endpoint string) ([]byte, error) {
|
||||
req, err := http.NewRequest("GET", endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", userAgent)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if strings.Contains(resp.Request.URL.String(), "challenge") {
|
||||
return nil, fmt.Errorf("VK captcha required - open %s in browser and solve it", resp.Request.URL.String())
|
||||
}
|
||||
return io.ReadAll(resp.Body)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
auth := func(bearer string) map[string]string {
|
||||
return map[string]string{"Authorization": "Bearer " + bearer}
|
||||
}
|
||||
|
||||
log.Println("[auth] Getting VK token...")
|
||||
r, err := httpPost("https://login.vk.com/?act=web_token",
|
||||
url.Values{"version": {"1"}, "app_id": {cfg.AppID}},
|
||||
map[string]string{"Cookie": cookieStr})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("web_token: %w", err)
|
||||
}
|
||||
var tok struct {
|
||||
Data struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
json.Unmarshal(r, &tok)
|
||||
vkToken := tok.Data.AccessToken
|
||||
if vkToken == "" {
|
||||
return nil, fmt.Errorf("empty VK token, response: %s", string(r))
|
||||
}
|
||||
|
||||
log.Println("[auth] Getting call settings...")
|
||||
r, err = httpPost("https://api.vk.com/method/calls.getSettings",
|
||||
url.Values{"v": {cfg.APIVersion}}, auth(vkToken))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("calls.getSettings: %w", err)
|
||||
}
|
||||
var settings struct {
|
||||
Response struct {
|
||||
Settings struct {
|
||||
PublicKey string `json:"public_key"`
|
||||
IsDev bool `json:"is_dev"`
|
||||
} `json:"settings"`
|
||||
} `json:"response"`
|
||||
}
|
||||
json.Unmarshal(r, &settings)
|
||||
appKey := settings.Response.Settings.PublicKey
|
||||
if appKey == "" {
|
||||
return nil, fmt.Errorf("empty public_key, response: %s", string(r))
|
||||
}
|
||||
env := "production"
|
||||
if settings.Response.Settings.IsDev {
|
||||
env = "development"
|
||||
}
|
||||
|
||||
log.Printf("[auth] Creating call peer_id=%s...", peerId)
|
||||
r, err = httpPost("https://api.vk.com/method/calls.start",
|
||||
url.Values{"v": {cfg.APIVersion}, "peer_id": {peerId}}, auth(vkToken))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("calls.start: %w", err)
|
||||
}
|
||||
var call struct {
|
||||
Response struct {
|
||||
CallID string `json:"call_id"`
|
||||
JoinLink string `json:"join_link"`
|
||||
OKJoinLink string `json:"ok_join_link"`
|
||||
ShortCredentials struct {
|
||||
LinkWithPassword string `json:"link_with_password"`
|
||||
} `json:"short_credentials"`
|
||||
} `json:"response"`
|
||||
}
|
||||
json.Unmarshal(r, &call)
|
||||
c := call.Response
|
||||
if c.CallID == "" {
|
||||
return nil, fmt.Errorf("empty call_id, response: %s", string(r))
|
||||
}
|
||||
if c.OKJoinLink == "" {
|
||||
return nil, fmt.Errorf("empty ok_join_link, response: %s", string(r))
|
||||
}
|
||||
log.Printf("[auth] call_id: %s", c.CallID)
|
||||
log.Printf("[auth] join_link: %s", c.JoinLink)
|
||||
|
||||
log.Println("[auth] Getting call token...")
|
||||
r, err = httpPost("https://api.vk.com/method/messages.getCallToken",
|
||||
url.Values{"v": {cfg.APIVersion}, "env": {env}}, auth(vkToken))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("messages.getCallToken: %w", err)
|
||||
}
|
||||
var ct struct {
|
||||
Response struct {
|
||||
Token string `json:"token"`
|
||||
APIBaseURL string `json:"api_base_url"`
|
||||
} `json:"response"`
|
||||
}
|
||||
json.Unmarshal(r, &ct)
|
||||
if ct.Response.Token == "" {
|
||||
return nil, fmt.Errorf("empty call token, response: %s", string(r))
|
||||
}
|
||||
if ct.Response.APIBaseURL == "" {
|
||||
return nil, fmt.Errorf("empty api_base_url, response: %s", string(r))
|
||||
}
|
||||
|
||||
log.Println("[auth] OK.ru auth...")
|
||||
apiBaseURL := strings.TrimRight(ct.Response.APIBaseURL, "/")
|
||||
if !strings.HasSuffix(apiBaseURL, "/fb.do") {
|
||||
apiBaseURL += "/fb.do"
|
||||
}
|
||||
sd, _ := json.Marshal(map[string]interface{}{
|
||||
"device_id": "headless-go-1", "client_version": cfg.AppVersion,
|
||||
"client_type": "SDK_JS", "auth_token": ct.Response.Token, "version": 3,
|
||||
})
|
||||
r, err = httpPost(apiBaseURL, url.Values{
|
||||
"method": {"auth.anonymLogin"}, "application_key": {appKey},
|
||||
"format": {"json"}, "session_data": {string(sd)},
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("auth.anonymLogin: %w", err)
|
||||
}
|
||||
var okAuth struct {
|
||||
SessionKey string `json:"session_key"`
|
||||
}
|
||||
json.Unmarshal(r, &okAuth)
|
||||
if okAuth.SessionKey == "" {
|
||||
return nil, fmt.Errorf("empty session_key, response: %s", string(r))
|
||||
}
|
||||
|
||||
log.Println("[auth] Joining conversation...")
|
||||
ms, _ := json.Marshal(map[string]bool{
|
||||
"isAudioEnabled": false, "isVideoEnabled": true, "isScreenSharingEnabled": false,
|
||||
})
|
||||
r, err = httpPost(apiBaseURL, url.Values{
|
||||
"method": {"vchat.joinConversationByLink"}, "session_key": {okAuth.SessionKey},
|
||||
"application_key": {appKey}, "format": {"json"}, "joinLink": {c.OKJoinLink},
|
||||
"isVideo": {"true"}, "isAudio": {"false"}, "mediaSettings": {string(ms)},
|
||||
}, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("vchat.joinConversationByLink: %w", err)
|
||||
}
|
||||
var jr struct {
|
||||
Endpoint string `json:"endpoint"`
|
||||
TurnServer TurnServer `json:"turn_server"`
|
||||
StunServer StunServer `json:"stun_server"`
|
||||
}
|
||||
json.Unmarshal(r, &jr)
|
||||
if jr.Endpoint == "" {
|
||||
return nil, fmt.Errorf("empty WS endpoint, response: %s", string(r))
|
||||
}
|
||||
|
||||
return &CallInfo{
|
||||
CallID: c.CallID, JoinLink: c.JoinLink, ShortLink: c.ShortCredentials.LinkWithPassword,
|
||||
OKJoinLink: c.OKJoinLink, TurnServer: jr.TurnServer, StunServer: jr.StunServer,
|
||||
WSEndpoint: jr.Endpoint,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type Bridge struct {
|
||||
mu sync.Mutex
|
||||
vkWs *websocket.Conn
|
||||
vkSeq int
|
||||
iceServers []webrtc.ICEServer
|
||||
topology string
|
||||
peers map[int64]struct{}
|
||||
relay Relay
|
||||
newRelay func() Relay
|
||||
p2p *P2PHandler
|
||||
}
|
||||
|
||||
func (b *Bridge) vkSend(command string, extra map[string]interface{}) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
if b.vkWs == nil {
|
||||
return
|
||||
}
|
||||
b.vkSeq++
|
||||
seq := b.vkSeq
|
||||
// VK SFU requires command, sequence, participantId before data
|
||||
var out []byte
|
||||
if pid, ok := extra["participantId"]; ok {
|
||||
dataJSON, _ := json.Marshal(extra["data"])
|
||||
out = []byte(fmt.Sprintf(`{"command":%q,"sequence":%d,"participantId":%v,"data":%s}`,
|
||||
command, seq, pid, dataJSON))
|
||||
} else {
|
||||
// Non-transmit-data commands: just marshal normally with command+sequence first
|
||||
extra["command"] = command
|
||||
extra["sequence"] = seq
|
||||
out, _ = json.Marshal(extra)
|
||||
}
|
||||
b.vkWs.WriteMessage(websocket.TextMessage, out)
|
||||
log.Printf("[vk-ws] -> %s", command)
|
||||
}
|
||||
|
||||
func (b *Bridge) handleVKMessage(raw []byte) {
|
||||
var msg map[string]interface{}
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
msgType, _ := msg["type"].(string)
|
||||
switch msgType {
|
||||
case "notification":
|
||||
notif, _ := msg["notification"].(string)
|
||||
log.Printf("[vk-ws] <- notification: %s", notif)
|
||||
|
||||
switch notif {
|
||||
case "connection":
|
||||
log.Println("[vk-ws] TURN creds received")
|
||||
|
||||
case "transmitted-data":
|
||||
data, _ := msg["data"].(map[string]interface{})
|
||||
if data != nil && b.topology == TopologyDirect && b.p2p != nil {
|
||||
b.p2p.OnTransmittedData(data)
|
||||
}
|
||||
|
||||
case "registered-peer":
|
||||
pid, _ := msg["participantId"].(float64)
|
||||
if b.topology == TopologyDirect && b.p2p != nil {
|
||||
b.p2p.OnRegisteredPeer(int64(pid))
|
||||
}
|
||||
|
||||
case "topology-changed":
|
||||
topo, _ := msg["topology"].(string)
|
||||
log.Printf("[vk-ws] Topology changed to %s", topo)
|
||||
b.topology = topo
|
||||
if topo != TopologyDirect {
|
||||
log.Printf("[vk-ws] SFU not supported, kicking %d peers", len(b.peers))
|
||||
for pid := range b.peers {
|
||||
b.vkSend("remove-participant", map[string]interface{}{
|
||||
"participantId": pid,
|
||||
"ban": false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
case "participant-joined", "participant-added":
|
||||
if pid, ok := msg["participantId"].(float64); ok {
|
||||
b.peers[int64(pid)] = struct{}{}
|
||||
log.Printf("[vk-ws] Participant %d joined (total: %d)", int64(pid), len(b.peers))
|
||||
if b.topology != TopologyDirect {
|
||||
log.Printf("[vk-ws] Kicking peer %d (SFU topology)", int64(pid))
|
||||
b.vkSend("remove-participant", map[string]interface{}{
|
||||
"participantId": int64(pid),
|
||||
"ban": false,
|
||||
})
|
||||
log.Println("[FATAL] SFU topology is not supported, exiting")
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
case "participant-left":
|
||||
if pid, ok := msg["participantId"].(float64); ok {
|
||||
delete(b.peers, int64(pid))
|
||||
log.Printf("[vk-ws] Participant %d left (total: %d)", int64(pid), len(b.peers))
|
||||
}
|
||||
|
||||
case "hungup":
|
||||
if pid, ok := msg["participantId"].(float64); ok {
|
||||
delete(b.peers, int64(pid))
|
||||
log.Printf("[vk-ws] Participant %d hung up (total: %d)", int64(pid), len(b.peers))
|
||||
} else {
|
||||
log.Println("[vk-ws] Participant hung up")
|
||||
}
|
||||
|
||||
default:
|
||||
snippet, _ := json.Marshal(msg)
|
||||
if len(snippet) > 1000 {
|
||||
snippet = append(snippet[:1000], '.', '.', '.')
|
||||
}
|
||||
log.Printf("[vk-ws] unhandled: %s", string(snippet))
|
||||
}
|
||||
|
||||
case "response":
|
||||
seq, _ := msg["sequence"].(float64)
|
||||
snippet, _ := json.Marshal(msg)
|
||||
if len(snippet) > 1000 {
|
||||
snippet = append(snippet[:1000], '.', '.', '.')
|
||||
}
|
||||
log.Printf("[vk-ws] <- response seq=%d: %s", int(seq), string(snippet))
|
||||
|
||||
case "error":
|
||||
errMsg, _ := msg["message"].(string)
|
||||
errCode, _ := msg["error"].(string)
|
||||
log.Printf("[vk-ws] <- error: %s %s", errCode, errMsg)
|
||||
}
|
||||
}
|
||||
|
||||
func buildICEServers(callInfo *CallInfo) []webrtc.ICEServer {
|
||||
var servers []webrtc.ICEServer
|
||||
if len(callInfo.StunServer.URLs) > 0 {
|
||||
servers = append(servers, webrtc.ICEServer{URLs: callInfo.StunServer.URLs})
|
||||
}
|
||||
if len(callInfo.TurnServer.URLs) > 0 {
|
||||
urls := append([]string{}, callInfo.TurnServer.URLs...)
|
||||
urls = append(urls, urls[len(urls)-1]+"?transport=tcp")
|
||||
servers = append(servers, webrtc.ICEServer{
|
||||
URLs: urls, Username: callInfo.TurnServer.Username, Credential: callInfo.TurnServer.Credential,
|
||||
})
|
||||
}
|
||||
return servers
|
||||
}
|
||||
|
||||
func (b *Bridge) connectVKWs(wsURL string) error {
|
||||
vkHeader := http.Header{}
|
||||
vkHeader.Set("User-Agent", userAgent)
|
||||
vkHeader.Set("Origin", "https://vk.com")
|
||||
vkDialer := websocket.Dialer{WriteBufferSize: rtpBufSize}
|
||||
vkWs, _, err := vkDialer.Dial(wsURL, vkHeader)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
b.mu.Lock()
|
||||
b.vkWs = vkWs
|
||||
b.vkSeq = 0
|
||||
b.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *Bridge) initRelay() {
|
||||
if b.relay != nil {
|
||||
b.relay.Close()
|
||||
}
|
||||
b.topology = TopologyDirect
|
||||
b.peers = make(map[int64]struct{})
|
||||
b.relay = b.newRelay()
|
||||
b.p2p = NewP2PHandler(b)
|
||||
b.p2p.Init()
|
||||
}
|
||||
|
||||
func (b *Bridge) readLoop() error {
|
||||
for {
|
||||
_, msg, err := b.vkWs.ReadMessage()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if string(msg) == "ping" {
|
||||
b.vkWs.WriteMessage(websocket.TextMessage, []byte("pong"))
|
||||
continue
|
||||
}
|
||||
b.handleVKMessage(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *Bridge) run(callInfo *CallInfo, cfg VKConfig) {
|
||||
fmt.Println("")
|
||||
fmt.Println(" CALL CREATED")
|
||||
fmt.Println(" join_link:", callInfo.JoinLink)
|
||||
if callInfo.ShortLink != "" {
|
||||
fmt.Println(" short: ", callInfo.ShortLink)
|
||||
}
|
||||
fmt.Println(" TURN: ", strings.Join(callInfo.TurnServer.URLs, ", "))
|
||||
fmt.Printf(" protocol: v%s sdk %s\n\n", cfg.ProtocolVersion, cfg.SDKVersion)
|
||||
|
||||
b.iceServers = buildICEServers(callInfo)
|
||||
|
||||
wsURL := callInfo.WSEndpoint +
|
||||
"&platform=WEB" +
|
||||
"&appVersion=" + cfg.AppVersion +
|
||||
"&version=" + cfg.ProtocolVersion +
|
||||
"&device=browser&capabilities=0&clientType=VK&tgt=join"
|
||||
|
||||
// Keepalive goroutine
|
||||
go func() {
|
||||
for {
|
||||
time.Sleep(15 * time.Second)
|
||||
b.mu.Lock()
|
||||
ws := b.vkWs
|
||||
b.mu.Unlock()
|
||||
if ws != nil {
|
||||
ws.WriteMessage(websocket.PingMessage, nil)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
for {
|
||||
b.initRelay()
|
||||
|
||||
log.Println("[vk-ws] Connecting...")
|
||||
if err := b.connectVKWs(wsURL); err != nil {
|
||||
log.Printf("[vk-ws] Connect failed: %v, retrying in 5s...", err)
|
||||
time.Sleep(5 * time.Second)
|
||||
continue
|
||||
}
|
||||
log.Println("[vk-ws] Connected")
|
||||
|
||||
b.vkSend("change-media-settings", map[string]interface{}{
|
||||
"mediaSettings": map[string]interface{}{
|
||||
"isAudioEnabled": false, "isVideoEnabled": true,
|
||||
"isScreenSharingEnabled": false, "isFastScreenSharingEnabled": false,
|
||||
"isAudioSharingEnabled": false, "isAnimojiEnabled": false,
|
||||
},
|
||||
})
|
||||
|
||||
err := b.readLoop()
|
||||
log.Printf("[vk-ws] Closed: %v", err)
|
||||
|
||||
b.mu.Lock()
|
||||
b.vkWs = nil
|
||||
b.mu.Unlock()
|
||||
|
||||
log.Println("[vk-ws] Reconnecting in 3s...")
|
||||
time.Sleep(3 * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
flag.Parse()
|
||||
|
||||
var readBuf int
|
||||
var maxDCBuf uint64
|
||||
var memLimit int64
|
||||
switch *resources {
|
||||
case "moderate":
|
||||
readBuf = 16384
|
||||
maxDCBuf = 1 * 1024 * 1024
|
||||
memLimit = 64 * 1024 * 1024
|
||||
case "default":
|
||||
readBuf = 32768
|
||||
maxDCBuf = 4 * 1024 * 1024
|
||||
memLimit = 128 * 1024 * 1024
|
||||
case "unlimited":
|
||||
readBuf = rtpBufSize
|
||||
maxDCBuf = 8 * 1024 * 1024
|
||||
memLimit = 256 * 1024 * 1024
|
||||
default:
|
||||
log.Fatalf("[config] unknown resources mode: %s (use moderate, default, unlimited)", *resources)
|
||||
}
|
||||
if memLimit > 0 {
|
||||
debug.SetMemoryLimit(memLimit)
|
||||
}
|
||||
log.Printf("[config] resources=%s read-buf=%d max-dc-buf=%d mem-limit=%d", *resources, readBuf, maxDCBuf, memLimit)
|
||||
|
||||
var cookieStr string
|
||||
if *cookieString != "" {
|
||||
cookieStr = *cookieString
|
||||
} else if *cookiesPath != "" {
|
||||
cookieStr = loadCookies(*cookiesPath)
|
||||
} else {
|
||||
log.Fatal("Either --cookies or --cookie-string is required")
|
||||
}
|
||||
|
||||
log.Println("[config] Fetching live config from VK bundle...")
|
||||
cfg, err := fetchConfig()
|
||||
if err != nil {
|
||||
log.Fatalf("[config] %v", err)
|
||||
}
|
||||
|
||||
callInfo, err := createAndJoinCall(cookieStr, *peerId, cfg)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to create call: %v", err)
|
||||
}
|
||||
|
||||
bridge := &Bridge{}
|
||||
bridge.newRelay = func() Relay {
|
||||
ur := NewTunnelRelay()
|
||||
ur.readBufSize = readBuf
|
||||
ur.maxDCBuf = maxDCBuf
|
||||
ur.OnConnected = func(tunnel *VP8DataTunnel) {
|
||||
NewRelayBridge(tunnel, "creator", log.Printf)
|
||||
}
|
||||
return ur
|
||||
}
|
||||
bridge.run(callInfo, cfg)
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// maskAddr masks the sensitive portion of an address for logging.
|
||||
// IPv4: keeps first two octets, e.g. "192.168.x.x"
|
||||
// IPv6: fully masked
|
||||
// hostname: first char + "***"
|
||||
// host:port: masks host, keeps port
|
||||
func maskAddr(addr string) string {
|
||||
host, port, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
host = addr
|
||||
port = ""
|
||||
}
|
||||
masked := maskHost(host)
|
||||
if port != "" {
|
||||
return net.JoinHostPort(masked, port)
|
||||
}
|
||||
return masked
|
||||
}
|
||||
|
||||
func maskHost(host string) string {
|
||||
if host == "" {
|
||||
return ""
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip != nil {
|
||||
if ip4 := ip.To4(); ip4 != nil {
|
||||
return fmt.Sprintf("%d.%d.x.x", ip4[0], ip4[1])
|
||||
}
|
||||
return "x::x"
|
||||
}
|
||||
if len(host) <= 1 {
|
||||
return "*"
|
||||
}
|
||||
return string(host[0]) + "***"
|
||||
}
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
interval="${1:-5}"
|
||||
printf "%-8s %-20s %10s %6s %6s\n" "TIME" "PROCESS" "RSS(MB)" "THR" "FD"
|
||||
echo "-------------------------------------------------------"
|
||||
while true; do
|
||||
pids=$(pgrep -f "headless-creator" 2>/dev/null)
|
||||
if [ -z "$pids" ]; then
|
||||
printf "%-8s %s\n" "$(date +%H:%M:%S)" "no processes found"
|
||||
else
|
||||
for pid in $pids; do
|
||||
name=$(ps -o comm= -p "$pid" 2>/dev/null | xargs basename 2>/dev/null)
|
||||
rss=$(ps -o rss= -p "$pid" 2>/dev/null | tr -d ' ')
|
||||
rss_mb=$(awk "BEGIN{printf \"%.3f\", $rss/1024}")
|
||||
thr=$(ps -M "$pid" 2>/dev/null | tail -n +2 | wc -l | tr -d ' ')
|
||||
fd=$(lsof -p "$pid" 2>/dev/null | wc -l | tr -d ' ')
|
||||
printf "%-8s %-20s %10s %6s %6s\n" "$(date +%H:%M:%S)" "$name($pid)" "${rss_mb}" "$thr" "$fd"
|
||||
done
|
||||
fi
|
||||
echo ""
|
||||
sleep "$interval"
|
||||
done
|
||||
+203
@@ -0,0 +1,203 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
type P2PHandler struct {
|
||||
bridge *Bridge
|
||||
remotePeerId *int64
|
||||
pendingOffer *webrtc.SessionDescription
|
||||
pendingCandidates []webrtc.ICECandidateInit
|
||||
connected bool
|
||||
}
|
||||
|
||||
func NewP2PHandler(bridge *Bridge) *P2PHandler {
|
||||
return &P2PHandler{bridge: bridge}
|
||||
}
|
||||
|
||||
func (p *P2PHandler) setupCallbacks() {
|
||||
p.bridge.relay.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
return
|
||||
}
|
||||
log.Printf("[p2p] ICE candidate: type=%s proto=%s", cand.Typ.String(), cand.Protocol.String())
|
||||
candJSON := cand.ToJSON()
|
||||
raw, _ := json.Marshal(candJSON)
|
||||
p.OnPionICECandidate(raw)
|
||||
})
|
||||
|
||||
p.bridge.relay.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
p.OnConnectionState(state.String())
|
||||
})
|
||||
}
|
||||
|
||||
// Init creates the initial Pion PC and offer.
|
||||
func (p *P2PHandler) Init() {
|
||||
relay := p.bridge.relay
|
||||
if err := relay.Init(p.bridge.iceServers); err != nil {
|
||||
log.Fatalf("[p2p] Init relay failed: %v", err)
|
||||
}
|
||||
p.setupCallbacks()
|
||||
|
||||
offer, err := relay.CreateOffer()
|
||||
if err != nil {
|
||||
log.Fatalf("[p2p] Create offer failed: %v", err)
|
||||
}
|
||||
p.pendingOffer = &offer
|
||||
log.Printf("[p2p] Offer ready, SDP length: %d", len(offer.SDP))
|
||||
}
|
||||
|
||||
// Reset tears down the current Pion PC and creates a fresh one with a new offer.
|
||||
func (p *P2PHandler) Reset() {
|
||||
log.Println("[p2p] Resetting Pion PC...")
|
||||
p.connected = false
|
||||
|
||||
p.bridge.relay.Close()
|
||||
p.bridge.relay = p.bridge.newRelay()
|
||||
|
||||
relay := p.bridge.relay
|
||||
if err := relay.Init(p.bridge.iceServers); err != nil {
|
||||
log.Printf("[p2p] Reset init failed: %v", err)
|
||||
return
|
||||
}
|
||||
p.setupCallbacks()
|
||||
|
||||
offer, err := relay.CreateOffer()
|
||||
if err != nil {
|
||||
log.Printf("[p2p] Reset create-offer failed: %v", err)
|
||||
return
|
||||
}
|
||||
p.pendingOffer = &offer
|
||||
p.pendingCandidates = nil
|
||||
log.Printf("[p2p] New offer ready after reset, SDP length: %d", len(offer.SDP))
|
||||
}
|
||||
|
||||
// OnRegisteredPeer handles the registered-peer notification.
|
||||
func (p *P2PHandler) OnRegisteredPeer(participantId int64) {
|
||||
oldPeer := p.remotePeerId
|
||||
p.remotePeerId = &participantId
|
||||
|
||||
log.Printf("[p2p] Peer registered: %d (connected=%v)", participantId, p.connected)
|
||||
|
||||
if oldPeer != nil && (p.pendingOffer == nil) {
|
||||
if *oldPeer != participantId {
|
||||
log.Printf("[p2p] New peer %d replacing old peer %d, resetting", participantId, *oldPeer)
|
||||
} else {
|
||||
log.Printf("[p2p] Same peer %d re-registered, no pending offer, resetting", participantId)
|
||||
}
|
||||
p.Reset()
|
||||
}
|
||||
|
||||
p.sendOfferToPeer(participantId)
|
||||
}
|
||||
|
||||
// OnTransmittedData handles SDP and ICE candidates from the remote peer.
|
||||
func (p *P2PHandler) OnTransmittedData(data map[string]interface{}) {
|
||||
if cand, ok := data["candidate"]; ok {
|
||||
log.Println("[p2p] Remote ICE candidate")
|
||||
candJSON, _ := json.Marshal(cand)
|
||||
var candInit webrtc.ICECandidateInit
|
||||
json.Unmarshal(candJSON, &candInit)
|
||||
p.bridge.relay.AddICECandidate(candInit)
|
||||
}
|
||||
if sdp, ok := data["sdp"].(map[string]interface{}); ok {
|
||||
sdpType, _ := sdp["type"].(string)
|
||||
sdpStr, _ := sdp["sdp"].(string)
|
||||
log.Printf("[p2p] Remote SDP: %s", sdpType)
|
||||
if sdpType == "answer" {
|
||||
p.bridge.relay.SetRemoteDescription(webrtc.SDPTypeAnswer, sdpStr)
|
||||
} else if sdpType == "offer" {
|
||||
p.bridge.relay.SetRemoteDescription(webrtc.SDPTypeOffer, sdpStr)
|
||||
answer, err := p.bridge.relay.CreateAnswer()
|
||||
if err == nil && p.remotePeerId != nil {
|
||||
p.bridge.vkSend("transmit-data", map[string]interface{}{
|
||||
"participantId": *p.remotePeerId,
|
||||
"data": map[string]interface{}{"sdp": map[string]interface{}{
|
||||
"type": answer.Type.String(), "sdp": answer.SDP,
|
||||
}},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// OnPionICECandidate handles an ICE candidate from the local Pion PC.
|
||||
func (p *P2PHandler) OnPionICECandidate(data json.RawMessage) {
|
||||
if p.remotePeerId != nil {
|
||||
var cand interface{}
|
||||
json.Unmarshal(data, &cand)
|
||||
p.bridge.vkSend("transmit-data", map[string]interface{}{
|
||||
"participantId": *p.remotePeerId,
|
||||
"data": map[string]interface{}{"candidate": cand},
|
||||
})
|
||||
} else {
|
||||
var candInit webrtc.ICECandidateInit
|
||||
json.Unmarshal(data, &candInit)
|
||||
p.pendingCandidates = append(p.pendingCandidates, candInit)
|
||||
}
|
||||
}
|
||||
|
||||
// OnConnectionState updates P2P connection state.
|
||||
func (p *P2PHandler) OnConnectionState(state string) {
|
||||
switch state {
|
||||
case "connected":
|
||||
p.connected = true
|
||||
log.Println("\n TUNNEL CONNECTED\n")
|
||||
case "disconnected":
|
||||
p.connected = false
|
||||
log.Println("[p2p] Connection disconnected, waiting for peer to rejoin")
|
||||
case "failed":
|
||||
p.connected = false
|
||||
log.Println("[p2p] Connection failed, removing stale peer")
|
||||
if p.remotePeerId != nil {
|
||||
p.bridge.vkSend("remove-participant", map[string]interface{}{
|
||||
"participantId": *p.remotePeerId,
|
||||
"ban": false,
|
||||
})
|
||||
}
|
||||
case "closed":
|
||||
p.connected = false
|
||||
log.Println("[p2p] Connection closed")
|
||||
}
|
||||
}
|
||||
|
||||
func (p *P2PHandler) sendOfferToPeer(participantId int64) {
|
||||
offer := p.pendingOffer
|
||||
candidates := p.pendingCandidates
|
||||
p.pendingOffer = nil
|
||||
p.pendingCandidates = nil
|
||||
|
||||
if offer != nil {
|
||||
log.Printf("[p2p] Sending offer to peer %d", participantId)
|
||||
sdpStr, _ := json.Marshal(offer.SDP)
|
||||
p.bridge.mu.Lock()
|
||||
p.bridge.vkSeq++
|
||||
seq := p.bridge.vkSeq
|
||||
raw := fmt.Sprintf(`{"command":"transmit-data","sequence":%d,"participantId":%d,"data":{"sdp":{"type":%q,"sdp":%s}}}`,
|
||||
seq, participantId, offer.Type.String(), sdpStr)
|
||||
if p.bridge.vkWs != nil {
|
||||
p.bridge.vkWs.WriteMessage(websocket.TextMessage, []byte(raw))
|
||||
}
|
||||
p.bridge.mu.Unlock()
|
||||
log.Printf("[vk-ws] -> transmit-data (offer)")
|
||||
}
|
||||
|
||||
for _, cand := range candidates {
|
||||
candJSON, _ := json.Marshal(cand)
|
||||
var c interface{}
|
||||
json.Unmarshal(candJSON, &c)
|
||||
p.bridge.vkSend("transmit-data", map[string]interface{}{
|
||||
"participantId": participantId,
|
||||
"data": map[string]interface{}{"candidate": c},
|
||||
})
|
||||
}
|
||||
if len(candidates) > 0 {
|
||||
log.Printf("[p2p] Flushed %d ICE candidates", len(candidates))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package main
|
||||
|
||||
import "github.com/pion/webrtc/v4"
|
||||
|
||||
// Tunnel frame protocol constants shared between DC and video relay paths.
|
||||
// Frame format: connID(4) + msgType(1) + payload
|
||||
const (
|
||||
msgConnect byte = 0x01
|
||||
msgConnectOK byte = 0x02
|
||||
msgConnectErr byte = 0x03
|
||||
msgData byte = 0x04
|
||||
msgClose byte = 0x05
|
||||
msgUDP byte = 0x06
|
||||
msgUDPReply byte = 0x07
|
||||
|
||||
socksVer = 0x05
|
||||
socksCmdTCP = 0x01
|
||||
socksCmdUDP = 0x03
|
||||
socksAtypIPv4 = 0x01
|
||||
socksAtypDomain = 0x03
|
||||
socksAtypIPv6 = 0x04
|
||||
|
||||
socksHandshakeBuf = 258
|
||||
udpBufSize = 4096
|
||||
rtpBufSize = 65536
|
||||
vp8RelayBufSize = 900
|
||||
)
|
||||
|
||||
var (
|
||||
socksNoAuth = []byte{socksVer, 0x00}
|
||||
socksOK = []byte{socksVer, 0x00, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
socksConnFail = []byte{socksVer, 0x05, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
socksCmdErr = []byte{socksVer, 0x07, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
socksAddrErr = []byte{socksVer, 0x08, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
socksGenFail = []byte{socksVer, 0x01, 0x00, socksAtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
)
|
||||
|
||||
// Relay is the common interface for DCRelay and VideoRelay.
|
||||
type Relay interface {
|
||||
Init(iceServers []webrtc.ICEServer) error
|
||||
CreateOffer() (webrtc.SessionDescription, error)
|
||||
CreateAnswer() (webrtc.SessionDescription, error)
|
||||
SetRemoteDescription(sdpType webrtc.SDPType, sdp string) error
|
||||
AddICECandidate(candidate webrtc.ICECandidateInit) error
|
||||
OnICECandidate(fn func(*webrtc.ICECandidate))
|
||||
OnConnectionStateChange(fn func(webrtc.PeerConnectionState))
|
||||
Close()
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"log"
|
||||
"net"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
)
|
||||
|
||||
type dcConn struct {
|
||||
conn net.Conn
|
||||
ch chan []byte
|
||||
}
|
||||
|
||||
type TunnelRelay struct {
|
||||
pc *webrtc.PeerConnection
|
||||
remoteSet bool
|
||||
pending []webrtc.ICECandidateInit
|
||||
externalICE func(*webrtc.ICECandidate)
|
||||
externalCSC func(webrtc.PeerConnectionState)
|
||||
|
||||
dc *webrtc.DataChannel
|
||||
dcMu sync.Mutex
|
||||
conns sync.Map
|
||||
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
tunnel *VP8DataTunnel
|
||||
OnConnected func(*VP8DataTunnel)
|
||||
|
||||
readBufSize int
|
||||
maxDCBuf uint64
|
||||
|
||||
mode string
|
||||
modeOnce sync.Once
|
||||
}
|
||||
|
||||
func NewTunnelRelay() *TunnelRelay {
|
||||
return &TunnelRelay{mode: "unknown"}
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) Init(iceServers []webrtc.ICEServer) error {
|
||||
pc, err := webrtc.NewPeerConnection(webrtc.Configuration{ICEServers: iceServers})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.pc = pc
|
||||
|
||||
negotiated := true
|
||||
dcID := uint16(2)
|
||||
dc, err := pc.CreateDataChannel("tunnel", &webrtc.DataChannelInit{
|
||||
Negotiated: &negotiated,
|
||||
ID: &dcID,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("[relay] warning: could not create tunnel DC: %v", err)
|
||||
} else {
|
||||
u.dc = dc
|
||||
dc.OnOpen(func() {
|
||||
log.Printf("[relay] tunnel DC open (readyState=%v)", dc.ReadyState())
|
||||
})
|
||||
dc.OnClose(func() {
|
||||
log.Println("[relay] tunnel DC closed")
|
||||
if u.mode == "dc" {
|
||||
u.closeAllConns()
|
||||
}
|
||||
})
|
||||
dc.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
u.modeOnce.Do(func() {
|
||||
u.mode = "dc"
|
||||
log.Println("[relay] === MODE: DC ===")
|
||||
})
|
||||
u.handleDCMessage(msg.Data)
|
||||
})
|
||||
}
|
||||
|
||||
sampleTrack, _ := webrtc.NewTrackLocalStaticSample(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeVP8},
|
||||
"video", "tunnel-video",
|
||||
)
|
||||
u.sampleTrack = sampleTrack
|
||||
|
||||
audioTrack, _ := webrtc.NewTrackLocalStaticRTP(
|
||||
webrtc.RTPCodecCapability{MimeType: webrtc.MimeTypeOpus},
|
||||
"audio", "tunnel-audio",
|
||||
)
|
||||
pc.AddTrack(audioTrack)
|
||||
pc.AddTrack(sampleTrack)
|
||||
|
||||
ordered := true
|
||||
dcNotif, err := pc.CreateDataChannel("producerNotification", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
if err == nil {
|
||||
dcNotif.OnOpen(func() { log.Println("[relay] producerNotification DC opened") })
|
||||
dcNotif.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
log.Printf("[relay] producerNotification msg len=%d", len(msg.Data))
|
||||
})
|
||||
}
|
||||
dcCmd, err := pc.CreateDataChannel("producerCommand", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
if err == nil {
|
||||
dcCmd.OnOpen(func() { log.Println("[relay] producerCommand DC opened") })
|
||||
dcCmd.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
log.Printf("[relay] producerCommand msg len=%d", len(msg.Data))
|
||||
})
|
||||
}
|
||||
pc.CreateDataChannel("producerScreenShare", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
pc.CreateDataChannel("consumerScreenShare", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
|
||||
pc.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
return
|
||||
}
|
||||
if u.externalICE != nil {
|
||||
u.externalICE(cand)
|
||||
}
|
||||
})
|
||||
|
||||
pc.OnConnectionStateChange(func(state webrtc.PeerConnectionState) {
|
||||
log.Printf("[relay] connection state: %s (mode=%s)", state.String(), u.mode)
|
||||
if u.externalCSC != nil {
|
||||
u.externalCSC(state)
|
||||
}
|
||||
})
|
||||
|
||||
pc.OnTrack(func(track *webrtc.TrackRemote, receiver *webrtc.RTPReceiver) {
|
||||
log.Printf("[relay] remote track: %s", track.Codec().MimeType)
|
||||
u.modeOnce.Do(func() {
|
||||
u.mode = "video"
|
||||
log.Println("[relay] === MODE: VIDEO ===")
|
||||
u.tunnel = NewVP8DataTunnel(sampleTrack, log.Printf)
|
||||
u.tunnel.Start(25)
|
||||
if u.OnConnected != nil {
|
||||
u.OnConnected(u.tunnel)
|
||||
}
|
||||
})
|
||||
go u.readTrack(track)
|
||||
})
|
||||
|
||||
log.Printf("[relay] PC created (%d ICE servers)", len(iceServers))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) CreateOffer() (webrtc.SessionDescription, error) {
|
||||
offer, err := u.pc.CreateOffer(nil)
|
||||
if err != nil {
|
||||
return offer, err
|
||||
}
|
||||
u.pc.SetLocalDescription(offer)
|
||||
return offer, nil
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) CreateAnswer() (webrtc.SessionDescription, error) {
|
||||
answer, err := u.pc.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
return answer, err
|
||||
}
|
||||
u.pc.SetLocalDescription(answer)
|
||||
return answer, nil
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) SetRemoteDescription(sdpType webrtc.SDPType, sdp string) error {
|
||||
err := u.pc.SetRemoteDescription(webrtc.SessionDescription{Type: sdpType, SDP: sdp})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
u.remoteSet = true
|
||||
for _, cand := range u.pending {
|
||||
u.pc.AddICECandidate(cand)
|
||||
}
|
||||
u.pending = nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) AddICECandidate(candidate webrtc.ICECandidateInit) error {
|
||||
if !u.remoteSet {
|
||||
u.pending = append(u.pending, candidate)
|
||||
return nil
|
||||
}
|
||||
return u.pc.AddICECandidate(candidate)
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) OnICECandidate(fn func(*webrtc.ICECandidate)) {
|
||||
u.externalICE = fn
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) OnConnectionStateChange(fn func(webrtc.PeerConnectionState)) {
|
||||
u.externalCSC = fn
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) Close() {
|
||||
u.closeAllConns()
|
||||
if u.tunnel != nil {
|
||||
u.tunnel.Stop()
|
||||
u.tunnel = nil
|
||||
}
|
||||
u.dcMu.Lock()
|
||||
u.dc = nil
|
||||
u.dcMu.Unlock()
|
||||
if u.pc != nil {
|
||||
u.pc.OnConnectionStateChange(nil)
|
||||
u.pc.OnICECandidate(nil)
|
||||
u.pc.OnTrack(nil)
|
||||
oldPC := u.pc
|
||||
u.pc = nil
|
||||
go oldPC.Close()
|
||||
}
|
||||
u.remoteSet = false
|
||||
u.pending = nil
|
||||
u.sampleTrack = nil
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) handleDCMessage(data []byte) {
|
||||
if len(data) < 5 {
|
||||
return
|
||||
}
|
||||
connID := binary.BigEndian.Uint32(data[0:4])
|
||||
mt := data[4]
|
||||
payload := data[5:]
|
||||
|
||||
switch mt {
|
||||
case msgConnect:
|
||||
go u.connectTCP(connID, string(payload))
|
||||
case msgUDP:
|
||||
go u.handleUDP(connID, payload)
|
||||
case msgData:
|
||||
val, ok := u.conns.Load(connID)
|
||||
if ok {
|
||||
dc := val.(*dcConn)
|
||||
cp := make([]byte, len(payload))
|
||||
copy(cp, payload)
|
||||
select {
|
||||
case dc.ch <- cp:
|
||||
default:
|
||||
log.Printf("[dc] conn %d write queue full, dropping %d bytes", connID, len(payload))
|
||||
}
|
||||
}
|
||||
case msgClose:
|
||||
val, ok := u.conns.LoadAndDelete(connID)
|
||||
if ok {
|
||||
dc := val.(*dcConn)
|
||||
close(dc.ch)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) sendDCFrame(connID uint32, mt byte, payload []byte) {
|
||||
u.dcMu.Lock()
|
||||
defer u.dcMu.Unlock()
|
||||
if u.dc == nil {
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 5+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], connID)
|
||||
buf[4] = mt
|
||||
copy(buf[5:], payload)
|
||||
u.dc.Send(buf)
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) connectTCP(connID uint32, addr string) {
|
||||
log.Printf("[dc] CONNECT %d -> %s", connID, maskAddr(addr))
|
||||
conn, err := net.DialTimeout("tcp", addr, 10*time.Second)
|
||||
if err != nil {
|
||||
log.Printf("[dc] CONNECT %d failed: %v", connID, err)
|
||||
u.sendDCFrame(connID, msgConnectErr, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
dc := &dcConn{conn: conn, ch: make(chan []byte, 256)}
|
||||
u.conns.Store(connID, dc)
|
||||
u.sendDCFrame(connID, msgConnectOK, nil)
|
||||
log.Printf("[dc] CONNECTED %d -> %s", connID, maskAddr(addr))
|
||||
|
||||
go func() {
|
||||
for data := range dc.ch {
|
||||
conn.Write(data)
|
||||
}
|
||||
conn.Close()
|
||||
}()
|
||||
|
||||
bufSz := u.readBufSize
|
||||
if bufSz <= 0 {
|
||||
bufSz = rtpBufSize
|
||||
}
|
||||
buf := make([]byte, bufSz)
|
||||
sent := 0
|
||||
for {
|
||||
if u.maxDCBuf > 0 {
|
||||
u.dcMu.Lock()
|
||||
dc := u.dc
|
||||
u.dcMu.Unlock()
|
||||
if dc != nil {
|
||||
for dc.BufferedAmount() > u.maxDCBuf {
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
u.sendDCFrame(connID, msgData, buf[:n])
|
||||
sent += n
|
||||
}
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
log.Printf("[dc] conn %d read error: %v", connID, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
log.Printf("[dc] conn %d closed, sent %d bytes", connID, sent)
|
||||
u.sendDCFrame(connID, msgClose, nil)
|
||||
u.conns.Delete(connID)
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) handleUDP(connID uint32, payload []byte) {
|
||||
if len(payload) < 2 {
|
||||
return
|
||||
}
|
||||
addrLen := int(payload[0])
|
||||
if len(payload) < 1+addrLen {
|
||||
return
|
||||
}
|
||||
addr := string(payload[1 : 1+addrLen])
|
||||
data := payload[1+addrLen:]
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
resp := make([]byte, udpBufSize)
|
||||
n, err := conn.Read(resp)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
u.sendDCFrame(connID, msgUDPReply, resp[:n])
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) closeAllConns() {
|
||||
u.conns.Range(func(key, val any) bool {
|
||||
dc := val.(*dcConn)
|
||||
dc.conn.Close()
|
||||
u.conns.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (u *TunnelRelay) readTrack(track *webrtc.TrackRemote) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
buf := make([]byte, udpBufSize)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var vp8Pkt codecs.VP8Packet
|
||||
var frameBuf []byte
|
||||
var dataCount, recvCount int
|
||||
buf := make([]byte, rtpBufSize)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
pkt := &rtp.Packet{}
|
||||
if pkt.Unmarshal(buf[:n]) != nil {
|
||||
continue
|
||||
}
|
||||
vp8Payload, err := vp8Pkt.Unmarshal(pkt.Payload)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if vp8Pkt.S == 1 {
|
||||
frameBuf = frameBuf[:0]
|
||||
}
|
||||
frameBuf = append(frameBuf, vp8Payload...)
|
||||
if pkt.Marker {
|
||||
recvCount++
|
||||
if recvCount <= 3 || recvCount%25 == 0 {
|
||||
if len(frameBuf) > 0 {
|
||||
log.Printf("[video] recv frame #%d %d bytes, first=0x%02x", recvCount, len(frameBuf), frameBuf[0])
|
||||
}
|
||||
}
|
||||
data := ExtractDataFromPayload(frameBuf)
|
||||
if data != nil {
|
||||
dataCount++
|
||||
if dataCount <= 5 || dataCount%100 == 0 {
|
||||
log.Printf("[video] TUNNEL DATA #%d: %d bytes", dataCount, len(data))
|
||||
}
|
||||
if u.tunnel != nil && u.tunnel.onData != nil {
|
||||
u.tunnel.onData(data)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
"net"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
func encodeFrame(connID uint32, msgType byte, payload []byte) []byte {
|
||||
buf := make([]byte, 4+5+len(payload))
|
||||
binary.BigEndian.PutUint32(buf[0:4], uint32(5+len(payload)))
|
||||
binary.BigEndian.PutUint32(buf[4:8], connID)
|
||||
buf[8] = msgType
|
||||
copy(buf[9:], payload)
|
||||
return buf
|
||||
}
|
||||
|
||||
func decodeFrames(data []byte, cb func(connID uint32, msgType byte, payload []byte)) {
|
||||
for len(data) >= 4 {
|
||||
frameLen := int(binary.BigEndian.Uint32(data[0:4]))
|
||||
if frameLen < 5 || 4+frameLen > len(data) {
|
||||
return
|
||||
}
|
||||
connID := binary.BigEndian.Uint32(data[4:8])
|
||||
msgType := data[8]
|
||||
payload := data[9 : 4+frameLen]
|
||||
cb(connID, msgType, payload)
|
||||
data = data[4+frameLen:]
|
||||
}
|
||||
}
|
||||
|
||||
type RelayBridge struct {
|
||||
tunnel *VP8DataTunnel
|
||||
conns sync.Map
|
||||
nextID atomic.Uint32
|
||||
logFn func(string, ...any)
|
||||
}
|
||||
|
||||
func NewRelayBridge(tunnel *VP8DataTunnel, mode string, logFn func(string, ...any)) *RelayBridge {
|
||||
rb := &RelayBridge{
|
||||
tunnel: tunnel,
|
||||
logFn: logFn,
|
||||
}
|
||||
tunnel.onData = rb.handleTunnelData
|
||||
tunnel.onClose = rb.closeAll
|
||||
return rb
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) closeAll() {
|
||||
rb.logFn("relay: closing all connections")
|
||||
rb.conns.Range(func(key, value any) bool {
|
||||
if c, ok := value.(net.Conn); ok {
|
||||
c.Close()
|
||||
}
|
||||
rb.conns.Delete(key)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) send(connID uint32, msgType byte, payload []byte) {
|
||||
frame := encodeFrame(connID, msgType, payload)
|
||||
rb.tunnel.SendData(frame)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleTunnelData(data []byte) {
|
||||
decodeFrames(data, rb.handleCreatorMessage)
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload []byte) {
|
||||
switch msgType {
|
||||
case msgConnect:
|
||||
go rb.connectTCP(connID, string(payload))
|
||||
case msgUDP:
|
||||
go rb.handleUDP(connID, payload)
|
||||
case msgData:
|
||||
val, ok := rb.conns.Load(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Write(payload)
|
||||
}
|
||||
case msgClose:
|
||||
val, ok := rb.conns.LoadAndDelete(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
if len(payload) < 2 {
|
||||
return
|
||||
}
|
||||
addrLen := int(payload[0])
|
||||
if addrLen == 0 || len(payload) < 1+addrLen {
|
||||
return
|
||||
}
|
||||
addr := string(payload[1 : 1+addrLen])
|
||||
data := payload[1+addrLen:]
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
conn, err := net.DialUDP("udp", nil, udpAddr)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
buf := make([]byte, udpBufSize)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rb.send(connID, msgUDPReply, buf[:n])
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
||||
rb.logFn("relay: CONNECT %d -> %s", connID, maskAddr(addr))
|
||||
conn, err := net.DialTimeout("tcp", addr, 10e9)
|
||||
if err != nil {
|
||||
rb.logFn("relay: CONNECT %d failed: %v", connID, err)
|
||||
rb.send(connID, msgConnectErr, []byte(err.Error()))
|
||||
return
|
||||
}
|
||||
rb.conns.Store(connID, conn)
|
||||
rb.send(connID, msgConnectOK, nil)
|
||||
rb.logFn("relay: CONNECTED %d -> %s", connID, maskAddr(addr))
|
||||
|
||||
buf := make([]byte, vp8RelayBufSize)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
rb.send(connID, msgData, buf[:n])
|
||||
}
|
||||
if err != nil {
|
||||
if err != io.EOF {
|
||||
rb.logFn("relay: conn %d read error: %v", connID, err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
rb.send(connID, msgClose, nil)
|
||||
rb.conns.Delete(connID)
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
"github.com/pion/webrtc/v4/pkg/media"
|
||||
)
|
||||
|
||||
// Real VP8 frames
|
||||
var vp8Keyframe = []byte{
|
||||
16, 2, 0, 157, 1, 42, 2, 0, 2, 0, 2, 7, 8, 133, 133, 136,
|
||||
153, 132, 136, 11, 2, 0, 12, 13, 96, 0, 254, 252, 173, 16,
|
||||
}
|
||||
|
||||
var vp8Interframe = []byte{
|
||||
177, 1, 0, 8, 17, 24, 0, 24, 0, 24, 88, 47, 244, 0, 8, 0, 0,
|
||||
}
|
||||
|
||||
// Handles sending and receiving data through VP8 video samples
|
||||
type VP8DataTunnel struct {
|
||||
track *webrtc.TrackLocalStaticSample
|
||||
mu sync.Mutex
|
||||
logFn func(string, ...any)
|
||||
frameCount uint64
|
||||
running bool
|
||||
stopCh chan struct{}
|
||||
sendQueue chan []byte
|
||||
onData func([]byte)
|
||||
onClose func()
|
||||
}
|
||||
|
||||
func NewVP8DataTunnel(track *webrtc.TrackLocalStaticSample, logFn func(string, ...any)) *VP8DataTunnel {
|
||||
return &VP8DataTunnel{
|
||||
track: track,
|
||||
logFn: logFn,
|
||||
stopCh: make(chan struct{}),
|
||||
sendQueue: make(chan []byte, 256),
|
||||
}
|
||||
}
|
||||
|
||||
// Data frame marker - first byte 0xFF distinguishes from VP8 (keyframe bit0=0, inter bit0=1)
|
||||
const dataFrameMarker = 0xFF
|
||||
|
||||
// buildFrame creates a VP8 frame or a data frame
|
||||
func (t *VP8DataTunnel) buildFrame(data []byte) []byte {
|
||||
t.frameCount++
|
||||
|
||||
if len(data) == 0 {
|
||||
// Keepalive - send valid VP8 keyframe every 60 frames (~2.4s)
|
||||
if t.frameCount%60 == 0 {
|
||||
return vp8Keyframe
|
||||
}
|
||||
return vp8Interframe
|
||||
}
|
||||
|
||||
// Data frame: [0xFF][4-byte length][payload]
|
||||
frame := make([]byte, 1+4+len(data))
|
||||
frame[0] = dataFrameMarker
|
||||
binary.BigEndian.PutUint32(frame[1:5], uint32(len(data)))
|
||||
copy(frame[5:], data)
|
||||
return frame
|
||||
}
|
||||
|
||||
// SendData queues tunnel data to be sent in the next VP8 frame
|
||||
var sendCount atomic.Uint64
|
||||
|
||||
func (t *VP8DataTunnel) SendData(data []byte) {
|
||||
n := sendCount.Add(1)
|
||||
if n <= 5 || n%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", n, len(data), len(t.sendQueue))
|
||||
}
|
||||
t.sendQueue <- data
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Start(fps int) {
|
||||
t.running = true
|
||||
keepaliveInterval := time.Second / time.Duration(fps)
|
||||
lastSend := time.Now()
|
||||
|
||||
go func() {
|
||||
ticker := time.NewTicker(keepaliveInterval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-t.stopCh:
|
||||
return
|
||||
case data := <-t.sendQueue:
|
||||
now := time.Now()
|
||||
elapsed := now.Sub(lastSend)
|
||||
minInterval := 5 * time.Millisecond
|
||||
if elapsed < minInterval {
|
||||
time.Sleep(minInterval - elapsed)
|
||||
}
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(data)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
if err != nil {
|
||||
t.logFn("vp8tunnel: WriteSample DATA error: %v (frame %d, %d bytes)", err, t.frameCount-1, len(frame))
|
||||
} else if t.frameCount <= 10 || t.frameCount%100 == 0 {
|
||||
t.logFn("vp8tunnel: WriteSample DATA ok frame=%d size=%d dataLen=%d first=0x%02x", t.frameCount-1, len(frame), len(data), frame[0])
|
||||
}
|
||||
if t.frameCount%60 == 0 {
|
||||
kf := t.buildFrame(nil)
|
||||
t.track.WriteSample(media.Sample{Data: kf, Duration: keepaliveInterval})
|
||||
}
|
||||
ticker.Reset(keepaliveInterval)
|
||||
case <-ticker.C:
|
||||
lastSend = time.Now()
|
||||
frame := t.buildFrame(nil)
|
||||
err := t.track.WriteSample(media.Sample{Data: frame, Duration: keepaliveInterval})
|
||||
if t.frameCount <= 3 || t.frameCount%500 == 0 {
|
||||
t.logFn("vp8tunnel: KEEPALIVE frame=%d first=0x%02x err=%v", t.frameCount-1, frame[0], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (t *VP8DataTunnel) Stop() {
|
||||
if t.running {
|
||||
close(t.stopCh)
|
||||
t.running = false
|
||||
if t.onClose != nil {
|
||||
t.onClose()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extracts tunnel data from reassembled VP8 frame
|
||||
// The payload has VP8 RTP payload descriptor stripped by the depacketizer
|
||||
// First byte: 0xFF = data frame, anything else = valid VP8 (keepalive)
|
||||
func ExtractDataFromPayload(payload []byte) []byte {
|
||||
if len(payload) < 5 {
|
||||
return nil
|
||||
}
|
||||
if payload[0] != dataFrameMarker {
|
||||
return nil // valid VP8 keepalive frame, skip
|
||||
}
|
||||
dataLen := binary.BigEndian.Uint32(payload[1:5])
|
||||
if dataLen == 0 || int(dataLen) > len(payload)-5 {
|
||||
return nil
|
||||
}
|
||||
return payload[5 : 5+dataLen]
|
||||
}
|
||||
@@ -49,5 +49,3 @@ require (
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
gvisor.dev/gvisor v0.0.0-20250523182742-eede7a881b20 // indirect
|
||||
)
|
||||
|
||||
|
||||
+30
-27
@@ -12,6 +12,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"whitelist-bypass/relay/socks"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -247,18 +248,18 @@ type udpClient struct {
|
||||
func (j *joinerRelay) handleUDPAssociate(tcpConn net.Conn) {
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
tcpConn.Write([]byte{0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
tcpConn.Write(socks.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
tcpConn.Write([]byte{0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
tcpConn.Write(socks.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
localAddr := udpConn.LocalAddr().(*net.UDPAddr)
|
||||
reply := []byte{0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0}
|
||||
reply := []byte{socks.Ver, 0x00, 0x00, socks.AtypIPv4, 127, 0, 0, 1, 0, 0}
|
||||
binary.BigEndian.PutUint16(reply[8:10], uint16(localAddr.Port))
|
||||
tcpConn.Write(reply)
|
||||
logMsg("dc-joiner: UDP ASSOCIATE on port %d", localAddr.Port)
|
||||
@@ -291,14 +292,14 @@ func (j *joinerRelay) handleUDPAssociate(tcpConn net.Conn) {
|
||||
var dstAddr string
|
||||
var headerLen int
|
||||
switch atyp {
|
||||
case 0x01:
|
||||
case socks.AtypIPv4:
|
||||
if n < 10 {
|
||||
continue
|
||||
}
|
||||
dstAddr = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
headerLen = 10
|
||||
case 0x03:
|
||||
case socks.AtypDomain:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
continue
|
||||
@@ -306,7 +307,7 @@ func (j *joinerRelay) handleUDPAssociate(tcpConn net.Conn) {
|
||||
dstAddr = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
headerLen = 5 + dlen + 2
|
||||
case 0x04:
|
||||
case socks.AtypIPv6:
|
||||
if n < 22 {
|
||||
continue
|
||||
}
|
||||
@@ -404,39 +405,39 @@ func (j *joinerRelay) listenSOCKS(ln net.Listener) error {
|
||||
|
||||
func (j *joinerRelay) handleSOCKS(conn net.Conn) {
|
||||
<-j.ready
|
||||
buf := make([]byte, 258)
|
||||
buf := make([]byte, socks.HandshakeBuf)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil || n < 2 || buf[0] != 0x05 {
|
||||
if err != nil || n < 2 || buf[0] != socks.Ver {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00})
|
||||
conn.Write(socks.NoAuth)
|
||||
n, err = conn.Read(buf)
|
||||
if err != nil || n < 7 || buf[0] != 0x05 {
|
||||
conn.Write([]byte{0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
if err != nil || n < 7 || buf[0] != socks.Ver {
|
||||
conn.Write(socks.GenFail)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
cmd := buf[1]
|
||||
if cmd == 0x03 {
|
||||
if cmd == socks.CmdUDP {
|
||||
j.handleUDPAssociate(conn)
|
||||
return
|
||||
}
|
||||
if cmd != 0x01 {
|
||||
conn.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
if cmd != socks.CmdTCP {
|
||||
conn.Write(socks.CmdErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch buf[3] {
|
||||
case 0x01:
|
||||
case socks.AtypIPv4:
|
||||
if n < 10 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
host = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
case 0x03:
|
||||
case socks.AtypDomain:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
conn.Close()
|
||||
@@ -444,7 +445,7 @@ func (j *joinerRelay) handleSOCKS(conn net.Conn) {
|
||||
}
|
||||
host = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
case 0x04:
|
||||
case socks.AtypIPv6:
|
||||
if n < 22 {
|
||||
conn.Close()
|
||||
return
|
||||
@@ -453,7 +454,7 @@ func (j *joinerRelay) handleSOCKS(conn net.Conn) {
|
||||
host = fmt.Sprintf("[%s]:%d", ip.String(),
|
||||
binary.BigEndian.Uint16(buf[20:22]))
|
||||
default:
|
||||
conn.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.AddrErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
@@ -464,12 +465,12 @@ func (j *joinerRelay) handleSOCKS(conn net.Conn) {
|
||||
j.send(id, msgConnect, []byte(host))
|
||||
if err := <-sc.rdy; err != nil {
|
||||
logMsg("dc-joiner: CONNECT %d failed: %v", id, err)
|
||||
conn.Write([]byte{0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.ConnFail)
|
||||
conn.Close()
|
||||
j.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.OK)
|
||||
logMsg("dc-joiner: CONNECTED %d -> %s", id, maskAddr(host))
|
||||
go func() {
|
||||
buf := make([]byte, readBufSize)
|
||||
@@ -518,14 +519,16 @@ func (c *creatorRelay) handleMessage(connID uint32, msgType byte, payload []byte
|
||||
case msgUDP:
|
||||
go c.handleUDP(connID, payload)
|
||||
case msgData:
|
||||
val, ok := c.conns.Load(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Write(payload)
|
||||
if val, ok := c.conns.Load(connID); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
conn.Write(payload)
|
||||
}
|
||||
}
|
||||
case msgClose:
|
||||
val, ok := c.conns.LoadAndDelete(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Close()
|
||||
if val, ok := c.conns.LoadAndDelete(connID); ok {
|
||||
if conn, ok := val.(net.Conn); ok {
|
||||
conn.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -569,7 +572,7 @@ func (c *creatorRelay) handleUDP(connID uint32, payload []byte) {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
buf := make([]byte, 4096)
|
||||
buf := make([]byte, socks.UDPBufSize)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
|
||||
+38
-29
@@ -9,6 +9,8 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"whitelist-bypass/relay/socks"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -148,14 +150,16 @@ func (rb *RelayBridge) handleCreatorMessage(connID uint32, msgType byte, payload
|
||||
case msgUDP:
|
||||
go rb.handleUDP(connID, payload)
|
||||
case msgData:
|
||||
val, ok := rb.conns.Load(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Write(payload)
|
||||
if val, ok := rb.conns.Load(connID); ok {
|
||||
if c, ok := val.(net.Conn); ok {
|
||||
c.Write(payload)
|
||||
}
|
||||
}
|
||||
case msgClose:
|
||||
val, ok := rb.conns.LoadAndDelete(connID)
|
||||
if ok {
|
||||
val.(net.Conn).Close()
|
||||
if val, ok := rb.conns.LoadAndDelete(connID); ok {
|
||||
if c, ok := val.(net.Conn); ok {
|
||||
c.Close()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,7 +188,7 @@ func (rb *RelayBridge) handleUDP(connID uint32, payload []byte) {
|
||||
defer conn.Close()
|
||||
conn.SetDeadline(time.Now().Add(5 * time.Second))
|
||||
conn.Write(data)
|
||||
buf := make([]byte, 4096)
|
||||
buf := make([]byte, socks.UDPBufSize)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil {
|
||||
return
|
||||
@@ -204,7 +208,7 @@ func (rb *RelayBridge) connectTCP(connID uint32, addr string) {
|
||||
rb.send(connID, msgConnectOK, nil)
|
||||
rb.logFn("relay: CONNECTED %d -> %s", connID, maskAddr(addr))
|
||||
|
||||
buf := make([]byte, 900)
|
||||
buf := make([]byte, socks.VP8BufSize)
|
||||
for {
|
||||
n, err := conn.Read(buf)
|
||||
if n > 0 {
|
||||
@@ -247,38 +251,38 @@ func (rb *RelayBridge) ListenSOCKS(addr string) error {
|
||||
|
||||
func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
<-rb.ready
|
||||
buf := make([]byte, 258)
|
||||
buf := make([]byte, socks.HandshakeBuf)
|
||||
n, err := conn.Read(buf)
|
||||
if err != nil || n < 2 || buf[0] != 0x05 {
|
||||
if err != nil || n < 2 || buf[0] != socks.Ver {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00})
|
||||
conn.Write(socks.NoAuth)
|
||||
n, err = conn.Read(buf)
|
||||
if err != nil || n < 7 || buf[0] != 0x05 {
|
||||
if err != nil || n < 7 || buf[0] != socks.Ver {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
cmd := buf[1]
|
||||
if cmd == 0x03 {
|
||||
if cmd == socks.CmdUDP {
|
||||
rb.handleUDPAssociate(conn)
|
||||
return
|
||||
}
|
||||
if cmd != 0x01 {
|
||||
conn.Write([]byte{0x05, 0x07, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
if cmd != socks.CmdTCP {
|
||||
conn.Write(socks.CmdErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
var host string
|
||||
switch buf[3] {
|
||||
case 0x01:
|
||||
case socks.AtypIPv4:
|
||||
if n < 10 {
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
host = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
case 0x03:
|
||||
case socks.AtypDomain:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
conn.Close()
|
||||
@@ -286,7 +290,7 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
}
|
||||
host = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
case 0x04:
|
||||
case socks.AtypIPv6:
|
||||
if n < 22 {
|
||||
conn.Close()
|
||||
return
|
||||
@@ -295,7 +299,7 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
host = fmt.Sprintf("[%s]:%d", ip.String(),
|
||||
binary.BigEndian.Uint16(buf[20:22]))
|
||||
default:
|
||||
conn.Write([]byte{0x05, 0x08, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.AddrErr)
|
||||
conn.Close()
|
||||
return
|
||||
}
|
||||
@@ -308,16 +312,16 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
|
||||
if err := <-sc.rdy; err != nil {
|
||||
rb.logFn("relay: SOCKS CONNECT %d failed: %v", id, err)
|
||||
conn.Write([]byte{0x05, 0x05, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.ConnFail)
|
||||
conn.Close()
|
||||
rb.conns.Delete(id)
|
||||
return
|
||||
}
|
||||
conn.Write([]byte{0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
conn.Write(socks.OK)
|
||||
rb.logFn("relay: SOCKS CONNECTED %d -> %s", id, maskAddr(host))
|
||||
|
||||
go func() {
|
||||
readBuf := make([]byte, 900)
|
||||
readBuf := make([]byte, socks.VP8BufSize)
|
||||
for {
|
||||
rn, rerr := conn.Read(readBuf)
|
||||
if rn > 0 {
|
||||
@@ -333,15 +337,20 @@ func (rb *RelayBridge) handleSOCKS(conn net.Conn) {
|
||||
}
|
||||
|
||||
func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
udpAddr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
tcpConn.Write(socks.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
tcpConn.Write([]byte{0x05, 0x01, 0x00, 0x01, 0, 0, 0, 0, 0, 0})
|
||||
tcpConn.Write(socks.GenFail)
|
||||
tcpConn.Close()
|
||||
return
|
||||
}
|
||||
localAddr := udpConn.LocalAddr().(*net.UDPAddr)
|
||||
reply := []byte{0x05, 0x00, 0x00, 0x01, 127, 0, 0, 1, 0, 0}
|
||||
reply := []byte{socks.Ver, 0x00, 0x00, socks.AtypIPv4, 127, 0, 0, 1, 0, 0}
|
||||
binary.BigEndian.PutUint16(reply[8:10], uint16(localAddr.Port))
|
||||
tcpConn.Write(reply)
|
||||
|
||||
@@ -354,7 +363,7 @@ func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
go func() {
|
||||
defer udpConn.Close()
|
||||
defer tcpConn.Close()
|
||||
buf := make([]byte, 4096)
|
||||
buf := make([]byte, socks.UDPBufSize)
|
||||
for {
|
||||
n, addr, err := udpConn.ReadFromUDP(buf)
|
||||
if err != nil {
|
||||
@@ -371,14 +380,14 @@ func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
var dstAddr string
|
||||
var headerLen int
|
||||
switch atyp {
|
||||
case 0x01:
|
||||
case socks.AtypIPv4:
|
||||
if n < 10 {
|
||||
continue
|
||||
}
|
||||
dstAddr = fmt.Sprintf("%d.%d.%d.%d:%d", buf[4], buf[5], buf[6], buf[7],
|
||||
binary.BigEndian.Uint16(buf[8:10]))
|
||||
headerLen = 10
|
||||
case 0x03:
|
||||
case socks.AtypDomain:
|
||||
dlen := int(buf[4])
|
||||
if n < 5+dlen+2 {
|
||||
continue
|
||||
@@ -386,7 +395,7 @@ func (rb *RelayBridge) handleUDPAssociate(tcpConn net.Conn) {
|
||||
dstAddr = fmt.Sprintf("%s:%d", string(buf[5:5+dlen]),
|
||||
binary.BigEndian.Uint16(buf[5+dlen:7+dlen]))
|
||||
headerLen = 5 + dlen + 2
|
||||
case 0x04:
|
||||
case socks.AtypIPv6:
|
||||
if n < 22 {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/socks"
|
||||
)
|
||||
|
||||
type tmPCState struct {
|
||||
@@ -283,7 +284,7 @@ func (c *TelemostClient) handleICECandidate(data json.RawMessage, role string) {
|
||||
|
||||
func (c *TelemostClient) readTrack(track *webrtc.TrackRemote) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
buf := make([]byte, 4096)
|
||||
buf := make([]byte, socks.UDPBufSize)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
c.logFn("telemost: readTrack (%s) error: %v", track.Codec().MimeType, err)
|
||||
@@ -296,7 +297,7 @@ func (c *TelemostClient) readTrack(track *webrtc.TrackRemote) {
|
||||
var frameBuf []byte
|
||||
dataCount := 0
|
||||
recvCount := 0
|
||||
buf := make([]byte, 65536)
|
||||
buf := make([]byte, socks.RTPBufSize)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
|
||||
+173
-30
@@ -8,17 +8,20 @@ import (
|
||||
"github.com/pion/rtp"
|
||||
"github.com/pion/rtp/codecs"
|
||||
"github.com/pion/webrtc/v4"
|
||||
"whitelist-bypass/relay/socks"
|
||||
)
|
||||
|
||||
type VKClient struct {
|
||||
WSHelper
|
||||
pc *webrtc.PeerConnection
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
tunnel *VP8DataTunnel
|
||||
logFn func(string, ...any)
|
||||
remoteSet bool
|
||||
pending []webrtc.ICECandidateInit
|
||||
OnConnected func(*VP8DataTunnel)
|
||||
pc *webrtc.PeerConnection
|
||||
sampleTrack *webrtc.TrackLocalStaticSample
|
||||
tunnel *VP8DataTunnel
|
||||
logFn func(string, ...any)
|
||||
remoteSet bool
|
||||
pending []webrtc.ICECandidateInit
|
||||
OnConnected func(*VP8DataTunnel)
|
||||
dcProducerNotif *webrtc.DataChannel
|
||||
dcProducerCmd *webrtc.DataChannel
|
||||
}
|
||||
|
||||
func NewVKClient(logFn func(string, ...any)) *VKClient {
|
||||
@@ -44,6 +47,7 @@ func (c *VKClient) handleMessage(raw []byte) {
|
||||
if err := json.Unmarshal(raw, &msg); err != nil {
|
||||
return
|
||||
}
|
||||
c.logFn("vk: >> msg type=%s id=%d", msg.Type, msg.ID)
|
||||
|
||||
switch msg.Type {
|
||||
case "ice-servers":
|
||||
@@ -58,26 +62,15 @@ func (c *VKClient) handleMessage(raw []byte) {
|
||||
case "add-ice-candidate", "remote-ice-candidate":
|
||||
c.handleICECandidate(msg.Data)
|
||||
case "add-track", "create-data-channel":
|
||||
case "reset":
|
||||
c.handleReset(msg.ID)
|
||||
case "close":
|
||||
c.cleanup()
|
||||
}
|
||||
c.logFn("vk: << msg type=%s id=%d done", msg.Type, msg.ID)
|
||||
}
|
||||
|
||||
func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
if c.pc != nil {
|
||||
return
|
||||
}
|
||||
iceLogFn = c.logFn
|
||||
iceServers, err := ParseICEServers(data)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
config := webrtc.Configuration{
|
||||
ICEServers: iceServers,
|
||||
ICETransportPolicy: webrtc.ICETransportPolicyRelay,
|
||||
}
|
||||
|
||||
func (c *VKClient) createPC(config webrtc.Configuration) error {
|
||||
se := webrtc.SettingEngine{}
|
||||
se.SetNet(&AndroidNet{})
|
||||
se.SetInterfaceFilter(func(iface string) bool { return false })
|
||||
@@ -85,7 +78,7 @@ func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
pc, err := api.NewPeerConnection(config)
|
||||
if err != nil {
|
||||
c.logFn("vk: failed to create PC: %v", err)
|
||||
return
|
||||
return err
|
||||
}
|
||||
c.pc = pc
|
||||
|
||||
@@ -106,6 +99,46 @@ func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
c.logFn("vk: AddTrack video: sender=%v err=%v", videoSender != nil, videoErr)
|
||||
c.logFn("vk: senders count: %d", len(pc.GetSenders()))
|
||||
|
||||
// Create DataChannels required by VK SFU.
|
||||
// The SFU sends producer-updated (SDP offer) via producerNotification DC.
|
||||
ordered := true
|
||||
dcNotif, err := pc.CreateDataChannel("producerNotification", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
if err != nil {
|
||||
c.logFn("vk: failed to create producerNotification DC: %v", err)
|
||||
} else {
|
||||
c.dcProducerNotif = dcNotif
|
||||
dcNotif.OnOpen(func() {
|
||||
c.logFn("vk: producerNotification DC opened")
|
||||
})
|
||||
dcNotif.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
c.logFn("vk: producerNotification msg len=%d isString=%v", len(msg.Data), msg.IsString)
|
||||
// Forward to Node bridge as sfu-dc-message
|
||||
c.SendToHook("sfu-dc-message", map[string]interface{}{
|
||||
"channel": "producerNotification",
|
||||
"data": string(msg.Data),
|
||||
})
|
||||
})
|
||||
}
|
||||
dcCmd, err := pc.CreateDataChannel("producerCommand", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
if err != nil {
|
||||
c.logFn("vk: failed to create producerCommand DC: %v", err)
|
||||
} else {
|
||||
c.dcProducerCmd = dcCmd
|
||||
dcCmd.OnOpen(func() {
|
||||
c.logFn("vk: producerCommand DC opened")
|
||||
})
|
||||
dcCmd.OnMessage(func(msg webrtc.DataChannelMessage) {
|
||||
c.logFn("vk: producerCommand msg len=%d", len(msg.Data))
|
||||
c.SendToHook("sfu-dc-message", map[string]interface{}{
|
||||
"channel": "producerCommand",
|
||||
"data": string(msg.Data),
|
||||
})
|
||||
})
|
||||
}
|
||||
// SFU also expects screen share DCs
|
||||
pc.CreateDataChannel("producerScreenShare", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
pc.CreateDataChannel("consumerScreenShare", &webrtc.DataChannelInit{Ordered: &ordered})
|
||||
|
||||
pc.OnICECandidate(func(cand *webrtc.ICECandidate) {
|
||||
if cand == nil {
|
||||
c.logFn("vk: ICE gathering complete (nil candidate)")
|
||||
@@ -136,7 +169,26 @@ func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
go c.readTrack(track)
|
||||
})
|
||||
|
||||
c.logFn("vk: PC created (%d ICE servers)", len(iceServers))
|
||||
c.logFn("vk: PC created (%d ICE servers)", len(config.ICEServers))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *VKClient) handleICEServers(data json.RawMessage) {
|
||||
if c.pc != nil {
|
||||
return
|
||||
}
|
||||
iceLogFn = c.logFn
|
||||
iceServers, err := ParseICEServers(data)
|
||||
if err != nil {
|
||||
c.logFn("vk: failed to parse ICE servers: %v", err)
|
||||
return
|
||||
}
|
||||
if err := c.createPC(webrtc.Configuration{
|
||||
ICEServers: iceServers,
|
||||
ICETransportPolicy: webrtc.ICETransportPolicyRelay,
|
||||
}); err != nil {
|
||||
c.logFn("vk: handleICEServers createPC failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VKClient) handleCreateOffer(id int) {
|
||||
@@ -145,30 +197,53 @@ func (c *VKClient) handleCreateOffer(id int) {
|
||||
}
|
||||
offer, err := c.pc.CreateOffer(nil)
|
||||
if err != nil {
|
||||
c.logFn("vk: createOffer error: %v", err)
|
||||
return
|
||||
}
|
||||
c.pc.SetLocalDescription(offer)
|
||||
c.logFn("vk: created offer, senders=%d signalingState=%s", len(c.pc.GetSenders()), c.pc.SignalingState().String())
|
||||
// Log offer media lines
|
||||
for _, line := range splitLines(offer.SDP) {
|
||||
if len(line) > 2 && line[:2] == "m=" {
|
||||
c.logFn("vk: offer>> %s", line)
|
||||
}
|
||||
}
|
||||
c.SendResponse(id, SDPMessage{Type: offer.Type.String(), SDP: offer.SDP})
|
||||
}
|
||||
|
||||
func (c *VKClient) handleCreateAnswer(id int) {
|
||||
if c.pc == nil {
|
||||
c.logFn("vk: createAnswer error: no PC")
|
||||
return
|
||||
}
|
||||
c.logFn("vk: createAnswer: signalingState=%s", c.pc.SignalingState().String())
|
||||
answer, err := c.pc.CreateAnswer(nil)
|
||||
if err != nil {
|
||||
c.logFn("vk: createAnswer error: %v", err)
|
||||
return
|
||||
}
|
||||
c.logFn("vk: createAnswer: setting local description...")
|
||||
c.pc.SetLocalDescription(answer)
|
||||
c.logFn("vk: created answer, senders=%d signalingState=%s", len(c.pc.GetSenders()), c.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: answer.Type.String(), SDP: answer.SDP})
|
||||
|
||||
// Wait for ICE gathering so the answer SDP includes candidates.
|
||||
// In SFU mode the SDK reads localDescription after setLocalDescription
|
||||
// and sends it via acceptProducer - it must have candidates already.
|
||||
gatherDone := webrtc.GatheringCompletePromise(c.pc)
|
||||
go func() {
|
||||
<-gatherDone
|
||||
localDesc := c.pc.LocalDescription()
|
||||
c.logFn("vk: created answer with ICE, senders=%d signalingState=%s", len(c.pc.GetSenders()), c.pc.SignalingState().String())
|
||||
c.SendResponse(id, SDPMessage{Type: localDesc.Type.String(), SDP: localDesc.SDP})
|
||||
}()
|
||||
}
|
||||
|
||||
func (c *VKClient) handleSetRemoteDescription(data json.RawMessage, id int) {
|
||||
var sdpMsg SDPMessage
|
||||
if err := json.Unmarshal(data, &sdpMsg); err != nil || c.pc == nil {
|
||||
c.logFn("vk: setRemoteDescription: no pc or bad data")
|
||||
if id > 0 {
|
||||
c.SendResponse(id, "error: no pc or bad data")
|
||||
}
|
||||
return
|
||||
}
|
||||
var sdpType webrtc.SDPType
|
||||
@@ -177,11 +252,34 @@ func (c *VKClient) handleSetRemoteDescription(data json.RawMessage, id int) {
|
||||
} else {
|
||||
sdpType = webrtc.SDPTypeAnswer
|
||||
}
|
||||
connState := c.pc.ConnectionState().String()
|
||||
iceState := c.pc.ICEConnectionState().String()
|
||||
c.logFn("vk: setRemoteDescription: type=%s signalingState=%s connectionState=%s iceState=%s senders=%d receivers=%d",
|
||||
sdpMsg.Type, c.pc.SignalingState().String(), connState, iceState,
|
||||
len(c.pc.GetSenders()), len(c.pc.GetReceivers()))
|
||||
|
||||
// Log SDP media lines for debugging codec issues
|
||||
lines := 0
|
||||
for _, line := range splitLines(sdpMsg.SDP) {
|
||||
if len(line) > 2 && (line[:2] == "m=" || line[:2] == "a=") {
|
||||
if line[:2] == "m=" || (len(line) > 9 && line[:9] == "a=rtpmap:") || (len(line) > 12 && line[:12] == "a=candidate:") {
|
||||
c.logFn("vk: SDP>> %s", line)
|
||||
lines++
|
||||
if lines > 20 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.pc.SetRemoteDescription(webrtc.SessionDescription{Type: sdpType, SDP: sdpMsg.SDP}); err != nil {
|
||||
c.logFn("vk: setRemoteDescription error: %v", err)
|
||||
c.logFn("vk: setRemoteDescription error (%s, state=%s): %v", sdpMsg.Type, c.pc.SignalingState().String(), err)
|
||||
if id > 0 {
|
||||
c.SendResponse(id, "ok")
|
||||
}
|
||||
return
|
||||
}
|
||||
c.logFn("vk: set remote description: %s, signalingState=%s, senders=%d", sdpMsg.Type, c.pc.SignalingState().String(), len(c.pc.GetSenders()))
|
||||
c.logFn("vk: set remote description OK: %s, signalingState=%s, senders=%d", sdpMsg.Type, c.pc.SignalingState().String(), len(c.pc.GetSenders()))
|
||||
for i, s := range c.pc.GetSenders() {
|
||||
if s.Track() != nil {
|
||||
c.logFn("vk: sender[%d]: kind=%s id=%s", i, s.Track().Kind().String(), s.Track().ID())
|
||||
@@ -216,7 +314,7 @@ func (c *VKClient) handleICECandidate(data json.RawMessage) {
|
||||
|
||||
func (c *VKClient) readTrack(track *webrtc.TrackRemote) {
|
||||
if track.Codec().MimeType != webrtc.MimeTypeVP8 {
|
||||
buf := make([]byte, 4096)
|
||||
buf := make([]byte, socks.UDPBufSize)
|
||||
for {
|
||||
if _, _, err := track.Read(buf); err != nil {
|
||||
return
|
||||
@@ -228,7 +326,7 @@ func (c *VKClient) readTrack(track *webrtc.TrackRemote) {
|
||||
var frameBuf []byte
|
||||
dataCount := 0
|
||||
recvCount := 0
|
||||
buf := make([]byte, 65536)
|
||||
buf := make([]byte, socks.RTPBufSize)
|
||||
for {
|
||||
n, _, err := track.Read(buf)
|
||||
if err != nil {
|
||||
@@ -267,6 +365,51 @@ func (c *VKClient) readTrack(track *webrtc.TrackRemote) {
|
||||
}
|
||||
}
|
||||
|
||||
func (c *VKClient) handleReset(id int) {
|
||||
c.logFn("vk: reset - closing PC for reconnection")
|
||||
if c.tunnel != nil {
|
||||
c.tunnel.Stop()
|
||||
c.tunnel = nil
|
||||
}
|
||||
if c.pc != nil {
|
||||
// Remove callbacks before Close() to prevent stale state events
|
||||
c.pc.OnConnectionStateChange(nil)
|
||||
c.pc.OnICECandidate(nil)
|
||||
c.pc.OnTrack(nil)
|
||||
oldPC := c.pc
|
||||
c.pc = nil
|
||||
// Close asynchronously - pc.Close() blocks on DTLS shutdown
|
||||
go oldPC.Close()
|
||||
}
|
||||
c.remoteSet = false
|
||||
c.pending = nil
|
||||
c.dcProducerNotif = nil
|
||||
c.dcProducerCmd = nil
|
||||
c.sampleTrack = nil
|
||||
if id > 0 {
|
||||
c.SendResponse(id, "ok")
|
||||
}
|
||||
}
|
||||
|
||||
func splitLines(s string) []string {
|
||||
var lines []string
|
||||
start := 0
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '\n' {
|
||||
line := s[start:i]
|
||||
if len(line) > 0 && line[len(line)-1] == '\r' {
|
||||
line = line[:len(line)-1]
|
||||
}
|
||||
lines = append(lines, line)
|
||||
start = i + 1
|
||||
}
|
||||
}
|
||||
if start < len(s) {
|
||||
lines = append(lines, s[start:])
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func (c *VKClient) cleanup() {
|
||||
if c.tunnel != nil {
|
||||
c.tunnel.Stop()
|
||||
|
||||
@@ -3,6 +3,7 @@ package pion
|
||||
import (
|
||||
"encoding/binary"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/pion/webrtc/v4"
|
||||
@@ -65,12 +66,12 @@ func (t *VP8DataTunnel) buildFrame(data []byte) []byte {
|
||||
}
|
||||
|
||||
// SendData queues tunnel data to be sent in the next VP8 frame
|
||||
var sendCount uint64
|
||||
var sendCount atomic.Uint64
|
||||
|
||||
func (t *VP8DataTunnel) SendData(data []byte) {
|
||||
sendCount++
|
||||
if sendCount <= 5 || sendCount%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", sendCount, len(data), len(t.sendQueue))
|
||||
n := sendCount.Add(1)
|
||||
if n <= 5 || n%100 == 0 {
|
||||
t.logFn("vp8tunnel: SendData #%d len=%d queueLen=%d", n, len(data), len(t.sendQueue))
|
||||
}
|
||||
t.sendQueue <- data
|
||||
}
|
||||
|
||||
BIN
Binary file not shown.
@@ -0,0 +1,24 @@
|
||||
package socks
|
||||
|
||||
const (
|
||||
Ver = 0x05
|
||||
CmdTCP = 0x01
|
||||
CmdUDP = 0x03
|
||||
AtypIPv4 = 0x01
|
||||
AtypDomain = 0x03
|
||||
AtypIPv6 = 0x04
|
||||
|
||||
HandshakeBuf = 258
|
||||
UDPBufSize = 4096
|
||||
RTPBufSize = 65536
|
||||
VP8BufSize = 900
|
||||
)
|
||||
|
||||
var (
|
||||
NoAuth = []byte{Ver, 0x00}
|
||||
OK = []byte{Ver, 0x00, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
ConnFail = []byte{Ver, 0x05, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
CmdErr = []byte{Ver, 0x07, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
AddrErr = []byte{Ver, 0x08, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
GenFail = []byte{Ver, 0x01, 0x00, AtypIPv4, 0, 0, 0, 0, 0, 0}
|
||||
)
|
||||
Reference in new issue
Block a user