-
Notifications
You must be signed in to change notification settings - Fork 39.7k
Expand file tree
/
Copy pathtunnelService.ts
More file actions
265 lines (229 loc) · 11.4 KB
/
tunnelService.ts
File metadata and controls
265 lines (229 loc) · 11.4 KB
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as net from 'net';
import * as os from 'os';
import { BROWSER_RESTRICTED_PORTS, findFreePortFaster } from '../../../base/node/ports.js';
import { NodeSocket } from '../../../base/parts/ipc/node/ipc.net.js';
import { Barrier } from '../../../base/common/async.js';
import { Disposable } from '../../../base/common/lifecycle.js';
import { OS } from '../../../base/common/platform.js';
import { ISocket } from '../../../base/parts/ipc/common/ipc.net.js';
import { IConfigurationService } from '../../configuration/common/configuration.js';
import { ILogService } from '../../log/common/log.js';
import { IProductService } from '../../product/common/productService.js';
import { IAddressProvider, IConnectionOptions, connectRemoteAgentTunnel } from '../../remote/common/remoteAgentConnection.js';
import { IRemoteSocketFactoryService } from '../../remote/common/remoteSocketFactoryService.js';
import { ISignService } from '../../sign/common/sign.js';
import { AbstractTunnelService, ISharedTunnelsService, ITunnelProvider, ITunnelService, RemoteTunnel, TunnelPrivacyId, isAllInterfaces, isLocalhost, isPortPrivileged, isTunnelProvider } from '../common/tunnel.js';
import { VSBuffer } from '../../../base/common/buffer.js';
async function createRemoteTunnel(options: IConnectionOptions, defaultTunnelHost: string, tunnelRemoteHost: string, tunnelRemotePort: number, tunnelLocalPort?: number): Promise<RemoteTunnel> {
let readyTunnel: NodeRemoteTunnel | undefined;
for (let attempts = 3; attempts; attempts--) {
readyTunnel?.dispose();
const tunnel = new NodeRemoteTunnel(options, defaultTunnelHost, tunnelRemoteHost, tunnelRemotePort, tunnelLocalPort);
readyTunnel = await tunnel.waitForReady();
if ((tunnelLocalPort && BROWSER_RESTRICTED_PORTS[tunnelLocalPort]) || !BROWSER_RESTRICTED_PORTS[readyTunnel.tunnelLocalPort]) {
break;
}
}
return readyTunnel!;
}
export class NodeRemoteTunnel extends Disposable implements RemoteTunnel {
public readonly tunnelRemotePort: number;
public tunnelLocalPort!: number;
public tunnelRemoteHost: string;
public localAddress!: string;
public readonly privacy = TunnelPrivacyId.Private;
private readonly _options: IConnectionOptions;
private readonly _server: net.Server;
private readonly _barrier: Barrier;
private readonly _listeningListener: () => void;
private readonly _connectionListener: (socket: net.Socket) => void;
private readonly _errorListener: () => void;
private readonly _socketsDispose: Map<string, () => void> = new Map();
constructor(options: IConnectionOptions, private readonly defaultTunnelHost: string, tunnelRemoteHost: string, tunnelRemotePort: number, private readonly suggestedLocalPort?: number) {
super();
this._options = options;
this._server = net.createServer();
this._barrier = new Barrier();
this._listeningListener = () => this._barrier.open();
this._server.on('listening', this._listeningListener);
this._connectionListener = (socket) => this._onConnection(socket);
this._server.on('connection', this._connectionListener);
// If there is no error listener and there is an error it will crash the whole window
this._errorListener = () => { };
this._server.on('error', this._errorListener);
this.tunnelRemotePort = tunnelRemotePort;
this.tunnelRemoteHost = tunnelRemoteHost;
}
public override async dispose(): Promise<void> {
super.dispose();
this._server.removeListener('listening', this._listeningListener);
this._server.removeListener('connection', this._connectionListener);
this._server.removeListener('error', this._errorListener);
this._server.close();
const disposers = Array.from(this._socketsDispose.values());
disposers.forEach(disposer => {
disposer();
});
}
public async waitForReady(): Promise<this> {
const startPort = this.suggestedLocalPort ?? this.tunnelRemotePort;
const hostname = isAllInterfaces(this.defaultTunnelHost) ? '0.0.0.0' : '127.0.0.1';
// try to get the same port number as the remote port number...
let localPort = await findFreePortFaster(startPort, 2, 1000, hostname);
// if that fails, the method above returns 0, which works out fine below...
let address: string | net.AddressInfo | null = null;
this._server.listen(localPort, this.defaultTunnelHost);
await this._barrier.wait();
address = <net.AddressInfo>this._server.address();
// It is possible for findFreePortFaster to return a port that there is already a server listening on. This causes the previous listen call to error out.
if (!address) {
localPort = 0;
this._server.listen(localPort, this.defaultTunnelHost);
await this._barrier.wait();
address = <net.AddressInfo>this._server.address();
}
this.tunnelLocalPort = address.port;
this.localAddress = `${this.tunnelRemoteHost === '127.0.0.1' ? '127.0.0.1' : 'localhost'}:${address.port}`;
return this;
}
private async _onConnection(localSocket: net.Socket): Promise<void> {
// pause reading on the socket until we have a chance to forward its data
localSocket.pause();
const tunnelRemoteHost = (isLocalhost(this.tunnelRemoteHost) || isAllInterfaces(this.tunnelRemoteHost)) ? 'localhost' : this.tunnelRemoteHost;
const protocol = await connectRemoteAgentTunnel(this._options, tunnelRemoteHost, this.tunnelRemotePort);
const remoteSocket = protocol.getSocket();
const dataChunk = protocol.readEntireBuffer();
protocol.dispose();
if (dataChunk.byteLength > 0) {
localSocket.write(dataChunk.buffer);
}
localSocket.on('end', () => {
if (localSocket.localAddress) {
this._socketsDispose.delete(localSocket.localAddress);
}
remoteSocket.end();
});
localSocket.on('close', () => remoteSocket.end());
localSocket.on('error', () => {
if (localSocket.localAddress) {
this._socketsDispose.delete(localSocket.localAddress);
}
if (remoteSocket instanceof NodeSocket) {
remoteSocket.socket.destroy();
} else {
remoteSocket.end();
}
});
if (remoteSocket instanceof NodeSocket) {
this._mirrorNodeSocket(localSocket, remoteSocket);
} else {
this._mirrorGenericSocket(localSocket, remoteSocket);
}
if (localSocket.localAddress) {
this._socketsDispose.set(localSocket.localAddress, () => {
// Need to end instead of unpipe, otherwise whatever is connected locally could end up "stuck" with whatever state it had until manually exited.
localSocket.end();
remoteSocket.end();
});
}
}
private _mirrorGenericSocket(localSocket: net.Socket, remoteSocket: ISocket) {
remoteSocket.onClose(() => localSocket.destroy());
remoteSocket.onEnd(() => localSocket.end());
remoteSocket.onData(d => localSocket.write(d.buffer));
localSocket.on('data', d => remoteSocket.write(VSBuffer.wrap(d)));
localSocket.resume();
}
private _mirrorNodeSocket(localSocket: net.Socket, remoteNodeSocket: NodeSocket) {
const remoteSocket = remoteNodeSocket.socket;
remoteSocket.on('end', () => localSocket.end());
remoteSocket.on('close', () => localSocket.end());
remoteSocket.on('error', () => {
localSocket.destroy();
});
remoteSocket.pipe(localSocket);
localSocket.pipe(remoteSocket);
}
}
export class BaseTunnelService extends AbstractTunnelService {
public constructor(
@IRemoteSocketFactoryService private readonly remoteSocketFactoryService: IRemoteSocketFactoryService,
@ILogService logService: ILogService,
@ISignService private readonly signService: ISignService,
@IProductService private readonly productService: IProductService,
@IConfigurationService configurationService: IConfigurationService
) {
super(logService, configurationService);
}
public isPortPrivileged(port: number): boolean {
return isPortPrivileged(port, this.defaultTunnelHost, OS, os.release());
}
protected retainOrCreateTunnel(addressOrTunnelProvider: IAddressProvider | ITunnelProvider, remoteHost: string, remotePort: number, localHost: string, localPort: number | undefined, elevateIfNeeded: boolean, privacy?: string, protocol?: string): Promise<RemoteTunnel | string | undefined> | undefined {
const existing = this.getTunnelFromMap(remoteHost, remotePort);
if (existing) {
++existing.refcount;
return existing.value;
}
if (isTunnelProvider(addressOrTunnelProvider)) {
return this.createWithProvider(addressOrTunnelProvider, remoteHost, remotePort, localPort, elevateIfNeeded, privacy, protocol);
} else {
this.logService.trace(`ForwardedPorts: (TunnelService) Creating tunnel without provider ${remoteHost}:${remotePort} on local port ${localPort}.`);
const options: IConnectionOptions = {
commit: this.productService.commit,
quality: this.productService.quality,
addressProvider: addressOrTunnelProvider,
remoteSocketFactoryService: this.remoteSocketFactoryService,
signService: this.signService,
logService: this.logService,
ipcLogger: null
};
const tunnel = createRemoteTunnel(options, localHost, remoteHost, remotePort, localPort);
this.logService.trace('ForwardedPorts: (TunnelService) Tunnel created without provider.');
this.addTunnelToMap(remoteHost, remotePort, tunnel);
return tunnel;
}
}
}
export class TunnelService extends BaseTunnelService {
public constructor(
@IRemoteSocketFactoryService remoteSocketFactoryService: IRemoteSocketFactoryService,
@ILogService logService: ILogService,
@ISignService signService: ISignService,
@IProductService productService: IProductService,
@IConfigurationService configurationService: IConfigurationService
) {
super(remoteSocketFactoryService, logService, signService, productService, configurationService);
}
}
export class SharedTunnelsService extends Disposable implements ISharedTunnelsService {
declare readonly _serviceBrand: undefined;
private readonly _tunnelServices: Map<string, ITunnelService> = new Map();
public constructor(
@IRemoteSocketFactoryService protected readonly remoteSocketFactoryService: IRemoteSocketFactoryService,
@ILogService protected readonly logService: ILogService,
@IProductService private readonly productService: IProductService,
@ISignService private readonly signService: ISignService,
@IConfigurationService private readonly configurationService: IConfigurationService,
) {
super();
}
async openTunnel(authority: string, addressProvider: IAddressProvider | undefined, remoteHost: string | undefined, remotePort: number, localHost: string, localPort?: number, elevateIfNeeded?: boolean, privacy?: string, protocol?: string): Promise<RemoteTunnel | string | undefined> {
this.logService.trace(`ForwardedPorts: (SharedTunnelService) openTunnel request for ${remoteHost}:${remotePort} on local port ${localPort}.`);
if (!this._tunnelServices.has(authority)) {
const tunnelService = new TunnelService(this.remoteSocketFactoryService, this.logService, this.signService, this.productService, this.configurationService);
this._register(tunnelService);
this._tunnelServices.set(authority, tunnelService);
tunnelService.onTunnelClosed(async () => {
if ((await tunnelService.tunnels).length === 0) {
tunnelService.dispose();
this._tunnelServices.delete(authority);
}
});
}
return this._tunnelServices.get(authority)!.openTunnel(addressProvider, remoteHost, remotePort, localHost, localPort, elevateIfNeeded, privacy, protocol);
}
}