blob: 236644e7f711831a35bd4046330756132cb57174 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000018#include <dirent.h>
Tao Bao641fa972018-04-25 18:59:40 -070019#include <errno.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Tao Bao641fa972018-04-25 18:59:40 -070028#include <sys/ioctl.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000029#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070030#include <sys/types.h>
31#include <sys/wait.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070032#include <time.h>
33#include <unistd.h>
34
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080036#include <limits>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tianjie Xu284752e2017-12-05 11:04:17 -080042#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080043#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080044#include <android-base/parseint.h>
45#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070046#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080047#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070048#include <brotli/decode.h>
Tao Bao641fa972018-04-25 18:59:40 -070049#include <fec/io.h>
Tao Bao51412212016-12-28 14:44:05 -080050#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070051#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070052#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070053
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070055#include "otafault/ota_io.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070056#include "otautil/error_code.h"
Tao Bao641fa972018-04-25 18:59:40 -070057#include "otautil/paths.h"
Tao Bao09e468f2017-09-29 14:39:33 -070058#include "otautil/print_sha1.h"
59#include "otautil/rangeset.h"
Tao Bao8f237572017-03-26 13:36:49 -070060#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070061#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070062
Sami Tolvanene82fa182015-06-10 15:58:12 +000063// Set this to 0 to interpret 'erase' transfers to mean do a
64// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
65// erase to mean fill the region with zeroes.
66#define DEBUG_ERASE 0
67
Tao Bao51412212016-12-28 14:44:05 -080068static constexpr size_t BLOCKSIZE = 4096;
Tao Bao51412212016-12-28 14:44:05 -080069static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
70static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000071
Tianjie Xu16255832016-04-30 11:49:59 -070072static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070073static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070074static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070075
Tianjie Xu284752e2017-12-05 11:04:17 -080076static void DeleteLastCommandFile() {
Tao Bao641fa972018-04-25 18:59:40 -070077 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080078 if (unlink(last_command_file.c_str()) == -1 && errno != ENOENT) {
79 PLOG(ERROR) << "Failed to unlink: " << last_command_file;
80 }
81}
82
83// Parse the last command index of the last update and save the result to |last_command_index|.
84// Return true if we successfully read the index.
85static bool ParseLastCommandFile(int* last_command_index) {
Tao Bao641fa972018-04-25 18:59:40 -070086 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -080087 android::base::unique_fd fd(TEMP_FAILURE_RETRY(open(last_command_file.c_str(), O_RDONLY)));
88 if (fd == -1) {
89 if (errno != ENOENT) {
90 PLOG(ERROR) << "Failed to open " << last_command_file;
91 return false;
92 }
93
94 LOG(INFO) << last_command_file << " doesn't exist.";
95 return false;
96 }
97
98 // Now that the last_command file exists, parse the last command index of previous update.
99 std::string content;
100 if (!android::base::ReadFdToString(fd.get(), &content)) {
101 LOG(ERROR) << "Failed to read: " << last_command_file;
102 return false;
103 }
104
105 std::vector<std::string> lines = android::base::Split(android::base::Trim(content), "\n");
106 if (lines.size() != 2) {
107 LOG(ERROR) << "Unexpected line counts in last command file: " << content;
108 return false;
109 }
110
111 if (!android::base::ParseInt(lines[0], last_command_index)) {
112 LOG(ERROR) << "Failed to parse integer in: " << lines[0];
113 return false;
114 }
115
116 return true;
117}
118
Tao Bao864c6682018-05-07 11:38:25 -0700119static bool FsyncDir(const std::string& dirname) {
120 android::base::unique_fd dfd(
121 TEMP_FAILURE_RETRY(ota_open(dirname.c_str(), O_RDONLY | O_DIRECTORY)));
122 if (dfd == -1) {
123 failure_type = kFileOpenFailure;
124 PLOG(ERROR) << "Failed to open " << dirname;
125 return false;
126 }
127 if (fsync(dfd) == -1) {
128 failure_type = kFsyncFailure;
129 PLOG(ERROR) << "Failed to fsync " << dirname;
130 return false;
131 }
132 return true;
133}
134
Tianjie Xuc2b2bb52018-05-15 15:09:59 -0700135// Update the last executed command index in the last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -0800136static bool UpdateLastCommandIndex(int command_index, const std::string& command_string) {
Tao Bao641fa972018-04-25 18:59:40 -0700137 const std::string& last_command_file = Paths::Get().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800138 std::string last_command_tmp = last_command_file + ".tmp";
139 std::string content = std::to_string(command_index) + "\n" + command_string;
140 android::base::unique_fd wfd(
141 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
142 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
143 PLOG(ERROR) << "Failed to update last command";
144 return false;
145 }
146
147 if (fsync(wfd) == -1) {
148 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
149 return false;
150 }
151
152 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
153 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
154 return false;
155 }
156
157 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
158 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
159 return false;
160 }
161
Tao Bao864c6682018-05-07 11:38:25 -0700162 if (!FsyncDir(android::base::Dirname(last_command_file))) {
Tianjie Xu284752e2017-12-05 11:04:17 -0800163 return false;
164 }
165
Tao Bao864c6682018-05-07 11:38:25 -0700166 return true;
167}
168
169static bool SetPartitionUpdatedMarker(const std::string& marker) {
170 if (!android::base::WriteStringToFile("", marker)) {
171 PLOG(ERROR) << "Failed to write to marker file " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800172 return false;
173 }
Tao Bao864c6682018-05-07 11:38:25 -0700174 if (!FsyncDir(android::base::Dirname(marker))) {
175 return false;
176 }
177 LOG(INFO) << "Wrote partition updated marker to " << marker;
Tianjie Xu284752e2017-12-05 11:04:17 -0800178 return true;
179}
180
Sami Tolvanen90221202014-12-09 16:39:47 +0000181static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700182 size_t so_far = 0;
183 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800184 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700185 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700186 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800187 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000188 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700189 } else if (r == 0) {
190 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800191 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700192 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700194 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700195 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000196 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197}
198
Tao Bao612336d2015-08-27 16:41:21 -0700199static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
200 return read_all(fd, buffer.data(), size);
201}
202
Sami Tolvanen90221202014-12-09 16:39:47 +0000203static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700204 size_t written = 0;
205 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800206 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700207 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700208 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800209 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000210 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700211 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700212 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700213 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000214
Sami Tolvanen90221202014-12-09 16:39:47 +0000215 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700216}
217
Tao Bao612336d2015-08-27 16:41:21 -0700218static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
219 return write_all(fd, buffer.data(), size);
220}
221
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700222static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700223 // Don't discard blocks unless the update is a retry run.
224 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700225 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700226 }
227
228 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
229 if (ioctl(fd, BLKDISCARD, &args) == -1) {
230 PLOG(ERROR) << "BLKDISCARD ioctl failed";
231 return false;
232 }
233 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700234}
235
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700236static bool check_lseek(int fd, off64_t offset, int whence) {
237 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
238 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700239 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800240 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700241 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700242 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700243 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244}
245
Tao Bao612336d2015-08-27 16:41:21 -0700246static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700247 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700248 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700249
Tao Bao612336d2015-08-27 16:41:21 -0700250 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 Bao612336d2015-08-27 16:41:21 -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;
512 if (read_all(fd, buffer.data() + p, size) == -1) {
513 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;
Tianjie Xu284752e2017-12-05 11:04:17 -0800549 int cmdindex;
Tao Baobaad2d42015-12-06 16:56:27 -0800550 const char* cmdname;
551 const char* cmdline;
552 std::string freestash;
553 std::string stashbase;
554 bool canwrite;
555 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700556 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800557 bool foundwrites;
558 bool isunresumable;
559 int version;
560 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700561 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800562 NewThreadInfo nti;
563 pthread_t thread;
564 std::vector<uint8_t> buffer;
565 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800566 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800567};
568
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000569// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
570// handled separately).
571static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
572 const std::vector<uint8_t>& buffer) {
573 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000574 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
575 params.tokens[0] == "imgdiff");
576
577 size_t pos = 0;
578 // Command example:
579 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
580 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
581 // [<loc_range> <stashed_blocks>]
582 if (params.tokens[0] == "move") {
583 // src_range for move starts at the 4th position.
584 if (params.tokens.size() < 5) {
585 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
586 return;
587 }
588 pos = 4;
589 } else {
590 // src_range for diff starts at the 7th position.
591 if (params.tokens.size() < 8) {
592 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
593 return;
594 }
595 pos = 7;
596 }
597
598 // Source blocks in stash only, no work to do.
599 if (params.tokens[pos] == "-") {
600 return;
601 }
602
Tao Bao8f237572017-03-26 13:36:49 -0700603 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700604 if (!src) {
605 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
606 return;
607 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000608
609 RangeSet locs;
610 // If there's no stashed blocks, content in the buffer is consecutive and has the same
611 // order as the source blocks.
612 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700613 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000614 } else {
615 // Otherwise, the next token is the offset of the source blocks in the target range.
616 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
617 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
618 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700619 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700620 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000621 }
622
Tao Baobf5b77d2017-03-30 16:57:29 -0700623 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
624 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700625 size_t block_num = src.GetBlockNumber(i);
626 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000627 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
628
629 uint8_t digest[SHA_DIGEST_LENGTH];
630 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
631 std::string hexdigest = print_sha1(digest);
632 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
633 }
634}
635
636// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
637// in hex for each block.
638static void PrintHashForCorruptedStashedBlocks(const std::string& id,
639 const std::vector<uint8_t>& buffer,
640 const RangeSet& src) {
641 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700642 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000643
Tao Baobf5b77d2017-03-30 16:57:29 -0700644 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700645 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000646
647 uint8_t digest[SHA_DIGEST_LENGTH];
648 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
649 std::string hexdigest = print_sha1(digest);
650 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
651 }
652}
653
654// If the stash file doesn't exist, read the source blocks this stash contains and print the
655// SHA-1 for these blocks.
656static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
657 if (stash_map.find(id) == stash_map.end()) {
658 LOG(ERROR) << "No stash saved for id: " << id;
659 return;
660 }
661
662 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
663 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700664 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000665 if (ReadBlocks(src, buffer, fd) == -1) {
666 LOG(ERROR) << "failed to read source blocks for stash: " << id;
667 return;
668 }
669 PrintHashForCorruptedStashedBlocks(id, buffer, src);
670}
671
Tao Bao612336d2015-08-27 16:41:21 -0700672static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700673 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800674 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700675 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000676
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800677 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000678
Tao Baoe6aa3322015-08-05 15:20:27 -0700679 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000680
Tao Bao0940fe12015-08-27 16:41:21 -0700681 if (hexdigest != expected) {
682 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800683 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
684 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700685 }
686 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000687 }
688
Tao Bao0940fe12015-08-27 16:41:21 -0700689 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000690}
691
Tao Bao0940fe12015-08-27 16:41:21 -0700692static std::string GetStashFileName(const std::string& base, const std::string& id,
Tao Bao641fa972018-04-25 18:59:40 -0700693 const std::string& postfix) {
694 if (base.empty()) {
695 return "";
696 }
Tao Bao864c6682018-05-07 11:38:25 -0700697 std::string filename = Paths::Get().stash_directory_base() + "/" + base;
698 if (id.empty() && postfix.empty()) {
699 return filename;
700 }
701 return filename + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000702}
703
Tao Baoec8272f2017-03-15 17:39:01 -0700704// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
705// directory and continues despite of errors. Calls the 'callback' function for each file.
706static void EnumerateStash(const std::string& dirname,
707 const std::function<void(const std::string&)>& callback) {
708 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000709
Tao Baoec8272f2017-03-15 17:39:01 -0700710 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000711
Tao Baoec8272f2017-03-15 17:39:01 -0700712 if (directory == nullptr) {
713 if (errno != ENOENT) {
714 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
Tao Bao51412212016-12-28 14:44:05 -0800716 return;
717 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700718
Tao Baoec8272f2017-03-15 17:39:01 -0700719 dirent* item;
720 while ((item = readdir(directory.get())) != nullptr) {
721 if (item->d_type != DT_REG) continue;
722 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800723 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000724}
725
726// Deletes the stash directory and all files in it. Assumes that it only
727// contains files. There is nothing we can do about unlikely, but possible
728// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700729static void DeleteFile(const std::string& fn) {
730 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000731
Tao Baoec8272f2017-03-15 17:39:01 -0700732 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733
Tao Baoec8272f2017-03-15 17:39:01 -0700734 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
735 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
736 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000737}
738
Tao Baoe6aa3322015-08-05 15:20:27 -0700739static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700740 if (base.empty()) return;
741
742 LOG(INFO) << "deleting stash " << base;
743
744 std::string dirname = GetStashFileName(base, "", "");
745 EnumerateStash(dirname, DeleteFile);
746
747 if (rmdir(dirname.c_str()) == -1) {
748 if (errno != ENOENT && errno != ENOTDIR) {
749 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 }
Tao Baoec8272f2017-03-15 17:39:01 -0700751 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000752}
753
Tao Baobcf46492017-03-23 15:28:20 -0700754static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
755 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700756 // In verify mode, if source range_set was saved for the given hash, check contents in the source
757 // blocks first. If the check fails, search for the stashed files on /cache as usual.
758 if (!params.canwrite) {
759 if (stash_map.find(id) != stash_map.end()) {
760 const RangeSet& src = stash_map[id];
761 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700762
Tao Baobf5b77d2017-03-30 16:57:29 -0700763 if (ReadBlocks(src, buffer, params.fd) == -1) {
764 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700765 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700766 }
767 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
768 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
769 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700770 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700771 }
772 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000773 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700774 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000775
Tao Baobf5b77d2017-03-30 16:57:29 -0700776 size_t blockcount = 0;
777 if (!blocks) {
778 blocks = &blockcount;
779 }
780
781 std::string fn = GetStashFileName(params.stashbase, id, "");
782
783 struct stat sb;
784 if (stat(fn.c_str(), &sb) == -1) {
785 if (errno != ENOENT || printnoent) {
786 PLOG(ERROR) << "stat \"" << fn << "\" failed";
787 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000788 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700789 return -1;
790 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000791
Tao Baobf5b77d2017-03-30 16:57:29 -0700792 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000793
Tao Baobf5b77d2017-03-30 16:57:29 -0700794 if ((sb.st_size % BLOCKSIZE) != 0) {
795 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
796 return -1;
797 }
798
799 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
800 if (fd == -1) {
801 PLOG(ERROR) << "open \"" << fn << "\" failed";
802 return -1;
803 }
804
805 allocate(sb.st_size, buffer);
806
807 if (read_all(fd, buffer, sb.st_size) == -1) {
808 return -1;
809 }
810
811 *blocks = sb.st_size / BLOCKSIZE;
812
813 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
814 LOG(ERROR) << "unexpected contents in " << fn;
815 if (stash_map.find(id) == stash_map.end()) {
816 LOG(ERROR) << "failed to find source blocks number for stash " << id
817 << " when executing command: " << params.cmdname;
818 } else {
819 const RangeSet& src = stash_map[id];
820 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000821 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700822 DeleteFile(fn);
823 return -1;
824 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000825
Tao Baobf5b77d2017-03-30 16:57:29 -0700826 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000827}
828
Tao Bao612336d2015-08-27 16:41:21 -0700829static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700830 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700831 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700832 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000833 }
834
835 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800836 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700837 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000838 }
839
Tao Bao0940fe12015-08-27 16:41:21 -0700840 std::string fn = GetStashFileName(base, id, ".partial");
841 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000842
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100843 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700844 struct stat sb;
845 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100846
847 if (res == 0) {
848 // The file already exists and since the name is the hash of the contents,
849 // it's safe to assume the contents are identical (accidental hash collisions
850 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800851 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700852 *exists = true;
853 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100854 }
855
Tao Bao0940fe12015-08-27 16:41:21 -0700856 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100857 }
858
Tao Bao039f2da2016-11-22 16:29:50 -0800859 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
Tao Bao039f2da2016-11-22 16:29:50 -0800861 android::base::unique_fd fd(
862 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000863 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800864 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700865 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000866 }
867
Tianjie Xua946b9e2017-03-21 16:24:57 -0700868 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
869 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
870 return -1;
871 }
872
Sami Tolvanen90221202014-12-09 16:39:47 +0000873 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700874 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000875 }
876
Jed Estepa7b9a462015-12-15 16:04:53 -0800877 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700878 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800879 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700880 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000881 }
882
Tao Baoe6aa3322015-08-05 15:20:27 -0700883 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800884 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700885 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000886 }
887
Tao Bao0940fe12015-08-27 16:41:21 -0700888 std::string dname = GetStashFileName(base, "", "");
Tao Bao864c6682018-05-07 11:38:25 -0700889 if (!FsyncDir(dname)) {
890 failure_type = kFsyncFailure;
891 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700892 }
893
Tao Bao0940fe12015-08-27 16:41:21 -0700894 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000895}
896
897// Creates a directory for storing stash files and checks if the /cache partition
898// hash enough space for the expected amount of blocks we need to store. Returns
899// >0 if we created the directory, zero if it existed already, and <0 of failure.
Tao Bao864c6682018-05-07 11:38:25 -0700900static int CreateStash(State* state, size_t maxblocks, const std::string& base) {
Tao Bao51412212016-12-28 14:44:05 -0800901 std::string dirname = GetStashFileName(base, "", "");
902 struct stat sb;
903 int res = stat(dirname.c_str(), &sb);
Tao Bao51412212016-12-28 14:44:05 -0800904 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800905 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800906 strerror(errno));
907 return -1;
Tao Bao864c6682018-05-07 11:38:25 -0700908 }
909
910 size_t max_stash_size = maxblocks * BLOCKSIZE;
911 if (res == -1) {
Tao Bao51412212016-12-28 14:44:05 -0800912 LOG(INFO) << "creating stash " << dirname;
913 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
914
915 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800916 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800917 strerror(errno));
918 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000919 }
920
Tianjie Xua946b9e2017-03-21 16:24:57 -0700921 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800922 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700923 strerror(errno));
924 return -1;
925 }
926
Tao Bao51412212016-12-28 14:44:05 -0800927 if (CacheSizeCheck(max_stash_size) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800928 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800929 max_stash_size);
930 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000931 }
932
Tao Bao51412212016-12-28 14:44:05 -0800933 return 1; // Created directory
934 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000935
Tao Bao51412212016-12-28 14:44:05 -0800936 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000937
Tao Baoec8272f2017-03-15 17:39:01 -0700938 // If the directory already exists, calculate the space already allocated to stash files and check
939 // if there's enough for all required blocks. Delete any partially completed stash files first.
940 EnumerateStash(dirname, [](const std::string& fn) {
941 if (android::base::EndsWith(fn, ".partial")) {
942 DeleteFile(fn);
943 }
944 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000945
Tao Bao51412212016-12-28 14:44:05 -0800946 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700947 EnumerateStash(dirname, [&existing](const std::string& fn) {
948 if (fn.empty()) return;
949 struct stat sb;
950 if (stat(fn.c_str(), &sb) == -1) {
951 PLOG(ERROR) << "stat \"" << fn << "\" failed";
952 return;
953 }
954 existing += static_cast<size_t>(sb.st_size);
955 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000956
Tao Bao51412212016-12-28 14:44:05 -0800957 if (max_stash_size > existing) {
958 size_t needed = max_stash_size - existing;
959 if (CacheSizeCheck(needed) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800960 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800961 needed);
962 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000963 }
Tao Bao51412212016-12-28 14:44:05 -0800964 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000965
Tao Bao51412212016-12-28 14:44:05 -0800966 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000967}
968
Tao Baobaad2d42015-12-06 16:56:27 -0800969static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700970 if (base.empty() || id.empty()) {
971 return -1;
972 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000973
Tao Baoec8272f2017-03-15 17:39:01 -0700974 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000975
Tao Baoec8272f2017-03-15 17:39:01 -0700976 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700977}
978
Tao Baobf5b77d2017-03-30 16:57:29 -0700979// Source contains packed data, which we want to move to the locations given in locs in the dest
980// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700981static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700982 const std::vector<uint8_t>& source) {
983 const uint8_t* from = source.data();
984 uint8_t* to = dest.data();
985 size_t start = locs.blocks();
986 // Must do the movement backward.
987 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
988 size_t blocks = it->second - it->first;
989 start -= blocks;
990 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
991 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700992}
993
Tao Baod2aecd42017-03-23 14:43:44 -0700994/**
995 * We expect to parse the remainder of the parameter tokens as one of:
996 *
997 * <src_block_count> <src_range>
998 * (loads data from source image only)
999 *
1000 * <src_block_count> - <[stash_id:stash_range] ...>
1001 * (loads data from stashes only)
1002 *
1003 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1004 * (loads data from both source image and stashes)
1005 *
1006 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1007 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1008 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1009 * LoadStash.
1010 */
1011static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1012 bool* overlap) {
1013 CHECK(src_blocks != nullptr);
1014 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001015
Tao Baod2aecd42017-03-23 14:43:44 -07001016 // <src_block_count>
1017 const std::string& token = params.tokens[params.cpos++];
1018 if (!android::base::ParseUint(token, src_blocks)) {
1019 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1020 return -1;
1021 }
Tao Baobaad2d42015-12-06 16:56:27 -08001022
Tao Baod2aecd42017-03-23 14:43:44 -07001023 allocate(*src_blocks * BLOCKSIZE, params.buffer);
1024
1025 // "-" or <src_range> [<src_loc>]
1026 if (params.tokens[params.cpos] == "-") {
1027 // no source ranges, only stashes
1028 params.cpos++;
1029 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001030 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001031 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001032 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001033
1034 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1035 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001036 }
1037
Tao Baod2aecd42017-03-23 14:43:44 -07001038 if (params.cpos >= params.tokens.size()) {
1039 // no stashes, only source range
1040 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001041 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001042
Tao Bao8f237572017-03-26 13:36:49 -07001043 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001044 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001045 MoveRange(params.buffer, locs, params.buffer);
1046 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001047
Tao Baod2aecd42017-03-23 14:43:44 -07001048 // <[stash_id:stash_range]>
1049 while (params.cpos < params.tokens.size()) {
1050 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1051 // in the source block that stashed data should go.
1052 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1053 if (tokens.size() != 2) {
1054 LOG(ERROR) << "invalid parameter";
1055 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001056 }
1057
Tao Baod2aecd42017-03-23 14:43:44 -07001058 std::vector<uint8_t> stash;
1059 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
1060 // These source blocks will fail verification if used later, but we
1061 // will let the caller decide if this is a fatal failure
1062 LOG(ERROR) << "failed to load stash " << tokens[0];
1063 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001064 }
1065
Tao Bao8f237572017-03-26 13:36:49 -07001066 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001067 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001068 MoveRange(params.buffer, locs, stash);
1069 }
1070
1071 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001072}
1073
Tao Bao33567772017-03-13 14:57:34 -07001074/**
1075 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1076 *
1077 * We expect to parse the remainder of the parameter tokens as one of:
1078 *
1079 * <tgt_range> <src_block_count> <src_range>
1080 * (loads data from source image only)
1081 *
1082 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1083 * (loads data from stashes only)
1084 *
1085 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1086 * (loads data from both source image and stashes)
1087 *
Tao Baod2aecd42017-03-23 14:43:44 -07001088 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1089 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001090 * verification fails in a way that the update cannot be resumed anymore.
1091 *
1092 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1093 * the return value is -1 and the command should be aborted.
1094 *
1095 * If the return value is 1, the command has already been completed according to the contents of the
1096 * target blocks, and should not be performed again.
1097 *
1098 * If the return value is 0, source blocks have expected content and the command can be performed.
1099 */
Tao Baod2aecd42017-03-23 14:43:44 -07001100static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
1101 bool onehash, bool* overlap) {
1102 CHECK(src_blocks != nullptr);
1103 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001104
Tao Baod2aecd42017-03-23 14:43:44 -07001105 if (params.cpos >= params.tokens.size()) {
1106 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001107 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001108 }
1109
1110 std::string srchash = params.tokens[params.cpos++];
1111 std::string tgthash;
1112
1113 if (onehash) {
1114 tgthash = srchash;
1115 } else {
1116 if (params.cpos >= params.tokens.size()) {
1117 LOG(ERROR) << "missing target hash";
1118 return -1;
1119 }
1120 tgthash = params.tokens[params.cpos++];
1121 }
1122
1123 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1124 // "-"/<src_range>.
1125 if (params.cpos + 2 >= params.tokens.size()) {
1126 LOG(ERROR) << "invalid parameters";
1127 return -1;
1128 }
1129
1130 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -07001131 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001132 CHECK(static_cast<bool>(tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001133
Tao Baobf5b77d2017-03-30 16:57:29 -07001134 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -07001135 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1136 return -1;
1137 }
1138
1139 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -07001140 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001141 return 1;
1142 }
1143
1144 // Load source blocks.
1145 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1146 return -1;
1147 }
1148
1149 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1150 // If source and target blocks overlap, stash the source blocks so we can
1151 // resume from possible write errors. In verify mode, we can skip stashing
1152 // because the source blocks won't be overwritten.
1153 if (*overlap && params.canwrite) {
1154 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1155
1156 bool stash_exists = false;
1157 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1158 &stash_exists) != 0) {
1159 LOG(ERROR) << "failed to stash overlapping source blocks";
1160 return -1;
1161 }
1162
1163 params.stashed += *src_blocks;
1164 // Can be deleted when the write has completed.
1165 if (!stash_exists) {
1166 params.freestash = srchash;
1167 }
1168 }
1169
1170 // Source blocks have expected content, command can proceed.
1171 return 0;
1172 }
1173
1174 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1175 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1176 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1177 // command.
1178 return 0;
1179 }
1180
1181 // Valid source data not available, update cannot be resumed.
1182 LOG(ERROR) << "partition has unexpected contents";
1183 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1184
1185 params.isunresumable = true;
1186
1187 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001188}
1189
Tao Bao0940fe12015-08-27 16:41:21 -07001190static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001191 size_t blocks = 0;
1192 bool overlap = false;
1193 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001194 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001195
Tao Bao33567772017-03-13 14:57:34 -07001196 if (status == -1) {
1197 LOG(ERROR) << "failed to read blocks for move";
1198 return -1;
1199 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001200
Tao Bao33567772017-03-13 14:57:34 -07001201 if (status == 0) {
1202 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001203 } else {
1204 params.target_verified = true;
1205 if (params.foundwrites) {
1206 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1207 }
Tao Bao33567772017-03-13 14:57:34 -07001208 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001209
Tao Bao33567772017-03-13 14:57:34 -07001210 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001211 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001212 LOG(INFO) << " moving " << blocks << " blocks";
1213
1214 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1215 return -1;
1216 }
1217 } else {
1218 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001219 }
Tao Bao33567772017-03-13 14:57:34 -07001220 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001221
Tao Bao33567772017-03-13 14:57:34 -07001222 if (!params.freestash.empty()) {
1223 FreeStash(params.stashbase, params.freestash);
1224 params.freestash.clear();
1225 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001226
Tao Baobf5b77d2017-03-30 16:57:29 -07001227 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001228
Tao Bao33567772017-03-13 14:57:34 -07001229 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001230}
1231
Tao Bao0940fe12015-08-27 16:41:21 -07001232static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001233 // <stash_id> <src_range>
1234 if (params.cpos + 1 >= params.tokens.size()) {
1235 LOG(ERROR) << "missing id and/or src range fields in stash command";
1236 return -1;
1237 }
1238
1239 const std::string& id = params.tokens[params.cpos++];
1240 size_t blocks = 0;
1241 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1242 // Stash file already exists and has expected contents. Do not read from source again, as the
1243 // source may have been already overwritten during a previous attempt.
1244 return 0;
1245 }
1246
Tao Bao8f237572017-03-26 13:36:49 -07001247 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001248 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001249
Tao Baobf5b77d2017-03-30 16:57:29 -07001250 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001251 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1252 return -1;
1253 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001254 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001255 stash_map[id] = src;
1256
1257 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1258 // Source blocks have unexpected contents. If we actually need this data later, this is an
1259 // unrecoverable error. However, the command that uses the data may have already completed
1260 // previously, so the possible failure will occur during source block verification.
1261 LOG(ERROR) << "failed to load source blocks for stash " << id;
1262 return 0;
1263 }
1264
1265 // In verify mode, we don't need to stash any blocks.
1266 if (!params.canwrite) {
1267 return 0;
1268 }
1269
1270 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001271 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1272 if (result == 0) {
Tianjie Xu284752e2017-12-05 11:04:17 -08001273 params.stashed += blocks;
1274 }
1275 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001276}
1277
Tao Bao0940fe12015-08-27 16:41:21 -07001278static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001279 // <stash_id>
1280 if (params.cpos >= params.tokens.size()) {
1281 LOG(ERROR) << "missing stash id in free command";
1282 return -1;
1283 }
Tao Baobaad2d42015-12-06 16:56:27 -08001284
Tao Baobcf46492017-03-23 15:28:20 -07001285 const std::string& id = params.tokens[params.cpos++];
1286 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001287
Tao Baobcf46492017-03-23 15:28:20 -07001288 if (params.createdstash || params.canwrite) {
1289 return FreeStash(params.stashbase, id);
1290 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001291
Tao Baobcf46492017-03-23 15:28:20 -07001292 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001293}
1294
Tao Bao0940fe12015-08-27 16:41:21 -07001295static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001296 if (params.cpos >= params.tokens.size()) {
1297 LOG(ERROR) << "missing target blocks for zero";
1298 return -1;
1299 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001300
Tao Baobf5b77d2017-03-30 16:57:29 -07001301 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001302 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001303
1304 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1305
1306 allocate(BLOCKSIZE, params.buffer);
1307 memset(params.buffer.data(), 0, BLOCKSIZE);
1308
1309 if (params.canwrite) {
1310 for (const auto& range : tgt) {
1311 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1312 size_t size = (range.second - range.first) * BLOCKSIZE;
1313 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001314 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001315 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001316
Tao Baobf5b77d2017-03-30 16:57:29 -07001317 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1318 return -1;
1319 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001320
Tao Baobf5b77d2017-03-30 16:57:29 -07001321 for (size_t j = range.first; j < range.second; ++j) {
1322 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1323 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001324 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001325 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001326 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001327 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001328
Tao Baobf5b77d2017-03-30 16:57:29 -07001329 if (params.cmdname[0] == 'z') {
1330 // Update only for the zero command, as the erase command will call
1331 // this if DEBUG_ERASE is defined.
1332 params.written += tgt.blocks();
1333 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001334
Tao Baobf5b77d2017-03-30 16:57:29 -07001335 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001336}
1337
Tao Bao0940fe12015-08-27 16:41:21 -07001338static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001339 if (params.cpos >= params.tokens.size()) {
1340 LOG(ERROR) << "missing target blocks for new";
1341 return -1;
1342 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001343
Tao Bao8f237572017-03-26 13:36:49 -07001344 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001345 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001346
1347 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001348 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001349
Tao Bao60a70af2017-03-26 14:03:52 -07001350 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001351 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001352 pthread_cond_broadcast(&params.nti.cv);
1353
1354 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001355 if (!params.nti.receiver_available) {
1356 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1357 << " bytes of new data";
1358 pthread_mutex_unlock(&params.nti.mu);
1359 return -1;
1360 }
Tao Bao60a70af2017-03-26 14:03:52 -07001361 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001362 }
1363
Tao Bao60a70af2017-03-26 14:03:52 -07001364 pthread_mutex_unlock(&params.nti.mu);
1365 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001366
Tao Baobf5b77d2017-03-30 16:57:29 -07001367 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001368
Tao Bao60a70af2017-03-26 14:03:52 -07001369 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001370}
1371
Tao Bao0940fe12015-08-27 16:41:21 -07001372static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001373 // <offset> <length>
1374 if (params.cpos + 1 >= params.tokens.size()) {
1375 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1376 return -1;
1377 }
Tao Bao0940fe12015-08-27 16:41:21 -07001378
Tao Baoc0e1c462017-02-01 10:20:10 -08001379 size_t offset;
1380 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1381 LOG(ERROR) << "invalid patch offset";
1382 return -1;
1383 }
Tao Bao0940fe12015-08-27 16:41:21 -07001384
Tao Baoc0e1c462017-02-01 10:20:10 -08001385 size_t len;
1386 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1387 LOG(ERROR) << "invalid patch len";
1388 return -1;
1389 }
Tao Bao0940fe12015-08-27 16:41:21 -07001390
Tao Baoc0e1c462017-02-01 10:20:10 -08001391 RangeSet tgt;
1392 size_t blocks = 0;
1393 bool overlap = false;
1394 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001395
Tao Baoc0e1c462017-02-01 10:20:10 -08001396 if (status == -1) {
1397 LOG(ERROR) << "failed to read blocks for diff";
1398 return -1;
1399 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001400
Tao Baoc0e1c462017-02-01 10:20:10 -08001401 if (status == 0) {
1402 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001403 } else {
1404 params.target_verified = true;
1405 if (params.foundwrites) {
1406 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1407 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001408 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001409
Tao Baoc0e1c462017-02-01 10:20:10 -08001410 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001411 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001412 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001413 Value patch_value(
1414 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001415
Tao Bao60a70af2017-03-26 14:03:52 -07001416 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001417 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001418 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001419 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1420 std::placeholders::_2),
Tao Bao8b0b0f12018-04-19 21:02:13 -07001421 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001422 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001423 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001424 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001425 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001426 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001427 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001428 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
Tao Bao8b0b0f12018-04-19 21:02:13 -07001429 std::placeholders::_2)) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001430 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001431 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001432 return -1;
1433 }
1434 }
1435
1436 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001437 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001438 LOG(ERROR) << "range sink underrun?";
1439 }
1440 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001441 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001442 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001443 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001444 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001445
Tao Baoc0e1c462017-02-01 10:20:10 -08001446 if (!params.freestash.empty()) {
1447 FreeStash(params.stashbase, params.freestash);
1448 params.freestash.clear();
1449 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001450
Tao Baobf5b77d2017-03-30 16:57:29 -07001451 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001452
Tao Baoc0e1c462017-02-01 10:20:10 -08001453 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001454}
1455
Tao Bao0940fe12015-08-27 16:41:21 -07001456static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001457 if (DEBUG_ERASE) {
1458 return PerformCommandZero(params);
1459 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001460
Tao Baobf5b77d2017-03-30 16:57:29 -07001461 struct stat sb;
1462 if (fstat(params.fd, &sb) == -1) {
1463 PLOG(ERROR) << "failed to fstat device to erase";
1464 return -1;
1465 }
1466
1467 if (!S_ISBLK(sb.st_mode)) {
1468 LOG(ERROR) << "not a block device; skipping erase";
1469 return -1;
1470 }
1471
1472 if (params.cpos >= params.tokens.size()) {
1473 LOG(ERROR) << "missing target blocks for erase";
1474 return -1;
1475 }
1476
1477 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001478 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001479
1480 if (params.canwrite) {
1481 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1482
1483 for (const auto& range : tgt) {
1484 uint64_t blocks[2];
1485 // offset in bytes
1486 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1487 // length in bytes
1488 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1489
1490 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1491 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001492 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001493 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001494 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001495 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001496
Tao Baobf5b77d2017-03-30 16:57:29 -07001497 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001498}
1499
1500// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001501typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001502
Tao Bao612336d2015-08-27 16:41:21 -07001503struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001504 const char* name;
1505 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001506};
Sami Tolvanen90221202014-12-09 16:39:47 +00001507
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001508// args:
1509// - block device (or file) to modify in-place
1510// - transfer list (blob)
1511// - new data stream (filename within package.zip)
1512// - patch stream (filename within package.zip, must be uncompressed)
1513
Tianjie Xuc4447322017-03-06 14:44:59 -08001514static Value* PerformBlockImageUpdate(const char* name, State* state,
1515 const std::vector<std::unique_ptr<Expr>>& argv,
1516 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001517 CommandParameters params = {};
1518 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001519
Tao Bao33567772017-03-13 14:57:34 -07001520 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1521 if (state->is_retry) {
1522 is_retry = true;
1523 LOG(INFO) << "This update is a retry.";
1524 }
1525 if (argv.size() != 4) {
1526 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1527 argv.size());
1528 return StringValue("");
1529 }
1530
1531 std::vector<std::unique_ptr<Value>> args;
1532 if (!ReadValueArgs(state, argv, &args)) {
1533 return nullptr;
1534 }
1535
Tao Baoc97edcb2017-03-31 01:18:13 -07001536 const std::unique_ptr<Value>& blockdev_filename = args[0];
1537 const std::unique_ptr<Value>& transfer_list_value = args[1];
1538 const std::unique_ptr<Value>& new_data_fn = args[2];
1539 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001540
1541 if (blockdev_filename->type != VAL_STRING) {
1542 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1543 return StringValue("");
1544 }
1545 if (transfer_list_value->type != VAL_BLOB) {
1546 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1547 return StringValue("");
1548 }
1549 if (new_data_fn->type != VAL_STRING) {
1550 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1551 return StringValue("");
1552 }
1553 if (patch_data_fn->type != VAL_STRING) {
1554 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1555 return StringValue("");
1556 }
1557
1558 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1559 if (ui == nullptr) {
1560 return StringValue("");
1561 }
1562
1563 FILE* cmd_pipe = ui->cmd_pipe;
1564 ZipArchiveHandle za = ui->package_zip;
1565
1566 if (cmd_pipe == nullptr || za == nullptr) {
1567 return StringValue("");
1568 }
1569
1570 ZipString path_data(patch_data_fn->data.c_str());
1571 ZipEntry patch_entry;
1572 if (FindEntry(za, path_data, &patch_entry) != 0) {
1573 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1574 return StringValue("");
1575 }
1576
1577 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1578 ZipString new_data(new_data_fn->data.c_str());
1579 ZipEntry new_entry;
1580 if (FindEntry(za, new_data, &new_entry) != 0) {
1581 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1582 return StringValue("");
1583 }
1584
1585 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1586 if (params.fd == -1) {
1587 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1588 return StringValue("");
1589 }
1590
Tao Bao864c6682018-05-07 11:38:25 -07001591 // Stash directory should be different for each partition to avoid conflicts when updating
1592 // multiple partitions at the same time, so we use the hash of the block device name as the base
1593 // directory.
1594 uint8_t digest[SHA_DIGEST_LENGTH];
1595 SHA1(reinterpret_cast<const uint8_t*>(blockdev_filename->data.data()),
1596 blockdev_filename->data.size(), digest);
1597 params.stashbase = print_sha1(digest);
1598
1599 // Possibly do return early on retry, by checking the marker. If the update on this partition has
1600 // been finished (but interrupted at a later point), there could be leftover on /cache that would
1601 // fail the no-op retry.
1602 std::string updated_marker = GetStashFileName(params.stashbase + ".UPDATED", "", "");
1603 if (is_retry) {
1604 struct stat sb;
1605 int result = stat(updated_marker.c_str(), &sb);
1606 if (result == 0) {
1607 LOG(INFO) << "Skipping already updated partition " << blockdev_filename->data
1608 << " based on marker";
1609 return StringValue("t");
1610 }
1611 } else {
1612 // Delete the obsolete marker if any.
1613 std::string err;
1614 if (!android::base::RemoveFileIfExists(updated_marker, &err)) {
1615 LOG(ERROR) << "Failed to remove partition updated marker " << updated_marker << ": " << err;
1616 return StringValue("");
1617 }
1618 }
1619
Tao Bao33567772017-03-13 14:57:34 -07001620 if (params.canwrite) {
1621 params.nti.za = za;
1622 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001623 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1624 if (params.nti.brotli_compressed) {
1625 // Initialize brotli decoder state.
1626 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1627 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001628 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001629
1630 pthread_mutex_init(&params.nti.mu, nullptr);
1631 pthread_cond_init(&params.nti.cv, nullptr);
1632 pthread_attr_t attr;
1633 pthread_attr_init(&attr);
1634 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1635
1636 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1637 if (error != 0) {
1638 PLOG(ERROR) << "pthread_create failed";
1639 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001640 }
Tao Bao33567772017-03-13 14:57:34 -07001641 }
1642
1643 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1644 if (lines.size() < 2) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001645 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]",
Tao Bao33567772017-03-13 14:57:34 -07001646 lines.size());
1647 return StringValue("");
1648 }
1649
1650 // First line in transfer list is the version number.
1651 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1652 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1653 return StringValue("");
1654 }
1655
1656 LOG(INFO) << "blockimg version is " << params.version;
1657
1658 // Second line in transfer list is the total number of blocks we expect to write.
1659 size_t total_blocks;
1660 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001661 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001662 return StringValue("");
1663 }
1664
1665 if (total_blocks == 0) {
1666 return StringValue("t");
1667 }
1668
1669 size_t start = 2;
1670 if (lines.size() < 4) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001671 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001672 lines.size());
1673 return StringValue("");
1674 }
1675
1676 // Third line is how many stash entries are needed simultaneously.
1677 LOG(INFO) << "maximum stash entries " << lines[2];
1678
1679 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1680 size_t stash_max_blocks;
1681 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001682 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001683 lines[3].c_str());
1684 return StringValue("");
1685 }
1686
Tao Bao864c6682018-05-07 11:38:25 -07001687 int res = CreateStash(state, stash_max_blocks, params.stashbase);
Tao Bao33567772017-03-13 14:57:34 -07001688 if (res == -1) {
1689 return StringValue("");
1690 }
1691
1692 params.createdstash = res;
1693
Tianjie Xu284752e2017-12-05 11:04:17 -08001694 // When performing an update, save the index and cmdline of the current command into
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001695 // the last_command_file.
Tianjie Xu284752e2017-12-05 11:04:17 -08001696 // Upon resuming an update, read the saved index first; then
1697 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1698 // the expected target blocks already. If not, these commands cannot be skipped and we need
1699 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1700 // the update will resume from the start of the transfer list.
1701 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1702 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1703 // If an update succeeds or is unresumable, delete the last_command_file.
1704 int saved_last_command_index;
1705 if (!ParseLastCommandFile(&saved_last_command_index)) {
1706 DeleteLastCommandFile();
1707 // We failed to parse the last command, set it explicitly to -1.
1708 saved_last_command_index = -1;
1709 }
1710
Tao Bao33567772017-03-13 14:57:34 -07001711 start += 2;
1712
1713 // Build a map of the available commands
1714 std::unordered_map<std::string, const Command*> cmd_map;
1715 for (size_t i = 0; i < cmdcount; ++i) {
1716 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1717 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
Tao Bao188f3a52018-04-24 14:15:14 -07001718 return StringValue("");
Tao Bao33567772017-03-13 14:57:34 -07001719 }
1720 cmd_map[commands[i].name] = &commands[i];
1721 }
1722
1723 int rc = -1;
1724
1725 // Subsequent lines are all individual transfer commands
Tianjie Xu284752e2017-12-05 11:04:17 -08001726 for (size_t i = start; i < lines.size(); i++) {
1727 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001728 if (line.empty()) continue;
1729
1730 params.tokens = android::base::Split(line, " ");
1731 params.cpos = 0;
Tianjie Xu284752e2017-12-05 11:04:17 -08001732 if (i - start > std::numeric_limits<int>::max()) {
1733 params.cmdindex = -1;
1734 } else {
1735 params.cmdindex = i - start;
1736 }
Tao Bao33567772017-03-13 14:57:34 -07001737 params.cmdname = params.tokens[params.cpos++].c_str();
1738 params.cmdline = line.c_str();
Tianjie Xu284752e2017-12-05 11:04:17 -08001739 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001740
1741 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1742 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1743 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001744 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001745
Tao Bao33567772017-03-13 14:57:34 -07001746 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001747
Tianjie Xuc2420842018-02-27 17:05:39 -08001748 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1749 // "erase" during block_image_verify.
Tianjie Xu284752e2017-12-05 11:04:17 -08001750 if (cmd->f == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001751 LOG(DEBUG) << "skip executing command [" << line << "]";
1752 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001753 }
1754
Tao Bao98f875e2018-05-07 15:03:30 -07001755 std::string cmdname = std::string(params.cmdname);
1756
1757 // Skip all commands before the saved last command index when resuming an update, except for
1758 // "new" command. Because new commands read in the data sequentially.
1759 if (params.canwrite && params.cmdindex != -1 && params.cmdindex <= saved_last_command_index &&
1760 cmdname != "new") {
Tianjie Xu284752e2017-12-05 11:04:17 -08001761 LOG(INFO) << "Skipping already executed command: " << params.cmdindex
1762 << ", last executed command for previous update: " << saved_last_command_index;
1763 continue;
1764 }
1765
1766 if (cmd->f(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001767 LOG(ERROR) << "failed to execute command [" << line << "]";
1768 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001769 }
1770
Tianjie Xu284752e2017-12-05 11:04:17 -08001771 // In verify mode, check if the commands before the saved last_command_index have been
1772 // executed correctly. If some target blocks have unexpected contents, delete the last command
1773 // file so that we will resume the update from the first command in the transfer list.
1774 if (!params.canwrite && saved_last_command_index != -1 && params.cmdindex != -1 &&
1775 params.cmdindex <= saved_last_command_index) {
1776 // TODO(xunchang) check that the cmdline of the saved index is correct.
Tianjie Xu284752e2017-12-05 11:04:17 -08001777 if ((cmdname == "move" || cmdname == "bsdiff" || cmdname == "imgdiff") &&
1778 !params.target_verified) {
1779 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1780 << params.cmdline << " doesn't produce expected target blocks.";
1781 saved_last_command_index = -1;
1782 DeleteLastCommandFile();
1783 }
1784 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001785 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001786 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001787 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001788 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001789 goto pbiudone;
1790 }
Tianjie Xuc2b2bb52018-05-15 15:09:59 -07001791
1792 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1793 LOG(WARNING) << "Failed to update the last command file.";
1794 }
1795
Tao Bao33567772017-03-13 14:57:34 -07001796 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1797 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001798 }
Tao Bao33567772017-03-13 14:57:34 -07001799 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001800
Tao Bao33567772017-03-13 14:57:34 -07001801 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001802
Tao Bao33567772017-03-13 14:57:34 -07001803pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001804 if (params.canwrite) {
1805 pthread_mutex_lock(&params.nti.mu);
1806 if (params.nti.receiver_available) {
1807 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1808 }
1809 params.nti.receiver_available = false;
1810 pthread_cond_broadcast(&params.nti.cv);
1811 pthread_mutex_unlock(&params.nti.mu);
1812 int ret = pthread_join(params.thread, nullptr);
1813 if (ret != 0) {
1814 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1815 }
1816
1817 if (rc == 0) {
1818 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1819 LOG(INFO) << "stashed " << params.stashed << " blocks";
1820 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1821
1822 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1823 if (partition != nullptr && *(partition + 1) != 0) {
1824 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1825 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1826 fflush(cmd_pipe);
1827 }
1828 // Delete stash only after successfully completing the update, as it may contain blocks needed
1829 // to complete the update later.
1830 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001831 DeleteLastCommandFile();
Tao Bao864c6682018-05-07 11:38:25 -07001832
1833 // Create a marker on /cache partition, which allows skipping the update on this partition on
1834 // retry. The marker will be removed once booting into normal boot, or before starting next
1835 // fresh install.
1836 if (!SetPartitionUpdatedMarker(updated_marker)) {
1837 LOG(WARNING) << "Failed to set updated marker; continuing";
1838 }
Tianjie Xu5450c842017-10-18 13:15:21 -07001839 }
1840
1841 pthread_mutex_destroy(&params.nti.mu);
1842 pthread_cond_destroy(&params.nti.cv);
1843 } else if (rc == 0) {
1844 LOG(INFO) << "verified partition contents; update may be resumed";
1845 }
1846
Tao Bao33567772017-03-13 14:57:34 -07001847 if (ota_fsync(params.fd) == -1) {
1848 failure_type = kFsyncFailure;
1849 PLOG(ERROR) << "fsync failed";
1850 }
1851 // params.fd will be automatically closed because it's a unique_fd.
1852
Tianjie Xu107a34f2017-06-29 17:04:21 -07001853 if (params.nti.brotli_decoder_state != nullptr) {
1854 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1855 }
1856
Tianjie Xu284752e2017-12-05 11:04:17 -08001857 // Delete the last command file if the update cannot be resumed.
1858 if (params.isunresumable) {
1859 DeleteLastCommandFile();
1860 }
1861
Tao Bao33567772017-03-13 14:57:34 -07001862 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1863 // created the stash.
1864 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1865 DeleteStash(params.stashbase);
1866 }
1867
1868 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1869 state->cause_code = failure_type;
1870 }
1871
1872 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001873}
1874
Tao Bao33567772017-03-13 14:57:34 -07001875/**
1876 * The transfer list is a text file containing commands to transfer data from one place to another
1877 * on the target partition. We parse it and execute the commands in order:
1878 *
1879 * zero [rangeset]
1880 * - Fill the indicated blocks with zeros.
1881 *
1882 * new [rangeset]
1883 * - Fill the blocks with data read from the new_data file.
1884 *
1885 * erase [rangeset]
1886 * - Mark the given blocks as empty.
1887 *
1888 * move <...>
1889 * bsdiff <patchstart> <patchlen> <...>
1890 * imgdiff <patchstart> <patchlen> <...>
1891 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1892 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1893 *
1894 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1895 *
1896 * stash <stash_id> <src_range>
1897 * - Load the given source range and stash the data in the given slot of the stash table.
1898 *
1899 * free <stash_id>
1900 * - Free the given stash data.
1901 *
1902 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1903 * a patch or move) after it has been written.
1904 *
1905 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1906 * in a move/bsdiff/imgdiff command.
1907 *
1908 * Within one command the source and target ranges may overlap so in general we need to read the
1909 * entire source into memory before writing anything to the target blocks.
1910 *
1911 * All the patch data is concatenated into one patch_data file in the update package. It must be
1912 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1913 * already compressed, we lose very little by not compressing their concatenation.)
1914 *
1915 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1916 * additional hashes before the range parameters, which are used to check if the command has already
1917 * been completed and verify the integrity of the source data.
1918 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001919Value* BlockImageVerifyFn(const char* name, State* state,
1920 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001921 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001922 const Command commands[] = {
1923 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001924 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001925 { "free", PerformCommandFree },
1926 { "imgdiff", PerformCommandDiff },
1927 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001928 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001929 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001930 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001931 };
1932
1933 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001934 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001935 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001936}
1937
Tianjie Xuc4447322017-03-06 14:44:59 -08001938Value* BlockImageUpdateFn(const char* name, State* state,
1939 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001940 const Command commands[] = {
1941 { "bsdiff", PerformCommandDiff },
1942 { "erase", PerformCommandErase },
1943 { "free", PerformCommandFree },
1944 { "imgdiff", PerformCommandDiff },
1945 { "move", PerformCommandMove },
1946 { "new", PerformCommandNew },
1947 { "stash", PerformCommandStash },
1948 { "zero", PerformCommandZero }
1949 };
1950
Tianjie Xuc4447322017-03-06 14:44:59 -08001951 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001952 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001953}
1954
Tianjie Xuc4447322017-03-06 14:44:59 -08001955Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001956 if (argv.size() != 2) {
1957 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1958 return StringValue("");
1959 }
1960
1961 std::vector<std::unique_ptr<Value>> args;
1962 if (!ReadValueArgs(state, argv, &args)) {
1963 return nullptr;
1964 }
1965
1966 const std::unique_ptr<Value>& blockdev_filename = args[0];
1967 const std::unique_ptr<Value>& ranges = args[1];
1968
1969 if (blockdev_filename->type != VAL_STRING) {
1970 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1971 return StringValue("");
1972 }
1973 if (ranges->type != VAL_STRING) {
1974 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1975 return StringValue("");
1976 }
1977
1978 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1979 if (fd == -1) {
1980 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1981 strerror(errno));
1982 return StringValue("");
1983 }
1984
1985 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07001986 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07001987
1988 SHA_CTX ctx;
1989 SHA1_Init(&ctx);
1990
1991 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001992 for (const auto& range : rs) {
1993 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001994 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1995 strerror(errno));
1996 return StringValue("");
1997 }
1998
Tao Baobf5b77d2017-03-30 16:57:29 -07001999 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002000 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
2001 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
2002 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002003 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002004 }
2005
2006 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08002007 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002008 }
2009 uint8_t digest[SHA_DIGEST_LENGTH];
2010 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08002011
Tao Baoc97edcb2017-03-31 01:18:13 -07002012 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002013}
2014
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002015// This function checks if a device has been remounted R/W prior to an incremental
2016// OTA update. This is an common cause of update abortion. The function reads the
2017// 1st block of each partition and check for mounting time/count. It return string "t"
2018// if executes successfully and an empty string otherwise.
2019
Tianjie Xuc4447322017-03-06 14:44:59 -08002020Value* CheckFirstBlockFn(const char* name, State* state,
2021 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002022 if (argv.size() != 1) {
2023 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
2024 argv.size());
2025 return StringValue("");
2026 }
Tianjie Xuc4447322017-03-06 14:44:59 -08002027
Tao Baoc97edcb2017-03-31 01:18:13 -07002028 std::vector<std::unique_ptr<Value>> args;
2029 if (!ReadValueArgs(state, argv, &args)) {
2030 return nullptr;
2031 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002032
Tao Baoc97edcb2017-03-31 01:18:13 -07002033 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002034
Tao Baoc97edcb2017-03-31 01:18:13 -07002035 if (arg_filename->type != VAL_STRING) {
2036 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2037 return StringValue("");
2038 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002039
Tao Baoc97edcb2017-03-31 01:18:13 -07002040 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2041 if (fd == -1) {
2042 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2043 strerror(errno));
2044 return StringValue("");
2045 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002046
Tao Baobf5b77d2017-03-30 16:57:29 -07002047 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002048 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002049
Tao Baoc97edcb2017-03-31 01:18:13 -07002050 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
2051 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2052 strerror(errno));
2053 return StringValue("");
2054 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002055
Tao Baoc97edcb2017-03-31 01:18:13 -07002056 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2057 // Super block starts from block 0, offset 0x400
2058 // 0x2C: len32 Mount time
2059 // 0x30: len32 Write time
2060 // 0x34: len16 Number of mounts since the last fsck
2061 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002062
Tao Baoc97edcb2017-03-31 01:18:13 -07002063 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2064 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002065
Tao Baoc97edcb2017-03-31 01:18:13 -07002066 if (mount_count > 0) {
2067 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2068 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2069 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002070
Tao Baoc97edcb2017-03-31 01:18:13 -07002071 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002072}
2073
Tianjie Xuc4447322017-03-06 14:44:59 -08002074Value* BlockImageRecoverFn(const char* name, State* state,
2075 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002076 if (argv.size() != 2) {
2077 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2078 argv.size());
2079 return StringValue("");
2080 }
2081
2082 std::vector<std::unique_ptr<Value>> args;
2083 if (!ReadValueArgs(state, argv, &args)) {
2084 return nullptr;
2085 }
2086
2087 const std::unique_ptr<Value>& filename = args[0];
2088 const std::unique_ptr<Value>& ranges = args[1];
2089
2090 if (filename->type != VAL_STRING) {
2091 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2092 return StringValue("");
2093 }
2094 if (ranges->type != VAL_STRING) {
2095 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2096 return StringValue("");
2097 }
Tao Bao67983152017-11-04 00:08:08 -07002098 RangeSet rs = RangeSet::Parse(ranges->data);
2099 if (!rs) {
2100 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2101 return StringValue("");
2102 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002103
2104 // Output notice to log when recover is attempted
2105 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2106
2107 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2108 fec::io fh(filename->data, O_RDWR);
2109
2110 if (!fh) {
2111 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2112 strerror(errno));
2113 return StringValue("");
2114 }
2115
2116 if (!fh.has_ecc() || !fh.has_verity()) {
2117 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2118 return StringValue("");
2119 }
2120
2121 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002122 if (!fh.get_status(status)) {
2123 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2124 return StringValue("");
2125 }
2126
Tao Baoc97edcb2017-03-31 01:18:13 -07002127 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002128 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002129 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002130 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002131 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002132 continue;
2133 }
2134
Tao Baobf5b77d2017-03-30 16:57:29 -07002135 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002136 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2137 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002138 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002139 }
2140
2141 // If we want to be able to recover from a situation where rewriting a corrected
2142 // block doesn't guarantee the same data will be returned when re-read later, we
2143 // can save a copy of corrected blocks to /cache. Note:
2144 //
2145 // 1. Maximum space required from /cache is the same as the maximum number of
2146 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2147 // this would be ~16 MiB, for example.
2148 //
2149 // 2. To find out if this block was corrupted, call fec_get_status after each
2150 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002151 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002152 }
2153 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2154 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002155}
2156
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002157void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002158 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2159 RegisterFunction("block_image_update", BlockImageUpdateFn);
2160 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2161 RegisterFunction("check_first_block", CheckFirstBlockFn);
2162 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002163}