server.ts 35.3 KB
Newer Older
A
Asher 已提交
1
import * as crypto from "crypto";
A
Asher 已提交
2 3
import * as fs from "fs";
import * as http from "http";
A
Asher 已提交
4
import * as https from "https";
A
Asher 已提交
5 6
import * as net from "net";
import * as path from "path";
A
Asher 已提交
7
import * as querystring from "querystring";
A
Asher 已提交
8
import { Readable } from "stream";
A
Asher 已提交
9
import * as tls from "tls";
A
Asher 已提交
10
import * as url from "url";
A
Asher 已提交
11
import * as util from "util";
A
Asher 已提交
12
import { Emitter } from "vs/base/common/event";
A
Asher 已提交
13
import { sanitizeFilePath } from "vs/base/common/extpath";
A
Asher 已提交
14 15
import { Schemas } from "vs/base/common/network";
import { URI, UriComponents } from "vs/base/common/uri";
A
Asher 已提交
16
import { generateUuid } from "vs/base/common/uuid";
A
Asher 已提交
17
import { getMachineId } from 'vs/base/node/id';
A
Asher 已提交
18
import { NLSConfiguration } from "vs/base/node/languagePacks";
A
Asher 已提交
19
import { mkdirp, rimraf } from "vs/base/node/pfs";
A
Asher 已提交
20
import { ClientConnectionEvent, IPCServer, IServerChannel } from "vs/base/parts/ipc/common/ipc";
A
Asher 已提交
21
import { createChannelReceiver } from "vs/base/parts/ipc/node/ipc";
A
Asher 已提交
22
import { LogsDataCleaner } from "vs/code/electron-browser/sharedProcess/contrib/logsDataCleaner";
A
Asher 已提交
23 24
import { IConfigurationService } from "vs/platform/configuration/common/configuration";
import { ConfigurationService } from "vs/platform/configuration/node/configurationService";
A
Asher 已提交
25
import { ExtensionHostDebugBroadcastChannel } from "vs/platform/debug/common/extensionHostDebugIpc";
A
Asher 已提交
26
import { IEnvironmentService, ParsedArgs } from "vs/platform/environment/common/environment";
A
Asher 已提交
27
import { EnvironmentService } from "vs/platform/environment/node/environmentService";
A
Asher 已提交
28 29 30
import { ExtensionGalleryService } from "vs/platform/extensionManagement/common/extensionGalleryService";
import { IExtensionGalleryService, IExtensionManagementService } from "vs/platform/extensionManagement/common/extensionManagement";
import { ExtensionManagementChannel } from "vs/platform/extensionManagement/common/extensionManagementIpc";
A
Asher 已提交
31
import { ExtensionManagementService } from "vs/platform/extensionManagement/node/extensionManagementService";
A
Asher 已提交
32 33 34
import { IFileService } from "vs/platform/files/common/files";
import { FileService } from "vs/platform/files/common/fileService";
import { DiskFileSystemProvider } from "vs/platform/files/node/diskFileSystemProvider";
A
Asher 已提交
35
import { SyncDescriptor } from "vs/platform/instantiation/common/descriptors";
A
Asher 已提交
36
import { InstantiationService } from "vs/platform/instantiation/common/instantiationService";
A
Asher 已提交
37
import { ServiceCollection } from "vs/platform/instantiation/common/serviceCollection";
A
Asher 已提交
38 39
import { ILocalizationsService } from "vs/platform/localizations/common/localizations";
import { LocalizationsService } from "vs/platform/localizations/node/localizations";
40
import { getLogLevel, ILogService } from "vs/platform/log/common/log";
A
Asher 已提交
41
import { LoggerChannel } from "vs/platform/log/common/logIpc";
A
Asher 已提交
42
import { SpdLogService } from "vs/platform/log/node/spdlogService";
A
Asher 已提交
43 44
import product from 'vs/platform/product/common/product';
import { IProductService } from "vs/platform/product/common/productService";
45
import { ConnectionType, ConnectionTypeRequest } from "vs/platform/remote/common/remoteAgentConnection";
A
Asher 已提交
46
import { RemoteAgentConnectionContext } from "vs/platform/remote/common/remoteAgentEnvironment";
A
Asher 已提交
47
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from "vs/platform/remote/common/remoteAgentFileSystemChannel";
A
Asher 已提交
48 49
import { IRequestService } from "vs/platform/request/common/request";
import { RequestChannel } from "vs/platform/request/common/requestIpc";
A
Asher 已提交
50
import { RequestService } from "vs/platform/request/node/requestService";
A
Asher 已提交
51
import ErrorTelemetry from "vs/platform/telemetry/browser/errorTelemetry";
A
Asher 已提交
52
import { ITelemetryService } from "vs/platform/telemetry/common/telemetry";
A
Asher 已提交
53 54
import { ITelemetryServiceConfig, TelemetryService } from "vs/platform/telemetry/common/telemetryService";
import { combinedAppender, LogAppender, NullTelemetryService } from "vs/platform/telemetry/common/telemetryUtils";
A
Asher 已提交
55 56
import { AppInsightsAppender } from "vs/platform/telemetry/node/appInsightsAppender";
import { resolveCommonProperties } from "vs/platform/telemetry/node/commonProperties";
A
Asher 已提交
57 58 59
import { UpdateChannel } from "vs/platform/update/electron-main/updateIpc";
import { INodeProxyService, NodeProxyChannel } from "vs/server/src/common/nodeProxy";
import { TelemetryChannel } from "vs/server/src/common/telemetry";
A
Asher 已提交
60
import { split } from "vs/server/src/common/util";
61 62 63 64 65 66
import { ExtensionEnvironmentChannel, FileProviderChannel, NodeProxyService } from "vs/server/src/node/channel";
import { Connection, ExtensionHostConnection, ManagementConnection } from "vs/server/src/node/connection";
import { TelemetryClient } from "vs/server/src/node/insights";
import { getLocaleFromConfig, getNlsConfiguration } from "vs/server/src/node/nls";
import { Protocol } from "vs/server/src/node/protocol";
import { UpdateService } from "vs/server/src/node/update";
A
Asher 已提交
67
import { AuthType, getMediaMime, getUriTransformer, hash, localRequire, tmpdir } from "vs/server/src/node/util";
A
Asher 已提交
68 69
import { RemoteExtensionLogFileName } from "vs/workbench/services/remote/common/remoteAgentService";
import { IWorkbenchConstructionOptions } from "vs/workbench/workbench.web.api";
A
Asher 已提交
70

