1 //
2 // Copyright (C) 2011 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #include "update_engine/payload_consumer/download_action.h"
18 
19 #include <errno.h>
20 
21 #include <algorithm>
22 #include <string>
23 #include <vector>
24 
25 #include <base/files/file_path.h>
26 #include <base/strings/stringprintf.h>
27 
28 #include "update_engine/common/action_pipe.h"
29 #include "update_engine/common/boot_control_interface.h"
30 #include "update_engine/common/error_code_utils.h"
31 #include "update_engine/common/utils.h"
32 #include "update_engine/omaha_request_params.h"
33 #include "update_engine/p2p_manager.h"
34 #include "update_engine/payload_state_interface.h"
35 
36 using base::FilePath;
37 using std::string;
38 using std::vector;
39 
40 namespace chromeos_update_engine {
41 
DownloadAction(PrefsInterface * prefs,BootControlInterface * boot_control,HardwareInterface * hardware,SystemState * system_state,HttpFetcher * http_fetcher)42 DownloadAction::DownloadAction(PrefsInterface* prefs,
43                                BootControlInterface* boot_control,
44                                HardwareInterface* hardware,
45                                SystemState* system_state,
46                                HttpFetcher* http_fetcher)
47     : prefs_(prefs),
48       boot_control_(boot_control),
49       hardware_(hardware),
50       system_state_(system_state),
51       http_fetcher_(http_fetcher),
52       writer_(nullptr),
53       code_(ErrorCode::kSuccess),
54       delegate_(nullptr),
55       bytes_received_(0),
56       p2p_sharing_fd_(-1),
57       p2p_visible_(true) {
58 }
59 
~DownloadAction()60 DownloadAction::~DownloadAction() {}
61 
CloseP2PSharingFd(bool delete_p2p_file)62 void DownloadAction::CloseP2PSharingFd(bool delete_p2p_file) {
63   if (p2p_sharing_fd_ != -1) {
64     if (close(p2p_sharing_fd_) != 0) {
65       PLOG(ERROR) << "Error closing p2p sharing fd";
66     }
67     p2p_sharing_fd_ = -1;
68   }
69 
70   if (delete_p2p_file) {
71     FilePath path =
72       system_state_->p2p_manager()->FileGetPath(p2p_file_id_);
73     if (unlink(path.value().c_str()) != 0) {
74       PLOG(ERROR) << "Error deleting p2p file " << path.value();
75     } else {
76       LOG(INFO) << "Deleted p2p file " << path.value();
77     }
78   }
79 
80   // Don't use p2p from this point onwards.
81   p2p_file_id_.clear();
82 }
83 
SetupP2PSharingFd()84 bool DownloadAction::SetupP2PSharingFd() {
85   P2PManager *p2p_manager = system_state_->p2p_manager();
86 
87   if (!p2p_manager->FileShare(p2p_file_id_, install_plan_.payload_size)) {
88     LOG(ERROR) << "Unable to share file via p2p";
89     CloseP2PSharingFd(true);  // delete p2p file
90     return false;
91   }
92 
93   // File has already been created (and allocated, xattrs been
94   // populated etc.) by FileShare() so just open it for writing.
95   FilePath path = p2p_manager->FileGetPath(p2p_file_id_);
96   p2p_sharing_fd_ = open(path.value().c_str(), O_WRONLY);
97   if (p2p_sharing_fd_ == -1) {
98     PLOG(ERROR) << "Error opening file " << path.value();
99     CloseP2PSharingFd(true);  // Delete p2p file.
100     return false;
101   }
102 
103   // Ensure file to share is world-readable, otherwise
104   // p2p-server and p2p-http-server can't access it.
105   //
106   // (Q: Why doesn't the file have mode 0644 already? A: Because
107   // the process-wide umask is set to 0700 in main.cc.)
108   if (fchmod(p2p_sharing_fd_, 0644) != 0) {
109     PLOG(ERROR) << "Error setting mode 0644 on " << path.value();
110     CloseP2PSharingFd(true);  // Delete p2p file.
111     return false;
112   }
113 
114   // All good.
115   LOG(INFO) << "Writing payload contents to " << path.value();
116   p2p_manager->FileGetVisible(p2p_file_id_, &p2p_visible_);
117   return true;
118 }
119 
WriteToP2PFile(const void * data,size_t length,off_t file_offset)120 void DownloadAction::WriteToP2PFile(const void* data,
121                                     size_t length,
122                                     off_t file_offset) {
123   if (p2p_sharing_fd_ == -1) {
124     if (!SetupP2PSharingFd())
125       return;
126   }
127 
128   // Check that the file is at least |file_offset| bytes long - if
129   // it's not something is wrong and we must immediately delete the
130   // file to avoid propagating this problem to other peers.
131   //
132   // How can this happen? It could be that we're resuming an update
133   // after a system crash... in this case, it could be that
134   //
135   //  1. the p2p file didn't get properly synced to stable storage; or
136   //  2. the file was deleted at bootup (it's in /var/cache after all); or
137   //  3. other reasons
138   off_t p2p_size = utils::FileSize(p2p_sharing_fd_);
139   if (p2p_size < 0) {
140     PLOG(ERROR) << "Error getting file status for p2p file";
141     CloseP2PSharingFd(true);  // Delete p2p file.
142     return;
143   }
144   if (p2p_size < file_offset) {
145     LOG(ERROR) << "Wanting to write to file offset " << file_offset
146                << " but existing p2p file is only " << p2p_size
147                << " bytes.";
148     CloseP2PSharingFd(true);  // Delete p2p file.
149     return;
150   }
151 
152   off_t cur_file_offset = lseek(p2p_sharing_fd_, file_offset, SEEK_SET);
153   if (cur_file_offset != static_cast<off_t>(file_offset)) {
154     PLOG(ERROR) << "Error seeking to position "
155                 << file_offset << " in p2p file";
156     CloseP2PSharingFd(true);  // Delete p2p file.
157   } else {
158     // OK, seeking worked, now write the data
159     ssize_t bytes_written = write(p2p_sharing_fd_, data, length);
160     if (bytes_written != static_cast<ssize_t>(length)) {
161       PLOG(ERROR) << "Error writing "
162                   << length << " bytes at file offset "
163                   << file_offset << " in p2p file";
164       CloseP2PSharingFd(true);  // Delete p2p file.
165     }
166   }
167 }
168 
PerformAction()169 void DownloadAction::PerformAction() {
170   http_fetcher_->set_delegate(this);
171 
172   // Get the InstallPlan and read it
173   CHECK(HasInputObject());
174   install_plan_ = GetInputObject();
175   bytes_received_ = 0;
176 
177   install_plan_.Dump();
178 
179   LOG(INFO) << "Marking new slot as unbootable";
180   if (!boot_control_->MarkSlotUnbootable(install_plan_.target_slot)) {
181     LOG(WARNING) << "Unable to mark new slot "
182                  << BootControlInterface::SlotName(install_plan_.target_slot)
183                  << ". Proceeding with the update anyway.";
184   }
185 
186   if (writer_) {
187     LOG(INFO) << "Using writer for test.";
188   } else {
189     delta_performer_.reset(new DeltaPerformer(
190         prefs_, boot_control_, hardware_, delegate_, &install_plan_));
191     writer_ = delta_performer_.get();
192   }
193   download_active_ = true;
194 
195   if (system_state_ != nullptr) {
196     const PayloadStateInterface* payload_state = system_state_->payload_state();
197     string file_id = utils::CalculateP2PFileId(install_plan_.payload_hash,
198                                                install_plan_.payload_size);
199     if (payload_state->GetUsingP2PForSharing()) {
200       // If we're sharing the update, store the file_id to convey
201       // that we should write to the file.
202       p2p_file_id_ = file_id;
203       LOG(INFO) << "p2p file id: " << p2p_file_id_;
204     } else {
205       // Even if we're not sharing the update, it could be that
206       // there's a partial file from a previous attempt with the same
207       // hash. If this is the case, we NEED to clean it up otherwise
208       // we're essentially timing out other peers downloading from us
209       // (since we're never going to complete the file).
210       FilePath path = system_state_->p2p_manager()->FileGetPath(file_id);
211       if (!path.empty()) {
212         if (unlink(path.value().c_str()) != 0) {
213           PLOG(ERROR) << "Error deleting p2p file " << path.value();
214         } else {
215           LOG(INFO) << "Deleting partial p2p file " << path.value()
216                     << " since we're not using p2p to share.";
217         }
218       }
219     }
220 
221     // Tweak timeouts on the HTTP fetcher if we're downloading from a
222     // local peer.
223     if (payload_state->GetUsingP2PForDownloading() &&
224         payload_state->GetP2PUrl() == install_plan_.download_url) {
225       LOG(INFO) << "Tweaking HTTP fetcher since we're downloading via p2p";
226       http_fetcher_->set_low_speed_limit(kDownloadP2PLowSpeedLimitBps,
227                                          kDownloadP2PLowSpeedTimeSeconds);
228       http_fetcher_->set_max_retry_count(kDownloadP2PMaxRetryCount);
229       http_fetcher_->set_connect_timeout(kDownloadP2PConnectTimeoutSeconds);
230     }
231   }
232 
233   http_fetcher_->BeginTransfer(install_plan_.download_url);
234 }
235 
SuspendAction()236 void DownloadAction::SuspendAction() {
237   http_fetcher_->Pause();
238 }
239 
ResumeAction()240 void DownloadAction::ResumeAction() {
241   http_fetcher_->Unpause();
242 }
243 
TerminateProcessing()244 void DownloadAction::TerminateProcessing() {
245   if (writer_) {
246     writer_->Close();
247     writer_ = nullptr;
248   }
249   download_active_ = false;
250   CloseP2PSharingFd(false);  // Keep p2p file.
251   // Terminates the transfer. The action is terminated, if necessary, when the
252   // TransferTerminated callback is received.
253   http_fetcher_->TerminateTransfer();
254 }
255 
SeekToOffset(off_t offset)256 void DownloadAction::SeekToOffset(off_t offset) {
257   bytes_received_ = offset;
258 }
259 
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)260 void DownloadAction::ReceivedBytes(HttpFetcher* fetcher,
261                                    const void* bytes,
262                                    size_t length) {
263   // Note that bytes_received_ is the current offset.
264   if (!p2p_file_id_.empty()) {
265     WriteToP2PFile(bytes, length, bytes_received_);
266   }
267 
268   bytes_received_ += length;
269   if (delegate_ && download_active_) {
270     delegate_->BytesReceived(
271         length, bytes_received_, install_plan_.payload_size);
272   }
273   if (writer_ && !writer_->Write(bytes, length, &code_)) {
274     LOG(ERROR) << "Error " << utils::ErrorCodeToString(code_) << " (" << code_
275                << ") in DeltaPerformer's Write method when "
276                << "processing the received payload -- Terminating processing";
277     // Delete p2p file, if applicable.
278     if (!p2p_file_id_.empty())
279       CloseP2PSharingFd(true);
280     // Don't tell the action processor that the action is complete until we get
281     // the TransferTerminated callback. Otherwise, this and the HTTP fetcher
282     // objects may get destroyed before all callbacks are complete.
283     TerminateProcessing();
284     return;
285   }
286 
287   // Call p2p_manager_->FileMakeVisible() when we've successfully
288   // verified the manifest!
289   if (!p2p_visible_ && system_state_ && delta_performer_.get() &&
290       delta_performer_->IsManifestValid()) {
291     LOG(INFO) << "Manifest has been validated. Making p2p file visible.";
292     system_state_->p2p_manager()->FileMakeVisible(p2p_file_id_);
293     p2p_visible_ = true;
294   }
295 }
296 
TransferComplete(HttpFetcher * fetcher,bool successful)297 void DownloadAction::TransferComplete(HttpFetcher* fetcher, bool successful) {
298   if (writer_) {
299     LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
300     writer_ = nullptr;
301   }
302   download_active_ = false;
303   ErrorCode code =
304       successful ? ErrorCode::kSuccess : ErrorCode::kDownloadTransferError;
305   if (code == ErrorCode::kSuccess && delta_performer_.get()) {
306     code = delta_performer_->VerifyPayload(install_plan_.payload_hash,
307                                            install_plan_.payload_size);
308     if (code != ErrorCode::kSuccess) {
309       LOG(ERROR) << "Download of " << install_plan_.download_url
310                  << " failed due to payload verification error.";
311       // Delete p2p file, if applicable.
312       if (!p2p_file_id_.empty())
313         CloseP2PSharingFd(true);
314     }
315   }
316 
317   // Write the path to the output pipe if we're successful.
318   if (code == ErrorCode::kSuccess && HasOutputPipe())
319     SetOutputObject(install_plan_);
320   processor_->ActionComplete(this, code);
321 }
322 
TransferTerminated(HttpFetcher * fetcher)323 void DownloadAction::TransferTerminated(HttpFetcher *fetcher) {
324   if (code_ != ErrorCode::kSuccess) {
325     processor_->ActionComplete(this, code_);
326   }
327 }
328 
329 }  // namespace chromeos_update_engine
330