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,
|
|
|
|
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 { 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
|
|
|
|
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 })
|
|
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
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 {
|
2020-03-17 00:43:32 +07:00
|
|
|
mime: "application/json",
|
2020-02-14 05:38:05 +07:00
|
|
|
content: {
|
|
|
|
applications: await this.applications(),
|
|
|
|
},
|
|
|
|
} as HttpResponse<ApplicationsResponse>
|
2020-03-17 00:43:32 +07:00
|
|
|
case ApiEndpoint.process:
|
|
|
|
return this.process(request)
|
2020-02-14 05:38:05 +07:00
|
|
|
case ApiEndpoint.recent:
|
|
|
|
this.ensureMethod(request)
|
|
|
|
return {
|
2020-03-17 00:43:32 +07:00
|
|
|
mime: "application/json",
|
2020-02-14 05:38:05 +07:00
|
|
|
content: await this.recent(),
|
|
|
|
} as HttpResponse<RecentResponse>
|
|
|
|
}
|
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-12 04:00:39 +07:00
|
|
|
): Promise<void> {
|
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
|
|
|
}
|
|
|
|
|
2020-03-12 04:00:39 +07:00
|
|
|
private async handleStatusSocket(request: http.IncomingMessage, socket: net.Socket, head: Buffer): Promise<void> {
|
2020-02-14 05:38:05 +07:00
|
|
|
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()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-03-17 00:43:32 +07:00
|
|
|
* A socket that connects to the process.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
|
|
|
private async handleRunSocket(
|
2020-03-17 00:43:32 +07:00
|
|
|
_route: Route,
|
2020-02-14 05:38:05 +07:00
|
|
|
request: http.IncomingMessage,
|
|
|
|
socket: net.Socket,
|
2020-02-15 07:46:00 +07:00
|
|
|
head: Buffer,
|
2020-03-12 04:00:39 +07:00
|
|
|
): Promise<void> {
|
2020-03-17 00:43:32 +07:00
|
|
|
logger.debug("connecting to process")
|
2020-02-14 05:38:05 +07:00
|
|
|
const ws = await new Promise<WebSocket>((resolve, reject) => {
|
|
|
|
this.ws.handleUpgrade(request, socket, head, (socket) => {
|
|
|
|
socket.binaryType = "arraybuffer"
|
|
|
|
|
|
|
|
socket.on("error", (error) => {
|
|
|
|
socket.close(SessionError.FailedToStart)
|
|
|
|
logger.error("got error while connecting socket", field("error", error))
|
|
|
|
reject(error)
|
|
|
|
})
|
2020-03-17 00:43:32 +07:00
|
|
|
|
|
|
|
resolve(socket as WebSocket)
|
2020-02-14 05:38:05 +07:00
|
|
|
})
|
|
|
|
})
|
|
|
|
|
2020-03-17 00:43:32 +07:00
|
|
|
logger.debug("connected to process")
|
|
|
|
|
2020-02-14 05:38:05 +07:00
|
|
|
// 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 whitelisted applications.
|
|
|
|
*/
|
|
|
|
public async applications(): Promise<ReadonlyArray<Application>> {
|
|
|
|
return findWhitelistedApplications()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return installed applications.
|
|
|
|
*/
|
|
|
|
public async installedApplications(): Promise<ReadonlyArray<Application>> {
|
|
|
|
return findApplications()
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-03-17 00:43:32 +07:00
|
|
|
* Handle /process endpoint.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
2020-03-17 00:43:32 +07:00
|
|
|
private async process(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-17 00:43:32 +07:00
|
|
|
throw new HttpError("No data was provided", HttpCode.BadRequest)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
2020-03-17 00:43:32 +07:00
|
|
|
const parsed: Application = JSON.parse(data)
|
|
|
|
|
2020-02-14 05:38:05 +07:00
|
|
|
switch (request.method) {
|
|
|
|
case "DELETE":
|
2020-03-17 00:43:32 +07:00
|
|
|
if (parsed.pid) {
|
|
|
|
await this.killProcess(parsed.pid)
|
|
|
|
} else if (parsed.path) {
|
|
|
|
await this.killProcess(parsed.path)
|
|
|
|
} else {
|
|
|
|
throw new Error("No pid or path was provided")
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
mime: "application/json",
|
|
|
|
code: HttpCode.Ok,
|
|
|
|
}
|
2020-02-14 05:38:05 +07:00
|
|
|
case "POST": {
|
2020-03-17 00:43:32 +07:00
|
|
|
if (!parsed.exec) {
|
|
|
|
throw new Error("No exec was provided")
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
return {
|
2020-03-17 00:43:32 +07:00
|
|
|
mime: "application/json",
|
2020-02-14 05:38:05 +07:00
|
|
|
content: {
|
|
|
|
created: true,
|
2020-03-17 00:43:32 +07:00
|
|
|
pid: await this.spawnProcess(parsed.exec),
|
2020-02-14 05:38:05 +07:00
|
|
|
},
|
|
|
|
} 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
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-03-17 00:43:32 +07:00
|
|
|
* Kill a process identified by pid or path if a web app.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
2020-03-17 00:43:32 +07:00
|
|
|
public async killProcess(pid: number | string): Promise<void> {
|
|
|
|
if (typeof pid === "string") {
|
|
|
|
switch (pid) {
|
|
|
|
case Vscode.path:
|
|
|
|
await this.vscode.dispose()
|
|
|
|
break
|
|
|
|
default:
|
|
|
|
throw new Error(`Process "${pid}" does not exist`)
|
2020-02-28 01:04:23 +07:00
|
|
|
}
|
2020-03-17 00:43:32 +07:00
|
|
|
} else {
|
|
|
|
process.kill(pid)
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2020-03-17 00:43:32 +07:00
|
|
|
* Spawn a process and return the pid.
|
2020-02-14 05:38:05 +07:00
|
|
|
*/
|
2020-03-17 00:43:32 +07:00
|
|
|
public async spawnProcess(exec: string): Promise<number> {
|
|
|
|
const proc = cp.spawn(exec, {
|
|
|
|
shell: process.env.SHELL || true,
|
|
|
|
env: {
|
|
|
|
...process.env,
|
|
|
|
},
|
|
|
|
})
|
2020-02-14 05:38:05 +07:00
|
|
|
|
2020-03-17 00:43:32 +07:00
|
|
|
proc.on("error", (error) => logger.error("process errored", field("pid", proc.pid), field("error", error)))
|
|
|
|
proc.on("exit", () => logger.debug("process exited", field("pid", proc.pid)))
|
2020-02-14 05:38:05 +07:00
|
|
|
|
2020-03-17 00:43:32 +07:00
|
|
|
logger.debug("started process", field("pid", proc.pid))
|
2020-02-14 05:38:05 +07:00
|
|
|
|
2020-03-17 00:43:32 +07:00
|
|
|
return proc.pid
|
2020-02-14 05:38:05 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
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) {
|
2020-03-17 00:43:32 +07:00
|
|
|
return { paths: [], workspaces: [] }
|
2020-02-19 03:13:22 +07:00
|
|
|
}
|
|
|
|
|
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
|
|
|
}
|
|
|
|
|
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 {
|
2020-03-17 00:43:32 +07:00
|
|
|
mime: "application/json",
|
2020-02-14 05:38:05 +07:00
|
|
|
content: JSON.stringify({ error }),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|