A
Asher 已提交
71 72
const tarFs = localRequire<typeof import("tar-fs")>("tar-fs/index");

A
Asher 已提交
73
export enum HttpCode {
A
Asher 已提交
74
	Ok = 200,
A
Asher 已提交
75
	Redirect = 302,
A
Asher 已提交
76 77
	NotFound = 404,
	BadRequest = 400,
A
Asher 已提交
78 79 80
	Unauthorized = 401,
	LargePayload = 413,
	ServerError = 500,
A
Asher 已提交
81 82
}

A
Asher 已提交
83
export interface Options {
A
Asher 已提交
84
	WORKBENCH_WEB_CONFIGURATION: IWorkbenchConstructionOptions & { folderUri?: UriComponents, workspaceUri?: UriComponents };
A
Asher 已提交
85
	REMOTE_USER_DATA_URI: UriComponents | URI;
A
Asher 已提交
86
	PRODUCT_CONFIGURATION: Partial<IProductService>;
A
Asher 已提交
87
	NLS_CONFIGURATION: NLSConfiguration;
A
Asher 已提交
88 89
}

90
export interface Response {
A
Asher 已提交
91
	cache?: boolean;
92
	code?: number;
A
Asher 已提交
93 94 95
	content?: string | Buffer;
	filePath?: string;
	headers?: http.OutgoingHttpHeaders;
A
Asher 已提交
96
	mime?: string;
A
Asher 已提交
97
	redirect?: string;
A
Asher 已提交
98
	stream?: Readable;
A
Asher 已提交
99 100 101
}

export interface LoginPayload {
A
Asher 已提交
102 103 104 105 106
	password?: string;
}

export interface AuthPayload {
	key?: string[];
107 108
}

A
Asher 已提交
109
export class HttpError extends Error {
A
Asher 已提交
110 111 112 113 114 115 116 117
	public constructor(message: string, public readonly code: number) {
		super(message);
		// @ts-ignore
		this.name = this.constructor.name;
		Error.captureStackTrace(this, this.constructor);
	}
}

A
Asher 已提交
118
export interface ServerOptions {
A
Asher 已提交
119
	readonly auth: AuthType;
A
Asher 已提交
120
	readonly basePath?: string;
A
Asher 已提交
121
	readonly connectionToken?: string;
A
Asher 已提交
122 123
	readonly cert?: string;
	readonly certKey?: string;
124
	readonly openUri?: string;
A
Asher 已提交
125 126 127 128
	readonly host?: string;
	readonly password?: string;
	readonly port?: number;
	readonly socket?: string;
A
Asher 已提交
129 130
}

A
Asher 已提交
131
export abstract class Server {
A
Asher 已提交
132
	protected readonly server: http.Server | https.Server;
133
	protected rootPath = path.resolve(__dirname, "../../../../..");
A
Asher 已提交
134 135
	protected serverRoot = path.join(this.rootPath, "/out/vs/server/src");
	protected readonly allowedRequestPaths: string[] = [this.rootPath];
A
Asher 已提交
136
	private listenPromise: Promise<string> | undefined;
A
Asher 已提交
137
	public readonly protocol: "http" | "https";
A
Asher 已提交
138 139 140 141
	public readonly options: ServerOptions;

	public constructor(options: ServerOptions) {
		this.options = {
A
Asher 已提交
142
			host: options.auth === "password" && options.cert ? "0.0.0.0" : "localhost",
A
Asher 已提交
143
			...options,
A
Asher 已提交
144
			basePath: options.basePath ? options.basePath.replace(/\/+$/, "") : "",
A
Asher 已提交
145
			password: options.password ? hash(options.password) : undefined,
A
Asher 已提交
146 147 148
		};
		this.protocol = this.options.cert ? "https" : "http";
		if (this.protocol === "https") {
149
			const httpolyglot = localRequire<typeof import("httpolyglot")>("httpolyglot/lib/index");
A
Asher 已提交
150
			this.server = httpolyglot.createServer({
A
Asher 已提交
151 152
				cert: this.options.cert && fs.readFileSync(this.options.cert),
				key: this.options.certKey && fs.readFileSync(this.options.certKey),
A
Asher 已提交
153 154 155 156
			}, this.onRequest);
		} else {
			this.server = http.createServer(this.onRequest);
		}
A
Asher 已提交
157 158
	}

A
Asher 已提交
159 160 161 162
	public listen(): Promise<string> {
		if (!this.listenPromise) {
			this.listenPromise = new Promise((resolve, reject) => {
				this.server.on("error", reject);
A
Asher 已提交
163
				this.server.on("upgrade", this.onUpgrade);
A
Asher 已提交
164
				const onListen = () => resolve(this.address());
A
Asher 已提交
165 166 167 168 169
				if (this.options.socket) {
					this.server.listen(this.options.socket, onListen);
				} else {
					this.server.listen(this.options.port, this.options.host, onListen);
				}
A
Asher 已提交
170 171 172
			});
		}
		return this.listenPromise;
A
Asher 已提交
173 174
	}

A
Asher 已提交
175
	/**
A
Asher 已提交
176
	 * The *local* address of the server.
A
Asher 已提交
177
	 */
A
Asher 已提交
178
	public address(): string {
A
Asher 已提交
179 180
		const address = this.server.address();
		const endpoint = typeof address !== "string"
A
Asher 已提交
181
			? (address.address === "::" ? "localhost" : address.address) + ":" + address.port
A
Asher 已提交
182
			: address;
A
Asher 已提交
183
		return `${this.protocol}://${endpoint}`;
A
Asher 已提交
184 185
	}

A
Asher 已提交
186 187 188 189 190
	protected abstract handleWebSocket(
		socket: net.Socket,
		parsedUrl: url.UrlWithParsedQuery
	): Promise<void>;

A
Asher 已提交
191 192 193 194 195 196 197
	protected abstract handleRequest(
		base: string,
		requestPath: string,
		parsedUrl: url.UrlWithParsedQuery,
		request: http.IncomingMessage,
	): Promise<Response>;

A
Asher 已提交
198
	protected async getResource(...parts: string[]): Promise<Response> {
A
Asher 已提交
199 200 201 202
		const filePath = this.ensureAuthorizedFilePath(...parts);
		return { content: await util.promisify(fs.readFile)(filePath), filePath };
	}

203 204 205 206 207
	protected async getAnyResource(...parts: string[]): Promise<Response> {
		const filePath = path.join(...parts);
		return { content: await util.promisify(fs.readFile)(filePath), filePath };
	}

A
Asher 已提交
208 209
	protected async getTarredResource(...parts: string[]): Promise<Response> {
		const filePath = this.ensureAuthorizedFilePath(...parts);
A
Asher 已提交
210
		return { stream: tarFs.pack(filePath), filePath, mime: "application/tar", cache: true };
A
Asher 已提交
211 212 213
	}

