Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New terminal #1297

Closed
wants to merge 17 commits into from
Closed
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 16 additions & 3 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions rust/agama-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,14 @@ chrono = { version = "0.4.34", default-features = false, features = [
"clock",
] }
pam = "0.8.0"
pty-process = { version = "0.4.0", features = ["async"] }
serde_with = "3.6.1"
pin-project = "1.1.5"
openssl = "0.10.64"
hyper = "1.2.0"
hyper-util = "0.1.3"
tokio-openssl = "0.6.4"
tokio-util = "0.7.11"
futures-util = { version = "0.3.30", default-features = false, features = [
"alloc",
] }
Expand Down
1 change: 1 addition & 0 deletions rust/agama-server/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ mod http;
mod service;
mod state;
mod ws;
mod terminal_ws;

use agama_lib::{connection, error::ServiceError};
pub use auth::generate_token;
Expand Down
4 changes: 3 additions & 1 deletion rust/agama-server/src/web/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ impl MainServiceBuilder {
where
P: AsRef<Path>,
{
let api_router = Router::new().route("/ws", get(super::ws::ws_handler));
let api_router = Router::new()
.route("/ws", get(super::ws::ws_handler))
.route("/terminal", get(super::terminal_ws::handler));
let config = ServiceConfig::default();

Self {
Expand Down
87 changes: 87 additions & 0 deletions rust/agama-server/src/web/terminal_ws.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
use std::borrow::Cow;
use axum::{extract::{ws::{close_code, CloseFrame, Message, WebSocket}, WebSocketUpgrade}, response::IntoResponse};
use pty_process::{OwnedReadPty, OwnedWritePty};
use tokio::io::AsyncWriteExt;
use tokio_stream::StreamExt;

pub(crate) async fn handler(
ws: WebSocketUpgrade,
) -> impl IntoResponse {
ws.on_upgrade(move |socket| handle_socket(socket))
}

fn start_shell() -> Result<(OwnedReadPty, OwnedWritePty, tokio::process::Child), pty_process::Error> {
let pty = pty_process::Pty::new()?;
pty.resize(pty_process::Size::new(24, 80))?;
let mut cmd = pty_process::Command::new("bash");
// TODO: check if children exit
let child = cmd.spawn(&pty.pts()?)?;
let (pty_out, pty_in) = pty.into_split();
Ok((pty_out, pty_in, child))
}

async fn handle_socket(mut socket: WebSocket) {
log::info!("Terminal connected");

// TODO: handle failed start of shell
let (pty_out, mut pty_in, mut child) = start_shell().unwrap();
let mut reader_stream = tokio_util::io::ReaderStream::new(pty_out);

loop {
tokio::select! {
message = socket.recv() => {
match message {
Some(Ok(Message::Text(s))) => {
let res = pty_in.write_all(s.as_bytes()).await;
if res.is_err() {
log::warn!("Failed to write to pty: {:?}", res);
}

continue;
},
Some(Ok(Message::Close(_))) => {
log::info!("websocket close {:?}", message);
break;
},
None => {
log::info!("Socket closed");
break;
}
_ => {
log::info!("websocket other {:?}", message);
continue
},
}
},
shell_output = reader_stream.next() => {
println!("shell output {:?}", shell_output);
if let Some(some_output) = shell_output {
match some_output {
Ok(output_bytes) => socket.send(Message::Binary(output_bytes.into())).await.unwrap(),
Err(e) => log::warn!("Shell error {}", e),
}

}
},
status = child.wait() => {
match status {
Err(err) => log::warn!("Child status error: {}", err),
Ok(status) => {
let code = status.code().unwrap_or(0);
let msg = format!("Bash exited with code: {code}");
let res = socket.send(Message::Close(Some(CloseFrame {
code: close_code::NORMAL,
reason: Cow::from(msg),
}))).await;
if res.is_err() {
log::warn!("Failed to send close message: {:?}", res);
}
break;
}
}
}
}
}

log::info!("Terminal disconnected.");
}
Loading
Loading