microsoft/vscode-react-native

Public

mirrored fromhttps://github.com/microsoft/vscode-react-nativeAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
dev/v-zhenyuan/update-parameters

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/extension/networkInspector/networkInspectorServer.ts

404lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT license. See LICENSE file in the project root for details.
3
4/* eslint-disable */
5/* eslint-enable prettier/prettier*/
6
7import { RSocketServer } from "rsocket-core";
8import RSocketTCPServer from "rsocket-tcp-server";
9import { AdbHelper } from "../android/adb";
10import { Single } from "rsocket-flowable";
11import { appNameWithUpdateHint, buildClientId } from "./clientUtils";
12import { SecureClientQuery, ClientCsrQuery, ClientDevice, ClientQuery } from "./clientDevice";
13import { OutputChannelLogger } from "../log/OutputChannelLogger";
14import { Responder, Payload, ReactiveSocket } from "rsocket-types";
15import {
16 CertificateProvider,
17 SecureServerConfig,
18 CertificateExchangeMedium,
19} from "./certificateProvider";
20import { ClientOS } from "./clientUtils";
21import * as net from "net";
22import * as tls from "tls";
23import * as nls from "vscode-nls";
24import { InspectorViewType } from "./views/inspectorView";
25import { TipNotificationService } from "../services/tipsNotificationsService/tipsNotificationService";
26nls.config({
27 messageFormat: nls.MessageFormat.bundle,
28 bundleFormat: nls.BundleFormat.standalone,
29})();
30const localize = nls.loadMessageBundle();
31
32/**
33 * @preserve
34 * Start region: the code is borrowed from https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
35 *
36 * Copyright (c) Facebook, Inc. and its affiliates.
37 *
38 * This source code is licensed under the MIT license found in the
39 * LICENSE file in the root directory of this source tree.
40 *
41 * @format
42 */
43
44function transformCertificateExchangeMediumToType(
45 medium: number | undefined,
46): CertificateExchangeMedium {
47 if (medium == 1) {
48 return "FS_ACCESS";
49 } else if (medium == 2) {
50 return "WWW";
51 } else {
52 return "FS_ACCESS";
53 }
54}
55
56export const NETWORK_INSPECTOR_LOG_CHANNEL_NAME = "Network Inspector";
57
58export class NetworkInspectorServer {
59 public static readonly SecureServerPort = 8088;
60 public static readonly InsecureServerPort = 8089;
61
62 private connections: Map<string, ClientDevice>;
63 private secureServer: RSocketServer<any, any> | null = null;
64 private insecureServer: RSocketServer<any, any> | null = null;
65 private certificateProvider!: CertificateProvider;
66 private initialisePromise: Promise<void> | null = null;
67 private logger: OutputChannelLogger;
68
69 constructor() {
70 this.connections = new Map<string, ClientDevice>();
71 this.logger = OutputChannelLogger.getChannel(NETWORK_INSPECTOR_LOG_CHANNEL_NAME);
72 }
73
74 public async start(adbHelper: AdbHelper): Promise<void> {
75 this.logger.info(localize("StartNetworkinspector", "Starting Network inspector"));
76 TipNotificationService.getInstance().setKnownDateForFeatureById("networkInspector");
77 TipNotificationService.getInstance().showTipNotification(
78 false,
79 "networkInspectorLogsColorTheme",
80 );
81 this.initialisePromise = new Promise(async (resolve, reject) => {
82 this.certificateProvider = new CertificateProvider(adbHelper);
83
84 try {
85 let options = await this.certificateProvider.loadSecureServerConfig();
86 this.secureServer = await this.startServer(
87 NetworkInspectorServer.SecureServerPort,
88 options,
89 );
90 this.insecureServer = await this.startServer(
91 NetworkInspectorServer.InsecureServerPort,
92 );
93 } catch (err) {
94 return reject(err);
95 }
96
97 this.logger.info(localize("NetworkInspectorWorking", "Network inspector is working"));
98 resolve();
99 });
100 return this.initialisePromise;
101 }
102
103 public async stop(): Promise<void> {
104 if (this.initialisePromise) {
105 try {
106 await this.initialisePromise;
107 } catch (err) {
108 this.logger.error((err as Error).toString());
109 }
110 if (this.secureServer) {
111 this.secureServer.stop();
112 }
113 if (this.insecureServer) {
114 this.insecureServer.stop();
115 }
116 }
117 this.logger.info(localize("NetworkInspectorStopped", "Network inspector has been stopped"));
118 }
119
120 private async startServer(
121 port: number,
122 sslConfig?: SecureServerConfig,
123 ): Promise<RSocketServer<any, any>> {
124 return new Promise((resolve, reject) => {
125 let rsServer: RSocketServer<any, any> | undefined; // eslint-disable-line prefer-const
126 const serverFactory = (onConnect: (socket: net.Socket) => void) => {
127 const transportServer = sslConfig
128 ? tls.createServer(sslConfig, socket => {
129 onConnect(socket);
130 })
131 : net.createServer(onConnect);
132 transportServer
133 .on("error", err => {
134 this.logger.error(
135 localize(
136 "ErrorOpeningNetworkInspectorServerOnPort",
137 "Error while opening Network inspector server on port {0}",
138 port,
139 ),
140 );
141 reject(err);
142 })
143 .on("listening", () => {
144 this.logger.debug(
145 `${
146 sslConfig ? "Secure" : "Certificate"
147 } server started on port ${port}`,
148 );
149 resolve(rsServer!);
150 });
151 return transportServer;
152 };
153 rsServer = new RSocketServer({
154 getRequestHandler: sslConfig
155 ? this.trustedRequestHandler
156 : this.untrustedRequestHandler,
157 transport: new RSocketTCPServer({
158 port: port,
159 serverFactory: serverFactory,
160 }),
161 });
162 rsServer && rsServer.start();
163 });
164 }
165
166 private trustedRequestHandler = (
167 socket: ReactiveSocket<string, any>,
168 payload: Payload<string, any>,
169 ): Partial<Responder<string, any>> => {
170 // eslint-disable-next-line @typescript-eslint/no-this-alias
171 const server = this;
172 if (!payload.data) {
173 return {};
174 }
175
176 const clientData: SecureClientQuery = JSON.parse(payload.data);
177
178 const { app, os, device, device_id, sdk_version, csr, csr_path, medium } = clientData;
179 const transformedMedium = transformCertificateExchangeMediumToType(medium);
180
181 const client: Promise<ClientDevice> = this.addConnection(
182 socket,
183 {
184 app,
185 os,
186 device,
187 device_id,
188 sdk_version,
189 medium: transformedMedium,
190 },
191 { csr, csr_path },
192 ).then(client => {
193 return (resolvedClient = client);
194 });
195 let resolvedClient: ClientDevice | undefined;
196
197 socket.connectionStatus().subscribe({
198 onNext(payload) {
199 if (payload.kind == "ERROR" || payload.kind == "CLOSED") {
200 client.then(client => {
201 server.logger.info(
202 localize(
203 "NIDeviceDisconnected",
204 "Device disconnected {0} from the Network inspector",
205 client.id,
206 ),
207 );
208 server.removeConnection(client.id);
209 });
210 }
211 },
212 onSubscribe(subscription) {
213 subscription.request(Number.MAX_SAFE_INTEGER);
214 },
215 onError(error) {
216 server.logger.error("Network inspector server connection status error ", error);
217 },
218 });
219
220 return {
221 fireAndForget: (payload: { data: string }) => {
222 if (resolvedClient) {
223 resolvedClient.onMessage(payload.data);
224 } else {
225 client.then(client => {
226 client.onMessage(payload.data);
227 });
228 }
229 },
230 };
231 };
232
233 private untrustedRequestHandler = (
234 _socket: ReactiveSocket<string, any>,
235 payload: Payload<string, any>,
236 ): Partial<Responder<string, any>> => {
237 if (!payload.data) {
238 return {};
239 }
240 const clientData: ClientQuery = JSON.parse(payload.data);
241
242 return {
243 requestResponse: (payload: Payload<string, any>): Single<Payload<string, any>> => {
244 if (typeof payload.data !== "string") {
245 return new Single(() => {});
246 }
247
248 let rawData;
249 try {
250 rawData = JSON.parse(payload.data);
251 } catch (err) {
252 this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
253 return new Single(() => {});
254 }
255
256 const json: {
257 method: "signCertificate";
258 csr: string;
259 destination: string;
260 medium: number | undefined; // OSS's older Client SDK might not send medium information. This is not an issue for internal FB users, as Flipper release is insync with client SDK through launcher.
261 } = rawData;
262
263 if (json.method === "signCertificate") {
264 this.logger.debug("CSR received from device");
265
266 const { csr, destination, medium } = json;
267 return new Single(subscriber => {
268 subscriber.onSubscribe(undefined);
269 this.certificateProvider
270 .processCertificateSigningRequest(
271 csr,
272 clientData.os,
273 destination,
274 transformCertificateExchangeMediumToType(medium),
275 )
276 .then(result => {
277 subscriber.onComplete({
278 data: JSON.stringify({
279 deviceId: result.deviceId,
280 }),
281 metadata: "",
282 });
283 })
284 .catch(e => {
285 this.logger.error(e.toString());
286 subscriber.onError(e);
287 });
288 });
289 }
290 return new Single(() => {});
291 },
292
293 // Leaving this here for a while for backwards compatibility,
294 // but for up to date SDKs it will no longer used.
295 // We can delete it after the SDK change has been using requestResponse for a few weeks.
296 fireAndForget: (payload: Payload<string, any>) => {
297 if (typeof payload.data !== "string") {
298 return;
299 }
300
301 let json:
302 | {
303 method: "signCertificate";
304 csr: string;
305 destination: string;
306 medium: number | undefined;
307 }
308 | undefined;
309 try {
310 json = JSON.parse(payload.data);
311 } catch (err) {
312 this.logger.error(`Network inspector: invalid JSON: ${payload.data}`);
313 return;
314 }
315
316 if (json && json.method === "signCertificate") {
317 this.logger.debug("CSR received from device");
318 const { csr, destination, medium } = json;
319 this.certificateProvider
320 .processCertificateSigningRequest(
321 csr,
322 clientData.os,
323 destination,
324 transformCertificateExchangeMediumToType(medium),
325 )
326 .catch(e => {
327 this.logger.error(e.toString());
328 });
329 }
330 },
331 };
332 };
333
334 private async addConnection(
335 conn: ReactiveSocket<any, any>,
336 query: ClientQuery & { medium: CertificateExchangeMedium },
337 csrQuery: ClientCsrQuery,
338 ): Promise<ClientDevice> {
339 // try to get id by comparing giving `csr` to file from `csr_path`
340 // otherwise, use given device_id
341 const { csr_path, csr } = csrQuery;
342 // For iOS we do not need to confirm the device id, as it never changes unlike android.
343 return (
344 csr_path && csr && query.os !== ClientOS.iOS
345 ? this.certificateProvider.extractAppNameFromCSR(csr).then(appName => {
346 return this.certificateProvider.getTargetDeviceId(
347 query.os,
348 appName,
349 csr_path,
350 csr,
351 );
352 })
353 : Promise.resolve(query.device_id)
354 ).then(async csrId => {
355 query.device_id = csrId;
356 query.app = appNameWithUpdateHint(query);
357
358 const id = buildClientId(
359 {
360 app: query.app,
361 os: query.os,
362 device: query.device,
363 device_id: csrId,
364 },
365 this.logger,
366 );
367 this.logger.info(localize("NIDeviceConnected", "Device connected: {0}", id));
368
369 const client = new ClientDevice(
370 id,
371 query,
372 conn,
373 InspectorViewType.console,
374 this.logger,
375 );
376
377 client.init().then(() => {
378 this.logger.debug(`Device client initialised: ${id}`);
379 /* If a device gets disconnected without being cleaned up properly,
380 * Flipper won't be aware until it attempts to reconnect.
381 * When it does we need to terminate the zombie connection.
382 */
383 this.removeConnection(id);
384
385 this.connections.set(id, client);
386 });
387
388 return client;
389 });
390 }
391
392 /**
393 * @preserve
394 * End region: https://github.com/facebook/flipper/blob/master/desktop/app/src/server.tsx
395 */
396
397 private removeConnection(id: string) {
398 const clientDevice = this.connections.get(id);
399 if (clientDevice) {
400 clientDevice.connection && clientDevice.connection.close();
401 this.connections.delete(id);
402 }
403 }
404}