	protected ensureAuthorizedFilePath(...parts: string[]): string {
A
Asher 已提交
214
		const filePath = path.join(...parts);
A
Asher 已提交
215 216 217
		if (!this.isAllowedRequestPath(filePath)) {
			throw new HttpError("Unauthorized", HttpCode.Unauthorized);
		}
A
Asher 已提交
218
		return filePath;
A
Asher 已提交
219
	}
A
Asher 已提交
220

A
Asher 已提交
221
	protected withBase(request: http.IncomingMessage, path: string): string {
A
Asher 已提交
222 223
		const [, query] = request.url ? split(request.url, "?") : [];
		return `${this.protocol}://${request.headers.host}${this.options.basePath}${path}${query ? `?${query}` : ""}`;
A
Asher 已提交
224 225
	}

A
Asher 已提交
226 227 228 229 230 231 232 233 234
	private isAllowedRequestPath(path: string): boolean {
		for (let i = 0; i < this.allowedRequestPaths.length; ++i) {
			if (path.indexOf(this.allowedRequestPaths[i]) === 0) {
				return true;
			}
		}
		return false;
	}

A
Asher 已提交
235
	private onRequest = async (request: http.IncomingMessage, response: http.ServerResponse): Promise<void> => {
A
Asher 已提交
236
		try {
A
Asher 已提交
237 238
			const parsedUrl = request.url ? url.parse(request.url, true) : { query: {}};
			const payload = await this.preHandleRequest(request, parsedUrl);
A
Asher 已提交
239
			response.writeHead(payload.redirect ? HttpCode.Redirect : payload.code || HttpCode.Ok, {
A
Asher 已提交
240
				"Content-Type": payload.mime || getMediaMime(payload.filePath),
A
Asher 已提交
241
				...(payload.redirect ? { Location: this.withBase(request, payload.redirect) } : {}),
242
				...(request.headers["service-worker"] ? { "Service-Worker-Allowed": this.options.basePath || "/" } : {}),
A
Asher 已提交
243
				...(payload.cache ? { "Cache-Control": "public, max-age=31536000" } : {}),
A
Asher 已提交
244 245
				...payload.headers,
			});
A
Asher 已提交
246 247 248 249 250 251 252 253 254
			if (payload.stream) {
				payload.stream.on("error", (error: NodeJS.ErrnoException) => {
					response.writeHead(error.code === "ENOENT" ? HttpCode.NotFound : HttpCode.ServerError);
					response.end(error.message);
				});
				payload.stream.pipe(response);
			} else {
				response.end(payload.content);
			}
A
Asher 已提交
255 256 257 258 259 260 261 262 263
		} catch (error) {
			if (error.code === "ENOENT" || error.code === "EISDIR") {
				error = new HttpError("Not found", HttpCode.NotFound);
			}
			response.writeHead(typeof error.code === "number" ? error.code : HttpCode.ServerError);
			response.end(error.message);
		}
	}

A
Asher 已提交
264
	private async preHandleRequest(request: http.IncomingMessage, parsedUrl: url.UrlWithParsedQuery): Promise<Response> {
A
Asher 已提交
265
		const secure = (request.connection as tls.TLSSocket).encrypted;
A
Asher 已提交
266
		if (this.options.cert && !secure) {
A
Asher 已提交
267
			return { redirect: request.url };
A
Asher 已提交
268 269
		}

A
Asher 已提交
270 271
		const fullPath = decodeURIComponent(parsedUrl.pathname || "/");
		const match = fullPath.match(/^(\/?[^/]*)(.*)$/);
272
		let [/* ignore */, base, requestPath] = match
A
Asher 已提交
273
			? match.map((p) => p.replace(/\/+$/, ""))
A
Asher 已提交
274 275 276 277 278 279 280
			: ["", "", ""];
		if (base.indexOf(".") !== -1) { // Assume it's a file at the root.
			requestPath = base;
			base = "/";
		} else if (base === "") { // Happens if it's a plain `domain.com`.
			base = "/";
		}
A
Asher 已提交
281
		base = path.normalize(base);
A
Asher 已提交
282
		requestPath = path.normalize(requestPath || "/index.html");
A
Asher 已提交
283

A
Asher 已提交
284
		if (base !== "/login" || this.options.auth !== "password" || requestPath !== "/index.html") {
A
Asher 已提交
285 286 287
			this.ensureGet(request);
		}

A
Asher 已提交
288 289 290 291 292
		// Allow for a versioned static endpoint. This lets us cache every static
		// resource underneath the path based on the version without any work and
		// without adding query parameters which have their own issues.
		// REVIEW: Discuss whether this is the best option; this is sort of a quick
		// hack almost to get caching in the meantime but it does work pretty well.
A
Asher 已提交
293
		if (/^\/static-/.test(base)) {
A
Asher 已提交
294 295 296
			base = "/static";
		}

A
Asher 已提交
297 298
		switch (base) {
			case "/":
A
Asher 已提交
299 300 301 302 303 304
				switch (requestPath) {
					case "/manifest.json":
						const response = await this.getResource(this.serverRoot, "media", requestPath);
						response.cache = true;
						return response;
				}
A
Asher 已提交
305
				if (!this.authenticate(request)) {
A
Asher 已提交
306
					return { redirect: "/login" };
A
Asher 已提交
307 308
				}
				break;
A
Asher 已提交
309
			case "/static":
A
Asher 已提交
310 311 312
				const response = await this.getResource(this.rootPath, requestPath);
				response.cache = true;
				return response;
A
Asher 已提交
313
			case "/login":
A
Asher 已提交
314
				if (this.options.auth !== "password" || requestPath !== "/index.html") {
A
Asher 已提交
315 316
					throw new HttpError("Not found", HttpCode.NotFound);
				}
A
Asher 已提交
317
				return this.tryLogin(request);
A
Asher 已提交
318 319
			default:
				if (!this.authenticate(request)) {
A
Asher 已提交
320
					throw new HttpError("Unauthorized", HttpCode.Unauthorized);
A
Asher 已提交
321 322 323
				}
				break;
		}
A
Asher 已提交
324

A
Asher 已提交
325 326
		return this.handleRequest(base, requestPath, parsedUrl, request);
	}
A
Asher 已提交
327

A
Asher 已提交
328 329 330 331 332
	private onUpgrade = async (request: http.IncomingMessage, socket: net.Socket): Promise<void> => {
		try {
			await this.preHandleWebSocket(request, socket);
		} catch (error) {
			socket.destroy();
A
Asher 已提交
333
			console.error(error.message);
A
Asher 已提交
334 335 336 337 338 339 340
		}
	}

