server.ts 21.4 KB
Newer Older
A
Asher 已提交
1 2
import * as fs from "fs";
import * as http from "http";
A
Asher 已提交
3
import * as https from "https";
A
Asher 已提交
4 5
import * as net from "net";
import * as path from "path";
A
Asher 已提交
6
import * as tls from "tls";
A
Asher 已提交
7 8
import * as util from "util";
import * as url from "url";
A
Asher 已提交
9
import * as querystring from "querystring";
A
Asher 已提交
10 11

import { Emitter } from "vs/base/common/event";
A
Asher 已提交
12
import { sanitizeFilePath } from "vs/base/common/extpath";
A
Asher 已提交
13
import { UriComponents, URI } from "vs/base/common/uri";
A
Asher 已提交
14
import { IPCServer, ClientConnectionEvent, StaticRouter } from "vs/base/parts/ipc/common/ipc";
A
Asher 已提交
15
import { mkdirp } from "vs/base/node/pfs";
A
Asher 已提交
16
import { LogsDataCleaner } from "vs/code/electron-browser/sharedProcess/contrib/logsDataCleaner";
A
Asher 已提交
17 18 19 20
import { IConfigurationService } from "vs/platform/configuration/common/configuration";
import { ConfigurationService } from "vs/platform/configuration/node/configurationService";
import { IDialogService } from "vs/platform/dialogs/common/dialogs";
import { DialogChannelClient } from "vs/platform/dialogs/node/dialogIpc";
A
Asher 已提交
21
import { IEnvironmentService, ParsedArgs } from "vs/platform/environment/common/environment";
A
Asher 已提交
22
import { EnvironmentService } from "vs/platform/environment/node/environmentService";
A
Asher 已提交
23
import { IExtensionManagementService, IExtensionGalleryService } from "vs/platform/extensionManagement/common/extensionManagement";
A
Asher 已提交
24
import { ExtensionGalleryChannel } from "vs/platform/extensionManagement/node/extensionGalleryIpc";
A
Asher 已提交
25 26 27 28
import { ExtensionGalleryService } from "vs/platform/extensionManagement/node/extensionGalleryService";
import { ExtensionManagementChannel } from "vs/platform/extensionManagement/node/extensionManagementIpc";
import { ExtensionManagementService } from "vs/platform/extensionManagement/node/extensionManagementService";
import { SyncDescriptor } from "vs/platform/instantiation/common/descriptors";
A
Asher 已提交
29
import { InstantiationService } from "vs/platform/instantiation/common/instantiationService";
A
Asher 已提交
30
import { ServiceCollection } from "vs/platform/instantiation/common/serviceCollection";
A
Asher 已提交
31 32
import { ILocalizationsService } from "vs/platform/localizations/common/localizations";
import { LocalizationsService } from "vs/platform/localizations/node/localizations";
33
import { getLogLevel, ILogService } from "vs/platform/log/common/log";
A
Asher 已提交
34
import { LogLevelSetterChannel } from "vs/platform/log/common/logIpc";
A
Asher 已提交
35
import { SpdLogService } from "vs/platform/log/node/spdlogService";
A
Asher 已提交
36
import { IProductConfiguration } from "vs/platform/product/common/product";
A
Asher 已提交
37
import product from "vs/platform/product/node/product";
38
import { ConnectionType, ConnectionTypeRequest } from "vs/platform/remote/common/remoteAgentConnection";
A
Asher 已提交
39
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from "vs/platform/remote/common/remoteAgentFileSystemChannel";
A
Asher 已提交
40 41 42 43
import { IRequestService } from "vs/platform/request/node/request";
import { RequestService } from "vs/platform/request/node/requestService";
import { ITelemetryService } from "vs/platform/telemetry/common/telemetry";
import { NullTelemetryService } from "vs/platform/telemetry/common/telemetryUtils";
A
Asher 已提交
44
import { RemoteExtensionLogFileName } from "vs/workbench/services/remote/common/remoteAgentService";
A
Asher 已提交
45
// import { TelemetryService } from "vs/workbench/services/telemetry/electron-browser/telemetryService";
A
Asher 已提交
46
import { IWorkbenchConstructionOptions } from "vs/workbench/workbench.web.api";
A
Asher 已提交
47

