cosmic-greeter/examples/server.rs

82 lines
3.4 KiB
Rust
Raw Normal View History

use greetd_ipc::{AuthMessageType, ErrorType, Request, Response, codec::TokioCodec};
2024-05-07 09:03:44 -06:00
use std::{env, fs, io, thread};
2023-10-02 14:38:00 -06:00
use tokio::net::UnixListener;
2025-11-12 16:24:05 +01:00
fn main() {
2024-05-07 09:03:44 -06:00
let greetd_sock = env::current_dir().unwrap().join("socket");
if greetd_sock.exists() {
fs::remove_file(&greetd_sock).unwrap();
}
2025-11-12 16:24:05 +01:00
// Set up the socket environment variable before spawning greeter
unsafe { env::set_var("GREETD_SOCK", &greetd_sock) };
2023-10-02 14:38:00 -06:00
2025-11-12 16:24:05 +01:00
// Spawn the mock greetd server in a background thread
thread::spawn(move || {
let rt = tokio::runtime::Runtime::new().unwrap();
rt.block_on(async {
let listener = UnixListener::bind(&greetd_sock).unwrap();
println!("listening at {:?}", greetd_sock);
loop {
let (socket, _addr) = listener.accept().await.unwrap();
println!("new connection");
2023-10-02 14:38:00 -06:00
2025-11-12 16:24:05 +01:00
loop {
let request = {
socket.readable().await.unwrap();
2023-10-02 14:38:00 -06:00
2025-11-12 16:24:05 +01:00
let mut bytes = Vec::with_capacity(4096);
match socket.try_read_buf(&mut bytes) {
Ok(0) => break,
Ok(count) => {
println!("read {} bytes", count);
}
Err(err) => match err.kind() {
io::ErrorKind::WouldBlock => continue,
_ => {
println!("failed to read socket: {:?}", err);
break;
}
},
2023-10-02 14:38:00 -06:00
}
2025-11-12 16:24:05 +01:00
let mut cursor = io::Cursor::new(bytes);
Request::read_from(&mut cursor).await.unwrap()
};
println!("{:?}", request);
2023-10-02 14:38:00 -06:00
2025-11-12 16:24:05 +01:00
let response = match request {
Request::CreateSession { .. } => Response::AuthMessage {
auth_message_type: AuthMessageType::Secret,
auth_message: "MOCKING:".to_string(),
},
2025-11-12 20:26:29 +01:00
Request::PostAuthMessageResponse { response } => {
match response.as_deref() {
Some("password") => Response::Success,
_ => {
// Add 1 second delay to simulate real PAM authentication failure behavior
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
Response::Error {
error_type: ErrorType::AuthError,
description: "AUTH_ERR".to_string(),
}
}
2025-11-12 20:26:29 +01:00
}
}
2025-11-12 16:24:05 +01:00
Request::StartSession { .. } => Response::Success,
Request::CancelSession => Response::Success,
};
2023-10-02 14:38:00 -06:00
2025-11-12 16:24:05 +01:00
let mut bytes = Vec::with_capacity(4096);
response.write_to(&mut bytes).await.unwrap();
socket.try_write(&bytes).unwrap();
}
}
});
});
// Run greeter on main thread (required for winit event loop)
cosmic_greeter::greeter::main().unwrap();
2023-10-02 14:38:00 -06:00
}