	private preHandleWebSocket(request: http.IncomingMessage, socket: net.Socket): Promise<void> {
		socket.on("error", () => socket.destroy());
		socket.on("end", () => socket.destroy());

A
Asher 已提交
341
		this.ensureGet(request);
A
Asher 已提交
342 343
		if (!this.authenticate(request)) {
			throw new HttpError("Unauthorized", HttpCode.Unauthorized);
344
		} else if (!request.headers.upgrade || request.headers.upgrade.toLowerCase() !== "websocket") {
A
Asher 已提交
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
			throw new Error("HTTP/1.1 400 Bad Request");
		}

		// This magic value is specified by the websocket spec.
		const magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
		const reply = crypto.createHash("sha1")
			.update(<string>request.headers["sec-websocket-key"] + magic)
			.digest("base64");
		socket.write([
			"HTTP/1.1 101 Switching Protocols",
			"Upgrade: websocket",
			"Connection: Upgrade",
			`Sec-WebSocket-Accept: ${reply}`,
		].join("\r\n") + "\r\n\r\n");

		const parsedUrl = request.url ? url.parse(request.url, true) : { query: {}};
		return this.handleWebSocket(socket, parsedUrl);
	}

A
Asher 已提交
364
	private async tryLogin(request: http.IncomingMessage): Promise<Response> {
A
Asher 已提交
365
		const redirect = (password: string | true) => {
A
Asher 已提交
366 367 368
			return {
				redirect: "/",
				headers: typeof password === "string"
A
Asher 已提交
369
					? { "Set-Cookie": `key=${password}; Path=${this.options.basePath || "/"}; HttpOnly; SameSite=strict` }
A
Asher 已提交
370 371 372 373 374 375
					: {},
			};
		};
		const providedPassword = this.authenticate(request);
		if (providedPassword && (request.method === "GET" || request.method === "POST")) {
			return redirect(providedPassword);
A
Asher 已提交
376 377 378
		}
		if (request.method === "POST") {
			const data = await this.getData<LoginPayload>(request);
A
Asher 已提交
379 380 381 382 383
			const password = this.authenticate(request, {
				key: typeof data.password === "string" ? [hash(data.password)] : undefined,
			});
			if (password) {
				return redirect(password);
A
Asher 已提交
384
			}
A
Asher 已提交
385 386 387
			console.error("Failed login attempt", JSON.stringify({
				xForwardedFor: request.headers["x-forwarded-for"],
				remoteAddress: request.connection.remoteAddress,
A
Asher 已提交
388 389
				userAgent: request.headers["user-agent"],
				timestamp: Math.floor(new Date().getTime() / 1000),
A
Asher 已提交
390 391
			}));
			return this.getLogin("Invalid password", data);
A
Asher 已提交
392
		}
A
Asher 已提交
393 394
		this.ensureGet(request);
		return this.getLogin();
A
Asher 已提交
395 396
	}

A
Asher 已提交
397
	private async getLogin(error: string = "", payload?: LoginPayload): Promise<Response> {
A
Asher 已提交
398
		const filePath = path.join(this.serverRoot, "browser/login.html");
A
Asher 已提交
399 400 401 402
		const content = (await util.promisify(fs.readFile)(filePath, "utf8"))
			.replace("{{ERROR}}", error)
			.replace("display:none", error ? "display:block" : "display:none")
			.replace('value=""', `value="${payload && payload.password || ""}"`);
A
Asher 已提交
403 404 405 406 407
		return { content, filePath };
	}

	private ensureGet(request: http.IncomingMessage): void {
		if (request.method !== "GET") {
A
Asher 已提交
408
			throw new HttpError(`Unsupported method ${request.method}`, HttpCode.BadRequest);
A
Asher 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
		}
	}