A
Asher 已提交
48 49 50
import { Connection, ManagementConnection, ExtensionHostConnection } from "vs/server/src/connection";
import { ExtensionEnvironmentChannel, FileProviderChannel , } from "vs/server/src/channel";
import { Protocol } from "vs/server/src/protocol";
A
Asher 已提交
51
import { getMediaMime, getUriTransformer, useHttpsTransformer } from "vs/server/src/util";
A
Asher 已提交
52

A
Asher 已提交
53
export enum HttpCode {
A
Asher 已提交
54
	Ok = 200,
A
Asher 已提交
55
	Redirect = 302,
A
Asher 已提交
56 57
	NotFound = 404,
	BadRequest = 400,
A
Asher 已提交
58 59 60
	Unauthorized = 401,
	LargePayload = 413,
	ServerError = 500,
A
Asher 已提交
61 62
}

A
Asher 已提交
63 64
export interface Options {
	WORKBENCH_WEB_CONGIGURATION: IWorkbenchConstructionOptions;
A
Asher 已提交
65
	REMOTE_USER_DATA_URI: UriComponents | URI;
A
Asher 已提交
66 67 68 69
	PRODUCT_CONFIGURATION: IProductConfiguration | null;
	CONNECTION_AUTH_TOKEN: string;
}

70 71
export interface Response {
	code?: number;
A
Asher 已提交
72 73 74 75 76 77 78 79
	content?: string | Buffer;
	filePath?: string;
	headers?: http.OutgoingHttpHeaders;
	redirect?: string;
}

export interface LoginPayload {
	password?: string;
80 81
}

A
Asher 已提交
82
export class HttpError extends Error {
A
Asher 已提交
83 84 85 86 87 88 89 90
	public constructor(message: string, public readonly code: number) {
		super(message);
		// @ts-ignore
		this.name = this.constructor.name;
		Error.captureStackTrace(this, this.constructor);
	}
}

A
Asher 已提交
91
export interface ServerOptions {
A
Asher 已提交
92 93
	readonly port?: number;
	readonly host?: string;
A
Asher 已提交
94 95 96 97
	readonly socket?: string;
	readonly allowHttp?: boolean;
	readonly cert?: string;
	readonly certKey?: string;
A
Asher 已提交
98 99
	readonly auth?: boolean;
	readonly password?: string;
A
Asher 已提交
100 101
}

A
Asher 已提交
102 103
export abstract class Server {
	// The underlying web server.
A
Asher 已提交
104
	protected readonly server: http.Server | https.Server;
A
Asher 已提交
105

A
Asher 已提交
106
	protected rootPath = path.resolve(__dirname, "../../../..");
A
Asher 已提交
107

A
Asher 已提交
108 109
	private listenPromise: Promise<string> | undefined;

A
Asher 已提交
110 111 112 113 114 115 116 117 118 119 120
	public constructor(private readonly options: ServerOptions) {
		if (this.options.cert && this.options.certKey) {
			useHttpsTransformer();
			const httpolyglot = require.__$__nodeRequire(path.resolve(__dirname, "../node_modules/httpolyglot/lib/index")) as typeof import("httpolyglot");
			this.server = httpolyglot.createServer({
				cert: fs.readFileSync(this.options.cert),
				key: fs.readFileSync(this.options.certKey),
			}, this.onRequest);
		} else {
			this.server = http.createServer(this.onRequest);
		}
A
Asher 已提交
121 122
	}

A
Asher 已提交
123 124 125 126
	public listen(): Promise<string> {
		if (!this.listenPromise) {
			this.listenPromise = new Promise((resolve, reject) => {
				this.server.on("error", reject);
A
Asher 已提交
127
				const onListen = () => resolve(this.address());
A
Asher 已提交
128 129 130 131 132
				if (this.options.socket) {
					this.server.listen(this.options.socket, onListen);
				} else {
					this.server.listen(this.options.port, this.options.host, onListen);
				}
A
Asher 已提交
133 134 135
			});
		}
		return this.listenPromise;
A
Asher 已提交
136 137
	}

A
Asher 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
	/**
	 * The local address of the server. If you pass in a request, it will use the
	 * request's host if listening on a port (rather than a socket). This enables
	 * accessing the webview server from the same host as the main server.
	 */
	public address(request?: http.IncomingMessage): string {
		const address = this.server.address();
		const endpoint = typeof address !== "string"
			? (request
					? request.headers.host!.split(":", 1)[0]
					: (address.address === "::" ? "localhost" : address.address)
			) + ":" + address.port
			: address;
		return `${this.options.allowHttp ? "http" : "https"}://${endpoint}`;
	}

A
Asher 已提交
154 155 156 157 158 159 160 161 162
	protected abstract handleRequest(
		base: string,
		requestPath: string,
		parsedUrl: url.UrlWithParsedQuery,
		request: http.IncomingMessage,
	): Promise<Response>;

