-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathapp-debug-socket-proxy-factory.ts
199 lines (163 loc) · 6.52 KB
/
app-debug-socket-proxy-factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
import { EventEmitter } from "events";
import { CONNECTION_ERROR_EVENT_NAME } from "../../constants";
import * as net from "net";
import * as ws from "ws";
import temp = require("temp");
import { MessageUnpackStream } from "ios-device-lib";
export class AppDebugSocketProxyFactory extends EventEmitter implements IAppDebugSocketProxyFactory {
private deviceWebServers: IDictionary<ws.Server> = {};
private deviceTcpServers: IDictionary<net.Server> = {};
constructor(private $logger: ILogger,
private $errors: IErrors,
private $options: IOptions,
private $net: INet) {
super();
}
public getTCPSocketProxy(deviceIdentifier: string, appId: string): net.Server {
return this.deviceTcpServers[`${deviceIdentifier}-${appId}`];
}
public async addTCPSocketProxy(device: Mobile.IiOSDevice, appId: string): Promise<net.Server> {
const cacheKey = `${device.deviceInfo.identifier}-${appId}`;
const existingServer = this.deviceTcpServers[cacheKey];
if (existingServer) {
this.$errors.failWithoutHelp(`TCP socket proxy is already running for device '${device.deviceInfo.identifier}' and app '${appId}'`);
}
this.$logger.info("\nSetting up proxy...\nPress Ctrl + C to terminate, or disconnect.\n");
const server = net.createServer({
allowHalfOpen: true
});
this.deviceTcpServers[cacheKey] = server;
server.on("connection", async (frontendSocket: net.Socket) => {
this.$logger.info("Frontend client connected.");
frontendSocket.on("end", () => {
this.$logger.info('Frontend socket closed!');
if (!this.$options.watch) {
process.exit(0);
}
});
const appDebugSocket = await device.getDebugSocket(appId);
this.$logger.info("Backend socket created.");
appDebugSocket.on("end", () => {
this.$logger.info("Backend socket closed!");
if (!this.$options.watch) {
process.exit(0);
}
});
frontendSocket.on("close", () => {
this.$logger.info("Frontend socket closed");
device.destroyDebugSocket(appId);
});
appDebugSocket.on("close", () => {
this.$logger.info("Backend socket closed");
frontendSocket.destroy();
server.close();
delete this.deviceTcpServers[cacheKey];
});
appDebugSocket.pipe(frontendSocket);
frontendSocket.pipe(appDebugSocket);
frontendSocket.resume();
});
const socketFileLocation = temp.path({ suffix: ".sock" });
server.listen(socketFileLocation);
if (!this.$options.client) {
this.$logger.info("socket-file-location: " + socketFileLocation);
}
return server;
}
public async ensureWebSocketProxy(device: Mobile.IiOSDevice, appId: string): Promise<ws.Server> {
const existingWebProxy = this.deviceWebServers[`${device.deviceInfo.identifier}-${appId}`];
const result = existingWebProxy || await this.addWebSocketProxy(device, appId);
// TODO: do not remove till VSCode waits for this message in order to reattach
this.$logger.info("Opened localhost " + result.options.port);
return result;
}
private async addWebSocketProxy(device: Mobile.IiOSDevice, appId: string): Promise<ws.Server> {
const cacheKey = `${device.deviceInfo.identifier}-${appId}`;
const existingServer = this.deviceWebServers[cacheKey];
if (existingServer) {
this.$errors.failWithoutHelp(`Web socket proxy is already running for device '${device.deviceInfo.identifier}' and app '${appId}'`);
}
// NOTE: We will try to provide command line options to select ports, at least on the localhost.
const localPort = await this.$net.getAvailablePortInRange(41000);
this.$logger.info("\nSetting up debugger proxy...\nPress Ctrl + C to terminate, or disconnect.\n");
// NB: When the inspector frontend connects we might not have connected to the inspector backend yet.
// That's why we use the verifyClient callback of the websocket server to stall the upgrade request until we connect.
// We store the socket that connects us to the device in the upgrade request object itself and later on retrieve it
// in the connection callback.
const server = new ws.Server(<any>{
port: localPort,
host: "localhost",
verifyClient: async (info: any, callback: (res: boolean, code?: number, message?: string) => void) => {
let acceptHandshake = true;
this.$logger.info("Frontend client connected.");
let appDebugSocket;
try {
appDebugSocket = await device.getDebugSocket(appId);
this.$logger.info("Backend socket created.");
info.req["__deviceSocket"] = appDebugSocket;
} catch (err) {
err.deviceIdentifier = device.deviceInfo.identifier;
this.$logger.trace(err);
this.emit(CONNECTION_ERROR_EVENT_NAME, err);
acceptHandshake = false;
this.$logger.warn(`Cannot connect to device socket. The error message is '${err.message}'.`);
}
callback(acceptHandshake);
}
});
this.deviceWebServers[cacheKey] = server;
server.on("connection", (webSocket, req) => {
const encoding = "utf16le";
const appDebugSocket: net.Socket = (<any>req)["__deviceSocket"];
const packets = new MessageUnpackStream();
appDebugSocket.pipe(packets);
packets.on("data", (buffer: Buffer) => {
const message = buffer.toString(encoding);
if (webSocket.readyState === webSocket.OPEN) {
webSocket.send(message);
} else {
this.$logger.trace(`Received message ${message}, but unable to send it to webSocket as its state is: ${webSocket.readyState}`);
}
});
webSocket.on("error", err => {
this.$logger.trace("Error on debugger websocket", err);
});
appDebugSocket.on("error", err => {
this.$logger.trace("Error on debugger deviceSocket", err);
});
webSocket.on("message", (message: string) => {
const length = Buffer.byteLength(message, encoding);
const payload = Buffer.allocUnsafe(length + 4);
payload.writeInt32BE(length, 0);
payload.write(message, 4, length, encoding);
appDebugSocket.write(payload);
});
appDebugSocket.on("close", () => {
this.$logger.info("Backend socket closed!");
webSocket.close();
});
webSocket.on("close", () => {
this.$logger.info('Frontend socket closed!');
appDebugSocket.unpipe(packets);
packets.destroy();
device.destroyDebugSocket(appId);
if (!this.$options.watch) {
process.exit(0);
}
});
});
return server;
}
public removeAllProxies() {
let deviceId;
for (deviceId in this.deviceWebServers) {
this.deviceWebServers[deviceId].close();
}
for (deviceId in this.deviceTcpServers) {
this.deviceTcpServers[deviceId].close();
}
this.deviceWebServers = {};
this.deviceTcpServers = {};
}
}
$injector.register("appDebugSocketProxyFactory", AppDebugSocketProxyFactory);