	private getData<T extends object>(request: http.IncomingMessage): Promise<T> {
		return request.method === "POST"
			? new Promise<T>((resolve, reject) => {
				let body = "";
				const onEnd = (): void => {
					off();
					resolve(querystring.parse(body) as T);
				};
				const onError = (error: Error): void => {
					off();
					reject(error);
				};
				const onData = (d: Buffer): void => {
					body += d;
					if (body.length > 1e6) {
A
Asher 已提交
427
						onError(new HttpError("Payload is too large", HttpCode.LargePayload));
A
Asher 已提交
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
						request.connection.destroy();
					}
				};
				const off = (): void => {
					request.off("error", onError);
					request.off("data", onError);
					request.off("end", onEnd);
				};
				request.on("error", onError);
				request.on("data", onData);
				request.on("end", onEnd);
			})
			: Promise.resolve({} as T);
	}

A
Asher 已提交
443 444
	private authenticate(request: http.IncomingMessage, payload?: AuthPayload): string | boolean {
		if (this.options.auth === "none") {
A
Asher 已提交
445 446
			return true;
		}
447
		const safeCompare = localRequire<typeof import("safe-compare")>("safe-compare/index");
A
Asher 已提交
448
		if (typeof payload === "undefined") {
A
Asher 已提交
449
			payload = this.parseCookies<AuthPayload>(request);
A
Asher 已提交
450
		}
A
Asher 已提交
451 452 453 454
		if (this.options.password && payload.key) {
			for (let i = 0; i < payload.key.length; ++i) {
				if (safeCompare(payload.key[i], this.options.password)) {
					return payload.key[i];
A
Asher 已提交
455 456 457 458
				}
			}
		}
		return false;
A
Asher 已提交
459 460 461
	}

	private parseCookies<T extends object>(request: http.IncomingMessage): T {
A
Asher 已提交
462
		const cookies: { [key: string]: string[] } = {};
A
Asher 已提交
463 464
		if (request.headers.cookie) {
			request.headers.cookie.split(";").forEach((keyValue) => {
A
Asher 已提交
465
				const [key, value] = split(keyValue, "=");
A
Asher 已提交
466 467 468 469
				if (!cookies[key]) {
					cookies[key] = [];
				}
				cookies[key].push(decodeURI(value));
A
Asher 已提交
470 471 472
			});
		}
		return cookies as T;
A
Asher 已提交
473
	}
A
Asher 已提交
474 475
}

A
Asher 已提交
476 477 478 479 480 481 482 483 484
interface StartPath {
	path?: string[] | string;
	workspace?: boolean;
}

interface Settings {
	lastVisited?: StartPath;
}

A
Asher 已提交
485 486 487
export class MainServer extends Server {
	public readonly _onDidClientConnect = new Emitter<ClientConnectionEvent>();
	public readonly onDidClientConnect = this._onDidClientConnect.event;
A
Asher 已提交
488
	private readonly ipc = new IPCServer<RemoteAgentConnectionContext>(this.onDidClientConnect);
A
Asher 已提交
489

490
	private readonly maxExtraOfflineConnections = 0;
A
Asher 已提交
491 492 493
	private readonly connections = new Map<ConnectionType, Map<string, Connection>>();

