prevent working on unlinked files
authorGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 10 Mar 2010 17:41:55 +0000 (18:41 +0100)
committerGerd von Egidy <gerd.von.egidy@intra2net.com>
Wed, 10 Mar 2010 17:41:55 +0000 (18:41 +0100)
src/tmpfstream.hpp
src/tmpfstream_impl.hpp
test/test_tmpfstream.cpp

index 024b0e5..17f9736 100644 (file)
@@ -39,6 +39,7 @@ class tmpfstreamTempl : public bio::stream<Device, Tr, Alloc>
 {
 private:
     std::string filename;
+    bool unlinked;
 
 public:
     tmpfstreamTempl()
@@ -64,7 +65,10 @@ public:
 
     bool unlink();
 
-    bool move(const std::string& targetpath, bool overwrite);
+    bool is_unlinked()
+        { return unlinked; }
+
+    bool move(const std::string& targetpath, bool overwrite=false);
 };
 
 typedef tmpfstreamTempl<bio::file_descriptor_sink> tmpofstream;
index be4dceb..f00bb3f 100644 (file)
@@ -71,7 +71,7 @@ bool tmpfstreamTempl<Device,Tr,Alloc>::open(const std::string& tmpnametemplate,
 template< typename Device, typename Tr, typename Alloc >
 bool tmpfstreamTempl<Device,Tr,Alloc>::set_file_mode(int mode)
 {
-    if (!get_tmp_filename().empty())
+    if (!get_tmp_filename().empty() && !is_unlinked())
         return I2n::chmod(get_tmp_filename(),mode);
     else
         return false;
@@ -81,7 +81,15 @@ template< typename Device, typename Tr, typename Alloc >
 bool tmpfstreamTempl<Device,Tr,Alloc>::unlink()
 {
     if (!get_tmp_filename().empty())
-        return I2n::unlink(get_tmp_filename());
+    {
+        if (I2n::unlink(get_tmp_filename()))
+        {
+            unlinked=true;
+            return true;
+        }
+        else
+            return false;
+    }
     else
         return false;
 }
@@ -90,7 +98,7 @@ template< typename Device, typename Tr, typename Alloc >
 bool tmpfstreamTempl<Device,Tr,Alloc>::move(const std::string& targetpath, 
                                           bool overwrite)
 {
-    if (get_tmp_filename().empty())
+    if (get_tmp_filename().empty() || is_unlinked())
         return false;
 
     if (overwrite)
index 5180401..1d61719 100644 (file)
@@ -194,6 +194,31 @@ BOOST_AUTO_TEST_CASE(TmpofstreamMoveOverwrite)
     unlink(".foobar");
 } 
 
+BOOST_AUTO_TEST_CASE(TmpofstreamMoveAfterUnlink)
+{
+    // just to be sure
+    unlink(".foobar");
+
+    tmpofstream tmpf("./tmp.XXXXXX");
+
+    BOOST_CHECK_EQUAL( true, tmpf.is_open() );
+
+    Stat stat(tmpf.get_tmp_filename());
+    BOOST_CHECK_EQUAL( true, (bool)stat );
+    BOOST_CHECK_EQUAL( true, stat.is_regular_file() );
+
+    tmpf << "hello world" << endl;
+    tmpf.flush();
+
+    BOOST_CHECK_EQUAL( true, tmpf.unlink() );
+
+    BOOST_CHECK_EQUAL( true, tmpf.is_unlinked() );
+
+    BOOST_CHECK_EQUAL( false, tmpf.move(".foobar") );
+
+    unlink(".foobar");
+} 
+
 BOOST_AUTO_TEST_CASE(TmpfstreamReadWrite)
 {
     tmpfstream tmpf("./tmp.XXXXXX",std::ios_base::out | std::ios_base::in );