blob: feb2aeb27dfac91558f415123fa0c1f75d108cf1 [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>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.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>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tao Baoec8272f2017-03-15 17:39:01 -070036#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080037#include <limits>
Tao Baoe6aa3322015-08-05 15:20:27 -070038#include <memory>
39#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070040#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070041#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070042
Tianjie Xu284752e2017-12-05 11:04:17 -080043#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080044#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/parseint.h>
46#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070047#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080048#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070049#include <brotli/decode.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 Bao09e468f2017-09-29 14:39:33 -070057#include "otautil/print_sha1.h"
58#include "otautil/rangeset.h"
Tao Bao8f237572017-03-26 13:36:49 -070059#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070060#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070061
Sami Tolvanene82fa182015-06-10 15:58:12 +000062// Set this to 0 to interpret 'erase' transfers to mean do a
63// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
64// erase to mean fill the region with zeroes.
65#define DEBUG_ERASE 0
66
Tao Bao51412212016-12-28 14:44:05 -080067static constexpr size_t BLOCKSIZE = 4096;
68static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
69static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
70static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000071
Tianjie Xu284752e2017-12-05 11:04:17 -080072std::string last_command_file = "/cache/recovery/last_command";
73
Tianjie Xu16255832016-04-30 11:49:59 -070074static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070075static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070076static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070077
Tianjie Xu284752e2017-12-05 11:04:17 -080078static void DeleteLastCommandFile() {
79 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
80 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
81 }
82}
83
84// Parse the last command index of the last update and save the result to |last_command_index|.
85// Return true if we successfully read the index.
86static bool ParseLastCommandFile(int* last_command_index) {
87 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
119// Update the last command index in the last_command_file if the current command writes to the
120// stash either explicitly or implicitly.
121static bool UpdateLastCommandIndex(int command_index, const std::string& command_string) {
122 std::string last_command_tmp = last_command_file + ".tmp";
123 std::string content = std::to_string(command_index) + "\n" + command_string;
124 android::base::unique_fd wfd(
125 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
126 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
127 PLOG(ERROR) << "Failed to update last command";
128 return false;
129 }
130
131 if (fsync(wfd) == -1) {
132 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
133 return false;
134 }
135
136 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
137 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
138 return false;
139 }
140
141 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
142 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
143 return false;
144 }
145
146 std::string last_command_dir = android::base::Dirname(last_command_file);
147 android::base::unique_fd dfd(
148 TEMP_FAILURE_RETRY(ota_open(last_command_dir.c_str(), O_RDONLY | O_DIRECTORY)));
149 if (dfd == -1) {
150 PLOG(ERROR) << "Failed to open " << last_command_dir;
151 return false;
152 }
153
154 if (fsync(dfd) == -1) {
155 PLOG(ERROR) << "Failed to fsync " << last_command_dir;
156 return false;
157 }
158
159 return true;
160}
161
Sami Tolvanen90221202014-12-09 16:39:47 +0000162static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700163 size_t so_far = 0;
164 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800165 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700166 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700167 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800168 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000169 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700170 } else if (r == 0) {
171 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800172 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700173 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700175 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000177 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700178}
179
Tao Bao612336d2015-08-27 16:41:21 -0700180static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
181 return read_all(fd, buffer.data(), size);
182}
183
Sami Tolvanen90221202014-12-09 16:39:47 +0000184static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185 size_t written = 0;
186 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800187 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700188 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700189 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800190 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000191 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700193 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000195
Sami Tolvanen90221202014-12-09 16:39:47 +0000196 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197}
198
Tao Bao612336d2015-08-27 16:41:21 -0700199static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
200 return write_all(fd, buffer.data(), size);
201}
202
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700203static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700204 // Don't discard blocks unless the update is a retry run.
205 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700206 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700207 }
208
209 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
210 if (ioctl(fd, BLKDISCARD, &args) == -1) {
211 PLOG(ERROR) << "BLKDISCARD ioctl failed";
212 return false;
213 }
214 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700215}
216
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700217static bool check_lseek(int fd, off64_t offset, int whence) {
218 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
219 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700220 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800221 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700222 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700224 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700225}
226
Tao Bao612336d2015-08-27 16:41:21 -0700227static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700229 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230
Tao Bao612336d2015-08-27 16:41:21 -0700231 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700232}
233
Tao Bao60a70af2017-03-26 14:03:52 -0700234/**
235 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
236 * given RangeSet.
237 */
238class RangeSinkWriter {
239 public:
240 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700241 : fd_(fd),
242 tgt_(tgt),
243 next_range_(0),
244 current_range_left_(0),
245 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700246 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700247 };
Tao Bao0940fe12015-08-27 16:41:21 -0700248
Tao Bao60a70af2017-03-26 14:03:52 -0700249 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700250 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700251 }
252
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700253 size_t AvailableSpace() const {
254 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
255 }
256
257 // Return number of bytes written; and 0 indicates a writing failure.
258 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700259 if (Finished()) {
260 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
261 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700262 }
263
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700264 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700265 while (size > 0) {
266 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700267 if (!SeekToOutputRange()) {
268 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700269 }
Tao Baof7eb7602017-03-27 15:12:48 -0700270
Tao Bao60a70af2017-03-26 14:03:52 -0700271 size_t write_now = size;
272 if (current_range_left_ < write_now) {
273 write_now = current_range_left_;
274 }
Tao Baof7eb7602017-03-27 15:12:48 -0700275
Tao Bao60a70af2017-03-26 14:03:52 -0700276 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700277 break;
278 }
Tao Bao60a70af2017-03-26 14:03:52 -0700279
280 data += write_now;
281 size -= write_now;
282
283 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700284 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700285 }
Tao Bao60a70af2017-03-26 14:03:52 -0700286
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700287 bytes_written_ += written;
288 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700289 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700290
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700291 size_t BytesWritten() const {
292 return bytes_written_;
293 }
294
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700295 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700296 // Set up the output cursor, move to next range if needed.
297 bool SeekToOutputRange() {
298 // We haven't finished the current range yet.
299 if (current_range_left_ != 0) {
300 return true;
301 }
302 // We can't write any more; let the write function return how many bytes have been written
303 // so far.
304 if (next_range_ >= tgt_.size()) {
305 return false;
306 }
307
308 const Range& range = tgt_[next_range_];
309 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
310 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
311 next_range_++;
312
313 if (!discard_blocks(fd_, offset, current_range_left_)) {
314 return false;
315 }
316 if (!check_lseek(fd_, offset, SEEK_SET)) {
317 return false;
318 }
319 return true;
320 }
321
322 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700323 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700324 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700325 const RangeSet& tgt_;
326 // The next range that we should write to.
327 size_t next_range_;
328 // The number of bytes to write before moving to the next range.
329 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700330 // Total bytes written by the writer.
331 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700332};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700333
Tao Bao60a70af2017-03-26 14:03:52 -0700334/**
335 * All of the data for all the 'new' transfers is contained in one file in the update package,
336 * concatenated together in the order in which transfers.list will need it. We want to stream it out
337 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
338 * section until it's that transfer's turn to go.
339 *
340 * To achieve this, we expand the new data from the archive in a background thread, and block that
341 * threads 'receive uncompressed data' function until the main thread has reached a point where we
342 * want some new data to be written. We signal the background thread with the destination for the
343 * data and block the main thread, waiting for the background thread to complete writing that
344 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
345 * transfer.
346 *
347 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
348 * the main thread wants some data written, it sets writer to the destination location and signals
349 * the condition. When the background thread is done writing, it clears writer and signals the
350 * condition again.
351 */
Tao Bao0940fe12015-08-27 16:41:21 -0700352struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700353 ZipArchiveHandle za;
354 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700355 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700356
Tianjie Xu107a34f2017-06-29 17:04:21 -0700357 std::unique_ptr<RangeSinkWriter> writer;
358 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700359 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700360
Tao Bao60a70af2017-03-26 14:03:52 -0700361 pthread_mutex_t mu;
362 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700363};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700364
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700365static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700366 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700367
Tao Bao60a70af2017-03-26 14:03:52 -0700368 while (size > 0) {
369 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
370 pthread_mutex_lock(&nti->mu);
371 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700372 // End the new data receiver if we encounter an error when performing block image update.
373 if (!nti->receiver_available) {
374 pthread_mutex_unlock(&nti->mu);
375 return false;
376 }
Tao Bao60a70af2017-03-26 14:03:52 -0700377 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700378 }
Tao Bao60a70af2017-03-26 14:03:52 -0700379 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700380
Tao Bao60a70af2017-03-26 14:03:52 -0700381 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
382 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700383 size_t write_now = std::min(size, nti->writer->AvailableSpace());
384 if (nti->writer->Write(data, write_now) != write_now) {
385 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700386 return false;
387 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700388
389 data += write_now;
390 size -= write_now;
391
392 if (nti->writer->Finished()) {
393 // We have written all the bytes desired by this writer.
394
395 pthread_mutex_lock(&nti->mu);
396 nti->writer = nullptr;
397 pthread_cond_broadcast(&nti->cv);
398 pthread_mutex_unlock(&nti->mu);
399 }
400 }
401
402 return true;
403}
404
405static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
406 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
407
408 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
409 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
410 pthread_mutex_lock(&nti->mu);
411 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700412 // End the receiver if we encounter an error when performing block image update.
413 if (!nti->receiver_available) {
414 pthread_mutex_unlock(&nti->mu);
415 return false;
416 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700417 pthread_cond_wait(&nti->cv, &nti->mu);
418 }
419 pthread_mutex_unlock(&nti->mu);
420
421 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
422 // disappear from nti.
423
424 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
425 if (buffer_size == 0) {
426 LOG(ERROR) << "No space left in output range";
427 return false;
428 }
429 uint8_t buffer[buffer_size];
430 size_t available_in = size;
431 size_t available_out = buffer_size;
432 uint8_t* next_out = buffer;
433
434 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
435 BrotliDecoderResult result = BrotliDecoderDecompressStream(
436 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
437
438 if (result == BROTLI_DECODER_RESULT_ERROR) {
439 LOG(ERROR) << "Decompression failed with "
440 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
441 return false;
442 }
443
444 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
445 << size - available_in << ", decoder status " << result;
446
447 size_t write_now = buffer_size - available_out;
448 if (nti->writer->Write(buffer, write_now) != write_now) {
449 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
450 return false;
451 }
452
453 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
454 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700455
456 if (nti->writer->Finished()) {
457 // We have written all the bytes desired by this writer.
458
459 pthread_mutex_lock(&nti->mu);
460 nti->writer = nullptr;
461 pthread_cond_broadcast(&nti->cv);
462 pthread_mutex_unlock(&nti->mu);
463 }
464 }
465
466 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700467}
468
469static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700470 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700471 if (nti->brotli_compressed) {
472 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
473 } else {
474 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
475 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700476 pthread_mutex_lock(&nti->mu);
477 nti->receiver_available = false;
478 if (nti->writer != nullptr) {
479 pthread_cond_broadcast(&nti->cv);
480 }
481 pthread_mutex_unlock(&nti->mu);
482 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700483}
484
Tao Bao612336d2015-08-27 16:41:21 -0700485static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700486 size_t p = 0;
487 for (const auto& range : src) {
488 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
489 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000490 }
491
Tao Baobf5b77d2017-03-30 16:57:29 -0700492 size_t size = (range.second - range.first) * BLOCKSIZE;
493 if (read_all(fd, buffer.data() + p, size) == -1) {
494 return -1;
495 }
496
497 p += size;
498 }
499
500 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000501}
502
Tao Bao612336d2015-08-27 16:41:21 -0700503static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700504 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700505 for (const auto& range : tgt) {
506 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
507 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700508 if (!discard_blocks(fd, offset, size)) {
509 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000510 }
511
Tao Bao60a70af2017-03-26 14:03:52 -0700512 if (!check_lseek(fd, offset, SEEK_SET)) {
513 return -1;
514 }
515
516 if (write_all(fd, buffer.data() + written, size) == -1) {
517 return -1;
518 }
519
520 written += size;
521 }
522
523 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000524}
525
Tao Baobaad2d42015-12-06 16:56:27 -0800526// Parameters for transfer list command functions
527struct CommandParameters {
528 std::vector<std::string> tokens;
529 size_t cpos;
Tianjie Xu284752e2017-12-05 11:04:17 -0800530 int cmdindex;
Tao Baobaad2d42015-12-06 16:56:27 -0800531 const char* cmdname;
532 const char* cmdline;
533 std::string freestash;
534 std::string stashbase;
535 bool canwrite;
536 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700537 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800538 bool foundwrites;
539 bool isunresumable;
540 int version;
541 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700542 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800543 NewThreadInfo nti;
544 pthread_t thread;
545 std::vector<uint8_t> buffer;
546 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800547 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800548};
549
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000550// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
551// handled separately).
552static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
553 const std::vector<uint8_t>& buffer) {
554 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000555 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
556 params.tokens[0] == "imgdiff");
557
558 size_t pos = 0;
559 // Command example:
560 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
561 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
562 // [<loc_range> <stashed_blocks>]
563 if (params.tokens[0] == "move") {
564 // src_range for move starts at the 4th position.
565 if (params.tokens.size() < 5) {
566 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
567 return;
568 }
569 pos = 4;
570 } else {
571 // src_range for diff starts at the 7th position.
572 if (params.tokens.size() < 8) {
573 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
574 return;
575 }
576 pos = 7;
577 }
578
579 // Source blocks in stash only, no work to do.
580 if (params.tokens[pos] == "-") {
581 return;
582 }
583
Tao Bao8f237572017-03-26 13:36:49 -0700584 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700585 if (!src) {
586 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
587 return;
588 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000589
590 RangeSet locs;
591 // If there's no stashed blocks, content in the buffer is consecutive and has the same
592 // order as the source blocks.
593 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700594 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000595 } else {
596 // Otherwise, the next token is the offset of the source blocks in the target range.
597 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
598 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
599 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700600 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700601 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000602 }
603
Tao Baobf5b77d2017-03-30 16:57:29 -0700604 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
605 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700606 size_t block_num = src.GetBlockNumber(i);
607 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000608 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
609
610 uint8_t digest[SHA_DIGEST_LENGTH];
611 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
612 std::string hexdigest = print_sha1(digest);
613 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
614 }
615}
616
617// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
618// in hex for each block.
619static void PrintHashForCorruptedStashedBlocks(const std::string& id,
620 const std::vector<uint8_t>& buffer,
621 const RangeSet& src) {
622 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700623 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000624
Tao Baobf5b77d2017-03-30 16:57:29 -0700625 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700626 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000627
628 uint8_t digest[SHA_DIGEST_LENGTH];
629 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
630 std::string hexdigest = print_sha1(digest);
631 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
632 }
633}
634
635// If the stash file doesn't exist, read the source blocks this stash contains and print the
636// SHA-1 for these blocks.
637static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
638 if (stash_map.find(id) == stash_map.end()) {
639 LOG(ERROR) << "No stash saved for id: " << id;
640 return;
641 }
642
643 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
644 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700645 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000646 if (ReadBlocks(src, buffer, fd) == -1) {
647 LOG(ERROR) << "failed to read source blocks for stash: " << id;
648 return;
649 }
650 PrintHashForCorruptedStashedBlocks(id, buffer, src);
651}
652
Tao Bao612336d2015-08-27 16:41:21 -0700653static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700654 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800655 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700656 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000657
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800658 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000659
Tao Baoe6aa3322015-08-05 15:20:27 -0700660 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000661
Tao Bao0940fe12015-08-27 16:41:21 -0700662 if (hexdigest != expected) {
663 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800664 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
665 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700666 }
667 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000668 }
669
Tao Bao0940fe12015-08-27 16:41:21 -0700670 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000671}
672
Tao Bao0940fe12015-08-27 16:41:21 -0700673static std::string GetStashFileName(const std::string& base, const std::string& id,
674 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700675 if (base.empty()) {
676 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000677 }
678
Tao Baoe6aa3322015-08-05 15:20:27 -0700679 std::string fn(STASH_DIRECTORY_BASE);
680 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000681
682 return fn;
683}
684
Tao Baoec8272f2017-03-15 17:39:01 -0700685// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
686// directory and continues despite of errors. Calls the 'callback' function for each file.
687static void EnumerateStash(const std::string& dirname,
688 const std::function<void(const std::string&)>& callback) {
689 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000690
Tao Baoec8272f2017-03-15 17:39:01 -0700691 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000692
Tao Baoec8272f2017-03-15 17:39:01 -0700693 if (directory == nullptr) {
694 if (errno != ENOENT) {
695 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000696 }
Tao Bao51412212016-12-28 14:44:05 -0800697 return;
698 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700699
Tao Baoec8272f2017-03-15 17:39:01 -0700700 dirent* item;
701 while ((item = readdir(directory.get())) != nullptr) {
702 if (item->d_type != DT_REG) continue;
703 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800704 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000705}
706
707// Deletes the stash directory and all files in it. Assumes that it only
708// contains files. There is nothing we can do about unlikely, but possible
709// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700710static void DeleteFile(const std::string& fn) {
711 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000712
Tao Baoec8272f2017-03-15 17:39:01 -0700713 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000714
Tao Baoec8272f2017-03-15 17:39:01 -0700715 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
716 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
717 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000718}
719
Tao Baoe6aa3322015-08-05 15:20:27 -0700720static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700721 if (base.empty()) return;
722
723 LOG(INFO) << "deleting stash " << base;
724
725 std::string dirname = GetStashFileName(base, "", "");
726 EnumerateStash(dirname, DeleteFile);
727
728 if (rmdir(dirname.c_str()) == -1) {
729 if (errno != ENOENT && errno != ENOTDIR) {
730 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000731 }
Tao Baoec8272f2017-03-15 17:39:01 -0700732 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000733}
734
Tao Baobcf46492017-03-23 15:28:20 -0700735static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
736 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700737 // In verify mode, if source range_set was saved for the given hash, check contents in the source
738 // blocks first. If the check fails, search for the stashed files on /cache as usual.
739 if (!params.canwrite) {
740 if (stash_map.find(id) != stash_map.end()) {
741 const RangeSet& src = stash_map[id];
742 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700743
Tao Baobf5b77d2017-03-30 16:57:29 -0700744 if (ReadBlocks(src, buffer, params.fd) == -1) {
745 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700746 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700747 }
748 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
749 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
750 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700751 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700752 }
753 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000754 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700755 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000756
Tao Baobf5b77d2017-03-30 16:57:29 -0700757 size_t blockcount = 0;
758 if (!blocks) {
759 blocks = &blockcount;
760 }
761
762 std::string fn = GetStashFileName(params.stashbase, id, "");
763
764 struct stat sb;
765 if (stat(fn.c_str(), &sb) == -1) {
766 if (errno != ENOENT || printnoent) {
767 PLOG(ERROR) << "stat \"" << fn << "\" failed";
768 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000769 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700770 return -1;
771 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000772
Tao Baobf5b77d2017-03-30 16:57:29 -0700773 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000774
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 if ((sb.st_size % BLOCKSIZE) != 0) {
776 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
777 return -1;
778 }
779
780 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
781 if (fd == -1) {
782 PLOG(ERROR) << "open \"" << fn << "\" failed";
783 return -1;
784 }
785
786 allocate(sb.st_size, buffer);
787
788 if (read_all(fd, buffer, sb.st_size) == -1) {
789 return -1;
790 }
791
792 *blocks = sb.st_size / BLOCKSIZE;
793
794 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
795 LOG(ERROR) << "unexpected contents in " << fn;
796 if (stash_map.find(id) == stash_map.end()) {
797 LOG(ERROR) << "failed to find source blocks number for stash " << id
798 << " when executing command: " << params.cmdname;
799 } else {
800 const RangeSet& src = stash_map[id];
801 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000802 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700803 DeleteFile(fn);
804 return -1;
805 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000806
Tao Baobf5b77d2017-03-30 16:57:29 -0700807 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000808}
809
Tao Bao612336d2015-08-27 16:41:21 -0700810static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700811 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700812 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700813 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000814 }
815
816 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800817 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700818 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000819 }
820
Tao Bao0940fe12015-08-27 16:41:21 -0700821 std::string fn = GetStashFileName(base, id, ".partial");
822 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000823
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100824 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700825 struct stat sb;
826 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100827
828 if (res == 0) {
829 // The file already exists and since the name is the hash of the contents,
830 // it's safe to assume the contents are identical (accidental hash collisions
831 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800832 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700833 *exists = true;
834 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100835 }
836
Tao Bao0940fe12015-08-27 16:41:21 -0700837 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100838 }
839
Tao Bao039f2da2016-11-22 16:29:50 -0800840 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000841
Tao Bao039f2da2016-11-22 16:29:50 -0800842 android::base::unique_fd fd(
843 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000844 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800845 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700846 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000847 }
848
Tianjie Xua946b9e2017-03-21 16:24:57 -0700849 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
850 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
851 return -1;
852 }
853
Sami Tolvanen90221202014-12-09 16:39:47 +0000854 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700855 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000856 }
857
Jed Estepa7b9a462015-12-15 16:04:53 -0800858 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700859 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800860 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700861 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000862 }
863
Tao Baoe6aa3322015-08-05 15:20:27 -0700864 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800865 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700866 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000867 }
868
Tao Bao0940fe12015-08-27 16:41:21 -0700869 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700870 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
871 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700872 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700873 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800874 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700875 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700876 }
877
Jed Estepa7b9a462015-12-15 16:04:53 -0800878 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700879 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800880 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700881 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700882 }
883
Tao Bao0940fe12015-08-27 16:41:21 -0700884 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000885}
886
887// Creates a directory for storing stash files and checks if the /cache partition
888// hash enough space for the expected amount of blocks we need to store. Returns
889// >0 if we created the directory, zero if it existed already, and <0 of failure.
890
Tao Bao51412212016-12-28 14:44:05 -0800891static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
892 std::string& base) {
893 if (blockdev.empty()) {
894 return -1;
895 }
896
897 // Stash directory should be different for each partition to avoid conflicts
898 // when updating multiple partitions at the same time, so we use the hash of
899 // the block device name as the base directory
900 uint8_t digest[SHA_DIGEST_LENGTH];
901 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
902 base = print_sha1(digest);
903
904 std::string dirname = GetStashFileName(base, "", "");
905 struct stat sb;
906 int res = stat(dirname.c_str(), &sb);
907 size_t max_stash_size = maxblocks * BLOCKSIZE;
908
909 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800910 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800911 strerror(errno));
912 return -1;
913 } else if (res != 0) {
914 LOG(INFO) << "creating stash " << dirname;
915 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
916
917 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800918 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800919 strerror(errno));
920 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000921 }
922
Tianjie Xua946b9e2017-03-21 16:24:57 -0700923 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800924 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700925 strerror(errno));
926 return -1;
927 }
928
Tao Bao51412212016-12-28 14:44:05 -0800929 if (CacheSizeCheck(max_stash_size) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800930 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800931 max_stash_size);
932 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000933 }
934
Tao Bao51412212016-12-28 14:44:05 -0800935 return 1; // Created directory
936 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000937
Tao Bao51412212016-12-28 14:44:05 -0800938 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000939
Tao Baoec8272f2017-03-15 17:39:01 -0700940 // If the directory already exists, calculate the space already allocated to stash files and check
941 // if there's enough for all required blocks. Delete any partially completed stash files first.
942 EnumerateStash(dirname, [](const std::string& fn) {
943 if (android::base::EndsWith(fn, ".partial")) {
944 DeleteFile(fn);
945 }
946 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000947
Tao Bao51412212016-12-28 14:44:05 -0800948 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700949 EnumerateStash(dirname, [&existing](const std::string& fn) {
950 if (fn.empty()) return;
951 struct stat sb;
952 if (stat(fn.c_str(), &sb) == -1) {
953 PLOG(ERROR) << "stat \"" << fn << "\" failed";
954 return;
955 }
956 existing += static_cast<size_t>(sb.st_size);
957 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000958
Tao Bao51412212016-12-28 14:44:05 -0800959 if (max_stash_size > existing) {
960 size_t needed = max_stash_size - existing;
961 if (CacheSizeCheck(needed) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800962 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800963 needed);
964 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000965 }
Tao Bao51412212016-12-28 14:44:05 -0800966 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000967
Tao Bao51412212016-12-28 14:44:05 -0800968 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000969}
970
Tao Baobaad2d42015-12-06 16:56:27 -0800971static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700972 if (base.empty() || id.empty()) {
973 return -1;
974 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000975
Tao Baoec8272f2017-03-15 17:39:01 -0700976 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000977
Tao Baoec8272f2017-03-15 17:39:01 -0700978 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700979}
980
Tao Baobf5b77d2017-03-30 16:57:29 -0700981// Source contains packed data, which we want to move to the locations given in locs in the dest
982// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700983static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700984 const std::vector<uint8_t>& source) {
985 const uint8_t* from = source.data();
986 uint8_t* to = dest.data();
987 size_t start = locs.blocks();
988 // Must do the movement backward.
989 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
990 size_t blocks = it->second - it->first;
991 start -= blocks;
992 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
993 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700994}
995
Tao Baod2aecd42017-03-23 14:43:44 -0700996/**
997 * We expect to parse the remainder of the parameter tokens as one of:
998 *
999 * <src_block_count> <src_range>
1000 * (loads data from source image only)
1001 *
1002 * <src_block_count> - <[stash_id:stash_range] ...>
1003 * (loads data from stashes only)
1004 *
1005 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1006 * (loads data from both source image and stashes)
1007 *
1008 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1009 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1010 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1011 * LoadStash.
1012 */
1013static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1014 bool* overlap) {
1015 CHECK(src_blocks != nullptr);
1016 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001017
Tao Baod2aecd42017-03-23 14:43:44 -07001018 // <src_block_count>
1019 const std::string& token = params.tokens[params.cpos++];
1020 if (!android::base::ParseUint(token, src_blocks)) {
1021 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1022 return -1;
1023 }
Tao Baobaad2d42015-12-06 16:56:27 -08001024
Tao Baod2aecd42017-03-23 14:43:44 -07001025 allocate(*src_blocks * BLOCKSIZE, params.buffer);
1026
1027 // "-" or <src_range> [<src_loc>]
1028 if (params.tokens[params.cpos] == "-") {
1029 // no source ranges, only stashes
1030 params.cpos++;
1031 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001032 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001033 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001034 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001035
1036 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1037 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001038 }
1039
Tao Baod2aecd42017-03-23 14:43:44 -07001040 if (params.cpos >= params.tokens.size()) {
1041 // no stashes, only source range
1042 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001043 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001044
Tao Bao8f237572017-03-26 13:36:49 -07001045 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001046 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001047 MoveRange(params.buffer, locs, params.buffer);
1048 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001049
Tao Baod2aecd42017-03-23 14:43:44 -07001050 // <[stash_id:stash_range]>
1051 while (params.cpos < params.tokens.size()) {
1052 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1053 // in the source block that stashed data should go.
1054 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1055 if (tokens.size() != 2) {
1056 LOG(ERROR) << "invalid parameter";
1057 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001058 }
1059
Tao Baod2aecd42017-03-23 14:43:44 -07001060 std::vector<uint8_t> stash;
1061 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
1062 // These source blocks will fail verification if used later, but we
1063 // will let the caller decide if this is a fatal failure
1064 LOG(ERROR) << "failed to load stash " << tokens[0];
1065 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001066 }
1067
Tao Bao8f237572017-03-26 13:36:49 -07001068 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001069 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001070 MoveRange(params.buffer, locs, stash);
1071 }
1072
1073 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001074}
1075
Tao Bao33567772017-03-13 14:57:34 -07001076/**
1077 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1078 *
1079 * We expect to parse the remainder of the parameter tokens as one of:
1080 *
1081 * <tgt_range> <src_block_count> <src_range>
1082 * (loads data from source image only)
1083 *
1084 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1085 * (loads data from stashes only)
1086 *
1087 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1088 * (loads data from both source image and stashes)
1089 *
Tao Baod2aecd42017-03-23 14:43:44 -07001090 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1091 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001092 * verification fails in a way that the update cannot be resumed anymore.
1093 *
1094 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1095 * the return value is -1 and the command should be aborted.
1096 *
1097 * If the return value is 1, the command has already been completed according to the contents of the
1098 * target blocks, and should not be performed again.
1099 *
1100 * If the return value is 0, source blocks have expected content and the command can be performed.
1101 */
Tao Baod2aecd42017-03-23 14:43:44 -07001102static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
1103 bool onehash, bool* overlap) {
1104 CHECK(src_blocks != nullptr);
1105 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001106
Tao Baod2aecd42017-03-23 14:43:44 -07001107 if (params.cpos >= params.tokens.size()) {
1108 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001109 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001110 }
1111
1112 std::string srchash = params.tokens[params.cpos++];
1113 std::string tgthash;
1114
1115 if (onehash) {
1116 tgthash = srchash;
1117 } else {
1118 if (params.cpos >= params.tokens.size()) {
1119 LOG(ERROR) << "missing target hash";
1120 return -1;
1121 }
1122 tgthash = params.tokens[params.cpos++];
1123 }
1124
1125 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1126 // "-"/<src_range>.
1127 if (params.cpos + 2 >= params.tokens.size()) {
1128 LOG(ERROR) << "invalid parameters";
1129 return -1;
1130 }
1131
1132 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -07001133 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001134 CHECK(static_cast<bool>(tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001135
Tao Baobf5b77d2017-03-30 16:57:29 -07001136 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -07001137 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1138 return -1;
1139 }
1140
1141 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -07001142 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001143 return 1;
1144 }
1145
1146 // Load source blocks.
1147 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1148 return -1;
1149 }
1150
1151 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1152 // If source and target blocks overlap, stash the source blocks so we can
1153 // resume from possible write errors. In verify mode, we can skip stashing
1154 // because the source blocks won't be overwritten.
1155 if (*overlap && params.canwrite) {
1156 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1157
1158 bool stash_exists = false;
1159 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1160 &stash_exists) != 0) {
1161 LOG(ERROR) << "failed to stash overlapping source blocks";
1162 return -1;
1163 }
1164
Tianjie Xu284752e2017-12-05 11:04:17 -08001165 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1166 LOG(WARNING) << "Failed to update the last command file.";
1167 }
1168
Tao Baod2aecd42017-03-23 14:43:44 -07001169 params.stashed += *src_blocks;
1170 // Can be deleted when the write has completed.
1171 if (!stash_exists) {
1172 params.freestash = srchash;
1173 }
1174 }
1175
1176 // Source blocks have expected content, command can proceed.
1177 return 0;
1178 }
1179
1180 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1181 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1182 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1183 // command.
1184 return 0;
1185 }
1186
1187 // Valid source data not available, update cannot be resumed.
1188 LOG(ERROR) << "partition has unexpected contents";
1189 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1190
1191 params.isunresumable = true;
1192
1193 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001194}
1195
Tao Bao0940fe12015-08-27 16:41:21 -07001196static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001197 size_t blocks = 0;
1198 bool overlap = false;
1199 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001200 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001201
Tao Bao33567772017-03-13 14:57:34 -07001202 if (status == -1) {
1203 LOG(ERROR) << "failed to read blocks for move";
1204 return -1;
1205 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001206
Tao Bao33567772017-03-13 14:57:34 -07001207 if (status == 0) {
1208 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001209 } else {
1210 params.target_verified = true;
1211 if (params.foundwrites) {
1212 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1213 }
Tao Bao33567772017-03-13 14:57:34 -07001214 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001215
Tao Bao33567772017-03-13 14:57:34 -07001216 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001218 LOG(INFO) << " moving " << blocks << " blocks";
1219
1220 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1221 return -1;
1222 }
1223 } else {
1224 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001225 }
Tao Bao33567772017-03-13 14:57:34 -07001226 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001227
Tao Bao33567772017-03-13 14:57:34 -07001228 if (!params.freestash.empty()) {
1229 FreeStash(params.stashbase, params.freestash);
1230 params.freestash.clear();
1231 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001232
Tao Baobf5b77d2017-03-30 16:57:29 -07001233 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001234
Tao Bao33567772017-03-13 14:57:34 -07001235 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001236}
1237
Tao Bao0940fe12015-08-27 16:41:21 -07001238static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001239 // <stash_id> <src_range>
1240 if (params.cpos + 1 >= params.tokens.size()) {
1241 LOG(ERROR) << "missing id and/or src range fields in stash command";
1242 return -1;
1243 }
1244
1245 const std::string& id = params.tokens[params.cpos++];
1246 size_t blocks = 0;
1247 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1248 // Stash file already exists and has expected contents. Do not read from source again, as the
1249 // source may have been already overwritten during a previous attempt.
1250 return 0;
1251 }
1252
Tao Bao8f237572017-03-26 13:36:49 -07001253 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001254 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001255
Tao Baobf5b77d2017-03-30 16:57:29 -07001256 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001257 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1258 return -1;
1259 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001260 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001261 stash_map[id] = src;
1262
1263 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1264 // Source blocks have unexpected contents. If we actually need this data later, this is an
1265 // unrecoverable error. However, the command that uses the data may have already completed
1266 // previously, so the possible failure will occur during source block verification.
1267 LOG(ERROR) << "failed to load source blocks for stash " << id;
1268 return 0;
1269 }
1270
1271 // In verify mode, we don't need to stash any blocks.
1272 if (!params.canwrite) {
1273 return 0;
1274 }
1275
1276 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001277 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1278 if (result == 0) {
1279 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1280 LOG(WARNING) << "Failed to update the last command file.";
1281 }
1282
1283 params.stashed += blocks;
1284 }
1285 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001286}
1287
Tao Bao0940fe12015-08-27 16:41:21 -07001288static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001289 // <stash_id>
1290 if (params.cpos >= params.tokens.size()) {
1291 LOG(ERROR) << "missing stash id in free command";
1292 return -1;
1293 }
Tao Baobaad2d42015-12-06 16:56:27 -08001294
Tao Baobcf46492017-03-23 15:28:20 -07001295 const std::string& id = params.tokens[params.cpos++];
1296 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001297
Tao Baobcf46492017-03-23 15:28:20 -07001298 if (params.createdstash || params.canwrite) {
1299 return FreeStash(params.stashbase, id);
1300 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001301
Tao Baobcf46492017-03-23 15:28:20 -07001302 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001303}
1304
Tao Bao0940fe12015-08-27 16:41:21 -07001305static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001306 if (params.cpos >= params.tokens.size()) {
1307 LOG(ERROR) << "missing target blocks for zero";
1308 return -1;
1309 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001310
Tao Baobf5b77d2017-03-30 16:57:29 -07001311 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001312 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001313
1314 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1315
1316 allocate(BLOCKSIZE, params.buffer);
1317 memset(params.buffer.data(), 0, BLOCKSIZE);
1318
1319 if (params.canwrite) {
1320 for (const auto& range : tgt) {
1321 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1322 size_t size = (range.second - range.first) * BLOCKSIZE;
1323 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001324 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001325 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001326
Tao Baobf5b77d2017-03-30 16:57:29 -07001327 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1328 return -1;
1329 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001330
Tao Baobf5b77d2017-03-30 16:57:29 -07001331 for (size_t j = range.first; j < range.second; ++j) {
1332 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1333 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001334 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001335 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001336 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001337 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001338
Tao Baobf5b77d2017-03-30 16:57:29 -07001339 if (params.cmdname[0] == 'z') {
1340 // Update only for the zero command, as the erase command will call
1341 // this if DEBUG_ERASE is defined.
1342 params.written += tgt.blocks();
1343 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001344
Tao Baobf5b77d2017-03-30 16:57:29 -07001345 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001346}
1347
Tao Bao0940fe12015-08-27 16:41:21 -07001348static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001349 if (params.cpos >= params.tokens.size()) {
1350 LOG(ERROR) << "missing target blocks for new";
1351 return -1;
1352 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001353
Tao Bao8f237572017-03-26 13:36:49 -07001354 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001355 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001356
1357 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001358 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001359
Tao Bao60a70af2017-03-26 14:03:52 -07001360 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001361 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001362 pthread_cond_broadcast(&params.nti.cv);
1363
1364 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001365 if (!params.nti.receiver_available) {
1366 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1367 << " bytes of new data";
1368 pthread_mutex_unlock(&params.nti.mu);
1369 return -1;
1370 }
Tao Bao60a70af2017-03-26 14:03:52 -07001371 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001372 }
1373
Tao Bao60a70af2017-03-26 14:03:52 -07001374 pthread_mutex_unlock(&params.nti.mu);
1375 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001376
Tao Baobf5b77d2017-03-30 16:57:29 -07001377 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001378
Tao Bao60a70af2017-03-26 14:03:52 -07001379 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001380}
1381
Tao Bao0940fe12015-08-27 16:41:21 -07001382static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001383 // <offset> <length>
1384 if (params.cpos + 1 >= params.tokens.size()) {
1385 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1386 return -1;
1387 }
Tao Bao0940fe12015-08-27 16:41:21 -07001388
Tao Baoc0e1c462017-02-01 10:20:10 -08001389 size_t offset;
1390 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1391 LOG(ERROR) << "invalid patch offset";
1392 return -1;
1393 }
Tao Bao0940fe12015-08-27 16:41:21 -07001394
Tao Baoc0e1c462017-02-01 10:20:10 -08001395 size_t len;
1396 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1397 LOG(ERROR) << "invalid patch len";
1398 return -1;
1399 }
Tao Bao0940fe12015-08-27 16:41:21 -07001400
Tao Baoc0e1c462017-02-01 10:20:10 -08001401 RangeSet tgt;
1402 size_t blocks = 0;
1403 bool overlap = false;
1404 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001405
Tao Baoc0e1c462017-02-01 10:20:10 -08001406 if (status == -1) {
1407 LOG(ERROR) << "failed to read blocks for diff";
1408 return -1;
1409 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001410
Tao Baoc0e1c462017-02-01 10:20:10 -08001411 if (status == 0) {
1412 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001413 } else {
1414 params.target_verified = true;
1415 if (params.foundwrites) {
1416 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1417 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001418 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001419
Tao Baoc0e1c462017-02-01 10:20:10 -08001420 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001421 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001422 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001423 Value patch_value(
1424 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001425
Tao Bao60a70af2017-03-26 14:03:52 -07001426 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001427 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001428 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001429 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1430 std::placeholders::_2),
1431 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001432 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001433 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001434 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001435 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001436 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001437 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001438 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1439 std::placeholders::_2),
1440 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001441 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001442 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001443 return -1;
1444 }
1445 }
1446
1447 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001448 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001449 LOG(ERROR) << "range sink underrun?";
1450 }
1451 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001452 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001453 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001454 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001455 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001456
Tao Baoc0e1c462017-02-01 10:20:10 -08001457 if (!params.freestash.empty()) {
1458 FreeStash(params.stashbase, params.freestash);
1459 params.freestash.clear();
1460 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001461
Tao Baobf5b77d2017-03-30 16:57:29 -07001462 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001463
Tao Baoc0e1c462017-02-01 10:20:10 -08001464 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001465}
1466
Tao Bao0940fe12015-08-27 16:41:21 -07001467static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001468 if (DEBUG_ERASE) {
1469 return PerformCommandZero(params);
1470 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001471
Tao Baobf5b77d2017-03-30 16:57:29 -07001472 struct stat sb;
1473 if (fstat(params.fd, &sb) == -1) {
1474 PLOG(ERROR) << "failed to fstat device to erase";
1475 return -1;
1476 }
1477
1478 if (!S_ISBLK(sb.st_mode)) {
1479 LOG(ERROR) << "not a block device; skipping erase";
1480 return -1;
1481 }
1482
1483 if (params.cpos >= params.tokens.size()) {
1484 LOG(ERROR) << "missing target blocks for erase";
1485 return -1;
1486 }
1487
1488 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001489 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001490
1491 if (params.canwrite) {
1492 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1493
1494 for (const auto& range : tgt) {
1495 uint64_t blocks[2];
1496 // offset in bytes
1497 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1498 // length in bytes
1499 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1500
1501 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1502 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001503 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001504 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001505 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001506 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001507
Tao Baobf5b77d2017-03-30 16:57:29 -07001508 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001509}
1510
1511// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001512typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001513
Tao Bao612336d2015-08-27 16:41:21 -07001514struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001515 const char* name;
1516 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001517};
Sami Tolvanen90221202014-12-09 16:39:47 +00001518
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001519// args:
1520// - block device (or file) to modify in-place
1521// - transfer list (blob)
1522// - new data stream (filename within package.zip)
1523// - patch stream (filename within package.zip, must be uncompressed)
1524
Tianjie Xuc4447322017-03-06 14:44:59 -08001525static Value* PerformBlockImageUpdate(const char* name, State* state,
1526 const std::vector<std::unique_ptr<Expr>>& argv,
1527 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001528 CommandParameters params = {};
1529 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001530
Tao Bao33567772017-03-13 14:57:34 -07001531 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1532 if (state->is_retry) {
1533 is_retry = true;
1534 LOG(INFO) << "This update is a retry.";
1535 }
1536 if (argv.size() != 4) {
1537 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1538 argv.size());
1539 return StringValue("");
1540 }
1541
1542 std::vector<std::unique_ptr<Value>> args;
1543 if (!ReadValueArgs(state, argv, &args)) {
1544 return nullptr;
1545 }
1546
Tao Baoc97edcb2017-03-31 01:18:13 -07001547 const std::unique_ptr<Value>& blockdev_filename = args[0];
1548 const std::unique_ptr<Value>& transfer_list_value = args[1];
1549 const std::unique_ptr<Value>& new_data_fn = args[2];
1550 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001551
1552 if (blockdev_filename->type != VAL_STRING) {
1553 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1554 return StringValue("");
1555 }
1556 if (transfer_list_value->type != VAL_BLOB) {
1557 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1558 return StringValue("");
1559 }
1560 if (new_data_fn->type != VAL_STRING) {
1561 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1562 return StringValue("");
1563 }
1564 if (patch_data_fn->type != VAL_STRING) {
1565 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1566 return StringValue("");
1567 }
1568
1569 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1570 if (ui == nullptr) {
1571 return StringValue("");
1572 }
1573
1574 FILE* cmd_pipe = ui->cmd_pipe;
1575 ZipArchiveHandle za = ui->package_zip;
1576
1577 if (cmd_pipe == nullptr || za == nullptr) {
1578 return StringValue("");
1579 }
1580
1581 ZipString path_data(patch_data_fn->data.c_str());
1582 ZipEntry patch_entry;
1583 if (FindEntry(za, path_data, &patch_entry) != 0) {
1584 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1585 return StringValue("");
1586 }
1587
1588 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1589 ZipString new_data(new_data_fn->data.c_str());
1590 ZipEntry new_entry;
1591 if (FindEntry(za, new_data, &new_entry) != 0) {
1592 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1593 return StringValue("");
1594 }
1595
1596 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1597 if (params.fd == -1) {
1598 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1599 return StringValue("");
1600 }
1601
1602 if (params.canwrite) {
1603 params.nti.za = za;
1604 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001605 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1606 if (params.nti.brotli_compressed) {
1607 // Initialize brotli decoder state.
1608 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1609 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001610 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001611
1612 pthread_mutex_init(&params.nti.mu, nullptr);
1613 pthread_cond_init(&params.nti.cv, nullptr);
1614 pthread_attr_t attr;
1615 pthread_attr_init(&attr);
1616 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1617
1618 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1619 if (error != 0) {
1620 PLOG(ERROR) << "pthread_create failed";
1621 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001622 }
Tao Bao33567772017-03-13 14:57:34 -07001623 }
1624
1625 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1626 if (lines.size() < 2) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001627 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]",
Tao Bao33567772017-03-13 14:57:34 -07001628 lines.size());
1629 return StringValue("");
1630 }
1631
1632 // First line in transfer list is the version number.
1633 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1634 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1635 return StringValue("");
1636 }
1637
1638 LOG(INFO) << "blockimg version is " << params.version;
1639
1640 // Second line in transfer list is the total number of blocks we expect to write.
1641 size_t total_blocks;
1642 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001643 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001644 return StringValue("");
1645 }
1646
1647 if (total_blocks == 0) {
1648 return StringValue("t");
1649 }
1650
1651 size_t start = 2;
1652 if (lines.size() < 4) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001653 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001654 lines.size());
1655 return StringValue("");
1656 }
1657
1658 // Third line is how many stash entries are needed simultaneously.
1659 LOG(INFO) << "maximum stash entries " << lines[2];
1660
1661 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1662 size_t stash_max_blocks;
1663 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001664 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001665 lines[3].c_str());
1666 return StringValue("");
1667 }
1668
1669 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1670 if (res == -1) {
1671 return StringValue("");
1672 }
1673
1674 params.createdstash = res;
1675
Tianjie Xu284752e2017-12-05 11:04:17 -08001676 // When performing an update, save the index and cmdline of the current command into
1677 // the last_command_file if this command writes to the stash either explicitly of implicitly.
1678 // Upon resuming an update, read the saved index first; then
1679 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1680 // the expected target blocks already. If not, these commands cannot be skipped and we need
1681 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1682 // the update will resume from the start of the transfer list.
1683 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1684 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1685 // If an update succeeds or is unresumable, delete the last_command_file.
1686 int saved_last_command_index;
1687 if (!ParseLastCommandFile(&saved_last_command_index)) {
1688 DeleteLastCommandFile();
1689 // We failed to parse the last command, set it explicitly to -1.
1690 saved_last_command_index = -1;
1691 }
1692
Tao Bao33567772017-03-13 14:57:34 -07001693 start += 2;
1694
1695 // Build a map of the available commands
1696 std::unordered_map<std::string, const Command*> cmd_map;
1697 for (size_t i = 0; i < cmdcount; ++i) {
1698 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1699 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1700 return StringValue(strdup(""));
1701 }
1702 cmd_map[commands[i].name] = &commands[i];
1703 }
1704
1705 int rc = -1;
1706
1707 // Subsequent lines are all individual transfer commands
Tianjie Xu284752e2017-12-05 11:04:17 -08001708 for (size_t i = start; i < lines.size(); i++) {
1709 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001710 if (line.empty()) continue;
1711
1712 params.tokens = android::base::Split(line, " ");
1713 params.cpos = 0;
Tianjie Xu284752e2017-12-05 11:04:17 -08001714 if (i - start > std::numeric_limits<int>::max()) {
1715 params.cmdindex = -1;
1716 } else {
1717 params.cmdindex = i - start;
1718 }
Tao Bao33567772017-03-13 14:57:34 -07001719 params.cmdname = params.tokens[params.cpos++].c_str();
1720 params.cmdline = line.c_str();
Tianjie Xu284752e2017-12-05 11:04:17 -08001721 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001722
1723 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1724 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1725 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001726 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001727
Tao Bao33567772017-03-13 14:57:34 -07001728 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001729
Tianjie Xu284752e2017-12-05 11:04:17 -08001730 if (cmd->f == nullptr) {
1731 LOG(ERROR) << "failed to find the function for command [" << line << "]";
1732 goto pbiudone;
1733 }
1734
1735 // Skip all commands before the saved last command index when resuming an update.
1736 if (params.canwrite && params.cmdindex != -1 && params.cmdindex <= saved_last_command_index) {
1737 LOG(INFO) << "Skipping already executed command: " << params.cmdindex
1738 << ", last executed command for previous update: " << saved_last_command_index;
1739 continue;
1740 }
1741
1742 if (cmd->f(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001743 LOG(ERROR) << "failed to execute command [" << line << "]";
1744 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001745 }
1746
Tianjie Xu284752e2017-12-05 11:04:17 -08001747 // In verify mode, check if the commands before the saved last_command_index have been
1748 // executed correctly. If some target blocks have unexpected contents, delete the last command
1749 // file so that we will resume the update from the first command in the transfer list.
1750 if (!params.canwrite && saved_last_command_index != -1 && params.cmdindex != -1 &&
1751 params.cmdindex <= saved_last_command_index) {
1752 // TODO(xunchang) check that the cmdline of the saved index is correct.
1753 std::string cmdname = std::string(params.cmdname);
1754 if ((cmdname == "move" || cmdname == "bsdiff" || cmdname == "imgdiff") &&
1755 !params.target_verified) {
1756 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1757 << params.cmdline << " doesn't produce expected target blocks.";
1758 saved_last_command_index = -1;
1759 DeleteLastCommandFile();
1760 }
1761 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001762 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001763 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001764 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001765 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001766 goto pbiudone;
1767 }
1768 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1769 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001770 }
Tao Bao33567772017-03-13 14:57:34 -07001771 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001772
Tao Bao33567772017-03-13 14:57:34 -07001773 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001774
Tao Bao33567772017-03-13 14:57:34 -07001775pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001776 if (params.canwrite) {
1777 pthread_mutex_lock(&params.nti.mu);
1778 if (params.nti.receiver_available) {
1779 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1780 }
1781 params.nti.receiver_available = false;
1782 pthread_cond_broadcast(&params.nti.cv);
1783 pthread_mutex_unlock(&params.nti.mu);
1784 int ret = pthread_join(params.thread, nullptr);
1785 if (ret != 0) {
1786 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1787 }
1788
1789 if (rc == 0) {
1790 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1791 LOG(INFO) << "stashed " << params.stashed << " blocks";
1792 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1793
1794 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1795 if (partition != nullptr && *(partition + 1) != 0) {
1796 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1797 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1798 fflush(cmd_pipe);
1799 }
1800 // Delete stash only after successfully completing the update, as it may contain blocks needed
1801 // to complete the update later.
1802 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001803 DeleteLastCommandFile();
Tianjie Xu5450c842017-10-18 13:15:21 -07001804 }
1805
1806 pthread_mutex_destroy(&params.nti.mu);
1807 pthread_cond_destroy(&params.nti.cv);
1808 } else if (rc == 0) {
1809 LOG(INFO) << "verified partition contents; update may be resumed";
1810 }
1811
Tao Bao33567772017-03-13 14:57:34 -07001812 if (ota_fsync(params.fd) == -1) {
1813 failure_type = kFsyncFailure;
1814 PLOG(ERROR) << "fsync failed";
1815 }
1816 // params.fd will be automatically closed because it's a unique_fd.
1817
Tianjie Xu107a34f2017-06-29 17:04:21 -07001818 if (params.nti.brotli_decoder_state != nullptr) {
1819 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1820 }
1821
Tianjie Xu284752e2017-12-05 11:04:17 -08001822 // Delete the last command file if the update cannot be resumed.
1823 if (params.isunresumable) {
1824 DeleteLastCommandFile();
1825 }
1826
Tao Bao33567772017-03-13 14:57:34 -07001827 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1828 // created the stash.
1829 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1830 DeleteStash(params.stashbase);
1831 }
1832
1833 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1834 state->cause_code = failure_type;
1835 }
1836
1837 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001838}
1839
Tao Bao33567772017-03-13 14:57:34 -07001840/**
1841 * The transfer list is a text file containing commands to transfer data from one place to another
1842 * on the target partition. We parse it and execute the commands in order:
1843 *
1844 * zero [rangeset]
1845 * - Fill the indicated blocks with zeros.
1846 *
1847 * new [rangeset]
1848 * - Fill the blocks with data read from the new_data file.
1849 *
1850 * erase [rangeset]
1851 * - Mark the given blocks as empty.
1852 *
1853 * move <...>
1854 * bsdiff <patchstart> <patchlen> <...>
1855 * imgdiff <patchstart> <patchlen> <...>
1856 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1857 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1858 *
1859 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1860 *
1861 * stash <stash_id> <src_range>
1862 * - Load the given source range and stash the data in the given slot of the stash table.
1863 *
1864 * free <stash_id>
1865 * - Free the given stash data.
1866 *
1867 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1868 * a patch or move) after it has been written.
1869 *
1870 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1871 * in a move/bsdiff/imgdiff command.
1872 *
1873 * Within one command the source and target ranges may overlap so in general we need to read the
1874 * entire source into memory before writing anything to the target blocks.
1875 *
1876 * All the patch data is concatenated into one patch_data file in the update package. It must be
1877 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1878 * already compressed, we lose very little by not compressing their concatenation.)
1879 *
1880 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1881 * additional hashes before the range parameters, which are used to check if the command has already
1882 * been completed and verify the integrity of the source data.
1883 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001884Value* BlockImageVerifyFn(const char* name, State* state,
1885 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001886 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001887 const Command commands[] = {
1888 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001889 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001890 { "free", PerformCommandFree },
1891 { "imgdiff", PerformCommandDiff },
1892 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001893 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001894 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001895 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001896 };
1897
1898 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001899 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001900 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001901}
1902
Tianjie Xuc4447322017-03-06 14:44:59 -08001903Value* BlockImageUpdateFn(const char* name, State* state,
1904 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001905 const Command commands[] = {
1906 { "bsdiff", PerformCommandDiff },
1907 { "erase", PerformCommandErase },
1908 { "free", PerformCommandFree },
1909 { "imgdiff", PerformCommandDiff },
1910 { "move", PerformCommandMove },
1911 { "new", PerformCommandNew },
1912 { "stash", PerformCommandStash },
1913 { "zero", PerformCommandZero }
1914 };
1915
Tianjie Xuc4447322017-03-06 14:44:59 -08001916 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001917 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001918}
1919
Tianjie Xuc4447322017-03-06 14:44:59 -08001920Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001921 if (argv.size() != 2) {
1922 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1923 return StringValue("");
1924 }
1925
1926 std::vector<std::unique_ptr<Value>> args;
1927 if (!ReadValueArgs(state, argv, &args)) {
1928 return nullptr;
1929 }
1930
1931 const std::unique_ptr<Value>& blockdev_filename = args[0];
1932 const std::unique_ptr<Value>& ranges = args[1];
1933
1934 if (blockdev_filename->type != VAL_STRING) {
1935 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1936 return StringValue("");
1937 }
1938 if (ranges->type != VAL_STRING) {
1939 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1940 return StringValue("");
1941 }
1942
1943 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1944 if (fd == -1) {
1945 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1946 strerror(errno));
1947 return StringValue("");
1948 }
1949
1950 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07001951 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07001952
1953 SHA_CTX ctx;
1954 SHA1_Init(&ctx);
1955
1956 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001957 for (const auto& range : rs) {
1958 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001959 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1960 strerror(errno));
1961 return StringValue("");
1962 }
1963
Tao Baobf5b77d2017-03-30 16:57:29 -07001964 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001965 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1966 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1967 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001968 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001969 }
1970
1971 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001972 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001973 }
1974 uint8_t digest[SHA_DIGEST_LENGTH];
1975 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001976
Tao Baoc97edcb2017-03-31 01:18:13 -07001977 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001978}
1979
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001980// This function checks if a device has been remounted R/W prior to an incremental
1981// OTA update. This is an common cause of update abortion. The function reads the
1982// 1st block of each partition and check for mounting time/count. It return string "t"
1983// if executes successfully and an empty string otherwise.
1984
Tianjie Xuc4447322017-03-06 14:44:59 -08001985Value* CheckFirstBlockFn(const char* name, State* state,
1986 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001987 if (argv.size() != 1) {
1988 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1989 argv.size());
1990 return StringValue("");
1991 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001992
Tao Baoc97edcb2017-03-31 01:18:13 -07001993 std::vector<std::unique_ptr<Value>> args;
1994 if (!ReadValueArgs(state, argv, &args)) {
1995 return nullptr;
1996 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001997
Tao Baoc97edcb2017-03-31 01:18:13 -07001998 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001999
Tao Baoc97edcb2017-03-31 01:18:13 -07002000 if (arg_filename->type != VAL_STRING) {
2001 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2002 return StringValue("");
2003 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002004
Tao Baoc97edcb2017-03-31 01:18:13 -07002005 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2006 if (fd == -1) {
2007 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2008 strerror(errno));
2009 return StringValue("");
2010 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002011
Tao Baobf5b77d2017-03-30 16:57:29 -07002012 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002013 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002014
Tao Baoc97edcb2017-03-31 01:18:13 -07002015 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
2016 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2017 strerror(errno));
2018 return StringValue("");
2019 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002020
Tao Baoc97edcb2017-03-31 01:18:13 -07002021 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2022 // Super block starts from block 0, offset 0x400
2023 // 0x2C: len32 Mount time
2024 // 0x30: len32 Write time
2025 // 0x34: len16 Number of mounts since the last fsck
2026 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002027
Tao Baoc97edcb2017-03-31 01:18:13 -07002028 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2029 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002030
Tao Baoc97edcb2017-03-31 01:18:13 -07002031 if (mount_count > 0) {
2032 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2033 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2034 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002035
Tao Baoc97edcb2017-03-31 01:18:13 -07002036 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002037}
2038
Tianjie Xuc4447322017-03-06 14:44:59 -08002039Value* BlockImageRecoverFn(const char* name, State* state,
2040 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002041 if (argv.size() != 2) {
2042 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2043 argv.size());
2044 return StringValue("");
2045 }
2046
2047 std::vector<std::unique_ptr<Value>> args;
2048 if (!ReadValueArgs(state, argv, &args)) {
2049 return nullptr;
2050 }
2051
2052 const std::unique_ptr<Value>& filename = args[0];
2053 const std::unique_ptr<Value>& ranges = args[1];
2054
2055 if (filename->type != VAL_STRING) {
2056 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2057 return StringValue("");
2058 }
2059 if (ranges->type != VAL_STRING) {
2060 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2061 return StringValue("");
2062 }
Tao Bao67983152017-11-04 00:08:08 -07002063 RangeSet rs = RangeSet::Parse(ranges->data);
2064 if (!rs) {
2065 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2066 return StringValue("");
2067 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002068
2069 // Output notice to log when recover is attempted
2070 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2071
2072 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2073 fec::io fh(filename->data, O_RDWR);
2074
2075 if (!fh) {
2076 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2077 strerror(errno));
2078 return StringValue("");
2079 }
2080
2081 if (!fh.has_ecc() || !fh.has_verity()) {
2082 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2083 return StringValue("");
2084 }
2085
2086 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002087 if (!fh.get_status(status)) {
2088 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2089 return StringValue("");
2090 }
2091
Tao Baoc97edcb2017-03-31 01:18:13 -07002092 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002093 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002094 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002095 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002096 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002097 continue;
2098 }
2099
Tao Baobf5b77d2017-03-30 16:57:29 -07002100 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002101 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2102 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002103 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002104 }
2105
2106 // If we want to be able to recover from a situation where rewriting a corrected
2107 // block doesn't guarantee the same data will be returned when re-read later, we
2108 // can save a copy of corrected blocks to /cache. Note:
2109 //
2110 // 1. Maximum space required from /cache is the same as the maximum number of
2111 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2112 // this would be ~16 MiB, for example.
2113 //
2114 // 2. To find out if this block was corrupted, call fec_get_status after each
2115 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002116 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002117 }
2118 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2119 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002120}
2121
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002122void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002123 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2124 RegisterFunction("block_image_update", BlockImageUpdateFn);
2125 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2126 RegisterFunction("check_first_block", CheckFirstBlockFn);
2127 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002128}