	private readonly services = new ServiceCollection();
A
Asher 已提交
494
	private readonly servicesPromise: Promise<void>;
A
Asher 已提交
495

A
Asher 已提交
496 497 498 499 500
	public readonly _onProxyConnect = new Emitter<net.Socket>();
	private proxyPipe = path.join(tmpdir, "tls-proxy");
	private _proxyServer?: Promise<net.Server>;
	private readonly proxyTimeout = 5000;

A
Asher 已提交
501
	private settings: Settings = {};
A
Asher 已提交
502 503 504
	private heartbeatTimer?: NodeJS.Timeout;
	private heartbeatInterval = 60000;
	private lastHeartbeat = 0;
A
Asher 已提交
505

A
Asher 已提交
506
	public constructor(options: ServerOptions, args: ParsedArgs) {
A
Asher 已提交
507
		super(options);
A
Asher 已提交
508
		this.servicesPromise = this.initializeServices(args);
A
Asher 已提交
509
	}
A
Asher 已提交
510

A
Asher 已提交
511 512
	public async listen(): Promise<string> {
		const environment = (this.services.get(IEnvironmentService) as EnvironmentService);
A
Asher 已提交
513 514 515 516
		const [address] = await Promise.all<string>([
			super.listen(), ...[
				environment.extensionsPath,
			].map((p) => mkdirp(p).then(() => p)),
A
Asher 已提交
517 518 519 520
		]);
		return address;
	}

A
Asher 已提交
521
	protected async handleWebSocket(socket: net.Socket, parsedUrl: url.UrlWithParsedQuery): Promise<void> {
A
Asher 已提交
522
		this.heartbeat();
A
Asher 已提交
523 524 525
		if (!parsedUrl.query.reconnectionToken) {
			throw new Error("Reconnection token is missing from query parameters");
		}
A
Asher 已提交
526
		const protocol = new Protocol(await this.createProxy(socket), {
A
Asher 已提交
527
			reconnectionToken: <string>parsedUrl.query.reconnectionToken,
A
Asher 已提交
528 529 530 531 532 533 534 535 536 537 538 539
			reconnection: parsedUrl.query.reconnection === "true",
			skipWebSocketFrames: parsedUrl.query.skipWebSocketFrames === "true",
		});
		try {
			await this.connect(await protocol.handshake(), protocol);
		} catch (error) {
			protocol.sendMessage({ type: "error", reason: error.message });
			protocol.dispose();
			protocol.getSocket().dispose();
		}
	}

A
Asher 已提交
540
	protected async handleRequest(
541
		base: string,
A
Asher 已提交
542
		requestPath: string,
A
Asher 已提交
543 544
		parsedUrl: url.UrlWithParsedQuery,
		request: http.IncomingMessage,
545
	): Promise<Response> {
A
Asher 已提交
546
		this.heartbeat();
547
		switch (base) {
A
Asher 已提交
548
			case "/": return this.getRoot(request, parsedUrl);
A
Asher 已提交
549 550 551
			case "/resource":
			case "/vscode-remote-resource":
				if (typeof parsedUrl.query.path === "string") {
A
Asher 已提交
552
					return this.getAnyResource(parsedUrl.query.path);
553
				}
A
Asher 已提交
554
				break;
A
Asher 已提交
555 556 557 558 559
			case "/tar":
				if (typeof parsedUrl.query.path === "string") {
					return this.getTarredResource(parsedUrl.query.path);
				}
				break;
A
Asher 已提交
560
			case "/webview":
A
Asher 已提交
561
				if (/^\/vscode-resource/.test(requestPath)) {
562
					return this.getAnyResource(requestPath.replace(/^\/vscode-resource(\/file)?/, ""));
563
				}
A
Asher 已提交
564 565 566 567 568
				return this.getResource(
					this.rootPath,
					"out/vs/workbench/contrib/webview/browser/pre",
					requestPath
				);
569
		}
A
Asher 已提交
570
		throw new HttpError("Not found", HttpCode.NotFound);
571
	}
A
Asher 已提交
572

573
	private async getRoot(request: http.IncomingMessage, parsedUrl: url.UrlWithParsedQuery): Promise<Response> {
A
Asher 已提交
574
		const filePath = path.join(this.serverRoot, "browser/workbench.html");
A
Asher 已提交
575
		let [content, startPath] = await Promise.all([
A
Asher 已提交
576
			util.promisify(fs.readFile)(filePath, "utf8"),
A
Asher 已提交
577 578
			this.getFirstValidPath([
				{ path: parsedUrl.query.workspace, workspace: true },
579
				{ path: parsedUrl.query.folder, workspace: false },
A
Asher 已提交
580
				(await this.readSettings()).lastVisited,
581
				{ path: this.options.openUri }
A
Asher 已提交
582
			]),
A
Asher 已提交
583 584
			this.servicesPromise,
		]);
A
Asher 已提交
585

A
Asher 已提交
586 587 588 589 590 591 592 593 594
		if (startPath) {
			this.writeSettings({
				lastVisited: {
					path: startPath.uri.fsPath,
					workspace: startPath.workspace
				},
			});
		}

595 596
		const logger = this.services.get(ILogService) as ILogService;
		logger.info("request.url", `"${request.url}"`);
A
Asher 已提交
597

A
Asher 已提交
598 599
		const remoteAuthority = request.headers.host as string;
		const transformer = getUriTransformer(remoteAuthority);
A
Asher 已提交
600 601

		const environment = this.services.get(IEnvironmentService) as IEnvironmentService;
602
		const options: Options = {
A
Asher 已提交
603
			WORKBENCH_WEB_CONFIGURATION: {
A
Asher 已提交
604 605
				workspaceUri: startPath && startPath.workspace ? transformer.transformOutgoing(startPath.uri) : undefined,
				folderUri: startPath && !startPath.workspace ? transformer.transformOutgoing(startPath.uri) : undefined,
606
				remoteAuthority,
A
Asher 已提交
607 608 609 610 611
				logLevel: getLogLevel(environment),
			},
			REMOTE_USER_DATA_URI: transformer.transformOutgoing(URI.file(environment.userDataPath)),
			PRODUCT_CONFIGURATION: {
				extensionsGallery: product.extensionsGallery,
612
			},
A
Asher 已提交
613
			NLS_CONFIGURATION: await getNlsConfiguration(environment.args.locale || await getLocaleFromConfig(environment.userDataPath), environment.userDataPath),
614 615
		};

A
Asher 已提交
616
		content = content.replace(/{{COMMIT}}/g, product.commit || "");
A
Asher 已提交
617 618 619
		for (const key in options) {
			content = content.replace(`"{{${key}}}"`, `'${JSON.stringify(options[key as keyof Options])}'`);
		}
620

A
Asher 已提交
621
		return { content, filePath };
A
Asher 已提交
622 623
	}

A
Asher 已提交
624
	/**
625 626 627
	 * Choose the first valid path. If `workspace` is undefined then either a
	 * workspace or a directory are acceptable. Otherwise it must be a file if a
	 * workspace or a directory otherwise.
A
Asher 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641
	 */
	private async getFirstValidPath(startPaths: Array<StartPath | undefined>): Promise<{ uri: URI, workspace?: boolean} | undefined> {
		const logger = this.services.get(ILogService) as ILogService;
		const cwd = process.env.VSCODE_CWD || process.cwd();
		for (let i = 0; i < startPaths.length; ++i) {
			const startPath = startPaths[i];
			if (!startPath) {
				continue;
			}
			const paths = typeof startPath.path === "string" ? [startPath.path] : (startPath.path || []);
			for (let j = 0; j < paths.length; ++j) {
				const uri = URI.file(sanitizeFilePath(paths[j], cwd));
				try {
					const stat = await util.promisify(fs.stat)(uri.fsPath);
642 643
					if (typeof startPath.workspace === "undefined" || startPath.workspace !== stat.isDirectory()) {
						return { uri, workspace: !stat.isDirectory() };
A
Asher 已提交
644 645 646 647 648 649 650 651 652
					}
				} catch (error) {
					logger.warn(error.message);
				}
			}
		}
		return undefined;
	}

653
	private async connect(message: ConnectionTypeRequest, protocol: Protocol): Promise<void> {
A
Asher 已提交
654 655 656 657
		if (product.commit && message.commit !== product.commit) {
			throw new Error(`Version mismatch (${message.commit} instead of ${product.commit})`);
		}

658 659 660 661 662 663 664 665
		switch (message.desiredConnectionType) {
			case ConnectionType.ExtensionHost:
			case ConnectionType.Management:
				if (!this.connections.has(message.desiredConnectionType)) {
					this.connections.set(message.desiredConnectionType, new Map());
				}
				const connections = this.connections.get(message.desiredConnectionType)!;

A
Asher 已提交
666 667 668 669 670 671 672
				const ok = async () => {
					return message.desiredConnectionType === ConnectionType.ExtensionHost
						? { debugPort: await this.getDebugPort() }
						: { type: "ok" };
				};

				const token = protocol.options.reconnectionToken;
673
				if (protocol.options.reconnection && connections.has(token)) {
A
Asher 已提交
674
					protocol.sendMessage(await ok());
675 676
					const buffer = protocol.readEntireBuffer();
					protocol.dispose();
A
Asher 已提交
677
					return connections.get(token)!.reconnect(protocol.getSocket(), buffer);
A
Asher 已提交
678
				} else if (protocol.options.reconnection || connections.has(token)) {
679 680 681 682 683 684
					throw new Error(protocol.options.reconnection
						? "Unrecognized reconnection token"
						: "Duplicate reconnection token"
					);
				}

A
Asher 已提交
685
				protocol.sendMessage(await ok());
686 687 688

				let connection: Connection;
				if (message.desiredConnectionType === ConnectionType.Management) {
689
					connection = new ManagementConnection(protocol, token);
690
					this._onDidClientConnect.fire({
A
Asher 已提交
691
						protocol, onDidClientDisconnect: connection.onClose,
692
					});
A
Asher 已提交
693 694 695
					// TODO: Need a way to match clients with a connection. For now
					// dispose everything which only works because no extensions currently
					// utilize long-running proxies.
A
Asher 已提交
696 697
					(this.services.get(INodeProxyService) as NodeProxyService)._onUp.fire();
					connection.onClose(() => (this.services.get(INodeProxyService) as NodeProxyService)._onDown.fire());
698
				} else {
A
Asher 已提交
699
					const buffer = protocol.readEntireBuffer();
A
Asher 已提交
700
					connection = new ExtensionHostConnection(
A
Asher 已提交
701
						message.args ? message.args.language : "en",
702
						protocol, buffer, token,
A
Asher 已提交
703 704
						this.services.get(ILogService) as ILogService,
						this.services.get(IEnvironmentService) as IEnvironmentService,
A
Asher 已提交
705
					);
706
				}
A
Asher 已提交
707 708
				connections.set(token, connection);
				connection.onClose(() => connections.delete(token));
709
				this.disposeOldOfflineConnections(connections);
710 711 712 713 714 715
				break;
			case ConnectionType.Tunnel: return protocol.tunnel();
			default: throw new Error("Unrecognized connection type");
		}
	}

716 717 718 719 720 721
	private disposeOldOfflineConnections(connections: Map<string, Connection>): void {
		const offline = Array.from(connections.values())
			.filter((connection) => typeof connection.offline !== "undefined");
		for (let i = 0, max = offline.length - this.maxExtraOfflineConnections; i < max; ++i) {
			offline[i].dispose();
		}
722 723
	}

A
Asher 已提交
724 725 726
	private async initializeServices(args: ParsedArgs): Promise<void> {
		const environmentService = new EnvironmentService(args, process.execPath);
		const logService = new SpdLogService(RemoteExtensionLogFileName, environmentService.logsPath, getLogLevel(environmentService));
A
Asher 已提交
727 728 729
		const fileService = new FileService(logService);
		fileService.registerProvider(Schemas.file, new DiskFileSystemProvider(logService));

A
Asher 已提交
730 731 732 733 734 735 736 737
		this.allowedRequestPaths.push(
			path.join(environmentService.userDataPath, "clp"), // Language packs.
			environmentService.extensionsPath,
			environmentService.builtinExtensionsPath,
			...environmentService.extraExtensionPaths,
			...environmentService.extraBuiltinExtensionPaths,
		);

A
Asher 已提交
738
		this.ipc.registerChannel("logger", new LoggerChannel(logService));
A
Asher 已提交
739
		this.ipc.registerChannel(ExtensionHostDebugBroadcastChannel.ChannelName, new ExtensionHostDebugBroadcastChannel());
A
Asher 已提交
740 741 742 743 744

		this.services.set(ILogService, logService);
		this.services.set(IEnvironmentService, environmentService);
		this.services.set(IConfigurationService, new SyncDescriptor(ConfigurationService, [environmentService.machineSettingsResource]));
		this.services.set(IRequestService, new SyncDescriptor(RequestService));
A
Asher 已提交
745
		this.services.set(IFileService, fileService);
A
Asher 已提交
746
		this.services.set(IProductService, { _serviceBrand: undefined, ...product });
A
Asher 已提交
747
		this.services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
A
Asher 已提交
748 749
		this.services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));

