blob: b008c28b47a9e64ae3cf9f62fd507f0f3a0ef2d5 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 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 <ctype.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000018#include <dirent.h>
Tao Bao641fa972018-04-25 18:59:40 -070019#include <errno.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Tao Bao641fa972018-04-25 18:59:40 -070028#include <sys/ioctl.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000029#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070030#include <sys/types.h>
31#include <sys/wait.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070032#include <time.h>
33#include <unistd.h>
34
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080036#include <limits>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tianjie Xu284752e2017-12-05 11:04:17 -080042#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080043#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/parseint.h>
45#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070046#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080047#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070048#include <brotli/decode.h>
Tao Bao641fa972018-04-25 18:59:40 -070049#include <fec/io.h>
Tao Bao51412212016-12-28 14:44:05 -080050#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070051#include <private/android_filesystem_config.h>
Tianjie Xu69ffa152018-08-01 16:40:00 -070052#include <verity/hash_tree_builder.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070053#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070054
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070055#include "edify/expr.h"
Yifan Hong63f52602019-01-11 13:52:33 -080056#include "otautil/dirutil.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070057#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070058#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070059#include "otautil/print_sha1.h"
60#include "otautil/rangeset.h"
Tao Baoc3901232018-05-21 16:05:56 -070061#include "private/commands.h"
Tao Bao8f237572017-03-26 13:36:49 -070062#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070063#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070064
Sami Tolvanene82fa182015-06-10 15:58:12 +000065// Set this to 0 to interpret 'erase' transfers to mean do a
66// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
67// erase to mean fill the region with zeroes.
68#define DEBUG_ERASE 0
69
Tao Bao51412212016-12-28 14:44:05 -080070static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080071static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
72static constexpr mode_t STASH_FILE_MODE = 0600;
Yifan Hong8ff84d72018-12-19 16:21:55 -080073static constexpr mode_t MARKER_DIRECTORY_MODE = 0700;
Sami Tolvanen90221202014-12-09 16:39:47 +000074
Tianjie Xu16255832016-04-30 11:49:59 -070075static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070076static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070077static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070078
Tianjie Xu284752e2017-12-05 11:04:17 -080079static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070080 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080081 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
82 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
83 }
84}
85
86// Parse the last command index of the last update and save the result to |last_command_index|.
87// Return true if we successfully read the index.
Tao Bao26efb0a2018-05-21 14:59:55 -070088static bool ParseLastCommandFile(size_t* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070089 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080090 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
91 if (fd == -1) {
92 if (errno != ENOENT) {
93 PLOG(ERROR) << "Failed to open " << last_command_file;
94 return false;
95 }
96
97 LOG(INFO) << last_command_file << " doesn't exist.";
98 return false;
99 }
100
101 // Now that the last_command file exists, parse the last command index of previous update.
102 std::string content;
103 if (!android::base::ReadFdToString(fd.get(), &content)) {
104 LOG(ERROR) << "Failed to read: " << last_command_file;
105 return false;
106 }
107
108 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
109 if (lines.size() != 2) {
110 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
111 return false;
112 }
113
Tom Cherry04e4afb2018-10-05 14:37:13 -0700114 if (!android::base::ParseUint(lines[0], last_command_index)) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800115 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
116 return false;
117 }
118
119 return true;
120}
121
Tao Bao864c6682018-05-07 11:38:25 -0700122static bool FsyncDir(const std::string& dirname) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700123 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
Tao Bao864c6682018-05-07 11:38:25 -0700124 if (dfd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700125 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700126 PLOG(ERROR) << "Failed to open " << dirname;
127 return false;
128 }
129 if (fsync(dfd) == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700130 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Bao864c6682018-05-07 11:38:25 -0700131 PLOG(ERROR) << "Failed to fsync " << dirname;
132 return false;
133 }
134 return true;
135}
136
Tianjie Xuc2b2bb52018-05-15 15:09:59 -0700137// Update the last executed command index in the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -0700138static bool UpdateLastCommandIndex(size_t command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700139 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800140 std::string last_command_tmp = last_command_file + ".tmp";
141 std::string content = std::to_string(command_index) + "\n" + command_string;
142 android::base::unique_fd wfd(
143 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
144 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
145 PLOG(ERROR) << "Failed to update last command";
146 return false;
147 }
148
149 if (fsync(wfd) == -1) {
150 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
151 return false;
152 }
153
154 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
155 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
156 return false;
157 }
158
159 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
160 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
161 return false;
162 }
163
Tao Bao864c6682018-05-07 11:38:25 -0700164 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800165 return false;
166 }
167
Tao Bao864c6682018-05-07 11:38:25 -0700168 return true;
169}
170
Yifan Hong8ff84d72018-12-19 16:21:55 -0800171bool SetUpdatedMarker(const std::string& marker) {
172 auto dirname = android::base::Dirname(marker);
173 auto res = mkdir(dirname.c_str(), MARKER_DIRECTORY_MODE);
174 if (res == -1 && errno != EEXIST) {
175 PLOG(ERROR) << "Failed to create directory for marker: " << dirname;
176 return false;
177 }
178
Tao Bao864c6682018-05-07 11:38:25 -0700179 if (!android::base::WriteStringToFile("", marker)) {
180 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800181 return false;
182 }
Yifan Hong8ff84d72018-12-19 16:21:55 -0800183 if (!FsyncDir(dirname)) {
Tao Bao864c6682018-05-07 11:38:25 -0700184 return false;
185 }
Yifan Hong8ff84d72018-12-19 16:21:55 -0800186 LOG(INFO) << "Wrote updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800187 return true;
188}
189
Yifan Hong363d6242019-01-04 11:14:19 -0800190static bool discard_blocks(int fd, off64_t offset, uint64_t size, bool force = false) {
191 // Don't discard blocks unless the update is a retry run or force == true
192 if (!is_retry && !force) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700193 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700194 }
195
196 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
197 if (ioctl(fd, BLKDISCARD, &args) == -1) {
Yifan Hong363d6242019-01-04 11:14:19 -0800198 // On devices that does not support BLKDISCARD, ignore the error.
199 if (errno == EOPNOTSUPP) {
200 return true;
201 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700202 PLOG(ERROR) << "BLKDISCARD ioctl failed";
203 return false;
204 }
205 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700206}
207
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700208static bool check_lseek(int fd, off64_t offset, int whence) {
209 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
210 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700211 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800212 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700213 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700214 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700215 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700216}
217
Tao Baode3bbb82018-05-30 16:14:14 -0700218static void allocate(size_t size, std::vector<uint8_t>* buffer) {
219 // If the buffer's big enough, reuse it.
220 if (size <= buffer->size()) return;
221 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700222}
223
Tao Bao60a70af2017-03-26 14:03:52 -0700224/**
225 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
226 * given RangeSet.
227 */
228class RangeSinkWriter {
229 public:
230 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700231 : fd_(fd),
232 tgt_(tgt),
233 next_range_(0),
234 current_range_left_(0),
235 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700236 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700237 };
Tao Bao0940fe12015-08-27 16:41:21 -0700238
Tao Bao60a70af2017-03-26 14:03:52 -0700239 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700240 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700241 }
242
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700243 size_t AvailableSpace() const {
244 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
245 }
246
247 // Return number of bytes written; and 0 indicates a writing failure.
248 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700249 if (Finished()) {
250 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
251 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700252 }
253
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700254 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700255 while (size > 0) {
256 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700257 if (!SeekToOutputRange()) {
258 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700259 }
Tao Baof7eb7602017-03-27 15:12:48 -0700260
Tao Bao60a70af2017-03-26 14:03:52 -0700261 size_t write_now = size;
262 if (current_range_left_ < write_now) {
263 write_now = current_range_left_;
264 }
Tao Baof7eb7602017-03-27 15:12:48 -0700265
Tianjie Xu22f11202018-08-27 10:50:31 -0700266 if (!android::base::WriteFully(fd_, data, write_now)) {
267 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
268 PLOG(ERROR) << "Failed to write " << write_now << " bytes of data";
Tao Baof7eb7602017-03-27 15:12:48 -0700269 break;
270 }
Tao Bao60a70af2017-03-26 14:03:52 -0700271
272 data += write_now;
273 size -= write_now;
274
275 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700276 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700277 }
Tao Bao60a70af2017-03-26 14:03:52 -0700278
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700279 bytes_written_ += written;
280 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700281 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700282
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700283 size_t BytesWritten() const {
284 return bytes_written_;
285 }
286
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700287 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700288 // Set up the output cursor, move to next range if needed.
289 bool SeekToOutputRange() {
290 // We haven't finished the current range yet.
291 if (current_range_left_ != 0) {
292 return true;
293 }
294 // We can't write any more; let the write function return how many bytes have been written
295 // so far.
296 if (next_range_ >= tgt_.size()) {
297 return false;
298 }
299
300 const Range& range = tgt_[next_range_];
301 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
302 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
303 next_range_++;
304
305 if (!discard_blocks(fd_, offset, current_range_left_)) {
306 return false;
307 }
308 if (!check_lseek(fd_, offset, SEEK_SET)) {
309 return false;
310 }
311 return true;
312 }
313
314 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700315 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700316 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700317 const RangeSet& tgt_;
318 // The next range that we should write to.
319 size_t next_range_;
320 // The number of bytes to write before moving to the next range.
321 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700322 // Total bytes written by the writer.
323 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700324};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700325
Tao Bao60a70af2017-03-26 14:03:52 -0700326/**
327 * All of the data for all the 'new' transfers is contained in one file in the update package,
328 * concatenated together in the order in which transfers.list will need it. We want to stream it out
329 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
330 * section until it's that transfer's turn to go.
331 *
332 * To achieve this, we expand the new data from the archive in a background thread, and block that
333 * threads 'receive uncompressed data' function until the main thread has reached a point where we
334 * want some new data to be written. We signal the background thread with the destination for the
335 * data and block the main thread, waiting for the background thread to complete writing that
336 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
337 * transfer.
338 *
339 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
340 * the main thread wants some data written, it sets writer to the destination location and signals
341 * the condition. When the background thread is done writing, it clears writer and signals the
342 * condition again.
343 */
Tao Bao0940fe12015-08-27 16:41:21 -0700344struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700345 ZipArchiveHandle za;
346 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700347 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700348
Tianjie Xu107a34f2017-06-29 17:04:21 -0700349 std::unique_ptr<RangeSinkWriter> writer;
350 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700351 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700352
Tao Bao60a70af2017-03-26 14:03:52 -0700353 pthread_mutex_t mu;
354 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700355};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700356
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700357static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700358 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700359
Tao Bao60a70af2017-03-26 14:03:52 -0700360 while (size > 0) {
361 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
362 pthread_mutex_lock(&nti->mu);
363 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700364 // End the new data receiver if we encounter an error when performing block image update.
365 if (!nti->receiver_available) {
366 pthread_mutex_unlock(&nti->mu);
367 return false;
368 }
Tao Bao60a70af2017-03-26 14:03:52 -0700369 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700370 }
Tao Bao60a70af2017-03-26 14:03:52 -0700371 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700372
Tao Bao60a70af2017-03-26 14:03:52 -0700373 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
374 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700375 size_t write_now = std::min(size, nti->writer->AvailableSpace());
376 if (nti->writer->Write(data, write_now) != write_now) {
377 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700378 return false;
379 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700380
381 data += write_now;
382 size -= write_now;
383
384 if (nti->writer->Finished()) {
385 // We have written all the bytes desired by this writer.
386
387 pthread_mutex_lock(&nti->mu);
388 nti->writer = nullptr;
389 pthread_cond_broadcast(&nti->cv);
390 pthread_mutex_unlock(&nti->mu);
391 }
392 }
393
394 return true;
395}
396
397static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
398 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
399
400 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
401 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
402 pthread_mutex_lock(&nti->mu);
403 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700404 // End the receiver if we encounter an error when performing block image update.
405 if (!nti->receiver_available) {
406 pthread_mutex_unlock(&nti->mu);
407 return false;
408 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700409 pthread_cond_wait(&nti->cv, &nti->mu);
410 }
411 pthread_mutex_unlock(&nti->mu);
412
413 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
414 // disappear from nti.
415
416 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
417 if (buffer_size == 0) {
418 LOG(ERROR) << "No space left in output range";
419 return false;
420 }
421 uint8_t buffer[buffer_size];
422 size_t available_in = size;
423 size_t available_out = buffer_size;
424 uint8_t* next_out = buffer;
425
426 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
427 BrotliDecoderResult result = BrotliDecoderDecompressStream(
428 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
429
430 if (result == BROTLI_DECODER_RESULT_ERROR) {
431 LOG(ERROR) << "Decompression failed with "
432 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
433 return false;
434 }
435
436 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
437 << size - available_in << ", decoder status " << result;
438
439 size_t write_now = buffer_size - available_out;
440 if (nti->writer->Write(buffer, write_now) != write_now) {
441 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
442 return false;
443 }
444
445 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
446 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700447
448 if (nti->writer->Finished()) {
449 // We have written all the bytes desired by this writer.
450
451 pthread_mutex_lock(&nti->mu);
452 nti->writer = nullptr;
453 pthread_cond_broadcast(&nti->cv);
454 pthread_mutex_unlock(&nti->mu);
455 }
456 }
457
458 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700459}
460
461static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700462 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700463 if (nti->brotli_compressed) {
464 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
465 } else {
466 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
467 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700468 pthread_mutex_lock(&nti->mu);
469 nti->receiver_available = false;
470 if (nti->writer != nullptr) {
471 pthread_cond_broadcast(&nti->cv);
472 }
473 pthread_mutex_unlock(&nti->mu);
474 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700475}
476
Tao Baode3bbb82018-05-30 16:14:14 -0700477static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700478 size_t p = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700479 for (const auto& [begin, end] : src) {
480 if (!check_lseek(fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700481 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000482 }
483
Tao Bao43bfa6e2018-08-28 10:09:13 -0700484 size_t size = (end - begin) * BLOCKSIZE;
Tianjie Xu22f11202018-08-27 10:50:31 -0700485 if (!android::base::ReadFully(fd, buffer->data() + p, size)) {
486 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
487 PLOG(ERROR) << "Failed to read " << size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700488 return -1;
489 }
490
491 p += size;
492 }
493
494 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000495}
496
Tao Bao612336d2015-08-27 16:41:21 -0700497static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700498 size_t written = 0;
Tao Bao43bfa6e2018-08-28 10:09:13 -0700499 for (const auto& [begin, end] : tgt) {
500 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
501 size_t size = (end - begin) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700502 if (!discard_blocks(fd, offset, size)) {
503 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000504 }
505
Tao Bao60a70af2017-03-26 14:03:52 -0700506 if (!check_lseek(fd, offset, SEEK_SET)) {
507 return -1;
508 }
509
Tianjie Xu22f11202018-08-27 10:50:31 -0700510 if (!android::base::WriteFully(fd, buffer.data() + written, size)) {
511 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
512 PLOG(ERROR) << "Failed to write " << size << " bytes of data";
Tao Bao60a70af2017-03-26 14:03:52 -0700513 return -1;
514 }
515
516 written += size;
517 }
518
519 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000520}
521
Tao Baobaad2d42015-12-06 16:56:27 -0800522// Parameters for transfer list command functions
523struct CommandParameters {
524 std::vector<std::string> tokens;
525 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700526 std::string cmdname;
527 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800528 std::string freestash;
529 std::string stashbase;
530 bool canwrite;
531 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700532 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800533 bool foundwrites;
534 bool isunresumable;
535 int version;
536 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700537 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800538 NewThreadInfo nti;
539 pthread_t thread;
540 std::vector<uint8_t> buffer;
541 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800542 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800543};
544
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000545// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
546// handled separately).
547static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
548 const std::vector<uint8_t>& buffer) {
549 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000550 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
551 params.tokens[0] == "imgdiff");
552
553 size_t pos = 0;
554 // Command example:
555 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
556 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
557 // [<loc_range> <stashed_blocks>]
558 if (params.tokens[0] == "move") {
559 // src_range for move starts at the 4th position.
560 if (params.tokens.size() < 5) {
561 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
562 return;
563 }
564 pos = 4;
565 } else {
566 // src_range for diff starts at the 7th position.
567 if (params.tokens.size() < 8) {
568 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
569 return;
570 }
571 pos = 7;
572 }
573
574 // Source blocks in stash only, no work to do.
575 if (params.tokens[pos] == "-") {
576 return;
577 }
578
Tao Bao8f237572017-03-26 13:36:49 -0700579 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700580 if (!src) {
581 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
582 return;
583 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000584
585 RangeSet locs;
586 // If there's no stashed blocks, content in the buffer is consecutive and has the same
587 // order as the source blocks.
588 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700589 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000590 } else {
591 // Otherwise, the next token is the offset of the source blocks in the target range.
592 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
593 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
594 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700595 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700596 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000597 }
598
Tao Baobf5b77d2017-03-30 16:57:29 -0700599 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
600 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700601 size_t block_num = src.GetBlockNumber(i);
602 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000603 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
604
605 uint8_t digest[SHA_DIGEST_LENGTH];
606 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
607 std::string hexdigest = print_sha1(digest);
608 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
609 }
610}
611
612// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
613// in hex for each block.
614static void PrintHashForCorruptedStashedBlocks(const std::string& id,
615 const std::vector<uint8_t>& buffer,
616 const RangeSet& src) {
617 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700618 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000619
Tao Baobf5b77d2017-03-30 16:57:29 -0700620 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700621 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000622
623 uint8_t digest[SHA_DIGEST_LENGTH];
624 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
625 std::string hexdigest = print_sha1(digest);
626 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
627 }
628}
629
630// If the stash file doesn't exist, read the source blocks this stash contains and print the
631// SHA-1 for these blocks.
632static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
633 if (stash_map.find(id) == stash_map.end()) {
634 LOG(ERROR) << "No stash saved for id: " << id;
635 return;
636 }
637
638 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
639 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700640 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700641 if (ReadBlocks(src, &buffer, fd) == -1) {
642 LOG(ERROR) << "failed to read source blocks for stash: " << id;
643 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000644 }
645 PrintHashForCorruptedStashedBlocks(id, buffer, src);
646}
647
Tao Bao612336d2015-08-27 16:41:21 -0700648static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700649 const size_t blocks, bool printerror) {
650 uint8_t digest[SHA_DIGEST_LENGTH];
651 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000652
Tao Baode3bbb82018-05-30 16:14:14 -0700653 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000654
Tao Baode3bbb82018-05-30 16:14:14 -0700655 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000656
Tao Baode3bbb82018-05-30 16:14:14 -0700657 if (hexdigest != expected) {
658 if (printerror) {
659 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
660 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000661 }
Tao Baode3bbb82018-05-30 16:14:14 -0700662 return -1;
663 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000664
Tao Baode3bbb82018-05-30 16:14:14 -0700665 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000666}
667
Tao Bao0940fe12015-08-27 16:41:21 -0700668static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700669 const std::string& postfix) {
670 if (base.empty()) {
671 return "";
672 }
Tao Bao864c6682018-05-07 11:38:25 -0700673 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
674 if (id.empty() && postfix.empty()) {
675 return filename;
676 }
677 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000678}
679
Tao Baoec8272f2017-03-15 17:39:01 -0700680// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
681// directory and continues despite of errors. Calls the 'callback' function for each file.
682static void EnumerateStash(const std::string& dirname,
683 const std::function<void(const std::string&)>& callback) {
684 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000685
Tao Baoec8272f2017-03-15 17:39:01 -0700686 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000687
Tao Baoec8272f2017-03-15 17:39:01 -0700688 if (directory == nullptr) {
689 if (errno != ENOENT) {
690 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000691 }
Tao Bao51412212016-12-28 14:44:05 -0800692 return;
693 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700694
Tao Baoec8272f2017-03-15 17:39:01 -0700695 dirent* item;
696 while ((item = readdir(directory.get())) != nullptr) {
697 if (item->d_type != DT_REG) continue;
698 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800699 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000700}
701
702// Deletes the stash directory and all files in it. Assumes that it only
703// contains files. There is nothing we can do about unlikely, but possible
704// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700705static void DeleteFile(const std::string& fn) {
706 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707
Tao Baoec8272f2017-03-15 17:39:01 -0700708 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000709
Tao Baoec8272f2017-03-15 17:39:01 -0700710 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
711 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
712 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000713}
714
Tao Baoe6aa3322015-08-05 15:20:27 -0700715static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700716 if (base.empty()) return;
717
718 LOG(INFO) << "deleting stash " << base;
719
720 std::string dirname = GetStashFileName(base, "", "");
721 EnumerateStash(dirname, DeleteFile);
722
723 if (rmdir(dirname.c_str()) == -1) {
724 if (errno != ENOENT && errno != ENOTDIR) {
725 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000726 }
Tao Baoec8272f2017-03-15 17:39:01 -0700727 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000728}
729
Tao Baode3bbb82018-05-30 16:14:14 -0700730static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
731 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700732 // In verify mode, if source range_set was saved for the given hash, check contents in the source
733 // blocks first. If the check fails, search for the stashed files on /cache as usual.
734 if (!params.canwrite) {
735 if (stash_map.find(id) != stash_map.end()) {
736 const RangeSet& src = stash_map[id];
737 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700738
Tao Baobf5b77d2017-03-30 16:57:29 -0700739 if (ReadBlocks(src, buffer, params.fd) == -1) {
740 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700741 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700742 }
Tao Baode3bbb82018-05-30 16:14:14 -0700743 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700744 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu3c5958f2018-03-09 14:10:25 -0800745 if (!is_retry) {
746 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
747 }
Tao Bao0940fe12015-08-27 16:41:21 -0700748 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700749 }
750 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000751 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700752 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000753
Tao Baobf5b77d2017-03-30 16:57:29 -0700754 std::string fn = GetStashFileName(params.stashbase, id, "");
755
756 struct stat sb;
757 if (stat(fn.c_str(), &sb) == -1) {
758 if (errno != ENOENT || printnoent) {
759 PLOG(ERROR) << "stat \"" << fn << "\" failed";
760 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000761 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700762 return -1;
763 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000764
Tao Baobf5b77d2017-03-30 16:57:29 -0700765 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000766
Tao Baobf5b77d2017-03-30 16:57:29 -0700767 if ((sb.st_size % BLOCKSIZE) != 0) {
768 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
769 return -1;
770 }
771
Tianjie Xu22f11202018-08-27 10:50:31 -0700772 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY)));
Tao Baobf5b77d2017-03-30 16:57:29 -0700773 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700774 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 PLOG(ERROR) << "open \"" << fn << "\" failed";
776 return -1;
777 }
778
779 allocate(sb.st_size, buffer);
780
Tianjie Xu22f11202018-08-27 10:50:31 -0700781 if (!android::base::ReadFully(fd, buffer->data(), sb.st_size)) {
782 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
783 PLOG(ERROR) << "Failed to read " << sb.st_size << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -0700784 return -1;
785 }
786
Tao Bao64957ce2018-05-30 16:21:39 -0700787 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700788 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700789 LOG(ERROR) << "unexpected contents in " << fn;
790 if (stash_map.find(id) == stash_map.end()) {
791 LOG(ERROR) << "failed to find source blocks number for stash " << id
792 << " when executing command: " << params.cmdname;
793 } else {
794 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700795 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000796 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700797 DeleteFile(fn);
798 return -1;
799 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000800
Tao Baobf5b77d2017-03-30 16:57:29 -0700801 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000802}
803
Tao Bao612336d2015-08-27 16:41:21 -0700804static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700805 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
806 if (base.empty()) {
807 return -1;
808 }
809
Tao Bao5ee25662018-07-11 15:55:32 -0700810 if (checkspace && !CheckAndFreeSpaceOnCache(blocks * BLOCKSIZE)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700811 LOG(ERROR) << "not enough space to write stash";
812 return -1;
813 }
814
815 std::string fn = GetStashFileName(base, id, ".partial");
816 std::string cn = GetStashFileName(base, id, "");
817
818 if (exists) {
819 struct stat sb;
820 int res = stat(cn.c_str(), &sb);
821
822 if (res == 0) {
823 // The file already exists and since the name is the hash of the contents,
824 // it's safe to assume the contents are identical (accidental hash collisions
825 // are unlikely)
826 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
827 *exists = true;
828 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000829 }
830
Tao Baode3bbb82018-05-30 16:14:14 -0700831 *exists = false;
832 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000833
Tao Baode3bbb82018-05-30 16:14:14 -0700834 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000835
Tao Baode3bbb82018-05-30 16:14:14 -0700836 android::base::unique_fd fd(
Tianjie Xu22f11202018-08-27 10:50:31 -0700837 TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Tao Baode3bbb82018-05-30 16:14:14 -0700838 if (fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -0700839 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700840 PLOG(ERROR) << "failed to create \"" << fn << "\"";
841 return -1;
842 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100843
Tao Baode3bbb82018-05-30 16:14:14 -0700844 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
845 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
846 return -1;
847 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100848
Tianjie Xu22f11202018-08-27 10:50:31 -0700849 if (!android::base::WriteFully(fd, buffer.data(), blocks * BLOCKSIZE)) {
850 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
851 PLOG(ERROR) << "Failed to write " << blocks * BLOCKSIZE << " bytes of data";
Tao Baode3bbb82018-05-30 16:14:14 -0700852 return -1;
853 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100854
Tianjie Xu22f11202018-08-27 10:50:31 -0700855 if (fsync(fd) == -1) {
856 failure_type = errno == EIO ? kEioFailure : kFsyncFailure;
Tao Baode3bbb82018-05-30 16:14:14 -0700857 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
858 return -1;
859 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
Tao Baode3bbb82018-05-30 16:14:14 -0700861 if (rename(fn.c_str(), cn.c_str()) == -1) {
862 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
863 return -1;
864 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000865
Tao Baode3bbb82018-05-30 16:14:14 -0700866 std::string dname = GetStashFileName(base, "", "");
867 if (!FsyncDir(dname)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700868 return -1;
869 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700870
Tao Baode3bbb82018-05-30 16:14:14 -0700871 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000872}
873
874// Creates a directory for storing stash files and checks if the /cache partition
875// hash enough space for the expected amount of blocks we need to store. Returns
876// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700877static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800878 std::string dirname = GetStashFileName(base, "", "");
879 struct stat sb;
880 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800881 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800882 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800883 strerror(errno));
884 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700885 }
886
887 size_t max_stash_size = maxblocks * BLOCKSIZE;
888 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800889 LOG(INFO) << "creating stash " << dirname;
Yifan Hong63f52602019-01-11 13:52:33 -0800890 res = mkdir_recursively(dirname, STASH_DIRECTORY_MODE, false, nullptr);
Tao Bao51412212016-12-28 14:44:05 -0800891
892 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800893 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800894 strerror(errno));
895 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000896 }
897
Tianjie Xua946b9e2017-03-21 16:24:57 -0700898 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800899 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700900 strerror(errno));
901 return -1;
902 }
903
Tao Bao5ee25662018-07-11 15:55:32 -0700904 if (!CheckAndFreeSpaceOnCache(max_stash_size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800905 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800906 max_stash_size);
907 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000908 }
909
Tao Bao51412212016-12-28 14:44:05 -0800910 return 1; // Created directory
911 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000912
Tao Bao51412212016-12-28 14:44:05 -0800913 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000914
Tao Baoec8272f2017-03-15 17:39:01 -0700915 // If the directory already exists, calculate the space already allocated to stash files and check
916 // if there's enough for all required blocks. Delete any partially completed stash files first.
917 EnumerateStash(dirname, [](const std::string& fn) {
918 if (android::base::EndsWith(fn, ".partial")) {
919 DeleteFile(fn);
920 }
921 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000922
Tao Bao51412212016-12-28 14:44:05 -0800923 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700924 EnumerateStash(dirname, [&existing](const std::string& fn) {
925 if (fn.empty()) return;
926 struct stat sb;
927 if (stat(fn.c_str(), &sb) == -1) {
928 PLOG(ERROR) << "stat \"" << fn << "\" failed";
929 return;
930 }
931 existing += static_cast<size_t>(sb.st_size);
932 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000933
Tao Bao51412212016-12-28 14:44:05 -0800934 if (max_stash_size > existing) {
935 size_t needed = max_stash_size - existing;
Tao Bao5ee25662018-07-11 15:55:32 -0700936 if (!CheckAndFreeSpaceOnCache(needed)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800937 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800938 needed);
939 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000940 }
Tao Bao51412212016-12-28 14:44:05 -0800941 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000942
Tao Bao51412212016-12-28 14:44:05 -0800943 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000944}
945
Tao Baobaad2d42015-12-06 16:56:27 -0800946static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700947 if (base.empty() || id.empty()) {
948 return -1;
949 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000950
Tao Baoec8272f2017-03-15 17:39:01 -0700951 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000952
Tao Baoec8272f2017-03-15 17:39:01 -0700953 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700954}
955
Tao Baobf5b77d2017-03-30 16:57:29 -0700956// Source contains packed data, which we want to move to the locations given in locs in the dest
957// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700958static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700959 const std::vector<uint8_t>& source) {
960 const uint8_t* from = source.data();
961 uint8_t* to = dest.data();
962 size_t start = locs.blocks();
963 // Must do the movement backward.
964 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
965 size_t blocks = it->second - it->first;
966 start -= blocks;
967 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
968 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700969}
970
Tao Baod2aecd42017-03-23 14:43:44 -0700971/**
972 * We expect to parse the remainder of the parameter tokens as one of:
973 *
974 * <src_block_count> <src_range>
975 * (loads data from source image only)
976 *
977 * <src_block_count> - <[stash_id:stash_range] ...>
978 * (loads data from stashes only)
979 *
980 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
981 * (loads data from both source image and stashes)
982 *
983 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
984 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
985 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
986 * LoadStash.
987 */
988static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
989 bool* overlap) {
990 CHECK(src_blocks != nullptr);
991 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700992
Tao Baod2aecd42017-03-23 14:43:44 -0700993 // <src_block_count>
994 const std::string& token = params.tokens[params.cpos++];
995 if (!android::base::ParseUint(token, src_blocks)) {
996 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
997 return -1;
998 }
Tao Baobaad2d42015-12-06 16:56:27 -0800999
Tao Baode3bbb82018-05-30 16:14:14 -07001000 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -07001001
1002 // "-" or <src_range> [<src_loc>]
1003 if (params.tokens[params.cpos] == "-") {
1004 // no source ranges, only stashes
1005 params.cpos++;
1006 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001007 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001008 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001009 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001010
Tao Baode3bbb82018-05-30 16:14:14 -07001011 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001012 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001013 }
1014
Tao Baod2aecd42017-03-23 14:43:44 -07001015 if (params.cpos >= params.tokens.size()) {
1016 // no stashes, only source range
1017 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001018 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001019
Tao Bao8f237572017-03-26 13:36:49 -07001020 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001021 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001022 MoveRange(params.buffer, locs, params.buffer);
1023 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001024
Tao Baod2aecd42017-03-23 14:43:44 -07001025 // <[stash_id:stash_range]>
1026 while (params.cpos < params.tokens.size()) {
1027 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1028 // in the source block that stashed data should go.
1029 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1030 if (tokens.size() != 2) {
1031 LOG(ERROR) << "invalid parameter";
1032 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001033 }
1034
Tao Baod2aecd42017-03-23 14:43:44 -07001035 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001036 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001037 // These source blocks will fail verification if used later, but we
1038 // will let the caller decide if this is a fatal failure
1039 LOG(ERROR) << "failed to load stash " << tokens[0];
1040 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001041 }
1042
Tao Bao8f237572017-03-26 13:36:49 -07001043 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001044 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001045 MoveRange(params.buffer, locs, stash);
1046 }
1047
1048 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001049}
1050
Tao Bao33567772017-03-13 14:57:34 -07001051/**
1052 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1053 *
1054 * We expect to parse the remainder of the parameter tokens as one of:
1055 *
1056 * <tgt_range> <src_block_count> <src_range>
1057 * (loads data from source image only)
1058 *
1059 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1060 * (loads data from stashes only)
1061 *
1062 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1063 * (loads data from both source image and stashes)
1064 *
Tao Baod2aecd42017-03-23 14:43:44 -07001065 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1066 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001067 * verification fails in a way that the update cannot be resumed anymore.
1068 *
1069 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1070 * the return value is -1 and the command should be aborted.
1071 *
1072 * If the return value is 1, the command has already been completed according to the contents of the
1073 * target blocks, and should not be performed again.
1074 *
1075 * If the return value is 0, source blocks have expected content and the command can be performed.
1076 */
Tao Baode3bbb82018-05-30 16:14:14 -07001077static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001078 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001079 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001080
Tao Baod2aecd42017-03-23 14:43:44 -07001081 if (params.cpos >= params.tokens.size()) {
1082 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001083 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001084 }
1085
1086 std::string srchash = params.tokens[params.cpos++];
1087 std::string tgthash;
1088
1089 if (onehash) {
1090 tgthash = srchash;
1091 } else {
1092 if (params.cpos >= params.tokens.size()) {
1093 LOG(ERROR) << "missing target hash";
1094 return -1;
1095 }
1096 tgthash = params.tokens[params.cpos++];
1097 }
1098
1099 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1100 // "-"/<src_range>.
1101 if (params.cpos + 2 >= params.tokens.size()) {
1102 LOG(ERROR) << "invalid parameters";
1103 return -1;
1104 }
1105
1106 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001107 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1108 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001109
Tao Baode3bbb82018-05-30 16:14:14 -07001110 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1111 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001112 return -1;
1113 }
1114
1115 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001116 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001117 return 1;
1118 }
1119
1120 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001121 bool overlap = false;
1122 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001123 return -1;
1124 }
1125
1126 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001127 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1128 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1129 // overwritten.
1130 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001131 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1132
1133 bool stash_exists = false;
1134 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1135 &stash_exists) != 0) {
1136 LOG(ERROR) << "failed to stash overlapping source blocks";
1137 return -1;
1138 }
1139
1140 params.stashed += *src_blocks;
1141 // Can be deleted when the write has completed.
1142 if (!stash_exists) {
1143 params.freestash = srchash;
1144 }
1145 }
1146
1147 // Source blocks have expected content, command can proceed.
1148 return 0;
1149 }
1150
Tao Bao4a135082018-06-07 22:27:44 -07001151 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001152 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1153 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1154 // command.
1155 return 0;
1156 }
1157
1158 // Valid source data not available, update cannot be resumed.
1159 LOG(ERROR) << "partition has unexpected contents";
1160 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1161
1162 params.isunresumable = true;
1163
1164 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001165}
1166
Tao Bao0940fe12015-08-27 16:41:21 -07001167static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001168 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001169 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001170 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001171
Tao Bao33567772017-03-13 14:57:34 -07001172 if (status == -1) {
1173 LOG(ERROR) << "failed to read blocks for move";
1174 return -1;
1175 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001176
Tao Bao33567772017-03-13 14:57:34 -07001177 if (status == 0) {
1178 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001179 } else {
1180 params.target_verified = true;
1181 if (params.foundwrites) {
1182 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1183 }
Tao Bao33567772017-03-13 14:57:34 -07001184 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001185
Tao Bao33567772017-03-13 14:57:34 -07001186 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001187 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001188 LOG(INFO) << " moving " << blocks << " blocks";
1189
1190 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1191 return -1;
1192 }
1193 } else {
1194 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001195 }
Tao Bao33567772017-03-13 14:57:34 -07001196 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001197
Tao Bao33567772017-03-13 14:57:34 -07001198 if (!params.freestash.empty()) {
1199 FreeStash(params.stashbase, params.freestash);
1200 params.freestash.clear();
1201 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Baobf5b77d2017-03-30 16:57:29 -07001203 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001204
Tao Bao33567772017-03-13 14:57:34 -07001205 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001206}
1207
Tao Bao0940fe12015-08-27 16:41:21 -07001208static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001209 // <stash_id> <src_range>
1210 if (params.cpos + 1 >= params.tokens.size()) {
1211 LOG(ERROR) << "missing id and/or src range fields in stash command";
1212 return -1;
1213 }
1214
1215 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001216 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001217 // Stash file already exists and has expected contents. Do not read from source again, as the
1218 // source may have been already overwritten during a previous attempt.
1219 return 0;
1220 }
1221
Tao Bao8f237572017-03-26 13:36:49 -07001222 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001223 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001224
Tao Bao64957ce2018-05-30 16:21:39 -07001225 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001226 allocate(blocks * BLOCKSIZE, &params.buffer);
1227 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001228 return -1;
1229 }
Tao Baobcf46492017-03-23 15:28:20 -07001230 stash_map[id] = src;
1231
1232 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1233 // Source blocks have unexpected contents. If we actually need this data later, this is an
1234 // unrecoverable error. However, the command that uses the data may have already completed
1235 // previously, so the possible failure will occur during source block verification.
1236 LOG(ERROR) << "failed to load source blocks for stash " << id;
1237 return 0;
1238 }
1239
1240 // In verify mode, we don't need to stash any blocks.
1241 if (!params.canwrite) {
1242 return 0;
1243 }
1244
1245 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001246 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1247 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001248 params.stashed += blocks;
1249 }
1250 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251}
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001254 // <stash_id>
1255 if (params.cpos >= params.tokens.size()) {
1256 LOG(ERROR) << "missing stash id in free command";
1257 return -1;
1258 }
Tao Baobaad2d42015-12-06 16:56:27 -08001259
Tao Baobcf46492017-03-23 15:28:20 -07001260 const std::string& id = params.tokens[params.cpos++];
1261 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001262
Tao Baobcf46492017-03-23 15:28:20 -07001263 if (params.createdstash || params.canwrite) {
1264 return FreeStash(params.stashbase, id);
1265 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001266
Tao Baobcf46492017-03-23 15:28:20 -07001267 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001268}
1269
Tao Bao0940fe12015-08-27 16:41:21 -07001270static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001271 if (params.cpos >= params.tokens.size()) {
1272 LOG(ERROR) << "missing target blocks for zero";
1273 return -1;
1274 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001275
Tao Baobf5b77d2017-03-30 16:57:29 -07001276 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001277 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001278
1279 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1280
Tao Baode3bbb82018-05-30 16:14:14 -07001281 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001282 memset(params.buffer.data(), 0, BLOCKSIZE);
1283
1284 if (params.canwrite) {
Tao Bao43bfa6e2018-08-28 10:09:13 -07001285 for (const auto& [begin, end] : tgt) {
1286 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1287 size_t size = (end - begin) * BLOCKSIZE;
Tao Baobf5b77d2017-03-30 16:57:29 -07001288 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001289 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001290 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001291
Tao Baobf5b77d2017-03-30 16:57:29 -07001292 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1293 return -1;
1294 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001295
Tao Bao43bfa6e2018-08-28 10:09:13 -07001296 for (size_t j = begin; j < end; ++j) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001297 if (!android::base::WriteFully(params.fd, params.buffer.data(), BLOCKSIZE)) {
1298 failure_type = errno == EIO ? kEioFailure : kFwriteFailure;
1299 PLOG(ERROR) << "Failed to write " << BLOCKSIZE << " bytes of data";
Tao Baobf5b77d2017-03-30 16:57:29 -07001300 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001301 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001302 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001303 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001304 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001305
Tao Baobf5b77d2017-03-30 16:57:29 -07001306 if (params.cmdname[0] == 'z') {
1307 // Update only for the zero command, as the erase command will call
1308 // this if DEBUG_ERASE is defined.
1309 params.written += tgt.blocks();
1310 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001311
Tao Baobf5b77d2017-03-30 16:57:29 -07001312 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001313}
1314
Tao Bao0940fe12015-08-27 16:41:21 -07001315static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001316 if (params.cpos >= params.tokens.size()) {
1317 LOG(ERROR) << "missing target blocks for new";
1318 return -1;
1319 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001320
Tao Bao8f237572017-03-26 13:36:49 -07001321 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001322 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001323
1324 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001325 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001326
Tao Bao60a70af2017-03-26 14:03:52 -07001327 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001328 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001329 pthread_cond_broadcast(&params.nti.cv);
1330
1331 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001332 if (!params.nti.receiver_available) {
1333 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1334 << " bytes of new data";
1335 pthread_mutex_unlock(&params.nti.mu);
1336 return -1;
1337 }
Tao Bao60a70af2017-03-26 14:03:52 -07001338 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001339 }
1340
Tao Bao60a70af2017-03-26 14:03:52 -07001341 pthread_mutex_unlock(&params.nti.mu);
1342 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001343
Tao Baobf5b77d2017-03-30 16:57:29 -07001344 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001345
Tao Bao60a70af2017-03-26 14:03:52 -07001346 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001347}
1348
Tao Bao0940fe12015-08-27 16:41:21 -07001349static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001350 // <offset> <length>
1351 if (params.cpos + 1 >= params.tokens.size()) {
1352 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1353 return -1;
1354 }
Tao Bao0940fe12015-08-27 16:41:21 -07001355
Tao Baoc0e1c462017-02-01 10:20:10 -08001356 size_t offset;
1357 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1358 LOG(ERROR) << "invalid patch offset";
1359 return -1;
1360 }
Tao Bao0940fe12015-08-27 16:41:21 -07001361
Tao Baoc0e1c462017-02-01 10:20:10 -08001362 size_t len;
1363 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1364 LOG(ERROR) << "invalid patch len";
1365 return -1;
1366 }
Tao Bao0940fe12015-08-27 16:41:21 -07001367
Tao Baoc0e1c462017-02-01 10:20:10 -08001368 RangeSet tgt;
1369 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001370 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001371
Tao Baoc0e1c462017-02-01 10:20:10 -08001372 if (status == -1) {
1373 LOG(ERROR) << "failed to read blocks for diff";
1374 return -1;
1375 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001376
Tao Baoc0e1c462017-02-01 10:20:10 -08001377 if (status == 0) {
1378 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001379 } else {
1380 params.target_verified = true;
1381 if (params.foundwrites) {
1382 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1383 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001384 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001385
Tao Baoc0e1c462017-02-01 10:20:10 -08001386 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001387 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001388 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001389 Value patch_value(
Tao Bao511d7592018-06-19 15:56:49 -07001390 Value::Type::BLOB,
1391 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001392
Tao Bao60a70af2017-03-26 14:03:52 -07001393 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001394 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001395 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001396 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1397 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001398 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001399 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001400 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001401 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001402 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001403 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001404 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001405 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001406 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001407 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001408 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001409 return -1;
1410 }
1411 }
1412
1413 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001414 if (!writer.Finished()) {
Tao Baoa2cff952018-11-02 15:44:07 -07001415 LOG(ERROR) << "Failed to fully write target blocks (range sink underrun): Missing "
1416 << writer.AvailableSpace() << " bytes";
1417 failure_type = kPatchApplicationFailure;
1418 return -1;
Tao Baoc0e1c462017-02-01 10:20:10 -08001419 }
1420 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001421 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001422 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001423 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001424 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001425
Tao Baoc0e1c462017-02-01 10:20:10 -08001426 if (!params.freestash.empty()) {
1427 FreeStash(params.stashbase, params.freestash);
1428 params.freestash.clear();
1429 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001430
Tao Baobf5b77d2017-03-30 16:57:29 -07001431 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001432
Tao Baoc0e1c462017-02-01 10:20:10 -08001433 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001434}
1435
Tao Bao0940fe12015-08-27 16:41:21 -07001436static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001437 if (DEBUG_ERASE) {
1438 return PerformCommandZero(params);
1439 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001440
Tao Baobf5b77d2017-03-30 16:57:29 -07001441 struct stat sb;
1442 if (fstat(params.fd, &sb) == -1) {
1443 PLOG(ERROR) << "failed to fstat device to erase";
1444 return -1;
1445 }
1446
1447 if (!S_ISBLK(sb.st_mode)) {
1448 LOG(ERROR) << "not a block device; skipping erase";
1449 return -1;
1450 }
1451
1452 if (params.cpos >= params.tokens.size()) {
1453 LOG(ERROR) << "missing target blocks for erase";
1454 return -1;
1455 }
1456
1457 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001458 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001459
1460 if (params.canwrite) {
1461 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1462
Tao Bao43bfa6e2018-08-28 10:09:13 -07001463 for (const auto& [begin, end] : tgt) {
Yifan Hong363d6242019-01-04 11:14:19 -08001464 off64_t offset = static_cast<off64_t>(begin) * BLOCKSIZE;
1465 size_t size = (end - begin) * BLOCKSIZE;
1466 if (!discard_blocks(params.fd, offset, size, true /* force */)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001467 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001468 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001469 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001470 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001471
Tao Baobf5b77d2017-03-30 16:57:29 -07001472 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001473}
1474
Tao Bao91a649a2018-05-21 16:05:56 -07001475static int PerformCommandAbort(CommandParameters&) {
1476 LOG(INFO) << "Aborting as instructed";
1477 return -1;
1478}
1479
Tianjie Xu69ffa152018-08-01 16:40:00 -07001480// Computes the hash_tree bytes based on the parameters, checks if the root hash of the tree
1481// matches the expected hash and writes the result to the specified range on the block_device.
1482// Hash_tree computation arguments:
1483// hash_tree_ranges
1484// source_ranges
1485// hash_algorithm
1486// salt_hex
1487// root_hash
1488static int PerformCommandComputeHashTree(CommandParameters& params) {
1489 if (params.cpos + 5 != params.tokens.size()) {
1490 LOG(ERROR) << "Invaild arguments count in hash computation " << params.cmdline;
1491 return -1;
1492 }
1493
1494 // Expects the hash_tree data to be contiguous.
1495 RangeSet hash_tree_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1496 if (!hash_tree_ranges || hash_tree_ranges.size() != 1) {
1497 LOG(ERROR) << "Invalid hash tree ranges in " << params.cmdline;
1498 return -1;
1499 }
1500
1501 RangeSet source_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1502 if (!source_ranges) {
1503 LOG(ERROR) << "Invalid source ranges in " << params.cmdline;
1504 return -1;
1505 }
1506
1507 auto hash_function = HashTreeBuilder::HashFunction(params.tokens[params.cpos++]);
1508 if (hash_function == nullptr) {
1509 LOG(ERROR) << "Invalid hash algorithm in " << params.cmdline;
1510 return -1;
1511 }
1512
1513 std::vector<unsigned char> salt;
1514 std::string salt_hex = params.tokens[params.cpos++];
1515 if (salt_hex.empty() || !HashTreeBuilder::ParseBytesArrayFromString(salt_hex, &salt)) {
1516 LOG(ERROR) << "Failed to parse salt in " << params.cmdline;
1517 return -1;
1518 }
1519
1520 std::string expected_root_hash = params.tokens[params.cpos++];
1521 if (expected_root_hash.empty()) {
1522 LOG(ERROR) << "Invalid root hash in " << params.cmdline;
1523 return -1;
1524 }
1525
1526 // Starts the hash_tree computation.
1527 HashTreeBuilder builder(BLOCKSIZE, hash_function);
xunchang53158e52019-01-17 09:26:12 -08001528 if (!builder.Initialize(static_cast<int64_t>(source_ranges.blocks()) * BLOCKSIZE, salt)) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001529 LOG(ERROR) << "Failed to initialize hash tree computation, source " << source_ranges.ToString()
1530 << ", salt " << salt_hex;
1531 return -1;
1532 }
1533
1534 // Iterates through every block in the source_ranges and updates the hash tree structure
1535 // accordingly.
Tao Bao43bfa6e2018-08-28 10:09:13 -07001536 for (const auto& [begin, end] : source_ranges) {
Tianjie Xu69ffa152018-08-01 16:40:00 -07001537 uint8_t buffer[BLOCKSIZE];
Tao Bao43bfa6e2018-08-28 10:09:13 -07001538 if (!check_lseek(params.fd, static_cast<off64_t>(begin) * BLOCKSIZE, SEEK_SET)) {
1539 PLOG(ERROR) << "Failed to seek to block: " << begin;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001540 return -1;
1541 }
1542
Tao Bao43bfa6e2018-08-28 10:09:13 -07001543 for (size_t i = begin; i < end; i++) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001544 if (!android::base::ReadFully(params.fd, buffer, BLOCKSIZE)) {
1545 failure_type = errno == EIO ? kEioFailure : kFreadFailure;
Tao Bao43bfa6e2018-08-28 10:09:13 -07001546 LOG(ERROR) << "Failed to read data in " << begin << ":" << end;
Tianjie Xu69ffa152018-08-01 16:40:00 -07001547 return -1;
1548 }
1549
1550 if (!builder.Update(reinterpret_cast<unsigned char*>(buffer), BLOCKSIZE)) {
1551 LOG(ERROR) << "Failed to update hash tree builder";
1552 return -1;
1553 }
1554 }
1555 }
1556
1557 if (!builder.BuildHashTree()) {
1558 LOG(ERROR) << "Failed to build hash tree";
1559 return -1;
1560 }
1561
1562 std::string root_hash_hex = HashTreeBuilder::BytesArrayToString(builder.root_hash());
1563 if (root_hash_hex != expected_root_hash) {
1564 LOG(ERROR) << "Root hash of the verity hash tree doesn't match the expected value. Expected: "
1565 << expected_root_hash << ", actual: " << root_hash_hex;
1566 return -1;
1567 }
1568
1569 uint64_t write_offset = static_cast<uint64_t>(hash_tree_ranges.GetBlockNumber(0)) * BLOCKSIZE;
1570 if (params.canwrite && !builder.WriteHashTreeToFd(params.fd, write_offset)) {
1571 LOG(ERROR) << "Failed to write hash tree to output";
1572 return -1;
1573 }
1574
1575 // TODO(xunchang) validates the written bytes
1576
1577 return 0;
1578}
1579
Tao Baoc3901232018-05-21 16:05:56 -07001580using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001581
Tao Baoc3901232018-05-21 16:05:56 -07001582using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001583
Yifan Hong8ff84d72018-12-19 16:21:55 -08001584static bool Sha1DevicePath(const std::string& path, uint8_t digest[SHA_DIGEST_LENGTH]) {
1585 auto device_name = android::base::Basename(path);
1586 auto dm_target_name_path = "/sys/block/" + device_name + "/dm/name";
1587
1588 struct stat sb;
1589 if (stat(dm_target_name_path.c_str(), &sb) == 0) {
1590 // This is a device mapper target. Use partition name as part of the hash instead. Do not
1591 // include extents as part of the hash, because the size of a partition may be shrunk after
1592 // the patches are applied.
1593 std::string dm_target_name;
1594 if (!android::base::ReadFileToString(dm_target_name_path, &dm_target_name)) {
1595 PLOG(ERROR) << "Cannot read " << dm_target_name_path;
1596 return false;
1597 }
1598 SHA1(reinterpret_cast<const uint8_t*>(dm_target_name.data()), dm_target_name.size(), digest);
1599 return true;
1600 }
1601
1602 if (errno != ENOENT) {
1603 // This is a device mapper target, but its name cannot be retrieved.
1604 PLOG(ERROR) << "Cannot get dm target name for " << path;
1605 return false;
1606 }
1607
1608 // This doesn't appear to be a device mapper target, but if its name starts with dm-, something
1609 // else might have gone wrong.
1610 if (android::base::StartsWith(device_name, "dm-")) {
1611 LOG(WARNING) << "Device " << path << " starts with dm- but is not mapped by device-mapper.";
1612 }
1613
1614 // Stash directory should be different for each partition to avoid conflicts when updating
1615 // multiple partitions at the same time, so we use the hash of the block device name as the base
1616 // directory.
1617 SHA1(reinterpret_cast<const uint8_t*>(path.data()), path.size(), digest);
1618 return true;
1619}
1620
Tianjie Xuc4447322017-03-06 14:44:59 -08001621static Value* PerformBlockImageUpdate(const char* name, State* state,
1622 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001623 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001624 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001625 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001626 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001627
Tao Bao33567772017-03-13 14:57:34 -07001628 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1629 if (state->is_retry) {
1630 is_retry = true;
1631 LOG(INFO) << "This update is a retry.";
1632 }
1633 if (argv.size() != 4) {
1634 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1635 argv.size());
1636 return StringValue("");
1637 }
1638
1639 std::vector<std::unique_ptr<Value>> args;
1640 if (!ReadValueArgs(state, argv, &args)) {
1641 return nullptr;
1642 }
1643
Tao Baoc3901232018-05-21 16:05:56 -07001644 // args:
1645 // - block device (or file) to modify in-place
1646 // - transfer list (blob)
1647 // - new data stream (filename within package.zip)
1648 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001649 const std::unique_ptr<Value>& blockdev_filename = args[0];
1650 const std::unique_ptr<Value>& transfer_list_value = args[1];
1651 const std::unique_ptr<Value>& new_data_fn = args[2];
1652 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001653
Tao Bao511d7592018-06-19 15:56:49 -07001654 if (blockdev_filename->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001655 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1656 return StringValue("");
1657 }
Tao Bao511d7592018-06-19 15:56:49 -07001658 if (transfer_list_value->type != Value::Type::BLOB) {
Tao Bao33567772017-03-13 14:57:34 -07001659 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1660 return StringValue("");
1661 }
Tao Bao511d7592018-06-19 15:56:49 -07001662 if (new_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001663 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1664 return StringValue("");
1665 }
Tao Bao511d7592018-06-19 15:56:49 -07001666 if (patch_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001667 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1668 return StringValue("");
1669 }
1670
1671 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1672 if (ui == nullptr) {
1673 return StringValue("");
1674 }
1675
1676 FILE* cmd_pipe = ui->cmd_pipe;
1677 ZipArchiveHandle za = ui->package_zip;
1678
1679 if (cmd_pipe == nullptr || za == nullptr) {
1680 return StringValue("");
1681 }
1682
Elliott Hughesa86dddb2019-05-03 22:52:37 -07001683 std::string_view path_data(patch_data_fn->data);
Tao Bao33567772017-03-13 14:57:34 -07001684 ZipEntry patch_entry;
1685 if (FindEntry(za, path_data, &patch_entry) != 0) {
1686 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1687 return StringValue("");
1688 }
1689
1690 params.patch_start = ui->package_zip_addr + patch_entry.offset;
Elliott Hughesa86dddb2019-05-03 22:52:37 -07001691 std::string_view new_data(new_data_fn->data);
Tao Bao33567772017-03-13 14:57:34 -07001692 ZipEntry new_entry;
1693 if (FindEntry(za, new_data, &new_entry) != 0) {
1694 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1695 return StringValue("");
1696 }
1697
Tianjie Xu22f11202018-08-27 10:50:31 -07001698 params.fd.reset(TEMP_FAILURE_RETRY(open(blockdev_filename->data.c_str(), O_RDWR)));
Tao Bao33567772017-03-13 14:57:34 -07001699 if (params.fd == -1) {
Tianjie Xu22f11202018-08-27 10:50:31 -07001700 failure_type = errno == EIO ? kEioFailure : kFileOpenFailure;
Tao Bao33567772017-03-13 14:57:34 -07001701 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1702 return StringValue("");
1703 }
1704
Tao Bao864c6682018-05-07 11:38:25 -07001705 uint8_t digest[SHA_DIGEST_LENGTH];
Yifan Hong