blob: ff1d20a78bd2558d9020be6504c1a4ff9c8d5b26 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000018#include <dirent.h>
Tao Bao641fa972018-04-25 18:59:40 -070019#include <errno.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Tao Bao641fa972018-04-25 18:59:40 -070028#include <sys/ioctl.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000029#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070030#include <sys/types.h>
31#include <sys/wait.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070032#include <time.h>
33#include <unistd.h>
34
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080036#include <limits>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tianjie Xu284752e2017-12-05 11:04:17 -080042#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080043#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/parseint.h>
45#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070046#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080047#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070048#include <brotli/decode.h>
Tao Bao641fa972018-04-25 18:59:40 -070049#include <fec/io.h>
Tao Bao51412212016-12-28 14:44:05 -080050#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070051#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070052#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070053
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070055#include "otafault/ota_io.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070056#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070057#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070058#include "otautil/print_sha1.h"
59#include "otautil/rangeset.h"
Tao Baoc3901232018-05-21 16:05:56 -070060#include "private/commands.h"
Tao Bao8f237572017-03-26 13:36:49 -070061#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070062#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070063
Sami Tolvanene82fa182015-06-10 15:58:12 +000064// Set this to 0 to interpret 'erase' transfers to mean do a
65// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
66// erase to mean fill the region with zeroes.
67#define DEBUG_ERASE 0
68
Tao Bao51412212016-12-28 14:44:05 -080069static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080070static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
71static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000072
Tianjie Xu16255832016-04-30 11:49:59 -070073static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070074static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070075static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070076
Tianjie Xu284752e2017-12-05 11:04:17 -080077static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070078 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080079 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.
Tao Bao26efb0a2018-05-21 14:59:55 -070086static bool ParseLastCommandFile(size_t* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070087 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080088 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
89 if (fd == -1) {
90 if (errno != ENOENT) {
91 PLOG(ERROR) << "Failed to open " << last_command_file;
92 return false;
93 }
94
95 LOG(INFO) << last_command_file << " doesn't exist.";
96 return false;
97 }
98
99 // Now that the last_command file exists, parse the last command index of previous update.
100 std::string content;
101 if (!android::base::ReadFdToString(fd.get(), &content)) {
102 LOG(ERROR) << "Failed to read: " << last_command_file;
103 return false;
104 }
105
106 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
107 if (lines.size() != 2) {
108 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
109 return false;
110 }
111
112 if (!android::base::ParseInt(lines[0], last_command_index)) {
113 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
114 return false;
115 }
116
117 return true;
118}
119
Tao Bao864c6682018-05-07 11:38:25 -0700120static bool FsyncDir(const std::string& dirname) {
121 android::base::unique_fd dfd(
122 TEMP_FAILURE_RETRY(ota_open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
123 if (dfd == -1) {
124 failure_type = kFileOpenFailure;
125 PLOG(ERROR) << "Failed to open " << dirname;
126 return false;
127 }
128 if (fsync(dfd) == -1) {
129 failure_type = kFsyncFailure;
130 PLOG(ERROR) << "Failed to fsync " << dirname;
131 return false;
132 }
133 return true;
134}
135
Tianjie Xuc2b2bb52018-05-15 15:09:59 -0700136// Update the last executed command index in the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -0700137static bool UpdateLastCommandIndex(size_t command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700138 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800139 std::string last_command_tmp = last_command_file + ".tmp";
140 std::string content = std::to_string(command_index) + "\n" + command_string;
141 android::base::unique_fd wfd(
142 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
143 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
144 PLOG(ERROR) << "Failed to update last command";
145 return false;
146 }
147
148 if (fsync(wfd) == -1) {
149 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
150 return false;
151 }
152
153 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
154 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
155 return false;
156 }
157
158 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
159 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
160 return false;
161 }
162
Tao Bao864c6682018-05-07 11:38:25 -0700163 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800164 return false;
165 }
166
Tao Bao864c6682018-05-07 11:38:25 -0700167 return true;
168}
169
170static bool SetPartitionUpdatedMarker(const std::string& marker) {
171 if (!android::base::WriteStringToFile("", marker)) {
172 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800173 return false;
174 }
Tao Bao864c6682018-05-07 11:38:25 -0700175 if (!FsyncDir(android::base::Dirname(marker))) {
176 return false;
177 }
178 LOG(INFO) << "Wrote partition updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800179 return true;
180}
181
Sami Tolvanen90221202014-12-09 16:39:47 +0000182static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700183 size_t so_far = 0;
184 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800185 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700186 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700187 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800188 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000189 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700190 } else if (r == 0) {
191 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800192 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700193 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700195 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000197 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700198}
199
Tao Baode3bbb82018-05-30 16:14:14 -0700200static int read_all(int fd, std::vector<uint8_t>* buffer, size_t size) {
201 return read_all(fd, buffer->data(), size);
Tao Bao612336d2015-08-27 16:41:21 -0700202}
203
Sami Tolvanen90221202014-12-09 16:39:47 +0000204static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205 size_t written = 0;
206 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800207 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700208 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700209 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800210 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000211 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700212 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700213 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700214 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000215
Sami Tolvanen90221202014-12-09 16:39:47 +0000216 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700217}
218
Tao Bao612336d2015-08-27 16:41:21 -0700219static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
220 return write_all(fd, buffer.data(), size);
221}
222
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700223static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700224 // Don't discard blocks unless the update is a retry run.
225 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700226 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700227 }
228
229 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
230 if (ioctl(fd, BLKDISCARD, &args) == -1) {
231 PLOG(ERROR) << "BLKDISCARD ioctl failed";
232 return false;
233 }
234 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700235}
236
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700237static bool check_lseek(int fd, off64_t offset, int whence) {
238 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
239 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700240 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800241 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700242 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700243 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700244 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245}
246
Tao Baode3bbb82018-05-30 16:14:14 -0700247static void allocate(size_t size, std::vector<uint8_t>* buffer) {
248 // If the buffer's big enough, reuse it.
249 if (size <= buffer->size()) return;
250 buffer->resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700251}
252
Tao Bao60a70af2017-03-26 14:03:52 -0700253/**
254 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
255 * given RangeSet.
256 */
257class RangeSinkWriter {
258 public:
259 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700260 : fd_(fd),
261 tgt_(tgt),
262 next_range_(0),
263 current_range_left_(0),
264 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700265 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700266 };
Tao Bao0940fe12015-08-27 16:41:21 -0700267
Tao Bao60a70af2017-03-26 14:03:52 -0700268 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700269 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700270 }
271
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700272 size_t AvailableSpace() const {
273 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
274 }
275
276 // Return number of bytes written; and 0 indicates a writing failure.
277 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700278 if (Finished()) {
279 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
280 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700281 }
282
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700283 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700284 while (size > 0) {
285 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700286 if (!SeekToOutputRange()) {
287 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700288 }
Tao Baof7eb7602017-03-27 15:12:48 -0700289
Tao Bao60a70af2017-03-26 14:03:52 -0700290 size_t write_now = size;
291 if (current_range_left_ < write_now) {
292 write_now = current_range_left_;
293 }
Tao Baof7eb7602017-03-27 15:12:48 -0700294
Tao Bao60a70af2017-03-26 14:03:52 -0700295 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700296 break;
297 }
Tao Bao60a70af2017-03-26 14:03:52 -0700298
299 data += write_now;
300 size -= write_now;
301
302 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700303 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700304 }
Tao Bao60a70af2017-03-26 14:03:52 -0700305
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700306 bytes_written_ += written;
307 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700308 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700309
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700310 size_t BytesWritten() const {
311 return bytes_written_;
312 }
313
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700314 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700315 // Set up the output cursor, move to next range if needed.
316 bool SeekToOutputRange() {
317 // We haven't finished the current range yet.
318 if (current_range_left_ != 0) {
319 return true;
320 }
321 // We can't write any more; let the write function return how many bytes have been written
322 // so far.
323 if (next_range_ >= tgt_.size()) {
324 return false;
325 }
326
327 const Range& range = tgt_[next_range_];
328 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
329 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
330 next_range_++;
331
332 if (!discard_blocks(fd_, offset, current_range_left_)) {
333 return false;
334 }
335 if (!check_lseek(fd_, offset, SEEK_SET)) {
336 return false;
337 }
338 return true;
339 }
340
341 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700342 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700343 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700344 const RangeSet& tgt_;
345 // The next range that we should write to.
346 size_t next_range_;
347 // The number of bytes to write before moving to the next range.
348 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700349 // Total bytes written by the writer.
350 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700351};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700352
Tao Bao60a70af2017-03-26 14:03:52 -0700353/**
354 * All of the data for all the 'new' transfers is contained in one file in the update package,
355 * concatenated together in the order in which transfers.list will need it. We want to stream it out
356 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
357 * section until it's that transfer's turn to go.
358 *
359 * To achieve this, we expand the new data from the archive in a background thread, and block that
360 * threads 'receive uncompressed data' function until the main thread has reached a point where we
361 * want some new data to be written. We signal the background thread with the destination for the
362 * data and block the main thread, waiting for the background thread to complete writing that
363 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
364 * transfer.
365 *
366 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
367 * the main thread wants some data written, it sets writer to the destination location and signals
368 * the condition. When the background thread is done writing, it clears writer and signals the
369 * condition again.
370 */
Tao Bao0940fe12015-08-27 16:41:21 -0700371struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700372 ZipArchiveHandle za;
373 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700374 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700375
Tianjie Xu107a34f2017-06-29 17:04:21 -0700376 std::unique_ptr<RangeSinkWriter> writer;
377 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700378 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700379
Tao Bao60a70af2017-03-26 14:03:52 -0700380 pthread_mutex_t mu;
381 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700382};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700383
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700384static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700385 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700386
Tao Bao60a70af2017-03-26 14:03:52 -0700387 while (size > 0) {
388 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
389 pthread_mutex_lock(&nti->mu);
390 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700391 // End the new data receiver if we encounter an error when performing block image update.
392 if (!nti->receiver_available) {
393 pthread_mutex_unlock(&nti->mu);
394 return false;
395 }
Tao Bao60a70af2017-03-26 14:03:52 -0700396 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700397 }
Tao Bao60a70af2017-03-26 14:03:52 -0700398 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700399
Tao Bao60a70af2017-03-26 14:03:52 -0700400 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
401 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700402 size_t write_now = std::min(size, nti->writer->AvailableSpace());
403 if (nti->writer->Write(data, write_now) != write_now) {
404 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700405 return false;
406 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700407
408 data += write_now;
409 size -= write_now;
410
411 if (nti->writer->Finished()) {
412 // We have written all the bytes desired by this writer.
413
414 pthread_mutex_lock(&nti->mu);
415 nti->writer = nullptr;
416 pthread_cond_broadcast(&nti->cv);
417 pthread_mutex_unlock(&nti->mu);
418 }
419 }
420
421 return true;
422}
423
424static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
425 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
426
427 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
428 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
429 pthread_mutex_lock(&nti->mu);
430 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700431 // End the receiver if we encounter an error when performing block image update.
432 if (!nti->receiver_available) {
433 pthread_mutex_unlock(&nti->mu);
434 return false;
435 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700436 pthread_cond_wait(&nti->cv, &nti->mu);
437 }
438 pthread_mutex_unlock(&nti->mu);
439
440 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
441 // disappear from nti.
442
443 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
444 if (buffer_size == 0) {
445 LOG(ERROR) << "No space left in output range";
446 return false;
447 }
448 uint8_t buffer[buffer_size];
449 size_t available_in = size;
450 size_t available_out = buffer_size;
451 uint8_t* next_out = buffer;
452
453 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
454 BrotliDecoderResult result = BrotliDecoderDecompressStream(
455 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
456
457 if (result == BROTLI_DECODER_RESULT_ERROR) {
458 LOG(ERROR) << "Decompression failed with "
459 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
460 return false;
461 }
462
463 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
464 << size - available_in << ", decoder status " << result;
465
466 size_t write_now = buffer_size - available_out;
467 if (nti->writer->Write(buffer, write_now) != write_now) {
468 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
469 return false;
470 }
471
472 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
473 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700474
475 if (nti->writer->Finished()) {
476 // We have written all the bytes desired by this writer.
477
478 pthread_mutex_lock(&nti->mu);
479 nti->writer = nullptr;
480 pthread_cond_broadcast(&nti->cv);
481 pthread_mutex_unlock(&nti->mu);
482 }
483 }
484
485 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700486}
487
488static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700489 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700490 if (nti->brotli_compressed) {
491 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
492 } else {
493 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
494 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700495 pthread_mutex_lock(&nti->mu);
496 nti->receiver_available = false;
497 if (nti->writer != nullptr) {
498 pthread_cond_broadcast(&nti->cv);
499 }
500 pthread_mutex_unlock(&nti->mu);
501 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700502}
503
Tao Baode3bbb82018-05-30 16:14:14 -0700504static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>* buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700505 size_t p = 0;
506 for (const auto& range : src) {
507 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
508 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000509 }
510
Tao Baobf5b77d2017-03-30 16:57:29 -0700511 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700512 if (read_all(fd, buffer->data() + p, size) == -1) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700513 return -1;
514 }
515
516 p += size;
517 }
518
519 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000520}
521
Tao Bao612336d2015-08-27 16:41:21 -0700522static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700523 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700524 for (const auto& range : tgt) {
525 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
526 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700527 if (!discard_blocks(fd, offset, size)) {
528 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000529 }
530
Tao Bao60a70af2017-03-26 14:03:52 -0700531 if (!check_lseek(fd, offset, SEEK_SET)) {
532 return -1;
533 }
534
535 if (write_all(fd, buffer.data() + written, size) == -1) {
536 return -1;
537 }
538
539 written += size;
540 }
541
542 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000543}
544
Tao Baobaad2d42015-12-06 16:56:27 -0800545// Parameters for transfer list command functions
546struct CommandParameters {
547 std::vector<std::string> tokens;
548 size_t cpos;
Tao Baoc3901232018-05-21 16:05:56 -0700549 std::string cmdname;
550 std::string cmdline;
Tao Baobaad2d42015-12-06 16:56:27 -0800551 std::string freestash;
552 std::string stashbase;
553 bool canwrite;
554 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700555 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800556 bool foundwrites;
557 bool isunresumable;
558 int version;
559 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700560 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800561 NewThreadInfo nti;
562 pthread_t thread;
563 std::vector<uint8_t> buffer;
564 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800565 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800566};
567
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000568// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
569// handled separately).
570static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
571 const std::vector<uint8_t>& buffer) {
572 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000573 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
574 params.tokens[0] == "imgdiff");
575
576 size_t pos = 0;
577 // Command example:
578 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
579 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
580 // [<loc_range> <stashed_blocks>]
581 if (params.tokens[0] == "move") {
582 // src_range for move starts at the 4th position.
583 if (params.tokens.size() < 5) {
584 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
585 return;
586 }
587 pos = 4;
588 } else {
589 // src_range for diff starts at the 7th position.
590 if (params.tokens.size() < 8) {
591 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
592 return;
593 }
594 pos = 7;
595 }
596
597 // Source blocks in stash only, no work to do.
598 if (params.tokens[pos] == "-") {
599 return;
600 }
601
Tao Bao8f237572017-03-26 13:36:49 -0700602 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700603 if (!src) {
604 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
605 return;
606 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000607
608 RangeSet locs;
609 // If there's no stashed blocks, content in the buffer is consecutive and has the same
610 // order as the source blocks.
611 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700612 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000613 } else {
614 // Otherwise, the next token is the offset of the source blocks in the target range.
615 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
616 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
617 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700618 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700619 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000620 }
621
Tao Baobf5b77d2017-03-30 16:57:29 -0700622 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
623 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700624 size_t block_num = src.GetBlockNumber(i);
625 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000626 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
627
628 uint8_t digest[SHA_DIGEST_LENGTH];
629 SHA1(buffer.data() + buffer_index * 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 calculated hash for the whole stash doesn't match the stash id, print the SHA-1
636// in hex for each block.
637static void PrintHashForCorruptedStashedBlocks(const std::string& id,
638 const std::vector<uint8_t>& buffer,
639 const RangeSet& src) {
640 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700641 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000642
Tao Baobf5b77d2017-03-30 16:57:29 -0700643 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700644 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000645
646 uint8_t digest[SHA_DIGEST_LENGTH];
647 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
648 std::string hexdigest = print_sha1(digest);
649 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
650 }
651}
652
653// If the stash file doesn't exist, read the source blocks this stash contains and print the
654// SHA-1 for these blocks.
655static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
656 if (stash_map.find(id) == stash_map.end()) {
657 LOG(ERROR) << "No stash saved for id: " << id;
658 return;
659 }
660
661 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
662 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700663 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tao Baode3bbb82018-05-30 16:14:14 -0700664 if (ReadBlocks(src, &buffer, fd) == -1) {
665 LOG(ERROR) << "failed to read source blocks for stash: " << id;
666 return;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000667 }
668 PrintHashForCorruptedStashedBlocks(id, buffer, src);
669}
670
Tao Bao612336d2015-08-27 16:41:21 -0700671static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Baode3bbb82018-05-30 16:14:14 -0700672 const size_t blocks, bool printerror) {
673 uint8_t digest[SHA_DIGEST_LENGTH];
674 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000675
Tao Baode3bbb82018-05-30 16:14:14 -0700676 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000677
Tao Baode3bbb82018-05-30 16:14:14 -0700678 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000679
Tao Baode3bbb82018-05-30 16:14:14 -0700680 if (hexdigest != expected) {
681 if (printerror) {
682 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read " << hexdigest
683 << ")";
Sami Tolvanen90221202014-12-09 16:39:47 +0000684 }
Tao Baode3bbb82018-05-30 16:14:14 -0700685 return -1;
686 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000687
Tao Baode3bbb82018-05-30 16:14:14 -0700688 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000689}
690
Tao Bao0940fe12015-08-27 16:41:21 -0700691static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700692 const std::string& postfix) {
693 if (base.empty()) {
694 return "";
695 }
Tao Bao864c6682018-05-07 11:38:25 -0700696 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
697 if (id.empty() && postfix.empty()) {
698 return filename;
699 }
700 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000701}
702
Tao Baoec8272f2017-03-15 17:39:01 -0700703// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
704// directory and continues despite of errors. Calls the 'callback' function for each file.
705static void EnumerateStash(const std::string& dirname,
706 const std::function<void(const std::string&)>& callback) {
707 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000708
Tao Baoec8272f2017-03-15 17:39:01 -0700709 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000710
Tao Baoec8272f2017-03-15 17:39:01 -0700711 if (directory == nullptr) {
712 if (errno != ENOENT) {
713 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000714 }
Tao Bao51412212016-12-28 14:44:05 -0800715 return;
716 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700717
Tao Baoec8272f2017-03-15 17:39:01 -0700718 dirent* item;
719 while ((item = readdir(directory.get())) != nullptr) {
720 if (item->d_type != DT_REG) continue;
721 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800722 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000723}
724
725// Deletes the stash directory and all files in it. Assumes that it only
726// contains files. There is nothing we can do about unlikely, but possible
727// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700728static void DeleteFile(const std::string& fn) {
729 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000730
Tao Baoec8272f2017-03-15 17:39:01 -0700731 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000732
Tao Baoec8272f2017-03-15 17:39:01 -0700733 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
734 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
735 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000736}
737
Tao Baoe6aa3322015-08-05 15:20:27 -0700738static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700739 if (base.empty()) return;
740
741 LOG(INFO) << "deleting stash " << base;
742
743 std::string dirname = GetStashFileName(base, "", "");
744 EnumerateStash(dirname, DeleteFile);
745
746 if (rmdir(dirname.c_str()) == -1) {
747 if (errno != ENOENT && errno != ENOTDIR) {
748 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000749 }
Tao Baoec8272f2017-03-15 17:39:01 -0700750 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000751}
752
Tao Baode3bbb82018-05-30 16:14:14 -0700753static int LoadStash(const CommandParameters& params, const std::string& id, bool verify,
754 std::vector<uint8_t>* buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700755 // In verify mode, if source range_set was saved for the given hash, check contents in the source
756 // blocks first. If the check fails, search for the stashed files on /cache as usual.
757 if (!params.canwrite) {
758 if (stash_map.find(id) != stash_map.end()) {
759 const RangeSet& src = stash_map[id];
760 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700761
Tao Baobf5b77d2017-03-30 16:57:29 -0700762 if (ReadBlocks(src, buffer, params.fd) == -1) {
763 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700764 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700765 }
Tao Baode3bbb82018-05-30 16:14:14 -0700766 if (VerifyBlocks(id, *buffer, src.blocks(), true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700767 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tao Baode3bbb82018-05-30 16:14:14 -0700768 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700769 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700770 }
771 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000772 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700773 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000774
Tao Baobf5b77d2017-03-30 16:57:29 -0700775 std::string fn = GetStashFileName(params.stashbase, id, "");
776
777 struct stat sb;
778 if (stat(fn.c_str(), &sb) == -1) {
779 if (errno != ENOENT || printnoent) {
780 PLOG(ERROR) << "stat \"" << fn << "\" failed";
781 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000782 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700783 return -1;
784 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000785
Tao Baobf5b77d2017-03-30 16:57:29 -0700786 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000787
Tao Baobf5b77d2017-03-30 16:57:29 -0700788 if ((sb.st_size % BLOCKSIZE) != 0) {
789 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
790 return -1;
791 }
792
793 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
794 if (fd == -1) {
795 PLOG(ERROR) << "open \"" << fn << "\" failed";
796 return -1;
797 }
798
799 allocate(sb.st_size, buffer);
800
801 if (read_all(fd, buffer, sb.st_size) == -1) {
802 return -1;
803 }
804
Tao Bao64957ce2018-05-30 16:21:39 -0700805 size_t blocks = sb.st_size / BLOCKSIZE;
Tao Baode3bbb82018-05-30 16:14:14 -0700806 if (verify && VerifyBlocks(id, *buffer, blocks, true) != 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700807 LOG(ERROR) << "unexpected contents in " << fn;
808 if (stash_map.find(id) == stash_map.end()) {
809 LOG(ERROR) << "failed to find source blocks number for stash " << id
810 << " when executing command: " << params.cmdname;
811 } else {
812 const RangeSet& src = stash_map[id];
Tao Baode3bbb82018-05-30 16:14:14 -0700813 PrintHashForCorruptedStashedBlocks(id, *buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000814 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700815 DeleteFile(fn);
816 return -1;
817 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000818
Tao Baobf5b77d2017-03-30 16:57:29 -0700819 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000820}
821
Tao Bao612336d2015-08-27 16:41:21 -0700822static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baode3bbb82018-05-30 16:14:14 -0700823 const std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
824 if (base.empty()) {
825 return -1;
826 }
827
828 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
829 LOG(ERROR) << "not enough space to write stash";
830 return -1;
831 }
832
833 std::string fn = GetStashFileName(base, id, ".partial");
834 std::string cn = GetStashFileName(base, id, "");
835
836 if (exists) {
837 struct stat sb;
838 int res = stat(cn.c_str(), &sb);
839
840 if (res == 0) {
841 // The file already exists and since the name is the hash of the contents,
842 // it's safe to assume the contents are identical (accidental hash collisions
843 // are unlikely)
844 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
845 *exists = true;
846 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000847 }
848
Tao Baode3bbb82018-05-30 16:14:14 -0700849 *exists = false;
850 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000851
Tao Baode3bbb82018-05-30 16:14:14 -0700852 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000853
Tao Baode3bbb82018-05-30 16:14:14 -0700854 android::base::unique_fd fd(
855 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
856 if (fd == -1) {
857 PLOG(ERROR) << "failed to create \"" << fn << "\"";
858 return -1;
859 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100860
Tao Baode3bbb82018-05-30 16:14:14 -0700861 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
862 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
863 return -1;
864 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100865
Tao Baode3bbb82018-05-30 16:14:14 -0700866 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
867 return -1;
868 }
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100869
Tao Baode3bbb82018-05-30 16:14:14 -0700870 if (ota_fsync(fd) == -1) {
871 failure_type = kFsyncFailure;
872 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
873 return -1;
874 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000875
Tao Baode3bbb82018-05-30 16:14:14 -0700876 if (rename(fn.c_str(), cn.c_str()) == -1) {
877 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
878 return -1;
879 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000880
Tao Baode3bbb82018-05-30 16:14:14 -0700881 std::string dname = GetStashFileName(base, "", "");
882 if (!FsyncDir(dname)) {
883 failure_type = kFsyncFailure;
884 return -1;
885 }
Tianjie Xua946b9e2017-03-21 16:24:57 -0700886
Tao Baode3bbb82018-05-30 16:14:14 -0700887 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000888}
889
890// Creates a directory for storing stash files and checks if the /cache partition
891// hash enough space for the expected amount of blocks we need to store. Returns
892// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700893static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800894 std::string dirname = GetStashFileName(base, "", "");
895 struct stat sb;
896 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800897 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800898 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800899 strerror(errno));
900 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700901 }
902
903 size_t max_stash_size = maxblocks * BLOCKSIZE;
904 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800905 LOG(INFO) << "creating stash " << dirname;
906 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
907
908 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800909 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800910 strerror(errno));
911 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000912 }
913
Tianjie Xua946b9e2017-03-21 16:24:57 -0700914 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800915 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700916 strerror(errno));
917 return -1;
918 }
919
Tao Bao51412212016-12-28 14:44:05 -0800920 if (CacheSizeCheck(max_stash_size) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800921 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800922 max_stash_size);
923 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000924 }
925
Tao Bao51412212016-12-28 14:44:05 -0800926 return 1; // Created directory
927 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000928
Tao Bao51412212016-12-28 14:44:05 -0800929 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000930
Tao Baoec8272f2017-03-15 17:39:01 -0700931 // If the directory already exists, calculate the space already allocated to stash files and check
932 // if there's enough for all required blocks. Delete any partially completed stash files first.
933 EnumerateStash(dirname, [](const std::string& fn) {
934 if (android::base::EndsWith(fn, ".partial")) {
935 DeleteFile(fn);
936 }
937 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000938
Tao Bao51412212016-12-28 14:44:05 -0800939 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700940 EnumerateStash(dirname, [&existing](const std::string& fn) {
941 if (fn.empty()) return;
942 struct stat sb;
943 if (stat(fn.c_str(), &sb) == -1) {
944 PLOG(ERROR) << "stat \"" << fn << "\" failed";
945 return;
946 }
947 existing += static_cast<size_t>(sb.st_size);
948 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000949
Tao Bao51412212016-12-28 14:44:05 -0800950 if (max_stash_size > existing) {
951 size_t needed = max_stash_size - existing;
952 if (CacheSizeCheck(needed) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800953 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800954 needed);
955 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 }
Tao Bao51412212016-12-28 14:44:05 -0800957 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000958
Tao Bao51412212016-12-28 14:44:05 -0800959 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000960}
961
Tao Baobaad2d42015-12-06 16:56:27 -0800962static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700963 if (base.empty() || id.empty()) {
964 return -1;
965 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000966
Tao Baoec8272f2017-03-15 17:39:01 -0700967 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000968
Tao Baoec8272f2017-03-15 17:39:01 -0700969 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700970}
971
Tao Baobf5b77d2017-03-30 16:57:29 -0700972// Source contains packed data, which we want to move to the locations given in locs in the dest
973// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700974static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700975 const std::vector<uint8_t>& source) {
976 const uint8_t* from = source.data();
977 uint8_t* to = dest.data();
978 size_t start = locs.blocks();
979 // Must do the movement backward.
980 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
981 size_t blocks = it->second - it->first;
982 start -= blocks;
983 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
984 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700985}
986
Tao Baod2aecd42017-03-23 14:43:44 -0700987/**
988 * We expect to parse the remainder of the parameter tokens as one of:
989 *
990 * <src_block_count> <src_range>
991 * (loads data from source image only)
992 *
993 * <src_block_count> - <[stash_id:stash_range] ...>
994 * (loads data from stashes only)
995 *
996 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
997 * (loads data from both source image and stashes)
998 *
999 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1000 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1001 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1002 * LoadStash.
1003 */
1004static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1005 bool* overlap) {
1006 CHECK(src_blocks != nullptr);
1007 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001008
Tao Baod2aecd42017-03-23 14:43:44 -07001009 // <src_block_count>
1010 const std::string& token = params.tokens[params.cpos++];
1011 if (!android::base::ParseUint(token, src_blocks)) {
1012 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1013 return -1;
1014 }
Tao Baobaad2d42015-12-06 16:56:27 -08001015
Tao Baode3bbb82018-05-30 16:14:14 -07001016 allocate(*src_blocks * BLOCKSIZE, &params.buffer);
Tao Baod2aecd42017-03-23 14:43:44 -07001017
1018 // "-" or <src_range> [<src_loc>]
1019 if (params.tokens[params.cpos] == "-") {
1020 // no source ranges, only stashes
1021 params.cpos++;
1022 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001023 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001024 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001025 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001026
Tao Baode3bbb82018-05-30 16:14:14 -07001027 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001028 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001029 }
1030
Tao Baod2aecd42017-03-23 14:43:44 -07001031 if (params.cpos >= params.tokens.size()) {
1032 // no stashes, only source range
1033 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001034 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001035
Tao Bao8f237572017-03-26 13:36:49 -07001036 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001037 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001038 MoveRange(params.buffer, locs, params.buffer);
1039 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001040
Tao Baod2aecd42017-03-23 14:43:44 -07001041 // <[stash_id:stash_range]>
1042 while (params.cpos < params.tokens.size()) {
1043 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1044 // in the source block that stashed data should go.
1045 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1046 if (tokens.size() != 2) {
1047 LOG(ERROR) << "invalid parameter";
1048 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001049 }
1050
Tao Baod2aecd42017-03-23 14:43:44 -07001051 std::vector<uint8_t> stash;
Tao Baode3bbb82018-05-30 16:14:14 -07001052 if (LoadStash(params, tokens[0], false, &stash, true) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001053 // These source blocks will fail verification if used later, but we
1054 // will let the caller decide if this is a fatal failure
1055 LOG(ERROR) << "failed to load stash " << tokens[0];
1056 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001057 }
1058
Tao Bao8f237572017-03-26 13:36:49 -07001059 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001060 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001061 MoveRange(params.buffer, locs, stash);
1062 }
1063
1064 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001065}
1066
Tao Bao33567772017-03-13 14:57:34 -07001067/**
1068 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1069 *
1070 * We expect to parse the remainder of the parameter tokens as one of:
1071 *
1072 * <tgt_range> <src_block_count> <src_range>
1073 * (loads data from source image only)
1074 *
1075 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1076 * (loads data from stashes only)
1077 *
1078 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1079 * (loads data from both source image and stashes)
1080 *
Tao Baod2aecd42017-03-23 14:43:44 -07001081 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1082 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001083 * verification fails in a way that the update cannot be resumed anymore.
1084 *
1085 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1086 * the return value is -1 and the command should be aborted.
1087 *
1088 * If the return value is 1, the command has already been completed according to the contents of the
1089 * target blocks, and should not be performed again.
1090 *
1091 * If the return value is 0, source blocks have expected content and the command can be performed.
1092 */
Tao Baode3bbb82018-05-30 16:14:14 -07001093static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet* tgt, size_t* src_blocks,
Tao Bao4a135082018-06-07 22:27:44 -07001094 bool onehash) {
Tao Baod2aecd42017-03-23 14:43:44 -07001095 CHECK(src_blocks != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001096
Tao Baod2aecd42017-03-23 14:43:44 -07001097 if (params.cpos >= params.tokens.size()) {
1098 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001099 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001100 }
1101
1102 std::string srchash = params.tokens[params.cpos++];
1103 std::string tgthash;
1104
1105 if (onehash) {
1106 tgthash = srchash;
1107 } else {
1108 if (params.cpos >= params.tokens.size()) {
1109 LOG(ERROR) << "missing target hash";
1110 return -1;
1111 }
1112 tgthash = params.tokens[params.cpos++];
1113 }
1114
1115 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1116 // "-"/<src_range>.
1117 if (params.cpos + 2 >= params.tokens.size()) {
1118 LOG(ERROR) << "invalid parameters";
1119 return -1;
1120 }
1121
1122 // <tgt_range>
Tao Baode3bbb82018-05-30 16:14:14 -07001123 *tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1124 CHECK(static_cast<bool>(*tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001125
Tao Baode3bbb82018-05-30 16:14:14 -07001126 std::vector<uint8_t> tgtbuffer(tgt->blocks() * BLOCKSIZE);
1127 if (ReadBlocks(*tgt, &tgtbuffer, params.fd) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001128 return -1;
1129 }
1130
1131 // Return now if target blocks already have expected content.
Tao Baode3bbb82018-05-30 16:14:14 -07001132 if (VerifyBlocks(tgthash, tgtbuffer, tgt->blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001133 return 1;
1134 }
1135
1136 // Load source blocks.
Tao Bao4a135082018-06-07 22:27:44 -07001137 bool overlap = false;
1138 if (LoadSourceBlocks(params, *tgt, src_blocks, &overlap) == -1) {
Tao Baod2aecd42017-03-23 14:43:44 -07001139 return -1;
1140 }
1141
1142 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
Tao Bao4a135082018-06-07 22:27:44 -07001143 // If source and target blocks overlap, stash the source blocks so we can resume from possible
1144 // write errors. In verify mode, we can skip stashing because the source blocks won't be
1145 // overwritten.
1146 if (overlap && params.canwrite) {
Tao Baod2aecd42017-03-23 14:43:44 -07001147 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1148
1149 bool stash_exists = false;
1150 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1151 &stash_exists) != 0) {
1152 LOG(ERROR) << "failed to stash overlapping source blocks";
1153 return -1;
1154 }
1155
1156 params.stashed += *src_blocks;
1157 // Can be deleted when the write has completed.
1158 if (!stash_exists) {
1159 params.freestash = srchash;
1160 }
1161 }
1162
1163 // Source blocks have expected content, command can proceed.
1164 return 0;
1165 }
1166
Tao Bao4a135082018-06-07 22:27:44 -07001167 if (overlap && LoadStash(params, srchash, true, &params.buffer, true) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001168 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1169 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1170 // command.
1171 return 0;
1172 }
1173
1174 // Valid source data not available, update cannot be resumed.
1175 LOG(ERROR) << "partition has unexpected contents";
1176 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1177
1178 params.isunresumable = true;
1179
1180 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001181}
1182
Tao Bao0940fe12015-08-27 16:41:21 -07001183static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001184 size_t blocks = 0;
Tao Bao33567772017-03-13 14:57:34 -07001185 RangeSet tgt;
Tao Bao4a135082018-06-07 22:27:44 -07001186 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Bao33567772017-03-13 14:57:34 -07001188 if (status == -1) {
1189 LOG(ERROR) << "failed to read blocks for move";
1190 return -1;
1191 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001192
Tao Bao33567772017-03-13 14:57:34 -07001193 if (status == 0) {
1194 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001195 } else {
1196 params.target_verified = true;
1197 if (params.foundwrites) {
1198 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1199 }
Tao Bao33567772017-03-13 14:57:34 -07001200 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001201
Tao Bao33567772017-03-13 14:57:34 -07001202 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001203 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001204 LOG(INFO) << " moving " << blocks << " blocks";
1205
1206 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1207 return -1;
1208 }
1209 } else {
1210 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001211 }
Tao Bao33567772017-03-13 14:57:34 -07001212 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001213
Tao Bao33567772017-03-13 14:57:34 -07001214 if (!params.freestash.empty()) {
1215 FreeStash(params.stashbase, params.freestash);
1216 params.freestash.clear();
1217 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001218
Tao Baobf5b77d2017-03-30 16:57:29 -07001219 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001220
Tao Bao33567772017-03-13 14:57:34 -07001221 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222}
1223
Tao Bao0940fe12015-08-27 16:41:21 -07001224static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001225 // <stash_id> <src_range>
1226 if (params.cpos + 1 >= params.tokens.size()) {
1227 LOG(ERROR) << "missing id and/or src range fields in stash command";
1228 return -1;
1229 }
1230
1231 const std::string& id = params.tokens[params.cpos++];
Tao Baode3bbb82018-05-30 16:14:14 -07001232 if (LoadStash(params, id, true, &params.buffer, false) == 0) {
Tao Baobcf46492017-03-23 15:28:20 -07001233 // Stash file already exists and has expected contents. Do not read from source again, as the
1234 // source may have been already overwritten during a previous attempt.
1235 return 0;
1236 }
1237
Tao Bao8f237572017-03-26 13:36:49 -07001238 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001239 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001240
Tao Bao64957ce2018-05-30 16:21:39 -07001241 size_t blocks = src.blocks();
Tao Baode3bbb82018-05-30 16:14:14 -07001242 allocate(blocks * BLOCKSIZE, &params.buffer);
1243 if (ReadBlocks(src, &params.buffer, params.fd) == -1) {
Tao Baobcf46492017-03-23 15:28:20 -07001244 return -1;
1245 }
Tao Baobcf46492017-03-23 15:28:20 -07001246 stash_map[id] = src;
1247
1248 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1249 // Source blocks have unexpected contents. If we actually need this data later, this is an
1250 // unrecoverable error. However, the command that uses the data may have already completed
1251 // previously, so the possible failure will occur during source block verification.
1252 LOG(ERROR) << "failed to load source blocks for stash " << id;
1253 return 0;
1254 }
1255
1256 // In verify mode, we don't need to stash any blocks.
1257 if (!params.canwrite) {
1258 return 0;
1259 }
1260
1261 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001262 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1263 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001264 params.stashed += blocks;
1265 }
1266 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001267}
1268
Tao Bao0940fe12015-08-27 16:41:21 -07001269static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001270 // <stash_id>
1271 if (params.cpos >= params.tokens.size()) {
1272 LOG(ERROR) << "missing stash id in free command";
1273 return -1;
1274 }
Tao Baobaad2d42015-12-06 16:56:27 -08001275
Tao Baobcf46492017-03-23 15:28:20 -07001276 const std::string& id = params.tokens[params.cpos++];
1277 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001278
Tao Baobcf46492017-03-23 15:28:20 -07001279 if (params.createdstash || params.canwrite) {
1280 return FreeStash(params.stashbase, id);
1281 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001282
Tao Baobcf46492017-03-23 15:28:20 -07001283 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284}
1285
Tao Bao0940fe12015-08-27 16:41:21 -07001286static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001287 if (params.cpos >= params.tokens.size()) {
1288 LOG(ERROR) << "missing target blocks for zero";
1289 return -1;
1290 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001291
Tao Baobf5b77d2017-03-30 16:57:29 -07001292 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001293 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001294
1295 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1296
Tao Baode3bbb82018-05-30 16:14:14 -07001297 allocate(BLOCKSIZE, &params.buffer);
Tao Baobf5b77d2017-03-30 16:57:29 -07001298 memset(params.buffer.data(), 0, BLOCKSIZE);
1299
1300 if (params.canwrite) {
1301 for (const auto& range : tgt) {
1302 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1303 size_t size = (range.second - range.first) * BLOCKSIZE;
1304 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001305 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001306 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001307
Tao Baobf5b77d2017-03-30 16:57:29 -07001308 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1309 return -1;
1310 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001311
Tao Baobf5b77d2017-03-30 16:57:29 -07001312 for (size_t j = range.first; j < range.second; ++j) {
1313 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1314 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001315 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001316 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001317 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001318 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001319
Tao Baobf5b77d2017-03-30 16:57:29 -07001320 if (params.cmdname[0] == 'z') {
1321 // Update only for the zero command, as the erase command will call
1322 // this if DEBUG_ERASE is defined.
1323 params.written += tgt.blocks();
1324 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001325
Tao Baobf5b77d2017-03-30 16:57:29 -07001326 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001327}
1328
Tao Bao0940fe12015-08-27 16:41:21 -07001329static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001330 if (params.cpos >= params.tokens.size()) {
1331 LOG(ERROR) << "missing target blocks for new";
1332 return -1;
1333 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001334
Tao Bao8f237572017-03-26 13:36:49 -07001335 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001336 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001337
1338 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001339 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001340
Tao Bao60a70af2017-03-26 14:03:52 -07001341 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001342 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001343 pthread_cond_broadcast(&params.nti.cv);
1344
1345 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001346 if (!params.nti.receiver_available) {
1347 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1348 << " bytes of new data";
1349 pthread_mutex_unlock(&params.nti.mu);
1350 return -1;
1351 }
Tao Bao60a70af2017-03-26 14:03:52 -07001352 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001353 }
1354
Tao Bao60a70af2017-03-26 14:03:52 -07001355 pthread_mutex_unlock(&params.nti.mu);
1356 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001357
Tao Baobf5b77d2017-03-30 16:57:29 -07001358 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001359
Tao Bao60a70af2017-03-26 14:03:52 -07001360 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001361}
1362
Tao Bao0940fe12015-08-27 16:41:21 -07001363static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001364 // <offset> <length>
1365 if (params.cpos + 1 >= params.tokens.size()) {
1366 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1367 return -1;
1368 }
Tao Bao0940fe12015-08-27 16:41:21 -07001369
Tao Baoc0e1c462017-02-01 10:20:10 -08001370 size_t offset;
1371 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1372 LOG(ERROR) << "invalid patch offset";
1373 return -1;
1374 }
Tao Bao0940fe12015-08-27 16:41:21 -07001375
Tao Baoc0e1c462017-02-01 10:20:10 -08001376 size_t len;
1377 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1378 LOG(ERROR) << "invalid patch len";
1379 return -1;
1380 }
Tao Bao0940fe12015-08-27 16:41:21 -07001381
Tao Baoc0e1c462017-02-01 10:20:10 -08001382 RangeSet tgt;
1383 size_t blocks = 0;
Tao Bao4a135082018-06-07 22:27:44 -07001384 int status = LoadSrcTgtVersion3(params, &tgt, &blocks, false);
Tao Bao0940fe12015-08-27 16:41:21 -07001385
Tao Baoc0e1c462017-02-01 10:20:10 -08001386 if (status == -1) {
1387 LOG(ERROR) << "failed to read blocks for diff";
1388 return -1;
1389 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001390
Tao Baoc0e1c462017-02-01 10:20:10 -08001391 if (status == 0) {
1392 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001393 } else {
1394 params.target_verified = true;
1395 if (params.foundwrites) {
1396 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1397 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001398 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001399
Tao Baoc0e1c462017-02-01 10:20:10 -08001400 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001401 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001402 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001403 Value patch_value(
1404 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001405
Tao Bao60a70af2017-03-26 14:03:52 -07001406 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001407 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001408 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001409 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1410 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001411 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001412 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001413 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001414 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001415 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001416 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001417 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001418 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001419 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001420 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001421 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001422 return -1;
1423 }
1424 }
1425
1426 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001427 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001428 LOG(ERROR) << "range sink underrun?";
1429 }
1430 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001431 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001432 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001433 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001434 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001435
Tao Baoc0e1c462017-02-01 10:20:10 -08001436 if (!params.freestash.empty()) {
1437 FreeStash(params.stashbase, params.freestash);
1438 params.freestash.clear();
1439 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001440
Tao Baobf5b77d2017-03-30 16:57:29 -07001441 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001442
Tao Baoc0e1c462017-02-01 10:20:10 -08001443 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001444}
1445
Tao Bao0940fe12015-08-27 16:41:21 -07001446static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001447 if (DEBUG_ERASE) {
1448 return PerformCommandZero(params);
1449 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001450
Tao Baobf5b77d2017-03-30 16:57:29 -07001451 struct stat sb;
1452 if (fstat(params.fd, &sb) == -1) {
1453 PLOG(ERROR) << "failed to fstat device to erase";
1454 return -1;
1455 }
1456
1457 if (!S_ISBLK(sb.st_mode)) {
1458 LOG(ERROR) << "not a block device; skipping erase";
1459 return -1;
1460 }
1461
1462 if (params.cpos >= params.tokens.size()) {
1463 LOG(ERROR) << "missing target blocks for erase";
1464 return -1;
1465 }
1466
1467 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001468 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001469
1470 if (params.canwrite) {
1471 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1472
1473 for (const auto& range : tgt) {
1474 uint64_t blocks[2];
1475 // offset in bytes
1476 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1477 // length in bytes
1478 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1479
1480 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1481 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001482 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001483 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001484 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001485 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001486
Tao Baobf5b77d2017-03-30 16:57:29 -07001487 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001488}
1489
Tao Baoc3901232018-05-21 16:05:56 -07001490using CommandFunction = std::function<int(CommandParameters&)>;
Sami Tolvanen90221202014-12-09 16:39:47 +00001491
Tao Baoc3901232018-05-21 16:05:56 -07001492using CommandMap = std::unordered_map<Command::Type, CommandFunction>;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001493
Tianjie Xuc4447322017-03-06 14:44:59 -08001494static Value* PerformBlockImageUpdate(const char* name, State* state,
1495 const std::vector<std::unique_ptr<Expr>>& argv,
Tao Baoc3901232018-05-21 16:05:56 -07001496 const CommandMap& command_map, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001497 CommandParameters params = {};
Tao Baoc0299ed2018-05-24 00:16:35 -07001498 stash_map.clear();
Tao Bao33567772017-03-13 14:57:34 -07001499 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001500
Tao Bao33567772017-03-13 14:57:34 -07001501 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1502 if (state->is_retry) {
1503 is_retry = true;
1504 LOG(INFO) << "This update is a retry.";
1505 }
1506 if (argv.size() != 4) {
1507 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1508 argv.size());
1509 return StringValue("");
1510 }
1511
1512 std::vector<std::unique_ptr<Value>> args;
1513 if (!ReadValueArgs(state, argv, &args)) {
1514 return nullptr;
1515 }
1516
Tao Baoc3901232018-05-21 16:05:56 -07001517 // args:
1518 // - block device (or file) to modify in-place
1519 // - transfer list (blob)
1520 // - new data stream (filename within package.zip)
1521 // - patch stream (filename within package.zip, must be uncompressed)
Tao Baoc97edcb2017-03-31 01:18:13 -07001522 const std::unique_ptr<Value>& blockdev_filename = args[0];
1523 const std::unique_ptr<Value>& transfer_list_value = args[1];
1524 const std::unique_ptr<Value>& new_data_fn = args[2];
1525 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001526
1527 if (blockdev_filename->type != VAL_STRING) {
1528 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1529 return StringValue("");
1530 }
1531 if (transfer_list_value->type != VAL_BLOB) {
1532 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1533 return StringValue("");
1534 }
1535 if (new_data_fn->type != VAL_STRING) {
1536 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1537 return StringValue("");
1538 }
1539 if (patch_data_fn->type != VAL_STRING) {
1540 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1541 return StringValue("");
1542 }
1543
1544 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1545 if (ui == nullptr) {
1546 return StringValue("");
1547 }
1548
1549 FILE* cmd_pipe = ui->cmd_pipe;
1550 ZipArchiveHandle za = ui->package_zip;
1551
1552 if (cmd_pipe == nullptr || za == nullptr) {
1553 return StringValue("");
1554 }
1555
1556 ZipString path_data(patch_data_fn->data.c_str());
1557 ZipEntry patch_entry;
1558 if (FindEntry(za, path_data, &patch_entry) != 0) {
1559 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1560 return StringValue("");
1561 }
1562
1563 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1564 ZipString new_data(new_data_fn->data.c_str());
1565 ZipEntry new_entry;
1566 if (FindEntry(za, new_data, &new_entry) != 0) {
1567 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1568 return StringValue("");
1569 }
1570
1571 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1572 if (params.fd == -1) {
1573 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1574 return StringValue("");
1575 }
1576
Tao Bao864c6682018-05-07 11:38:25 -07001577 // Stash directory should be different for each partition to avoid conflicts when updating
1578 // multiple partitions at the same time, so we use the hash of the block device name as the base
1579 // directory.
1580 uint8_t digest[SHA_DIGEST_LENGTH];
1581 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1582 blockdev_filename->data.size(), digest);
1583 params.stashbase = print_sha1(digest);
1584
1585 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1586 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1587 // fail the no-op retry.
1588 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1589 if (is_retry) {
1590 struct stat sb;
1591 int result = stat(updated_marker.c_str(), &sb);
1592 if (result == 0) {
1593 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1594 << " based on marker";
1595 return StringValue("t");
1596 }
1597 } else {
1598 // Delete the obsolete marker if any.
1599 std::string err;
1600 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1601 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1602 return StringValue("");
1603 }
1604 }
1605
Tao Bao33567772017-03-13 14:57:34 -07001606 if (params.canwrite) {
1607 params.nti.za = za;
1608 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001609 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1610 if (params.nti.brotli_compressed) {
1611 // Initialize brotli decoder state.
1612 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1613 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001614 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001615
1616 pthread_mutex_init(&params.nti.mu, nullptr);
1617 pthread_cond_init(&params.nti.cv, nullptr);
1618 pthread_attr_t attr;
1619 pthread_attr_init(&attr);
1620 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1621
1622 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1623 if (error != 0) {
1624 PLOG(ERROR) << "pthread_create failed";
1625 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001626 }
Tao Bao33567772017-03-13 14:57:34 -07001627 }
1628
Tao Baoffede3e2018-06-07 09:56:19 -07001629 static constexpr size_t kTransferListHeaderLines = 4;
Tao Bao33567772017-03-13 14:57:34 -07001630 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
Tao Baoffede3e2018-06-07 09:56:19 -07001631 if (lines.size() < kTransferListHeaderLines) {
1632 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001633 lines.size());
1634 return StringValue("");
1635 }
1636
1637 // First line in transfer list is the version number.
1638 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1639 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1640 return StringValue("");
1641 }
1642
1643 LOG(INFO) << "blockimg version is " << params.version;
1644
1645 // Second line in transfer list is the total number of blocks we expect to write.
1646 size_t total_blocks;
1647 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001648 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001649 return StringValue("");
1650 }
1651
1652 if (total_blocks == 0) {
1653 return StringValue("t");
1654 }
1655
Tao Bao33567772017-03-13 14:57:34 -07001656 // Third line is how many stash entries are needed simultaneously.
1657 LOG(INFO) << "maximum stash entries " << lines[2];
1658
1659 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1660 size_t stash_max_blocks;
1661 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001662 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001663 lines[3].c_str());
1664 return StringValue("");
1665 }
1666
Tao Bao864c6682018-05-07 11:38:25 -07001667 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001668 if (res == -1) {
1669 return StringValue("");
1670 }
1671
1672 params.createdstash = res;
1673
Tao Bao26efb0a2018-05-21 14:59:55 -07001674 // When performing an update, save the index and cmdline of the current command into the
1675 // last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001676 // Upon resuming an update, read the saved index first; then
1677 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1678 // the expected target blocks already. If not, these commands cannot be skipped and we need
1679 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1680 // the update will resume from the start of the transfer list.
1681 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1682 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1683 // If an update succeeds or is unresumable, delete the last_command_file.
Tao Bao26efb0a2018-05-21 14:59:55 -07001684 bool skip_executed_command = true;
1685 size_t saved_last_command_index;
Tianjie Xu284752e2017-12-05 11:04:17 -08001686 if (!ParseLastCommandFile(&saved_last_command_index)) {
1687 DeleteLastCommandFile();
Tao Bao26efb0a2018-05-21 14:59:55 -07001688 // We failed to parse the last command. Disallow skipping executed commands.
1689 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001690 }
1691
Tao Bao33567772017-03-13 14:57:34 -07001692 int rc = -1;
1693
1694 // Subsequent lines are all individual transfer commands
Tao Baoab207062018-05-21 14:48:49 -07001695 for (size_t i = kTransferListHeaderLines; i < lines.size(); i++) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001696 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001697 if (line.empty()) continue;
1698
Tao Bao26efb0a2018-05-21 14:59:55 -07001699 size_t cmdindex = i - kTransferListHeaderLines;
Tao Bao33567772017-03-13 14:57:34 -07001700 params.tokens = android::base::Split(line, " ");
1701 params.cpos = 0;
Tao Baoc3901232018-05-21 16:05:56 -07001702 params.cmdname = params.tokens[params.cpos++];
1703 params.cmdline = line;
Tianjie Xu284752e2017-12-05 11:04:17 -08001704 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001705
Tao Baoc3901232018-05-21 16:05:56 -07001706 Command::Type cmd_type = Command::ParseType(params.cmdname);
1707 if (cmd_type == Command::Type::LAST) {
Tao Bao33567772017-03-13 14:57:34 -07001708 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1709 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001710 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001711
Tao Baoc3901232018-05-21 16:05:56 -07001712 const CommandFunction& performer = command_map.at(cmd_type);
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001713
Tianjie Xuc2420842018-02-27 17:05:39 -08001714 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1715 // "erase" during block_image_verify.
Tao Baoc3901232018-05-21 16:05:56 -07001716 if (performer == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001717 LOG(DEBUG) << "skip executing command [" << line << "]";
1718 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001719 }
1720
Tao Bao98f875e2018-05-07 15:03:30 -07001721 // Skip all commands before the saved last command index when resuming an update, except for
1722 // "new" command. Because new commands read in the data sequentially.
Tao Bao26efb0a2018-05-21 14:59:55 -07001723 if (params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index &&
Tao Baoc3901232018-05-21 16:05:56 -07001724 cmd_type != Command::Type::NEW) {
Tao Bao26efb0a2018-05-21 14:59:55 -07001725 LOG(INFO) << "Skipping already executed command: " << cmdindex
Tianjie Xu284752e2017-12-05 11:04:17 -08001726 << ", last executed command for previous update: " << saved_last_command_index;
1727 continue;
1728 }
1729
Tao Baoc3901232018-05-21 16:05:56 -07001730 if (performer(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001731 LOG(ERROR) << "failed to execute command [" << line << "]";
1732 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001733 }
1734
Tao Bao26efb0a2018-05-21 14:59:55 -07001735 // In verify mode, check if the commands before the saved last_command_index have been executed
1736 // correctly. If some target blocks have unexpected contents, delete the last command file so
1737 // that we will resume the update from the first command in the transfer list.
1738 if (!params.canwrite && skip_executed_command && cmdindex <= saved_last_command_index) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001739 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tao Baoc3901232018-05-21 16:05:56 -07001740 if ((cmd_type == Command::Type::MOVE || cmd_type == Command::Type::BSDIFF ||
1741 cmd_type == Command::Type::IMGDIFF) &&
Tianjie Xu284752e2017-12-05 11:04:17 -08001742 !params.target_verified) {
1743 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1744 << params.cmdline << " doesn't produce expected target blocks.";
Tao Bao26efb0a2018-05-21 14:59:55 -07001745 skip_executed_command = false;
Tianjie Xu284752e2017-12-05 11:04:17 -08001746 DeleteLastCommandFile();
1747 }
1748 }
Tao Baoc3901232018-05-21 16:05:56 -07001749
Sami Tolvanen90221202014-12-09 16:39:47 +00001750 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001751 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001752 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001753 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001754 goto pbiudone;
1755 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001756
Tao Bao26efb0a2018-05-21 14:59:55 -07001757 if (!UpdateLastCommandIndex(cmdindex, params.cmdline)) {
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001758 LOG(WARNING) << "Failed to update the last command file.";
1759 }
1760
Tao Bao33567772017-03-13 14:57:34 -07001761 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1762 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001763 }
Tao Bao33567772017-03-13 14:57:34 -07001764 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001765
Tao Bao33567772017-03-13 14:57:34 -07001766 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001767
Tao Bao33567772017-03-13 14:57:34 -07001768pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001769 if (params.canwrite) {
1770 pthread_mutex_lock(&params.nti.mu);
1771 if (params.nti.receiver_available) {
1772 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1773 }
1774 params.nti.receiver_available = false;
1775 pthread_cond_broadcast(&params.nti.cv);
1776 pthread_mutex_unlock(&params.nti.mu);
1777 int ret = pthread_join(params.thread, nullptr);
1778 if (ret != 0) {
1779 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1780 }
1781
1782 if (rc == 0) {
1783 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1784 LOG(INFO) << "stashed " << params.stashed << " blocks";
1785 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1786
1787 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1788 if (partition != nullptr && *(partition + 1) != 0) {
1789 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1790 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1791 fflush(cmd_pipe);
1792 }
1793 // Delete stash only after successfully completing the update, as it may contain blocks needed
1794 // to complete the update later.
1795 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001796 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001797
1798 // Create a marker on /cache partition, which allows skipping the update on this partition on
1799 // retry. The marker will be removed once booting into normal boot, or before starting next
1800 // fresh install.
1801 if (!SetPartitionUpdatedMarker(updated_marker)) {
1802 LOG(WARNING) << "Failed to set updated marker; continuing";
1803 }
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 Baoc3901232018-05-21 16:05:56 -07001886 // Commands which are not allowed are set to nullptr to skip them completely.
1887 const CommandMap command_map{
1888 // clang-format off
1889 { Command::Type::BSDIFF, PerformCommandDiff },
1890 { Command::Type::ERASE, nullptr },
1891 { Command::Type::FREE, PerformCommandFree },
1892 { Command::Type::IMGDIFF, PerformCommandDiff },
1893 { Command::Type::MOVE, PerformCommandMove },
1894 { Command::Type::NEW, nullptr },
1895 { Command::Type::STASH, PerformCommandStash },
1896 { Command::Type::ZERO, nullptr },
1897 // clang-format on
1898 };
1899 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00001900
Tao Baoc3901232018-05-21 16:05:56 -07001901 // Perform a dry run without writing to test if an update can proceed.
1902 return PerformBlockImageUpdate(name, state, argv, command_map, true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001903}
1904
Tianjie Xuc4447322017-03-06 14:44:59 -08001905Value* BlockImageUpdateFn(const char* name, State* state,
1906 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc3901232018-05-21 16:05:56 -07001907 const CommandMap command_map{
1908 // clang-format off
1909 { Command::Type::BSDIFF, PerformCommandDiff },
1910 { Command::Type::ERASE, PerformCommandErase },
1911 { Command::Type::FREE, PerformCommandFree },
1912 { Command::Type::IMGDIFF, PerformCommandDiff },
1913 { Command::Type::MOVE, PerformCommandMove },
1914 { Command::Type::NEW, PerformCommandNew },
1915 { Command::Type::STASH, PerformCommandStash },
1916 { Command::Type::ZERO, PerformCommandZero },
1917 // clang-format on
1918 };
1919 CHECK_EQ(static_cast<size_t>(Command::Type::LAST), command_map.size());
Sami Tolvanen90221202014-12-09 16:39:47 +00001920
Tao Baoc3901232018-05-21 16:05:56 -07001921 return PerformBlockImageUpdate(name, state, argv, command_map, false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001922}
1923
Tianjie Xuc4447322017-03-06 14:44:59 -08001924Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001925 if (argv.size() != 2) {
1926 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1927 return StringValue("");
1928 }
1929
1930 std::vector<std::unique_ptr<Value>> args;
1931 if (!ReadValueArgs(state, argv, &args)) {
1932 return nullptr;
1933 }
1934
1935 const std::unique_ptr<Value>& blockdev_filename = args[0];
1936 const std::unique_ptr<Value>& ranges = args[1];
1937
1938 if (blockdev_filename->type != VAL_STRING) {
1939 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1940 return StringValue("");
1941 }
1942 if (ranges->type != VAL_STRING) {
1943 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1944 return StringValue("");
1945 }
1946
1947 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1948 if (fd == -1) {
1949 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1950 strerror(errno));
1951 return StringValue("");
1952 }
1953
1954 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07001955 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07001956
1957 SHA_CTX ctx;
1958 SHA1_Init(&ctx);
1959
1960 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001961 for (const auto& range : rs) {
1962 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001963 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1964 strerror(errno));
1965 return StringValue("");
1966 }
1967
Tao Baobf5b77d2017-03-30 16:57:29 -07001968 for (size_t j = range.first; j < range.second; ++j) {
Tao Baode3bbb82018-05-30 16:14:14 -07001969 if (read_all(fd, &buffer, BLOCKSIZE) == -1) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001970 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1971 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001972 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001973 }
1974
1975 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001976 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001977 }
1978 uint8_t digest[SHA_DIGEST_LENGTH];
1979 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001980
Tao Baoc97edcb2017-03-31 01:18:13 -07001981 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001982}
1983
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001984// This function checks if a device has been remounted R/W prior to an incremental
1985// OTA update. This is an common cause of update abortion. The function reads the
1986// 1st block of each partition and check for mounting time/count. It return string "t"
1987// if executes successfully and an empty string otherwise.
1988
Tianjie Xuc4447322017-03-06 14:44:59 -08001989Value* CheckFirstBlockFn(const char* name, State* state,
1990 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001991 if (argv.size() != 1) {
1992 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1993 argv.size());
1994 return StringValue("");
1995 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001996
Tao Baoc97edcb2017-03-31 01:18:13 -07001997 std::vector<std::unique_ptr<Value>> args;
1998 if (!ReadValueArgs(state, argv, &args)) {
1999 return nullptr;
2000 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002001
Tao Baoc97edcb2017-03-31 01:18:13 -07002002 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002003
Tao Baoc97edcb2017-03-31 01:18:13 -07002004 if (arg_filename->type != VAL_STRING) {
2005 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2006 return StringValue("");
2007 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002008
Tao Baoc97edcb2017-03-31 01:18:13 -07002009 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2010 if (fd == -1) {
2011 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2012 strerror(errno));
2013 return StringValue("");
2014 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002015
Tao Baobf5b77d2017-03-30 16:57:29 -07002016 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002017 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002018
Tao Baode3bbb82018-05-30 16:14:14 -07002019 if (ReadBlocks(blk0, &block0_buffer, fd) == -1) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002020 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2021 strerror(errno));
2022 return StringValue("");
2023 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002024
Tao Baoc97edcb2017-03-31 01:18:13 -07002025 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2026 // Super block starts from block 0, offset 0x400
2027 // 0x2C: len32 Mount time
2028 // 0x30: len32 Write time
2029 // 0x34: len16 Number of mounts since the last fsck
2030 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002031
Tao Baoc97edcb2017-03-31 01:18:13 -07002032 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2033 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002034
Tao Baoc97edcb2017-03-31 01:18:13 -07002035 if (mount_count > 0) {
2036 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2037 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2038 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002039
Tao Baoc97edcb2017-03-31 01:18:13 -07002040 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002041}
2042
Tianjie Xuc4447322017-03-06 14:44:59 -08002043Value* BlockImageRecoverFn(const char* name, State* state,
2044 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002045 if (argv.size() != 2) {
2046 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2047 argv.size());
2048 return StringValue("");
2049 }
2050
2051 std::vector<std::unique_ptr<Value>> args;
2052 if (!ReadValueArgs(state, argv, &args)) {
2053 return nullptr;
2054 }
2055
2056 const std::unique_ptr<Value>& filename = args[0];
2057 const std::unique_ptr<Value>& ranges = args[1];
2058
2059 if (filename->type != VAL_STRING) {
2060 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2061 return StringValue("");
2062 }
2063 if (ranges->type != VAL_STRING) {
2064 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2065 return StringValue("");
2066 }
Tao Bao67983152017-11-04 00:08:08 -07002067 RangeSet rs = RangeSet::Parse(ranges->data);
2068 if (!rs) {
2069 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2070 return StringValue("");
2071 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002072
2073 // Output notice to log when recover is attempted
2074 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2075
2076 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2077 fec::io fh(filename->data, O_RDWR);
2078
2079 if (!fh) {
2080 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2081 strerror(errno));
2082 return StringValue("");
2083 }
2084
2085 if (!fh.has_ecc() || !fh.has_verity()) {
2086 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2087 return StringValue("");
2088 }
2089
2090 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002091 if (!fh.get_status(status)) {
2092 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2093 return StringValue("");
2094 }
2095
Tao Baoc97edcb2017-03-31 01:18:13 -07002096 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002097 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002098 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002099 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002100 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002101 continue;
2102 }
2103
Tao Baobf5b77d2017-03-30 16:57:29 -07002104 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002105 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2106 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002107 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002108 }
2109
2110 // If we want to be able to recover from a situation where rewriting a corrected
2111 // block doesn't guarantee the same data will be returned when re-read later, we
2112 // can save a copy of corrected blocks to /cache. Note:
2113 //
2114 // 1. Maximum space required from /cache is the same as the maximum number of
2115 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2116 // this would be ~16 MiB, for example.
2117 //
2118 // 2. To find out if this block was corrupted, call fec_get_status after each
2119 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002120 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002121 }
2122 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2123 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002124}
2125
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002126void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002127 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2128 RegisterFunction("block_image_update", BlockImageUpdateFn);
2129 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2130 RegisterFunction("check_first_block", CheckFirstBlockFn);
2131 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002132}