A
Asher 已提交
750 751 752
		if (!environmentService.args["disable-telemetry"]) {
			this.services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [{
				appender: combinedAppender(
A
Asher 已提交
753
					new AppInsightsAppender("code-server", null, () => new TelemetryClient() as any, logService),
A
Asher 已提交
754 755 756
					new LogAppender(logService),
				),
				commonProperties: resolveCommonProperties(
A
Asher 已提交
757
					product.commit, product.codeServerVersion, await getMachineId(),
A
Asher 已提交
758
					[], environmentService.installSourcePath, "code-server",
A
Asher 已提交
759
				),
A
Asher 已提交
760
				piiPaths: this.allowedRequestPaths,
A
Asher 已提交
761 762 763 764 765
			} as ITelemetryServiceConfig]));
		} else {
			this.services.set(ITelemetryService, NullTelemetryService);
		}

A
Asher 已提交
766 767
		await new Promise((resolve) => {
			const instantiationService = new InstantiationService(this.services);
A
Asher 已提交
768 769 770
			this.services.set(ILocalizationsService, instantiationService.createInstance(LocalizationsService));
			this.services.set(INodeProxyService, instantiationService.createInstance(NodeProxyService));

A
Asher 已提交
771 772
			instantiationService.invokeFunction(() => {
				instantiationService.createInstance(LogsDataCleaner);
A
Asher 已提交
773
				const telemetryService = this.services.get(ITelemetryService) as ITelemetryService;
A
Asher 已提交
774 775 776 777 778 779 780 781 782 783
				this.ipc.registerChannel("extensions", new ExtensionManagementChannel(
					this.services.get(IExtensionManagementService) as IExtensionManagementService,
					(context) => getUriTransformer(context.remoteAuthority),
				));
				this.ipc.registerChannel("remoteextensionsenvironment", new ExtensionEnvironmentChannel(
					environmentService, logService, telemetryService, this.options.connectionToken || "",
				));
				this.ipc.registerChannel("request", new RequestChannel(this.services.get(IRequestService) as IRequestService));
				this.ipc.registerChannel("telemetry", new TelemetryChannel(telemetryService));
				this.ipc.registerChannel("nodeProxy", new NodeProxyChannel(this.services.get(INodeProxyService) as INodeProxyService));
A
Asher 已提交
784
				this.ipc.registerChannel("localizations", <IServerChannel<any>>createChannelReceiver(this.services.get(ILocalizationsService) as ILocalizationsService));
A
Asher 已提交
785 786
				this.ipc.registerChannel("update", new UpdateChannel(instantiationService.createInstance(UpdateService)));
				this.ipc.registerChannel(REMOTE_FILE_SYSTEM_CHANNEL_NAME, new FileProviderChannel(environmentService, logService));
A
Asher 已提交
787
				resolve(new ErrorTelemetry(telemetryService));
A
Asher 已提交
788 789 790 791
			});
		});
	}

