main.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. mod ipc;
  5. mod server;
  6. use crate::server::run_server;
  7. use clap::Parser;
  8. use std::process;
  9. use tokio::process::Command;
  10. use tracing::{error, info};
  11. /// 命令行参数
  12. #[derive(Parser, Debug)]
  13. #[command(author, version, about, long_about = None)]
  14. struct Args {
  15. /// 服务器监听端口
  16. #[arg(short, long, default_value_t = 12801)]
  17. port: u16,
  18. /// 用户会话启动命令
  19. #[arg(short, long)]
  20. session_command: Option<String>,
  21. /// 启动子进程命令 (父进程退出时会自动终止子进程)
  22. #[arg(short, long)]
  23. launch_command: Option<String>,
  24. /// 自定义 HTML 页面路径
  25. #[arg(long)]
  26. page: Option<std::path::PathBuf>,
  27. }
  28. #[tokio::main]
  29. async fn main() {
  30. // 初始化日志
  31. tracing_subscriber::fmt::init();
  32. let args = Args::parse();
  33. info!("启动参数: {:?}", args);
  34. // 设置会话命令环境变量
  35. if let Some(cmd) = &args.session_command {
  36. info!("设置会话命令: {}", cmd);
  37. unsafe {
  38. std::env::set_var("SESSION_COMMAND", cmd);
  39. }
  40. } else {
  41. info!("使用默认会话命令: $SHELL");
  42. }
  43. // 启动子进程
  44. let child = if let Some(cmd) = &args.launch_command {
  45. info!("启动子进程: {}", cmd);
  46. Some(
  47. Command::new("sh")
  48. .arg("-c")
  49. .arg(cmd)
  50. .kill_on_drop(true)
  51. .spawn()
  52. .expect("启动子进程失败")
  53. )
  54. } else {
  55. None
  56. };
  57. // 启动服务器
  58. info!("启动服务器,监听端口: {}", args.port);
  59. let html_content = match args.page {
  60. Some(path) => std::fs::read_to_string(path).unwrap_or_else(|_| {
  61. error!("无法读取自定义HTML文件,使用默认页面");
  62. "none".to_string()
  63. }),
  64. None => "none".to_string(),
  65. };
  66. if let Err(e) = run_server(args.port, html_content).await {
  67. error!("服务器启动失败: {}", e);
  68. process::exit(1);
  69. }
  70. // 等待子进程退出
  71. if let Some(mut child) = child {
  72. match child.wait().await {
  73. Ok(status) => {
  74. info!("子进程已退出,状态码: {}", status);
  75. process::exit(0);
  76. }
  77. Err(e) => {
  78. error!("等待子进程时出错: {}", e);
  79. process::exit(1);
  80. }
  81. }
  82. }
  83. }