	protected async getResource(filePath: string): Promise<Response> {
		const content = await util.promisify(fs.readFile)(filePath);
A
Asher 已提交
163
		return { content, filePath };
A
Asher 已提交
164
	}
A
Asher 已提交
165 166

	private onRequest = async (request: http.IncomingMessage, response: http.ServerResponse): Promise<void> => {
A
Asher 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
		try {
			const payload = await this.preHandleRequest(request);
			response.writeHead(payload.redirect ? HttpCode.Redirect : payload.code || HttpCode.Ok, {
				"Cache-Control": "max-age=86400", // TODO: ETag?
				"Content-Type": getMediaMime(payload.filePath),
				...(payload.redirect ? { Location: payload.redirect } : {}),
				...payload.headers,
			});
			response.end(payload.content);
		} 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);
		}
	}

	private async preHandleRequest(request: http.IncomingMessage): Promise<Response> {
A
Asher 已提交
186 187
		const secure = (request.connection as tls.TLSSocket).encrypted;
		if (!this.options.allowHttp && !secure) {
A
Asher 已提交
188
			return { redirect: "https://" + request.headers.host + request.url };
A
Asher 已提交
189 190
		}

A
Asher 已提交
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
		const parsedUrl = url.parse(request.url || "", true);
		const fullPath = decodeURIComponent(parsedUrl.pathname || "/");
		const match = fullPath.match(/^(\/?[^/]*)(.*)$/);
		let [, base, requestPath] = match
			? match.map((p) => p.replace(/\/$/, ""))
			: ["", "", ""];
		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 = "/";
		}
		if (requestPath === "/") { // Trailing slash, like `domain.com/login/`.
			requestPath = "";
		} else if (requestPath !== "") { // "" will become "." with normalize.
			requestPath = path.normalize(requestPath);
		}
		base = path.normalize(base);

		switch (base) {
			case "/":
				this.ensureGet(request);
				if (!this.authenticate(request)) {
					return { redirect: "https://" + request.headers.host + "/login" };
				}
				break;
			case "/login":
				if (!this.options.auth) {
					throw new HttpError("Not found", HttpCode.NotFound);
				}
				if (requestPath === "") {
					return this.tryLogin(request);
				}
				this.ensureGet(request);
				return this.getResource(path.join(this.rootPath, "/out/vs/server/src/login", requestPath));
			case "/favicon.ico":
				this.ensureGet(request);
				return this.getResource(path.join(this.rootPath, "/out/vs/server/src/favicon", base));
			default:
				this.ensureGet(request);
				if (!this.authenticate(request)) {
					throw new HttpError(`Unauthorized`, HttpCode.Unauthorized);
				}
				break;
		}
A
Asher 已提交
236

A
Asher 已提交
237 238
		return this.handleRequest(base, requestPath, parsedUrl, request);
	}
A
Asher 已提交
239

A
Asher 已提交
240 241 242 243 244
	private async tryLogin(request: http.IncomingMessage): Promise<Response> {
		if (this.authenticate(request)) {
			this.ensureGet(request);
			return { redirect: "https://" + request.headers.host + "/" };
		}
A
Asher 已提交
245

A
Asher 已提交
246 247 248 249 250 251 252 253 254
		if (request.method === "POST") {
			const data = await this.getData<LoginPayload>(request);
			if (this.authenticate(request, data)) {
				return {
					redirect: "https://" + request.headers.host + "/",
					headers: {
					 "Set-Cookie": `password=${data.password}`,
					}
				};
A
Asher 已提交
255
			}
A
Asher 已提交
256 257 258 259 260 261 262 263 264 265 266 267
			let userAgent = request.headers["user-agent"];
			const timestamp = Math.floor(new Date().getTime() / 1000);
			if (Array.isArray(userAgent)) {
				userAgent = userAgent.join(", ");
			}
			console.error("Failed login attempt", JSON.stringify({
				xForwardedFor: request.headers["x-forwarded-for"],
				remoteAddress: request.connection.remoteAddress,
				userAgent,
				timestamp,
			}));
			return this.getLogin("Invalid password", data);
A
Asher 已提交
268
		}
A
Asher 已提交
269 270
		this.ensureGet(request);
		return this.getLogin();
A
Asher 已提交
271 272
	}

