blob: 96b2d9feb22b8f398f83a60685161618a39719c2 [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"
Tao Baod33b2f82017-09-28 21:29:11 -070056#include "otafault/ota_io.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;
Sami Tolvanen90221202014-12-09 16:39:47 +000073
Tianjie Xu16255832016-04-30 11:49:59 -070074static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070075static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070076static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070077
Tianjie Xu284752e2017-12-05 11:04:17 -080078static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070079 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080080 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
81 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
82 }
83}
84
85// Parse the last command index of the last update and save the result to |last_command_index|.
86// Return true if we successfully read the index.
Tao Bao26efb0a2018-05-21 14:59:55 -070087static bool ParseLastCommandFile(size_t* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070088 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080089 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
90 if (fd == -1) {
91 if (errno != ENOENT) {
92 PLOG(ERROR) << "Failed to open " << last_command_file;
93 return false;
94 }
95
96 LOG(INFO) << last_command_file << " doesn't exist.";
97 return false;
98 }
99
100 // Now that the last_command file exists, parse the last command index of previous update.
101 std::string content;
102 if (!android::base::ReadFdToString(fd.get(), &content)) {
103 LOG(ERROR) << "Failed to read: " << last_command_file;
104 return false;
105 }
106
107 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
108 if (lines.size() != 2) {
109 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
110 return false;
111 }
112
113 if (!android::base::ParseInt(lines[0], last_command_index)) {
114 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
115 return false;
116 }
117
118 return true;
119}
120
Tao Bao864c6682018-05-07 11:38:25 -0700121static bool FsyncDir(const std::string& dirname) {
122 android::base::unique_fd dfd(
123 TEMP_FAILURE_RETRY(ota_open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
124 if (dfd == -1) {
125 failure_type = kFileOpenFailure;
126 PLOG(ERROR) << "Failed to open " << dirname;
127 return false;
128 }
129 if (fsync(dfd) == -1) {
130 failure_type = kFsyncFailure;
131 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
171static bool SetPartitionUpdatedMarker(const std::string& marker) {
172 if (!android::base::WriteStringToFile("", marker)) {
173 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800174 return false;
175 }
Tao Bao864c6682018-05-07 11:38:25 -0700176 if (!FsyncDir(android::base::Dirname(marker))) {
177 return false;
178 }
179 LOG(INFO) << "Wrote partition updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800180 return true;
181}
182
Sami Tolvanen90221202014-12-09 16:39:47 +0000183static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700184 size_t so_far = 0;
185 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800186 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700187 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700188 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800189 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000190 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700191 } else if (r == 0) {
192 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800193 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700194 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700195 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700196 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000198 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700199}
200
Tao Baode3bbb82018-05-30 16:14:14 -0700201static int read_all(int fd, std::vector<uint8_t>* buffer, size_t size) {
202 return read_all(fd, buffer->data(), size);
Tao Bao612336d2015-08-27 16:41:21 -0700203}
204
Sami Tolvanen90221202014-12-09 16:39:47 +0000205static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700206 size_t written = 0;
207 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800208 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700209 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700210 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800211 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000212 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700213 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700214 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700215 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000216
Sami Tolvanen90221202014-12-09 16:39:47 +0000217 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700218}
219
Tao Bao612336d2015-08-27 16:41:21 -0700220static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
221 return write_all(fd, buffer.data(), size);
222}
223
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700224static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700225 // Don't discard blocks unless the update is a retry run.
226 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700227 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700228 }
229
230 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
231 if (ioctl(fd, BLKDISCARD, &args) == -1) {
232 PLOG(ERROR) << "BLKDISCARD ioctl failed";
233 return false;
234 }
235 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700236}
237
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700238static bool check_lseek(int fd, off64_t offset, int whence) {
239 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
240 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700241 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800242 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700243 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700245 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700246}
247
Tao Baode3bbb82018-05-30 16:14:14 -0700248static void allocate(size_t size, std::vector<uint8_t>* buffer) {
249 // If the buffer's big enough, reuse it.
250 if (size <= buffer->size()) return;
251 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700252}
253
Tao Bao60a70af2017-03-26 14:03:52 -0700254/**
255 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
256 * given RangeSet.
257 */
258class RangeSinkWriter {
259 public:
260 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700261 : fd_(fd),
262 tgt_(tgt),
263 next_range_(0),
264 current_range_left_(0),
265 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700266 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700267 };
Tao Bao0940fe12015-08-27 16:41:21 -0700268
Tao Bao60a70af2017-03-26 14:03:52 -0700269 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700270 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700271 }
272
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700273 size_t AvailableSpace() const {
274 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
275 }
276
277 // Return number of bytes written; and 0 indicates a writing failure.
278 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700279 if (Finished()) {
280 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
281 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700282 }
283
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700284 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700285 while (size > 0) {
286 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700287 if (!SeekToOutputRange()) {
288 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700289 }
Tao Baof7eb7602017-03-27 15:12:48 -0700290
Tao Bao60a70af2017-03-26 14:03:52 -0700291 size_t write_now = size;
292 if (current_range_left_ < write_now) {
293 write_now = current_range_left_;
294 }
Tao Baof7eb7602017-03-27 15:12:48 -0700295
Tao Bao60a70af2017-03-26 14:03:52 -0700296 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700297 break;
298 }
Tao Bao60a70af2017-03-26 14:03:52 -0700299
300 data += write_now;
301 size -= write_now;
302
303 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700304 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700305 }
Tao Bao60a70af2017-03-26 14:03:52 -0700306
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700307 bytes_written_ += written;
308 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700309 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700310
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700311 size_t BytesWritten() const {
312 return bytes_written_;
313 }
314
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700315 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700316 // Set up the output cursor, move to next range if needed.
317 bool SeekToOutputRange() {
318 // We haven't finished the current range yet.
319 if (current_range_left_ != 0) {
320 return true;
321 }
322 // We can't write any more; let the write function return how many bytes have been written
323 // so far.
324 if (next_range_ >= tgt_.size()) {
325 return false;
326 }
327
328 const Range& range = tgt_[next_range_];
329 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
330 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
331 next_range_++;
332
333 if (!discard_blocks(fd_, offset, current_range_left_)) {
334 return false;
335 }
336 if (!check_lseek(fd_, offset, SEEK_SET)) {
337 return false;
338 }
339 return true;
340 }
341
342 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700343 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700344 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700345 const RangeSet& tgt_;
346 // The next range that we should write to.
347 size_t next_range_;
348 // The number of bytes to write before moving to the next range.
349 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700350 // Total bytes written by the writer.
351 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700352};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700353
Tao Bao60a70af2017-03-26 14:03:52 -0700354/**
355 * All of the data for all the 'new' transfers is contained in one file in the update package,
356 * concatenated together in the order in which transfers.list will need it. We want to stream it out
357 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
358 * section until it's that transfer's turn to go.
359 *
360 * To achieve this, we expand the new data from the archive in a background thread, and block that
361 * threads 'receive uncompressed data' function until the main thread has reached a point where we
362 * want some new data to be written. We signal the background thread with the destination for the
363 * data and block the main thread, waiting for the background thread to complete writing that
364 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
365 * transfer.
366 *
367 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
368 * the main thread wants some data written, it sets writer to the destination location and signals
369 * the condition. When the background thread is done writing, it clears writer and signals the
370 * condition again.
371 */
Tao Bao0940fe12015-08-27 16:41:21 -0700372struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700373 ZipArchiveHandle za;
374 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700375 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700376
Tianjie Xu107a34f2017-06-29 17:04:21 -0700377 std::unique_ptr<RangeSinkWriter> writer;
378 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700379 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700380
Tao Bao60a70af2017-03-26 14:03:52 -0700381 pthread_mutex_t mu;
382 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700383};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700384
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700385static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700386 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700387
Tao Bao60a70af2017-03-26 14:03:52 -0700388 while (size > 0) {
389 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
390 pthread_mutex_lock(&nti->mu);
391 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700392 // End the new data receiver if we encounter an error when performing block image update.
393 if (!nti->receiver_available) {
394 pthread_mutex_unlock(&nti->mu);
395 return false;
396 }
Tao Bao60a70af2017-03-26 14:03:52 -0700397 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700398 }
Tao Bao60a70af2017-03-26 14:03:52 -0700399 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700400
Tao Bao60a70af2017-03-26 14:03:52 -0700401 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
402 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700403 size_t write_now = std::min(size, nti->writer->AvailableSpace());
404 if (nti->writer->Write(data, write_now) != write_now) {
405 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700406 return false;
407 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700408
409 data += write_now;
410 size -= write_now;
411
412 if (nti->writer->Finished()) {
413 // We have written all the bytes desired by this writer.
414
415 pthread_mutex_lock(&nti->mu);
416 nti->writer = nullptr;
417 pthread_cond_broadcast(&nti->cv);
418 pthread_mutex_unlock(&nti->mu);
419 }
420 }
421
422 return true;
423}
424
425static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
426 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
427
428 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
429 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
430 pthread_mutex_lock(&nti->mu);
431 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700432 // End the receiver if we encounter an error when performing block image update.
433 if (!nti->receiver_available) {
434 pthread_mutex_unlock(&nti->mu);
435 return false;
436 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700437 pthread_cond_wait(&nti->cv, &nti->mu);
438 }
439 pthread_mutex_unlock(&nti->mu);
440
441 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
442 // disappear from nti.
443
444 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
445 if (buffer_size == 0) {
446 LOG(ERROR) << "No space left in output range";
447 return false;
448 }
449 uint8_t buffer[buffer_size];
450 size_t available_in = size;
451 size_t available_out = buffer_size;
452 uint8_t* next_out = buffer;
453
454 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
455 BrotliDecoderResult result = BrotliDecoderDecompressStream(
456 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
457
458 if (result == BROTLI_DECODER_RESULT_ERROR) {
459 LOG(ERROR) << "Decompression failed with "
460 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
461 return false;
462 }
463
464 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
465 << size - available_in << ", decoder status " << result;
466
467 size_t write_now = buffer_size - available_out;
468 if (nti->writer->Write(buffer, write_now) != write_now) {
469 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
470 return false;
471 }
472
473 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
474 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700475
476 if (nti->writer->Finished()) {
477 // We have written all the bytes desired by this writer.
478
479 pthread_mutex_lock(&nti->mu);
480 nti->writer = nullptr;
481 pthread_cond_broadcast(&nti->cv);
482 pthread_mutex_unlock(&nti->mu);
483 }
484 }
485
486 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700487}
488
489static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700490 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700491 if (nti->brotli_compressed) {
492 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
493 } else {
494 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
495 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700496 pthread_mutex_lock(&nti->mu);
497 nti->receiver_available = false;
498 if (nti->writer != nullptr) {
499 pthread_cond_broadcast(&nti->cv);
500 }
501 pthread_mutex_unlock(&nti->mu);
502 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700503}
504
Tao Baode3bbb82018-05-30 16:14:14 -0700505static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700506 size_t p = 0;
507 for (const auto& range : src) {
508 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
509 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000510 }
511
Tao Baobf5b77d2017-03-30 16:57:29 -0700512 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700513 if (read_all(fd, buffer->data() + p, size) == -1) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700514 return -1;
515 }
516
517 p += size;
518 }
519
520 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000521}
522
Tao Bao612336d2015-08-27 16:41:21 -0700523static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700524 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700525 for (const auto& range : tgt) {
526 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
527 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700528 if (!discard_blocks(fd, offset, size)) {
529 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000530 }
531
Tao Bao60a70af2017-03-26 14:03:52 -0700532 if (!check_lseek(fd, offset, SEEK_SET)) {
533 return -1;
534 }
535
536 if (write_all(fd, buffer.data() + written, size) == -1) {
537 return -1;
538 }
539
540 written += size;
541 }
542
543 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000544}
545
Tao Baobaad2d42015-12-06 16:56:27 -0800546// Parameters for transfer list command functions
547struct CommandParameters {
548 std::vector<std::string> tokens;
549 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700550 std::string cmdname;
551 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800552 std::string freestash;
553 std::string stashbase;
554 bool canwrite;
555 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700556 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800557 bool foundwrites;
558 bool isunresumable;
559 int version;
560 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700561 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800562 NewThreadInfo nti;
563 pthread_t thread;
564 std::vector<uint8_t> buffer;
565 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800566 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800567};
568
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000569// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
570// handled separately).
571static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
572 const std::vector<uint8_t>& buffer) {
573 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000574 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
575 params.tokens[0] == "imgdiff");
576
577 size_t pos = 0;
578 // Command example:
579 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
580 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
581 // [<loc_range> <stashed_blocks>]
582 if (params.tokens[0] == "move") {
583 // src_range for move starts at the 4th position.
584 if (params.tokens.size() < 5) {
585 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
586 return;
587 }
588 pos = 4;
589 } else {
590 // src_range for diff starts at the 7th position.
591 if (params.tokens.size() < 8) {
592 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
593 return;
594 }
595 pos = 7;
596 }
597
598 // Source blocks in stash only, no work to do.
599 if (params.tokens[pos] == "-") {
600 return;
601 }
602
Tao Bao8f237572017-03-26 13:36:49 -0700603 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700604 if (!src) {
605 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
606 return;
607 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000608
609 RangeSet locs;
610 // If there's no stashed blocks, content in the buffer is consecutive and has the same
611 // order as the source blocks.
612 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700613 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000614 } else {
615 // Otherwise, the next token is the offset of the source blocks in the target range.
616 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
617 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
618 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700619 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700620 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000621 }
622
Tao Baobf5b77d2017-03-30 16:57:29 -0700623 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
624 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700625 size_t block_num = src.GetBlockNumber(i);
626 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000627 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
628
629 uint8_t digest[SHA_DIGEST_LENGTH];
630 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
631 std::string hexdigest = print_sha1(digest);
632 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
633 }
634}
635
636// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
637// in hex for each block.
638static void PrintHashForCorruptedStashedBlocks(const std::string& id,
639 const std::vector<uint8_t>& buffer,
640 const RangeSet& src) {
641 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700642 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000643
Tao Baobf5b77d2017-03-30 16:57:29 -0700644 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700645 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000646
647 uint8_t digest[SHA_DIGEST_LENGTH];
648 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
649 std::string hexdigest = print_sha1(digest);
650 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
651 }
652}
653
654// If the stash file doesn't exist, read the source blocks this stash contains and print the
655// SHA-1 for these blocks.
656static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
657 if (stash_map.find(id) == stash_map.end()) {
658 LOG(ERROR) << "No stash saved for id: " << id;
659 return;
660 }
661
662 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
663 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700664 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700665 if (ReadBlocks(src, &buffer, fd) == -1) {
666 LOG(ERROR) << "failed to read source blocks for stash: " << id;
667 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000668 }
669 PrintHashForCorruptedStashedBlocks(id, buffer, src);
670}
671
Tao Bao612336d2015-08-27 16:41:21 -0700672static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700673 const size_t blocks, bool printerror) {
674 uint8_t digest[SHA_DIGEST_LENGTH];
675 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000676
Tao Baode3bbb82018-05-30 16:14:14 -0700677 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000678
Tao Baode3bbb82018-05-30 16:14:14 -0700679 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000680
Tao Baode3bbb82018-05-30 16:14:14 -0700681 if (hexdigest != expected) {
682 if (printerror) {
683 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
684 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000685 }
Tao Baode3bbb82018-05-30 16:14:14 -0700686 return -1;
687 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000688
Tao Baode3bbb82018-05-30 16:14:14 -0700689 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000690}
691
Tao Bao0940fe12015-08-27 16:41:21 -0700692static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700693 const std::string& postfix) {
694 if (base.empty()) {
695 return "";
696 }
Tao Bao864c6682018-05-07 11:38:25 -0700697 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
698 if (id.empty() && postfix.empty()) {
699 return filename;
700 }
701 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000702}
703
Tao Baoec8272f2017-03-15 17:39:01 -0700704// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
705// directory and continues despite of errors. Calls the 'callback' function for each file.
706static void EnumerateStash(const std::string& dirname,
707 const std::function<void(const std::string&)>& callback) {
708 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000709
Tao Baoec8272f2017-03-15 17:39:01 -0700710 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000711
Tao Baoec8272f2017-03-15 17:39:01 -0700712 if (directory == nullptr) {
713 if (errno != ENOENT) {
714 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
Tao Bao51412212016-12-28 14:44:05 -0800716 return;
717 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700718
Tao Baoec8272f2017-03-15 17:39:01 -0700719 dirent* item;
720 while ((item = readdir(directory.get())) != nullptr) {
721 if (item->d_type != DT_REG) continue;
722 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800723 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000724}
725
726// Deletes the stash directory and all files in it. Assumes that it only
727// contains files. There is nothing we can do about unlikely, but possible
728// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700729static void DeleteFile(const std::string& fn) {
730 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000731
Tao Baoec8272f2017-03-15 17:39:01 -0700732 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733
Tao Baoec8272f2017-03-15 17:39:01 -0700734 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
735 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
736 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000737}
738
Tao Baoe6aa3322015-08-05 15:20:27 -0700739static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700740 if (base.empty()) return;
741
742 LOG(INFO) << "deleting stash " << base;
743
744 std::string dirname = GetStashFileName(base, "", "");
745 EnumerateStash(dirname, DeleteFile);
746
747 if (rmdir(dirname.c_str()) == -1) {
748 if (errno != ENOENT && errno != ENOTDIR) {
749 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 }
Tao Baoec8272f2017-03-15 17:39:01 -0700751 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000752}
753
Tao Baode3bbb82018-05-30 16:14:14 -0700754static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
755 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700756 // In verify mode, if source range_set was saved for the given hash, check contents in the source
757 // blocks first. If the check fails, search for the stashed files on /cache as usual.
758 if (!params.canwrite) {
759 if (stash_map.find(id) != stash_map.end()) {
760 const RangeSet& src = stash_map[id];
761 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700762
Tao Baobf5b77d2017-03-30 16:57:29 -0700763 if (ReadBlocks(src, buffer, params.fd) == -1) {
764 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700765 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700766 }
Tao Baode3bbb82018-05-30 16:14:14 -0700767 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700768 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu3c5958f2018-03-09 14:10:25 -0800769 if (!is_retry) {
770 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
771 }
Tao Bao0940fe12015-08-27 16:41:21 -0700772 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700773 }
774 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000775 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700776 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000777
Tao Baobf5b77d2017-03-30 16:57:29 -0700778 std::string fn = GetStashFileName(params.stashbase, id, "");
779
780 struct stat sb;
781 if (stat(fn.c_str(), &sb) == -1) {
782 if (errno != ENOENT || printnoent) {
783 PLOG(ERROR) << "stat \"" << fn << "\" failed";
784 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000785 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700786 return -1;
787 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000788
Tao Baobf5b77d2017-03-30 16:57:29 -0700789 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000790
Tao Baobf5b77d2017-03-30 16:57:29 -0700791 if ((sb.st_size % BLOCKSIZE) != 0) {
792 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
793 return -1;
794 }
795
796 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
797 if (fd == -1) {
798 PLOG(ERROR) << "open \"" << fn << "\" failed";
799 return -1;
800 }
801
802 allocate(sb.st_size, buffer);
803
804 if (read_all(fd, buffer, sb.st_size) == -1) {
805 return -1;
806 }
807
Tao Bao64957ce2018-05-30 16:21:39 -0700808 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700809 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700810 LOG(ERROR) << "unexpected contents in " << fn;
811 if (stash_map.find(id) == stash_map.end()) {
812 LOG(ERROR) << "failed to find source blocks number for stash " << id
813 << " when executing command: " << params.cmdname;
814 } else {
815 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700816 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000817 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700818 DeleteFile(fn);
819 return -1;
820 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000821
Tao Baobf5b77d2017-03-30 16:57:29 -0700822 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000823}
824
Tao Bao612336d2015-08-27 16:41:21 -0700825static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700826 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
827 if (base.empty()) {
828 return -1;
829 }
830
Tao Bao5ee25662018-07-11 15:55:32 -0700831 if (checkspace && !CheckAndFreeSpaceOnCache(blocks * BLOCKSIZE)) {
Tao Baode3bbb82018-05-30 16:14:14 -0700832 LOG(ERROR) << "not enough space to write stash";
833 return -1;
834 }
835
836 std::string fn = GetStashFileName(base, id, ".partial");
837 std::string cn = GetStashFileName(base, id, "");
838
839 if (exists) {
840 struct stat sb;
841 int res = stat(cn.c_str(), &sb);
842
843 if (res == 0) {
844 // The file already exists and since the name is the hash of the contents,
845 // it's safe to assume the contents are identical (accidental hash collisions
846 // are unlikely)
847 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
848 *exists = true;
849 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000850 }
851
Tao Baode3bbb82018-05-30 16:14:14 -0700852 *exists = false;
853 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000854
Tao Baode3bbb82018-05-30 16:14:14 -0700855 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000856
Tao Baode3bbb82018-05-30 16:14:14 -0700857 android::base::unique_fd fd(
858 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
859 if (fd == -1) {
860 PLOG(ERROR) << "failed to create \"" << fn << "\"";
861 return -1;
862 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100863
Tao Baode3bbb82018-05-30 16:14:14 -0700864 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
865 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
866 return -1;
867 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100868
Tao Baode3bbb82018-05-30 16:14:14 -0700869 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
870 return -1;
871 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100872
Tao Baode3bbb82018-05-30 16:14:14 -0700873 if (ota_fsync(fd) == -1) {
874 failure_type = kFsyncFailure;
875 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
876 return -1;
877 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000878
Tao Baode3bbb82018-05-30 16:14:14 -0700879 if (rename(fn.c_str(), cn.c_str()) == -1) {
880 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
881 return -1;
882 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000883
Tao Baode3bbb82018-05-30 16:14:14 -0700884 std::string dname = GetStashFileName(base, "", "");
885 if (!FsyncDir(dname)) {
886 failure_type = kFsyncFailure;
887 return -1;
888 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700889
Tao Baode3bbb82018-05-30 16:14:14 -0700890 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000891}
892
893// Creates a directory for storing stash files and checks if the /cache partition
894// hash enough space for the expected amount of blocks we need to store. Returns
895// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700896static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800897 std::string dirname = GetStashFileName(base, "", "");
898 struct stat sb;
899 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800900 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800901 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800902 strerror(errno));
903 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700904 }
905
906 size_t max_stash_size = maxblocks * BLOCKSIZE;
907 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800908 LOG(INFO) << "creating stash " << dirname;
909 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
910
911 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800912 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800913 strerror(errno));
914 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000915 }
916
Tianjie Xua946b9e2017-03-21 16:24:57 -0700917 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800918 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700919 strerror(errno));
920 return -1;
921 }
922
Tao Bao5ee25662018-07-11 15:55:32 -0700923 if (!CheckAndFreeSpaceOnCache(max_stash_size)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800924 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800925 max_stash_size);
926 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 }
928
Tao Bao51412212016-12-28 14:44:05 -0800929 return 1; // Created directory
930 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000931
Tao Bao51412212016-12-28 14:44:05 -0800932 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000933
Tao Baoec8272f2017-03-15 17:39:01 -0700934 // If the directory already exists, calculate the space already allocated to stash files and check
935 // if there's enough for all required blocks. Delete any partially completed stash files first.
936 EnumerateStash(dirname, [](const std::string& fn) {
937 if (android::base::EndsWith(fn, ".partial")) {
938 DeleteFile(fn);
939 }
940 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000941
Tao Bao51412212016-12-28 14:44:05 -0800942 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700943 EnumerateStash(dirname, [&existing](const std::string& fn) {
944 if (fn.empty()) return;
945 struct stat sb;
946 if (stat(fn.c_str(), &sb) == -1) {
947 PLOG(ERROR) << "stat \"" << fn << "\" failed";
948 return;
949 }
950 existing += static_cast<size_t>(sb.st_size);
951 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000952
Tao Bao51412212016-12-28 14:44:05 -0800953 if (max_stash_size > existing) {
954 size_t needed = max_stash_size - existing;
Tao Bao5ee25662018-07-11 15:55:32 -0700955 if (!CheckAndFreeSpaceOnCache(needed)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800956 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800957 needed);
958 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000959 }
Tao Bao51412212016-12-28 14:44:05 -0800960 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000961
Tao Bao51412212016-12-28 14:44:05 -0800962 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000963}
964
Tao Baobaad2d42015-12-06 16:56:27 -0800965static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700966 if (base.empty() || id.empty()) {
967 return -1;
968 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000969
Tao Baoec8272f2017-03-15 17:39:01 -0700970 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000971
Tao Baoec8272f2017-03-15 17:39:01 -0700972 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700973}
974
Tao Baobf5b77d2017-03-30 16:57:29 -0700975// Source contains packed data, which we want to move to the locations given in locs in the dest
976// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700977static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700978 const std::vector<uint8_t>& source) {
979 const uint8_t* from = source.data();
980 uint8_t* to = dest.data();
981 size_t start = locs.blocks();
982 // Must do the movement backward.
983 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
984 size_t blocks = it->second - it->first;
985 start -= blocks;
986 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
987 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700988}
989
Tao Baod2aecd42017-03-23 14:43:44 -0700990/**
991 * We expect to parse the remainder of the parameter tokens as one of:
992 *
993 * <src_block_count> <src_range>
994 * (loads data from source image only)
995 *
996 * <src_block_count> - <[stash_id:stash_range] ...>
997 * (loads data from stashes only)
998 *
999 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1000 * (loads data from both source image and stashes)
1001 *
1002 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1003 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1004 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1005 * LoadStash.
1006 */
1007static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1008 bool* overlap) {
1009 CHECK(src_blocks != nullptr);
1010 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001011
Tao Baod2aecd42017-03-23 14:43:44 -07001012 // <src_block_count>
1013 const std::string& token = params.tokens[params.cpos++];
1014 if (!android::base::ParseUint(token, src_blocks)) {
1015 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1016 return -1;
1017 }
Tao Baobaad2d42015-12-06 16:56:27 -08001018
Tao Baode3bbb82018-05-30 16:14:14 -07001019 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -07001020
1021 // "-" or <src_range> [<src_loc>]
1022 if (params.tokens[params.cpos] == "-") {
1023 // no source ranges, only stashes
1024 params.cpos++;
1025 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001026 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001027 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001028 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001029
Tao Baode3bbb82018-05-30 16:14:14 -07001030 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001031 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001032 }
1033
Tao Baod2aecd42017-03-23 14:43:44 -07001034 if (params.cpos >= params.tokens.size()) {
1035 // no stashes, only source range
1036 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001037 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001038
Tao Bao8f237572017-03-26 13:36:49 -07001039 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001040 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001041 MoveRange(params.buffer, locs, params.buffer);
1042 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001043
Tao Baod2aecd42017-03-23 14:43:44 -07001044 // <[stash_id:stash_range]>
1045 while (params.cpos < params.tokens.size()) {
1046 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1047 // in the source block that stashed data should go.
1048 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1049 if (tokens.size() != 2) {
1050 LOG(ERROR) << "invalid parameter";
1051 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001052 }
1053
Tao Baod2aecd42017-03-23 14:43:44 -07001054 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001055 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001056 // These source blocks will fail verification if used later, but we
1057 // will let the caller decide if this is a fatal failure
1058 LOG(ERROR) << "failed to load stash " << tokens[0];
1059 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001060 }
1061
Tao Bao8f237572017-03-26 13:36:49 -07001062 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001063 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001064 MoveRange(params.buffer, locs, stash);
1065 }
1066
1067 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001068}
1069
Tao Bao33567772017-03-13 14:57:34 -07001070/**
1071 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1072 *
1073 * We expect to parse the remainder of the parameter tokens as one of:
1074 *
1075 * <tgt_range> <src_block_count> <src_range>
1076 * (loads data from source image only)
1077 *
1078 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1079 * (loads data from stashes only)
1080 *
1081 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1082 * (loads data from both source image and stashes)
1083 *
Tao Baod2aecd42017-03-23 14:43:44 -07001084 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1085 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001086 * verification fails in a way that the update cannot be resumed anymore.
1087 *
1088 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1089 * the return value is -1 and the command should be aborted.
1090 *
1091 * If the return value is 1, the command has already been completed according to the contents of the
1092 * target blocks, and should not be performed again.
1093 *
1094 * If the return value is 0, source blocks have expected content and the command can be performed.
1095 */
Tao Baode3bbb82018-05-30 16:14:14 -07001096static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001097 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001098 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001099
Tao Baod2aecd42017-03-23 14:43:44 -07001100 if (params.cpos >= params.tokens.size()) {
1101 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001102 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001103 }
1104
1105 std::string srchash = params.tokens[params.cpos++];
1106 std::string tgthash;
1107
1108 if (onehash) {
1109 tgthash = srchash;
1110 } else {
1111 if (params.cpos >= params.tokens.size()) {
1112 LOG(ERROR) << "missing target hash";
1113 return -1;
1114 }
1115 tgthash = params.tokens[params.cpos++];
1116 }
1117
1118 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1119 // "-"/<src_range>.
1120 if (params.cpos + 2 >= params.tokens.size()) {
1121 LOG(ERROR) << "invalid parameters";
1122 return -1;
1123 }
1124
1125 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001126 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1127 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001128
Tao Baode3bbb82018-05-30 16:14:14 -07001129 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1130 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001131 return -1;
1132 }
1133
1134 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001135 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001136 return 1;
1137 }
1138
1139 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001140 bool overlap = false;
1141 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001142 return -1;
1143 }
1144
1145 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001146 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1147 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1148 // overwritten.
1149 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001150 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1151
1152 bool stash_exists = false;
1153 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1154 &stash_exists) != 0) {
1155 LOG(ERROR) << "failed to stash overlapping source blocks";
1156 return -1;
1157 }
1158
1159 params.stashed += *src_blocks;
1160 // Can be deleted when the write has completed.
1161 if (!stash_exists) {
1162 params.freestash = srchash;
1163 }
1164 }
1165
1166 // Source blocks have expected content, command can proceed.
1167 return 0;
1168 }
1169
Tao Bao4a135082018-06-07 22:27:44 -07001170 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001171 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1172 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1173 // command.
1174 return 0;
1175 }
1176
1177 // Valid source data not available, update cannot be resumed.
1178 LOG(ERROR) << "partition has unexpected contents";
1179 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1180
1181 params.isunresumable = true;
1182
1183 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001184}
1185
Tao Bao0940fe12015-08-27 16:41:21 -07001186static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001187 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001188 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001189 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001190
Tao Bao33567772017-03-13 14:57:34 -07001191 if (status == -1) {
1192 LOG(ERROR) << "failed to read blocks for move";
1193 return -1;
1194 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001195
Tao Bao33567772017-03-13 14:57:34 -07001196 if (status == 0) {
1197 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001198 } else {
1199 params.target_verified = true;
1200 if (params.foundwrites) {
1201 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1202 }
Tao Bao33567772017-03-13 14:57:34 -07001203 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001204
Tao Bao33567772017-03-13 14:57:34 -07001205 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001206 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001207 LOG(INFO) << " moving " << blocks << " blocks";
1208
1209 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1210 return -1;
1211 }
1212 } else {
1213 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001214 }
Tao Bao33567772017-03-13 14:57:34 -07001215 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001216
Tao Bao33567772017-03-13 14:57:34 -07001217 if (!params.freestash.empty()) {
1218 FreeStash(params.stashbase, params.freestash);
1219 params.freestash.clear();
1220 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001221
Tao Baobf5b77d2017-03-30 16:57:29 -07001222 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001223
Tao Bao33567772017-03-13 14:57:34 -07001224 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001225}
1226
Tao Bao0940fe12015-08-27 16:41:21 -07001227static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001228 // <stash_id> <src_range>
1229 if (params.cpos + 1 >= params.tokens.size()) {
1230 LOG(ERROR) << "missing id and/or src range fields in stash command";
1231 return -1;
1232 }
1233
1234 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001235 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001236 // Stash file already exists and has expected contents. Do not read from source again, as the
1237 // source may have been already overwritten during a previous attempt.
1238 return 0;
1239 }
1240
Tao Bao8f237572017-03-26 13:36:49 -07001241 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001242 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001243
Tao Bao64957ce2018-05-30 16:21:39 -07001244 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001245 allocate(blocks * BLOCKSIZE, &params.buffer);
1246 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001247 return -1;
1248 }
Tao Baobcf46492017-03-23 15:28:20 -07001249 stash_map[id] = src;
1250
1251 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1252 // Source blocks have unexpected contents. If we actually need this data later, this is an
1253 // unrecoverable error. However, the command that uses the data may have already completed
1254 // previously, so the possible failure will occur during source block verification.
1255 LOG(ERROR) << "failed to load source blocks for stash " << id;
1256 return 0;
1257 }
1258
1259 // In verify mode, we don't need to stash any blocks.
1260 if (!params.canwrite) {
1261 return 0;
1262 }
1263
1264 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001265 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1266 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001267 params.stashed += blocks;
1268 }
1269 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001270}
1271
Tao Bao0940fe12015-08-27 16:41:21 -07001272static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001273 // <stash_id>
1274 if (params.cpos >= params.tokens.size()) {
1275 LOG(ERROR) << "missing stash id in free command";
1276 return -1;
1277 }
Tao Baobaad2d42015-12-06 16:56:27 -08001278
Tao Baobcf46492017-03-23 15:28:20 -07001279 const std::string& id = params.tokens[params.cpos++];
1280 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001281
Tao Baobcf46492017-03-23 15:28:20 -07001282 if (params.createdstash || params.canwrite) {
1283 return FreeStash(params.stashbase, id);
1284 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001285
Tao Baobcf46492017-03-23 15:28:20 -07001286 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001287}
1288
Tao Bao0940fe12015-08-27 16:41:21 -07001289static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001290 if (params.cpos >= params.tokens.size()) {
1291 LOG(ERROR) << "missing target blocks for zero";
1292 return -1;
1293 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001294
Tao Baobf5b77d2017-03-30 16:57:29 -07001295 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001296 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001297
1298 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1299
Tao Baode3bbb82018-05-30 16:14:14 -07001300 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001301 memset(params.buffer.data(), 0, BLOCKSIZE);
1302
1303 if (params.canwrite) {
1304 for (const auto& range : tgt) {
1305 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1306 size_t size = (range.second - range.first) * BLOCKSIZE;
1307 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001308 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001309 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001310
Tao Baobf5b77d2017-03-30 16:57:29 -07001311 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1312 return -1;
1313 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001314
Tao Baobf5b77d2017-03-30 16:57:29 -07001315 for (size_t j = range.first; j < range.second; ++j) {
1316 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1317 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001318 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001319 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001320 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001321 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001322
Tao Baobf5b77d2017-03-30 16:57:29 -07001323 if (params.cmdname[0] == 'z') {
1324 // Update only for the zero command, as the erase command will call
1325 // this if DEBUG_ERASE is defined.
1326 params.written += tgt.blocks();
1327 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001328
Tao Baobf5b77d2017-03-30 16:57:29 -07001329 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001330}
1331
Tao Bao0940fe12015-08-27 16:41:21 -07001332static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001333 if (params.cpos >= params.tokens.size()) {
1334 LOG(ERROR) << "missing target blocks for new";
1335 return -1;
1336 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001337
Tao Bao8f237572017-03-26 13:36:49 -07001338 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001339 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001340
1341 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001342 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001343
Tao Bao60a70af2017-03-26 14:03:52 -07001344 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001345 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001346 pthread_cond_broadcast(&params.nti.cv);
1347
1348 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001349 if (!params.nti.receiver_available) {
1350 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1351 << " bytes of new data";
1352 pthread_mutex_unlock(&params.nti.mu);
1353 return -1;
1354 }
Tao Bao60a70af2017-03-26 14:03:52 -07001355 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001356 }
1357
Tao Bao60a70af2017-03-26 14:03:52 -07001358 pthread_mutex_unlock(&params.nti.mu);
1359 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001360
Tao Baobf5b77d2017-03-30 16:57:29 -07001361 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001362
Tao Bao60a70af2017-03-26 14:03:52 -07001363 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001364}
1365
Tao Bao0940fe12015-08-27 16:41:21 -07001366static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001367 // <offset> <length>
1368 if (params.cpos + 1 >= params.tokens.size()) {
1369 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1370 return -1;
1371 }
Tao Bao0940fe12015-08-27 16:41:21 -07001372
Tao Baoc0e1c462017-02-01 10:20:10 -08001373 size_t offset;
1374 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1375 LOG(ERROR) << "invalid patch offset";
1376 return -1;
1377 }
Tao Bao0940fe12015-08-27 16:41:21 -07001378
Tao Baoc0e1c462017-02-01 10:20:10 -08001379 size_t len;
1380 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1381 LOG(ERROR) << "invalid patch len";
1382 return -1;
1383 }
Tao Bao0940fe12015-08-27 16:41:21 -07001384
Tao Baoc0e1c462017-02-01 10:20:10 -08001385 RangeSet tgt;
1386 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001387 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001388
Tao Baoc0e1c462017-02-01 10:20:10 -08001389 if (status == -1) {
1390 LOG(ERROR) << "failed to read blocks for diff";
1391 return -1;
1392 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001393
Tao Baoc0e1c462017-02-01 10:20:10 -08001394 if (status == 0) {
1395 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001396 } else {
1397 params.target_verified = true;
1398 if (params.foundwrites) {
1399 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1400 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001401 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001402
Tao Baoc0e1c462017-02-01 10:20:10 -08001403 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001404 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001405 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001406 Value patch_value(
Tao Bao511d7592018-06-19 15:56:49 -07001407 Value::Type::BLOB,
1408 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001409
Tao Bao60a70af2017-03-26 14:03:52 -07001410 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001411 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001412 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001413 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1414 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001415 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001416 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001417 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001418 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001419 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001420 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001421 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001422 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001423 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001424 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001425 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001426 return -1;
1427 }
1428 }
1429
1430 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001431 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001432 LOG(ERROR) << "range sink underrun?";
1433 }
1434 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001435 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001436 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001437 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001438 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001439
Tao Baoc0e1c462017-02-01 10:20:10 -08001440 if (!params.freestash.empty()) {
1441 FreeStash(params.stashbase, params.freestash);
1442 params.freestash.clear();
1443 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001444
Tao Baobf5b77d2017-03-30 16:57:29 -07001445 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001446
Tao Baoc0e1c462017-02-01 10:20:10 -08001447 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001448}
1449
Tao Bao0940fe12015-08-27 16:41:21 -07001450static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001451 if (DEBUG_ERASE) {
1452 return PerformCommandZero(params);
1453 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001454
Tao Baobf5b77d2017-03-30 16:57:29 -07001455 struct stat sb;
1456 if (fstat(params.fd, &sb) == -1) {
1457 PLOG(ERROR) << "failed to fstat device to erase";
1458 return -1;
1459 }
1460
1461 if (!S_ISBLK(sb.st_mode)) {
1462 LOG(ERROR) << "not a block device; skipping erase";
1463 return -1;
1464 }
1465
1466 if (params.cpos >= params.tokens.size()) {
1467 LOG(ERROR) << "missing target blocks for erase";
1468 return -1;
1469 }
1470
1471 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001472 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001473
1474 if (params.canwrite) {
1475 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1476
1477 for (const auto& range : tgt) {
1478 uint64_t blocks[2];
1479 // offset in bytes
1480 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1481 // length in bytes
1482 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1483
1484 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1485 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001486 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001487 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001488 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001489 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001490
Tao Baobf5b77d2017-03-30 16:57:29 -07001491 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001492}
1493
Tao Bao91a649a2018-05-21 16:05:56 -07001494static int PerformCommandAbort(CommandParameters&) {
1495 LOG(INFO) << "Aborting as instructed";
1496 return -1;
1497}
1498
Tianjie Xu69ffa152018-08-01 16:40:00 -07001499// Computes the hash_tree bytes based on the parameters, checks if the root hash of the tree
1500// matches the expected hash and writes the result to the specified range on the block_device.
1501// Hash_tree computation arguments:
1502// hash_tree_ranges
1503// source_ranges
1504// hash_algorithm
1505// salt_hex
1506// root_hash
1507static int PerformCommandComputeHashTree(CommandParameters& params) {
1508 if (params.cpos + 5 != params.tokens.size()) {
1509 LOG(ERROR) << "Invaild arguments count in hash computation " << params.cmdline;
1510 return -1;
1511 }
1512
1513 // Expects the hash_tree data to be contiguous.
1514 RangeSet hash_tree_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1515 if (!hash_tree_ranges || hash_tree_ranges.size() != 1) {
1516 LOG(ERROR) << "Invalid hash tree ranges in " << params.cmdline;
1517 return -1;
1518 }
1519
1520 RangeSet source_ranges = RangeSet::Parse(params.tokens[params.cpos++]);
1521 if (!source_ranges) {
1522 LOG(ERROR) << "Invalid source ranges in " << params.cmdline;
1523 return -1;
1524 }
1525
1526 auto hash_function = HashTreeBuilder::HashFunction(params.tokens[params.cpos++]);
1527 if (hash_function == nullptr) {
1528 LOG(ERROR) << "Invalid hash algorithm in " << params.cmdline;
1529 return -1;
1530 }
1531
1532 std::vector<unsigned char> salt;
1533 std::string salt_hex = params.tokens[params.cpos++];
1534 if (salt_hex.empty() || !HashTreeBuilder::ParseBytesArrayFromString(salt_hex, &salt)) {
1535 LOG(ERROR) << "Failed to parse salt in " << params.cmdline;
1536 return -1;
1537 }
1538
1539 std::string expected_root_hash = params.tokens[params.cpos++];
1540 if (expected_root_hash.empty()) {
1541 LOG(ERROR) << "Invalid root hash in " << params.cmdline;
1542 return -1;
1543 }
1544
1545 // Starts the hash_tree computation.
1546 HashTreeBuilder builder(BLOCKSIZE, hash_function);
1547 if (!builder.Initialize(source_ranges.blocks() * BLOCKSIZE, salt)) {
1548 LOG(ERROR) << "Failed to initialize hash tree computation, source " << source_ranges.ToString()
1549 << ", salt " << salt_hex;
1550 return -1;
1551 }
1552
1553 // Iterates through every block in the source_ranges and updates the hash tree structure
1554 // accordingly.
1555 for (const auto& range : source_ranges) {
1556 uint8_t buffer[BLOCKSIZE];
1557 if (!check_lseek(params.fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
1558 PLOG(ERROR) << "Failed to seek to block: " << range.first;
1559 return -1;
1560 }
1561
1562 for (size_t i = range.first; i < range.second; i++) {
1563 if (read_all(params.fd, buffer, BLOCKSIZE) == -1) {
1564 LOG(ERROR) << "Failed to read data in " << range.first << ":" << range.second;
1565 return -1;
1566 }
1567
1568 if (!builder.Update(reinterpret_cast<unsigned char*>(buffer), BLOCKSIZE)) {
1569 LOG(ERROR) << "Failed to update hash tree builder";
1570 return -1;
1571 }
1572 }
1573 }
1574
1575 if (!builder.BuildHashTree()) {
1576 LOG(ERROR) << "Failed to build hash tree";
1577 return -1;
1578 }
1579
1580 std::string root_hash_hex = HashTreeBuilder::BytesArrayToString(builder.root_hash());
1581 if (root_hash_hex != expected_root_hash) {
1582 LOG(ERROR) << "Root hash of the verity hash tree doesn't match the expected value. Expected: "
1583 << expected_root_hash << ", actual: " << root_hash_hex;
1584 return -1;
1585 }
1586
1587 uint64_t write_offset = static_cast<uint64_t>(hash_tree_ranges.GetBlockNumber(0)) * BLOCKSIZE;
1588 if (params.canwrite && !builder.WriteHashTreeToFd(params.fd, write_offset)) {
1589 LOG(ERROR) << "Failed to write hash tree to output";
1590 return -1;
1591 }
1592
1593 // TODO(xunchang) validates the written bytes
1594
1595 return 0;
1596}
1597
Tao Baoc3901232018-05-21 16:05:56 -07001598using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001599
Tao Baoc3901232018-05-21 16:05:56 -07001600using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001601
Tianjie Xuc4447322017-03-06 14:44:59 -08001602static Value* PerformBlockImageUpdate(const char* name, State* state,
1603 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001604 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001605 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001606 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001607 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001608
Tao Bao33567772017-03-13 14:57:34 -07001609 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1610 if (state->is_retry) {
1611 is_retry = true;
1612 LOG(INFO) << "This update is a retry.";
1613 }
1614 if (argv.size() != 4) {
1615 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1616 argv.size());
1617 return StringValue("");
1618 }
1619
1620 std::vector<std::unique_ptr<Value>> args;
1621 if (!ReadValueArgs(state, argv, &args)) {
1622 return nullptr;
1623 }
1624
Tao Baoc3901232018-05-21 16:05:56 -07001625 // args:
1626 // - block device (or file) to modify in-place
1627 // - transfer list (blob)
1628 // - new data stream (filename within package.zip)
1629 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001630 const std::unique_ptr<Value>& blockdev_filename = args[0];
1631 const std::unique_ptr<Value>& transfer_list_value = args[1];
1632 const std::unique_ptr<Value>& new_data_fn = args[2];
1633 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001634
Tao Bao511d7592018-06-19 15:56:49 -07001635 if (blockdev_filename->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001636 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1637 return StringValue("");
1638 }
Tao Bao511d7592018-06-19 15:56:49 -07001639 if (transfer_list_value->type != Value::Type::BLOB) {
Tao Bao33567772017-03-13 14:57:34 -07001640 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1641 return StringValue("");
1642 }
Tao Bao511d7592018-06-19 15:56:49 -07001643 if (new_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001644 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1645 return StringValue("");
1646 }
Tao Bao511d7592018-06-19 15:56:49 -07001647 if (patch_data_fn->type != Value::Type::STRING) {
Tao Bao33567772017-03-13 14:57:34 -07001648 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1649 return StringValue("");
1650 }
1651
1652 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1653 if (ui == nullptr) {
1654 return StringValue("");
1655 }
1656
1657 FILE* cmd_pipe = ui->cmd_pipe;
1658 ZipArchiveHandle za = ui->package_zip;
1659
1660 if (cmd_pipe == nullptr || za == nullptr) {
1661 return StringValue("");
1662 }
1663
1664 ZipString path_data(patch_data_fn->data.c_str());
1665 ZipEntry patch_entry;
1666 if (FindEntry(za, path_data, &patch_entry) != 0) {
1667 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1668 return StringValue("");
1669 }
1670
1671 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1672 ZipString new_data(new_data_fn->data.c_str());
1673 ZipEntry new_entry;
1674 if (FindEntry(za, new_data, &new_entry) != 0) {
1675 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1676 return StringValue("");
1677 }
1678
1679 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1680 if (params.fd == -1) {
1681 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1682 return StringValue("");
1683 }
1684
Tao Bao864c6682018-05-07 11:38:25 -07001685 // Stash directory should be different for each partition to avoid conflicts when updating
1686 // multiple partitions at the same time, so we use the hash of the block device name as the base
1687 // directory.
1688 uint8_t digest[SHA_DIGEST_LENGTH];
1689 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1690 blockdev_filename->data.size(), digest);
1691 params.stashbase = print_sha1(digest);
1692
1693 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1694 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1695 // fail the no-op retry.
1696 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1697 if (is_retry) {
1698 struct stat sb;
1699 int result = stat(updated_marker.c_str(), &sb);
1700 if (result == 0) {
1701 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1702 << " based on marker";
1703 return StringValue("t");
1704 }
1705 } else {
1706 // Delete the obsolete marker if any.
1707 std::string err;
1708 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1709 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1710 return StringValue("");
1711 }
1712 }
1713
Tao Baoffede3e2018-06-07 09:56:19 -07001714 static constexpr size_t kTransferListHeaderLines = 4;
Tao Bao33567772017-03-13 14:57:34 -07001715 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baoffede3e2018-06-07 09:56:19 -07001716 if (lines.size() < kTransferListHeaderLines) {
1717 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001718 lines.size());
1719 return StringValue("");
1720 }
1721
1722 // First line in transfer list is the version number.
1723 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1724 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1725 return StringValue("");
1726 }
1727
1728 LOG(INFO) << "blockimg version is " << params.version;
1729
1730 // Second line in transfer list is the total number of blocks we expect to write.
1731 size_t total_blocks;
1732 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001733 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001734 return StringValue("");
1735 }
1736
1737 if (total_blocks == 0) {
1738 return StringValue("t");
1739 }
1740
Tao Bao33567772017-03-13 14:57:34 -07001741 // Third line is how many stash entries are needed simultaneously.
1742 LOG(INFO) << "maximum stash entries " << lines[2];
1743
1744 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1745 size_t stash_max_blocks;
1746 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001747 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001748 lines[3].c_str());
1749 return StringValue("");
1750 }
1751
Tao Bao864c6682018-05-07 11:38:25 -07001752 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001753 if (res == -1) {
1754 return StringValue("");
1755 }
Tao Bao33567772017-03-13 14:57:34 -07001756 params.createdstash = res;
1757
Tao Bao0a883c12018-06-18 12:49:06 -07001758 // Set up the new data writer.
1759 if (params.canwrite) {
1760 params.nti.za = za;
1761 params.nti.entry = new_entry;
1762 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1763 if (params.nti.brotli_compressed) {
1764 // Initialize brotli decoder state.
1765 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1766 }
1767 params.nti.receiver_available = true;
1768
1769 pthread_mutex_init(&params.nti.mu, nullptr);
1770 pthread_cond_init(&params.nti.cv, nullptr);
1771 pthread_attr_t attr;
1772 pthread_attr_init(&attr);
1773 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1774
1775 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1776 if (error != 0) {
1777 LOG(ERROR) << "pthread_create failed: " << strerror(error);
1778 return StringValue("");
1779 }
1780 }
1781
Tao Bao26efb0a2018-05-21 14:59:55 -07001782 // When performing an update, save the index and cmdline of the current command into the
1783 // last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001784 // Upon resuming an update, read the saved index first; then
1785 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1786 // the expected target blocks already. If not, these commands cannot be skipped and we need
1787 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1788 // the update will resume from the start of the transfer list.
1789 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1790 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1791 // If an update succeeds or is unresumable, delete the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -07001792 bool skip_executed_command = true;
1793 size_t saved_last_command_index;
Tianjie Xu284752e2017-12-05 11:04:17 -08001794 if (!ParseLastCommandFile(&saved_last_command_index)) {
1795 DeleteLastCommandFile();
Tao Bao26efb0a2018-05-21 14:59:55 -07001796 // We failed to parse the last command. Disallow skipping executed commands.
1797 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001798 }
1799
Tao Bao33567772017-03-13 14:57:34 -07001800 int rc = -1;
1801
1802 // Subsequent lines are all individual transfer commands
Tao Baoab207062018-05-21 14:48:49 -07001803 for (size_t i = kTransferListHeaderLines; i < lines.size(); i++) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001804 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001805 if (line.empty()) continue;
1806
Tao Bao26efb0a2018-05-21 14:59:55 -07001807 size_t cmdindex = i - kTransferListHeaderLines;
Tao Bao33567772017-03-13 14:57:34 -07001808 params.tokens = android::base::Split(line, " ");
1809 params.cpos = 0;
Tao Baoc3901232018-05-21 16:05:56 -07001810 params.cmdname = params.tokens[params.cpos++];
1811 params.cmdline = line;
Tianjie Xu284752e2017-12-05 11:04:17 -08001812 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001813
Tao Baoc3901232018-05-21 16:05:56 -07001814 Command::Type cmd_type = Command::ParseType(params.cmdname);
1815 if (cmd_type == Command::Type::LAST) {
Tao Bao33567772017-03-13 14:57:34 -07001816 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1817 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001818 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001819
Tao Baoc3901232018-05-21 16:05:56 -07001820 const CommandFunction& performer = command_map.at(cmd_type);
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001821
Tianjie Xuc2420842018-02-27 17:05:39 -08001822 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1823 // "erase" during block_image_verify.
Tao Baoc3901232018-05-21 16:05:56 -07001824 if (performer == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001825 LOG(DEBUG) << "skip executing command [" << line << "]";
1826 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001827 }
1828
Tao Bao98f875e2018-05-07 15:03:30 -07001829 // Skip all commands before the saved last command index when resuming an update, except for
1830 // "new" command. Because new commands read in the data sequentially.
Tao Bao26efb0a2018-05-21 14:59:55 -07001831 if (params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index &&
Tao Baoc3901232018-05-21 16:05:56 -07001832 cmd_type != Command::Type::NEW) {
Tao Bao26efb0a2018-05-21 14:59:55 -07001833 LOG(INFO) << "Skipping already executed command: " << cmdindex
Tianjie Xu284752e2017-12-05 11:04:17 -08001834 << ", last executed command for previous update: " << saved_last_command_index;
1835 continue;
1836 }
1837
Tao Baoc3901232018-05-21 16:05:56 -07001838 if (performer(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001839 LOG(ERROR) << "failed to execute command [" << line << "]";
Tianjie Xu69ffa152018-08-01 16:40:00 -07001840 if (cmd_type == Command::Type::COMPUTE_HASH_TREE && failure_type == kNoCause) {
1841 failure_type = kHashTreeComputationFailure;
1842 }
Tao Bao33567772017-03-13 14:57:34 -07001843 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001844 }
1845
Tao Bao26efb0a2018-05-21 14:59:55 -07001846 // In verify mode, check if the commands before the saved last_command_index have been executed
1847 // correctly. If some target blocks have unexpected contents, delete the last command file so
1848 // that we will resume the update from the first command in the transfer list.
1849 if (!params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001850 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tao Baoc3901232018-05-21 16:05:56 -07001851 if ((cmd_type == Command::Type::MOVE || cmd_type == Command::Type::BSDIFF ||
1852 cmd_type == Command::Type::IMGDIFF) &&
Tianjie Xu284752e2017-12-05 11:04:17 -08001853 !params.target_verified) {
1854 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1855 << params.cmdline << " doesn't produce expected target blocks.";
Tao Bao26efb0a2018-05-21 14:59:55 -07001856 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001857 DeleteLastCommandFile();
1858 }
1859 }
Tao Baoc3901232018-05-21 16:05:56 -07001860
Sami Tolvanen90221202014-12-09 16:39:47 +00001861 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001862 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001863 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001864 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001865 goto pbiudone;
1866 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001867
Tao Bao26efb0a2018-05-21 14:59:55 -07001868 if (!UpdateLastCommandIndex(cmdindex, params.cmdline)) {
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001869 LOG(WARNING) << "Failed to update the last command file.";
1870 }
1871
Tao Bao33567772017-03-13 14:57:34 -07001872 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1873 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001874 }
Tao Bao33567772017-03-13 14:57:34 -07001875 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001876
Tao Bao33567772017-03-13 14:57:34 -07001877 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001878
Tao Bao33567772017-03-13 14:57:34 -07001879pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001880 if (params.canwrite) {
1881 pthread_mutex_lock(&params.nti.mu);
1882 if (params.nti.receiver_available) {
1883 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1884 }
1885 params.nti.receiver_available = false;
1886 pthread_cond_broadcast(&params.nti.cv);
1887 pthread_mutex_unlock(&params.nti.mu);
1888 int ret = pthread_join(params.thread, nullptr);
1889 if (ret != 0) {
1890 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1891 }
1892
1893 if (rc == 0) {
1894 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1895 LOG(INFO) << "stashed " << params.stashed << " blocks";
1896 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1897
1898 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1899 if (partition != nullptr && *(partition + 1) != 0) {
1900 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1901 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1902 fflush(cmd_pipe);
1903 }
1904 // Delete stash only after successfully completing the update, as it may contain blocks needed
1905 // to complete the update later.
1906 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001907 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001908
1909 // Create a marker on /cache partition, which allows skipping the update on this partition on
1910 // retry. The marker will be removed once booting into normal boot, or before starting next
1911 // fresh install.
1912 if (!SetPartitionUpdatedMarker(updated_marker)) {
1913 LOG(WARNING) << "Failed to set updated marker; continuing";
1914 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001915 }
1916
1917 pthread_mutex_destroy(&params.nti.mu);
1918 pthread_cond_destroy(&params.nti.cv);
1919 } else if (rc == 0) {
1920 LOG(INFO) << "verified partition contents; update may be resumed";
1921 }
1922
Tao Bao33567772017-03-13 14:57:34 -07001923 if (ota_fsync(params.fd) == -1) {
1924 failure_type = kFsyncFailure;
1925 PLOG(ERROR) << "fsync failed";
1926 }
1927 // params.fd will be automatically closed because it's a unique_fd.
1928
Tianjie Xu107a34f2017-06-29 17:04:21 -07001929 if (params.nti.brotli_decoder_state != nullptr) {
1930 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1931 }
1932
Tianjie Xu284752e2017-12-05 11:04:17 -08001933 // Delete the last command file if the update cannot be resumed.
1934 if (params.isunresumable) {
1935 DeleteLastCommandFile();
1936 }
1937
Tao Bao33567772017-03-13 14:57:34 -07001938 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1939 // created the stash.
1940 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1941 DeleteStash(params.stashbase);
1942 }
1943
1944 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1945 state->cause_code = failure_type;
1946 }
1947
1948 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001949}
1950
Tao Bao33567772017-03-13 14:57:34 -07001951/**
1952 * The transfer list is a text file containing commands to transfer data from one place to another
1953 * on the target partition. We parse it and execute the commands in order:
1954 *
1955 * zero [rangeset]
1956 * - Fill the indicated blocks with zeros.
1957 *
1958 * new [rangeset]
1959 * - Fill the blocks with data read from the new_data file.
1960 *
1961 * erase [rangeset]
1962 * - Mark the given blocks as empty.
1963 *
1964 * move <...>
1965 * bsdiff <patchstart> <patchlen> <...>
1966 * imgdiff <patchstart> <patchlen> <...>
1967 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1968 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1969 *
1970 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1971 *
1972 * stash <stash_id> <src_range>
1973 * - Load the given source range and stash the data in the given slot of the stash table.
1974 *
1975 * free <stash_id>
1976 * - Free the given stash data.
1977 *
1978 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1979 * a patch or move) after it has been written.
1980 *
1981 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1982 * in a move/bsdiff/imgdiff command.
1983 *
1984 * Within one command the source and target ranges may overlap so in general we need to read the
1985 * entire source into memory before writing anything to the target blocks.
1986 *
1987 * All the patch data is concatenated into one patch_data file in the update package. It must be
1988 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1989 * already compressed, we lose very little by not compressing their concatenation.)
1990 *
1991 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1992 * additional hashes before the range parameters, which are used to check if the command has already
1993 * been completed and verify the integrity of the source data.
1994 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001995Value* BlockImageVerifyFn(const char* name, State* state,
1996 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001997 // Commands which are not allowed are set to nullptr to skip them completely.
1998 const CommandMap command_map{
1999 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07002000 { Command::Type::ABORT, PerformCommandAbort },
2001 { Command::Type::BSDIFF, PerformCommandDiff },
2002 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
2003 { Command::Type::ERASE, nullptr },
2004 { Command::Type::FREE, PerformCommandFree },
2005 { Command::Type::IMGDIFF, PerformCommandDiff },
2006 { Command::Type::MOVE, PerformCommandMove },
2007 { Command::Type::NEW, nullptr },
2008 { Command::Type::STASH, PerformCommandStash },
2009 { Command::Type::ZERO, nullptr },
Tao Baoc3901232018-05-21 16:05:56 -07002010 // clang-format on
2011 };
2012 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002013
Tao Baoc3901232018-05-21 16:05:56 -07002014 // Perform a dry run without writing to test if an update can proceed.
2015 return PerformBlockImageUpdate(name, state, argv, command_map, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00002016}
2017
Tianjie Xuc4447322017-03-06 14:44:59 -08002018Value* BlockImageUpdateFn(const char* name, State* state,
2019 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07002020 const CommandMap command_map{
2021 // clang-format off
Tianjie Xu69ffa152018-08-01 16:40:00 -07002022 { Command::Type::ABORT, PerformCommandAbort },
2023 { Command::Type::BSDIFF, PerformCommandDiff },
2024 { Command::Type::COMPUTE_HASH_TREE, PerformCommandComputeHashTree },
2025 { Command::Type::ERASE, PerformCommandErase },
2026 { Command::Type::FREE, PerformCommandFree },
2027 { Command::Type::IMGDIFF, PerformCommandDiff },
2028 { Command::Type::MOVE, PerformCommandMove },
2029 { Command::Type::NEW, PerformCommandNew },
2030 { Command::Type::STASH, PerformCommandStash },
2031 { Command::Type::ZERO, PerformCommandZero },
Tao Baoc3901232018-05-21 16:05:56 -07002032 // clang-format on
2033 };
2034 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00002035
Tao Baoc3901232018-05-21 16:05:56 -07002036 return PerformBlockImageUpdate(name, state, argv, command_map, false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002037}
2038
Tianjie Xuc4447322017-03-06 14:44:59 -08002039Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002040 if (argv.size() != 2) {
2041 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
2042 return StringValue("");
2043 }
2044
2045 std::vector<std::unique_ptr<Value>> args;
2046 if (!ReadValueArgs(state, argv, &args)) {
2047 return nullptr;
2048 }
2049
2050 const std::unique_ptr<Value>& blockdev_filename = args[0];
2051 const std::unique_ptr<Value>& ranges = args[1];
2052
Tao Bao511d7592018-06-19 15:56:49 -07002053 if (blockdev_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002054 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
2055 return StringValue("");
2056 }
Tao Bao511d7592018-06-19 15:56:49 -07002057 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002058 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2059 return StringValue("");
2060 }
2061
2062 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
2063 if (fd == -1) {
2064 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
2065 strerror(errno));
2066 return StringValue("");
2067 }
2068
2069 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07002070 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07002071
2072 SHA_CTX ctx;
2073 SHA1_Init(&ctx);
2074
2075 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07002076 for (const auto& range : rs) {
2077 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002078 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
2079 strerror(errno));
2080 return StringValue("");
2081 }
2082
Tao Baobf5b77d2017-03-30 16:57:29 -07002083 for (size_t j = range.first; j < range.second; ++j) {
Tao Baode3bbb82018-05-30 16:14:14 -07002084 if (read_all(fd, &buffer, BLOCKSIZE) == -1) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002085 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
2086 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002087 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002088 }
2089
2090 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002091 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002092 }
2093 uint8_t digest[SHA_DIGEST_LENGTH];
2094 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002095
Tao Baoc97edcb2017-03-31 01:18:13 -07002096 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002097}
2098
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002099// This function checks if a device has been remounted R/W prior to an incremental
2100// OTA update. This is an common cause of update abortion. The function reads the
2101// 1st block of each partition and check for mounting time/count. It return string "t"
2102// if executes successfully and an empty string otherwise.
2103
Tianjie Xuc4447322017-03-06 14:44:59 -08002104Value* CheckFirstBlockFn(const char* name, State* state,
2105 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002106 if (argv.size() != 1) {
2107 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2108 argv.size());
2109 return StringValue("");
2110 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002111
Tao Baoc97edcb2017-03-31 01:18:13 -07002112 std::vector<std::unique_ptr<Value>> args;
2113 if (!ReadValueArgs(state, argv, &args)) {
2114 return nullptr;
2115 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002116
Tao Baoc97edcb2017-03-31 01:18:13 -07002117 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002118
Tao Bao511d7592018-06-19 15:56:49 -07002119 if (arg_filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002120 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2121 return StringValue("");
2122 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002123
Tao Baoc97edcb2017-03-31 01:18:13 -07002124 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2125 if (fd == -1) {
2126 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2127 strerror(errno));
2128 return StringValue("");
2129 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002130
Tao Baobf5b77d2017-03-30 16:57:29 -07002131 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002132 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002133
Tao Baode3bbb82018-05-30 16:14:14 -07002134 if (ReadBlocks(blk0, &block0_buffer, fd) == -1) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002135 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2136 strerror(errno));
2137 return StringValue("");
2138 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002139
Tao Baoc97edcb2017-03-31 01:18:13 -07002140 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2141 // Super block starts from block 0, offset 0x400
2142 // 0x2C: len32 Mount time
2143 // 0x30: len32 Write time
2144 // 0x34: len16 Number of mounts since the last fsck
2145 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002146
Tao Baoc97edcb2017-03-31 01:18:13 -07002147 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2148 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002149
Tao Baoc97edcb2017-03-31 01:18:13 -07002150 if (mount_count > 0) {
2151 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2152 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2153 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002154
Tao Baoc97edcb2017-03-31 01:18:13 -07002155 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002156}
2157
Tianjie Xuc4447322017-03-06 14:44:59 -08002158Value* BlockImageRecoverFn(const char* name, State* state,
2159 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002160 if (argv.size() != 2) {
2161 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2162 argv.size());
2163 return StringValue("");
2164 }
2165
2166 std::vector<std::unique_ptr<Value>> args;
2167 if (!ReadValueArgs(state, argv, &args)) {
2168 return nullptr;
2169 }
2170
2171 const std::unique_ptr<Value>& filename = args[0];
2172 const std::unique_ptr<Value>& ranges = args[1];
2173
Tao Bao511d7592018-06-19 15:56:49 -07002174 if (filename->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002175 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2176 return StringValue("");
2177 }
Tao Bao511d7592018-06-19 15:56:49 -07002178 if (ranges->type != Value::Type::STRING) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002179 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2180 return StringValue("");
2181 }
Tao Bao67983152017-11-04 00:08:08 -07002182 RangeSet rs = RangeSet::Parse(ranges->data);
2183 if (!rs) {
2184 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2185 return StringValue("");
2186 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002187
2188 // Output notice to log when recover is attempted
2189 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2190
2191 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2192 fec::io fh(filename->data, O_RDWR);
2193
2194 if (!fh) {
2195 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2196 strerror(errno));
2197 return StringValue("");
2198 }
2199
2200 if (!fh.has_ecc() || !fh.has_verity()) {
2201 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2202 return StringValue("");
2203 }
2204
2205 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002206 if (!fh.get_status(status)) {
2207 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2208 return StringValue("");
2209 }
2210
Tao Baoc97edcb2017-03-31 01:18:13 -07002211 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002212 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002213 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002214 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002215 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002216 continue;
2217 }
2218
Tao Baobf5b77d2017-03-30 16:57:29 -07002219 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002220 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2221 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002222 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002223 }
2224
2225 // If we want to be able to recover from a situation where rewriting a corrected
2226 // block doesn't guarantee the same data will be returned when re-read later, we
2227 // can save a copy of corrected blocks to /cache. Note:
2228 //
2229 // 1. Maximum space required from /cache is the same as the maximum number of
2230 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2231 // this would be ~16 MiB, for example.
2232 //
2233 // 2. To find out if this block was corrupted, call fec_get_status after each
2234 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002235 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002236 }
2237 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2238 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002239}
2240
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002241void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002242 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2243 RegisterFunction("block_image_update", BlockImageUpdateFn);
2244 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2245 RegisterFunction("check_first_block", CheckFirstBlockFn);
2246 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002247}