forked from facebookarchive/WebDriverAgent
-
Notifications
You must be signed in to change notification settings - Fork 545
feat: optional reverse TCP tunnel for WDA in NAT-restricted environments #1128
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dankefox
wants to merge
4
commits into
appium:master
Choose a base branch
from
dankefox:feat/reverse-tcp-tunnel
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
24f73f1
feat: optional reverse TCP tunnel for WDA in NAT-restricted environments
dankefox abafbc5
refactor: move relay server to docs/, convert to ESM, extract default…
dankefox e462c41
refactor: align with tested implementation, address review feedback
dankefox d909419
refactor: add exponential backoff, extract constants, add documentation
dankefox File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| #!/usr/bin/env node | ||
| /** | ||
| * WDA Reverse Tunnel Relay Server | ||
| * | ||
| * This server acts as a bridge between WDA (running on an iOS device behind NAT) | ||
| * and HTTP clients. WDA connects outbound to this relay; HTTP clients connect | ||
| * to localhost:8100 as usual. | ||
| * | ||
| * Usage: | ||
| * WDA_RELAY_HOST=<this-server-ip> WDA_RELAY_PORT=8201 xcodebuild test-without-building ... | ||
| * node wda-relay-server.js # relay on 8201, proxy on 8100 | ||
| * node wda-relay-server.js 9201 9100 # custom ports | ||
| * | ||
| * Protocol (between relay and WDA): | ||
| * [4-byte big-endian length][payload] | ||
| * Request payload: raw HTTP request (method + headers + body) | ||
| * Response payload: raw HTTP response (status + headers + body) | ||
| */ | ||
|
|
||
| const net = require('net'); | ||
| const http = require('http'); | ||
|
|
||
| const RELAY_PORT = parseInt(process.argv[2]) || 8201; | ||
| const PROXY_PORT = parseInt(process.argv[3]) || 8100; | ||
|
|
||
| let wdaSocket = null; | ||
| let pendingRequests = new Map(); | ||
| let requestCounter = 0; | ||
|
|
||
| // --- Relay server: accepts reverse connection from WDA --- | ||
| const relayServer = net.createServer((socket) => { | ||
| console.log(`[relay] WDA connected from ${socket.remoteAddress}`); | ||
| wdaSocket = socket; | ||
|
|
||
| let buffer = Buffer.alloc(0); | ||
|
|
||
| socket.on('data', (chunk) => { | ||
| buffer = Buffer.concat([buffer, chunk]); | ||
|
|
||
| while (buffer.length >= 4) { | ||
| const len = buffer.readUInt32BE(0); | ||
| if (buffer.length < 4 + len) break; | ||
|
|
||
| const payload = buffer.slice(4, 4 + len); | ||
| buffer = buffer.slice(4 + len); | ||
|
|
||
| // Route response to the oldest pending HTTP request | ||
| const oldest = pendingRequests.entries().next().value; | ||
| if (oldest) { | ||
| const [id, res] = oldest; | ||
| pendingRequests.delete(id); | ||
|
|
||
| const text = payload.toString(); | ||
| const headerEnd = text.indexOf('\r\n\r\n'); | ||
| if (headerEnd !== -1) { | ||
| const statusMatch = text.match(/^HTTP\/\d\.\d (\d+)/); | ||
| const statusCode = statusMatch ? parseInt(statusMatch[1]) : 200; | ||
| const body = payload.slice(headerEnd + 4); | ||
| res.writeHead(statusCode, { 'Content-Type': 'application/json' }); | ||
| res.end(body); | ||
| } else { | ||
| res.writeHead(200, { 'Content-Type': 'application/json' }); | ||
| res.end(payload); | ||
| } | ||
| } | ||
| } | ||
| }); | ||
|
|
||
| socket.on('close', () => { | ||
| console.log('[relay] WDA disconnected'); | ||
| wdaSocket = null; | ||
| }); | ||
|
|
||
| socket.on('error', (err) => { | ||
| console.error('[relay] Socket error:', err.message); | ||
| wdaSocket = null; | ||
| }); | ||
| }); | ||
|
|
||
| // --- HTTP proxy: accepts normal WDA API requests --- | ||
| const proxyServer = http.createServer((req, res) => { | ||
| if (!wdaSocket || wdaSocket.destroyed) { | ||
| res.writeHead(503, { 'Content-Type': 'application/json' }); | ||
| res.end(JSON.stringify({ error: 'WDA not connected to relay' })); | ||
| return; | ||
| } | ||
|
|
||
| let body = []; | ||
| req.on('data', (chunk) => body.push(chunk)); | ||
| req.on('end', () => { | ||
| const bodyBuf = Buffer.concat(body); | ||
| const httpReq = `${req.method} ${req.url} HTTP/1.1\r\nHost: localhost\r\n` + | ||
| Object.entries(req.headers).map(([k, v]) => `${k}: ${v}`).join('\r\n') + | ||
| '\r\n\r\n' + bodyBuf.toString(); | ||
|
|
||
| const reqBuf = Buffer.from(httpReq); | ||
| const lenBuf = Buffer.alloc(4); | ||
| lenBuf.writeUInt32BE(reqBuf.length); | ||
|
|
||
| const id = requestCounter++; | ||
| pendingRequests.set(id, res); | ||
|
|
||
| try { | ||
| wdaSocket.write(Buffer.concat([lenBuf, reqBuf])); | ||
| } catch (err) { | ||
| pendingRequests.delete(id); | ||
| res.writeHead(502, { 'Content-Type': 'application/json' }); | ||
| res.end(JSON.stringify({ error: 'Failed to forward request' })); | ||
| } | ||
| }); | ||
| }); | ||
|
|
||
| relayServer.listen(RELAY_PORT, () => { | ||
| console.log(`[relay] Waiting for WDA on port ${RELAY_PORT}`); | ||
| }); | ||
|
|
||
| proxyServer.listen(PROXY_PORT, () => { | ||
| console.log(`[proxy] HTTP proxy on port ${PROXY_PORT}`); | ||
| console.log(`\nUsage: set WDA_RELAY_HOST and WDA_RELAY_PORT env vars when launching WDA`); | ||
| console.log(` WDA_RELAY_HOST=<this-ip> WDA_RELAY_PORT=${RELAY_PORT} xcodebuild test-without-building ...`); | ||
| console.log(` curl http://localhost:${PROXY_PORT}/status`); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| /** | ||
| * Copyright (c) 2015-present, Facebook, Inc. | ||
| * All rights reserved. | ||
| * | ||
| * This source code is licensed under the BSD-style license found in the | ||
| * LICENSE file in the root directory of this source tree. | ||
| */ | ||
|
|
||
| #import <Foundation/Foundation.h> | ||
|
|
||
| NS_ASSUME_NONNULL_BEGIN | ||
|
|
||
| /** | ||
| Optional reverse TCP tunnel for NAT-restricted environments. | ||
|
|
||
| When WDA_RELAY_HOST is set, this module opens an outbound TCP connection | ||
| to an external relay server, allowing WDA to be controlled in environments | ||
| where inbound connections to port 8100 are not feasible (symmetric NAT, | ||
| multi-layer firewalls, VPN tunnels, etc.). | ||
|
|
||
| The tunnel uses a simple 4-byte big-endian length-prefixed framing protocol | ||
| to multiplex HTTP request/response pairs over a single persistent connection. | ||
|
|
||
| When WDA_RELAY_HOST is not set, this module is completely inactive. | ||
| */ | ||
| @interface FBReverseTunnel : NSObject | ||
|
|
||
| /** | ||
| Starts the reverse tunnel if WDA_RELAY_HOST is configured. | ||
| Does nothing if the environment variable is not set (default behavior unchanged). | ||
|
|
||
| @param localPort The local WDA HTTP server port to forward requests to | ||
| */ | ||
| + (void)startIfConfiguredWithLocalPort:(NSUInteger)localPort; | ||
|
mykola-mokhnach marked this conversation as resolved.
Outdated
|
||
|
|
||
| @end | ||
|
|
||
| NS_ASSUME_NONNULL_END | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.