Procházet zdrojové kódy

【新增】实现基础终端 greeter 功能

- 新增状态机流程图,明确 Greeter 状态转换逻辑
- 设计核心数据结构,包括 IPC 消息枚举和 Greeter 状态控制
- 实现主控制循环和终端交互逻辑
- 添加错误处理策略,包括统一错误处理和指数退避重试机制
- 优化会话启动流程,增加环境变量过滤和 VT 号码自动检测
- 完善设计文档,详细说明新增功能和实现细节
PJ568 před 1 rokem
rodič
revize
178d4cf551
5 změnil soubory, kde provedl 803 přidání a 9 odebrání
  1. 474 1
      Cargo.lock
  2. 11 1
      Cargo.toml
  3. 2 0
      README.md
  4. 128 5
      doc/design.md
  5. 188 2
      src/main.rs

+ 474 - 1
Cargo.lock

@@ -2,6 +2,479 @@
 # It is not intended for manual editing.
 version = 4
 
+[[package]]
+name = "addr2line"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
+dependencies = [
+ "gimli",
+]
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "async-trait"
+version = "0.1.88"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e539d3fca749fcee5236ab05e93a52867dd549cc157c8cb7f99595f3cedffdb5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "backtrace"
+version = "0.3.75"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6806a6321ec58106fea15becdad98371e28d92ccbc7c8f1b3b6dd724fe8f1002"
+dependencies = [
+ "addr2line",
+ "cfg-if",
+ "libc",
+ "miniz_oxide",
+ "object",
+ "rustc-demangle",
+ "windows-targets",
+]
+
+[[package]]
+name = "bitflags"
+version = "2.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b8e56985ec62d17e9c1001dc89c88ecd7dc08e47eba5ec7c29c7b5eeecde967"
+
+[[package]]
+name = "bytes"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9555578bc9e57714c812a1f84e4fc5b4d21fcb063490c624de019f7464c91268"
+
+[[package]]
+name = "gimli"
+version = "0.31.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
+
+[[package]]
+name = "greetd_ipc"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "700d2e5bfc91a042d1d531b46de245085c6a179debedf149aa97c7ca71492078"
+dependencies = [
+ "async-trait",
+ "serde",
+ "serde_json",
+ "thiserror",
+ "tokio",
+]
+
+[[package]]
+name = "io-uring"
+version = "0.7.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b86e202f00093dcba4275d4636b93ef9dd75d025ae560d2521b45ea28ab49013"
+dependencies = [
+ "bitflags",
+ "cfg-if",
+ "libc",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
+
+[[package]]
+name = "libc"
+version = "0.2.174"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1171693293099992e19cddea4e8b849964e9846f4acee11b3948bcc337be8776"
+
+[[package]]
+name = "lock_api"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765"
+dependencies = [
+ "autocfg",
+ "scopeguard",
+]
+
+[[package]]
+name = "memchr"
+version = "2.7.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+]
+
+[[package]]
+name = "mio"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78bed444cc8a2160f01cbcf811ef18cac863ad68ae8ca62092e8db51d51c761c"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "object"
+version = "0.36.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
+dependencies = [
+ "memchr",
+]
+
 [[package]]
 name = "pageos-greet"
-version = "0.1.3"
+version = "0.2.0"
+dependencies = [
+ "greetd_ipc",
+ "rpassword",
+ "serde",
+ "serde_json",
+ "tokio",
+]
+
+[[package]]
+name = "parking_lot"
+version = "0.12.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-targets",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.95"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d04b7d0ee6b4a0207a0a7adb104d23ecb0b47d6beae7152d0fa34b692b29fd6"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "rpassword"
+version = "7.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66d4c8b64f049c6721ec8ccec37ddfc3d641c4a7fca57e8f2a89de509c73df39"
+dependencies = [
+ "libc",
+ "rtoolbox",
+ "windows-sys 0.59.0",
+]
+
+[[package]]
+name = "rtoolbox"
+version = "0.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7cc970b249fbe527d6e02e0a227762c9108b2f49d81094fe357ffc6d14d7f6f"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "rustc-demangle"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "989e6739f80c4ad5b13e0fd7fe89531180375b18520cc8c82080e4dc4035b84f"
+
+[[package]]
+name = "ryu"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
+version = "1.0.219"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.219"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.140"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
+dependencies = [
+ "itoa",
+ "memchr",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "signal-hook-registry"
+version = "1.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9203b8055f63a2a00e2f593bb0510367fe707d7ff1e5c872de2f537b339e5410"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "slab"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04dc19736151f35336d325007ac991178d504a119863a2fcb3758cdb5e52c50d"
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "socket2"
+version = "0.5.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
+dependencies = [
+ "libc",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17b6f705963418cdb9927482fa304bc562ece2fdd4f616084c50b7023b435a40"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio"
+version = "1.46.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cc3a2344dafbe23a245241fe8b09735b521110d30fcefbbd5feb1797ca35d17"
+dependencies = [
+ "backtrace",
+ "bytes",
+ "io-uring",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "slab",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.52.0",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "windows-sys"
+version = "0.52.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
+dependencies = [
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.52.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"

+ 11 - 1
Cargo.toml

@@ -1,8 +1,18 @@
 [package]
 name = "pageos-greet"
-version = "0.1.3"
+version = "0.2.0"
 authors = ["PJ568 <[email protected]>"]
 edition = "2024"
 license = "MPL-2.0"
+description = "Rust 语言编写的登录界面服务器。包含一个最小网页服务器和内置的登录页面。"
+repository = "https://github.com/swaybien/pageos-greet"
+homepage = "https://github.com/swaybien/pageos-greet"
+keywords = ["greetd", "login", "web-server", "authentication"]
+categories = ["web-programming", "authentication"]
 
 [dependencies]
+tokio = { version = "1.37", features = ["full"] }
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+greetd_ipc = { version = "0.10", features = ["tokio-codec"] }
+rpassword = "7.4"

+ 2 - 0
README.md

@@ -2,6 +2,8 @@
 
 Rust 语言编写的登录界面服务器。包含一个最小网页服务器和内置的登录页面。
 
+本项目是 [pageos](https://github.com/swaybien/pageos) 项目的一个子项目。
+
 核心思想:
 
 - 尽量依赖现有软件,保持本项目为最小实现。

+ 128 - 5
doc/design.md

@@ -1,8 +1,131 @@
-# pageos-greet 设计文档
+# 终端 Greeter 实现设计
 
-## 1. 需求分析
+## 1. 状态机流程图
 
-- 实现符合 greetd-ipc(7) 协议的独立 greeter
-- 最小化依赖原则
+```mermaid
+stateDiagram-v2
+    [*] --> 建立连接
+    建立连接 --> 创建会话 : 发送CreateSession
+    创建会话 --> 认证处理 : 收到AuthMessage
+    认证处理 --> 认证处理 : 多轮认证交互
+    创建会话 --> 启动会话准备 : 收到Success
+    创建会话 --> 错误处理 : 收到Error
+    认证处理 --> 启动会话准备 : 收到Success
+    认证处理 --> 错误处理 : 收到Error
+    启动会话准备 --> 启动会话 : 发送StartSession
+    错误处理 --> 创建会话 : 发送CancelSession后重试
+    启动会话 --> [*]
+```
 
-## 2. 协议适配方案
+## 2. 核心数据结构
+
+### IPC 消息枚举
+
+```rust
+#[derive(Serialize, Deserialize)]
+#[serde(tag = "type")]
+enum IpcMessage {
+    CreateSession { username: String },
+    AuthMessage {
+        auth_message_type: AuthType,
+        auth_message: String
+    },
+    PostAuthMessageResponse { response: String },
+    StartSession { cmd: Vec<String>, env: Vec<String> },
+    CancelSession,
+    Success,
+    Error { description: String }
+}
+```
+
+### Greeter 状态控制
+
+```rust
+struct GreeterState {
+    retry_count: u8,
+    username: String,
+    starting_session: bool, // 会话启动标志
+}
+
+// 状态通过控制流实现
+```
+
+## 3. 终端交互逻辑
+
+### 主控制循环
+
+```rust
+fn main_loop() -> Result<()> {
+    let mut state = GreeterState::new();
+
+    while !state.is_terminal() {
+        match current_phase {
+            Phase::Initial => connect_to_greetd(),
+            Phase::SessionCreation => send_create_session(),
+            Phase::Authentication => handle_auth_message(),
+            Phase::SessionStart => send_start_session(),
+            Phase::Error => handle_error_retry(),
+        }
+    }
+    Ok(())
+}
+```
+
+## 4. 错误处理策略
+
+### 统一错误处理
+
+```rust
+fn handle_error(state: &mut GreeterState, error: &io::Error) {
+    match error.kind() {
+        io::ErrorKind::PermissionDenied => {
+            // 认证错误立即重试
+            state.retry_count += 1;
+        }
+        io::ErrorKind::ConnectionRefused => {
+            // 连接错误使用指数退避
+            let delay = RETRY_DELAY * 2u64.pow(state.retry_count as u32);
+            sleep(Duration::from_secs(delay));
+            state.retry_count += 1;
+        }
+        _ => {
+            // 其他错误终止会话
+            state.terminal = true;
+        }
+    }
+}
+```
+
+## 5. 新增功能说明
+
+### 指数退避重试机制
+
+```rust
+// 网络错误重试策略
+for retry in 0..MAX_RETRIES {
+    match connect() {
+        Ok(stream) => break,
+        Err(_) => {
+            let delay = RETRY_DELAY * 2u64.pow(retry as u32);
+            sleep(Duration::from_secs(delay));
+        }
+    }
+}
+```
+
+### 环境变量过滤
+
+```rust
+// 安全环境变量白名单
+let safe_env = vec!["LANG", "PATH", "DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY"];
+let env: Vec<String> = env::vars()
+    .filter(|(k, _)| safe_env.contains(&k.as_str()))
+    .map(|(k, v)| format!("{k}={v}"))
+    .collect();
+```
+
+## 6. 会话启动优化
+
+- 使用 `starting_session` 标志替代 `ReadyToStart` 状态
+- 环境变量自动继承当前会话安全值
+- VT 号码自动检测(通过 `XDG_VTNR`)

+ 188 - 2
src/main.rs

@@ -2,6 +2,192 @@
 // 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/.
 
-fn main() {
-    println!("Hello, world!");
+use greetd_ipc::{AuthMessageType, ErrorType, Request, Response, codec::TokioCodec};
+use rpassword::prompt_password;
+use std::env;
+use std::io::{self, Write};
+use std::process;
+use std::time::Duration;
+use tokio::net::UnixStream;
+
+const MAX_RETRIES: u8 = 3;
+const RETRY_DELAY: u64 = 2;
+
+struct GreeterState {
+    retry_count: u8,
+    username: String,
+    stream: Option<UnixStream>,
+}
+
+impl GreeterState {
+    fn new() -> Self {
+        Self {
+            retry_count: 0,
+            username: String::new(),
+            stream: None,
+        }
+    }
+}
+
+#[tokio::main]
+async fn main() -> io::Result<()> {
+    let mut state = GreeterState::new();
+    state.username = prompt_input("用户名:")?;
+
+    loop {
+        match try_login_flow(&mut state).await {
+            Ok(()) => break,
+            Err(e) => {
+                handle_error(&mut state, &e);
+
+                if state.retry_count >= MAX_RETRIES {
+                    eprintln!("超过最大重试次数");
+                    process::exit(1);
+                }
+
+                // 根据错误类型决定重试策略
+                if !should_retry_immediately(&e) {
+                    let delay =
+                        Duration::from_secs(RETRY_DELAY * 2u64.pow(state.retry_count as u32));
+                    eprintln!("等待 {:?} 后重试...", delay);
+                    tokio::time::sleep(delay).await;
+                }
+            }
+        }
+    }
+    Ok(())
+}
+
+async fn try_login_flow(state: &mut GreeterState) -> io::Result<()> {
+    let stream = connect_to_greetd().await?;
+    state.stream = Some(stream);
+    state.retry_count = 0;
+
+    let mut request = Request::CreateSession {
+        username: state.username.clone(),
+    };
+    let mut starting_session = false;
+
+    loop {
+        let stream = state.stream.as_mut().unwrap();
+        request
+            .write_to(stream)
+            .await
+            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
+
+        match Response::read_from(stream)
+            .await
+            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?
+        {
+            Response::AuthMessage {
+                auth_message_type,
+                auth_message,
+            } => {
+                let response = match auth_message_type {
+                    AuthMessageType::Visible => Some(prompt_input(&auth_message)?),
+                    AuthMessageType::Secret => {
+                        let password = prompt_password(&auth_message)
+                            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
+                        Some(password)
+                    }
+                    AuthMessageType::Info => {
+                        eprintln!("信息: {}", auth_message);
+                        None
+                    }
+                    AuthMessageType::Error => {
+                        eprintln!("错误: {}", auth_message);
+                        None
+                    }
+                };
+
+                request = Request::PostAuthMessageResponse { response };
+            }
+            Response::Success => {
+                if starting_session {
+                    return Ok(());
+                }
+
+                starting_session = true;
+                let cmd = env::var("SHELL")
+                    .map(|s| vec![s])
+                    .unwrap_or_else(|_| vec!["/bin/bash".to_string()]);
+
+                // 安全的环境变量白名单
+                let safe_env = vec!["LANG", "PATH", "DISPLAY", "XAUTHORITY", "WAYLAND_DISPLAY"];
+                let env: Vec<String> = env::vars()
+                    .filter(|(k, _)| safe_env.contains(&k.as_str()))
+                    .map(|(k, v)| format!("{k}={v}"))
+                    .collect();
+
+                request = Request::StartSession { cmd, env };
+            }
+            Response::Error {
+                error_type,
+                description,
+            } => {
+                match error_type {
+                    ErrorType::AuthError => {
+                        // 认证错误时取消会话
+                        Request::CancelSession
+                            .write_to(stream)
+                            .await
+                            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
+                        return Err(io::Error::new(io::ErrorKind::PermissionDenied, description));
+                    }
+                    ErrorType::Error => {
+                        Request::CancelSession
+                            .write_to(stream)
+                            .await
+                            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
+                        return Err(io::Error::new(io::ErrorKind::Other, description));
+                    }
+                }
+            }
+        }
+    }
+}
+
+async fn connect_to_greetd() -> io::Result<UnixStream> {
+    let sock_path = env::var("GREETD_SOCK")
+        .map_err(|_| io::Error::new(io::ErrorKind::NotFound, "GREETD_SOCK环境变量未设置"))?;
+
+    for retry in 0..MAX_RETRIES {
+        match UnixStream::connect(&sock_path).await {
+            Ok(stream) => return Ok(stream),
+            Err(_e) if retry < MAX_RETRIES - 1 => {
+                eprintln!("连接失败,重试中... ({}/{})", retry + 1, MAX_RETRIES);
+                tokio::time::sleep(Duration::from_secs(RETRY_DELAY)).await;
+            }
+            Err(e) => {
+                return Err(io::Error::new(
+                    io::ErrorKind::ConnectionRefused,
+                    format!("连接greetd服务失败: {} (sock={})", e, sock_path),
+                ));
+            }
+        }
+    }
+    unreachable!()
+}
+
+fn prompt_input(prompt: &str) -> io::Result<String> {
+    print!("{}", prompt);
+    io::stdout().flush()?;
+    let mut input = String::new();
+    io::stdin().read_line(&mut input)?;
+    Ok(input.trim().to_string())
+}
+
+fn handle_error(state: &mut GreeterState, error: &io::Error) {
+    eprintln!("错误: {}", error);
+    state.retry_count += 1;
+    state.stream = None;
+}
+
+// 错误分类处理
+fn should_retry_immediately(error: &io::Error) -> bool {
+    match error.kind() {
+        io::ErrorKind::PermissionDenied => true, // 认证错误
+        io::ErrorKind::InvalidData => true,      // 无效凭据
+        _ => false,                              // 连接或其他错误
+    }
 }