A
Asher 已提交
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
	private async getLogin(error: string = "", payload?: LoginPayload): Promise<Response> {
		const filePath = path.join(this.rootPath, "out/vs/server/src/login/login.html");
		let content = await util.promisify(fs.readFile)(filePath, "utf8");
		if (error) {
			content = content.replace("{{ERROR}}", error)
				.replace("display:none", "display:block");
		}
		if (payload && payload.password) {
			content = content.replace('value=""', `value="${payload.password}"`);
		}
		return { content, filePath };
	}

	private ensureGet(request: http.IncomingMessage): void {
		if (request.method !== "GET") {
			throw new HttpError(
				`Unsupported method ${request.method}`,
				HttpCode.BadRequest,
			);
		}
	}

	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) {
						onError(new HttpError(
							"Payload is too large",
							HttpCode.LargePayload,
						));
						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);
	}

	private authenticate(request: http.IncomingMessage, payload?: LoginPayload): boolean {
		if (!this.options.auth) {
			return true;
		}
		const safeCompare = require.__$__nodeRequire(path.resolve(__dirname, "../node_modules/safe-compare/index")) as typeof import("safe-compare");
		if (typeof payload === "undefined") {
			payload = this.parseCookies<LoginPayload>(request);
		}
		return !!this.options.password && safeCompare(payload.password || "", this.options.password);
	}

	private parseCookies<T extends object>(request: http.IncomingMessage): T {
		const cookies: { [key: string]: string } = {};
		if (request.headers.cookie) {
			request.headers.cookie.split(";").forEach((keyValue) => {
				const [key, value] = keyValue.split("=", 2);
				cookies[key.trim()] = decodeURI(value);
			});
		}
		return cookies as T;
A
Asher 已提交
349
	}
A
Asher 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
}

export class MainServer extends Server {
	// Used to notify the IPC server that there is a new client.
	public readonly _onDidClientConnect = new Emitter<ClientConnectionEvent>();
	public readonly onDidClientConnect = this._onDidClientConnect.event;

	// This is separate instead of just extending this class since we can't
	// use properties in the super call. This manages channels.
	private readonly ipc = new IPCServer(this.onDidClientConnect);

	// Persistent connections. These can reconnect within a timeout.
	private readonly connections = new Map<ConnectionType, Map<string, Connection>>();

	private readonly services = new ServiceCollection();

366
	public constructor(
A
Asher 已提交
367
		options: ServerOptions,
368 369 370
		private readonly webviewServer: WebviewServer,
		args: ParsedArgs,
	) {
A
Asher 已提交
371
		super(options);
A
Asher 已提交
372

373 374
		this.server.on("upgrade", async (request, socket) => {
			const protocol = this.createProtocol(request, socket);
A
Asher 已提交
375
			try {
376
				await this.connect(await protocol.handshake(), protocol);
A
Asher 已提交
377
			} catch (error) {
378
				protocol.dispose(error);
A
Asher 已提交
379
			}
A
Asher 已提交
380 381
		});

A
Asher 已提交
382
		const environmentService = new EnvironmentService(args, process.execPath);
A
Asher 已提交
383 384
		const logService = new SpdLogService(RemoteExtensionLogFileName, environmentService.logsPath, getLogLevel(environmentService));
		this.ipc.registerChannel("loglevel", new LogLevelSetterChannel(logService));
A
Asher 已提交
385

A
Asher 已提交
386 387 388
		const router = new StaticRouter((context: any) => {
			return context.clientId === "renderer";
		});
A
Asher 已提交
389

A
Asher 已提交
390 391 392 393 394 395 396 397
		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));
		this.services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));
		this.services.set(ITelemetryService, NullTelemetryService); // TODO: telemetry
		this.services.set(IDialogService, new DialogChannelClient(this.ipc.getChannel("dialog", router)));
		this.services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
