// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. use crate::ipc::{IpcError, connect_to_greetd, handle_websocket}; use axum::{ Router, extract::ws::{WebSocket, WebSocketUpgrade}, response::Html, routing::get, }; use std::net::SocketAddr; use tokio::net::TcpListener; use tracing::{error, info}; // 简单的 HTML 转义 fn html_escape(s: &str) -> String { s.replace('&', "&") .replace('<', "<") .replace('>', ">") .replace('\"', "\"") .replace('\'', "\'") } /// 启动 HTTP 服务器 pub async fn run_server(port: u16, html_content: String) -> Result<(), IpcError> { let app = Router::new() .route( "/", get(move || { let session_command = std::env::var("SESSION_COMMAND").unwrap_or_default(); let escaped_session_command = html_escape(&session_command); async move { let mut content = if html_content != "none".to_string() { html_content.clone() } else { index_handler().await }; // 确保替换所有占位符 // 优先替换带引号的占位符,再替换不带引号的 if escaped_session_command.is_empty() { content = content .replace("\"%SESSION_COMMAND%\"", "\"\"") .replace("%SESSION_COMMAND%", ""); } else { content = content .replace( "\"%SESSION_COMMAND%\"", &format!("\"{}\"", &escaped_session_command), ) .replace("%SESSION_COMMAND%", &escaped_session_command); } Html(content) } }), ) .route("/ws", get(websocket_handler)); let addr = SocketAddr::from(([127, 0, 0, 1], port)); info!("正在绑定TCP监听端口: {}", addr); let listener = TcpListener::bind(addr).await.map_err(|e| { error!("无法绑定端口 {}: {}", port, e); IpcError::Protocol(e.to_string()) })?; info!("服务器启动成功,监听端口: {}", port); axum::serve(listener, app.into_make_service()) .await .map_err(|e| { error!("服务器运行错误: {}", e); IpcError::Protocol(e.to_string()) })?; Ok(()) } /// 处理首页请求 async fn index_handler() -> String { INDEX_HTML.to_string() } /// 处理 WebSocket 升级请求 async fn websocket_handler(ws: WebSocketUpgrade) -> impl axum::response::IntoResponse { ws.on_upgrade(handle_socket) } /// 处理 WebSocket 连接 async fn handle_socket(socket: WebSocket) { // 连接到 greetd IPC match connect_to_greetd().await { Ok(ipc_conn) => { if let Err(e) = handle_websocket(socket, ipc_conn).await { error!("WebSocket 处理错误: {}", e); } } Err(e) => error!("无法连接到 greetd: {}", e), } } const INDEX_HTML: &str = r#"