2020-02-14 05:38:05 +07:00
|
|
|
import { field, logger } from "@coder/logger"
|
|
|
|
import * as cp from "child_process"
|
2020-02-19 03:13:22 +07:00
|
|
|
import * as fs from "fs-extra"
|
2020-02-14 05:38:05 +07:00
|
|
|
import * as http from "http"
|
|
|
|
import * as net from "net"
|
2020-02-19 03:13:22 +07:00
|
|
|
import * as path from "path"
|
|
|
|
import * as url from "url"
|
2020-02-14 05:38:05 +07:00
|
|
|
import * as WebSocket from "ws"
|
|
|
|
import {
|
|
|
|
Application,
|
|
|
|
ApplicationsResponse,
|
|
|
|
ClientMessage,
|
|
|
|
RecentResponse,
|
2020-02-19 03:13:22 +07:00
|
|
|
RunningResponse,
|
2020-02-14 05:38:05 +07:00
|
|
|
ServerMessage,
|
|
|
|
SessionError,
|
|
|
|
SessionResponse,
|
|
|
|
} from "../../common/api"
|
2020-03-03 01:43:02 +07:00
|
|
|
import { ApiEndpoint, HttpCode, HttpError } from "../../common/http"
|
2020-02-14 05:38:05 +07:00
|
|
|
import { normalize } from "../../common/util"
|
|
|
|
import { HttpProvider, HttpProviderOptions, HttpResponse, HttpServer, Route } from "../http"
|
2020-02-28 01:04:23 +07:00
|
|
|
import { findApplications, findWhitelistedApplications, Vscode } from "./bin"
|
|
|
|
import { VscodeHttpProvider } from "./vscode"
|
2020-02-14 05:38:05 +07:00
|
|
|
|
|
|
|
interface ServerSession {
|
|
|
|
process?: cp.ChildProcess
|
|
|
|
readonly app: Application
|
|
|
|
}
|
|
|
|
|
2020-02-19 03:13:22 +07:00
|
|
|
interface VsRecents {
|
2020-03-03 00:52:39 +07:00
|
|
|
[key: string]: (string | { configURIPath: string })[]
|
2020-02-19 03:13:22 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
type VsSettings = [string, string][]
|
|
|
|
|
2020-02-14 05:38:05 +07:00
|
|
|
/**
|
|
|
|
* API HTTP provider.
|
|
|
|
*/
|
|
|
|
export class ApiHttpProvider extends HttpProvider {
|
|
|
|
private readonly ws = new WebSocket.Server({ noServer: true })
|
|
|
|
private readonly sessions = new Map<string, ServerSession>()
|
|
|
|
|
2020-02-19 03:13:22 +07:00
|
|
|
public constructor(
|
|
|
|
options: HttpProviderOptions,
|
|
|
|
private readonly server: HttpServer,
|
2020-02-28 01:04:23 +07:00
|
|
|
private readonly vscode: VscodeHttpProvider,
|
2020-02-19 03:13:22 +07:00
|
|
|
private readonly dataDir?: string,
|
|
|
|
) {
|
2020-02-14 05:38:05 +07:00
|
|
|
super(options)
|
|
|
|
}
|
|
|
|
|
|
|
|
public dispose(): void {
|
|
|
|
this.sessions.forEach((s) => {
|
|
|
|
if (s.process) {
|
|
|
|
s.process.kill()
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-03-03 01:43:02 +07:00
|
|
|
public async handleRequest(route: Route, request: http.IncomingMessage): Promise<HttpResponse> {
|
|
|
|
this.ensureAuthenticated(request)
|
2020-03-03 03:39:12 +07:00
|
|
|
if (route.requestPath !== "/index.html") {
|
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
|
|
|
}
|
2020-03-03 01:43:02 +07:00
|
|
|
|
2020-02-14 05:38:05 +07:00
|
|
|
switch (route.base) {
|
|
|
|
case ApiEndpoint.applications:
|
|
|
|
this.ensureMethod(request)
|
|
|
|
return {
|
|
|
|
content: {
|
|
|
|
applications: await this.applications(),
|
|
|
|
},
|
|
|
|
} as HttpResponse<ApplicationsResponse>
|
|
|
|
case ApiEndpoint.session:
|
|
|
|
return this.session(request)
|
|
|
|
case ApiEndpoint.recent:
|
|
|
|
this.ensureMethod(request)
|
|
|
|
return {
|
|
|
|
content: await this.recent(),
|
|
|
|
} as HttpResponse<RecentResponse>
|
2020-02-19 03:13:22 +07:00
|
|
|
case ApiEndpoint.running:
|
|
|
|
this.ensureMethod(request)
|
|
|
|
return {
|
|
|
|
content: await this.running(),
|
|
|
|
} as HttpResponse<RunningResponse>
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
2020-03-03 01:43:02 +07:00
|
|
|
|
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
public async handleWebSocket(
|
|
|
|
route: Route,
|
|
|
|
request: http.IncomingMessage,
|
|
|
|
socket: net.Socket,
|
2020-02-15 07:46:00 +07:00
|
|
|
head: Buffer,
|
2020-03-03 01:43:02 +07:00
|
|
|
): Promise<true> {
|
2020-02-14 05:38:05 +07:00
|
|
|
if (!this.authenticated(request)) {
|
|
|
|
throw new Error("not authenticated")
|
|
|
|
}
|
|
|
|
switch (route.base) {
|
|
|
|
case ApiEndpoint.status:
|
|
|
|
return this.handleStatusSocket(request, socket, head)
|
|
|
|
case ApiEndpoint.run:
|
|
|
|
return this.handleRunSocket(route, request, socket, head)
|
|
|
|
}
|
2020-03-03 01:43:02 +07:00
|
|
|
|
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
private async handleStatusSocket(request: http.IncomingMessage, socket: net.Socket, head: Buffer): Promise<true> {
|
|
|
|
const getMessageResponse = async (event: "health"): Promise<ServerMessage> => {
|
|
|
|
switch (event) {
|
|
|
|
case "health":
|
|
|
|
return { event, connections: await this.server.getConnections() }
|
|
|
|
default:
|
|
|
|
throw new Error("unexpected message")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
await new Promise<WebSocket>((resolve) => {
|
|
|
|
this.ws.handleUpgrade(request, socket, head, (ws) => {
|
|
|
|
const send = (event: ServerMessage): void => {
|
|
|
|
ws.send(JSON.stringify(event))
|
|
|
|
}
|
|
|
|
ws.on("message", (data) => {
|
|
|
|
logger.trace("got message", field("message", data))
|
|
|
|
try {
|
|
|
|
const message: ClientMessage = JSON.parse(data.toString())
|
|
|
|
getMessageResponse(message.event).then(send)
|
|
|
|
} catch (error) {
|
|
|
|
logger.error(error.message, field("message", data))
|
|
|
|
}
|
|
|
|
})
|
|
|
|
resolve()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* A socket that connects to a session.
|
|
|
|
*/
|
|
|
|
private async handleRunSocket(
|
|
|
|
route: Route,
|
|
|
|
request: http.IncomingMessage,
|
|
|
|
socket: net.Socket,
|
2020-02-15 07:46:00 +07:00
|
|
|
head: Buffer,
|
2020-02-14 05:38:05 +07:00
|
|
|
): Promise<true> {
|
|
|
|
const sessionId = route.requestPath.replace(/^\//, "")
|
|
|
|
logger.debug("connecting session", field("sessionId", sessionId))
|
|
|
|
const ws = await new Promise<WebSocket>((resolve, reject) => {
|
|
|
|
this.ws.handleUpgrade(request, socket, head, (socket) => {
|
|
|
|
socket.binaryType = "arraybuffer"
|
|
|
|
|
|
|
|
const session = this.sessions.get(sessionId)
|
|
|
|
if (!session) {
|
|
|
|
socket.close(SessionError.NotFound)
|
|
|
|
return reject(new Error("session not found"))
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve(socket as WebSocket)
|
|
|
|
|
|
|
|
socket.on("error", (error) => {
|
|
|
|
socket.close(SessionError.FailedToStart)
|
|
|
|
logger.error("got error while connecting socket", field("error", error))
|
|
|
|
reject(error)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
// Send ready message.
|
|
|
|
ws.send(
|
|
|
|
Buffer.from(
|
|
|
|
JSON.stringify({
|
|
|
|
protocol: "TODO",
|
2020-02-15 07:46:00 +07:00
|
|
|
}),
|
|
|
|
),
|
2020-02-14 05:38:05 +07:00
|
|
|
)
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return whitelisted applications.
|
|
|
|
*/
|
|
|
|
public async applications(): Promise<ReadonlyArray<Application>> {
|
|
|
|
return findWhitelistedApplications()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return installed applications.
|
|
|
|
*/
|
|
|
|
public async installedApplications(): Promise<ReadonlyArray<Application>> {
|
|
|
|
return findApplications()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Get a running application.
|
|
|
|
*/
|
|
|
|
public getRunningApplication(sessionIdOrPath?: string): Application | undefined {
|
|
|
|
if (!sessionIdOrPath) {
|
|
|
|
return undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
const sessionId = sessionIdOrPath.replace(/\//g, "")
|
|
|
|
let session = this.sessions.get(sessionId)
|
|
|
|
if (session) {
|
|
|
|
logger.debug("found application by session id", field("id", sessionId))
|
|
|
|
return session.app
|
|
|
|
}
|
|
|
|
|
|
|
|
const base = normalize("/" + sessionIdOrPath)
|
|
|
|
session = Array.from(this.sessions.values()).find((s) => s.app.path === base)
|
|
|
|
if (session) {
|
|
|
|
logger.debug("found application by path", field("path", base))
|
|
|
|
return session.app
|
|
|
|
}
|
|
|
|
|
|
|
|
logger.debug("no application found matching route", field("route", sessionIdOrPath))
|
|
|
|
return undefined
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handle /session endpoint.
|
|
|
|
*/
|
2020-03-03 01:43:02 +07:00
|
|
|
private async session(request: http.IncomingMessage): Promise<HttpResponse> {
|
2020-02-14 05:38:05 +07:00
|
|
|
this.ensureMethod(request, ["DELETE", "POST"])
|
|
|
|
|
|
|
|
const data = await this.getData(request)
|
|
|
|
if (!data) {
|
2020-03-03 01:43:02 +07:00
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
switch (request.method) {
|
|
|
|
case "DELETE":
|
|
|
|
return this.deleteSession(JSON.parse(data).sessionId)
|
|
|
|
case "POST": {
|
|
|
|
// Prevent spawning the same app multiple times.
|
|
|
|
const parsed: Application = JSON.parse(data)
|
|
|
|
const app = this.getRunningApplication(parsed.sessionId || parsed.path)
|
|
|
|
if (app) {
|
|
|
|
return {
|
|
|
|
content: {
|
|
|
|
created: false,
|
|
|
|
sessionId: app.sessionId,
|
|
|
|
},
|
|
|
|
} as HttpResponse<SessionResponse>
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
content: {
|
|
|
|
created: true,
|
|
|
|
sessionId: await this.createSession(parsed),
|
|
|
|
},
|
|
|
|
} as HttpResponse<SessionResponse>
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-03 01:43:02 +07:00
|
|
|
throw new HttpError("Not found", HttpCode.NotFound)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Kill a session identified by `app.sessionId`.
|
|
|
|
*/
|
2020-02-28 01:04:23 +07:00
|
|
|
public async deleteSession(sessionId: string): Promise<HttpResponse> {
|
2020-02-14 05:38:05 +07:00
|
|
|
logger.debug("deleting session", field("sessionId", sessionId))
|
2020-02-28 01:04:23 +07:00
|
|
|
switch (sessionId) {
|
|
|
|
case "vscode":
|
|
|
|
await this.vscode.dispose()
|
|
|
|
return { code: HttpCode.Ok }
|
|
|
|
default: {
|
|
|
|
const session = this.sessions.get(sessionId)
|
|
|
|
if (!session) {
|
|
|
|
throw new Error("session does not exist")
|
|
|
|
}
|
|
|
|
if (session.process) {
|
|
|
|
session.process.kill()
|
|
|
|
}
|
|
|
|
this.sessions.delete(sessionId)
|
|
|
|
return { code: HttpCode.Ok }
|
|
|
|
}
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new session and return the session ID.
|
|
|
|
*/
|
|
|
|
public async createSession(app: Application): Promise<string> {
|
|
|
|
const sessionId = Math.floor(Math.random() * 10000).toString()
|
|
|
|
if (this.sessions.has(sessionId)) {
|
|
|
|
throw new Error("conflicting session id")
|
|
|
|
}
|
|
|
|
|
|
|
|
if (!app.exec) {
|
|
|
|
throw new Error("cannot execute application with no `exec`")
|
|
|
|
}
|
|
|
|
|
|
|
|
const appSession: ServerSession = {
|
|
|
|
app: {
|
|
|
|
...app,
|
|
|
|
sessionId,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
this.sessions.set(sessionId, appSession)
|
|
|
|
|
|
|
|
try {
|
|
|
|
throw new Error("TODO")
|
|
|
|
} catch (error) {
|
|
|
|
this.sessions.delete(sessionId)
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-02-19 03:13:22 +07:00
|
|
|
* Return VS Code's recent paths.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
|
|
|
public async recent(): Promise<RecentResponse> {
|
2020-02-19 03:13:22 +07:00
|
|
|
try {
|
|
|
|
if (!this.dataDir) {
|
|
|
|
throw new Error("data directory is not set")
|
|
|
|
}
|
|
|
|
|
|
|
|
const state: VsSettings = JSON.parse(await fs.readFile(path.join(this.dataDir, "User/state/global.json"), "utf8"))
|
|
|
|
const setting = Array.isArray(state) && state.find((item) => item[0] === "recently.opened")
|
|
|
|
if (!setting) {
|
|
|
|
throw new Error("settings appear malformed")
|
|
|
|
}
|
|
|
|
|
2020-03-03 00:52:39 +07:00
|
|
|
const pathPromises: { [key: string]: Promise<string> } = {}
|
|
|
|
const workspacePromises: { [key: string]: Promise<string> } = {}
|
2020-02-19 03:13:22 +07:00
|
|
|
Object.values(JSON.parse(setting[1]) as VsRecents).forEach((recents) => {
|
2020-03-03 00:52:39 +07:00
|
|
|
recents.forEach((recent) => {
|
|
|
|
try {
|
|
|
|
const target = typeof recent === "string" ? pathPromises : workspacePromises
|
|
|
|
const pathname = url.parse(typeof recent === "string" ? recent : recent.configURIPath).pathname
|
|
|
|
if (pathname && !target[pathname]) {
|
|
|
|
target[pathname] = new Promise<string>((resolve) => {
|
|
|
|
fs.stat(pathname)
|
|
|
|
.then(() => resolve(pathname))
|
|
|
|
.catch(() => resolve())
|
|
|
|
})
|
2020-02-19 03:13:22 +07:00
|
|
|
}
|
2020-03-03 00:52:39 +07:00
|
|
|
} catch (error) {
|
|
|
|
logger.debug("invalid path", field("path", recent))
|
|
|
|
}
|
|
|
|
})
|
2020-02-19 03:13:22 +07:00
|
|
|
})
|
|
|
|
|
2020-03-03 00:52:39 +07:00
|
|
|
const [paths, workspaces] = await Promise.all([
|
|
|
|
Promise.all(Object.values(pathPromises)),
|
|
|
|
Promise.all(Object.values(workspacePromises)),
|
|
|
|
])
|
|
|
|
|
2020-02-19 03:13:22 +07:00
|
|
|
return {
|
2020-03-03 00:52:39 +07:00
|
|
|
paths: paths.filter((p) => !!p),
|
|
|
|
workspaces: workspaces.filter((p) => !!p),
|
2020-02-19 03:13:22 +07:00
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
if (error.code !== "ENOENT") {
|
|
|
|
throw error
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-03-03 00:52:39 +07:00
|
|
|
return { paths: [], workspaces: [] }
|
2020-02-19 03:13:22 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return running sessions.
|
|
|
|
*/
|
|
|
|
public async running(): Promise<RunningResponse> {
|
2020-02-14 05:38:05 +07:00
|
|
|
return {
|
2020-02-28 01:04:23 +07:00
|
|
|
applications: (this.vscode.running
|
|
|
|
? [
|
|
|
|
{
|
|
|
|
...Vscode,
|
|
|
|
sessionId: "vscode",
|
|
|
|
},
|
|
|
|
]
|
|
|
|
: []
|
|
|
|
).concat(
|
|
|
|
Array.from(this.sessions).map(([sessionId, session]) => ({
|
|
|
|
...session.app,
|
|
|
|
sessionId,
|
|
|
|
})),
|
|
|
|
),
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* For these, just return the error message since they'll be requested as
|
|
|
|
* JSON.
|
|
|
|
*/
|
|
|
|
public async getErrorRoot(_route: Route, _title: string, _header: string, error: string): Promise<HttpResponse> {
|
|
|
|
return {
|
|
|
|
content: JSON.stringify({ error }),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|