From 3d2ac056d6f216e762510beedab795c166df3f8b Mon Sep 17 00:00:00 2001 From: oblique Date: Sun, 18 Sep 2022 01:03:14 +0300 Subject: [PATCH] Return error on empty name --- src/error.rs | 3 +++ src/lib.rs | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/src/error.rs b/src/error.rs index 1b3c2be..7a1e2d4 100644 --- a/src/error.rs +++ b/src/error.rs @@ -9,6 +9,9 @@ pub enum Error { #[error("Invalid character in name")] InvalidCharacter, + #[error("Name must not be empty")] + EmptyName, + #[error("Failed to create named lock: {0}")] CreateFailed(#[source] std::io::Error), diff --git a/src/lib.rs b/src/lib.rs index c2a8fea..15e5032 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -78,11 +78,19 @@ impl NamedLock { /// /// This will create/open a [global] mutex with [`CreateMutexW`]. /// + /// # Notes + /// + /// * `name` must not be empty, otherwise an error is returned. + /// * `name` must not contain `\0`, `/`, nor `\`, otherwise an error is returned. /// /// [`flock`]: https://linux.die.net/man/2/flock /// [global]: https://docs.microsoft.com/en-us/windows/win32/termserv/kernel-object-namespaces /// [`CreateMutexW`]: https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexw pub fn create(name: &str) -> Result { + if name.is_empty() { + return Err(Error::EmptyName); + } + // On UNIX we want to restrict the user on `/tmp` directory, // so we block the `/` character. // @@ -112,8 +120,8 @@ impl NamedLock { /// /// # Notes /// - /// * This function does not append `.lock` on the path - /// * Parent directories must exist + /// * This function does not append `.lock` on the path. + /// * Parent directories must exist. #[cfg(unix)] #[cfg_attr(docsrs, doc(cfg(unix)))] pub fn with_path

(path: P) -> Result @@ -263,4 +271,24 @@ mod tests { Ok(()) } + + #[test] + fn invalid_names() { + assert!(matches!(NamedLock::create(""), Err(Error::EmptyName))); + + assert!(matches!( + NamedLock::create("abc/"), + Err(Error::InvalidCharacter) + )); + + assert!(matches!( + NamedLock::create("abc\\"), + Err(Error::InvalidCharacter) + )); + + assert!(matches!( + NamedLock::create("abc\0"), + Err(Error::InvalidCharacter) + )); + } }