blob: b44e1a2194fb90da7851c70ffe8584962eced7fd [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tao Baoec8272f2017-03-15 17:39:01 -070036#include <functional>
Tianjie Xu284752e2017-12-05 11:04:17 -080037#include <limits>
Tao Baoe6aa3322015-08-05 15:20:27 -070038#include <memory>
39#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070040#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070041#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070042
Tianjie Xu284752e2017-12-05 11:04:17 -080043#include <android-base/file.h>
Tao Bao039f2da2016-11-22 16:29:50 -080044#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080045#include <android-base/parseint.h>
46#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070047#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080048#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070049#include <brotli/decode.h>
Tao Bao51412212016-12-28 14:44:05 -080050#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070051#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070052#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070053
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070055#include "otafault/ota_io.h"
Tianjie Xu3bbb20f2018-02-27 15:56:11 -080056#include "otautil/cache_location.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070057#include "otautil/error_code.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() {
Tianjie Xu3bbb20f2018-02-27 15:56:11 -080077 std::string last_command_file = CacheLocation::location().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) {
Tianjie Xu3bbb20f2018-02-27 15:56:11 -080086 std::string last_command_file = CacheLocation::location().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
119// Update the last command index in the last_command_file if the current command writes to the
120// stash either explicitly or implicitly.
121static bool UpdateLastCommandIndex(int command_index, const std::string& command_string) {
Tianjie Xu3bbb20f2018-02-27 15:56:11 -0800122 std::string last_command_file = CacheLocation::location().last_command_file();
Tianjie Xu284752e2017-12-05 11:04:17 -0800123 std::string last_command_tmp = last_command_file + ".tmp";
124 std::string content = std::to_string(command_index) + "\n" + command_string;
125 android::base::unique_fd wfd(
126 TEMP_FAILURE_RETRY(open(last_command_tmp.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0660)));
127 if (wfd == -1 || !android::base::WriteStringToFd(content, wfd)) {
128 PLOG(ERROR) << "Failed to update last command";
129 return false;
130 }
131
132 if (fsync(wfd) == -1) {
133 PLOG(ERROR) << "Failed to fsync " << last_command_tmp;
134 return false;
135 }
136
137 if (chown(last_command_tmp.c_str(), AID_SYSTEM, AID_SYSTEM) == -1) {
138 PLOG(ERROR) << "Failed to change owner for " << last_command_tmp;
139 return false;
140 }
141
142 if (rename(last_command_tmp.c_str(), last_command_file.c_str()) == -1) {
143 PLOG(ERROR) << "Failed to rename" << last_command_tmp;
144 return false;
145 }
146
147 std::string last_command_dir = android::base::Dirname(last_command_file);
148 android::base::unique_fd dfd(
149 TEMP_FAILURE_RETRY(ota_open(last_command_dir.c_str(), O_RDONLY | O_DIRECTORY)));
150 if (dfd == -1) {
151 PLOG(ERROR) << "Failed to open " << last_command_dir;
152 return false;
153 }
154
155 if (fsync(dfd) == -1) {
156 PLOG(ERROR) << "Failed to fsync " << last_command_dir;
157 return false;
158 }
159
160 return true;
161}
162
Sami Tolvanen90221202014-12-09 16:39:47 +0000163static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700164 size_t so_far = 0;
165 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800166 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700167 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700168 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800169 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000170 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700171 } else if (r == 0) {
172 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800173 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700174 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700176 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000178 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700179}
180
Tao Bao612336d2015-08-27 16:41:21 -0700181static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
182 return read_all(fd, buffer.data(), size);
183}
184
Sami Tolvanen90221202014-12-09 16:39:47 +0000185static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700186 size_t written = 0;
187 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800188 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700189 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700190 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800191 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000192 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700194 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700195 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000196
Sami Tolvanen90221202014-12-09 16:39:47 +0000197 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700198}
199
Tao Bao612336d2015-08-27 16:41:21 -0700200static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
201 return write_all(fd, buffer.data(), size);
202}
203
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700204static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700205 // Don't discard blocks unless the update is a retry run.
206 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700207 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700208 }
209
210 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
211 if (ioctl(fd, BLKDISCARD, &args) == -1) {
212 PLOG(ERROR) << "BLKDISCARD ioctl failed";
213 return false;
214 }
215 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700216}
217
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700218static bool check_lseek(int fd, off64_t offset, int whence) {
219 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
220 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700221 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800222 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700223 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700224 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700225 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700226}
227
Tao Bao612336d2015-08-27 16:41:21 -0700228static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700229 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700230 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700231
Tao Bao612336d2015-08-27 16:41:21 -0700232 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700233}
234
Tao Bao60a70af2017-03-26 14:03:52 -0700235/**
236 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
237 * given RangeSet.
238 */
239class RangeSinkWriter {
240 public:
241 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700242 : fd_(fd),
243 tgt_(tgt),
244 next_range_(0),
245 current_range_left_(0),
246 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700247 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700248 };
Tao Bao0940fe12015-08-27 16:41:21 -0700249
Tao Bao60a70af2017-03-26 14:03:52 -0700250 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700251 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700252 }
253
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700254 size_t AvailableSpace() const {
255 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
256 }
257
258 // Return number of bytes written; and 0 indicates a writing failure.
259 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700260 if (Finished()) {
261 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
262 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700263 }
264
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700265 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700266 while (size > 0) {
267 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700268 if (!SeekToOutputRange()) {
269 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700270 }
Tao Baof7eb7602017-03-27 15:12:48 -0700271
Tao Bao60a70af2017-03-26 14:03:52 -0700272 size_t write_now = size;
273 if (current_range_left_ < write_now) {
274 write_now = current_range_left_;
275 }
Tao Baof7eb7602017-03-27 15:12:48 -0700276
Tao Bao60a70af2017-03-26 14:03:52 -0700277 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700278 break;
279 }
Tao Bao60a70af2017-03-26 14:03:52 -0700280
281 data += write_now;
282 size -= write_now;
283
284 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700285 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700286 }
Tao Bao60a70af2017-03-26 14:03:52 -0700287
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700288 bytes_written_ += written;
289 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700290 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700291
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700292 size_t BytesWritten() const {
293 return bytes_written_;
294 }
295
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700296 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700297 // Set up the output cursor, move to next range if needed.
298 bool SeekToOutputRange() {
299 // We haven't finished the current range yet.
300 if (current_range_left_ != 0) {
301 return true;
302 }
303 // We can't write any more; let the write function return how many bytes have been written
304 // so far.
305 if (next_range_ >= tgt_.size()) {
306 return false;
307 }
308
309 const Range& range = tgt_[next_range_];
310 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
311 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
312 next_range_++;
313
314 if (!discard_blocks(fd_, offset, current_range_left_)) {
315 return false;
316 }
317 if (!check_lseek(fd_, offset, SEEK_SET)) {
318 return false;
319 }
320 return true;
321 }
322
323 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700324 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700325 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700326 const RangeSet& tgt_;
327 // The next range that we should write to.
328 size_t next_range_;
329 // The number of bytes to write before moving to the next range.
330 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700331 // Total bytes written by the writer.
332 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700333};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700334
Tao Bao60a70af2017-03-26 14:03:52 -0700335/**
336 * All of the data for all the 'new' transfers is contained in one file in the update package,
337 * concatenated together in the order in which transfers.list will need it. We want to stream it out
338 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
339 * section until it's that transfer's turn to go.
340 *
341 * To achieve this, we expand the new data from the archive in a background thread, and block that
342 * threads 'receive uncompressed data' function until the main thread has reached a point where we
343 * want some new data to be written. We signal the background thread with the destination for the
344 * data and block the main thread, waiting for the background thread to complete writing that
345 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
346 * transfer.
347 *
348 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
349 * the main thread wants some data written, it sets writer to the destination location and signals
350 * the condition. When the background thread is done writing, it clears writer and signals the
351 * condition again.
352 */
Tao Bao0940fe12015-08-27 16:41:21 -0700353struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700354 ZipArchiveHandle za;
355 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700356 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700357
Tianjie Xu107a34f2017-06-29 17:04:21 -0700358 std::unique_ptr<RangeSinkWriter> writer;
359 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700360 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700361
Tao Bao60a70af2017-03-26 14:03:52 -0700362 pthread_mutex_t mu;
363 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700364};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700365
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700366static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700367 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700368
Tao Bao60a70af2017-03-26 14:03:52 -0700369 while (size > 0) {
370 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
371 pthread_mutex_lock(&nti->mu);
372 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700373 // End the new data receiver if we encounter an error when performing block image update.
374 if (!nti->receiver_available) {
375 pthread_mutex_unlock(&nti->mu);
376 return false;
377 }
Tao Bao60a70af2017-03-26 14:03:52 -0700378 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700379 }
Tao Bao60a70af2017-03-26 14:03:52 -0700380 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700381
Tao Bao60a70af2017-03-26 14:03:52 -0700382 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
383 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700384 size_t write_now = std::min(size, nti->writer->AvailableSpace());
385 if (nti->writer->Write(data, write_now) != write_now) {
386 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700387 return false;
388 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700389
390 data += write_now;
391 size -= write_now;
392
393 if (nti->writer->Finished()) {
394 // We have written all the bytes desired by this writer.
395
396 pthread_mutex_lock(&nti->mu);
397 nti->writer = nullptr;
398 pthread_cond_broadcast(&nti->cv);
399 pthread_mutex_unlock(&nti->mu);
400 }
401 }
402
403 return true;
404}
405
406static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
407 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
408
409 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
410 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
411 pthread_mutex_lock(&nti->mu);
412 while (nti->writer == nullptr) {
Tianjie Xu5450c842017-10-18 13:15:21 -0700413 // End the receiver if we encounter an error when performing block image update.
414 if (!nti->receiver_available) {
415 pthread_mutex_unlock(&nti->mu);
416 return false;
417 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700418 pthread_cond_wait(&nti->cv, &nti->mu);
419 }
420 pthread_mutex_unlock(&nti->mu);
421
422 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
423 // disappear from nti.
424
425 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
426 if (buffer_size == 0) {
427 LOG(ERROR) << "No space left in output range";
428 return false;
429 }
430 uint8_t buffer[buffer_size];
431 size_t available_in = size;
432 size_t available_out = buffer_size;
433 uint8_t* next_out = buffer;
434
435 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
436 BrotliDecoderResult result = BrotliDecoderDecompressStream(
437 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
438
439 if (result == BROTLI_DECODER_RESULT_ERROR) {
440 LOG(ERROR) << "Decompression failed with "
441 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
442 return false;
443 }
444
445 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
446 << size - available_in << ", decoder status " << result;
447
448 size_t write_now = buffer_size - available_out;
449 if (nti->writer->Write(buffer, write_now) != write_now) {
450 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
451 return false;
452 }
453
454 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
455 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700456
457 if (nti->writer->Finished()) {
458 // We have written all the bytes desired by this writer.
459
460 pthread_mutex_lock(&nti->mu);
461 nti->writer = nullptr;
462 pthread_cond_broadcast(&nti->cv);
463 pthread_mutex_unlock(&nti->mu);
464 }
465 }
466
467 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700468}
469
470static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700471 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700472 if (nti->brotli_compressed) {
473 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
474 } else {
475 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
476 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700477 pthread_mutex_lock(&nti->mu);
478 nti->receiver_available = false;
479 if (nti->writer != nullptr) {
480 pthread_cond_broadcast(&nti->cv);
481 }
482 pthread_mutex_unlock(&nti->mu);
483 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700484}
485
Tao Bao612336d2015-08-27 16:41:21 -0700486static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700487 size_t p = 0;
488 for (const auto& range : src) {
489 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
490 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000491 }
492
Tao Baobf5b77d2017-03-30 16:57:29 -0700493 size_t size = (range.second - range.first) * BLOCKSIZE;
494 if (read_all(fd, buffer.data() + p, size) == -1) {
495 return -1;
496 }
497
498 p += size;
499 }
500
501 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000502}
503
Tao Bao612336d2015-08-27 16:41:21 -0700504static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700505 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700506 for (const auto& range : tgt) {
507 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
508 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700509 if (!discard_blocks(fd, offset, size)) {
510 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000511 }
512
Tao Bao60a70af2017-03-26 14:03:52 -0700513 if (!check_lseek(fd, offset, SEEK_SET)) {
514 return -1;
515 }
516
517 if (write_all(fd, buffer.data() + written, size) == -1) {
518 return -1;
519 }
520
521 written += size;
522 }
523
524 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000525}
526
Tao Baobaad2d42015-12-06 16:56:27 -0800527// Parameters for transfer list command functions
528struct CommandParameters {
529 std::vector<std::string> tokens;
530 size_t cpos;
Tianjie Xu284752e2017-12-05 11:04:17 -0800531 int cmdindex;
Tao Baobaad2d42015-12-06 16:56:27 -0800532 const char* cmdname;
533 const char* cmdline;
534 std::string freestash;
535 std::string stashbase;
536 bool canwrite;
537 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700538 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800539 bool foundwrites;
540 bool isunresumable;
541 int version;
542 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700543 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800544 NewThreadInfo nti;
545 pthread_t thread;
546 std::vector<uint8_t> buffer;
547 uint8_t* patch_start;
Tianjie Xu284752e2017-12-05 11:04:17 -0800548 bool target_verified; // The target blocks have expected contents already.
Tao Baobaad2d42015-12-06 16:56:27 -0800549};
550
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000551// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
552// handled separately).
553static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
554 const std::vector<uint8_t>& buffer) {
555 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000556 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
557 params.tokens[0] == "imgdiff");
558
559 size_t pos = 0;
560 // Command example:
561 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
562 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
563 // [<loc_range> <stashed_blocks>]
564 if (params.tokens[0] == "move") {
565 // src_range for move starts at the 4th position.
566 if (params.tokens.size() < 5) {
567 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
568 return;
569 }
570 pos = 4;
571 } else {
572 // src_range for diff starts at the 7th position.
573 if (params.tokens.size() < 8) {
574 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
575 return;
576 }
577 pos = 7;
578 }
579
580 // Source blocks in stash only, no work to do.
581 if (params.tokens[pos] == "-") {
582 return;
583 }
584
Tao Bao8f237572017-03-26 13:36:49 -0700585 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tao Bao67983152017-11-04 00:08:08 -0700586 if (!src) {
587 LOG(ERROR) << "Failed to parse range in " << params.cmdline;
588 return;
589 }
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000590
591 RangeSet locs;
592 // If there's no stashed blocks, content in the buffer is consecutive and has the same
593 // order as the source blocks.
594 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700595 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000596 } else {
597 // Otherwise, the next token is the offset of the source blocks in the target range.
598 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
599 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
600 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700601 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700602 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000603 }
604
Tao Baobf5b77d2017-03-30 16:57:29 -0700605 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
606 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700607 size_t block_num = src.GetBlockNumber(i);
608 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000609 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
610
611 uint8_t digest[SHA_DIGEST_LENGTH];
612 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
613 std::string hexdigest = print_sha1(digest);
614 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
615 }
616}
617
618// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
619// in hex for each block.
620static void PrintHashForCorruptedStashedBlocks(const std::string& id,
621 const std::vector<uint8_t>& buffer,
622 const RangeSet& src) {
623 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700624 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000625
Tao Baobf5b77d2017-03-30 16:57:29 -0700626 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700627 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000628
629 uint8_t digest[SHA_DIGEST_LENGTH];
630 SHA1(buffer.data() + i * 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 stash file doesn't exist, read the source blocks this stash contains and print the
637// SHA-1 for these blocks.
638static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
639 if (stash_map.find(id) == stash_map.end()) {
640 LOG(ERROR) << "No stash saved for id: " << id;
641 return;
642 }
643
644 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
645 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700646 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000647 if (ReadBlocks(src, buffer, fd) == -1) {
648 LOG(ERROR) << "failed to read source blocks for stash: " << id;
649 return;
650 }
651 PrintHashForCorruptedStashedBlocks(id, buffer, src);
652}
653
Tao Bao612336d2015-08-27 16:41:21 -0700654static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700655 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800656 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700657 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000658
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800659 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000660
Tao Baoe6aa3322015-08-05 15:20:27 -0700661 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000662
Tao Bao0940fe12015-08-27 16:41:21 -0700663 if (hexdigest != expected) {
664 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800665 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
666 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700667 }
668 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000669 }
670
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672}
673
Tao Bao0940fe12015-08-27 16:41:21 -0700674static std::string GetStashFileName(const std::string& base, const std::string& id,
675 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700676 if (base.empty()) {
677 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000678 }
679
Tianjie Xu3bbb20f2018-02-27 15:56:11 -0800680 std::string fn(CacheLocation::location().stash_directory_base());
Tao Baoe6aa3322015-08-05 15:20:27 -0700681 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000682
683 return fn;
684}
685
Tao Baoec8272f2017-03-15 17:39:01 -0700686// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
687// directory and continues despite of errors. Calls the 'callback' function for each file.
688static void EnumerateStash(const std::string& dirname,
689 const std::function<void(const std::string&)>& callback) {
690 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000691
Tao Baoec8272f2017-03-15 17:39:01 -0700692 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000693
Tao Baoec8272f2017-03-15 17:39:01 -0700694 if (directory == nullptr) {
695 if (errno != ENOENT) {
696 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000697 }
Tao Bao51412212016-12-28 14:44:05 -0800698 return;
699 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700700
Tao Baoec8272f2017-03-15 17:39:01 -0700701 dirent* item;
702 while ((item = readdir(directory.get())) != nullptr) {
703 if (item->d_type != DT_REG) continue;
704 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800705 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000706}
707
708// Deletes the stash directory and all files in it. Assumes that it only
709// contains files. There is nothing we can do about unlikely, but possible
710// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700711static void DeleteFile(const std::string& fn) {
712 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000713
Tao Baoec8272f2017-03-15 17:39:01 -0700714 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000715
Tao Baoec8272f2017-03-15 17:39:01 -0700716 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
717 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
718 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000719}
720
Tao Baoe6aa3322015-08-05 15:20:27 -0700721static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700722 if (base.empty()) return;
723
724 LOG(INFO) << "deleting stash " << base;
725
726 std::string dirname = GetStashFileName(base, "", "");
727 EnumerateStash(dirname, DeleteFile);
728
729 if (rmdir(dirname.c_str()) == -1) {
730 if (errno != ENOENT && errno != ENOTDIR) {
731 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 }
Tao Baoec8272f2017-03-15 17:39:01 -0700733 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000734}
735
Tao Baobcf46492017-03-23 15:28:20 -0700736static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
737 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700738 // In verify mode, if source range_set was saved for the given hash, check contents in the source
739 // blocks first. If the check fails, search for the stashed files on /cache as usual.
740 if (!params.canwrite) {
741 if (stash_map.find(id) != stash_map.end()) {
742 const RangeSet& src = stash_map[id];
743 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700744
Tao Baobf5b77d2017-03-30 16:57:29 -0700745 if (ReadBlocks(src, buffer, params.fd) == -1) {
746 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700747 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700748 }
749 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
750 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
751 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700752 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700753 }
754 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000755 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700756 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000757
Tao Baobf5b77d2017-03-30 16:57:29 -0700758 size_t blockcount = 0;
759 if (!blocks) {
760 blocks = &blockcount;
761 }
762
763 std::string fn = GetStashFileName(params.stashbase, id, "");
764
765 struct stat sb;
766 if (stat(fn.c_str(), &sb) == -1) {
767 if (errno != ENOENT || printnoent) {
768 PLOG(ERROR) << "stat \"" << fn << "\" failed";
769 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000770 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700771 return -1;
772 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000773
Tao Baobf5b77d2017-03-30 16:57:29 -0700774 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000775
Tao Baobf5b77d2017-03-30 16:57:29 -0700776 if ((sb.st_size % BLOCKSIZE) != 0) {
777 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
778 return -1;
779 }
780
781 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
782 if (fd == -1) {
783 PLOG(ERROR) << "open \"" << fn << "\" failed";
784 return -1;
785 }
786
787 allocate(sb.st_size, buffer);
788
789 if (read_all(fd, buffer, sb.st_size) == -1) {
790 return -1;
791 }
792
793 *blocks = sb.st_size / BLOCKSIZE;
794
795 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
796 LOG(ERROR) << "unexpected contents in " << fn;
797 if (stash_map.find(id) == stash_map.end()) {
798 LOG(ERROR) << "failed to find source blocks number for stash " << id
799 << " when executing command: " << params.cmdname;
800 } else {
801 const RangeSet& src = stash_map[id];
802 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000803 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700804 DeleteFile(fn);
805 return -1;
806 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000807
Tao Baobf5b77d2017-03-30 16:57:29 -0700808 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000809}
810
Tao Bao612336d2015-08-27 16:41:21 -0700811static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700812 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700813 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700814 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000815 }
816
817 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800818 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700819 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000820 }
821
Tao Bao0940fe12015-08-27 16:41:21 -0700822 std::string fn = GetStashFileName(base, id, ".partial");
823 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000824
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100825 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700826 struct stat sb;
827 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100828
829 if (res == 0) {
830 // The file already exists and since the name is the hash of the contents,
831 // it's safe to assume the contents are identical (accidental hash collisions
832 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800833 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700834 *exists = true;
835 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100836 }
837
Tao Bao0940fe12015-08-27 16:41:21 -0700838 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100839 }
840
Tao Bao039f2da2016-11-22 16:29:50 -0800841 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000842
Tao Bao039f2da2016-11-22 16:29:50 -0800843 android::base::unique_fd fd(
844 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000845 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800846 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700847 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000848 }
849
Tianjie Xua946b9e2017-03-21 16:24:57 -0700850 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
851 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
852 return -1;
853 }
854
Sami Tolvanen90221202014-12-09 16:39:47 +0000855 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700856 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000857 }
858
Jed Estepa7b9a462015-12-15 16:04:53 -0800859 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700860 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800861 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700862 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000863 }
864
Tao Baoe6aa3322015-08-05 15:20:27 -0700865 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800866 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700867 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000868 }
869
Tao Bao0940fe12015-08-27 16:41:21 -0700870 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700871 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
872 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700873 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700874 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800875 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700876 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700877 }
878
Jed Estepa7b9a462015-12-15 16:04:53 -0800879 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700880 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800881 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700882 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700883 }
884
Tao Bao0940fe12015-08-27 16:41:21 -0700885 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000886}
887
888// Creates a directory for storing stash files and checks if the /cache partition
889// hash enough space for the expected amount of blocks we need to store. Returns
890// >0 if we created the directory, zero if it existed already, and <0 of failure.
891
Tao Bao51412212016-12-28 14:44:05 -0800892static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
893 std::string& base) {
894 if (blockdev.empty()) {
895 return -1;
896 }
897
898 // Stash directory should be different for each partition to avoid conflicts
899 // when updating multiple partitions at the same time, so we use the hash of
900 // the block device name as the base directory
901 uint8_t digest[SHA_DIGEST_LENGTH];
902 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
903 base = print_sha1(digest);
904
905 std::string dirname = GetStashFileName(base, "", "");
906 struct stat sb;
907 int res = stat(dirname.c_str(), &sb);
908 size_t max_stash_size = maxblocks * BLOCKSIZE;
909
910 if (res == -1 && errno != ENOENT) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800911 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800912 strerror(errno));
913 return -1;
914 } else if (res != 0) {
915 LOG(INFO) << "creating stash " << dirname;
916 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
917
918 if (res != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800919 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s", dirname.c_str(),
Tao Bao51412212016-12-28 14:44:05 -0800920 strerror(errno));
921 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000922 }
923
Tianjie Xua946b9e2017-03-21 16:24:57 -0700924 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
Tianjie Xu5ad80282018-01-28 15:37:48 -0800925 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s", dirname.c_str(),
Tianjie Xua946b9e2017-03-21 16:24:57 -0700926 strerror(errno));
927 return -1;
928 }
929
Tao Bao51412212016-12-28 14:44:05 -0800930 if (CacheSizeCheck(max_stash_size) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800931 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)",
Tao Bao51412212016-12-28 14:44:05 -0800932 max_stash_size);
933 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000934 }
935
Tao Bao51412212016-12-28 14:44:05 -0800936 return 1; // Created directory
937 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000938
Tao Bao51412212016-12-28 14:44:05 -0800939 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000940
Tao Baoec8272f2017-03-15 17:39:01 -0700941 // If the directory already exists, calculate the space already allocated to stash files and check
942 // if there's enough for all required blocks. Delete any partially completed stash files first.
943 EnumerateStash(dirname, [](const std::string& fn) {
944 if (android::base::EndsWith(fn, ".partial")) {
945 DeleteFile(fn);
946 }
947 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000948
Tao Bao51412212016-12-28 14:44:05 -0800949 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700950 EnumerateStash(dirname, [&existing](const std::string& fn) {
951 if (fn.empty()) return;
952 struct stat sb;
953 if (stat(fn.c_str(), &sb) == -1) {
954 PLOG(ERROR) << "stat \"" << fn << "\" failed";
955 return;
956 }
957 existing += static_cast<size_t>(sb.st_size);
958 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000959
Tao Bao51412212016-12-28 14:44:05 -0800960 if (max_stash_size > existing) {
961 size_t needed = max_stash_size - existing;
962 if (CacheSizeCheck(needed) != 0) {
Tianjie Xu5ad80282018-01-28 15:37:48 -0800963 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)",
Tao Bao51412212016-12-28 14:44:05 -0800964 needed);
965 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000966 }
Tao Bao51412212016-12-28 14:44:05 -0800967 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000968
Tao Bao51412212016-12-28 14:44:05 -0800969 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000970}
971
Tao Baobaad2d42015-12-06 16:56:27 -0800972static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700973 if (base.empty() || id.empty()) {
974 return -1;
975 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000976
Tao Baoec8272f2017-03-15 17:39:01 -0700977 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000978
Tao Baoec8272f2017-03-15 17:39:01 -0700979 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700980}
981
Tao Baobf5b77d2017-03-30 16:57:29 -0700982// Source contains packed data, which we want to move to the locations given in locs in the dest
983// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700984static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700985 const std::vector<uint8_t>& source) {
986 const uint8_t* from = source.data();
987 uint8_t* to = dest.data();
988 size_t start = locs.blocks();
989 // Must do the movement backward.
990 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
991 size_t blocks = it->second - it->first;
992 start -= blocks;
993 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
994 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700995}
996
Tao Baod2aecd42017-03-23 14:43:44 -0700997/**
998 * We expect to parse the remainder of the parameter tokens as one of:
999 *
1000 * <src_block_count> <src_range>
1001 * (loads data from source image only)
1002 *
1003 * <src_block_count> - <[stash_id:stash_range] ...>
1004 * (loads data from stashes only)
1005 *
1006 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1007 * (loads data from both source image and stashes)
1008 *
1009 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
1010 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
1011 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
1012 * LoadStash.
1013 */
1014static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
1015 bool* overlap) {
1016 CHECK(src_blocks != nullptr);
1017 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -07001018
Tao Baod2aecd42017-03-23 14:43:44 -07001019 // <src_block_count>
1020 const std::string& token = params.tokens[params.cpos++];
1021 if (!android::base::ParseUint(token, src_blocks)) {
1022 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
1023 return -1;
1024 }
Tao Baobaad2d42015-12-06 16:56:27 -08001025
Tao Baod2aecd42017-03-23 14:43:44 -07001026 allocate(*src_blocks * BLOCKSIZE, params.buffer);
1027
1028 // "-" or <src_range> [<src_loc>]
1029 if (params.tokens[params.cpos] == "-") {
1030 // no source ranges, only stashes
1031 params.cpos++;
1032 } else {
Tao Bao8f237572017-03-26 13:36:49 -07001033 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001034 CHECK(static_cast<bool>(src));
Tao Bao8f237572017-03-26 13:36:49 -07001035 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -07001036
1037 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1038 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -08001039 }
1040
Tao Baod2aecd42017-03-23 14:43:44 -07001041 if (params.cpos >= params.tokens.size()) {
1042 // no stashes, only source range
1043 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -08001044 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001045
Tao Bao8f237572017-03-26 13:36:49 -07001046 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001047 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001048 MoveRange(params.buffer, locs, params.buffer);
1049 }
Doug Zongker52ae67d2014-09-08 12:22:09 -07001050
Tao Baod2aecd42017-03-23 14:43:44 -07001051 // <[stash_id:stash_range]>
1052 while (params.cpos < params.tokens.size()) {
1053 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
1054 // in the source block that stashed data should go.
1055 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
1056 if (tokens.size() != 2) {
1057 LOG(ERROR) << "invalid parameter";
1058 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001059 }
1060
Tao Baod2aecd42017-03-23 14:43:44 -07001061 std::vector<uint8_t> stash;
1062 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
1063 // These source blocks will fail verification if used later, but we
1064 // will let the caller decide if this is a fatal failure
1065 LOG(ERROR) << "failed to load stash " << tokens[0];
1066 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +00001067 }
1068
Tao Bao8f237572017-03-26 13:36:49 -07001069 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Bao67983152017-11-04 00:08:08 -07001070 CHECK(static_cast<bool>(locs));
Tao Baod2aecd42017-03-23 14:43:44 -07001071 MoveRange(params.buffer, locs, stash);
1072 }
1073
1074 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001075}
1076
Tao Bao33567772017-03-13 14:57:34 -07001077/**
1078 * Do a source/target load for move/bsdiff/imgdiff in version 3.
1079 *
1080 * We expect to parse the remainder of the parameter tokens as one of:
1081 *
1082 * <tgt_range> <src_block_count> <src_range>
1083 * (loads data from source image only)
1084 *
1085 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
1086 * (loads data from stashes only)
1087 *
1088 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
1089 * (loads data from both source image and stashes)
1090 *
Tao Baod2aecd42017-03-23 14:43:44 -07001091 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
1092 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -07001093 * verification fails in a way that the update cannot be resumed anymore.
1094 *
1095 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
1096 * the return value is -1 and the command should be aborted.
1097 *
1098 * If the return value is 1, the command has already been completed according to the contents of the
1099 * target blocks, and should not be performed again.
1100 *
1101 * If the return value is 0, source blocks have expected content and the command can be performed.
1102 */
Tao Baod2aecd42017-03-23 14:43:44 -07001103static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
1104 bool onehash, bool* overlap) {
1105 CHECK(src_blocks != nullptr);
1106 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001107
Tao Baod2aecd42017-03-23 14:43:44 -07001108 if (params.cpos >= params.tokens.size()) {
1109 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001110 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001111 }
1112
1113 std::string srchash = params.tokens[params.cpos++];
1114 std::string tgthash;
1115
1116 if (onehash) {
1117 tgthash = srchash;
1118 } else {
1119 if (params.cpos >= params.tokens.size()) {
1120 LOG(ERROR) << "missing target hash";
1121 return -1;
1122 }
1123 tgthash = params.tokens[params.cpos++];
1124 }
1125
1126 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1127 // "-"/<src_range>.
1128 if (params.cpos + 2 >= params.tokens.size()) {
1129 LOG(ERROR) << "invalid parameters";
1130 return -1;
1131 }
1132
1133 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -07001134 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001135 CHECK(static_cast<bool>(tgt));
Tao Baod2aecd42017-03-23 14:43:44 -07001136
Tao Baobf5b77d2017-03-30 16:57:29 -07001137 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -07001138 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1139 return -1;
1140 }
1141
1142 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -07001143 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001144 return 1;
1145 }
1146
1147 // Load source blocks.
1148 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1149 return -1;
1150 }
1151
1152 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1153 // If source and target blocks overlap, stash the source blocks so we can
1154 // resume from possible write errors. In verify mode, we can skip stashing
1155 // because the source blocks won't be overwritten.
1156 if (*overlap && params.canwrite) {
1157 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1158
1159 bool stash_exists = false;
1160 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1161 &stash_exists) != 0) {
1162 LOG(ERROR) << "failed to stash overlapping source blocks";
1163 return -1;
1164 }
1165
Tianjie Xu284752e2017-12-05 11:04:17 -08001166 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1167 LOG(WARNING) << "Failed to update the last command file.";
1168 }
1169
Tao Baod2aecd42017-03-23 14:43:44 -07001170 params.stashed += *src_blocks;
1171 // Can be deleted when the write has completed.
1172 if (!stash_exists) {
1173 params.freestash = srchash;
1174 }
1175 }
1176
1177 // Source blocks have expected content, command can proceed.
1178 return 0;
1179 }
1180
1181 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1182 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1183 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1184 // command.
1185 return 0;
1186 }
1187
1188 // Valid source data not available, update cannot be resumed.
1189 LOG(ERROR) << "partition has unexpected contents";
1190 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1191
1192 params.isunresumable = true;
1193
1194 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001195}
1196
Tao Bao0940fe12015-08-27 16:41:21 -07001197static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001198 size_t blocks = 0;
1199 bool overlap = false;
1200 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001201 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Bao33567772017-03-13 14:57:34 -07001203 if (status == -1) {
1204 LOG(ERROR) << "failed to read blocks for move";
1205 return -1;
1206 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001207
Tao Bao33567772017-03-13 14:57:34 -07001208 if (status == 0) {
1209 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001210 } else {
1211 params.target_verified = true;
1212 if (params.foundwrites) {
1213 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1214 }
Tao Bao33567772017-03-13 14:57:34 -07001215 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001216
Tao Bao33567772017-03-13 14:57:34 -07001217 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001218 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001219 LOG(INFO) << " moving " << blocks << " blocks";
1220
1221 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1222 return -1;
1223 }
1224 } else {
1225 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001226 }
Tao Bao33567772017-03-13 14:57:34 -07001227 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001228
Tao Bao33567772017-03-13 14:57:34 -07001229 if (!params.freestash.empty()) {
1230 FreeStash(params.stashbase, params.freestash);
1231 params.freestash.clear();
1232 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001233
Tao Baobf5b77d2017-03-30 16:57:29 -07001234 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001235
Tao Bao33567772017-03-13 14:57:34 -07001236 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001237}
1238
Tao Bao0940fe12015-08-27 16:41:21 -07001239static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001240 // <stash_id> <src_range>
1241 if (params.cpos + 1 >= params.tokens.size()) {
1242 LOG(ERROR) << "missing id and/or src range fields in stash command";
1243 return -1;
1244 }
1245
1246 const std::string& id = params.tokens[params.cpos++];
1247 size_t blocks = 0;
1248 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1249 // Stash file already exists and has expected contents. Do not read from source again, as the
1250 // source may have been already overwritten during a previous attempt.
1251 return 0;
1252 }
1253
Tao Bao8f237572017-03-26 13:36:49 -07001254 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001255 CHECK(static_cast<bool>(src));
Tao Baobcf46492017-03-23 15:28:20 -07001256
Tao Baobf5b77d2017-03-30 16:57:29 -07001257 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001258 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1259 return -1;
1260 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001261 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001262 stash_map[id] = src;
1263
1264 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1265 // Source blocks have unexpected contents. If we actually need this data later, this is an
1266 // unrecoverable error. However, the command that uses the data may have already completed
1267 // previously, so the possible failure will occur during source block verification.
1268 LOG(ERROR) << "failed to load source blocks for stash " << id;
1269 return 0;
1270 }
1271
1272 // In verify mode, we don't need to stash any blocks.
1273 if (!params.canwrite) {
1274 return 0;
1275 }
1276
1277 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
Tianjie Xu284752e2017-12-05 11:04:17 -08001278 int result = WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
1279 if (result == 0) {
1280 if (!UpdateLastCommandIndex(params.cmdindex, params.cmdline)) {
1281 LOG(WARNING) << "Failed to update the last command file.";
1282 }
1283
1284 params.stashed += blocks;
1285 }
1286 return result;
Sami Tolvanen90221202014-12-09 16:39:47 +00001287}
1288
Tao Bao0940fe12015-08-27 16:41:21 -07001289static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001290 // <stash_id>
1291 if (params.cpos >= params.tokens.size()) {
1292 LOG(ERROR) << "missing stash id in free command";
1293 return -1;
1294 }
Tao Baobaad2d42015-12-06 16:56:27 -08001295
Tao Baobcf46492017-03-23 15:28:20 -07001296 const std::string& id = params.tokens[params.cpos++];
1297 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001298
Tao Baobcf46492017-03-23 15:28:20 -07001299 if (params.createdstash || params.canwrite) {
1300 return FreeStash(params.stashbase, id);
1301 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001302
Tao Baobcf46492017-03-23 15:28:20 -07001303 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001304}
1305
Tao Bao0940fe12015-08-27 16:41:21 -07001306static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001307 if (params.cpos >= params.tokens.size()) {
1308 LOG(ERROR) << "missing target blocks for zero";
1309 return -1;
1310 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001311
Tao Baobf5b77d2017-03-30 16:57:29 -07001312 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001313 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001314
1315 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1316
1317 allocate(BLOCKSIZE, params.buffer);
1318 memset(params.buffer.data(), 0, BLOCKSIZE);
1319
1320 if (params.canwrite) {
1321 for (const auto& range : tgt) {
1322 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1323 size_t size = (range.second - range.first) * BLOCKSIZE;
1324 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001325 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001326 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001327
Tao Baobf5b77d2017-03-30 16:57:29 -07001328 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1329 return -1;
1330 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001331
Tao Baobf5b77d2017-03-30 16:57:29 -07001332 for (size_t j = range.first; j < range.second; ++j) {
1333 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1334 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001335 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001336 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001337 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001338 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001339
Tao Baobf5b77d2017-03-30 16:57:29 -07001340 if (params.cmdname[0] == 'z') {
1341 // Update only for the zero command, as the erase command will call
1342 // this if DEBUG_ERASE is defined.
1343 params.written += tgt.blocks();
1344 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001345
Tao Baobf5b77d2017-03-30 16:57:29 -07001346 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001347}
1348
Tao Bao0940fe12015-08-27 16:41:21 -07001349static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001350 if (params.cpos >= params.tokens.size()) {
1351 LOG(ERROR) << "missing target blocks for new";
1352 return -1;
1353 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001354
Tao Bao8f237572017-03-26 13:36:49 -07001355 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001356 CHECK(static_cast<bool>(tgt));
Tao Bao60a70af2017-03-26 14:03:52 -07001357
1358 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001359 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001360
Tao Bao60a70af2017-03-26 14:03:52 -07001361 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001362 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001363 pthread_cond_broadcast(&params.nti.cv);
1364
1365 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001366 if (!params.nti.receiver_available) {
1367 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1368 << " bytes of new data";
1369 pthread_mutex_unlock(&params.nti.mu);
1370 return -1;
1371 }
Tao Bao60a70af2017-03-26 14:03:52 -07001372 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001373 }
1374
Tao Bao60a70af2017-03-26 14:03:52 -07001375 pthread_mutex_unlock(&params.nti.mu);
1376 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001377
Tao Baobf5b77d2017-03-30 16:57:29 -07001378 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001379
Tao Bao60a70af2017-03-26 14:03:52 -07001380 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001381}
1382
Tao Bao0940fe12015-08-27 16:41:21 -07001383static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001384 // <offset> <length>
1385 if (params.cpos + 1 >= params.tokens.size()) {
1386 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1387 return -1;
1388 }
Tao Bao0940fe12015-08-27 16:41:21 -07001389
Tao Baoc0e1c462017-02-01 10:20:10 -08001390 size_t offset;
1391 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1392 LOG(ERROR) << "invalid patch offset";
1393 return -1;
1394 }
Tao Bao0940fe12015-08-27 16:41:21 -07001395
Tao Baoc0e1c462017-02-01 10:20:10 -08001396 size_t len;
1397 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1398 LOG(ERROR) << "invalid patch len";
1399 return -1;
1400 }
Tao Bao0940fe12015-08-27 16:41:21 -07001401
Tao Baoc0e1c462017-02-01 10:20:10 -08001402 RangeSet tgt;
1403 size_t blocks = 0;
1404 bool overlap = false;
1405 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001406
Tao Baoc0e1c462017-02-01 10:20:10 -08001407 if (status == -1) {
1408 LOG(ERROR) << "failed to read blocks for diff";
1409 return -1;
1410 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001411
Tao Baoc0e1c462017-02-01 10:20:10 -08001412 if (status == 0) {
1413 params.foundwrites = true;
Tianjie Xu284752e2017-12-05 11:04:17 -08001414 } else {
1415 params.target_verified = true;
1416 if (params.foundwrites) {
1417 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1418 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001419 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001420
Tao Baoc0e1c462017-02-01 10:20:10 -08001421 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001422 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001423 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001424 Value patch_value(
1425 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001426
Tao Bao60a70af2017-03-26 14:03:52 -07001427 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001428 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao1e0941f2017-11-10 11:49:53 -08001429 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value,
Tao Bao60a70af2017-03-26 14:03:52 -07001430 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1431 std::placeholders::_2),
1432 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001433 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001434 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001435 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001436 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001437 } else {
Tao Bao1e0941f2017-11-10 11:49:53 -08001438 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, patch_value, 0,
Tao Bao60a70af2017-03-26 14:03:52 -07001439 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1440 std::placeholders::_2),
1441 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001442 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001443 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001444 return -1;
1445 }
1446 }
1447
1448 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001449 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001450 LOG(ERROR) << "range sink underrun?";
1451 }
1452 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001453 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001454 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001455 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001456 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001457
Tao Baoc0e1c462017-02-01 10:20:10 -08001458 if (!params.freestash.empty()) {
1459 FreeStash(params.stashbase, params.freestash);
1460 params.freestash.clear();
1461 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001462
Tao Baobf5b77d2017-03-30 16:57:29 -07001463 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001464
Tao Baoc0e1c462017-02-01 10:20:10 -08001465 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001466}
1467
Tao Bao0940fe12015-08-27 16:41:21 -07001468static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001469 if (DEBUG_ERASE) {
1470 return PerformCommandZero(params);
1471 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001472
Tao Baobf5b77d2017-03-30 16:57:29 -07001473 struct stat sb;
1474 if (fstat(params.fd, &sb) == -1) {
1475 PLOG(ERROR) << "failed to fstat device to erase";
1476 return -1;
1477 }
1478
1479 if (!S_ISBLK(sb.st_mode)) {
1480 LOG(ERROR) << "not a block device; skipping erase";
1481 return -1;
1482 }
1483
1484 if (params.cpos >= params.tokens.size()) {
1485 LOG(ERROR) << "missing target blocks for erase";
1486 return -1;
1487 }
1488
1489 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao67983152017-11-04 00:08:08 -07001490 CHECK(static_cast<bool>(tgt));
Tao Baobf5b77d2017-03-30 16:57:29 -07001491
1492 if (params.canwrite) {
1493 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1494
1495 for (const auto& range : tgt) {
1496 uint64_t blocks[2];
1497 // offset in bytes
1498 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1499 // length in bytes
1500 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1501
andi340ef64922015-05-09 10:48:52 -07001502#ifndef SUPPRESS_EMMC_WIPE
Tao Baobf5b77d2017-03-30 16:57:29 -07001503 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1504 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001505 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001506 }
andi340ef64922015-05-09 10:48:52 -07001507#endif
Sami Tolvanen90221202014-12-09 16:39:47 +00001508 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001509 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001510
Tao Baobf5b77d2017-03-30 16:57:29 -07001511 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001512}
1513
1514// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001515typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001516
Tao Bao612336d2015-08-27 16:41:21 -07001517struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001518 const char* name;
1519 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001520};
Sami Tolvanen90221202014-12-09 16:39:47 +00001521
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001522// args:
1523// - block device (or file) to modify in-place
1524// - transfer list (blob)
1525// - new data stream (filename within package.zip)
1526// - patch stream (filename within package.zip, must be uncompressed)
1527
Tianjie Xuc4447322017-03-06 14:44:59 -08001528static Value* PerformBlockImageUpdate(const char* name, State* state,
1529 const std::vector<std::unique_ptr<Expr>>& argv,
1530 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001531 CommandParameters params = {};
1532 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001533
Tao Bao33567772017-03-13 14:57:34 -07001534 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1535 if (state->is_retry) {
1536 is_retry = true;
1537 LOG(INFO) << "This update is a retry.";
1538 }
1539 if (argv.size() != 4) {
1540 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1541 argv.size());
1542 return StringValue("");
1543 }
1544
1545 std::vector<std::unique_ptr<Value>> args;
1546 if (!ReadValueArgs(state, argv, &args)) {
1547 return nullptr;
1548 }
1549
Tao Baoc97edcb2017-03-31 01:18:13 -07001550 const std::unique_ptr<Value>& blockdev_filename = args[0];
1551 const std::unique_ptr<Value>& transfer_list_value = args[1];
1552 const std::unique_ptr<Value>& new_data_fn = args[2];
1553 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001554
1555 if (blockdev_filename->type != VAL_STRING) {
1556 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1557 return StringValue("");
1558 }
1559 if (transfer_list_value->type != VAL_BLOB) {
1560 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1561 return StringValue("");
1562 }
1563 if (new_data_fn->type != VAL_STRING) {
1564 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1565 return StringValue("");
1566 }
1567 if (patch_data_fn->type != VAL_STRING) {
1568 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1569 return StringValue("");
1570 }
1571
1572 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1573 if (ui == nullptr) {
1574 return StringValue("");
1575 }
1576
1577 FILE* cmd_pipe = ui->cmd_pipe;
1578 ZipArchiveHandle za = ui->package_zip;
1579
1580 if (cmd_pipe == nullptr || za == nullptr) {
1581 return StringValue("");
1582 }
1583
1584 ZipString path_data(patch_data_fn->data.c_str());
1585 ZipEntry patch_entry;
1586 if (FindEntry(za, path_data, &patch_entry) != 0) {
1587 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1588 return StringValue("");
1589 }
1590
1591 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1592 ZipString new_data(new_data_fn->data.c_str());
1593 ZipEntry new_entry;
1594 if (FindEntry(za, new_data, &new_entry) != 0) {
1595 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1596 return StringValue("");
1597 }
1598
1599 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1600 if (params.fd == -1) {
1601 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1602 return StringValue("");
1603 }
1604
1605 if (params.canwrite) {
1606 params.nti.za = za;
1607 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001608 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1609 if (params.nti.brotli_compressed) {
1610 // Initialize brotli decoder state.
1611 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1612 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001613 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001614
1615 pthread_mutex_init(&params.nti.mu, nullptr);
1616 pthread_cond_init(&params.nti.cv, nullptr);
1617 pthread_attr_t attr;
1618 pthread_attr_init(&attr);
1619 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1620
1621 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1622 if (error != 0) {
1623 PLOG(ERROR) << "pthread_create failed";
1624 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001625 }
Tao Bao33567772017-03-13 14:57:34 -07001626 }
1627
1628 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1629 if (lines.size() < 2) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001630 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]",
Tao Bao33567772017-03-13 14:57:34 -07001631 lines.size());
1632 return StringValue("");
1633 }
1634
1635 // First line in transfer list is the version number.
1636 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1637 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1638 return StringValue("");
1639 }
1640
1641 LOG(INFO) << "blockimg version is " << params.version;
1642
1643 // Second line in transfer list is the total number of blocks we expect to write.
1644 size_t total_blocks;
1645 if (!android::base::ParseUint(lines[1], &total_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001646 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]", lines[1].c_str());
Tao Bao33567772017-03-13 14:57:34 -07001647 return StringValue("");
1648 }
1649
1650 if (total_blocks == 0) {
1651 return StringValue("t");
1652 }
1653
1654 size_t start = 2;
1655 if (lines.size() < 4) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001656 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]",
Tao Bao33567772017-03-13 14:57:34 -07001657 lines.size());
1658 return StringValue("");
1659 }
1660
1661 // Third line is how many stash entries are needed simultaneously.
1662 LOG(INFO) << "maximum stash entries " << lines[2];
1663
1664 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1665 size_t stash_max_blocks;
1666 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
Tianjie Xu5ad80282018-01-28 15:37:48 -08001667 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]",
Tao Bao33567772017-03-13 14:57:34 -07001668 lines[3].c_str());
1669 return StringValue("");
1670 }
1671
1672 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1673 if (res == -1) {
1674 return StringValue("");
1675 }
1676
1677 params.createdstash = res;
1678
Tianjie Xu284752e2017-12-05 11:04:17 -08001679 // When performing an update, save the index and cmdline of the current command into
1680 // the last_command_file if this command writes to the stash either explicitly of implicitly.
1681 // Upon resuming an update, read the saved index first; then
1682 // 1. In verification mode, check if the 'move' or 'diff' commands before the saved index has
1683 // the expected target blocks already. If not, these commands cannot be skipped and we need
1684 // to attempt to execute them again. Therefore, we will delete the last_command_file so that
1685 // the update will resume from the start of the transfer list.
1686 // 2. In update mode, skip all commands before the saved index. Therefore, we can avoid deleting
1687 // stashes with duplicate id unintentionally (b/69858743); and also speed up the update.
1688 // If an update succeeds or is unresumable, delete the last_command_file.
1689 int saved_last_command_index;
1690 if (!ParseLastCommandFile(&saved_last_command_index)) {
1691 DeleteLastCommandFile();
1692 // We failed to parse the last command, set it explicitly to -1.
1693 saved_last_command_index = -1;
1694 }
1695
Tao Bao33567772017-03-13 14:57:34 -07001696 start += 2;
1697
1698 // Build a map of the available commands
1699 std::unordered_map<std::string, const Command*> cmd_map;
1700 for (size_t i = 0; i < cmdcount; ++i) {
1701 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1702 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1703 return StringValue(strdup(""));
1704 }
1705 cmd_map[commands[i].name] = &commands[i];
1706 }
1707
1708 int rc = -1;
1709
1710 // Subsequent lines are all individual transfer commands
Tianjie Xu284752e2017-12-05 11:04:17 -08001711 for (size_t i = start; i < lines.size(); i++) {
1712 const std::string& line = lines[i];
Tao Bao33567772017-03-13 14:57:34 -07001713 if (line.empty()) continue;
1714
1715 params.tokens = android::base::Split(line, " ");
1716 params.cpos = 0;
Tianjie Xu284752e2017-12-05 11:04:17 -08001717 if (i - start > std::numeric_limits<int>::max()) {
1718 params.cmdindex = -1;
1719 } else {
1720 params.cmdindex = i - start;
1721 }
Tao Bao33567772017-03-13 14:57:34 -07001722 params.cmdname = params.tokens[params.cpos++].c_str();
1723 params.cmdline = line.c_str();
Tianjie Xu284752e2017-12-05 11:04:17 -08001724 params.target_verified = false;
Tao Bao33567772017-03-13 14:57:34 -07001725
1726 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1727 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1728 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001729 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001730
Tao Bao33567772017-03-13 14:57:34 -07001731 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001732
Tianjie Xuc2420842018-02-27 17:05:39 -08001733 // Skip the command if we explicitly set the corresponding function pointer to nullptr, e.g.
1734 // "erase" during block_image_verify.
Tianjie Xu284752e2017-12-05 11:04:17 -08001735 if (cmd->f == nullptr) {
Tianjie Xuc2420842018-02-27 17:05:39 -08001736 LOG(DEBUG) << "skip executing command [" << line << "]";
1737 continue;
Tianjie Xu284752e2017-12-05 11:04:17 -08001738 }
1739
1740 // Skip all commands before the saved last command index when resuming an update.
1741 if (params.canwrite && params.cmdindex != -1 && params.cmdindex <= saved_last_command_index) {
1742 LOG(INFO) << "Skipping already executed command: " << params.cmdindex
1743 << ", last executed command for previous update: " << saved_last_command_index;
1744 continue;
1745 }
1746
1747 if (cmd->f(params) == -1) {
Tao Bao33567772017-03-13 14:57:34 -07001748 LOG(ERROR) << "failed to execute command [" << line << "]";
1749 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001750 }
1751
Tianjie Xu284752e2017-12-05 11:04:17 -08001752 // In verify mode, check if the commands before the saved last_command_index have been
1753 // executed correctly. If some target blocks have unexpected contents, delete the last command
1754 // file so that we will resume the update from the first command in the transfer list.
1755 if (!params.canwrite && saved_last_command_index != -1 && params.cmdindex != -1 &&
1756 params.cmdindex <= saved_last_command_index) {
1757 // TODO(xunchang) check that the cmdline of the saved index is correct.
1758 std::string cmdname = std::string(params.cmdname);
1759 if ((cmdname == "move" || cmdname == "bsdiff" || cmdname == "imgdiff") &&
1760 !params.target_verified) {
1761 LOG(WARNING) << "Previously executed command " << saved_last_command_index << ": "
1762 << params.cmdline << " doesn't produce expected target blocks.";
1763 saved_last_command_index = -1;
1764 DeleteLastCommandFile();
1765 }
1766 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001767 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001768 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001769 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001770 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001771 goto pbiudone;
1772 }
1773 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1774 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001775 }
Tao Bao33567772017-03-13 14:57:34 -07001776 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001777
Tao Bao33567772017-03-13 14:57:34 -07001778 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001779
Tao Bao33567772017-03-13 14:57:34 -07001780pbiudone:
Tianjie Xu5450c842017-10-18 13:15:21 -07001781 if (params.canwrite) {
1782 pthread_mutex_lock(&params.nti.mu);
1783 if (params.nti.receiver_available) {
1784 LOG(WARNING) << "new data receiver is still available after executing all commands.";
1785 }
1786 params.nti.receiver_available = false;
1787 pthread_cond_broadcast(&params.nti.cv);
1788 pthread_mutex_unlock(&params.nti.mu);
1789 int ret = pthread_join(params.thread, nullptr);
1790 if (ret != 0) {
1791 LOG(WARNING) << "pthread join returned with " << strerror(ret);
1792 }
1793
1794 if (rc == 0) {
1795 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1796 LOG(INFO) << "stashed " << params.stashed << " blocks";
1797 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1798
1799 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1800 if (partition != nullptr && *(partition + 1) != 0) {
1801 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1802 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1803 fflush(cmd_pipe);
1804 }
1805 // Delete stash only after successfully completing the update, as it may contain blocks needed
1806 // to complete the update later.
1807 DeleteStash(params.stashbase);
Tianjie Xu284752e2017-12-05 11:04:17 -08001808 DeleteLastCommandFile();
Tianjie Xu5450c842017-10-18 13:15:21 -07001809 }
1810
1811 pthread_mutex_destroy(&params.nti.mu);
1812 pthread_cond_destroy(&params.nti.cv);
1813 } else if (rc == 0) {
1814 LOG(INFO) << "verified partition contents; update may be resumed";
1815 }
1816
Tao Bao33567772017-03-13 14:57:34 -07001817 if (ota_fsync(params.fd) == -1) {
1818 failure_type = kFsyncFailure;
1819 PLOG(ERROR) << "fsync failed";
1820 }
1821 // params.fd will be automatically closed because it's a unique_fd.
1822
Tianjie Xu107a34f2017-06-29 17:04:21 -07001823 if (params.nti.brotli_decoder_state != nullptr) {
1824 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1825 }
1826
Tianjie Xu284752e2017-12-05 11:04:17 -08001827 // Delete the last command file if the update cannot be resumed.
1828 if (params.isunresumable) {
1829 DeleteLastCommandFile();
1830 }
1831
Tao Bao33567772017-03-13 14:57:34 -07001832 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1833 // created the stash.
1834 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1835 DeleteStash(params.stashbase);
1836 }
1837
1838 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1839 state->cause_code = failure_type;
1840 }
1841
1842 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001843}
1844
Tao Bao33567772017-03-13 14:57:34 -07001845/**
1846 * The transfer list is a text file containing commands to transfer data from one place to another
1847 * on the target partition. We parse it and execute the commands in order:
1848 *
1849 * zero [rangeset]
1850 * - Fill the indicated blocks with zeros.
1851 *
1852 * new [rangeset]
1853 * - Fill the blocks with data read from the new_data file.
1854 *
1855 * erase [rangeset]
1856 * - Mark the given blocks as empty.
1857 *
1858 * move <...>
1859 * bsdiff <patchstart> <patchlen> <...>
1860 * imgdiff <patchstart> <patchlen> <...>
1861 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1862 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1863 *
1864 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1865 *
1866 * stash <stash_id> <src_range>
1867 * - Load the given source range and stash the data in the given slot of the stash table.
1868 *
1869 * free <stash_id>
1870 * - Free the given stash data.
1871 *
1872 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1873 * a patch or move) after it has been written.
1874 *
1875 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1876 * in a move/bsdiff/imgdiff command.
1877 *
1878 * Within one command the source and target ranges may overlap so in general we need to read the
1879 * entire source into memory before writing anything to the target blocks.
1880 *
1881 * All the patch data is concatenated into one patch_data file in the update package. It must be
1882 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1883 * already compressed, we lose very little by not compressing their concatenation.)
1884 *
1885 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1886 * additional hashes before the range parameters, which are used to check if the command has already
1887 * been completed and verify the integrity of the source data.
1888 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001889Value* BlockImageVerifyFn(const char* name, State* state,
1890 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001891 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001892 const Command commands[] = {
1893 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001894 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001895 { "free", PerformCommandFree },
1896 { "imgdiff", PerformCommandDiff },
1897 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001898 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001899 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001900 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001901 };
1902
1903 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001904 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001905 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001906}
1907
Tianjie Xuc4447322017-03-06 14:44:59 -08001908Value* BlockImageUpdateFn(const char* name, State* state,
1909 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001910 const Command commands[] = {
1911 { "bsdiff", PerformCommandDiff },
1912 { "erase", PerformCommandErase },
1913 { "free", PerformCommandFree },
1914 { "imgdiff", PerformCommandDiff },
1915 { "move", PerformCommandMove },
1916 { "new", PerformCommandNew },
1917 { "stash", PerformCommandStash },
1918 { "zero", PerformCommandZero }
1919 };
1920
Tianjie Xuc4447322017-03-06 14:44:59 -08001921 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001922 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001923}
1924
Tianjie Xuc4447322017-03-06 14:44:59 -08001925Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001926 if (argv.size() != 2) {
1927 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1928 return StringValue("");
1929 }
1930
1931 std::vector<std::unique_ptr<Value>> args;
1932 if (!ReadValueArgs(state, argv, &args)) {
1933 return nullptr;
1934 }
1935
1936 const std::unique_ptr<Value>& blockdev_filename = args[0];
1937 const std::unique_ptr<Value>& ranges = args[1];
1938
1939 if (blockdev_filename->type != VAL_STRING) {
1940 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1941 return StringValue("");
1942 }
1943 if (ranges->type != VAL_STRING) {
1944 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1945 return StringValue("");
1946 }
1947
1948 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1949 if (fd == -1) {
1950 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1951 strerror(errno));
1952 return StringValue("");
1953 }
1954
1955 RangeSet rs = RangeSet::Parse(ranges->data);
Tao Bao67983152017-11-04 00:08:08 -07001956 CHECK(static_cast<bool>(rs));
Tao Baoc97edcb2017-03-31 01:18:13 -07001957
1958 SHA_CTX ctx;
1959 SHA1_Init(&ctx);
1960
1961 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001962 for (const auto& range : rs) {
1963 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001964 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1965 strerror(errno));
1966 return StringValue("");
1967 }
1968
Tao Baobf5b77d2017-03-30 16:57:29 -07001969 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001970 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1971 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1972 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001973 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001974 }
1975
1976 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001977 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001978 }
1979 uint8_t digest[SHA_DIGEST_LENGTH];
1980 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001981
Tao Baoc97edcb2017-03-31 01:18:13 -07001982 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001983}
1984
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001985// This function checks if a device has been remounted R/W prior to an incremental
1986// OTA update. This is an common cause of update abortion. The function reads the
1987// 1st block of each partition and check for mounting time/count. It return string "t"
1988// if executes successfully and an empty string otherwise.
1989
Tianjie Xuc4447322017-03-06 14:44:59 -08001990Value* CheckFirstBlockFn(const char* name, State* state,
1991 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001992 if (argv.size() != 1) {
1993 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1994 argv.size());
1995 return StringValue("");
1996 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001997
Tao Baoc97edcb2017-03-31 01:18:13 -07001998 std::vector<std::unique_ptr<Value>> args;
1999 if (!ReadValueArgs(state, argv, &args)) {
2000 return nullptr;
2001 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002002
Tao Baoc97edcb2017-03-31 01:18:13 -07002003 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07002004
Tao Baoc97edcb2017-03-31 01:18:13 -07002005 if (arg_filename->type != VAL_STRING) {
2006 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2007 return StringValue("");
2008 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002009
Tao Baoc97edcb2017-03-31 01:18:13 -07002010 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
2011 if (fd == -1) {
2012 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
2013 strerror(errno));
2014 return StringValue("");
2015 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002016
Tao Baobf5b77d2017-03-30 16:57:29 -07002017 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07002018 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002019
Tao Baoc97edcb2017-03-31 01:18:13 -07002020 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
2021 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
2022 strerror(errno));
2023 return StringValue("");
2024 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002025
Tao Baoc97edcb2017-03-31 01:18:13 -07002026 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
2027 // Super block starts from block 0, offset 0x400
2028 // 0x2C: len32 Mount time
2029 // 0x30: len32 Write time
2030 // 0x34: len16 Number of mounts since the last fsck
2031 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002032
Tao Baoc97edcb2017-03-31 01:18:13 -07002033 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
2034 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002035
Tao Baoc97edcb2017-03-31 01:18:13 -07002036 if (mount_count > 0) {
2037 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
2038 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
2039 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002040
Tao Baoc97edcb2017-03-31 01:18:13 -07002041 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08002042}
2043
Tianjie Xuc4447322017-03-06 14:44:59 -08002044Value* BlockImageRecoverFn(const char* name, State* state,
2045 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002046 if (argv.size() != 2) {
2047 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
2048 argv.size());
2049 return StringValue("");
2050 }
2051
2052 std::vector<std::unique_ptr<Value>> args;
2053 if (!ReadValueArgs(state, argv, &args)) {
2054 return nullptr;
2055 }
2056
2057 const std::unique_ptr<Value>& filename = args[0];
2058 const std::unique_ptr<Value>& ranges = args[1];
2059
2060 if (filename->type != VAL_STRING) {
2061 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
2062 return StringValue("");
2063 }
2064 if (ranges->type != VAL_STRING) {
2065 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
2066 return StringValue("");
2067 }
Tao Bao67983152017-11-04 00:08:08 -07002068 RangeSet rs = RangeSet::Parse(ranges->data);
2069 if (!rs) {
2070 ErrorAbort(state, kArgsParsingFailure, "failed to parse ranges: %s", ranges->data.c_str());
2071 return StringValue("");
2072 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002073
2074 // Output notice to log when recover is attempted
2075 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
2076
2077 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
2078 fec::io fh(filename->data, O_RDWR);
2079
2080 if (!fh) {
2081 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
2082 strerror(errno));
2083 return StringValue("");
2084 }
2085
2086 if (!fh.has_ecc() || !fh.has_verity()) {
2087 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
2088 return StringValue("");
2089 }
2090
2091 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07002092 if (!fh.get_status(status)) {
2093 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
2094 return StringValue("");
2095 }
2096
Tao Baoc97edcb2017-03-31 01:18:13 -07002097 uint8_t buffer[BLOCKSIZE];
Tao Bao67983152017-11-04 00:08:08 -07002098 for (const auto& range : rs) {
Tao Baobf5b77d2017-03-30 16:57:29 -07002099 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002100 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07002101 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002102 continue;
2103 }
2104
Tao Baobf5b77d2017-03-30 16:57:29 -07002105 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07002106 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
2107 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08002108 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07002109 }
2110
2111 // If we want to be able to recover from a situation where rewriting a corrected
2112 // block doesn't guarantee the same data will be returned when re-read later, we
2113 // can save a copy of corrected blocks to /cache. Note:
2114 //
2115 // 1. Maximum space required from /cache is the same as the maximum number of
2116 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
2117 // this would be ~16 MiB, for example.
2118 //
2119 // 2. To find out if this block was corrupted, call fec_get_status after each
2120 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08002121 }
Tao Baoc97edcb2017-03-31 01:18:13 -07002122 }
2123 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
2124 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01002125}
2126
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002127void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07002128 RegisterFunction("block_image_verify", BlockImageVerifyFn);
2129 RegisterFunction("block_image_update", BlockImageUpdateFn);
2130 RegisterFunction("block_image_recover", BlockImageRecoverFn);
2131 RegisterFunction("check_first_block", CheckFirstBlockFn);
2132 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07002133}