xref: /aosp_15_r20/external/pigweed/pw_transfer/atomic_file_transfer_handler.cc (revision 61c4878ac05f98d0ceed94b57d316916de578985)
1 // Copyright 2022 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 //     https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14 #include "pw_transfer/atomic_file_transfer_handler.h"
15 
16 #include <filesystem>
17 #include <system_error>
18 
19 #include "pw_log/log.h"
20 #include "pw_status/status.h"
21 #include "pw_stream/std_file_stream.h"
22 #include "pw_transfer_private/filename_generator.h"
23 
24 namespace pw::transfer {
25 
26 namespace {
27 // Linux Error code for Cross-Device Link Error.
28 constexpr auto CROSS_DEVICE_LINK_ERROR = 18;
29 
EnsureDirectoryExists(std::string_view filepath)30 pw::Status EnsureDirectoryExists(std::string_view filepath) {
31   const auto target_directory = std::filesystem::path{filepath}.parent_path();
32   return std::filesystem::exists(target_directory) ||
33                  std::filesystem::create_directories(target_directory)
34              ? pw::OkStatus()
35              : pw::Status::Internal();
36 }
37 
38 // Copy file and remove on succes.
39 // If the copy fails, the file `input_target` is not removed.
CopyFile(std::string_view input_target,std::string_view output_target)40 pw::Status CopyFile(std::string_view input_target,
41                     std::string_view output_target) {
42   auto err = std::error_code{};
43   std::filesystem::copy(input_target,
44                         output_target,
45                         std::filesystem::copy_options::overwrite_existing,
46                         err);
47   if (err) {
48     PW_LOG_ERROR("Error with status code: %d (%s) during copy of file %s",
49                  err.value(),
50                  err.message().c_str(),
51                  input_target.data());
52     return pw::Status::Internal();
53   }
54   PW_LOG_INFO("Successfully copied the file.");
55   if (!std::filesystem::remove(input_target)) {
56     PW_LOG_WARN("Failed to remove tmp file %s", input_target.data());
57   }
58   return pw::OkStatus();
59 }
60 
61 // Uses the same approach as unix `mv` command. First try to rename. If we get
62 // a cross-device link error, copies then deletes input_target.
RenameFile(std::string_view input_target,std::string_view output_target)63 pw::Status RenameFile(std::string_view input_target,
64                       std::string_view output_target) {
65   auto err = std::error_code{};
66   std::filesystem::rename(input_target, output_target, err);
67   if (err && err.value() == CROSS_DEVICE_LINK_ERROR) {
68     PW_LOG_INFO("%s[%d] during rename of file %s. Trying Copy/Remove.",
69                 err.message().c_str(),
70                 err.value(),
71                 input_target.data());
72     return CopyFile(input_target, output_target);
73   }
74   return err ? pw::Status::Internal() : pw::OkStatus();
75 }
76 
77 }  // namespace
78 
PrepareRead()79 Status AtomicFileTransferHandler::PrepareRead() {
80   auto file_path = path_.c_str();
81   PW_LOG_DEBUG("Preparing read for file %s", file_path);
82   if (!std::filesystem::exists(file_path)) {
83     PW_LOG_ERROR("File does not exist, path: %s", file_path);
84     return Status::NotFound();
85   }
86   set_reader(stream_.emplace<stream::StdFileReader>(file_path));
87   return OkStatus();
88 }
89 
FinalizeRead(Status)90 void AtomicFileTransferHandler::FinalizeRead(Status) {
91   std::get<stream::StdFileReader>(stream_).Close();
92 }
93 
PrepareWrite()94 Status AtomicFileTransferHandler::PrepareWrite() {
95   const std::string tmp_file = GetTempFilePath(path_);
96   PW_LOG_DEBUG("Preparing write for file %s", tmp_file.c_str());
97   set_writer(stream_.emplace<stream::StdFileWriter>(tmp_file.c_str()));
98   return OkStatus();
99 }
100 
FinalizeWrite(Status status)101 Status AtomicFileTransferHandler::FinalizeWrite(Status status) {
102   std::get<stream::StdFileWriter>(stream_).Close();
103   auto tmp_file = GetTempFilePath(path_);
104   if (!status.ok() || !std::filesystem::exists(tmp_file) ||
105       std::filesystem::is_empty(tmp_file)) {
106     PW_LOG_ERROR("Transfer unsuccesful, attempt to remove temp file %s",
107                  tmp_file.c_str());
108     // Remove temp file if transfer fails.
109     return std::filesystem::remove(tmp_file) ? status : Status::Aborted();
110   }
111 
112   const auto directory_exists_status = EnsureDirectoryExists(path_);
113   if (!directory_exists_status.ok()) {
114     std::filesystem::remove(tmp_file);
115     return directory_exists_status;
116   }
117 
118   PW_LOG_DEBUG(
119       "Copying file from: %s, to: %s", tmp_file.c_str(), path_.c_str());
120   const auto rename_status = RenameFile(tmp_file, path_);
121   if (!rename_status.ok()) {
122     std::filesystem::remove(tmp_file);
123     return rename_status;
124   }
125 
126   PW_LOG_INFO("File transfer was successful.");
127   return OkStatus();
128 }
129 
130 }  // namespace pw::transfer
131