-
Notifications
You must be signed in to change notification settings - Fork 29.4k
/
server-main.js
317 lines (284 loc) · 10.5 KB
/
server-main.js
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// @ts-check
const perf = require('./vs/base/common/performance');
const performance = require('perf_hooks').performance;
const product = require('../product.json');
const readline = require('readline');
const http = require('http');
perf.mark('code/server/start');
// @ts-ignore
global.vscodeServerStartTime = performance.now();
async function start() {
const minimist = require('minimist');
// Do a quick parse to determine if a server or the cli needs to be started
const parsedArgs = minimist(process.argv.slice(2), {
boolean: ['start-server', 'list-extensions', 'print-ip-address', 'help', 'version', 'accept-server-license-terms'],
string: ['install-extension', 'install-builtin-extension', 'uninstall-extension', 'locate-extension', 'socket-path', 'host', 'port', 'compatibility'],
alias: { help: 'h', version: 'v' }
});
['host', 'port', 'accept-server-license-terms'].forEach(e => {
if (!parsedArgs[e]) {
const envValue = process.env[`VSCODE_SERVER_${e.toUpperCase().replace('-', '_')}`];
if (envValue) {
parsedArgs[e] = envValue;
}
}
});
const extensionLookupArgs = ['list-extensions', 'locate-extension'];
const extensionInstallArgs = ['install-extension', 'install-builtin-extension', 'uninstall-extension'];
const shouldSpawnCli = parsedArgs.help || parsedArgs.version || extensionLookupArgs.some(a => !!parsedArgs[a]) || (extensionInstallArgs.some(a => !!parsedArgs[a]) && !parsedArgs['start-server']);
if (shouldSpawnCli) {
loadCode().then((mod) => {
mod.spawnCli();
});
return;
}
if (parsedArgs['compatibility'] === '1.63') {
console.warn(`server.sh is being replaced by 'bin/${product.serverApplicationName}'. Please migrate to the new command and adopt the following new default behaviors:`);
console.warn('* connection token is mandatory unless --without-connection-token is used');
console.warn('* host defaults to `localhost`');
}
/**
* @typedef { import('./vs/server/node/remoteExtensionHostAgentServer').IServerAPI } IServerAPI
*/
/** @type {IServerAPI | null} */
let _remoteExtensionHostAgentServer = null;
/** @type {Promise<IServerAPI> | null} */
let _remoteExtensionHostAgentServerPromise = null;
/** @returns {Promise<IServerAPI>} */
const getRemoteExtensionHostAgentServer = () => {
if (!_remoteExtensionHostAgentServerPromise) {
_remoteExtensionHostAgentServerPromise = loadCode().then(async (mod) => {
const server = await mod.createServer(address);
_remoteExtensionHostAgentServer = server;
return server;
});
}
return _remoteExtensionHostAgentServerPromise;
};
const http = require('http');
const os = require('os');
if (Array.isArray(product.serverLicense) && product.serverLicense.length) {
console.log(product.serverLicense.join('\n'));
if (product.serverLicensePrompt && parsedArgs['accept-server-license-terms'] !== true) {
if (hasStdinWithoutTty()) {
console.log('To accept the license terms, start the server with --accept-server-license-terms');
process.exit(1);
}
try {
const accept = await prompt(product.serverLicensePrompt);
if (!accept) {
process.exit(1);
}
} catch (e) {
console.log(e);
process.exit(1);
}
}
}
let firstRequest = true;
let firstWebSocket = true;
/** @type {string | import('net').AddressInfo | null} */
let address = null;
const server = http.createServer(async (req, res) => {
if (firstRequest) {
firstRequest = false;
perf.mark('code/server/firstRequest');
}
const remoteExtensionHostAgentServer = await getRemoteExtensionHostAgentServer();
return remoteExtensionHostAgentServer.handleRequest(req, res);
});
server.on('upgrade', async (req, socket) => {
if (firstWebSocket) {
firstWebSocket = false;
perf.mark('code/server/firstWebSocket');
}
const remoteExtensionHostAgentServer = await getRemoteExtensionHostAgentServer();
// @ts-ignore
return remoteExtensionHostAgentServer.handleUpgrade(req, socket);
});
server.on('error', async (err) => {
const remoteExtensionHostAgentServer = await getRemoteExtensionHostAgentServer();
return remoteExtensionHostAgentServer.handleServerError(err);
});
const host = sanitizeStringArg(parsedArgs['host']) || (parsedArgs['compatibility'] !== '1.63' ? 'localhost' : undefined);
const nodeListenOptions = (
parsedArgs['socket-path']
? { path: sanitizeStringArg(parsedArgs['socket-path']) }
: { host, port: await parsePort(host, sanitizeStringArg(parsedArgs['port'])) }
);
server.listen(nodeListenOptions, async () => {
let output = Array.isArray(product.serverGreeting) && product.serverGreeting.length ? `\n\n${product.serverGreeting.join('\n')}\n\n` : ``;
if (typeof nodeListenOptions.port === 'number' && parsedArgs['print-ip-address']) {
const ifaces = os.networkInterfaces();
Object.keys(ifaces).forEach(function (ifname) {
ifaces[ifname]?.forEach(function (iface) {
if (!iface.internal && iface.family === 'IPv4') {
output += `IP Address: ${iface.address}\n`;
}
});
});
}
address = server.address();
if (address === null) {
throw new Error('Unexpected server address');
}
output += `Server bound to ${typeof address === 'string' ? address : `${address.address}:${address.port} (${address.family})`}\n`;
// Do not change this line. VS Code looks for this in the output.
output += `Extension host agent listening on ${typeof address === 'string' ? address : address.port}\n`;
console.log(output);
perf.mark('code/server/started');
// @ts-ignore
global.vscodeServerListenTime = performance.now();
await getRemoteExtensionHostAgentServer();
});
process.on('exit', () => {
server.close();
if (_remoteExtensionHostAgentServer) {
_remoteExtensionHostAgentServer.dispose();
}
});
}
/**
* @param {any} val
* @returns {string | undefined}
*/
function sanitizeStringArg(val) {
if (Array.isArray(val)) { // if an argument is passed multiple times, minimist creates an array
val = val.pop(); // take the last item
}
return typeof val === 'string' ? val : undefined;
}
/**
* If `--port` is specified and describes a single port, connect to that port.
*
* If `--port`describes a port range
* then find a free port in that range. Throw error if no
* free port available in range.
*
* In absence of specified ports, connect to port 8000.
* @param {string | undefined} host
* @param {string | undefined} strPort
* @returns {Promise<number>}
* @throws
*/
async function parsePort(host, strPort) {
if (strPort) {
let range;
if (strPort.match(/^\d+$/)) {
return parseInt(strPort, 10);
} else if (range = parseRange(strPort)) {
const port = await findFreePort(host, range.start, range.end);
if (port !== undefined) {
return port;
}
// Remote-SSH extension relies on this exact port error message, treat as an API
console.warn(`--port: Could not find free port in range: ${range.start} - ${range.end} (inclusive).`);
process.exit(1);
} else {
console.warn(`--port "${strPort}" is not a valid number or range. Ranges must be in the form 'from-to' with 'from' an integer larger than 0 and not larger than 'end'.`);
process.exit(1);
}
}
return 8000;
}
/**
* @param {string} strRange
* @returns {{ start: number; end: number } | undefined}
*/
function parseRange(strRange) {
const match = strRange.match(/^(\d+)-(\d+)$/);
if (match) {
const start = parseInt(match[1], 10), end = parseInt(match[2], 10);
if (start > 0 && start <= end && end <= 65535) {
return { start, end };
}
}
return undefined;
}
/**
* Starting at the `start` port, look for a free port incrementing
* by 1 until `end` inclusive. If no free port is found, undefined is returned.
*
* @param {string | undefined} host
* @param {number} start
* @param {number} end
* @returns {Promise<number | undefined>}
* @throws
*/
async function findFreePort(host, start, end) {
const testPort = (/** @type {number} */ port) => {
return new Promise((resolve) => {
const server = http.createServer();
server.listen(port, host, () => {
server.close();
resolve(true);
}).on('error', () => {
resolve(false);
});
});
};
for (let port = start; port <= end; port++) {
if (await testPort(port)) {
return port;
}
}
return undefined;
}
/** @returns { Promise<typeof import('./vs/server/node/server.main')> } */
function loadCode() {
return new Promise((resolve, reject) => {
const path = require('path');
delete process.env['ELECTRON_RUN_AS_NODE']; // Keep bootstrap-amd.js from redefining 'fs'.
// See https://github.com/microsoft/vscode-remote-release/issues/6543
// We would normally install a SIGPIPE listener in bootstrap.js
// But in certain situations, the console itself can be in a broken pipe state
// so logging SIGPIPE to the console will cause an infinite async loop
process.env['VSCODE_HANDLES_SIGPIPE'] = 'true';
if (process.env['VSCODE_DEV']) {
// When running out of sources, we need to load node modules from remote/node_modules,
// which are compiled against nodejs, not electron
process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH'] = process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH'] || path.join(__dirname, '..', 'remote', 'node_modules');
require('./bootstrap-node').injectNodeModuleLookupPath(process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH']);
} else {
delete process.env['VSCODE_INJECT_NODE_MODULE_LOOKUP_PATH'];
}
require('./bootstrap-amd').load('vs/server/node/server.main', resolve, reject);
});
}
function hasStdinWithoutTty() {
try {
return !process.stdin.isTTY; // Via https://twitter.com/MylesBorins/status/782009479382626304
} catch (error) {
// Windows workaround for https://github.com/nodejs/node/issues/11656
}
return false;
}
/**
* @param {string} question
* @returns { Promise<boolean> }
*/
function prompt(question) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
return new Promise((resolve, reject) => {
rl.question(question + ' ', async function (data) {
rl.close();
const str = data.toString().trim().toLowerCase();
if (str === '' || str === 'y' || str === 'yes') {
resolve(true);
} else if (str === 'n' || str === 'no') {
resolve(false);
} else {
process.stdout.write('\nInvalid Response. Answer either yes (y, yes) or no (n, no)\n');
resolve(await prompt(question));
}
});
});
}
start();