A
Asher 已提交
398 399

		const instantiationService = new InstantiationService(this.services);
A
Asher 已提交
400 401 402

		this.services.set(ILocalizationsService, instantiationService.createInstance(LocalizationsService));

A
Asher 已提交
403
		instantiationService.invokeFunction(() => {
A
Asher 已提交
404
			instantiationService.createInstance(LogsDataCleaner);
A
Asher 已提交
405 406 407 408 409
			this.ipc.registerChannel(REMOTE_FILE_SYSTEM_CHANNEL_NAME, new FileProviderChannel(logService));
			this.ipc.registerChannel("remoteextensionsenvironment", new ExtensionEnvironmentChannel(environmentService, logService));
			const extensionsService = this.services.get(IExtensionManagementService) as IExtensionManagementService;
			const extensionsChannel = new ExtensionManagementChannel(extensionsService, (context) => getUriTransformer(context.remoteAuthority));
			this.ipc.registerChannel("extensions", extensionsChannel);
A
Asher 已提交
410 411 412
			const galleryService = this.services.get(IExtensionGalleryService) as IExtensionGalleryService;
			const galleryChannel = new ExtensionGalleryChannel(galleryService);
			this.ipc.registerChannel("gallery", galleryChannel);
A
Asher 已提交
413
		});
A
Asher 已提交
414
	}
A
Asher 已提交
415

A
Asher 已提交
416 417 418 419 420 421 422 423 424 425 426 427
	public async listen(): Promise<string> {
		const environment = (this.services.get(IEnvironmentService) as EnvironmentService);
		const mkdirs = Promise.all([
			environment.extensionsPath,
		].map((p) => mkdirp(p)));
		const [address] = await Promise.all([
			super.listen(),
			mkdirs,
		]);
		return address;
	}

A
Asher 已提交
428
	protected async handleRequest(
429
		base: string,
A
Asher 已提交
430
		requestPath: string,
A
Asher 已提交
431 432
		parsedUrl: url.UrlWithParsedQuery,
		request: http.IncomingMessage,
433 434
	): Promise<Response> {
		switch (base) {
A
Asher 已提交
435
			case "/": return this.getRoot(request, parsedUrl);
436 437 438 439 440 441 442 443 444
			case "/node_modules":
			case "/out":
				return this.getResource(path.join(this.rootPath, base, requestPath));
			// TODO: this setup means you can't request anything from the root if it
			// starts with /node_modules or /out, although that's probably low risk.
			// There doesn't seem to be a really good way to solve this since some
			// resources are requested by the browser (like the extension icon) and
			// some by the file provider (like the extension README). Maybe add a
			// /resource prefix and a file provider that strips that prefix?
A
Asher 已提交
445
			default: return this.getResource(path.join(base, requestPath));
446 447
		}
	}
A
Asher 已提交
448

449
	private async getRoot(request: http.IncomingMessage, parsedUrl: url.UrlWithParsedQuery): Promise<Response> {
A
Asher 已提交
450 451
		const filePath = path.join(this.rootPath, "out/vs/code/browser/workbench/workbench.html");
		let content = await util.promisify(fs.readFile)(filePath, "utf8");
452 453 454 455

		const remoteAuthority = request.headers.host as string;
		const transformer = getUriTransformer(remoteAuthority);

A
Asher 已提交
456 457
		await this.webviewServer.listen();
		const webviewEndpoint = this.webviewServer.address(request);
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

		const cwd = process.env.VSCODE_CWD || process.cwd();
		const workspacePath = parsedUrl.query.workspace as string | undefined;
		const folderPath = !workspacePath ? parsedUrl.query.folder as string | undefined || cwd: undefined;

		const options: Options = {
			WORKBENCH_WEB_CONGIGURATION: {
				workspaceUri: workspacePath
					? transformer.transformOutgoing(URI.file(sanitizeFilePath(workspacePath, cwd)))
					: undefined,
				folderUri: folderPath
					? transformer.transformOutgoing(URI.file(sanitizeFilePath(folderPath, cwd)))
					: undefined,
				remoteAuthority,
				webviewEndpoint,
			},
			REMOTE_USER_DATA_URI: transformer.transformOutgoing(
				(this.services.get(IEnvironmentService) as EnvironmentService).webUserDataHome,
			),
			PRODUCT_CONFIGURATION: product,
			CONNECTION_AUTH_TOKEN: "",
		};

		Object.keys(options).forEach((key) => {
			content = content.replace(`"{{${key}}}"`, `'${JSON.stringify(options[key])}'`);
		});

		content = content.replace('{{WEBVIEW_ENDPOINT}}', webviewEndpoint);

A
Asher 已提交
487
		return { content, filePath };
A
Asher 已提交
488 489
	}

