diff --git a/src/server/controlchan/commands/site.rs b/src/server/controlchan/commands/site.rs index 9de0c233..e238896f 100644 --- a/src/server/controlchan/commands/site.rs +++ b/src/server/controlchan/commands/site.rs @@ -28,17 +28,17 @@ impl Site { Storage: StorageBackend + 'static, Storage::Metadata: Metadata, { - let (username, storage, user) = { - let session = context.session.lock().await; - (session.username.clone(), session.storage.clone(), session.user.clone()) - }; + let session = context.session.lock().await; SiteCommandContext { command: self.command.clone(), arguments: self.arguments.clone(), - username, - storage, - user, + username: session.username.clone(), + storage: session.storage.clone(), + user: session.user.clone(), logger: context.logger.clone(), + cwd: session.cwd.clone(), + source_ip: session.control_connection.map_or(session.source, |pair| pair.source).ip(), + trace_id: session.trace_id.to_string(), } } } diff --git a/src/server/ftpserver.rs b/src/server/ftpserver.rs index 94390388..a62ce950 100644 --- a/src/server/ftpserver.rs +++ b/src/server/ftpserver.rs @@ -779,7 +779,7 @@ where /// /// Clients send `SITE [arguments]` and the server will call `handler.handle()` with a /// [`SiteCommandContext`](options::SiteCommandContext) containing the arguments, the current - /// username, and access to the storage back-end. The `name` is case-insensitive; it is + /// username and working directory, and access to the storage back-end. The `name` is case-insensitive; it is /// normalised to uppercase internally. /// /// Names must contain only ASCII letters, digits, `-`, or `_`. Subcommands cannot be diff --git a/src/server/ftpserver/options.rs b/src/server/ftpserver/options.rs index 06b9d39d..e00bc532 100644 --- a/src/server/ftpserver/options.rs +++ b/src/server/ftpserver/options.rs @@ -6,6 +6,7 @@ use crate::storage::{Metadata, StorageBackend}; use async_trait::async_trait; use bitflags::bitflags; use std::ops::RangeInclusive; +use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; use std::{ @@ -178,6 +179,11 @@ pub enum SiteMd5 { /// Context passed to a custom [`SiteCommandHandler`]. Custom SITE commands are dispatched only /// after the client has authenticated successfully. +/// +/// The context is a snapshot of the session taken when the command is dispatched. It is +/// `#[non_exhaustive]` so that fields can be added without breaking handlers; outside libunftp, +/// build one with [`SiteCommandContext::new`]. +#[non_exhaustive] pub struct SiteCommandContext where Storage: StorageBackend + 'static, @@ -197,6 +203,64 @@ where pub user: Arc>, /// The logger associated with the session. pub logger: slog::Logger, + /// The session's current working directory, as set by `CWD` and `CDUP`. Resolve relative paths + /// in [`arguments`](Self::arguments) against it, as the built-in commands do. + pub cwd: PathBuf, + /// The IP address of the client. In proxy protocol mode this is the client's address as + /// reported by the proxy, not the proxy's own address. + pub source_ip: IpAddr, + /// Identifies the session in log statements and in + /// [`EventMeta::trace_id`](crate::notification::EventMeta::trace_id). + pub trace_id: String, +} + +impl SiteCommandContext +where + Storage: StorageBackend + 'static, + Storage::Metadata: Metadata, + User: UserDetail + 'static, +{ + /// Creates a context, for example to unit test a [`SiteCommandHandler`]. + /// + /// The remaining fields describe a session with no authenticated user, a working directory of + /// `/`, an unspecified source IP address and an empty trace ID. Assign them directly to describe + /// a different session. + /// + /// # Parameters + /// + /// - `command`: the SITE subcommand name; it is normalised to uppercase. + /// - `arguments`: the text following the subcommand name. + /// - `storage`: the storage back-end the handler should use. + /// - `logger`: the logger the handler should use. + /// + /// # Example + /// + /// ```rust + /// use libunftp::options::SiteCommandContext; + /// use std::sync::Arc; + /// use unftp_core::auth::DefaultUser; + /// use unftp_sbe_fs::Filesystem; + /// + /// let storage = Arc::new(Filesystem::new(std::env::temp_dir()).unwrap()); + /// let logger = slog::Logger::root(slog::Discard, slog::o!()); + /// let mut ctx = SiteCommandContext::::new("send", "file.txt", storage, logger); + /// ctx.username = Some("alice".to_string()); + /// ctx.cwd = "/orders".into(); + /// assert_eq!(ctx.command, "SEND"); + /// ``` + pub fn new(command: impl Into, arguments: impl Into, storage: Arc, logger: slog::Logger) -> Self { + SiteCommandContext { + command: command.into().to_ascii_uppercase(), + arguments: arguments.into(), + username: None, + storage, + user: Arc::new(None), + logger, + cwd: PathBuf::from("/"), + source_ip: IpAddr::V4(Ipv4Addr::UNSPECIFIED), + trace_id: String::new(), + } + } } impl std::fmt::Debug for SiteCommandContext @@ -210,6 +274,9 @@ where .field("command", &self.command) .field("arguments", &self.arguments) .field("username", &self.username) + .field("cwd", &self.cwd) + .field("source_ip", &self.source_ip) + .field("trace_id", &self.trace_id) .finish_non_exhaustive() } } diff --git a/tests/site.rs b/tests/site.rs index ab0eaafd..35194fef 100644 --- a/tests/site.rs +++ b/tests/site.rs @@ -17,6 +17,7 @@ use unftp_sbe_fs::Filesystem; use common::{read_from_server, send_to_server}; const ADDR: &str = "127.0.0.1:2155"; +const SITE_CWD_DIR: &str = "libunftp-site-cwd-test"; lazy_static! { static ref CONSUMERS: Arc> = Arc::new(Mutex::new(0)); @@ -52,13 +53,46 @@ where } } +#[derive(Debug)] +struct WhereAmIHandler; + +#[async_trait] +impl SiteCommandHandler for WhereAmIHandler +where + Storage: StorageBackend + 'static, + Storage::Metadata: Metadata, + User: UserDetail + 'static, +{ + async fn handle(&self, ctx: &SiteCommandContext) -> Reply { + Reply::new(ReplyCode::CommandOkay, &ctx.cwd.to_string_lossy()) + } +} + +#[derive(Debug)] +struct ConnectionHandler; + +#[async_trait] +impl SiteCommandHandler for ConnectionHandler +where + Storage: StorageBackend + 'static, + Storage::Metadata: Metadata, + User: UserDetail + 'static, +{ + async fn handle(&self, ctx: &SiteCommandContext) -> Reply { + Reply::new(ReplyCode::CommandOkay, &format!("{} {}", ctx.source_ip, ctx.trace_id)) + } +} + async fn run_with_site_handlers() { let root = std::env::temp_dir(); + std::fs::create_dir_all(root.join(SITE_CWD_DIR)).unwrap(); let server = ServerBuilder::new(Box::new(move || Filesystem::new(root.clone()).unwrap())) .authenticator(Arc::new(TestAuthenticator {})) .greeting("Welcome test") .site_command("ECHO", EchoHandler) .site_command("WHOAMI", WhoAmIHandler) + .site_command("WHEREAMI", WhereAmIHandler) + .site_command("CONNECTION", ConnectionHandler) .build() .unwrap(); server.listen(ADDR).await.unwrap(); @@ -158,6 +192,51 @@ async fn test_custom_site_command_receives_session_context() { finalize().await; } +#[tokio::test(flavor = "current_thread")] +async fn test_custom_site_command_receives_cwd() { + initialize().await; + + let stream = tcp_connect().await.unwrap(); + let mut buffer = vec![0_u8; 1024]; + login(&stream, &mut buffer).await; + + send_to_server("SITE WHEREAMI\r\n", &stream).await; + assert_eq!(read_from_server(&mut buffer, &stream).await, "200 /\r\n"); + + send_to_server(&format!("CWD {SITE_CWD_DIR}\r\n"), &stream).await; + assert_eq!(read_from_server(&mut buffer, &stream).await, "250 Successfully changed working directory\r\n"); + send_to_server("SITE WHEREAMI\r\n", &stream).await; + assert_eq!(read_from_server(&mut buffer, &stream).await, format!("200 /{SITE_CWD_DIR}\r\n")); + + send_to_server("CDUP\r\n", &stream).await; + assert_eq!(read_from_server(&mut buffer, &stream).await, "250 OK\r\n"); + send_to_server("SITE WHEREAMI\r\n", &stream).await; + assert_eq!(read_from_server(&mut buffer, &stream).await, "200 /\r\n"); + + finalize().await; +} + +#[tokio::test(flavor = "current_thread")] +async fn test_custom_site_command_receives_connection_details() { + initialize().await; + + let stream = tcp_connect().await.unwrap(); + let mut buffer = vec![0_u8; 1024]; + login(&stream, &mut buffer).await; + + send_to_server("SITE CONNECTION\r\n", &stream).await; + let reply = read_from_server(&mut buffer, &stream).await; + let (source_ip, trace_id) = reply + .strip_prefix("200 ") + .and_then(|rest| rest.strip_suffix("\r\n")) + .and_then(|rest| rest.split_once(' ')) + .unwrap_or_else(|| panic!("unexpected reply {reply:?}")); + assert_eq!(source_ip, "127.0.0.1"); + assert!(trace_id.starts_with("0x"), "unexpected trace ID {trace_id:?}"); + + finalize().await; +} + #[tokio::test(flavor = "current_thread")] async fn test_unregistered_site_command_returns_502() { initialize().await;