blob: 156a8293917cd207395c00e214946491297d2b14 [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 Xu8cf5c8f2016-09-08 20:10:11 -070052#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070053
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070055#include "otafault/ota_io.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070056#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070057#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070058#include "otautil/print_sha1.h"
59#include "otautil/rangeset.h"
Tao Bao8f237572017-03-26 13:36:49 -070060#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070061#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070062
Sami Tolvanene82fa182015-06-10 15:58:12 +000063// Set this to 0 to interpret 'erase' transfers to mean do a
64// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
65// erase to mean fill the region with zeroes.
66#define DEBUG_ERASE 0
67
Tao Bao51412212016-12-28 14:44:05 -080068static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080069static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
70static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000071
Tianjie Xu16255832016-04-30 11:49:59 -070072static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070073static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070074static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070075
Tianjie Xu284752e2017-12-05 11:04:17 -080076static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070077 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080078 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
79 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
80 }
81}
82
83// Parse the last command index of the last update and save the result to |last_command_index|.
84// Return true if we successfully read the index.
85static bool ParseLastCommandFile(int* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070086 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080087 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
88 if (fd == -1) {
89 if (errno != ENOENT) {
90 PLOG(ERROR) << "Failed to open " << last_command_file;
91 return false;
92 }
93
94 LOG(INFO) << last_command_file << " doesn't exist.";
95 return false;
96 }
97
98 // Now that the last_command file exists, parse the last command index of previous update.
99 std::string content;
100 if (!android::base::ReadFdToString(fd.get(), &content)) {
101 LOG(ERROR) << "Failed to read: " << last_command_file;
102 return false;
103 }
104
105 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
106 if (lines.size() != 2) {
107 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
108 return false;
109 }
110
111 if (!android::base::ParseInt(lines[0], last_command_index)) {
112 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
113 return false;
114 }
115
116 return true;
117}
118
Tao Bao864c6682018-05-07 11:38:25 -0700119static bool FsyncDir(const std::string& dirname) {
120 android::base::unique_fd dfd(
121 TEMP_FAILURE_RETRY(ota_open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
122 if (dfd == -1) {
123 failure_type = kFileOpenFailure;
124 PLOG(ERROR) << "Failed to open " << dirname;
125 return false;
126 }
127 if (fsync(dfd) == -1) {
128 failure_type = kFsyncFailure;
129 PLOG(ERROR) << "Failed to fsync " << dirname;
130 return false;
131 }
132 return true;
133}
134
Tianjie Xu284752e2017-12-05 11:04:17 -0800135// Update the last command index in the last_command_file if the current command writes to the
136// stash either explicitly or implicitly.
137static bool UpdateLastCommandIndex(int command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700138 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800139 std::string last_command_tmp = last_command_file + ".tmp";
140 std::string content = std::to_string(command_index) + "\n" + command_string;
141 android::base::unique_fd wfd(
142 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
143 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
144 PLOG(ERROR) << "Failed to update last command";
145 return false;
146 }
147
148 if (fsync(wfd) == -1) {
149 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
150 return false;
151 }
152
153 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
154 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
155 return false;
156 }
157
158 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
159 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
160 return false;
161 }
162
Tao Bao864c6682018-05-07 11:38:25 -0700163 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800164 return false;
165 }
166
Tao Bao864c6682018-05-07 11:38:25 -0700167 return true;
168}
169
170static bool SetPartitionUpdatedMarker(const std::string& marker) {
171 if (!android::base::WriteStringToFile("", marker)) {
172 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800173 return false;
174 }
Tao Bao864c6682018-05-07 11:38:25 -0700175 if (!FsyncDir(android::base::Dirname(marker))) {
176 return false;
177 }
178 LOG(INFO) << "Wrote partition updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800179 return true;
180}
181
Sami Tolvanen90221202014-12-09 16:39:47 +0000182static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700183 size_t so_far = 0;
184 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800185 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700186 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700187 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800188 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000189 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700190 } else if (r == 0) {
191 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800192 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700193 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700195 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000197 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700198}
199
Tao Bao612336d2015-08-27 16:41:21 -0700200static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
201 return read_all(fd, buffer.data(), size);
202}
203
Sami Tolvanen90221202014-12-09 16:39:47 +0000204static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205 size_t written = 0;
206 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800207 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700208 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700209 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800210 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000211 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700212 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700213 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700214 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000215
Sami Tolvanen90221202014-12-09 16:39:47 +0000216 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700217}
218
Tao Bao612336d2015-08-27 16:41:21 -0700219static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
220 return write_all(fd, buffer.data(), size);
221}
222
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700223static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700224 // Don't discard blocks unless the update is a retry run.
225 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700226 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700227 }
228
229 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
230 if (ioctl(fd, BLKDISCARD, &args) == -1) {
231 PLOG(ERROR) << "BLKDISCARD ioctl failed";
232 return false;
233 }
234 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700235}
236
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700237static bool check_lseek(int fd, off64_t offset, int whence) {
238 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
239 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700240 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800241 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700242 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700243 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700244 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245}
246
Tao Bao612336d2015-08-27 16:41:21 -0700247static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700248 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700249 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700250
Tao Bao612336d2015-08-27 16:41:21 -0700251 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 Bao612336d2015-08-27 16:41:21 -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;
513 if (read_all(fd, buffer.data() + p, size) == -1) {
514 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;
Tianjie Xu284752e2017-12-05 11:04:17 -0800550 int cmdindex;
Tao Baobaad2d42015-12-06 16:56:27 -0800551 const char* cmdname;
552 const char* cmdline;
553 std::string freestash;
554 std::string stashbase;
555 bool canwrite;
556 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700557 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800558 bool foundwrites;
559 bool isunresumable;
560 int version;
561 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700562 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800563 NewThreadInfo nti;
564 pthread_t thread;
565 std::vector<uint8_t> buffer;
566 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800567 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800568};
569
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000570// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
571// handled separately).
572static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
573 const std::vector<uint8_t>& buffer) {
574 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000575 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
576 params.tokens[0] == "imgdiff");
577
578 size_t pos = 0;
579 // Command example:
580 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
581 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
582 // [<loc_range> <stashed_blocks>]
583 if (params.tokens[0] == "move") {
584 // src_range for move starts at the 4th position.
585 if (params.tokens.size() < 5) {
586 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
587 return;
588 }
589 pos = 4;
590 } else {
591 // src_range for diff starts at the 7th position.
592 if (params.tokens.size() < 8) {
593 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
594 return;
595 }
596 pos = 7;
597 }
598
599 // Source blocks in stash only, no work to do.
600 if (params.tokens[pos] == "-") {
601 return;
602 }
603
Tao Bao8f237572017-03-26 13:36:49 -0700604 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700605 if (!src) {
606 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
607 return;
608 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000609
610 RangeSet locs;
611 // If there's no stashed blocks, content in the buffer is consecutive and has the same
612 // order as the source blocks.
613 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700614 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000615 } else {
616 // Otherwise, the next token is the offset of the source blocks in the target range.
617 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
618 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
619 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700620 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700621 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000622 }
623
Tao Baobf5b77d2017-03-30 16:57:29 -0700624 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
625 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700626 size_t block_num = src.GetBlockNumber(i);
627 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000628 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
629
630 uint8_t digest[SHA_DIGEST_LENGTH];
631 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
632 std::string hexdigest = print_sha1(digest);
633 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
634 }
635}
636
637// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
638// in hex for each block.
639static void PrintHashForCorruptedStashedBlocks(const std::string& id,
640 const std::vector<uint8_t>& buffer,
641 const RangeSet& src) {
642 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700643 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000644
Tao Baobf5b77d2017-03-30 16:57:29 -0700645 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700646 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000647
648 uint8_t digest[SHA_DIGEST_LENGTH];
649 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
650 std::string hexdigest = print_sha1(digest);
651 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
652 }
653}
654
655// If the stash file doesn't exist, read the source blocks this stash contains and print the
656// SHA-1 for these blocks.
657static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
658 if (stash_map.find(id) == stash_map.end()) {
659 LOG(ERROR) << "No stash saved for id: " << id;
660 return;
661 }
662
663 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
664 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700665 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000666 if (ReadBlocks(src, buffer, fd) == -1) {
667 LOG(ERROR) << "failed to read source blocks for stash: " << id;
668 return;
669 }
670 PrintHashForCorruptedStashedBlocks(id, buffer, src);
671}
672
Tao Bao612336d2015-08-27 16:41:21 -0700673static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700674 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800675 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700676 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000677
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800678 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000679
Tao Baoe6aa3322015-08-05 15:20:27 -0700680 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000681
Tao Bao0940fe12015-08-27 16:41:21 -0700682 if (hexdigest != expected) {
683 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800684 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
685 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700686 }
687 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000688 }
689
Tao Bao0940fe12015-08-27 16:41:21 -0700690 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000691}
692
Tao Bao0940fe12015-08-27 16:41:21 -0700693static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700694 const std::string& postfix) {
695 if (base.empty()) {
696 return "";
697 }
Tao Bao864c6682018-05-07 11:38:25 -0700698 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
699 if (id.empty() && postfix.empty()) {
700 return filename;
701 }
702 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000703}
704
Tao Baoec8272f2017-03-15 17:39:01 -0700705// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
706// directory and continues despite of errors. Calls the 'callback' function for each file.
707static void EnumerateStash(const std::string& dirname,
708 const std::function<void(const std::string&)>& callback) {
709 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000710
Tao Baoec8272f2017-03-15 17:39:01 -0700711 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000712
Tao Baoec8272f2017-03-15 17:39:01 -0700713 if (directory == nullptr) {
714 if (errno != ENOENT) {
715 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000716 }
Tao Bao51412212016-12-28 14:44:05 -0800717 return;
718 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700719
Tao Baoec8272f2017-03-15 17:39:01 -0700720 dirent* item;
721 while ((item = readdir(directory.get())) != nullptr) {
722 if (item->d_type != DT_REG) continue;
723 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800724 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000725}
726
727// Deletes the stash directory and all files in it. Assumes that it only
728// contains files. There is nothing we can do about unlikely, but possible
729// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700730static void DeleteFile(const std::string& fn) {
731 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732
Tao Baoec8272f2017-03-15 17:39:01 -0700733 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000734
Tao Baoec8272f2017-03-15 17:39:01 -0700735 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
736 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
737 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000738}
739
Tao Baoe6aa3322015-08-05 15:20:27 -0700740static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700741 if (base.empty()) return;
742
743 LOG(INFO) << "deleting stash " << base;
744
745 std::string dirname = GetStashFileName(base, "", "");
746 EnumerateStash(dirname, DeleteFile);
747
748 if (rmdir(dirname.c_str()) == -1) {
749 if (errno != ENOENT && errno != ENOTDIR) {
750 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000751 }
Tao Baoec8272f2017-03-15 17:39:01 -0700752 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000753}
754
Tao Baobcf46492017-03-23 15:28:20 -0700755static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
756 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700757 // In verify mode, if source range_set was saved for the given hash, check contents in the source
758 // blocks first. If the check fails, search for the stashed files on /cache as usual.
759 if (!params.canwrite) {
760 if (stash_map.find(id) != stash_map.end()) {
761 const RangeSet& src = stash_map[id];
762 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700763
Tao Baobf5b77d2017-03-30 16:57:29 -0700764 if (ReadBlocks(src, buffer, params.fd) == -1) {
765 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700766 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700767 }
768 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
769 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
770 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700771 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700772 }
773 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000774 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000776
Tao Baobf5b77d2017-03-30 16:57:29 -0700777 size_t blockcount = 0;
778 if (!blocks) {
779 blocks = &blockcount;
780 }
781
782 std::string fn = GetStashFileName(params.stashbase, id, "");
783
784 struct stat sb;
785 if (stat(fn.c_str(), &sb) == -1) {
786 if (errno != ENOENT || printnoent) {
787 PLOG(ERROR) << "stat \"" << fn << "\" failed";
788 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000789 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700790 return -1;
791 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000792
Tao Baobf5b77d2017-03-30 16:57:29 -0700793 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000794
Tao Baobf5b77d2017-03-30 16:57:29 -0700795 if ((sb.st_size % BLOCKSIZE) != 0) {
796 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
797 return -1;
798 }
799
800 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
801 if (fd == -1) {
802 PLOG(ERROR) << "open \"" << fn << "\" failed";
803 return -1;
804 }
805
806 allocate(sb.st_size, buffer);
807
808 if (read_all(fd, buffer, sb.st_size) == -1) {
809 return -1;
810 }
811
812 *blocks = sb.st_size / BLOCKSIZE;
813
814 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
815 LOG(ERROR) << "unexpected contents in " << fn;
816 if (stash_map.find(id) == stash_map.end()) {
817 LOG(ERROR) << "failed to find source blocks number for stash " << id
818 << " when executing command: " << params.cmdname;
819 } else {
820 const RangeSet& src = stash_map[id];
821 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000822 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700823 DeleteFile(fn);
824 return -1;
825 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000826
Tao Baobf5b77d2017-03-30 16:57:29 -0700827 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000828}
829
Tao Bao612336d2015-08-27 16:41:21 -0700830static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700831 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700832 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700833 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000834 }
835
836 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800837 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700838 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000839 }
840
Tao Bao0940fe12015-08-27 16:41:21 -0700841 std::string fn = GetStashFileName(base, id, ".partial");
842 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000843
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100844 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700845 struct stat sb;
846 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100847
848 if (res == 0) {
849 // The file already exists and since the name is the hash of the contents,
850 // it's safe to assume the contents are identical (accidental hash collisions
851 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800852 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700853 *exists = true;
854 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100855 }
856
Tao Bao0940fe12015-08-27 16:41:21 -0700857 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100858 }
859
Tao Bao039f2da2016-11-22 16:29:50 -0800860 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000861
Tao Bao039f2da2016-11-22 16:29:50 -0800862 android::base::unique_fd fd(
863 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000864 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800865 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700866 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000867 }
868
Tianjie Xua946b9e2017-03-21 16:24:57 -0700869 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
870 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
871 return -1;
872 }
873
Sami Tolvanen90221202014-12-09 16:39:47 +0000874 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700875 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000876 }
877
Jed Estepa7b9a462015-12-15 16:04:53 -0800878 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700879 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800880 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700881 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000882 }
883
Tao Baoe6aa3322015-08-05 15:20:27 -0700884 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800885 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700886 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000887 }
888
Tao Bao0940fe12015-08-27 16:41:21 -0700889 std::string dname = GetStashFileName(base, "", "");
Tao Bao864c6682018-05-07 11:38:25 -0700890 if (!FsyncDir(dname)) {
891 failure_type = kFsyncFailure;
892 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700893 }
894
Tao Bao0940fe12015-08-27 16:41:21 -0700895 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000896}
897
898// Creates a directory for storing stash files and checks if the /cache partition
899// hash enough space for the expected amount of blocks we need to store. Returns
900// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700901static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800902 std::string dirname = GetStashFileName(base, "", "");
903 struct stat sb;
904 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800905 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800906 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800907 strerror(errno));
908 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700909 }
910
911 size_t max_stash_size = maxblocks * BLOCKSIZE;
912 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800913 LOG(INFO) << "creating stash " << dirname;
914 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
915
916 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800917 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800918 strerror(errno));
919 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000920 }
921
Tianjie Xua946b9e2017-03-21 16:24:57 -0700922 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800923 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700924 strerror(errno));
925 return -1;
926 }
927
Tao Bao51412212016-12-28 14:44:05 -0800928 if (CacheSizeCheck(max_stash_size) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800929 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800930 max_stash_size);
931 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 }
933
Tao Bao51412212016-12-28 14:44:05 -0800934 return 1; // Created directory
935 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000936
Tao Bao51412212016-12-28 14:44:05 -0800937 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000938
Tao Baoec8272f2017-03-15 17:39:01 -0700939 // If the directory already exists, calculate the space already allocated to stash files and check
940 // if there's enough for all required blocks. Delete any partially completed stash files first.
941 EnumerateStash(dirname, [](const std::string& fn) {
942 if (android::base::EndsWith(fn, ".partial")) {
943 DeleteFile(fn);
944 }
945 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000946
Tao Bao51412212016-12-28 14:44:05 -0800947 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700948 EnumerateStash(dirname, [&existing](const std::string& fn) {
949 if (fn.empty()) return;
950 struct stat sb;
951 if (stat(fn.c_str(), &sb) == -1) {
952 PLOG(ERROR) << "stat \"" << fn << "\" failed";
953 return;
954 }
955 existing += static_cast<size_t>(sb.st_size);
956 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000957
Tao Bao51412212016-12-28 14:44:05 -0800958 if (max_stash_size > existing) {
959 size_t needed = max_stash_size - existing;
960 if (CacheSizeCheck(needed) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800961 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800962 needed);
963 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000964 }
Tao Bao51412212016-12-28 14:44:05 -0800965 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000966
Tao Bao51412212016-12-28 14:44:05 -0800967 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000968}
969
Tao Baobaad2d42015-12-06 16:56:27 -0800970static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700971 if (base.empty() || id.empty()) {
972 return -1;
973 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000974
Tao Baoec8272f2017-03-15 17:39:01 -0700975 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000976
Tao Baoec8272f2017-03-15 17:39:01 -0700977 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700978}
979
Tao Baobf5b77d2017-03-30 16:57:29 -0700980// Source contains packed data, which we want to move to the locations given in locs in the dest
981// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700982static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700983 const std::vector<uint8_t>& source) {
984 const uint8_t* from = source.data();
985 uint8_t* to = dest.data();
986 size_t start = locs.blocks();
987 // Must do the movement backward.
988 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
989 size_t blocks = it->second - it->first;
990 start -= blocks;
991 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
992 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700993}
994
Tao Baod2aecd42017-03-23 14:43:44 -0700995/**
996 * We expect to parse the remainder of the parameter tokens as one of:
997 *
998 * <src_block_count> <src_range>
999 * (loads data from source image only)
1000 *
1001 * <src_block_count> - <[stash_id:stash_range] ...>
1002 * (loads data from stashes only)
1003 *
1004 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1005 * (loads data from both source image and stashes)
1006 *
1007 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1008 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1009 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1010 * LoadStash.
1011 */
1012static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1013 bool* overlap) {
1014 CHECK(src_blocks != nullptr);
1015 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001016
Tao Baod2aecd42017-03-23 14:43:44 -07001017 // <src_block_count>
1018 const std::string& token = params.tokens[params.cpos++];
1019 if (!android::base::ParseUint(token, src_blocks)) {
1020 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1021 return -1;
1022 }
Tao Baobaad2d42015-12-06 16:56:27 -08001023
Tao Baod2aecd42017-03-23 14:43:44 -07001024 allocate(*src_blocks * BLOCKSIZE, params.buffer);
1025
1026 // "-" or <src_range> [<src_loc>]
1027 if (params.tokens[params.cpos] == "-") {
1028 // no source ranges, only stashes
1029 params.cpos++;
1030 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001031 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001032 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001033 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001034
1035 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1036 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001037 }
1038
Tao Baod2aecd42017-03-23 14:43:44 -07001039 if (params.cpos >= params.tokens.size()) {
1040 // no stashes, only source range
1041 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001042 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001043
Tao Bao8f237572017-03-26 13:36:49 -07001044 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001045 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001046 MoveRange(params.buffer, locs, params.buffer);
1047 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001048
Tao Baod2aecd42017-03-23 14:43:44 -07001049 // <[stash_id:stash_range]>
1050 while (params.cpos < params.tokens.size()) {
1051 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1052 // in the source block that stashed data should go.
1053 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1054 if (tokens.size() != 2) {
1055 LOG(ERROR) << "invalid parameter";
1056 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001057 }
1058
Tao Baod2aecd42017-03-23 14:43:44 -07001059 std::vector<uint8_t> stash;
1060 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
1061 // These source blocks will fail verification if used later, but we
1062 // will let the caller decide if this is a fatal failure
1063 LOG(ERROR) << "failed to load stash " << tokens[0];
1064 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001065 }
1066
Tao Bao8f237572017-03-26 13:36:49 -07001067 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001068 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001069 MoveRange(params.buffer, locs, stash);
1070 }
1071
1072 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001073}
1074
Tao Bao33567772017-03-13 14:57:34 -07001075/**
1076 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1077 *
1078 * We expect to parse the remainder of the parameter tokens as one of:
1079 *
1080 * <tgt_range> <src_block_count> <src_range>
1081 * (loads data from source image only)
1082 *
1083 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1084 * (loads data from stashes only)
1085 *
1086 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1087 * (loads data from both source image and stashes)
1088 *
Tao Baod2aecd42017-03-23 14:43:44 -07001089 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1090 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001091 * verification fails in a way that the update cannot be resumed anymore.
1092 *
1093 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1094 * the return value is -1 and the command should be aborted.
1095 *
1096 * If the return value is 1, the command has already been completed according to the contents of the
1097 * target blocks, and should not be performed again.
1098 *
1099 * If the return value is 0, source blocks have expected content and the command can be performed.
1100 */
Tao Baod2aecd42017-03-23 14:43:44 -07001101static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
1102 bool onehash, bool* overlap) {
1103 CHECK(src_blocks != nullptr);
1104 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001105
Tao Baod2aecd42017-03-23 14:43:44 -07001106 if (params.cpos >= params.tokens.size()) {
1107 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001108 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001109 }
1110
1111 std::string srchash = params.tokens[params.cpos++];
1112 std::string tgthash;
1113
1114 if (onehash) {
1115 tgthash = srchash;
1116 } else {
1117 if (params.cpos >= params.tokens.size()) {
1118 LOG(ERROR) << "missing target hash";
1119 return -1;
1120 }
1121 tgthash = params.tokens[params.cpos++];
1122 }
1123
1124 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1125 // "-"/<src_range>.
1126 if (params.cpos + 2 >= params.tokens.size()) {
1127 LOG(ERROR) << "invalid parameters";
1128 return -1;
1129 }
1130
1131 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -07001132 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001133 CHECK(static_cast<bool>(tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001134
Tao Baobf5b77d2017-03-30 16:57:29 -07001135 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -07001136 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1137 return -1;
1138 }
1139
1140 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -07001141 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001142 return 1;
1143 }
1144
1145 // Load source blocks.
1146 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1147 return -1;
1148 }
1149
1150 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1151 // If source and target blocks overlap, stash the source blocks so we can
1152 // resume from possible write errors. In verify mode, we can skip stashing
1153 // because the source blocks won't be overwritten.
1154 if (*overlap && params.canwrite) {
1155 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1156
1157 bool stash_exists = false;
1158 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1159 &stash_exists) != 0) {
1160 LOG(ERROR) << "failed to stash overlapping source blocks";
1161 return -1;
1162 }
1163
Tianjie Xu284752e2017-12-05 11:04:17 -08001164 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1165 LOG(WARNING) << "Failed to update the last command file.";
1166 }
1167
Tao Baod2aecd42017-03-23 14:43:44 -07001168 params.stashed += *src_blocks;
1169 // Can be deleted when the write has completed.
1170 if (!stash_exists) {
1171 params.freestash = srchash;
1172 }
1173 }
1174
1175 // Source blocks have expected content, command can proceed.
1176 return 0;
1177 }
1178
1179 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1180 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1181 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1182 // command.
1183 return 0;
1184 }
1185
1186 // Valid source data not available, update cannot be resumed.
1187 LOG(ERROR) << "partition has unexpected contents";
1188 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1189
1190 params.isunresumable = true;
1191
1192 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001193}
1194
Tao Bao0940fe12015-08-27 16:41:21 -07001195static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001196 size_t blocks = 0;
1197 bool overlap = false;
1198 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001199 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001200
Tao Bao33567772017-03-13 14:57:34 -07001201 if (status == -1) {
1202 LOG(ERROR) << "failed to read blocks for move";
1203 return -1;
1204 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001205
Tao Bao33567772017-03-13 14:57:34 -07001206 if (status == 0) {
1207 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001208 } else {
1209 params.target_verified = true;
1210 if (params.foundwrites) {
1211 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1212 }
Tao Bao33567772017-03-13 14:57:34 -07001213 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001214
Tao Bao33567772017-03-13 14:57:34 -07001215 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001216 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001217 LOG(INFO) << " moving " << blocks << " blocks";
1218
1219 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1220 return -1;
1221 }
1222 } else {
1223 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001224 }
Tao Bao33567772017-03-13 14:57:34 -07001225 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001226
Tao Bao33567772017-03-13 14:57:34 -07001227 if (!params.freestash.empty()) {
1228 FreeStash(params.stashbase, params.freestash);
1229 params.freestash.clear();
1230 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001231
Tao Baobf5b77d2017-03-30 16:57:29 -07001232 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001233
Tao Bao33567772017-03-13 14:57:34 -07001234 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001235}
1236
Tao Bao0940fe12015-08-27 16:41:21 -07001237static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001238 // <stash_id> <src_range>
1239 if (params.cpos + 1 >= params.tokens.size()) {
1240 LOG(ERROR) << "missing id and/or src range fields in stash command";
1241 return -1;
1242 }
1243
1244 const std::string& id = params.tokens[params.cpos++];
1245 size_t blocks = 0;
1246 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1247 // Stash file already exists and has expected contents. Do not read from source again, as the
1248 // source may have been already overwritten during a previous attempt.
1249 return 0;
1250 }
1251
Tao Bao8f237572017-03-26 13:36:49 -07001252 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001253 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001254
Tao Baobf5b77d2017-03-30 16:57:29 -07001255 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001256 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1257 return -1;
1258 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001259 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001260 stash_map[id] = src;
1261
1262 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1263 // Source blocks have unexpected contents. If we actually need this data later, this is an
1264 // unrecoverable error. However, the command that uses the data may have already completed
1265 // previously, so the possible failure will occur during source block verification.
1266 LOG(ERROR) << "failed to load source blocks for stash " << id;
1267 return 0;
1268 }
1269
1270 // In verify mode, we don't need to stash any blocks.
1271 if (!params.canwrite) {
1272 return 0;
1273 }
1274
1275 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001276 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1277 if (result == 0) {
1278 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1279 LOG(WARNING) << "Failed to update the last command file.";
1280 }
1281
1282 params.stashed += blocks;
1283 }
1284 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001285}
1286
Tao Bao0940fe12015-08-27 16:41:21 -07001287static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001288 // <stash_id>
1289 if (params.cpos >= params.tokens.size()) {
1290 LOG(ERROR) << "missing stash id in free command";
1291 return -1;
1292 }
Tao Baobaad2d42015-12-06 16:56:27 -08001293
Tao Baobcf46492017-03-23 15:28:20 -07001294 const std::string& id = params.tokens[params.cpos++];
1295 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001296
Tao Baobcf46492017-03-23 15:28:20 -07001297 if (params.createdstash || params.canwrite) {
1298 return FreeStash(params.stashbase, id);
1299 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001300
Tao Baobcf46492017-03-23 15:28:20 -07001301 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302}
1303
Tao Bao0940fe12015-08-27 16:41:21 -07001304static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001305 if (params.cpos >= params.tokens.size()) {
1306 LOG(ERROR) << "missing target blocks for zero";
1307 return -1;
1308 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001309
Tao Baobf5b77d2017-03-30 16:57:29 -07001310 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001311 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001312
1313 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1314
1315 allocate(BLOCKSIZE, params.buffer);
1316 memset(params.buffer.data(), 0, BLOCKSIZE);
1317
1318 if (params.canwrite) {
1319 for (const auto& range : tgt) {
1320 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1321 size_t size = (range.second - range.first) * BLOCKSIZE;
1322 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001323 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001324 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001325
Tao Baobf5b77d2017-03-30 16:57:29 -07001326 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1327 return -1;
1328 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001329
Tao Baobf5b77d2017-03-30 16:57:29 -07001330 for (size_t j = range.first; j < range.second; ++j) {
1331 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1332 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001333 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001334 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001335 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001336 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001337
Tao Baobf5b77d2017-03-30 16:57:29 -07001338 if (params.cmdname[0] == 'z') {
1339 // Update only for the zero command, as the erase command will call
1340 // this if DEBUG_ERASE is defined.
1341 params.written += tgt.blocks();
1342 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001343
Tao Baobf5b77d2017-03-30 16:57:29 -07001344 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001345}
1346
Tao Bao0940fe12015-08-27 16:41:21 -07001347static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001348 if (params.cpos >= params.tokens.size()) {
1349 LOG(ERROR) << "missing target blocks for new";
1350 return -1;
1351 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001352
Tao Bao8f237572017-03-26 13:36:49 -07001353 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001354 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001355
1356 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001357 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001358
Tao Bao60a70af2017-03-26 14:03:52 -07001359 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001360 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001361 pthread_cond_broadcast(&params.nti.cv);
1362
1363 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001364 if (!params.nti.receiver_available) {
1365 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1366 << " bytes of new data";
1367 pthread_mutex_unlock(&params.nti.mu);
1368 return -1;
1369 }
Tao Bao60a70af2017-03-26 14:03:52 -07001370 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001371 }
1372
Tao Bao60a70af2017-03-26 14:03:52 -07001373 pthread_mutex_unlock(&params.nti.mu);
1374 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001375
Tao Baobf5b77d2017-03-30 16:57:29 -07001376 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001377
Tao Bao60a70af2017-03-26 14:03:52 -07001378 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001379}
1380
Tao Bao0940fe12015-08-27 16:41:21 -07001381static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001382 // <offset> <length>
1383 if (params.cpos + 1 >= params.tokens.size()) {
1384 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1385 return -1;
1386 }
Tao Bao0940fe12015-08-27 16:41:21 -07001387
Tao Baoc0e1c462017-02-01 10:20:10 -08001388 size_t offset;
1389 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1390 LOG(ERROR) << "invalid patch offset";
1391 return -1;
1392 }
Tao Bao0940fe12015-08-27 16:41:21 -07001393
Tao Baoc0e1c462017-02-01 10:20:10 -08001394 size_t len;
1395 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1396 LOG(ERROR) << "invalid patch len";
1397 return -1;
1398 }
Tao Bao0940fe12015-08-27 16:41:21 -07001399
Tao Baoc0e1c462017-02-01 10:20:10 -08001400 RangeSet tgt;
1401 size_t blocks = 0;
1402 bool overlap = false;
1403 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001404
Tao Baoc0e1c462017-02-01 10:20:10 -08001405 if (status == -1) {
1406 LOG(ERROR) << "failed to read blocks for diff";
1407 return -1;
1408 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001409
Tao Baoc0e1c462017-02-01 10:20:10 -08001410 if (status == 0) {
1411 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001412 } else {
1413 params.target_verified = true;
1414 if (params.foundwrites) {
1415 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1416 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001417 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001418
Tao Baoc0e1c462017-02-01 10:20:10 -08001419 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001420 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001421 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001422 Value patch_value(
1423 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001424
Tao Bao60a70af2017-03-26 14:03:52 -07001425 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001426 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001427 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001428 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1429 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001430 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001431 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001432 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001433 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001434 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001435 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001436 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001437 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001438 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001439 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001440 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001441 return -1;
1442 }
1443 }
1444
1445 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001446 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001447 LOG(ERROR) << "range sink underrun?";
1448 }
1449 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001450 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001451 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001452 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001453 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001454
Tao Baoc0e1c462017-02-01 10:20:10 -08001455 if (!params.freestash.empty()) {
1456 FreeStash(params.stashbase, params.freestash);
1457 params.freestash.clear();
1458 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001459
Tao Baobf5b77d2017-03-30 16:57:29 -07001460 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001461
Tao Baoc0e1c462017-02-01 10:20:10 -08001462 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001463}
1464
Tao Bao0940fe12015-08-27 16:41:21 -07001465static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001466 if (DEBUG_ERASE) {
1467 return PerformCommandZero(params);
1468 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001469
Tao Baobf5b77d2017-03-30 16:57:29 -07001470 struct stat sb;
1471 if (fstat(params.fd, &sb) == -1) {
1472 PLOG(ERROR) << "failed to fstat device to erase";
1473 return -1;
1474 }
1475
1476 if (!S_ISBLK(sb.st_mode)) {
1477 LOG(ERROR) << "not a block device; skipping erase";
1478 return -1;
1479 }
1480
1481 if (params.cpos >= params.tokens.size()) {
1482 LOG(ERROR) << "missing target blocks for erase";
1483 return -1;
1484 }
1485
1486 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001487 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001488
1489 if (params.canwrite) {
1490 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1491
1492 for (const auto& range : tgt) {
1493 uint64_t blocks[2];
1494 // offset in bytes
1495 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1496 // length in bytes
1497 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1498
1499 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1500 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001501 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001502 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001503 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001504 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001505
Tao Baobf5b77d2017-03-30 16:57:29 -07001506 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001507}
1508
1509// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001510typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001511
Tao Bao612336d2015-08-27 16:41:21 -07001512struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001513 const char* name;
1514 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001515};
Sami Tolvanen90221202014-12-09 16:39:47 +00001516
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001517// args:
1518// - block device (or file) to modify in-place
1519// - transfer list (blob)
1520// - new data stream (filename within package.zip)
1521// - patch stream (filename within package.zip, must be uncompressed)
1522
Tianjie Xuc4447322017-03-06 14:44:59 -08001523static Value* PerformBlockImageUpdate(const char* name, State* state,
1524 const std::vector<std::unique_ptr<Expr>>& argv,
1525 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001526 CommandParameters params = {};
1527 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001528
Tao Bao33567772017-03-13 14:57:34 -07001529 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1530 if (state->is_retry) {
1531 is_retry = true;
1532 LOG(INFO) << "This update is a retry.";
1533 }
1534 if (argv.size() != 4) {
1535 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1536 argv.size());
1537 return StringValue("");
1538 }
1539
1540 std::vector<std::unique_ptr<Value>> args;
1541 if (!ReadValueArgs(state, argv, &args)) {
1542 return nullptr;
1543 }
1544
Tao Baoc97edcb2017-03-31 01:18:13 -07001545 const std::unique_ptr<Value>& blockdev_filename = args[0];
1546 const std::unique_ptr<Value>& transfer_list_value = args[1];
1547 const std::unique_ptr<Value>& new_data_fn = args[2];
1548 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001549
1550 if (blockdev_filename->type != VAL_STRING) {
1551 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1552 return StringValue("");
1553 }
1554 if (transfer_list_value->type != VAL_BLOB) {
1555 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1556 return StringValue("");
1557 }
1558 if (new_data_fn->type != VAL_STRING) {
1559 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1560 return StringValue("");
1561 }
1562 if (patch_data_fn->type != VAL_STRING) {
1563 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1564 return StringValue("");
1565 }
1566
1567 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1568 if (ui == nullptr) {
1569 return StringValue("");
1570 }
1571
1572 FILE* cmd_pipe = ui->cmd_pipe;
1573 ZipArchiveHandle za = ui->package_zip;
1574
1575 if (cmd_pipe == nullptr || za == nullptr) {
1576 return StringValue("");
1577 }
1578
1579 ZipString path_data(patch_data_fn->data.c_str());
1580 ZipEntry patch_entry;
1581 if (FindEntry(za, path_data, &patch_entry) != 0) {
1582 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1583 return StringValue("");
1584 }
1585
1586 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1587 ZipString new_data(new_data_fn->data.c_str());
1588 ZipEntry new_entry;
1589 if (FindEntry(za, new_data, &new_entry) != 0) {
1590 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1591 return StringValue("");
1592 }
1593
1594 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1595 if (params.fd == -1) {
1596 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1597 return StringValue("");
1598 }
1599
Tao Bao864c6682018-05-07 11:38:25 -07001600 // Stash directory should be different for each partition to avoid conflicts when updating
1601 // multiple partitions at the same time, so we use the hash of the block device name as the base
1602 // directory.
1603 uint8_t digest[SHA_DIGEST_LENGTH];
1604 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1605 blockdev_filename->data.size(), digest);
1606 params.stashbase = print_sha1(digest);
1607
1608 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1609 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1610 // fail the no-op retry.
1611 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1612 if (is_retry) {
1613 struct stat sb;
1614 int result = stat(updated_marker.c_str(), &sb);
1615 if (result == 0) {
1616 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1617 << " based on marker";
1618 return StringValue("t");
1619 }
1620 } else {
1621 // Delete the obsolete marker if any.
1622 std::string err;
1623 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1624 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1625 return StringValue("");
1626 }
1627 }
1628
Tao Bao33567772017-03-13 14:57:34 -07001629 if (params.canwrite) {
1630 params.nti.za = za;
1631 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001632 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1633 if (params.nti.brotli_compressed) {
1634 // Initialize brotli decoder state.
1635 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1636 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001637 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001638
1639 pthread_mutex_init(&params.nti.mu, nullptr);
1640 pthread_cond_init(&params.nti.cv, nullptr);
1641 pthread_attr_t attr;
1642 pthread_attr_init(&attr);
1643 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1644
1645 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1646 if (error != 0) {
1647 PLOG(ERROR) << "pthread_create failed";
1648 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001649 }
Tao Bao33567772017-03-13 14:57:34 -07001650 }
1651
1652 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1653 if (lines.size() < 2) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001654 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]",
Tao Bao33567772017-03-13 14:57:34 -07001655 lines.size());
1656 return StringValue("");
1657 }
1658
1659 // First line in transfer list is the version number.
1660 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1661 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1662 return StringValue("");
1663 }
1664
1665 LOG(INFO) << "blockimg version is " << params.version;
1666
1667 // Second line in transfer list is the total number of blocks we expect to write.
1668 size_t total_blocks;
1669 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001670 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001671 return StringValue("");
1672 }
1673
1674 if (total_blocks == 0) {
1675 return StringValue("t");
1676 }
1677
1678 size_t start = 2;
1679 if (lines.size() < 4) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001680 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001681 lines.size());
1682 return StringValue("");
1683 }
1684
1685 // Third line is how many stash entries are needed simultaneously.
1686 LOG(INFO) << "maximum stash entries " << lines[2];
1687
1688 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1689 size_t stash_max_blocks;
1690 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001691 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001692 lines[3].c_str());
1693 return StringValue("");
1694 }
1695
Tao Bao864c6682018-05-07 11:38:25 -07001696 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001697 if (res == -1) {
1698 return StringValue("");
1699 }
1700
1701 params.createdstash = res;
1702
Tianjie Xu284752e2017-12-05 11:04:17 -08001703 // When performing an update, save the index and cmdline of the current command into
1704 // the last_command_file if this command writes to the stash either explicitly of implicitly.
1705 // Upon resuming an update, read the saved index first; then
1706 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1707 // the expected target blocks already. If not, these commands cannot be skipped and we need
1708 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1709 // the update will resume from the start of the transfer list.
1710 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1711 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1712 // If an update succeeds or is unresumable, delete the last_command_file.
1713 int saved_last_command_index;
1714 if (!ParseLastCommandFile(&saved_last_command_index)) {
1715 DeleteLastCommandFile();
1716 // We failed to parse the last command, set it explicitly to -1.
1717 saved_last_command_index = -1;
1718 }
1719
Tao Bao33567772017-03-13 14:57:34 -07001720 start += 2;
1721
1722 // Build a map of the available commands
1723 std::unordered_map<std::string, const Command*> cmd_map;
1724 for (size_t i = 0; i < cmdcount; ++i) {
1725 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1726 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
Tao Bao188f3a52018-04-24 14:15:14 -07001727 return StringValue("");
Tao Bao33567772017-03-13 14:57:34 -07001728 }
1729 cmd_map[commands[i].name] = &commands[i];
1730 }
1731
1732 int rc = -1;
1733
1734 // Subsequent lines are all individual transfer commands
Tianjie Xu284752e2017-12-05 11:04:17 -08001735 for (size_t i = start; i < lines.size(); i++) {
1736 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001737 if (line.empty()) continue;
1738
1739 params.tokens = android::base::Split(line, " ");
1740 params.cpos = 0;
Tianjie Xu284752e2017-12-05 11:04:17 -08001741 if (i - start > std::numeric_limits<int>::max()) {
1742 params.cmdindex = -1;
1743 } else {
1744 params.cmdindex = i - start;
1745 }
Tao Bao33567772017-03-13 14:57:34 -07001746 params.cmdname = params.tokens[params.cpos++].c_str();
1747 params.cmdline = line.c_str();
Tianjie Xu284752e2017-12-05 11:04:17 -08001748 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001749
1750 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1751 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1752 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001753 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001754
Tao Bao33567772017-03-13 14:57:34 -07001755 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001756
Tianjie Xuc2420842018-02-27 17:05:39 -08001757 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1758 // "erase" during block_image_verify.
Tianjie Xu284752e2017-12-05 11:04:17 -08001759 if (cmd->f == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001760 LOG(DEBUG) << "skip executing command [" << line << "]";
1761 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001762 }
1763
Tao Bao98f875e2018-05-07 15:03:30 -07001764 std::string cmdname = std::string(params.cmdname);
1765
1766 // Skip all commands before the saved last command index when resuming an update, except for
1767 // "new" command. Because new commands read in the data sequentially.
1768 if (params.canwrite && params.cmdindex != -1 && params.cmdindex <= saved_last_command_index &&
1769 cmdname != "new") {
Tianjie Xu284752e2017-12-05 11:04:17 -08001770 LOG(INFO) << "Skipping already executed command: " << params.cmdindex
1771 << ", last executed command for previous update: " << saved_last_command_index;
1772 continue;
1773 }
1774
1775 if (cmd->f(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001776 LOG(ERROR) << "failed to execute command [" << line << "]";
1777 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001778 }
1779
Tianjie Xu284752e2017-12-05 11:04:17 -08001780 // In verify mode, check if the commands before the saved last_command_index have been
1781 // executed correctly. If some target blocks have unexpected contents, delete the last command
1782 // file so that we will resume the update from the first command in the transfer list.
1783 if (!params.canwrite && saved_last_command_index != -1 && params.cmdindex != -1 &&
1784 params.cmdindex <= saved_last_command_index) {
1785 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tianjie Xu284752e2017-12-05 11:04:17 -08001786 if ((cmdname == "move" || cmdname == "bsdiff" || cmdname == "imgdiff") &&
1787 !params.target_verified) {
1788 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1789 << params.cmdline << " doesn't produce expected target blocks.";
1790 saved_last_command_index = -1;
1791 DeleteLastCommandFile();
1792 }
1793 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001794 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001795 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001796 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001797 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001798 goto pbiudone;
1799 }
1800 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1801 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001802 }
Tao Bao33567772017-03-13 14:57:34 -07001803 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001804
Tao Bao33567772017-03-13 14:57:34 -07001805 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001806
Tao Bao33567772017-03-13 14:57:34 -07001807pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001808 if (params.canwrite) {
1809 pthread_mutex_lock(&params.nti.mu);
1810 if (params.nti.receiver_available) {
1811 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1812 }
1813 params.nti.receiver_available = false;
1814 pthread_cond_broadcast(&params.nti.cv);
1815 pthread_mutex_unlock(&params.nti.mu);
1816 int ret = pthread_join(params.thread, nullptr);
1817 if (ret != 0) {
1818 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1819 }
1820
1821 if (rc == 0) {
1822 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1823 LOG(INFO) << "stashed " << params.stashed << " blocks";
1824 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1825
1826 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1827 if (partition != nullptr && *(partition + 1) != 0) {
1828 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1829 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1830 fflush(cmd_pipe);
1831 }
1832 // Delete stash only after successfully completing the update, as it may contain blocks needed
1833 // to complete the update later.
1834 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001835 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001836
1837 // Create a marker on /cache partition, which allows skipping the update on this partition on
1838 // retry. The marker will be removed once booting into normal boot, or before starting next
1839 // fresh install.
1840 if (!SetPartitionUpdatedMarker(updated_marker)) {
1841 LOG(WARNING) << "Failed to set updated marker; continuing";
1842 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001843 }
1844
1845 pthread_mutex_destroy(&params.nti.mu);
1846 pthread_cond_destroy(&params.nti.cv);
1847 } else if (rc == 0) {
1848 LOG(INFO) << "verified partition contents; update may be resumed";
1849 }
1850
Tao Bao33567772017-03-13 14:57:34 -07001851 if (ota_fsync(params.fd) == -1) {
1852 failure_type = kFsyncFailure;
1853 PLOG(ERROR) << "fsync failed";
1854 }
1855 // params.fd will be automatically closed because it's a unique_fd.
1856
Tianjie Xu107a34f2017-06-29 17:04:21 -07001857 if (params.nti.brotli_decoder_state != nullptr) {
1858 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1859 }
1860
Tianjie Xu284752e2017-12-05 11:04:17 -08001861 // Delete the last command file if the update cannot be resumed.
1862 if (params.isunresumable) {
1863 DeleteLastCommandFile();
1864 }
1865
Tao Bao33567772017-03-13 14:57:34 -07001866 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1867 // created the stash.
1868 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1869 DeleteStash(params.stashbase);
1870 }
1871
1872 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1873 state->cause_code = failure_type;
1874 }
1875
1876 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001877}
1878
Tao Bao33567772017-03-13 14:57:34 -07001879/**
1880 * The transfer list is a text file containing commands to transfer data from one place to another
1881 * on the target partition. We parse it and execute the commands in order:
1882 *
1883 * zero [rangeset]
1884 * - Fill the indicated blocks with zeros.
1885 *
1886 * new [rangeset]
1887 * - Fill the blocks with data read from the new_data file.
1888 *
1889 * erase [rangeset]
1890 * - Mark the given blocks as empty.
1891 *
1892 * move <...>
1893 * bsdiff <patchstart> <patchlen> <...>
1894 * imgdiff <patchstart> <patchlen> <...>
1895 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1896 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1897 *
1898 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1899 *
1900 * stash <stash_id> <src_range>
1901 * - Load the given source range and stash the data in the given slot of the stash table.
1902 *
1903 * free <stash_id>
1904 * - Free the given stash data.
1905 *
1906 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1907 * a patch or move) after it has been written.
1908 *
1909 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1910 * in a move/bsdiff/imgdiff command.
1911 *
1912 * Within one command the source and target ranges may overlap so in general we need to read the
1913 * entire source into memory before writing anything to the target blocks.
1914 *
1915 * All the patch data is concatenated into one patch_data file in the update package. It must be
1916 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1917 * already compressed, we lose very little by not compressing their concatenation.)
1918 *
1919 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1920 * additional hashes before the range parameters, which are used to check if the command has already
1921 * been completed and verify the integrity of the source data.
1922 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001923Value* BlockImageVerifyFn(const char* name, State* state,
1924 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001925 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001926 const Command commands[] = {
1927 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001928 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001929 { "free", PerformCommandFree },
1930 { "imgdiff", PerformCommandDiff },
1931 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001932 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001933 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001934 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001935 };
1936
1937 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001938 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001939 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001940}
1941
Tianjie Xuc4447322017-03-06 14:44:59 -08001942Value* BlockImageUpdateFn(const char* name, State* state,
1943 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001944 const Command commands[] = {
1945 { "bsdiff", PerformCommandDiff },
1946 { "erase", PerformCommandErase },
1947 { "free", PerformCommandFree },
1948 { "imgdiff", PerformCommandDiff },
1949 { "move", PerformCommandMove },
1950 { "new", PerformCommandNew },
1951 { "stash", PerformCommandStash },
1952 { "zero", PerformCommandZero }
1953 };
1954
Tianjie Xuc4447322017-03-06 14:44:59 -08001955 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001956 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001957}
1958
Tianjie Xuc4447322017-03-06 14:44:59 -08001959Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001960 if (argv.size() != 2) {
1961 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1962 return StringValue("");
1963 }
1964
1965 std::vector<std::unique_ptr<Value>> args;
1966 if (!ReadValueArgs(state, argv, &args)) {
1967 return nullptr;
1968 }
1969
1970 const std::unique_ptr<Value>& blockdev_filename = args[0];
1971 const std::unique_ptr<Value>& ranges = args[1];
1972
1973 if (blockdev_filename->type != VAL_STRING) {
1974 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1975 return StringValue("");
1976 }
1977 if (ranges->type != VAL_STRING) {
1978 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1979 return StringValue("");
1980 }
1981
1982 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1983 if (fd == -1) {
1984 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1985 strerror(errno));
1986 return StringValue("");
1987 }
1988
1989 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07001990 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07001991
1992 SHA_CTX ctx;
1993 SHA1_Init(&ctx);
1994
1995 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001996 for (const auto& range : rs) {
1997 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001998 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1999 strerror(errno));
2000 return StringValue("");
2001 }
2002
Tao Baobf5b77d2017-03-30 16:57:29 -07002003 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002004 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
2005 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
2006 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002007 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002008 }
2009
2010 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002011 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002012 }
2013 uint8_t digest[SHA_DIGEST_LENGTH];
2014 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002015
Tao Baoc97edcb2017-03-31 01:18:13 -07002016 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002017}
2018
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002019// This function checks if a device has been remounted R/W prior to an incremental
2020// OTA update. This is an common cause of update abortion. The function reads the
2021// 1st block of each partition and check for mounting time/count. It return string "t"
2022// if executes successfully and an empty string otherwise.
2023
Tianjie Xuc4447322017-03-06 14:44:59 -08002024Value* CheckFirstBlockFn(const char* name, State* state,
2025 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002026 if (argv.size() != 1) {
2027 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2028 argv.size());
2029 return StringValue("");
2030 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002031
Tao Baoc97edcb2017-03-31 01:18:13 -07002032 std::vector<std::unique_ptr<Value>> args;
2033 if (!ReadValueArgs(state, argv, &args)) {
2034 return nullptr;
2035 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002036
Tao Baoc97edcb2017-03-31 01:18:13 -07002037 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002038
Tao Baoc97edcb2017-03-31 01:18:13 -07002039 if (arg_filename->type != VAL_STRING) {
2040 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2041 return StringValue("");
2042 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002043
Tao Baoc97edcb2017-03-31 01:18:13 -07002044 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2045 if (fd == -1) {
2046 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2047 strerror(errno));
2048 return StringValue("");
2049 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002050
Tao Baobf5b77d2017-03-30 16:57:29 -07002051 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002052 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002053
Tao Baoc97edcb2017-03-31 01:18:13 -07002054 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
2055 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2056 strerror(errno));
2057 return StringValue("");
2058 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002059
Tao Baoc97edcb2017-03-31 01:18:13 -07002060 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2061 // Super block starts from block 0, offset 0x400
2062 // 0x2C: len32 Mount time
2063 // 0x30: len32 Write time
2064 // 0x34: len16 Number of mounts since the last fsck
2065 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002066
Tao Baoc97edcb2017-03-31 01:18:13 -07002067 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2068 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002069
Tao Baoc97edcb2017-03-31 01:18:13 -07002070 if (mount_count > 0) {
2071 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2072 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2073 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002074
Tao Baoc97edcb2017-03-31 01:18:13 -07002075 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002076}
2077
Tianjie Xuc4447322017-03-06 14:44:59 -08002078Value* BlockImageRecoverFn(const char* name, State* state,
2079 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002080 if (argv.size() != 2) {
2081 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2082 argv.size());
2083 return StringValue("");
2084 }
2085
2086 std::vector<std::unique_ptr<Value>> args;
2087 if (!ReadValueArgs(state, argv, &args)) {
2088 return nullptr;
2089 }
2090
2091 const std::unique_ptr<Value>& filename = args[0];
2092 const std::unique_ptr<Value>& ranges = args[1];
2093
2094 if (filename->type != VAL_STRING) {
2095 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2096 return StringValue("");
2097 }
2098 if (ranges->type != VAL_STRING) {
2099 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2100 return StringValue("");
2101 }
Tao Bao67983152017-11-04 00:08:08 -07002102 RangeSet rs = RangeSet::Parse(ranges->data);
2103 if (!rs) {
2104 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2105 return StringValue("");
2106 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002107
2108 // Output notice to log when recover is attempted
2109 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2110
2111 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2112 fec::io fh(filename->data, O_RDWR);
2113
2114 if (!fh) {
2115 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2116 strerror(errno));
2117 return StringValue("");
2118 }
2119
2120 if (!fh.has_ecc() || !fh.has_verity()) {
2121 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2122 return StringValue("");
2123 }
2124
2125 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002126 if (!fh.get_status(status)) {
2127 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2128 return StringValue("");
2129 }
2130
Tao Baoc97edcb2017-03-31 01:18:13 -07002131 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002132 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002133 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002134 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002135 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002136 continue;
2137 }
2138
Tao Baobf5b77d2017-03-30 16:57:29 -07002139 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002140 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2141 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002142 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002143 }
2144
2145 // If we want to be able to recover from a situation where rewriting a corrected
2146 // block doesn't guarantee the same data will be returned when re-read later, we
2147 // can save a copy of corrected blocks to /cache. Note:
2148 //
2149 // 1. Maximum space required from /cache is the same as the maximum number of
2150 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2151 // this would be ~16 MiB, for example.
2152 //
2153 // 2. To find out if this block was corrupted, call fec_get_status after each
2154 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002155 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002156 }
2157 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2158 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002159}
2160
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002161void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002162 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2163 RegisterFunction("block_image_update", BlockImageUpdateFn);
2164 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2165 RegisterFunction("check_first_block", CheckFirstBlockFn);
2166 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002167}