server.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. // This Source Code Form is subject to the terms of the Mozilla Public
  2. // License, v. 2.0. If a copy of the MPL was not distributed with this
  3. // file, You can obtain one at https://mozilla.org/MPL/2.0/.
  4. use crate::ipc::{IpcError, connect_to_greetd, handle_websocket};
  5. use axum::{
  6. Router,
  7. extract::ws::{WebSocket, WebSocketUpgrade},
  8. response::Html,
  9. routing::get,
  10. };
  11. use std::net::SocketAddr;
  12. use tokio::net::TcpListener;
  13. use tracing::{error, info};
  14. // 简单的 HTML 转义
  15. fn html_escape(s: &str) -> String {
  16. s.replace('&', "&")
  17. .replace('<', "<")
  18. .replace('>', ">")
  19. .replace('\"', "\"")
  20. .replace('\'', "\'")
  21. }
  22. /// 启动 HTTP 服务器
  23. pub async fn run_server(port: u16, html_content: String) -> Result<(), IpcError> {
  24. let app = Router::new()
  25. .route(
  26. "/",
  27. get(move || {
  28. let session_command = std::env::var("SESSION_COMMAND").unwrap_or_default();
  29. let escaped_session_command = html_escape(&session_command);
  30. async move {
  31. let mut content = if html_content != "none".to_string() {
  32. html_content.clone()
  33. } else {
  34. index_handler().await
  35. };
  36. // 确保替换所有占位符
  37. // 优先替换带引号的占位符,再替换不带引号的
  38. if escaped_session_command.is_empty() {
  39. content = content
  40. .replace("\"%SESSION_COMMAND%\"", "\"\"")
  41. .replace("%SESSION_COMMAND%", "");
  42. } else {
  43. content = content
  44. .replace(
  45. "\"%SESSION_COMMAND%\"",
  46. &format!("\"{}\"", &escaped_session_command),
  47. )
  48. .replace("%SESSION_COMMAND%", &escaped_session_command);
  49. }
  50. Html(content)
  51. }
  52. }),
  53. )
  54. .route("/ws", get(websocket_handler));
  55. let addr = SocketAddr::from(([127, 0, 0, 1], port));
  56. info!("正在绑定TCP监听端口: {}", addr);
  57. let listener = TcpListener::bind(addr).await.map_err(|e| {
  58. error!("无法绑定端口 {}: {}", port, e);
  59. IpcError::Protocol(e.to_string())
  60. })?;
  61. info!("服务器启动成功,监听端口: {}", port);
  62. axum::serve(listener, app.into_make_service())
  63. .await
  64. .map_err(|e| {
  65. error!("服务器运行错误: {}", e);
  66. IpcError::Protocol(e.to_string())
  67. })?;
  68. Ok(())
  69. }
  70. /// 处理首页请求
  71. async fn index_handler() -> String {
  72. INDEX_HTML.to_string()
  73. }
  74. /// 处理 WebSocket 升级请求
  75. async fn websocket_handler(ws: WebSocketUpgrade) -> impl axum::response::IntoResponse {
  76. ws.on_upgrade(handle_socket)
  77. }
  78. /// 处理 WebSocket 连接
  79. async fn handle_socket(socket: WebSocket) {
  80. // 连接到 greetd IPC
  81. match connect_to_greetd().await {
  82. Ok(ipc_conn) => {
  83. if let Err(e) = handle_websocket(socket, ipc_conn).await {
  84. error!("WebSocket 处理错误: {}", e);
  85. }
  86. }
  87. Err(e) => error!("无法连接到 greetd: {}", e),
  88. }
  89. }
  90. const INDEX_HTML: &str = r#"<!DOCTYPE html>
  91. <html lang="zh-Hans-CN">
  92. <head>
  93. <meta charset="UTF-8" />
  94. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  95. <title>PageOS 登录管理器</title>
  96. <link
  97. rel="icon"
  98. type="image/svg+xml"
  99. href="data:image/svg+xml;charset=utf-8;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI1MCIgaGVpZ2h0PSI1MCI+PGNpcmNsZSBjeD0iMjUiIGN5PSIyNSIgcj0iMjAiIGZpbGw9ImdyZXkiIC8+PC9zdmc+"
  100. />
  101. <style>
  102. :root,
  103. body {
  104. width: 100%;
  105. height: 100%;
  106. background-color: gray;
  107. display: flex;
  108. align-items: center;
  109. justify-content: center;
  110. }
  111. h1 {
  112. font-size: xx-large;
  113. }
  114. summary {
  115. text-decoration: underline;
  116. }
  117. button,
  118. summary {
  119. cursor: pointer;
  120. }
  121. .auth-container {
  122. margin: 1rem;
  123. color: black;
  124. background-color: white;
  125. display: flex;
  126. flex-direction: column;
  127. gap: 0.5rem;
  128. border: 0.1rem solid black;
  129. padding: 1rem;
  130. }
  131. .auth-container .auth-interface {
  132. display: flex;
  133. flex-direction: column;
  134. gap: 0.5rem;
  135. }
  136. .loading .auth-interface {
  137. display: none;
  138. }
  139. .auth-container input {
  140. box-sizing: border-box;
  141. width: 100%;
  142. }
  143. .auth-container .load {
  144. display: none;
  145. color: white;
  146. text-align: center;
  147. padding: 0.2rem;
  148. background-color: grey;
  149. }
  150. .loading .load {
  151. display: block;
  152. }
  153. .auth-container .log {
  154. border: 0.1rem solid black;
  155. padding: 0.5rem;
  156. font-size: smaller;
  157. }
  158. .auth-container .warn {
  159. color: yellow;
  160. }
  161. .auth-container .error {
  162. color: red;
  163. }
  164. </style>
  165. </head>
  166. <body>
  167. <form id="auth" class="loading">
  168. <div class="auth-container">
  169. <h1>PageOS 登录</h1>
  170. <span class="load">正加载</span>
  171. <div class="auth-interface">
  172. <label class="prompt">
  173. <div>用户名:</div>
  174. </label>
  175. <input
  176. id="input"
  177. type="text"
  178. placeholder="请输入用户名"
  179. autocomplete="username"
  180. />
  181. <button type="submit" class="submit-btn">提交</button>
  182. </div>
  183. <details>
  184. <summary>高级</summary>
  185. <p>环境变量:</p>
  186. <input
  187. id="session-env"
  188. type="text"
  189. placeholder="LANG=zh_CN.UTF-8"
  190. autocomplete="session-env"
  191. />
  192. <p>启动命令:</p>
  193. <input
  194. id="session-cmd"
  195. type="text"
  196. value="%SESSION_COMMAND%"
  197. placeholder="pageos-core --command 'cage -s -- firefox --kiosk --no-remote http://127.0.0.1:12800'"
  198. autocomplete="session-cmd"
  199. />
  200. <p>日志:</p>
  201. <div class="log"></div>
  202. </details>
  203. </div>
  204. </form>
  205. <script>
  206. (function () {
  207. // 获取表单元素
  208. const auth = document.getElementById("auth");
  209. const loadElm = auth.querySelector(".auth-container span.load");
  210. const ai = auth.querySelector(".auth-container .auth-interface");
  211. const promptElm = auth.querySelector(".auth-container label.prompt");
  212. const inputElm = auth.querySelector(".auth-container input#input");
  213. const submitBtn = auth.querySelector(".auth-container .submit-btn");
  214. const statusLog = auth.querySelector(".auth-container .log");
  215. // 显示加载状态
  216. function showLoading(message = "正加载") {
  217. loadElm.textContent = message;
  218. auth.classList.add("loading");
  219. }
  220. // 隐藏加载状态
  221. function hideLoading() {
  222. auth.classList.remove("loading");
  223. inputElm.focus();
  224. }
  225. // 接口和状态
  226. const ws = new WebSocket(`ws://${window.location.host}/ws`);
  227. var currentState = "username"; // username: 未创建 greetd 会话, auth: 在会话中验证
  228. hideLoading();
  229. // 显示状态信息
  230. function logMessage(msg, type = "info") {
  231. const time = new Date().toLocaleTimeString();
  232. const div = document.createElement("div");
  233. div.textContent = `${time}:${msg}`;
  234. if (type === "error") div.className = "error";
  235. statusLog.appendChild(div);
  236. statusLog.scrollTop = statusLog.scrollHeight;
  237. }
  238. // 新增一条提示信息
  239. function addPrompt(text, type = "info") {
  240. const message = document.createElement("div");
  241. message.textContent = text;
  242. message.className = type;
  243. promptElm.appendChild(message);
  244. promptElm.scrollTop = promptElm.scrollHeight;
  245. }
  246. // 清空提示信息
  247. function clearPrompt() {
  248. promptElm.innerHTML = "";
  249. }
  250. // 设定页面文字
  251. function inerface_text(
  252. prompt = "用户名:",
  253. type = "info",
  254. input_type = "text",
  255. placeholder = "请输入用户名"
  256. ) {
  257. addPrompt(prompt, type);
  258. inputElm.type = input_type;
  259. inputElm.placeholder = placeholder;
  260. inputElm.value = "";
  261. hideLoading();
  262. }
  263. // 重置表单
  264. function resetForm() {
  265. clearPrompt();
  266. inerface_text();
  267. hideLoading();
  268. currentState = "username";
  269. }
  270. // 连接
  271. ws.onopen = () => {
  272. logMessage("已连接到服务器");
  273. };
  274. // 断开链接
  275. ws.onclose = () => {
  276. logMessage("连接已关闭", "warn");
  277. resetForm();
  278. };
  279. // 连接出错
  280. ws.onerror = (err) => {
  281. logMessage(`连接错误:${err}`, "error");
  282. };
  283. // 接收消息
  284. ws.onmessage = (event) => {
  285. try {
  286. const msg = JSON.parse(event.data);
  287. logMessage(`收到:${JSON.stringify(msg)}`);
  288. switch (msg.type) {
  289. case "AUTH_PROMPT":
  290. currentState = "auth";
  291. if (msg.message_type === "SECRET") {
  292. inerface_text(msg.message, "info", "password", "请输入密钥");
  293. } else if (msg.message_type === "VISIBLE") {
  294. currentState = "auth";
  295. inerface_text(msg.message, "info", "text", "请输入文本");
  296. } else if (msg.message_type === "INFO") {
  297. currentState = "auth";
  298. addPrompt(msg.message);
  299. } else if (msg.message_type === "ERROR") {
  300. logMessage(`✖ greetd 错误:${msg.message}`, "error");
  301. addPrompt(msg.message, "error");
  302. }
  303. break;
  304. case "AUTH_SUCCESS":
  305. logMessage("✔ 登录成功! 正在启动会话……");
  306. showLoading("登录成功,正启动会话");
  307. const envStr = document.getElementById("session-env").value;
  308. const cmdStr = document.getElementById("session-cmd").value;
  309. // 将命令字符串分割为参数数组,处理带引号的参数
  310. const cmd =
  311. cmdStr
  312. .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
  313. ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
  314. // 将环境变量字符串分割为键值对数组
  315. const env =
  316. envStr
  317. .match(/[^\s"']+|"([^"]*)"|'([^']*)'/g)
  318. ?.map((arg) => arg.replace(/^["']|["']$/g, "")) || [];
  319. ws.send(JSON.stringify({ type: "START_SESSION", cmd, env }));
  320. break;
  321. case "AUTH_ERROR":
  322. logMessage(`✖ 错误:${msg.reason}`, "error");
  323. resetForm();
  324. break;
  325. }
  326. hideLoading();
  327. } catch (e) {
  328. logMessage(`消息解析错误:${e}`, "error");
  329. addPrompt(`消息解析错误:${e}`, "error");
  330. }
  331. };
  332. document.getElementById("auth").addEventListener("submit", (e) => {
  333. e.preventDefault();
  334. console.log("表单提交已触发");
  335. if (currentState === "username") {
  336. const username = inputElm.value.trim();
  337. if (!username) {
  338. logMessage("请输入用户名", "warn");
  339. addPrompt("请输入用户名", "warn");
  340. return;
  341. }
  342. showLoading();
  343. ws.send(JSON.stringify({ type: "AUTH_REQUEST", username }));
  344. } else {
  345. const response = inputElm.value;
  346. if (!response) {
  347. logMessage("请输入信息", "warn");
  348. addPrompt("请输入信息", "warn");
  349. return;
  350. }
  351. showLoading();
  352. ws.send(JSON.stringify({ type: "AUTH_RESPONSE", response }));
  353. }
  354. });
  355. })();
  356. </script>
  357. </body>
  358. </html>"#;