792 793 794 795 796 797
	/**
	 * TODO: implement.
	 */
	private async getDebugPort(): Promise<number | undefined> {
		return undefined;
	}
A
Asher 已提交
798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872

	/**
	 * Since we can't pass TLS sockets to children, use this to proxy the socket
	 * and pass a non-TLS socket.
	 */
	private createProxy = async (socket: net.Socket): Promise<net.Socket> => {
		if (!(socket instanceof tls.TLSSocket)) {
			return socket;
		}

		await this.startProxyServer();

		return new Promise((resolve, reject) => {
			const timeout = setTimeout(() => {
				listener.dispose();
				socket.destroy();
				proxy.destroy();
				reject(new Error("TLS socket proxy timed out"));
			}, this.proxyTimeout);

			const listener = this._onProxyConnect.event((connection) => {
				connection.once("data", (data) => {
					if (!socket.destroyed && !proxy.destroyed && data.toString() === id) {
						clearTimeout(timeout);
						listener.dispose();
						[[proxy, socket], [socket, proxy]].forEach(([a, b]) => {
							a.pipe(b);
							a.on("error", () => b.destroy());
							a.on("close", () => b.destroy());
							a.on("end", () => b.end());
						});
						resolve(connection);
					}
				});
			});

			const id = generateUuid();
			const proxy = net.connect(this.proxyPipe);
			proxy.once("connect", () => proxy.write(id));
		});
	}

	private async startProxyServer(): Promise<net.Server> {
		if (!this._proxyServer) {
			this._proxyServer = new Promise(async (resolve) => {
				this.proxyPipe = await this.findFreeSocketPath(this.proxyPipe);
				await mkdirp(tmpdir);
				await rimraf(this.proxyPipe);
				const proxyServer = net.createServer((p) => this._onProxyConnect.fire(p));
				proxyServer.once("listening", resolve);
				proxyServer.listen(this.proxyPipe);
			});
		}
		return this._proxyServer;
	}

	private async findFreeSocketPath(basePath: string, maxTries: number = 100): Promise<string> {
		const canConnect = (path: string): Promise<boolean> => {
			return new Promise((resolve) => {
				const socket = net.connect(path);
				socket.once("error", () => resolve(false));
				socket.once("connect", () => {
					socket.destroy();
					resolve(true);
				});
			});
		};

		let i = 0;
		let path = basePath;
		while (await canConnect(path) && i < maxTries) {
			path = `${basePath}-${++i}`;
		}
		return path;
	}
A
Asher 已提交
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909

	/**
	 * Return the file path for Coder settings.
	 */
	private get settingsPath(): string {
		const environment = this.services.get(IEnvironmentService) as IEnvironmentService;
		return path.join(environment.userDataPath, "coder.json");
	}

	/**
	 * Read settings from the file. On a failure return last known settings and
	 * log a warning.
	 *
	 */
	private async readSettings(): Promise<Settings> {
		try {
			const raw = (await util.promisify(fs.readFile)(this.settingsPath, "utf8")).trim();
			this.settings = raw ? JSON.parse(raw) : {};
		} catch (error) {
			if (error.code !== "ENOENT") {
				(this.services.get(ILogService) as ILogService).warn(error.message);
			}
		}
		return this.settings;
	}

	/**
	 * Write settings combined with current settings. On failure log a warning.
	 */
	private async writeSettings(newSettings: Partial<Settings>): Promise<void> {
		this.settings = { ...this.settings, ...newSettings };
		try {
			await util.promisify(fs.writeFile)(this.settingsPath, JSON.stringify(this.settings));
		} catch (error) {
			(this.services.get(ILogService) as ILogService).warn(error.message);
		}
	}
A
Asher 已提交
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953

	/**
	 * Return the file path for the heartbeat file.
	 */
	private get heartbeatPath(): string {
		const environment = this.services.get(IEnvironmentService) as IEnvironmentService;
		return path.join(environment.userDataPath, "heartbeat");
	}

	/**
	 * Return all online connections regardless of type.
	 */
	private get onlineConnections(): Connection[] {
		const online = <Connection[]>[];
		this.connections.forEach((connections) => {
			connections.forEach((connection) => {
				if (typeof connection.offline === "undefined") {
					online.push(connection);
				}
			});
		});
		return online;
	}

	/**
	 * Write to the heartbeat file if we haven't already done so within the
	 * timeout and start or reset a timer that keeps running as long as there are
	 * active connections. Failures are logged as warnings.
	 */
	private heartbeat(): void {
		const now = Date.now();
		if (now - this.lastHeartbeat >= this.heartbeatInterval) {
			util.promisify(fs.writeFile)(this.heartbeatPath, "").catch((error) => {
				(this.services.get(ILogService) as ILogService).warn(error.message);
			});
			this.lastHeartbeat = now;
			clearTimeout(this.heartbeatTimer!); // We can clear undefined so ! is fine.
			this.heartbeatTimer = setTimeout(() => {
				if (this.onlineConnections.length > 0) {
					this.heartbeat();
				}
			}, this.heartbeatInterval);
		}
	}
A
Asher 已提交
954
}