Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Changelog

### Unreleased

- Add `ServerBuilder::help_text` to set the reply to the `HELP` command, which by default names the library
and its version to any client ([#608](https://github.com/Cloudinvoke/libunftp/issues/608)).

### libunftp 0.25.0

- [#602](https://github.com/Cloudinvoke/libunftp/pull/602) Move libunftp and unFTP from bol.com to [CloudInvoke](https://github.com/Cloudinvoke).
Expand Down
15 changes: 14 additions & 1 deletion src/server/controlchan/commands/help.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,19 @@ use crate::{
storage::{Metadata, StorageBackend},
};
use async_trait::async_trait;
use std::sync::Arc;

#[derive(Debug)]
pub struct Help;
pub struct Help {
// Set with `ServerBuilder::help_text`, else the default text
text: Option<Arc<[String]>>,
}

impl Help {
pub fn new(text: Option<Arc<[String]>>) -> Self {
Help { text }
}
}

#[async_trait]
impl<Storage, User> CommandHandler<Storage, User> for Help
Expand All @@ -28,6 +38,9 @@ where
{
#[tracing_attributes::instrument]
async fn handle(&self, _args: CommandContext<Storage, User>) -> Result<Reply, ControlChanError> {
if let Some(text) = &self.text {
return Ok(Reply::new_multiline(ReplyCode::HelpMessage, text.iter()));
}
let text: Vec<String> = vec![
"Help:".to_string(),
format!("Powered by libunftp: {}", env!("CARGO_PKG_VERSION")),
Expand Down
6 changes: 5 additions & 1 deletion src/server/controlchan/control_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ where
{
pub storage: Storage,
pub greeting: &'static str,
pub help_text: Option<Arc<[String]>>,
pub auth_pipeline: Arc<AuthenticationPipeline<User>>,
pub passive_ports: RangeInclusive<u16>,
pub passive_host: PassiveHost,
Expand Down Expand Up @@ -138,6 +139,7 @@ where
logger,
site_md5: sitemd5,
site_handlers,
help_text,
data_listener,
presence_listener,
active_passive_mode,
Expand Down Expand Up @@ -178,6 +180,7 @@ where
tx_proxy_loop: switchboard_msg_tx.clone(),
sitemd5,
site_handlers,
help_text,
};

let event_chain = EventDispatcherMiddleware::new(data_listener, presence_listener, event_chain);
Expand Down Expand Up @@ -382,6 +385,7 @@ where
tx_proxy_loop: Option<SwitchboardSender<Storage, User>>,
sitemd5: SiteMd5,
site_handlers: Arc<HashMap<String, Arc<dyn SiteCommandHandler<Storage, User>>>>,
help_text: Option<Arc<[String]>>,
}

impl<Storage, User> PrimaryEventHandler<Storage, User>
Expand Down Expand Up @@ -485,7 +489,7 @@ where
Command::Type => Box::new(commands::Type),
Command::Stru { structure } => Box::new(commands::Stru::new(structure)),
Command::Mode { mode } => Box::new(commands::Mode::new(mode)),
Command::Help => Box::new(commands::Help),
Command::Help => Box::new(commands::Help::new(self.help_text.clone())),
Command::Noop => Box::new(commands::Noop),
Command::Pasv => Box::new(commands::Pasv::new()),
Command::Epsv => Box::new(commands::Epsv::new()),
Expand Down
33 changes: 33 additions & 0 deletions src/server/ftpserver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ where
{
storage: Arc<dyn (Fn() -> Storage) + Send + Sync>,
greeting: &'static str,
help_text: Option<Arc<[String]>>,
authenticator: Arc<dyn Authenticator>,
user_detail_provider: Arc<dyn UserDetailProvider<User = User> + Send + Sync>,
data_listener: Arc<dyn DataListener>,
Expand Down Expand Up @@ -91,6 +92,7 @@ where
{
storage: Arc<dyn (Fn() -> Storage) + Send + Sync>,
greeting: &'static str,
help_text: Option<Arc<[String]>>,
authenticator: Arc<dyn Authenticator>,
user_detail_provider: Arc<dyn UserDetailProvider<User = User> + Send + Sync>,
data_listener: Arc<dyn DataListener>,
Expand Down Expand Up @@ -142,6 +144,7 @@ where
ServerBuilder {
storage: Arc::from(sbe_generator),
greeting: DEFAULT_GREETING,
help_text: None,
authenticator,
user_detail_provider: Arc::new(DefaultUserDetailProvider {}),
data_listener: Arc::new(NopListener {}),
Expand Down Expand Up @@ -217,6 +220,7 @@ where
ServerBuilder {
storage: self.storage,
greeting: self.greeting,
help_text: self.help_text,
authenticator: self.authenticator,
user_detail_provider: provider,
data_listener: self.data_listener,
Expand Down Expand Up @@ -275,6 +279,7 @@ where
ServerBuilder {
storage: Arc::from(sbe_generator),
greeting: DEFAULT_GREETING,
help_text: None,
authenticator: Arc::new(AnonymousAuthenticator {}),
user_detail_provider: provider,
data_listener: Arc::new(NopListener {}),
Expand Down Expand Up @@ -361,6 +366,7 @@ where
Ok(Server {
storage: self.storage,
greeting: self.greeting,
help_text: self.help_text,
authenticator: self.authenticator,
user_detail_provider: self.user_detail_provider,
data_listener: self.data_listener,
Expand Down Expand Up @@ -524,6 +530,30 @@ where
self
}

/// Set the text of the reply to the `HELP` command, one item per line.
///
/// By default the reply names the library and its version, which lets any client, even before
/// logging in, know which server software it talks to. Use this to send something else.
///
/// # Example
///
/// ```rust
/// use libunftp::ServerBuilder;
/// use unftp_sbe_fs::Filesystem;
///
/// let server = ServerBuilder::new(Box::new(|| Filesystem::new("/tmp").unwrap()))
/// .help_text(["The following commands are recognized.", "Help OK."])
/// .build();
/// ```
pub fn help_text<I>(mut self, lines: I) -> Self
where
I: IntoIterator,
I::Item: Into<String>,
{
self.help_text = Some(lines.into_iter().map(Into::into).collect());
self
}

/// Set the idle session timeout in seconds. The default is 600 seconds.
///
/// # Example
Expand Down Expand Up @@ -1062,6 +1092,7 @@ where
ftps_config: server.ftps_mode.clone(),
collect_metrics: server.collect_metrics,
greeting: server.greeting,
help_text: server.help_text.clone(),
idle_session_timeout: server.idle_session_timeout,
passive_ports: server.passive_ports.clone(),
passive_host: server.passive_host.clone(),
Expand Down Expand Up @@ -1090,6 +1121,7 @@ where
.field("collect_metrics", &self.collect_metrics)
.field("active_passive_mode", &self.active_passive_mode)
.field("greeting", &self.greeting)
.field("help_text", &self.help_text)
.field("logger", &self.logger)
.field("metrics", &self.collect_metrics)
.field("passive_ports", &self.passive_ports)
Expand Down Expand Up @@ -1119,6 +1151,7 @@ where
.field("collect_metrics", &self.collect_metrics)
.field("active_passive_mode", &self.active_passive_mode)
.field("greeting", &self.greeting)
.field("help_text", &self.help_text)
.field("logger", &self.logger)
.field("metrics", &self.collect_metrics)
.field("passive_ports", &self.passive_ports)
Expand Down
2 changes: 2 additions & 0 deletions src/server/ftpserver/chosen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ where
{
pub storage: Arc<dyn (Fn() -> Storage) + Send + Sync>,
pub greeting: &'static str,
pub help_text: Option<Arc<[String]>>,
pub authenticator: Arc<dyn Authenticator>,
pub user_detail_provider: Arc<dyn UserDetailProvider<User = User> + Send + Sync>,
pub passive_ports: RangeInclusive<u16>,
Expand Down Expand Up @@ -58,6 +59,7 @@ where
ftps_config: server.ftps_config.clone(),
collect_metrics: server.collect_metrics,
greeting: server.greeting,
help_text: server.help_text.clone(),
idle_session_timeout: server.idle_session_timeout,
passive_ports: server.passive_ports.clone(),
passive_host: server.passive_host.clone(),
Expand Down
75 changes: 75 additions & 0 deletions tests/help.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#![allow(missing_docs)]

use libunftp::ServerBuilder;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use unftp_sbe_fs::Filesystem;

const DEFAULT_ADDR: &str = "127.0.0.1:2170";
const CUSTOM_ADDR: &str = "127.0.0.1:2171";

async fn serve(addr: &'static str, help_text: Option<Vec<&'static str>>) {
let root = std::env::temp_dir();
let mut builder = ServerBuilder::new(Box::new(move || Filesystem::new(root.clone()).unwrap())).greeting("Welcome test");
if let Some(lines) = help_text {
builder = builder.help_text(lines);
}
builder.build().unwrap().listen(addr).await.unwrap();
}

/// The reply to HELP, every line of it, once logged in
async fn help_reply(addr: &str) -> Vec<String> {
let mut stream = None;
for _ in 0..50 {
if let Ok(s) = TcpStream::connect(addr).await {
stream = Some(s);
break;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
let mut stream = BufReader::new(stream.expect("server did not start"));
let mut line = String::new();

async fn send(stream: &mut BufReader<TcpStream>, line: &mut String, command: &str, expected: &str) {
stream.get_mut().write_all(command.as_bytes()).await.unwrap();
line.clear();
stream.read_line(line).await.unwrap();
assert!(line.starts_with(expected), "{command:?}: {line:?}");
}
stream.read_line(&mut line).await.unwrap();
assert_eq!(line, "220 Welcome test\r\n");
send(&mut stream, &mut line, "USER anonymous\r\n", "331").await;
send(&mut stream, &mut line, "PASS anonymous\r\n", "230").await;

stream.get_mut().write_all(b"HELP\r\n").await.unwrap();
let mut reply = Vec::new();
loop {
line.clear();
stream.read_line(&mut line).await.unwrap();
reply.push(line.trim_end_matches("\r\n").to_string());
// The last line has the code followed by a space
if line.starts_with("214 ") {
return reply;
}
assert!(reply.len() < 20, "no end to the reply: {reply:?}");
}
}

#[tokio::test(flavor = "current_thread")]
async fn help_text_default_is_unchanged() {
tokio::spawn(serve(DEFAULT_ADDR, None));
let reply = help_reply(DEFAULT_ADDR).await;
assert_eq!(reply[0], "214-Help:");
assert!(reply.iter().any(|l| l.starts_with("Powered by libunftp: ")), "{reply:?}");
}

#[tokio::test(flavor = "current_thread")]
async fn help_text_replaces_the_reply() {
tokio::spawn(serve(
CUSTOM_ADDR,
Some(vec!["The following commands are recognized.", " ABOR CWD LIST", "Help OK."]),
));
let reply = help_reply(CUSTOM_ADDR).await;
assert_eq!(reply, ["214-The following commands are recognized.", " ABOR CWD LIST", "214 Help OK."]);
}