490
	private createProtocol(request: http.IncomingMessage, socket: net.Socket): Protocol {
A
Asher 已提交
491
		if (request.headers.upgrade !== "websocket") {
A
Asher 已提交
492
			throw new Error("HTTP/1.1 400 Bad Request");
A
Asher 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
		}

		const options = {
			reconnectionToken: "",
			reconnection: false,
			skipWebSocketFrames: false,
		};

		if (request.url) {
			const query = url.parse(request.url, true).query;
			if (query.reconnectionToken) {
				options.reconnectionToken = query.reconnectionToken as string;
			}
			if (query.reconnection === "true") {
				options.reconnection = true;
			}
			if (query.skipWebSocketFrames === "true") {
				options.skipWebSocketFrames = true;
			}
		}

514 515 516 517 518
		return new Protocol(
			request.headers["sec-websocket-key"] as string,
			socket,
			options,
		);
A
Asher 已提交
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
	private async connect(message: ConnectionTypeRequest, protocol: Protocol): Promise<void> {
		switch (message.desiredConnectionType) {
			case ConnectionType.ExtensionHost:
			case ConnectionType.Management:
				const debugPort = await this.getDebugPort();
				const ok = message.desiredConnectionType === ConnectionType.ExtensionHost
					? (debugPort ? { debugPort } : {})
					: { type: "ok" };

				if (!this.connections.has(message.desiredConnectionType)) {
					this.connections.set(message.desiredConnectionType, new Map());
				}

				const connections = this.connections.get(message.desiredConnectionType)!;
				const token = protocol.options.reconnectionToken;

				if (protocol.options.reconnection && connections.has(token)) {
					protocol.sendMessage(ok);
					const buffer = protocol.readEntireBuffer();
					protocol.dispose();
					return connections.get(token)!.reconnect(protocol, buffer);
				}

				if (protocol.options.reconnection || connections.has(token)) {
					throw new Error(protocol.options.reconnection
						? "Unrecognized reconnection token"
						: "Duplicate reconnection token"
					);
				}

				protocol.sendMessage(ok);

				let connection: Connection;
				if (message.desiredConnectionType === ConnectionType.Management) {
					connection = new ManagementConnection(protocol);
					this._onDidClientConnect.fire({
						protocol,
						onDidClientDisconnect: connection.onClose,
					});
				} else {
A
Asher 已提交
561 562 563
					connection = new ExtensionHostConnection(
						protocol, this.services.get(ILogService) as ILogService,
					);
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
				}
				connections.set(protocol.options.reconnectionToken, connection);
				connection.onClose(() => {
					connections.delete(protocol.options.reconnectionToken);
				});
				break;
			case ConnectionType.Tunnel: return protocol.tunnel();
			default: throw new Error("Unrecognized connection type");
		}
	}

	/**
	 * TODO: implement.
	 */
	private async getDebugPort(): Promise<number | undefined> {
		return undefined;
	}
A
Asher 已提交
581
}
A
Asher 已提交
582 583

export class WebviewServer extends Server {
A
Asher 已提交
584 585 586 587
	protected async handleRequest(
		base: string,
		requestPath: string,
	): Promise<Response> {
A
Asher 已提交
588 589 590
		const webviewPath = path.join(this.rootPath, "out/vs/workbench/contrib/webview/browser/pre");
		if (requestPath === "") {
			requestPath = "/index.html";
A
Asher 已提交
591 592
		}
		return this.getResource(path.join(webviewPath, base, requestPath));
A
Asher 已提交
593 594
	}
}