Line data Source code
1 : #include "fastmove.h"
2 : #include <system_error>
3 :
4 : using namespace std;
5 : using namespace std::filesystem;
6 :
7 : namespace Utils
8 : {
9 0 : void move_file(const path& source, const path& dest, bool overwriteExisting, std::error_code& ec)
10 : {
11 0 : auto options = copy_options::none;
12 0 : if (overwriteExisting)
13 : {
14 0 : options |= copy_options::overwrite_existing;
15 : }
16 :
17 0 : if (copy_file(source, dest, options, ec) &&
18 0 : ec.value() == 0)
19 : {
20 0 : remove(source, ec);
21 : }
22 0 : }
23 :
24 3 : void fastmove_file(const path& source, const path& dest, bool overwriteExisting, std::error_code& ec)
25 : {
26 : // Security-audit F002: POSIX rename() silently replaces an existing
27 : // destination, which made the overwriteExisting=false contract a no-op
28 : // - callers asking for no-overwrite (design upload) were overwriting
29 : // stored files anyway. Honor the flag: refuse when the destination
30 : // exists unless overwrite was explicitly requested. Note the check is
31 : // not atomic with rename(): two concurrent no-overwrite moves of the
32 : // same name race to last-writer-wins (still contained to the caller's
33 : // destination directory, so this is a correctness nicety, not a
34 : // containment hole).
35 3 : ec.clear();
36 3 : if (!overwriteExisting)
37 : {
38 2 : std::error_code existsEc;
39 2 : const bool destExists = exists(dest, existsEc);
40 2 : if (existsEc)
41 : {
42 0 : ec = existsEc;
43 0 : return;
44 : }
45 2 : if (destExists)
46 : {
47 1 : ec = std::make_error_code(std::errc::file_exists);
48 1 : return;
49 : }
50 : }
51 :
52 2 : rename(source, dest, ec);
53 2 : if (ec.value() == static_cast<int>(std::errc::cross_device_link))
54 : {
55 0 : move_file(source, dest, overwriteExisting, ec);
56 : }
57 : }
58 : }
|