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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
|
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as crypto from 'crypto';
import * as fs from 'fs';
import * as http from 'http';
import * as net from 'net';
import { performance } from 'perf_hooks';
import * as url from 'url';
import { LoaderStats } from 'vs/base/common/amd';
import { VSBuffer } from 'vs/base/common/buffer';
import { setUnexpectedErrorHandler } from 'vs/base/common/errors';
import { isEqualOrParent } from 'vs/base/common/extpath';
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { connectionTokenQueryName, FileAccess, Schemas } from 'vs/base/common/network';
import { dirname, join } from 'vs/base/common/path';
import * as perf from 'vs/base/common/performance';
import * as platform from 'vs/base/common/platform';
import { createRegExp, escapeRegExpCharacters } from 'vs/base/common/strings';
import { URI } from 'vs/base/common/uri';
import { generateUuid } from 'vs/base/common/uuid';
import { findFreePort } from 'vs/base/node/ports';
import { PersistentProtocol } from 'vs/base/parts/ipc/common/ipc.net';
import { NodeSocket, WebSocketNodeSocket } from 'vs/base/parts/ipc/node/ipc.net';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { ILogService } from 'vs/platform/log/common/log';
import { IProductService } from 'vs/platform/product/common/productService';
import { ConnectionType, ConnectionTypeRequest, ErrorMessage, HandshakeMessage, IRemoteExtensionHostStartParams, ITunnelConnectionStartParams, SignRequest } from 'vs/platform/remote/common/remoteAgentConnection';
import { RemoteAgentConnectionContext } from 'vs/platform/remote/common/remoteAgentEnvironment';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { ExtensionHostConnection } from 'vs/server/node/extensionHostConnection';
import { ManagementConnection } from 'vs/server/node/remoteExtensionManagement';
import { determineServerConnectionToken, requestHasValidConnectionToken as httpRequestHasValidConnectionToken, ServerConnectionToken, ServerConnectionTokenParseError, ServerConnectionTokenType } from 'vs/server/node/serverConnectionToken';
import { IServerEnvironmentService, ServerParsedArgs } from 'vs/server/node/serverEnvironmentService';
import { setupServerServices, SocketServer } from 'vs/server/node/serverServices';
import { serveError, serveFile, WebClientServer } from 'vs/server/node/webClientServer';
const SHUTDOWN_TIMEOUT = 5 * 60 * 1000;
declare module vsda {
// the signer is a native module that for historical reasons uses a lower case class name
// eslint-disable-next-line @typescript-eslint/naming-convention
export class signer {
sign(arg: string): string;
}
// eslint-disable-next-line @typescript-eslint/naming-convention
export class validator {
createNewMessage(arg: string): string;
validate(arg: string): 'ok' | 'error';
}
}
export class RemoteExtensionHostAgentServer extends Disposable implements IServerAPI {
private readonly _extHostConnections: { [reconnectionToken: string]: ExtensionHostConnection };
private readonly _managementConnections: { [reconnectionToken: string]: ManagementConnection };
private readonly _allReconnectionTokens: Set<string>;
private readonly _webClientServer: WebClientServer | null;
private readonly _webEndpointOriginChecker = WebEndpointOriginChecker.create(this._productService);
private shutdownTimer: NodeJS.Timer | undefined;
constructor(
private readonly _socketServer: SocketServer<RemoteAgentConnectionContext>,
private readonly _connectionToken: ServerConnectionToken,
private readonly _vsdaMod: typeof vsda | null,
hasWebClient: boolean,
@IServerEnvironmentService private readonly _environmentService: IServerEnvironmentService,
@IProductService private readonly _productService: IProductService,
@ILogService private readonly _logService: ILogService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
) {
super();
this._extHostConnections = Object.create(null);
this._managementConnections = Object.create(null);
this._allReconnectionTokens = new Set<string>();
this._webClientServer = (
hasWebClient
? this._instantiationService.createInstance(WebClientServer, this._connectionToken)
: null
);
this._logService.info(`Extension host agent started.`);
}
public async handleRequest(req: http.IncomingMessage, res: http.ServerResponse) {
// Only serve GET requests
if (req.method !== 'GET') {
return serveError(req, res, 405, `Unsupported method ${req.method}`);
}
if (!req.url) {
return serveError(req, res, 400, `Bad request.`);
}
const parsedUrl = url.parse(req.url, true);
const pathname = parsedUrl.pathname;
if (!pathname) {
return serveError(req, res, 400, `Bad request.`);
}
// Version
if (pathname === '/version') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
return res.end(this._productService.commit || '');
}
// Delay shutdown
if (pathname === '/delay-shutdown') {
this._delayShutdown();
res.writeHead(200);
return res.end('OK');
}
if (!httpRequestHasValidConnectionToken(this._connectionToken, req, parsedUrl)) {
// invalid connection token
return serveError(req, res, 403, `Forbidden.`);
}
if (pathname === '/vscode-remote-resource') {
// Handle HTTP requests for resources rendered in the rich client (images, fonts, etc.)
// These resources could be files shipped with extensions or even workspace files.
const desiredPath = parsedUrl.query['path'];
if (typeof desiredPath !== 'string') {
return serveError(req, res, 400, `Bad request.`);
}
let filePath: string;
try {
filePath = URI.from({ scheme: Schemas.file, path: desiredPath }).fsPath;
} catch (err) {
return serveError(req, res, 400, `Bad request.`);
}
const responseHeaders: Record<string, string> = Object.create(null);
if (this._environmentService.isBuilt) {
if (isEqualOrParent(filePath, this._environmentService.builtinExtensionsPath, !platform.isLinux)
|| isEqualOrParent(filePath, this._environmentService.extensionsPath, !platform.isLinux)
) {
responseHeaders['Cache-Control'] = 'public, max-age=31536000';
}
}
// Allow cross origin requests from the web worker extension host
responseHeaders['Vary'] = 'Origin';
const requestOrigin = req.headers['origin'];
if (requestOrigin && this._webEndpointOriginChecker.matches(requestOrigin)) {
responseHeaders['Access-Control-Allow-Origin'] = requestOrigin;
}
return serveFile(this._logService, req, res, filePath, responseHeaders);
}
// workbench web UI
if (this._webClientServer) {
this._webClientServer.handle(req, res, parsedUrl);
return;
}
res.writeHead(404, { 'Content-Type': 'text/plain' });
return res.end('Not found');
}
public handleUpgrade(req: http.IncomingMessage, socket: net.Socket) {
let reconnectionToken = generateUuid();
let isReconnection = false;
let skipWebSocketFrames = false;
if (req.url) {
const query = url.parse(req.url, true).query;
if (typeof query.reconnectionToken === 'string') {
reconnectionToken = query.reconnectionToken;
}
if (query.reconnection === 'true') {
isReconnection = true;
}
if (query.skipWebSocketFrames === 'true') {
skipWebSocketFrames = true;
}
}
if (req.headers['upgrade'] !== 'websocket') {
socket.end('HTTP/1.1 400 Bad Request');
return;
}
// https://tools.ietf.org/html/rfc6455#section-4
const requestNonce = req.headers['sec-websocket-key'];
const hash = crypto.createHash('sha1');
hash.update(requestNonce + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11');
const responseNonce = hash.digest('base64');
const responseHeaders = [
`HTTP/1.1 101 Switching Protocols`,
`Upgrade: websocket`,
`Connection: Upgrade`,
`Sec-WebSocket-Accept: ${responseNonce}`
];
// See https://tools.ietf.org/html/rfc7692#page-12
let permessageDeflate = false;
if (!skipWebSocketFrames && !this._environmentService.args['disable-websocket-compression'] && req.headers['sec-websocket-extensions']) {
const websocketExtensionOptions = Array.isArray(req.headers['sec-websocket-extensions']) ? req.headers['sec-websocket-extensions'] : [req.headers['sec-websocket-extensions']];
for (const websocketExtensionOption of websocketExtensionOptions) {
if (/\b((server_max_window_bits)|(server_no_context_takeover)|(client_no_context_takeover))\b/.test(websocketExtensionOption)) {
// sorry, the server does not support zlib parameter tweaks
continue;
}
if (/\b(permessage-deflate)\b/.test(websocketExtensionOption)) {
permessageDeflate = true;
responseHeaders.push(`Sec-WebSocket-Extensions: permessage-deflate`);
break;
}
if (/\b(x-webkit-deflate-frame)\b/.test(websocketExtensionOption)) {
permessageDeflate = true;
responseHeaders.push(`Sec-WebSocket-Extensions: x-webkit-deflate-frame`);
break;
}
}
}
socket.write(responseHeaders.join('\r\n') + '\r\n\r\n');
// Never timeout this socket due to inactivity!
socket.setTimeout(0);
// Disable Nagle's algorithm
socket.setNoDelay(true);
// Finally!
if (skipWebSocketFrames) {
this._handleWebSocketConnection(new NodeSocket(socket, `server-connection-${reconnectionToken}`), isReconnection, reconnectionToken);
} else {
this._handleWebSocketConnection(new WebSocketNodeSocket(new NodeSocket(socket, `server-connection-${reconnectionToken}`), permessageDeflate, null, true), isReconnection, reconnectionToken);
}
}
public handleServerError(err: Error): void {
this._logService.error(`Error occurred in server`);
this._logService.error(err);
}
// Eventually cleanup
private _getRemoteAddress(socket: NodeSocket | WebSocketNodeSocket): string {
let _socket: net.Socket;
if (socket instanceof NodeSocket) {
_socket = socket.socket;
} else {
_socket = socket.socket.socket;
}
return _socket.remoteAddress || `<unknown>`;
}
private async _rejectWebSocketConnection(logPrefix: string, protocol: PersistentProtocol, reason: string): Promise<void> {
const socket = protocol.getSocket();
this._logService.error(`${logPrefix} ${reason}.`);
const errMessage: ErrorMessage = {
type: 'error',
reason: reason
};
protocol.sendControl(VSBuffer.fromString(JSON.stringify(errMessage)));
protocol.dispose();
await socket.drain();
socket.dispose();
}
/**
* NOTE: Avoid using await in this method!
* The problem is that await introduces a process.nextTick due to the implicit Promise.then
* This can lead to some bytes being interpreted and a control message being emitted before the next listener has a chance to be registered.
*/
private _handleWebSocketConnection(socket: NodeSocket | WebSocketNodeSocket, isReconnection: boolean, reconnectionToken: string): void {
const remoteAddress = this._getRemoteAddress(socket);
const logPrefix = `[${remoteAddress}][${reconnectionToken.substr(0, 8)}]`;
const protocol = new PersistentProtocol(socket);
const validator = this._vsdaMod ? new this._vsdaMod.validator() : null;
const signer = this._vsdaMod ? new this._vsdaMod.signer() : null;
const enum State {
WaitingForAuth,
WaitingForConnectionType,
Done,
Error
}
let state = State.WaitingForAuth;
const rejectWebSocketConnection = (msg: string) => {
state = State.Error;
listener.dispose();
this._rejectWebSocketConnection(logPrefix, protocol, msg);
};
const listener = protocol.onControlMessage((raw) => {
if (state === State.WaitingForAuth) {
let msg1: HandshakeMessage;
try {
msg1 = <HandshakeMessage>JSON.parse(raw.toString());
} catch (err) {
return rejectWebSocketConnection(`Malformed first message`);
}
if (msg1.type !== 'auth') {
return rejectWebSocketConnection(`Invalid first message`);
}
if (this._connectionToken.type === ServerConnectionTokenType.Mandatory && !this._connectionToken.validate(msg1.auth)) {
return rejectWebSocketConnection(`Unauthorized client refused: auth mismatch`);
}
// Send `sign` request
let signedData = generateUuid();
if (signer) {
try {
signedData = signer.sign(msg1.data);
} catch (e) {
}
}
let someText = generateUuid();
if (validator) {
try {
someText = validator.createNewMessage(someText);
} catch (e) {
}
}
const signRequest: SignRequest = {
type: 'sign',
data: someText,
signedData: signedData
};
protocol.sendControl(VSBuffer.fromString(JSON.stringify(signRequest)));
state = State.WaitingForConnectionType;
} else if (state === State.WaitingForConnectionType) {
let msg2: HandshakeMessage;
try {
msg2 = <HandshakeMessage>JSON.parse(raw.toString());
} catch (err) {
return rejectWebSocketConnection(`Malformed second message`);
}
if (msg2.type !== 'connectionType') {
return rejectWebSocketConnection(`Invalid second message`);
}
if (typeof msg2.signedData !== 'string') {
return rejectWebSocketConnection(`Invalid second message field type`);
}
const rendererCommit = msg2.commit;
const myCommit = this._productService.commit;
if (rendererCommit && myCommit) {
// Running in the built version where commits are defined
if (rendererCommit !== myCommit) {
return rejectWebSocketConnection(`Client refused: version mismatch`);
}
}
let valid = false;
if (!validator) {
valid = true;
} else if (this._connectionToken.validate(msg2.signedData)) {
// web client
valid = true;
} else {
try {
valid = validator.validate(msg2.signedData) === 'ok';
} catch (e) {
}
}
if (!valid) {
if (this._environmentService.isBuilt) {
return rejectWebSocketConnection(`Unauthorized client refused`);
} else {
this._logService.error(`${logPrefix} Unauthorized client handshake failed but we proceed because of dev mode.`);
}
}
// We have received a new connection.
// This indicates that the server owner has connectivity.
// Therefore we will shorten the reconnection grace period for disconnected connections!
for (let key in this._managementConnections) {
const managementConnection = this._managementConnections[key];
managementConnection.shortenReconnectionGraceTimeIfNecessary();
}
for (let key in this._extHostConnections) {
const extHostConnection = this._extHostConnections[key];
extHostConnection.shortenReconnectionGraceTimeIfNecessary();
}
state = State.Done;
listener.dispose();
this._handleConnectionType(remoteAddress, logPrefix, protocol, socket, isReconnection, reconnectionToken, msg2);
}
});
}
private async _handleConnectionType(remoteAddress: string, _logPrefix: string, protocol: PersistentProtocol, socket: NodeSocket | WebSocketNodeSocket, isReconnection: boolean, reconnectionToken: string, msg: ConnectionTypeRequest): Promise<void> {
const logPrefix = (
msg.desiredConnectionType === ConnectionType.Management
? `${_logPrefix}[ManagementConnection]`
: msg.desiredConnectionType === ConnectionType.ExtensionHost
? `${_logPrefix}[ExtensionHostConnection]`
: _logPrefix
);
if (msg.desiredConnectionType === ConnectionType.Management) {
// This should become a management connection
if (isReconnection) {
// This is a reconnection
if (!this._managementConnections[reconnectionToken]) {
if (!this._allReconnectionTokens.has(reconnectionToken)) {
// This is an unknown reconnection token
return this._rejectWebSocketConnection(logPrefix, protocol, `Unknown reconnection token (never seen)`);
} else {
// This is a connection that was seen in the past, but is no longer valid
return this._rejectWebSocketConnection(logPrefix, protocol, `Unknown reconnection token (seen before)`);
}
}
protocol.sendControl(VSBuffer.fromString(JSON.stringify({ type: 'ok' })));
const dataChunk = protocol.readEntireBuffer();
protocol.dispose();
this._managementConnections[reconnectionToken].acceptReconnection(remoteAddress, socket, dataChunk);
} else {
// This is a fresh connection
if (this._managementConnections[reconnectionToken]) {
// Cannot have two concurrent connections using the same reconnection token
return this._rejectWebSocketConnection(logPrefix, protocol, `Duplicate reconnection token`);
}
protocol.sendControl(VSBuffer.fromString(JSON.stringify({ type: 'ok' })));
const con = new ManagementConnection(this._logService, reconnectionToken, remoteAddress, protocol);
this._socketServer.acceptConnection(con.protocol, con.onClose);
this._managementConnections[reconnectionToken] = con;
this._allReconnectionTokens.add(reconnectionToken);
con.onClose(() => {
delete this._managementConnections[reconnectionToken];
});
}
} else if (msg.desiredConnectionType === ConnectionType.ExtensionHost) {
// This should become an extension host connection
const startParams0 = <IRemoteExtensionHostStartParams>msg.args || { language: 'en' };
const startParams = await this._updateWithFreeDebugPort(startParams0);
if (startParams.port) {
this._logService.trace(`${logPrefix} - startParams debug port ${startParams.port}`);
}
this._logService.trace(`${logPrefix} - startParams language: ${startParams.language}`);
this._logService.trace(`${logPrefix} - startParams env: ${JSON.stringify(startParams.env)}`);
if (isReconnection) {
// This is a reconnection
if (!this._extHostConnections[reconnectionToken]) {
if (!this._allReconnectionTokens.has(reconnectionToken)) {
// This is an unknown reconnection token
return this._rejectWebSocketConnection(logPrefix, protocol, `Unknown reconnection token (never seen)`);
} else {
// This is a connection that was seen in the past, but is no longer valid
return this._rejectWebSocketConnection(logPrefix, protocol, `Unknown reconnection token (seen before)`);
}
}
protocol.sendPause();
protocol.sendControl(VSBuffer.fromString(JSON.stringify(startParams.port ? { debugPort: startParams.port } : {})));
const dataChunk = protocol.readEntireBuffer();
protocol.dispose();
this._extHostConnections[reconnectionToken].acceptReconnection(remoteAddress, socket, dataChunk);
} else {
// This is a fresh connection
if (this._extHostConnections[reconnectionToken]) {
// Cannot have two concurrent connections using the same reconnection token
return this._rejectWebSocketConnection(logPrefix, protocol, `Duplicate reconnection token`);
}
protocol.sendPause();
protocol.sendControl(VSBuffer.fromString(JSON.stringify(startParams.port ? { debugPort: startParams.port } : {})));
const dataChunk = protocol.readEntireBuffer();
protocol.dispose();
const con = this._instantiationService.createInstance(ExtensionHostConnection, reconnectionToken, remoteAddress, socket, dataChunk);
this._extHostConnections[reconnectionToken] = con;
this._allReconnectionTokens.add(reconnectionToken);
con.onClose(() => {
delete this._extHostConnections[reconnectionToken];
this._onDidCloseExtHostConnection();
});
con.start(startParams);
}
} else if (msg.desiredConnectionType === ConnectionType.Tunnel) {
const tunnelStartParams = <ITunnelConnectionStartParams>msg.args;
this._createTunnel(protocol, tunnelStartParams);
} else {
return this._rejectWebSocketConnection(logPrefix, protocol, `Unknown initial data received`);
}
}
private async _createTunnel(protocol: PersistentProtocol, tunnelStartParams: ITunnelConnectionStartParams): Promise<void> {
const remoteSocket = (<NodeSocket>protocol.getSocket()).socket;
const dataChunk = protocol.readEntireBuffer();
protocol.dispose();
remoteSocket.pause();
const localSocket = await this._connectTunnelSocket(tunnelStartParams.host, tunnelStartParams.port);
if (dataChunk.byteLength > 0) {
localSocket.write(dataChunk.buffer);
}
localSocket.on('end', () => remoteSocket.end());
localSocket.on('close', () => remoteSocket.end());
localSocket.on('error', () => remoteSocket.destroy());
remoteSocket.on('end', () => localSocket.end());
remoteSocket.on('close', () => localSocket.end());
remoteSocket.on('error', () => localSocket.destroy());
localSocket.pipe(remoteSocket);
remoteSocket.pipe(localSocket);
}
private _connectTunnelSocket(host: string, port: number): Promise<net.Socket> {
return new Promise<net.Socket>((c, e) => {
const socket = net.createConnection(
{
host: host,
port: port
}, () => {
socket.removeListener('error', e);
socket.pause();
c(socket);
}
);
socket.once('error', e);
});
}
private _updateWithFreeDebugPort(startParams: IRemoteExtensionHostStartParams): Thenable<IRemoteExtensionHostStartParams> {
if (typeof startParams.port === 'number') {
return findFreePort(startParams.port, 10 /* try 10 ports */, 5000 /* try up to 5 seconds */).then(freePort => {
startParams.port = freePort;
return startParams;
});
}
// No port clear debug configuration.
startParams.debugId = undefined;
startParams.port = undefined;
startParams.break = undefined;
return Promise.resolve(startParams);
}
private async _onDidCloseExtHostConnection(): Promise<void> {
if (!this._environmentService.args['enable-remote-auto-shutdown']) {
return;
}
this._cancelShutdown();
const hasActiveExtHosts = !!Object.keys(this._extHostConnections).length;
if (!hasActiveExtHosts) {
console.log('Last EH closed, waiting before shutting down');
this._logService.info('Last EH closed, waiting before shutting down');
this._waitThenShutdown();
}
}
private _waitThenShutdown(): void {
if (!this._environmentService.args['enable-remote-auto-shutdown']) {
return;
}
if (this._environmentService.args['remote-auto-shutdown-without-delay']) {
this._shutdown();
} else {
this.shutdownTimer = setTimeout(() => {
this.shutdownTimer = undefined;
this._shutdown();
}, SHUTDOWN_TIMEOUT);
}
}
private _shutdown(): void {
const hasActiveExtHosts = !!Object.keys(this._extHostConnections).length;
if (hasActiveExtHosts) {
console.log('New EH opened, aborting shutdown');
this._logService.info('New EH opened, aborting shutdown');
return;
} else {
console.log('Last EH closed, shutting down');
this._logService.info('Last EH closed, shutting down');
this.dispose();
process.exit(0);
}
}
/**
* If the server is in a shutdown timeout, cancel it and start over
*/
private _delayShutdown(): void {
if (this.shutdownTimer) {
console.log('Got delay-shutdown request while in shutdown timeout, delaying');
this._logService.info('Got delay-shutdown request while in shutdown timeout, delaying');
this._cancelShutdown();
this._waitThenShutdown();
}
}
private _cancelShutdown(): void {
if (this.shutdownTimer) {
console.log('Cancelling previous shutdown timeout');
this._logService.info('Cancelling previous shutdown timeout');
clearTimeout(this.shutdownTimer);
this.shutdownTimer = undefined;
}
}
}
export interface IServerAPI {
/**
* Do not remove!!. Called from server-main.js
*/
handleRequest(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>;
/**
* Do not remove!!. Called from server-main.js
*/
handleUpgrade(req: http.IncomingMessage, socket: net.Socket): void;
/**
* Do not remove!!. Called from server-main.js
*/
handleServerError(err: Error): void;
/**
* Do not remove!!. Called from server-main.js
*/
dispose(): void;
}
export async function createServer(address: string | net.AddressInfo | null, args: ServerParsedArgs, REMOTE_DATA_FOLDER: string): Promise<IServerAPI> {
const connectionToken = await determineServerConnectionToken(args);
if (connectionToken instanceof ServerConnectionTokenParseError) {
console.warn(connectionToken.message);
process.exit(1);
}
const disposables = new DisposableStore();
const { socketServer, instantiationService } = await setupServerServices(connectionToken, args, REMOTE_DATA_FOLDER, disposables);
// Set the unexpected error handler after the services have been initialized, to avoid having
// the telemetry service overwrite our handler
instantiationService.invokeFunction((accessor) => {
const logService = accessor.get(ILogService);
setUnexpectedErrorHandler(err => {
// See https://github.com/microsoft/vscode-remote-release/issues/6481
// In some circumstances, console.error will throw an asynchronous error. This asynchronous error
// will end up here, and then it will be logged again, thus creating an endless asynchronous loop.
// Here we try to break the loop by ignoring EPIPE errors that include our own unexpected error handler in the stack.
if (err && err.code === 'EPIPE' && err.syscall === 'write' && err.stack && /unexpectedErrorHandler/.test(err.stack)) {
return;
}
logService.error(err);
});
});
//
// On Windows, exit early with warning message to users about potential security issue
// if there is node_modules folder under home drive or Users folder.
//
instantiationService.invokeFunction((accessor) => {
const logService = accessor.get(ILogService);
if (process.platform === 'win32' && process.env.HOMEDRIVE && process.env.HOMEPATH) {
const homeDirModulesPath = join(process.env.HOMEDRIVE, 'node_modules');
const userDir = dirname(join(process.env.HOMEDRIVE, process.env.HOMEPATH));
const userDirModulesPath = join(userDir, 'node_modules');
if (fs.existsSync(homeDirModulesPath) || fs.existsSync(userDirModulesPath)) {
const message = `
*
* !!!! Server terminated due to presence of CVE-2020-1416 !!!!
*
* Please remove the following directories and re-try
* ${homeDirModulesPath}
* ${userDirModulesPath}
*
* For more information on the vulnerability https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-1416
*
`;
logService.warn(message);
console.warn(message);
process.exit(0);
}
}
});
const vsdaMod = instantiationService.invokeFunction((accessor) => {
const logService = accessor.get(ILogService);
const hasVSDA = fs.existsSync(join(FileAccess.asFileUri('', require).fsPath, '../node_modules/vsda'));
if (hasVSDA) {
try {
return <typeof vsda>require.__$__nodeRequire('vsda');
} catch (err) {
logService.error(err);
}
}
return null;
});
const hasWebClient = fs.existsSync(FileAccess.asFileUri('vs/code/browser/workbench/workbench.html', require).fsPath);
if (hasWebClient && address && typeof address !== 'string') {
// ships the web ui!
const queryPart = (connectionToken.type !== ServerConnectionTokenType.None ? `?${connectionTokenQueryName}=${connectionToken.value}` : '');
console.log(`Web UI available at http://localhost${address.port === 80 ? '' : `:${address.port}`}/${queryPart}`);
}
const remoteExtensionHostAgentServer = instantiationService.createInstance(RemoteExtensionHostAgentServer, socketServer, connectionToken, vsdaMod, hasWebClient);
perf.mark('code/server/ready');
const currentTime = performance.now();
const vscodeServerStartTime: number = (<any>global).vscodeServerStartTime;
const vscodeServerListenTime: number = (<any>global).vscodeServerListenTime;
const vscodeServerCodeLoadedTime: number = (<any>global).vscodeServerCodeLoadedTime;
instantiationService.invokeFunction((accessor) => {
const telemetryService = accessor.get(ITelemetryService);
type ServerStartClassification = {
startTime: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' };
startedTime: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' };
codeLoadedTime: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' };
readyTime: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth' };
};
type ServerStartEvent = {
startTime: number;
startedTime: number;
codeLoadedTime: number;
readyTime: number;
};
telemetryService.publicLog2<ServerStartEvent, ServerStartClassification>('serverStart', {
startTime: vscodeServerStartTime,
startedTime: vscodeServerListenTime,
codeLoadedTime: vscodeServerCodeLoadedTime,
readyTime: currentTime
});
});
if (args['print-startup-performance']) {
const stats = LoaderStats.get();
let output = '';
output += '\n\n### Load AMD-module\n';
output += LoaderStats.toMarkdownTable(['Module', 'Duration'], stats.amdLoad);
output += '\n\n### Load commonjs-module\n';
output += LoaderStats.toMarkdownTable(['Module', 'Duration'], stats.nodeRequire);
output += '\n\n### Invoke AMD-module factory\n';
output += LoaderStats.toMarkdownTable(['Module', 'Duration'], stats.amdInvoke);
output += '\n\n### Invoke commonjs-module\n';
output += LoaderStats.toMarkdownTable(['Module', 'Duration'], stats.nodeEval);
output += `Start-up time: ${vscodeServerListenTime - vscodeServerStartTime}\n`;
output += `Code loading time: ${vscodeServerCodeLoadedTime - vscodeServerStartTime}\n`;
output += `Initialized time: ${currentTime - vscodeServerStartTime}\n`;
output += `\n`;
console.log(output);
}
return remoteExtensionHostAgentServer;
}
class WebEndpointOriginChecker {
public static create(productService: IProductService): WebEndpointOriginChecker {
const webEndpointUrlTemplate = productService.webEndpointUrlTemplate;
const commit = productService.commit;
const quality = productService.quality;
if (!webEndpointUrlTemplate || !commit || !quality) {
return new WebEndpointOriginChecker(null);
}
const uuid = generateUuid();
const exampleUrl = new URL(
webEndpointUrlTemplate
.replace('{{uuid}}', uuid)
.replace('{{commit}}', commit)
.replace('{{quality}}', quality)
);
const exampleOrigin = exampleUrl.origin;
const originRegExpSource = (
escapeRegExpCharacters(exampleOrigin)
.replace(uuid, '[a-zA-Z0-9\\-]+')
);
try {
const originRegExp = createRegExp(`^${originRegExpSource}$`, true, { matchCase: false });
return new WebEndpointOriginChecker(originRegExp);
} catch (err) {
return new WebEndpointOriginChecker(null);
}
}
constructor(
private readonly _originRegExp: RegExp | null
) { }
public matches(origin: string): boolean {
if (!this._originRegExp) {
return false;
}
return this._originRegExp.test(origin);
}
}
|