From 56e88805a0545e547f163b6d5740614fa0bedf61 Mon Sep 17 00:00:00 2001 From: Matthias Koefferlein Date: Sun, 15 Sep 2024 17:15:21 +0200 Subject: [PATCH] Refusing to write files with empty string and to a path that is a directory - the latter would rename the directory and later try to remove it --- src/tl/tl/tlStream.cc | 34 +++++++++++++++++++++--------- src/tl/unit_tests/tlStreamTests.cc | 15 +++++++++++++ 2 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/tl/tl/tlStream.cc b/src/tl/tl/tlStream.cc index 751c4841d..f83be7bfb 100644 --- a/src/tl/tl/tlStream.cc +++ b/src/tl/tl/tlStream.cc @@ -1178,20 +1178,34 @@ OutputStream::seek (size_t pos) OutputFileBase::OutputFileBase (const std::string &p, int keep_backups) : m_keep_backups (keep_backups), m_path (tl::absolute_file_path (p)), m_has_error (false) { + if (p.empty ()) { + throw tl::Exception (tl::to_string (tr ("Path cannot be an empty string"))); + } + if (tl::file_exists (m_path)) { - m_backup_path = m_path + ".~backup"; - if (tl::file_exists (m_backup_path)) { - if (! tl::rm_file (m_backup_path)) { - tl::warn << tl::sprintf (tl::to_string (tr ("Could not create backup file: unable to remove existing file '%s'")), m_backup_path); - m_backup_path = std::string (); + + if (tl::is_dir (m_path)) { + + throw tl::Exception (tl::to_string (tr ("Path exists and is a directory: '%s'")), m_path); + + } else { + + m_backup_path = m_path + ".~backup"; + if (tl::file_exists (m_backup_path)) { + if (! tl::rm_file (m_backup_path)) { + tl::warn << tl::sprintf (tl::to_string (tr ("Could not create backup file: unable to remove existing file '%s'")), m_backup_path); + m_backup_path = std::string (); + } } - } - if (! m_backup_path.empty ()) { - if (! tl::rename_file (m_path, tl::filename (m_backup_path))) { - tl::warn << tl::sprintf (tl::to_string (tr ("Could not create backup file: unable to rename original file '%s' to backup file")), m_path, m_backup_path); - m_backup_path = std::string (); + if (! m_backup_path.empty ()) { + if (! tl::rename_file (m_path, tl::filename (m_backup_path))) { + tl::warn << tl::sprintf (tl::to_string (tr ("Could not create backup file: unable to rename original file '%s' to backup file")), m_path, m_backup_path); + m_backup_path = std::string (); + } } + } + } } diff --git a/src/tl/unit_tests/tlStreamTests.cc b/src/tl/unit_tests/tlStreamTests.cc index 517d71615..156f276c2 100644 --- a/src/tl/unit_tests/tlStreamTests.cc +++ b/src/tl/unit_tests/tlStreamTests.cc @@ -462,5 +462,20 @@ TEST(Backups) } } +TEST(RefuseToWrite) +{ + try { + tl::OutputStream os (""); + EXPECT_EQ (1, 0); + } catch (tl::Exception &ex) { + EXPECT_EQ (ex.msg (), "Path cannot be an empty string"); + } + try { + tl::OutputStream os ("."); + EXPECT_EQ (1, 0); + } catch (tl::Exception &ex) { + EXPECT_EQ (ex.msg ().find ("Path exists and is a directory"), size_t (0)); + } +}