code-server-2/server.ts

222 lines
6.7 KiB
TypeScript
Raw Normal View History

2019-06-27 22:34:33 +00:00
import * as fs from "fs";
import * as http from "http";
import * as net from "net";
import * as path from "path";
import * as util from "util";
import * as url from "url";
import { Emitter } from "vs/base/common/event";
2019-06-28 22:49:29 +00:00
import { getMediaMime } from "vs/base/common/mime";
import { extname } from "vs/base/common/path";
2019-06-28 22:37:23 +00:00
import { IPCServer, ClientConnectionEvent } from "vs/base/parts/ipc/common/ipc";
import { validatePaths } from "vs/code/node/paths";
import { parseMainProcessArgv } from "vs/platform/environment/node/argvHelper";
import { ParsedArgs } from "vs/platform/environment/common/environment";
import { EnvironmentService } from "vs/platform/environment/node/environmentService";
import { InstantiationService } from "vs/platform/instantiation/common/instantiationService";
import { ConsoleLogMainService } from "vs/platform/log/common/log";
import { LogLevelSetterChannel } from "vs/platform/log/common/logIpc";
import { ConnectionType } from "vs/platform/remote/common/remoteAgentConnection";
import { REMOTE_FILE_SYSTEM_CHANNEL_NAME } from "vs/platform/remote/common/remoteAgentFileSystemChannel";
import { Connection, Server as IServer } from "vs/server/connection";
import { ExtensionEnvironmentChannel, FileProviderChannel } from "vs/server/channel";
import { Socket } from "vs/server/socket";
2019-06-27 22:34:33 +00:00
2019-06-28 22:37:23 +00:00
export enum HttpCode {
2019-06-27 22:34:33 +00:00
Ok = 200,
NotFound = 404,
BadRequest = 400,
}
2019-06-28 22:37:23 +00:00
export class HttpError extends Error {
2019-06-27 22:34:33 +00:00
public constructor(message: string, public readonly code: number) {
super(message);
// @ts-ignore
this.name = this.constructor.name;
Error.captureStackTrace(this, this.constructor);
}
}
2019-06-28 22:37:23 +00:00
export class Server implements IServer {
// When a new client connects, it will fire this event which is used in the
// IPC server which manages channels.
public readonly _onDidClientConnect = new Emitter<ClientConnectionEvent>();
2019-06-27 22:34:33 +00:00
public readonly onDidClientConnect = this._onDidClientConnect.event;
private readonly rootPath = path.resolve(__dirname, "../../..");
2019-06-28 22:37:23 +00:00
// 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);
// The web server.
2019-06-27 22:34:33 +00:00
private readonly server: http.Server;
2019-06-28 22:37:23 +00:00
// Persistent connections. These can reconnect within a timeout. Individual
// sockets will add connections made through them to this map and remove them
// when they close.
2019-06-27 22:34:33 +00:00
public readonly connections = new Map<ConnectionType, Map<string, Connection>>();
public constructor() {
this.server = http.createServer(async (request, response): Promise<void> => {
try {
2019-06-28 22:49:29 +00:00
const [content, headers] = await this.handleRequest(request);
2019-06-27 22:34:33 +00:00
response.writeHead(HttpCode.Ok, {
"Cache-Control": "max-age=86400",
// TODO: ETag?
2019-06-28 22:49:29 +00:00
...headers,
2019-06-27 22:34:33 +00:00
});
response.end(content);
} catch (error) {
response.writeHead(typeof error.code === "number" ? error.code : 500);
response.end(error.message);
}
});
this.server.on("upgrade", (request, socket) => {
2019-06-28 22:37:23 +00:00
try {
const nodeSocket = this.handleUpgrade(request, socket);
nodeSocket.handshake(this);
} catch (error) {
socket.end(error.message);
}
2019-06-27 22:34:33 +00:00
});
this.server.on("error", (error) => {
console.error(error);
process.exit(1);
});
2019-06-28 22:37:23 +00:00
let args: ParsedArgs;
try {
args = parseMainProcessArgv(process.argv);
args = validatePaths(args);
} catch (error) {
console.error(error.message);
return process.exit(1);
}
const environmentService = new EnvironmentService(args, process.execPath);
// TODO: might want to use spdlog.
const logService = new ConsoleLogMainService();
this.ipc.registerChannel("loglevel", new LogLevelSetterChannel(logService));
const instantiationService = new InstantiationService();
instantiationService.invokeFunction(() => {
this.ipc.registerChannel(
REMOTE_FILE_SYSTEM_CHANNEL_NAME,
new FileProviderChannel(),
);
this.ipc.registerChannel(
"remoteextensionsenvironment",
new ExtensionEnvironmentChannel(environmentService),
);
});
2019-06-27 22:34:33 +00:00
}
2019-06-28 22:49:29 +00:00
private async handleRequest(request: http.IncomingMessage): Promise<[string | Buffer, http.OutgoingHttpHeaders]> {
2019-06-27 22:34:33 +00:00
if (request.method !== "GET") {
throw new HttpError(
`Unsupported method ${request.method}`,
HttpCode.BadRequest,
);
}
const requestPath = url.parse(request.url || "").pathname || "/";
if (requestPath === "/") {
const htmlPath = path.join(
this.rootPath,
'out/vs/code/browser/workbench/workbench.html',
);
let html = await util.promisify(fs.readFile)(htmlPath, "utf8");
const options = {
WEBVIEW_ENDPOINT: {},
WORKBENCH_WEB_CONGIGURATION: {
remoteAuthority: request.headers.host,
},
REMOTE_USER_DATA_URI: {
scheme: "http",
authority: request.headers.host,
path: "/",
},
PRODUCT_CONFIGURATION: {},
CONNECTION_AUTH_TOKEN: {}
};
Object.keys(options).forEach((key) => {
html = html.replace(`"{{${key}}}"`, `'${JSON.stringify(options[key])}'`);
});
html = html.replace('{{WEBVIEW_ENDPOINT}}', JSON.stringify(options.WEBVIEW_ENDPOINT));
2019-06-28 22:49:29 +00:00
return [html, {
"Content-Type": "text/html",
}];
2019-06-27 22:34:33 +00:00
}
try {
const content = await util.promisify(fs.readFile)(
path.join(this.rootPath, requestPath),
);
2019-06-28 22:49:29 +00:00
return [content, {
"Content-Type": getMediaMime(requestPath) || {
".css": "text/css",
".html": "text/html",
".js": "text/javascript",
".json": "application/json",
}[extname(requestPath)] || "text/plain",
}];
2019-06-27 22:34:33 +00:00
} catch (error) {
if (error.code === "ENOENT" || error.code === "EISDIR") {
throw new HttpError("Not found", HttpCode.NotFound);
}
throw error;
}
}
2019-06-28 22:37:23 +00:00
private handleUpgrade(request: http.IncomingMessage, socket: net.Socket): Socket {
2019-06-27 22:34:33 +00:00
if (request.headers.upgrade !== "websocket") {
2019-06-28 22:37:23 +00:00
throw new Error("HTTP/1.1 400 Bad Request");
2019-06-27 22:34:33 +00:00
}
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;
}
}
const nodeSocket = new Socket(socket, options);
nodeSocket.upgrade(request.headers["sec-websocket-key"] as string);
2019-06-28 22:37:23 +00:00
return nodeSocket;
2019-06-27 22:34:33 +00:00
}
2019-06-28 22:37:23 +00:00
public listen(port: number = 8443): void {
2019-06-27 22:34:33 +00:00
this.server.listen(port, () => {
const address = this.server.address();
const location = typeof address === "string"
? address
: `port ${address.port}`;
console.log(`Listening on ${location}`);
console.log(`Serving ${this.rootPath}`);
});
}
}