pub mod actions;
use crate::llm::action_helper::call_llm;
use crate::llm::ollama_client::OllamaClient;
use crate::logging::emit::Log;
use crate::protocol::Event;
use crate::server::connection::ConnectionId;
use crate::state::app_state::AppState;
use crate::utils::WireFailure;
use actions::{FingerQuery, FINGER_QUERY_EVENT, MAX_QUERY_BYTES};
use anyhow::Result;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
use tokio::sync::{mpsc, Mutex};
const FORWARD_DENIED: &[u8] = b"Finger forwarding service denied.\r\n";
const QUERY_TOO_LONG: &[u8] = b"finger: query too long\r\n";
const NO_INFORMATION: &[u8] = b"finger: no information available\r\n";
const QUERY_READ_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_CONNECTIONS: usize = crate::server::accept_bounded::DEFAULT_MAX_CONNECTIONS;
const CONNECTION_CAP_REFUSAL: &[u8] = b"finger: too many connections, try again later\r\n";
pub struct FingerServer;
impl FingerServer {
pub async fn spawn_with_llm_actions(
listen_addr: SocketAddr,
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
server_id: crate::state::ServerId,
answer_forward_queries: bool,
) -> Result<SocketAddr> {
let listener = TcpListener::bind(listen_addr).await?;
let local_addr = listener.local_addr()?;
let log = Log::new(Some(&status_tx));
log.info(format!("FINGER server listening on {}", local_addr));
if answer_forward_queries {
log.warn(
"FINGER answer_forward_queries=true: user@host queries will be answered locally \
with invented information. Nothing is proxied to the named host.",
);
} else {
log.debug(
"FINGER forwarding refused (RFC 1288 3.2.1); set answer_forward_queries=true to \
answer user@host locally instead",
);
}
let protocol = Arc::new(actions::FingerProtocol::new());
let task_registrar = app_state.clone();
let limiter = crate::server::accept_bounded::ConnectionLimiter::new(MAX_CONNECTIONS);
let accept_handle = tokio::spawn(async move {
loop {
match crate::server::accept_bounded::accept_bounded(
&listener,
&limiter,
CONNECTION_CAP_REFUSAL,
"FINGER",
Some(&status_tx),
)
.await
{
Ok((socket, peer_addr, permit)) => {
let connection_id =
ConnectionId::new(app_state.get_next_unified_id().await);
use crate::state::server::{
ConnectionState as ServerConnectionState, ConnectionStatus,
ProtocolConnectionInfo,
};
let now = crate::utils::clock::Instant::now();
let conn_state = ServerConnectionState {
id: connection_id,
remote_addr: peer_addr,
local_addr,
bytes_sent: 0,
bytes_received: 0,
packets_sent: 0,
packets_received: 0,
last_activity: now,
status: ConnectionStatus::Active,
status_changed_at: now,
protocol_info: ProtocolConnectionInfo::empty(),
};
app_state
.add_connection_to_server(server_id, conn_state)
.await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
Log::new(Some(&status_tx))
.info(format!("FINGER client connected from {}", peer_addr));
let llm_clone = llm_client.clone();
let state_clone = app_state.clone();
let status_clone = status_tx.clone();
let protocol_clone = protocol.clone();
let registrar = app_state.clone();
let conn_handle = tokio::spawn(async move {
let _permit = permit;
handle_finger_connection(
socket,
peer_addr,
llm_clone,
state_clone,
status_clone,
server_id,
protocol_clone,
connection_id,
answer_forward_queries,
)
.await
});
registrar.register_server_task(server_id, conn_handle).await;
}
Err(e) => {
Log::new(Some(&status_tx)).error(format!("FINGER accept error: {}", e));
break;
}
}
}
});
task_registrar
.register_server_task(server_id, accept_handle)
.await;
Ok(local_addr)
}
}
async fn write_counted<W>(
write_half: &Arc<Mutex<W>>,
data: &[u8],
app_state: &AppState,
server_id: crate::state::ServerId,
connection_id: ConnectionId,
) -> std::io::Result<()>
where
W: tokio::io::AsyncWrite + Unpin,
{
{
let mut writer = write_half.lock().await;
writer.write_all(data).await?;
writer.flush().await?;
}
app_state
.update_connection_stats(
server_id,
connection_id,
None,
Some(data.len() as u64),
None,
Some(1),
)
.await;
Ok(())
}
#[allow(clippy::too_many_arguments)]
async fn handle_finger_connection(
socket: tokio::net::TcpStream,
peer_addr: SocketAddr,
llm_client: OllamaClient,
app_state: Arc<AppState>,
status_tx: mpsc::UnboundedSender<String>,
server_id: crate::state::ServerId,
protocol: Arc<actions::FingerProtocol>,
connection_id: ConnectionId,
answer_forward_queries: bool,
) {
let (reader, write_half) = tokio::io::split(socket);
let write_half = Arc::new(Mutex::new(write_half));
let peer_rx = crate::server::peer_support::register_peer_channel(
&app_state,
server_id,
connection_id.as_u32(),
)
.await;
crate::server::peer_support::spawn_peer_command_task(
peer_rx,
protocol.clone(),
app_state.clone(),
server_id,
connection_id.as_u32(),
write_half.clone(),
status_tx.clone(),
);
run_finger_session(
reader,
&write_half,
peer_addr,
&llm_client,
&app_state,
&status_tx,
server_id,
&protocol,
connection_id,
answer_forward_queries,
)
.await;
app_state
.remove_peer_handle(server_id, connection_id.as_u32())
.await;
let _ = write_half.lock().await.shutdown().await;
use crate::state::server::ConnectionStatus;
app_state
.update_connection_status(server_id, connection_id, ConnectionStatus::Closed)
.await;
let _ = status_tx.send("__UPDATE_UI__".to_string());
}
enum QueryRead {
Line(String, usize),
Eof,
TooLong,
TimedOut,
Failed(std::io::Error),
}
async fn read_query_line<R>(reader: &mut R) -> QueryRead
where
R: tokio::io::AsyncRead + Unpin,
{
let mut accumulated: Vec<u8> = Vec::with_capacity(64);
let mut chunk = [0u8; 256];
loop {
let read = match tokio::time::timeout(QUERY_READ_TIMEOUT, reader.read(&mut chunk)).await {
Err(_) => return QueryRead::TimedOut,
Ok(read) => read,
};
match read {
Ok(0) => {
return if accumulated.is_empty() {
QueryRead::Eof
} else {
let n = accumulated.len();
QueryRead::Line(
String::from_utf8_lossy(&accumulated).trim_end().to_string(),
n,
)
};
}
Ok(n) => {
accumulated.extend_from_slice(&chunk[..n]);
if let Some(idx) = accumulated.iter().position(|b| *b == b'\n') {
let consumed = accumulated.len();
let line = String::from_utf8_lossy(&accumulated[..idx])
.trim_end_matches('\r')
.to_string();
return QueryRead::Line(line, consumed);
}
if accumulated.len() > MAX_QUERY_BYTES {
return QueryRead::TooLong;
}
}
Err(e) => return QueryRead::Failed(e),
}
}
}
#[allow(clippy::too_many_arguments)]
async fn run_finger_session<R, W>(
mut reader: R,
write_half: &Arc<Mutex<W>>,
peer_addr: SocketAddr,
llm_client: &OllamaClient,
app_state: &Arc<AppState>,
status_tx: &mpsc::UnboundedSender<String>,
server_id: crate::state::ServerId,
protocol: &Arc<actions::FingerProtocol>,
connection_id: ConnectionId,
answer_forward_queries: bool,
) where
R: tokio::io::AsyncRead + Unpin,
W: tokio::io::AsyncWrite + Unpin,
{
let log = Log::new(Some(status_tx));
let (line, consumed) = match read_query_line(&mut reader).await {
QueryRead::Line(line, consumed) => (line, consumed),
QueryRead::Eof => {
log.info(format!(
"FINGER client {} disconnected without sending a query",
peer_addr
));
return;
}
QueryRead::TooLong => {
log.warn(format!(
"FINGER query from {} exceeded {} bytes with no terminator; refusing",
peer_addr, MAX_QUERY_BYTES
));
let _ = write_counted(
write_half,
QUERY_TOO_LONG,
app_state,
server_id,
connection_id,
)
.await;
return;
}
QueryRead::TimedOut => {
log.info(format!(
"FINGER client {} sent no query within {}s; closing",
peer_addr,
QUERY_READ_TIMEOUT.as_secs()
));
return;
}
QueryRead::Failed(e) => {
log.error(format!("FINGER read error from {}: {}", peer_addr, e));
return;
}
};
app_state
.update_connection_stats(
server_id,
connection_id,
Some(consumed as u64),
None,
Some(1),
None,
)
.await;
log.debug(format!(
"FINGER received {} bytes from {}",
consumed, peer_addr
));
log.trace(format!("FINGER query line: {}", line));
let query = FingerQuery::parse(&line);
if let Some(host) = query.forward_host.as_deref() {
if !answer_forward_queries {
log.warn(format!(
"FINGER decision=forward_refused peer={} user={:?} forward_host={}",
peer_addr, query.username, host
));
let _ = write_counted(
write_half,
FORWARD_DENIED,
app_state,
server_id,
connection_id,
)
.await;
return;
}
log.warn(format!(
"FINGER decision=forward_answered_locally peer={} user={:?} forward_host={} \
(nothing is contacted; the model invents the answer)",
peer_addr, query.username, host
));
}
let event = Event::new(&FINGER_QUERY_EVENT, query.to_event_data());
log.debug(format!("FINGER calling LLM for query from {}", peer_addr));
match call_llm(
llm_client,
app_state,
server_id,
Some(connection_id),
&event,
protocol.as_ref(),
)
.await
{
Ok(execution_result) => {
for message in &execution_result.messages {
log.info(message);
}
let mut wrote_output = false;
for protocol_result in execution_result.protocol_results {
match protocol_result {
crate::llm::actions::protocol_trait::ActionResult::Output(output_data) => {
if let Err(e) = write_counted(
write_half,
&output_data,
app_state,
server_id,
connection_id,
)
.await
{
log.error(format!("FINGER write error: {}", e));
return;
}
wrote_output = true;
log.debug(format!(
"FINGER sent {} bytes to {}",
output_data.len(),
peer_addr
));
log.trace(format!(
"FINGER response: {}",
String::from_utf8_lossy(&output_data)
));
log.info(format!(
"FINGER response to {} ({} bytes)",
peer_addr,
output_data.len()
));
}
crate::llm::actions::protocol_trait::ActionResult::CloseConnection => {
log.debug("FINGER closing connection per LLM request");
break;
}
_ => {}
}
}
if !wrote_output {
log.warn(format!(
"FINGER produced no response for {} ({} failed action(s)); answering with a \
notice instead of closing silently",
peer_addr,
execution_result.failures.len()
));
let _ = write_counted(
write_half,
NO_INFORMATION,
app_state,
server_id,
connection_id,
)
.await;
}
}
Err(e) => {
log.warn(format!("FINGER LLM call failed for {}: {}", peer_addr, e));
let notice: &[u8] = match WireFailure::classify(&e) {
WireFailure::Overloaded => b"finger: backend at capacity, retry later\r\n",
WireFailure::Unavailable => b"finger: request could not be processed\r\n",
};
let _ = write_counted(write_half, notice, app_state, server_id, connection_id).await;
}
}
}