1 //
2 // Copyright (C) 2020 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/cros/download_action_chromeos.h"
18 
19 #include <errno.h>
20 
21 #include <algorithm>
22 #include <string>
23 
24 #include <base/files/file_path.h>
25 #include <base/metrics/statistics_recorder.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/multi_range_http_fetcher.h"
32 #include "update_engine/common/system_state.h"
33 #include "update_engine/common/utils.h"
34 #include "update_engine/cros/omaha_request_params.h"
35 #include "update_engine/cros/p2p_manager.h"
36 #include "update_engine/cros/payload_state_interface.h"
37 
38 using base::FilePath;
39 using std::string;
40 
41 namespace chromeos_update_engine {
42 
DownloadActionChromeos(PrefsInterface * prefs,BootControlInterface * boot_control,HardwareInterface * hardware,HttpFetcher * http_fetcher,bool interactive)43 DownloadActionChromeos::DownloadActionChromeos(
44     PrefsInterface* prefs,
45     BootControlInterface* boot_control,
46     HardwareInterface* hardware,
47     HttpFetcher* http_fetcher,
48     bool interactive)
49     : prefs_(prefs),
50       boot_control_(boot_control),
51       hardware_(hardware),
52       http_fetcher_(new MultiRangeHttpFetcher(http_fetcher)),
53       interactive_(interactive),
54       writer_(nullptr),
55       code_(ErrorCode::kSuccess),
56       delegate_(nullptr),
57       p2p_sharing_fd_(-1),
58       p2p_visible_(true) {}
59 
~DownloadActionChromeos()60 DownloadActionChromeos::~DownloadActionChromeos() {}
61 
CloseP2PSharingFd(bool delete_p2p_file)62 void DownloadActionChromeos::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         SystemState::Get()->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 DownloadActionChromeos::SetupP2PSharingFd() {
85   P2PManager* p2p_manager = SystemState::Get()->p2p_manager();
86 
87   if (!p2p_manager->FileShare(p2p_file_id_, 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 DownloadActionChromeos::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 << " bytes.";
147     CloseP2PSharingFd(true);  // Delete p2p file.
148     return;
149   }
150 
151   off_t cur_file_offset = lseek(p2p_sharing_fd_, file_offset, SEEK_SET);
152   if (cur_file_offset != static_cast<off_t>(file_offset)) {
153     PLOG(ERROR) << "Error seeking to position " << file_offset
154                 << " in p2p file";
155     CloseP2PSharingFd(true);  // Delete p2p file.
156   } else {
157     // OK, seeking worked, now write the data
158     ssize_t bytes_written = write(p2p_sharing_fd_, data, length);
159     if (bytes_written != static_cast<ssize_t>(length)) {
160       PLOG(ERROR) << "Error writing " << length << " bytes at file offset "
161                   << file_offset << " in p2p file";
162       CloseP2PSharingFd(true);  // Delete p2p file.
163     }
164   }
165 }
166 
PerformAction()167 void DownloadActionChromeos::PerformAction() {
168   http_fetcher_->set_delegate(this);
169 
170   // Get the InstallPlan and read it
171   CHECK(HasInputObject());
172   install_plan_ = GetInputObject();
173   install_plan_.Dump();
174 
175   bytes_received_ = 0;
176   bytes_received_previous_payloads_ = 0;
177   bytes_total_ = 0;
178   for (const auto& payload : install_plan_.payloads)
179     bytes_total_ += payload.size;
180 
181   if (install_plan_.is_resume) {
182     int64_t payload_index = 0;
183     if (prefs_->GetInt64(kPrefsUpdateStatePayloadIndex, &payload_index) &&
184         static_cast<size_t>(payload_index) < install_plan_.payloads.size()) {
185       // Save the index for the resume payload before downloading any previous
186       // payload, otherwise it will be overwritten.
187       resume_payload_index_ = payload_index;
188       for (int i = 0; i < payload_index; i++)
189         install_plan_.payloads[i].already_applied = true;
190     }
191   }
192   // TODO(senj): check that install plan has at least one payload.
193   if (!payload_)
194     payload_ = &install_plan_.payloads[0];
195 
196   LOG(INFO) << "Marking new slot as unbootable";
197   if (!boot_control_->MarkSlotUnbootable(install_plan_.target_slot)) {
198     LOG(WARNING) << "Unable to mark new slot "
199                  << BootControlInterface::SlotName(install_plan_.target_slot)
200                  << ". Proceeding with the update anyway.";
201   }
202 
203   StartDownloading();
204 }
205 
LoadCachedManifest(int64_t manifest_size)206 bool DownloadActionChromeos::LoadCachedManifest(int64_t manifest_size) {
207   std::string cached_manifest_bytes;
208   if (!prefs_->GetString(kPrefsManifestBytes, &cached_manifest_bytes) ||
209       cached_manifest_bytes.size() <= 0) {
210     LOG(INFO) << "Cached Manifest data not found";
211     return false;
212   }
213   if (static_cast<int64_t>(cached_manifest_bytes.size()) != manifest_size) {
214     LOG(WARNING) << "Cached metadata has unexpected size: "
215                  << cached_manifest_bytes.size() << " vs. " << manifest_size;
216     return false;
217   }
218 
219   ErrorCode error;
220   const bool success =
221       delta_performer_->Write(
222           cached_manifest_bytes.data(), cached_manifest_bytes.size(), &error) &&
223       delta_performer_->IsManifestValid();
224   if (success) {
225     LOG(INFO) << "Successfully parsed cached manifest";
226   } else {
227     // If parsing of cached data failed, fall back to fetch them using HTTP
228     LOG(WARNING) << "Cached manifest data fails to load, error code:"
229                  << static_cast<int>(error) << "," << error;
230   }
231   return success;
232 }
233 
StartDownloading()234 void DownloadActionChromeos::StartDownloading() {
235   download_active_ = true;
236   http_fetcher_->ClearRanges();
237 
238   if (writer_ && writer_ != delta_performer_.get()) {
239     LOG(INFO) << "Using writer for test.";
240   } else {
241     delta_performer_.reset(new DeltaPerformer(prefs_,
242                                               boot_control_,
243                                               hardware_,
244                                               delegate_,
245                                               &install_plan_,
246                                               payload_,
247                                               interactive_));
248     writer_ = delta_performer_.get();
249   }
250 
251   if (install_plan_.is_resume &&
252       payload_ == &install_plan_.payloads[resume_payload_index_]) {
253     // Resuming an update so parse the cached manifest first
254     int64_t manifest_metadata_size = 0;
255     int64_t manifest_signature_size = 0;
256     prefs_->GetInt64(kPrefsManifestMetadataSize, &manifest_metadata_size);
257     prefs_->GetInt64(kPrefsManifestSignatureSize, &manifest_signature_size);
258 
259     // TODO(zhangkelvin) Add unittest for success and fallback route
260     if (!LoadCachedManifest(manifest_metadata_size + manifest_signature_size)) {
261       if (delta_performer_) {
262         // Create a new DeltaPerformer to reset all its state
263         delta_performer_ = std::make_unique<DeltaPerformer>(prefs_,
264                                                             boot_control_,
265                                                             hardware_,
266                                                             delegate_,
267                                                             &install_plan_,
268                                                             payload_,
269                                                             interactive_);
270         writer_ = delta_performer_.get();
271       }
272       http_fetcher_->AddRange(base_offset_,
273                               manifest_metadata_size + manifest_signature_size);
274     }
275 
276     // If there're remaining unprocessed data blobs, fetch them. Be careful not
277     // to request data beyond the end of the payload to avoid 416 HTTP response
278     // error codes.
279     int64_t next_data_offset = 0;
280     prefs_->GetInt64(kPrefsUpdateStateNextDataOffset, &next_data_offset);
281     uint64_t resume_offset =
282         manifest_metadata_size + manifest_signature_size + next_data_offset;
283     if (!payload_->size) {
284       http_fetcher_->AddRange(base_offset_ + resume_offset);
285     } else if (resume_offset < payload_->size) {
286       http_fetcher_->AddRange(base_offset_ + resume_offset,
287                               payload_->size - resume_offset);
288     }
289   } else {
290     if (payload_->size) {
291       http_fetcher_->AddRange(base_offset_, payload_->size);
292     } else {
293       // If no payload size is passed we assume we read until the end of the
294       // stream.
295       http_fetcher_->AddRange(base_offset_);
296     }
297   }
298 
299   if (SystemState::Get() != nullptr) {
300     const PayloadStateInterface* payload_state =
301         SystemState::Get()->payload_state();
302     string file_id = utils::CalculateP2PFileId(payload_->hash, payload_->size);
303     if (payload_state->GetUsingP2PForSharing()) {
304       // If we're sharing the update, store the file_id to convey
305       // that we should write to the file.
306       p2p_file_id_ = file_id;
307       LOG(INFO) << "p2p file id: " << p2p_file_id_;
308     } else {
309       // Even if we're not sharing the update, it could be that
310       // there's a partial file from a previous attempt with the same
311       // hash. If this is the case, we NEED to clean it up otherwise
312       // we're essentially timing out other peers downloading from us
313       // (since we're never going to complete the file).
314       FilePath path = SystemState::Get()->p2p_manager()->FileGetPath(file_id);
315       if (!path.empty()) {
316         if (unlink(path.value().c_str()) != 0) {
317           PLOG(ERROR) << "Error deleting p2p file " << path.value();
318         } else {
319           LOG(INFO) << "Deleting partial p2p file " << path.value()
320                     << " since we're not using p2p to share.";
321         }
322       }
323     }
324 
325     // Tweak timeouts on the HTTP fetcher if we're downloading from a
326     // local peer.
327     if (payload_state->GetUsingP2PForDownloading() &&
328         payload_state->GetP2PUrl() == install_plan_.download_url) {
329       LOG(INFO) << "Tweaking HTTP fetcher since we're downloading via p2p";
330       http_fetcher_->set_low_speed_limit(kDownloadP2PLowSpeedLimitBps,
331                                          kDownloadP2PLowSpeedTimeSeconds);
332       http_fetcher_->set_max_retry_count(kDownloadP2PMaxRetryCount);
333       http_fetcher_->set_connect_timeout(kDownloadP2PConnectTimeoutSeconds);
334     }
335   }
336 
337   http_fetcher_->BeginTransfer(install_plan_.download_url);
338 }
339 
SuspendAction()340 void DownloadActionChromeos::SuspendAction() {
341   http_fetcher_->Pause();
342 }
343 
ResumeAction()344 void DownloadActionChromeos::ResumeAction() {
345   http_fetcher_->Unpause();
346 }
347 
TerminateProcessing()348 void DownloadActionChromeos::TerminateProcessing() {
349   if (writer_) {
350     writer_->Close();
351     writer_ = nullptr;
352   }
353   download_active_ = false;
354   CloseP2PSharingFd(false);  // Keep p2p file.
355   // Terminates the transfer. The action is terminated, if necessary, when the
356   // TransferTerminated callback is received.
357   http_fetcher_->TerminateTransfer();
358 }
359 
SeekToOffset(off_t offset)360 void DownloadActionChromeos::SeekToOffset(off_t offset) {
361   bytes_received_ = offset;
362 }
363 
ReceivedBytes(HttpFetcher * fetcher,const void * bytes,size_t length)364 bool DownloadActionChromeos::ReceivedBytes(HttpFetcher* fetcher,
365                                            const void* bytes,
366                                            size_t length) {
367   // Note that bytes_received_ is the current offset.
368   if (!p2p_file_id_.empty()) {
369     WriteToP2PFile(bytes, length, bytes_received_);
370   }
371 
372   bytes_received_ += length;
373   uint64_t bytes_downloaded_total =
374       bytes_received_previous_payloads_ + bytes_received_;
375   if (delegate_ && download_active_) {
376     delegate_->BytesReceived(length, bytes_downloaded_total, bytes_total_);
377   }
378   if (writer_ && !writer_->Write(bytes, length, &code_)) {
379     if (code_ != ErrorCode::kSuccess) {
380       LOG(ERROR) << "Error " << utils::ErrorCodeToString(code_) << " (" << code_
381                  << ") in DeltaPerformer's Write method when "
382                  << "processing the received payload -- Terminating processing";
383     }
384     // Delete p2p file, if applicable.
385     if (!p2p_file_id_.empty())
386       CloseP2PSharingFd(true);
387     // Don't tell the action processor that the action is complete until we get
388     // the TransferTerminated callback. Otherwise, this and the HTTP fetcher
389     // objects may get destroyed before all callbacks are complete.
390     TerminateProcessing();
391     return false;
392   }
393 
394   // Call p2p_manager_->FileMakeVisible() when we've successfully
395   // verified the manifest!
396   if (!p2p_visible_ && SystemState::Get() && delta_performer_.get() &&
397       delta_performer_->IsManifestValid()) {
398     LOG(INFO) << "Manifest has been validated. Making p2p file visible.";
399     SystemState::Get()->p2p_manager()->FileMakeVisible(p2p_file_id_);
400     p2p_visible_ = true;
401   }
402   return true;
403 }
404 
TransferComplete(HttpFetcher * fetcher,bool successful)405 void DownloadActionChromeos::TransferComplete(HttpFetcher* fetcher,
406                                               bool successful) {
407   if (writer_) {
408     LOG_IF(WARNING, writer_->Close() != 0) << "Error closing the writer.";
409     if (delta_performer_.get() == writer_) {
410       // no delta_performer_ in tests, so leave the test writer in place
411       writer_ = nullptr;
412     }
413   }
414   download_active_ = false;
415   ErrorCode code =
416       successful ? ErrorCode::kSuccess : ErrorCode::kDownloadTransferError;
417   if (code == ErrorCode::kSuccess) {
418     if (delta_performer_ && !payload_->already_applied)
419       code = delta_performer_->VerifyPayload(payload_->hash, payload_->size);
420     if (code == ErrorCode::kSuccess) {
421       if (payload_ < &install_plan_.payloads.back() &&
422           SystemState::Get()->payload_state()->NextPayload()) {
423         LOG(INFO) << "Incrementing to next payload";
424         // No need to reset if this payload was already applied.
425         if (delta_performer_ && !payload_->already_applied)
426           DeltaPerformer::ResetUpdateProgress(prefs_, false);
427         // Start downloading next payload.
428         bytes_received_previous_payloads_ += payload_->size;
429         payload_++;
430         install_plan_.download_url =
431             SystemState::Get()->payload_state()->GetCurrentUrl();
432         StartDownloading();
433         return;
434       }
435 
436       // All payloads have been applied and verified.
437       if (delegate_)
438         delegate_->DownloadComplete();
439 
440       std::string histogram_output;
441       base::StatisticsRecorder::WriteGraph(
442           "UpdateEngine.DownloadActionChromeos.", &histogram_output);
443       LOG(INFO) << histogram_output;
444     } else {
445       LOG(ERROR) << "Download of " << install_plan_.download_url
446                  << " failed due to payload verification error.";
447       // Delete p2p file, if applicable.
448       if (!p2p_file_id_.empty())
449         CloseP2PSharingFd(true);
450     }
451   }
452 
453   // Write the path to the output pipe if we're successful.
454   if (code == ErrorCode::kSuccess && HasOutputPipe())
455     SetOutputObject(install_plan_);
456   processor_->ActionComplete(this, code);
457 }
458 
TransferTerminated(HttpFetcher * fetcher)459 void DownloadActionChromeos::TransferTerminated(HttpFetcher* fetcher) {
460   if (code_ != ErrorCode::kSuccess) {
461     processor_->ActionComplete(this, code_);
462   } else if (payload_->already_applied) {
463     LOG(INFO) << "TransferTerminated with ErrorCode::kSuccess when the current "
464                  "payload has already applied, treating as TransferComplete.";
465     TransferComplete(fetcher, true);
466   }
467 }
468 
469 }  // namespace chromeos_update_engine
470