| 1 | import net from "node:net"; |
| 2 | import fs from "node:fs/promises"; |
| 3 | import path from "node:path"; |
| 4 | import { lines } from "./windows-browser.mjs"; |
| 5 | |
| 6 | async function privateDirectory(directory) { |
| 7 | await fs.mkdir(directory, { recursive: true, mode: 0o700 }); |
| 8 | const info = await fs.lstat(directory); |
| 9 | if (!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o077)) |
| 10 | throw new Error("Browser service directory is unavailable"); |
| 11 | return path.join(directory, "browser.sock"); |
| 12 | } |
| 13 | |
| 14 | async function socketInfo(address) { |
| 15 | const info = await fs.lstat(address); |
| 16 | if (!info.isSocket() || info.uid !== process.getuid() || (info.mode & 0o077)) |
| 17 | throw new Error("Browser service socket is unavailable"); |
| 18 | return info; |
| 19 | } |
| 20 | |
| 21 | function connect(address) { |
| 22 | return new Promise((resolve, reject) => { |
| 23 | const socket = net.createConnection({ path: address, allowHalfOpen: true }); |
| 24 | socket.once("error", reject); |
| 25 | socket.once("connect", () => { socket.off("error", reject); resolve(socket); }); |
| 26 | }); |
| 27 | } |
| 28 | |
| 29 | export async function relayMacOSBrowser(directory, input = process.stdin, output = process.stdout) { |
| 30 | const address = await privateDirectory(directory); |
| 31 | await socketInfo(address); |
| 32 | const socket = await connect(address); |
| 33 | socket.on("error", () => {}); |
| 34 | try { |
| 35 | const replies = lines(socket, 30 << 20)[Symbol.asyncIterator](); |
| 36 | for await (const line of lines(input)) { |
| 37 | await new Promise((resolve, reject) => socket.write(line + "\n", error => error ? reject(error) : resolve())); |
| 38 | const reply = await replies.next(); |
| 39 | if (reply.done) throw new Error("Browser service connection closed"); |
| 40 | await new Promise((resolve, reject) => output.write(reply.value + "\n", error => error ? reject(error) : resolve())); |
| 41 | } |
| 42 | socket.end(); |
| 43 | } finally { |
| 44 | socket.destroy(); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | |
| 49 | |
| 50 | export async function serveMacOSBrowser({ directory, dispatch, close, disconnect }) { |
| 51 | const address = await privateDirectory(directory); |
| 52 | const previous = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; }); |
| 53 | if (previous) { |
| 54 | await socketInfo(address); |
| 55 | let live; |
| 56 | try { live = await connect(address); } |
| 57 | catch (error) { if (error.code !== "ECONNREFUSED" && error.code !== "ENOENT") throw error; } |
| 58 | if (live) { live.destroy(); throw new Error("Browser service is already running"); } |
| 59 | const current = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; }); |
| 60 | if (current && current.ino !== previous.ino) throw new Error("Browser service owner changed"); |
| 61 | if (current) await fs.unlink(address); |
| 62 | } |
| 63 | const clients = new Set(); |
| 64 | let queue = Promise.resolve(), stopping; |
| 65 | const request = (input, options = {}) => { |
| 66 | const pending = queue.then(() => { |
| 67 | if (stopping) throw new Error("Browser service is stopping"); |
| 68 | options.signal?.throwIfAborted(); |
| 69 | return dispatch(input, options); |
| 70 | }); |
| 71 | queue = pending.catch(() => {}); |
| 72 | return pending; |
| 73 | }; |
| 74 | const server = net.createServer({ allowHalfOpen: true }, socket => { |
| 75 | if (stopping || clients.size >= 16) { socket.destroy(); return; } |
| 76 | clients.add(socket); |
| 77 | const cancellation = new AbortController(); |
| 78 | socket.on("error", () => {}); |
| 79 | socket.once("end", () => { cancellation.abort(); socket.end(); }); |
| 80 | socket.once("close", () => { |
| 81 | cancellation.abort(); clients.delete(socket); |
| 82 | if (disconnect) { |
| 83 | const released = queue.then(() => disconnect(cancellation.signal)); |
| 84 | queue = released.catch(() => {}); |
| 85 | } |
| 86 | }); |
| 87 | let pendingReply = false; |
| 88 | void (async () => { |
| 89 | try { |
| 90 | for await (const line of lines(socket)) { |
| 91 | if (pendingReply) throw new Error("Browser service caller has an unfinished request"); |
| 92 | pendingReply = true; |
| 93 | const pending = request(JSON.parse(line), { signal: cancellation.signal }); |
| 94 | void (async () => { |
| 95 | let result; |
| 96 | try { result = await pending; } |
| 97 | catch (error) { result = { error: error.safe ? error.message : "客机浏览器操作失败", code: error.safe ? error.code : "browser_operation_failed" }; } |
| 98 | if (socket.destroyed) return; |
| 99 | const data = JSON.stringify({ ...result, service: { version: 1, persistent: true } }) + "\n"; |
| 100 | if (Buffer.byteLength(data) > 30 << 20) throw new Error("Browser service response is too large"); |
| 101 | await new Promise((resolve, reject) => socket.write(data, error => error ? reject(error) : resolve())); |
| 102 | })().catch(() => socket.destroy()).finally(() => { pendingReply = false; }); |
| 103 | } |
| 104 | } catch { socket.destroy(); } |
| 105 | })(); |
| 106 | }); |
| 107 | await new Promise((resolve, reject) => { server.once("error", reject); server.listen(address, resolve); }); |
| 108 | await fs.chmod(address, 0o600); |
| 109 | const owned = await socketInfo(address); |
| 110 | const stop = async () => { |
| 111 | if (!stopping) stopping = (async () => { |
| 112 | const closed = new Promise(resolve => server.close(resolve)); |
| 113 | for (const client of clients) client.destroy(); |
| 114 | try { await close(); } |
| 115 | finally { |
| 116 | await closed; |
| 117 | await queue; |
| 118 | const current = await fs.lstat(address).catch(() => null); |
| 119 | if (current?.ino === owned.ino) await fs.unlink(address); |
| 120 | } |
| 121 | })(); |
| 122 | return stopping; |
| 123 | }; |
| 124 | return { request, close: stop }; |
| 125 | } |