From 8e4cf7ad553f904bb94791e14c56da87d38ff600 Mon Sep 17 00:00:00 2001 From: Astro Date: Sat, 24 Sep 2022 01:22:49 +0200 Subject: [PATCH] make file creation lazy so that there are no more 0-byte files --- src/main.rs | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/main.rs b/src/main.rs index a74e877..02a8ab5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -60,13 +60,9 @@ impl server::Server for Server { ); let path = Path::new(path); create_dir_all(path.parent().unwrap()).unwrap(); - let file = OpenOptions::new() - .create(true) - .append(true) - .open(path) - .unwrap(); Handler { - file, + filename: path.display().to_string(), + lazy_file: None, buffer: vec![], user: "root".into(), } @@ -79,12 +75,25 @@ fn send_str(session: &mut Session, channel: ChannelId, s: String) { } struct Handler { - file: File, + filename: String, + lazy_file: Option, buffer: Vec, user: String, } impl Handler { + fn file(&mut self) -> &mut File { + if self.lazy_file.is_none() { + let file = OpenOptions::new() + .create(true) + .append(true) + .open(&self.filename) + .unwrap(); + self.lazy_file = Some(file); + } + self.lazy_file.as_mut().unwrap() + } + fn send_prompt(&self, session: &mut Session, channel: ChannelId) { send_str(session, channel, format!("{}@fnordister:~$ ", self.user)); } @@ -145,7 +154,7 @@ impl server::Handler for Handler { fn exec_request(mut self, channel: ChannelId, data: &[u8], mut session: Session) -> Self::FutureUnit { info!("exec_request"); - writeln!(self.file, "Execute: {}\n", String::from_utf8_lossy(data)) + writeln!(self.file(), "Execute: {}\n", String::from_utf8_lossy(data)) .unwrap(); let line = String::from_utf8_lossy(data).into(); @@ -166,21 +175,21 @@ impl server::Handler for Handler { session: Session ) -> Self::FutureUnit { info!("subsystem_request"); - writeln!(self.file, "Subsystem requested: {}\n", name) + writeln!(self.file(), "Subsystem requested: {}\n", name) .unwrap(); self.finished(session) } fn auth_password(mut self, user: &str, password: &str) -> Self::FutureAuth { - writeln!(self.file, "Authenticated as {} with {}\n", user, password) + writeln!(self.file(), "Authenticated as {} with {}\n", user, password) .unwrap(); self.user = user.into(); self.finished_auth(server::Auth::Accept) } fn data(mut self, channel: ChannelId, data: &[u8], mut session: Session) -> Self::FutureUnit { - self.file.write(data) + self.file().write(data) .unwrap(); // echo input back session.data(channel, data.to_vec().into());