blob: a1a5773d4457462cc4935ff854cd2de8a2ad952c [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>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tao Bao039f2da2016-11-22 16:29:50 -080042#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/parseint.h>
44#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070045#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080046#include <applypatch/applypatch.h>
47#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070048#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070049#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070050
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070051#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070052#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070053#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080054#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070055#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070056#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070057
Sami Tolvanene82fa182015-06-10 15:58:12 +000058// Set this to 0 to interpret 'erase' transfers to mean do a
59// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
60// erase to mean fill the region with zeroes.
61#define DEBUG_ERASE 0
62
Tao Bao51412212016-12-28 14:44:05 -080063static constexpr size_t BLOCKSIZE = 4096;
64static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
65static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
66static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000067
Tao Bao0940fe12015-08-27 16:41:21 -070068struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080069 size_t count; // Limit is INT_MAX.
70 size_t size;
71 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000072
73 // Get the block number for the ith(starting from 0) block in the range set.
74 int get_block(size_t idx) const {
75 if (idx >= size) {
76 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
77 return -1;
78 }
79 for (size_t i = 0; i < pos.size(); i += 2) {
80 if (idx < pos[i + 1] - pos[i]) {
81 return pos[i] + idx;
82 }
83 idx -= (pos[i + 1] - pos[i]);
84 }
85 return -1;
86 }
Tao Bao0940fe12015-08-27 16:41:21 -070087};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070088
Tianjie Xu16255832016-04-30 11:49:59 -070089static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070090static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070091static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070092
Tao Baoc844c062016-12-28 15:15:55 -080093static RangeSet parse_range(const std::string& range_text) {
94 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010095
Tao Baoc844c062016-12-28 15:15:55 -080096 std::vector<std::string> pieces = android::base::Split(range_text, ",");
97 if (pieces.size() < 3) {
98 goto err;
99 }
100
101 size_t num;
102 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
103 goto err;
104 }
105
106 if (num == 0 || num % 2) {
107 goto err; // must be even
108 } else if (num != pieces.size() - 1) {
109 goto err;
110 }
111
112 rs.pos.resize(num);
113 rs.count = num / 2;
114 rs.size = 0;
115
116 for (size_t i = 0; i < num; i += 2) {
117 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
118 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100119 }
120
Tao Baoc844c062016-12-28 15:15:55 -0800121 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
122 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100123 }
124
Tao Baoc844c062016-12-28 15:15:55 -0800125 if (rs.pos[i] >= rs.pos[i + 1]) {
126 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700127 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100128
Tao Baoc844c062016-12-28 15:15:55 -0800129 size_t sz = rs.pos[i + 1] - rs.pos[i];
130 if (rs.size > SIZE_MAX - sz) {
131 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700132 }
133
Tao Baoc844c062016-12-28 15:15:55 -0800134 rs.size += sz;
135 }
136
137 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100138
139err:
Tao Baoc844c062016-12-28 15:15:55 -0800140 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800141 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700142}
143
Tao Baoe6aa3322015-08-05 15:20:27 -0700144static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800145 for (size_t i = 0; i < r1.count; ++i) {
146 size_t r1_0 = r1.pos[i * 2];
147 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000148
Tao Baoc844c062016-12-28 15:15:55 -0800149 for (size_t j = 0; j < r2.count; ++j) {
150 size_t r2_0 = r2.pos[j * 2];
151 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000152
Tao Baoc844c062016-12-28 15:15:55 -0800153 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
154 return true;
155 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000156 }
Tao Baoc844c062016-12-28 15:15:55 -0800157 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000158
Tao Baoc844c062016-12-28 15:15:55 -0800159 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000160}
161
162static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700163 size_t so_far = 0;
164 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800165 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700166 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700167 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800168 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000169 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700170 } else if (r == 0) {
171 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800172 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700173 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700174 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700175 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000177 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700178}
179
Tao Bao612336d2015-08-27 16:41:21 -0700180static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
181 return read_all(fd, buffer.data(), size);
182}
183
Sami Tolvanen90221202014-12-09 16:39:47 +0000184static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185 size_t written = 0;
186 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800187 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700188 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700189 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800190 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000191 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700193 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000195
Sami Tolvanen90221202014-12-09 16:39:47 +0000196 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197}
198
Tao Bao612336d2015-08-27 16:41:21 -0700199static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
200 return write_all(fd, buffer.data(), size);
201}
202
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700203static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
204 // Don't discard blocks unless the update is a retry run.
205 if (!is_retry) {
206 return true;
207 }
208
209 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
210 int status = ioctl(fd, BLKDISCARD, &args);
211 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800212 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700213 return false;
214 }
215 return true;
216}
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)
242 : fd_(fd), tgt_(tgt), next_range_(0), current_range_left_(0) {
243 CHECK_NE(tgt.count, static_cast<size_t>(0));
244 };
Tao Bao0940fe12015-08-27 16:41:21 -0700245
Tao Bao60a70af2017-03-26 14:03:52 -0700246 bool Finished() const {
247 return next_range_ == tgt_.count && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700248 }
249
Tao Bao60a70af2017-03-26 14:03:52 -0700250 size_t Write(const uint8_t* data, size_t size) {
251 if (Finished()) {
252 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
253 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700254 }
255
Tao Bao60a70af2017-03-26 14:03:52 -0700256 size_t written = 0;
257 while (size > 0) {
258 // Move to the next range as needed.
259 if (current_range_left_ == 0) {
260 if (next_range_ < tgt_.count) {
261 off64_t offset = static_cast<off64_t>(tgt_.pos[next_range_ * 2]) * BLOCKSIZE;
262 current_range_left_ =
263 (tgt_.pos[next_range_ * 2 + 1] - tgt_.pos[next_range_ * 2]) * BLOCKSIZE;
264 next_range_++;
265 if (!discard_blocks(fd_, offset, current_range_left_)) {
266 break;
267 }
Tao Baof7eb7602017-03-27 15:12:48 -0700268
Tao Bao60a70af2017-03-26 14:03:52 -0700269 if (!check_lseek(fd_, offset, SEEK_SET)) {
270 break;
271 }
272 } else {
273 // We can't write any more; return how many bytes have been written so far.
Tao Baof7eb7602017-03-27 15:12:48 -0700274 break;
275 }
Tao Bao60a70af2017-03-26 14:03:52 -0700276 }
Tao Baof7eb7602017-03-27 15:12:48 -0700277
Tao Bao60a70af2017-03-26 14:03:52 -0700278 size_t write_now = size;
279 if (current_range_left_ < write_now) {
280 write_now = current_range_left_;
281 }
Tao Baof7eb7602017-03-27 15:12:48 -0700282
Tao Bao60a70af2017-03-26 14:03:52 -0700283 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700284 break;
285 }
Tao Bao60a70af2017-03-26 14:03:52 -0700286
287 data += write_now;
288 size -= write_now;
289
290 current_range_left_ -= write_now;
291 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700292 }
Tao Bao60a70af2017-03-26 14:03:52 -0700293
294 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700295 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700296
Tao Bao60a70af2017-03-26 14:03:52 -0700297 private:
298 // The input data.
299 int fd_;
300 // The destination for the data.
301 const RangeSet& tgt_;
302 // The next range that we should write to.
303 size_t next_range_;
304 // The number of bytes to write before moving to the next range.
305 size_t current_range_left_;
306};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700307
Tao Bao60a70af2017-03-26 14:03:52 -0700308/**
309 * All of the data for all the 'new' transfers is contained in one file in the update package,
310 * concatenated together in the order in which transfers.list will need it. We want to stream it out
311 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
312 * section until it's that transfer's turn to go.
313 *
314 * To achieve this, we expand the new data from the archive in a background thread, and block that
315 * threads 'receive uncompressed data' function until the main thread has reached a point where we
316 * want some new data to be written. We signal the background thread with the destination for the
317 * data and block the main thread, waiting for the background thread to complete writing that
318 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
319 * transfer.
320 *
321 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
322 * the main thread wants some data written, it sets writer to the destination location and signals
323 * the condition. When the background thread is done writing, it clears writer and signals the
324 * condition again.
325 */
Tao Bao0940fe12015-08-27 16:41:21 -0700326struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700327 ZipArchiveHandle za;
328 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700329
Tao Bao60a70af2017-03-26 14:03:52 -0700330 RangeSinkWriter* writer;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700331
Tao Bao60a70af2017-03-26 14:03:52 -0700332 pthread_mutex_t mu;
333 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700334};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700335
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700336static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700337 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700338
Tao Bao60a70af2017-03-26 14:03:52 -0700339 while (size > 0) {
340 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
341 pthread_mutex_lock(&nti->mu);
342 while (nti->writer == nullptr) {
343 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700344 }
Tao Bao60a70af2017-03-26 14:03:52 -0700345 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700346
Tao Bao60a70af2017-03-26 14:03:52 -0700347 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
348 // disappear from nti.
349 size_t written = nti->writer->Write(data, size);
350 data += written;
351 size -= written;
352
353 if (nti->writer->Finished()) {
354 // We have written all the bytes desired by this writer.
355
356 pthread_mutex_lock(&nti->mu);
357 nti->writer = nullptr;
358 pthread_cond_broadcast(&nti->cv);
359 pthread_mutex_unlock(&nti->mu);
360 }
361 }
362
363 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700364}
365
366static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100367 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700368 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700369 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700370}
371
Tao Bao612336d2015-08-27 16:41:21 -0700372static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000373 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700374 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000375
Tao Bao0940fe12015-08-27 16:41:21 -0700376 for (size_t i = 0; i < src.count; ++i) {
377 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000378 return -1;
379 }
380
Tao Bao0940fe12015-08-27 16:41:21 -0700381 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000382
Tao Bao612336d2015-08-27 16:41:21 -0700383 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000384 return -1;
385 }
386
387 p += size;
388 }
389
390 return 0;
391}
392
Tao Bao612336d2015-08-27 16:41:21 -0700393static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700394 size_t written = 0;
395 for (size_t i = 0; i < tgt.count; ++i) {
396 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
397 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
398 if (!discard_blocks(fd, offset, size)) {
399 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000400 }
401
Tao Bao60a70af2017-03-26 14:03:52 -0700402 if (!check_lseek(fd, offset, SEEK_SET)) {
403 return -1;
404 }
405
406 if (write_all(fd, buffer.data() + written, size) == -1) {
407 return -1;
408 }
409
410 written += size;
411 }
412
413 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000414}
415
Tao Baobaad2d42015-12-06 16:56:27 -0800416// Parameters for transfer list command functions
417struct CommandParameters {
418 std::vector<std::string> tokens;
419 size_t cpos;
420 const char* cmdname;
421 const char* cmdline;
422 std::string freestash;
423 std::string stashbase;
424 bool canwrite;
425 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700426 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800427 bool foundwrites;
428 bool isunresumable;
429 int version;
430 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700431 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800432 NewThreadInfo nti;
433 pthread_t thread;
434 std::vector<uint8_t> buffer;
435 uint8_t* patch_start;
436};
437
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000438// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
439// handled separately).
440static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
441 const std::vector<uint8_t>& buffer) {
442 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000443 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
444 params.tokens[0] == "imgdiff");
445
446 size_t pos = 0;
447 // Command example:
448 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
449 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
450 // [<loc_range> <stashed_blocks>]
451 if (params.tokens[0] == "move") {
452 // src_range for move starts at the 4th position.
453 if (params.tokens.size() < 5) {
454 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
455 return;
456 }
457 pos = 4;
458 } else {
459 // src_range for diff starts at the 7th position.
460 if (params.tokens.size() < 8) {
461 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
462 return;
463 }
464 pos = 7;
465 }
466
467 // Source blocks in stash only, no work to do.
468 if (params.tokens[pos] == "-") {
469 return;
470 }
471
472 RangeSet src = parse_range(params.tokens[pos++]);
473
474 RangeSet locs;
475 // If there's no stashed blocks, content in the buffer is consecutive and has the same
476 // order as the source blocks.
477 if (pos == params.tokens.size()) {
478 locs.count = 1;
479 locs.size = src.size;
480 locs.pos = { 0, src.size };
481 } else {
482 // Otherwise, the next token is the offset of the source blocks in the target range.
483 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
484 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
485 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
486 locs = parse_range(params.tokens[pos++]);
487 CHECK_EQ(src.size, locs.size);
488 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
489 }
490
491 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
492 for (size_t i = 0; i < src.size; i++) {
493 int block_num = src.get_block(i);
494 CHECK_NE(block_num, -1);
495 int buffer_index = locs.get_block(i);
496 CHECK_NE(buffer_index, -1);
497 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
498
499 uint8_t digest[SHA_DIGEST_LENGTH];
500 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
501 std::string hexdigest = print_sha1(digest);
502 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
503 }
504}
505
506// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
507// in hex for each block.
508static void PrintHashForCorruptedStashedBlocks(const std::string& id,
509 const std::vector<uint8_t>& buffer,
510 const RangeSet& src) {
511 LOG(INFO) << "printing hash in hex for stash_id: " << id;
512 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
513
514 for (size_t i = 0; i < src.size; i++) {
515 int block_num = src.get_block(i);
516 CHECK_NE(block_num, -1);
517
518 uint8_t digest[SHA_DIGEST_LENGTH];
519 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
520 std::string hexdigest = print_sha1(digest);
521 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
522 }
523}
524
525// If the stash file doesn't exist, read the source blocks this stash contains and print the
526// SHA-1 for these blocks.
527static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
528 if (stash_map.find(id) == stash_map.end()) {
529 LOG(ERROR) << "No stash saved for id: " << id;
530 return;
531 }
532
533 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
534 const RangeSet& src = stash_map[id];
535 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
536 if (ReadBlocks(src, buffer, fd) == -1) {
537 LOG(ERROR) << "failed to read source blocks for stash: " << id;
538 return;
539 }
540 PrintHashForCorruptedStashedBlocks(id, buffer, src);
541}
542
Tao Bao612336d2015-08-27 16:41:21 -0700543static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700544 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800545 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700546 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000547
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800548 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000549
Tao Baoe6aa3322015-08-05 15:20:27 -0700550 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000551
Tao Bao0940fe12015-08-27 16:41:21 -0700552 if (hexdigest != expected) {
553 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800554 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
555 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700556 }
557 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000558 }
559
Tao Bao0940fe12015-08-27 16:41:21 -0700560 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000561}
562
Tao Bao0940fe12015-08-27 16:41:21 -0700563static std::string GetStashFileName(const std::string& base, const std::string& id,
564 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700565 if (base.empty()) {
566 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000567 }
568
Tao Baoe6aa3322015-08-05 15:20:27 -0700569 std::string fn(STASH_DIRECTORY_BASE);
570 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000571
572 return fn;
573}
574
Tao Baoec8272f2017-03-15 17:39:01 -0700575// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
576// directory and continues despite of errors. Calls the 'callback' function for each file.
577static void EnumerateStash(const std::string& dirname,
578 const std::function<void(const std::string&)>& callback) {
579 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000580
Tao Baoec8272f2017-03-15 17:39:01 -0700581 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000582
Tao Baoec8272f2017-03-15 17:39:01 -0700583 if (directory == nullptr) {
584 if (errno != ENOENT) {
585 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000586 }
Tao Bao51412212016-12-28 14:44:05 -0800587 return;
588 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700589
Tao Baoec8272f2017-03-15 17:39:01 -0700590 dirent* item;
591 while ((item = readdir(directory.get())) != nullptr) {
592 if (item->d_type != DT_REG) continue;
593 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800594 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000595}
596
597// Deletes the stash directory and all files in it. Assumes that it only
598// contains files. There is nothing we can do about unlikely, but possible
599// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700600static void DeleteFile(const std::string& fn) {
601 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000602
Tao Baoec8272f2017-03-15 17:39:01 -0700603 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000604
Tao Baoec8272f2017-03-15 17:39:01 -0700605 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
606 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
607 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000608}
609
Tao Baoe6aa3322015-08-05 15:20:27 -0700610static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700611 if (base.empty()) return;
612
613 LOG(INFO) << "deleting stash " << base;
614
615 std::string dirname = GetStashFileName(base, "", "");
616 EnumerateStash(dirname, DeleteFile);
617
618 if (rmdir(dirname.c_str()) == -1) {
619 if (errno != ENOENT && errno != ENOTDIR) {
620 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000621 }
Tao Baoec8272f2017-03-15 17:39:01 -0700622 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000623}
624
Tao Baobcf46492017-03-23 15:28:20 -0700625static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
626 std::vector<uint8_t>& buffer, bool printnoent) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700627 // In verify mode, if source range_set was saved for the given hash,
628 // check contents in the source blocks first. If the check fails,
629 // search for the stashed files on /cache as usual.
630 if (!params.canwrite) {
631 if (stash_map.find(id) != stash_map.end()) {
632 const RangeSet& src = stash_map[id];
633 allocate(src.size * BLOCKSIZE, buffer);
634
635 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800636 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700637 return -1;
638 }
639 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800640 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000641 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700642 return -1;
643 }
644 return 0;
645 }
646 }
647
Tao Bao0940fe12015-08-27 16:41:21 -0700648 size_t blockcount = 0;
649
Sami Tolvanen90221202014-12-09 16:39:47 +0000650 if (!blocks) {
651 blocks = &blockcount;
652 }
653
Tao Baobcf46492017-03-23 15:28:20 -0700654 std::string fn = GetStashFileName(params.stashbase, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000655
Tao Bao0940fe12015-08-27 16:41:21 -0700656 struct stat sb;
657 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000658
659 if (res == -1) {
660 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800661 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000662 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000663 }
Tao Bao0940fe12015-08-27 16:41:21 -0700664 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000665 }
666
Tao Bao039f2da2016-11-22 16:29:50 -0800667 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000668
Tao Bao0940fe12015-08-27 16:41:21 -0700669 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800670 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672 }
673
Elliott Hughesbcabd092016-03-22 20:19:22 -0700674 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000675 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800676 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700677 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000678 }
679
Tao Bao612336d2015-08-27 16:41:21 -0700680 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000681
Tao Bao612336d2015-08-27 16:41:21 -0700682 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700683 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000684 }
685
Tao Bao0940fe12015-08-27 16:41:21 -0700686 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000687
Tao Bao612336d2015-08-27 16:41:21 -0700688 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800689 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000690 if (stash_map.find(id) == stash_map.end()) {
691 LOG(ERROR) << "failed to find source blocks number for stash " << id
692 << " when executing command: " << params.cmdname;
693 } else {
694 const RangeSet& src = stash_map[id];
695 PrintHashForCorruptedStashedBlocks(id, buffer, src);
696 }
Tao Baoec8272f2017-03-15 17:39:01 -0700697 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700698 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000699 }
700
Tao Bao0940fe12015-08-27 16:41:21 -0700701 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000702}
703
Tao Bao612336d2015-08-27 16:41:21 -0700704static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700705 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700706 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700707 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000708 }
709
710 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800711 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700712 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000713 }
714
Tao Bao0940fe12015-08-27 16:41:21 -0700715 std::string fn = GetStashFileName(base, id, ".partial");
716 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000717
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100718 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700719 struct stat sb;
720 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100721
722 if (res == 0) {
723 // The file already exists and since the name is the hash of the contents,
724 // it's safe to assume the contents are identical (accidental hash collisions
725 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800726 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700727 *exists = true;
728 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100729 }
730
Tao Bao0940fe12015-08-27 16:41:21 -0700731 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100732 }
733
Tao Bao039f2da2016-11-22 16:29:50 -0800734 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000735
Tao Bao039f2da2016-11-22 16:29:50 -0800736 android::base::unique_fd fd(
737 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000738 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800739 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700740 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 }
742
Tianjie Xua946b9e2017-03-21 16:24:57 -0700743 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
744 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
745 return -1;
746 }
747
Sami Tolvanen90221202014-12-09 16:39:47 +0000748 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700749 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 }
751
Jed Estepa7b9a462015-12-15 16:04:53 -0800752 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700753 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800754 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700755 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000756 }
757
Tao Baoe6aa3322015-08-05 15:20:27 -0700758 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800759 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700760 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000761 }
762
Tao Bao0940fe12015-08-27 16:41:21 -0700763 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700764 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
765 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700766 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700767 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800768 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700769 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700770 }
771
Jed Estepa7b9a462015-12-15 16:04:53 -0800772 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700773 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800774 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700775 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700776 }
777
Tao Bao0940fe12015-08-27 16:41:21 -0700778 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000779}
780
781// Creates a directory for storing stash files and checks if the /cache partition
782// hash enough space for the expected amount of blocks we need to store. Returns
783// >0 if we created the directory, zero if it existed already, and <0 of failure.
784
Tao Bao51412212016-12-28 14:44:05 -0800785static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
786 std::string& base) {
787 if (blockdev.empty()) {
788 return -1;
789 }
790
791 // Stash directory should be different for each partition to avoid conflicts
792 // when updating multiple partitions at the same time, so we use the hash of
793 // the block device name as the base directory
794 uint8_t digest[SHA_DIGEST_LENGTH];
795 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
796 base = print_sha1(digest);
797
798 std::string dirname = GetStashFileName(base, "", "");
799 struct stat sb;
800 int res = stat(dirname.c_str(), &sb);
801 size_t max_stash_size = maxblocks * BLOCKSIZE;
802
803 if (res == -1 && errno != ENOENT) {
804 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
805 strerror(errno));
806 return -1;
807 } else if (res != 0) {
808 LOG(INFO) << "creating stash " << dirname;
809 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
810
811 if (res != 0) {
812 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
813 strerror(errno));
814 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000815 }
816
Tianjie Xua946b9e2017-03-21 16:24:57 -0700817 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
818 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
819 strerror(errno));
820 return -1;
821 }
822
Tao Bao51412212016-12-28 14:44:05 -0800823 if (CacheSizeCheck(max_stash_size) != 0) {
824 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
825 max_stash_size);
826 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000827 }
828
Tao Bao51412212016-12-28 14:44:05 -0800829 return 1; // Created directory
830 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000831
Tao Bao51412212016-12-28 14:44:05 -0800832 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000833
Tao Baoec8272f2017-03-15 17:39:01 -0700834 // If the directory already exists, calculate the space already allocated to stash files and check
835 // if there's enough for all required blocks. Delete any partially completed stash files first.
836 EnumerateStash(dirname, [](const std::string& fn) {
837 if (android::base::EndsWith(fn, ".partial")) {
838 DeleteFile(fn);
839 }
840 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000841
Tao Bao51412212016-12-28 14:44:05 -0800842 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700843 EnumerateStash(dirname, [&existing](const std::string& fn) {
844 if (fn.empty()) return;
845 struct stat sb;
846 if (stat(fn.c_str(), &sb) == -1) {
847 PLOG(ERROR) << "stat \"" << fn << "\" failed";
848 return;
849 }
850 existing += static_cast<size_t>(sb.st_size);
851 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000852
Tao Bao51412212016-12-28 14:44:05 -0800853 if (max_stash_size > existing) {
854 size_t needed = max_stash_size - existing;
855 if (CacheSizeCheck(needed) != 0) {
856 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
857 needed);
858 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000859 }
Tao Bao51412212016-12-28 14:44:05 -0800860 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000861
Tao Bao51412212016-12-28 14:44:05 -0800862 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000863}
864
Tao Baobaad2d42015-12-06 16:56:27 -0800865static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700866 if (base.empty() || id.empty()) {
867 return -1;
868 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000869
Tao Baoec8272f2017-03-15 17:39:01 -0700870 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000871
Tao Baoec8272f2017-03-15 17:39:01 -0700872 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700873}
874
Tao Bao612336d2015-08-27 16:41:21 -0700875static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
876 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700877 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700878 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700879 // may be the same buffer.
880
Tao Bao612336d2015-08-27 16:41:21 -0700881 const uint8_t* from = source.data();
882 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700883 size_t start = locs.size;
884 for (int i = locs.count-1; i >= 0; --i) {
885 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700886 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700887 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700888 blocks * BLOCKSIZE);
889 }
890}
891
Tao Baod2aecd42017-03-23 14:43:44 -0700892/**
893 * We expect to parse the remainder of the parameter tokens as one of:
894 *
895 * <src_block_count> <src_range>
896 * (loads data from source image only)
897 *
898 * <src_block_count> - <[stash_id:stash_range] ...>
899 * (loads data from stashes only)
900 *
901 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
902 * (loads data from both source image and stashes)
903 *
904 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
905 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
906 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
907 * LoadStash.
908 */
909static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
910 bool* overlap) {
911 CHECK(src_blocks != nullptr);
912 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700913
Tao Baod2aecd42017-03-23 14:43:44 -0700914 // <src_block_count>
915 const std::string& token = params.tokens[params.cpos++];
916 if (!android::base::ParseUint(token, src_blocks)) {
917 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
918 return -1;
919 }
Tao Baobaad2d42015-12-06 16:56:27 -0800920
Tao Baod2aecd42017-03-23 14:43:44 -0700921 allocate(*src_blocks * BLOCKSIZE, params.buffer);
922
923 // "-" or <src_range> [<src_loc>]
924 if (params.tokens[params.cpos] == "-") {
925 // no source ranges, only stashes
926 params.cpos++;
927 } else {
928 RangeSet src = parse_range(params.tokens[params.cpos++]);
929 *overlap = range_overlaps(src, tgt);
930
931 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
932 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800933 }
934
Tao Baod2aecd42017-03-23 14:43:44 -0700935 if (params.cpos >= params.tokens.size()) {
936 // no stashes, only source range
937 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800938 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700939
Tao Baod2aecd42017-03-23 14:43:44 -0700940 RangeSet locs = parse_range(params.tokens[params.cpos++]);
941 MoveRange(params.buffer, locs, params.buffer);
942 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700943
Tao Baod2aecd42017-03-23 14:43:44 -0700944 // <[stash_id:stash_range]>
945 while (params.cpos < params.tokens.size()) {
946 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
947 // in the source block that stashed data should go.
948 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
949 if (tokens.size() != 2) {
950 LOG(ERROR) << "invalid parameter";
951 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700952 }
953
Tao Baod2aecd42017-03-23 14:43:44 -0700954 std::vector<uint8_t> stash;
955 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
956 // These source blocks will fail verification if used later, but we
957 // will let the caller decide if this is a fatal failure
958 LOG(ERROR) << "failed to load stash " << tokens[0];
959 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000960 }
961
Tao Baod2aecd42017-03-23 14:43:44 -0700962 RangeSet locs = parse_range(tokens[1]);
963 MoveRange(params.buffer, locs, stash);
964 }
965
966 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000967}
968
Tao Bao33567772017-03-13 14:57:34 -0700969/**
970 * Do a source/target load for move/bsdiff/imgdiff in version 3.
971 *
972 * We expect to parse the remainder of the parameter tokens as one of:
973 *
974 * <tgt_range> <src_block_count> <src_range>
975 * (loads data from source image only)
976 *
977 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
978 * (loads data from stashes only)
979 *
980 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
981 * (loads data from both source image and stashes)
982 *
Tao Baod2aecd42017-03-23 14:43:44 -0700983 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
984 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700985 * verification fails in a way that the update cannot be resumed anymore.
986 *
987 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
988 * the return value is -1 and the command should be aborted.
989 *
990 * If the return value is 1, the command has already been completed according to the contents of the
991 * target blocks, and should not be performed again.
992 *
993 * If the return value is 0, source blocks have expected content and the command can be performed.
994 */
Tao Baod2aecd42017-03-23 14:43:44 -0700995static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
996 bool onehash, bool* overlap) {
997 CHECK(src_blocks != nullptr);
998 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000999
Tao Baod2aecd42017-03-23 14:43:44 -07001000 if (params.cpos >= params.tokens.size()) {
1001 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001002 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001003 }
1004
1005 std::string srchash = params.tokens[params.cpos++];
1006 std::string tgthash;
1007
1008 if (onehash) {
1009 tgthash = srchash;
1010 } else {
1011 if (params.cpos >= params.tokens.size()) {
1012 LOG(ERROR) << "missing target hash";
1013 return -1;
1014 }
1015 tgthash = params.tokens[params.cpos++];
1016 }
1017
1018 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1019 // "-"/<src_range>.
1020 if (params.cpos + 2 >= params.tokens.size()) {
1021 LOG(ERROR) << "invalid parameters";
1022 return -1;
1023 }
1024
1025 // <tgt_range>
1026 tgt = parse_range(params.tokens[params.cpos++]);
1027
1028 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
1029 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1030 return -1;
1031 }
1032
1033 // Return now if target blocks already have expected content.
1034 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
1035 return 1;
1036 }
1037
1038 // Load source blocks.
1039 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1040 return -1;
1041 }
1042
1043 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1044 // If source and target blocks overlap, stash the source blocks so we can
1045 // resume from possible write errors. In verify mode, we can skip stashing
1046 // because the source blocks won't be overwritten.
1047 if (*overlap && params.canwrite) {
1048 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1049
1050 bool stash_exists = false;
1051 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1052 &stash_exists) != 0) {
1053 LOG(ERROR) << "failed to stash overlapping source blocks";
1054 return -1;
1055 }
1056
1057 params.stashed += *src_blocks;
1058 // Can be deleted when the write has completed.
1059 if (!stash_exists) {
1060 params.freestash = srchash;
1061 }
1062 }
1063
1064 // Source blocks have expected content, command can proceed.
1065 return 0;
1066 }
1067
1068 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1069 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1070 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1071 // command.
1072 return 0;
1073 }
1074
1075 // Valid source data not available, update cannot be resumed.
1076 LOG(ERROR) << "partition has unexpected contents";
1077 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1078
1079 params.isunresumable = true;
1080
1081 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001082}
1083
Tao Bao0940fe12015-08-27 16:41:21 -07001084static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001085 size_t blocks = 0;
1086 bool overlap = false;
1087 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001088 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001089
Tao Bao33567772017-03-13 14:57:34 -07001090 if (status == -1) {
1091 LOG(ERROR) << "failed to read blocks for move";
1092 return -1;
1093 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001094
Tao Bao33567772017-03-13 14:57:34 -07001095 if (status == 0) {
1096 params.foundwrites = true;
1097 } else if (params.foundwrites) {
1098 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1099 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001100
Tao Bao33567772017-03-13 14:57:34 -07001101 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001102 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001103 LOG(INFO) << " moving " << blocks << " blocks";
1104
1105 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1106 return -1;
1107 }
1108 } else {
1109 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001110 }
Tao Bao33567772017-03-13 14:57:34 -07001111 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Bao33567772017-03-13 14:57:34 -07001113 if (!params.freestash.empty()) {
1114 FreeStash(params.stashbase, params.freestash);
1115 params.freestash.clear();
1116 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001117
Tao Bao33567772017-03-13 14:57:34 -07001118 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001119
Tao Bao33567772017-03-13 14:57:34 -07001120 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001121}
1122
Tao Bao0940fe12015-08-27 16:41:21 -07001123static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001124 // <stash_id> <src_range>
1125 if (params.cpos + 1 >= params.tokens.size()) {
1126 LOG(ERROR) << "missing id and/or src range fields in stash command";
1127 return -1;
1128 }
1129
1130 const std::string& id = params.tokens[params.cpos++];
1131 size_t blocks = 0;
1132 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1133 // Stash file already exists and has expected contents. Do not read from source again, as the
1134 // source may have been already overwritten during a previous attempt.
1135 return 0;
1136 }
1137
1138 RangeSet src = parse_range(params.tokens[params.cpos++]);
1139
1140 allocate(src.size * BLOCKSIZE, params.buffer);
1141 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1142 return -1;
1143 }
1144 blocks = src.size;
1145 stash_map[id] = src;
1146
1147 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1148 // Source blocks have unexpected contents. If we actually need this data later, this is an
1149 // unrecoverable error. However, the command that uses the data may have already completed
1150 // previously, so the possible failure will occur during source block verification.
1151 LOG(ERROR) << "failed to load source blocks for stash " << id;
1152 return 0;
1153 }
1154
1155 // In verify mode, we don't need to stash any blocks.
1156 if (!params.canwrite) {
1157 return 0;
1158 }
1159
1160 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1161 params.stashed += blocks;
1162 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001163}
1164
Tao Bao0940fe12015-08-27 16:41:21 -07001165static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001166 // <stash_id>
1167 if (params.cpos >= params.tokens.size()) {
1168 LOG(ERROR) << "missing stash id in free command";
1169 return -1;
1170 }
Tao Baobaad2d42015-12-06 16:56:27 -08001171
Tao Baobcf46492017-03-23 15:28:20 -07001172 const std::string& id = params.tokens[params.cpos++];
1173 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001174
Tao Baobcf46492017-03-23 15:28:20 -07001175 if (params.createdstash || params.canwrite) {
1176 return FreeStash(params.stashbase, id);
1177 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001178
Tao Baobcf46492017-03-23 15:28:20 -07001179 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001180}
1181
Tao Bao0940fe12015-08-27 16:41:21 -07001182static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001183
Tao Baobaad2d42015-12-06 16:56:27 -08001184 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001185 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001186 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001187 }
1188
Tao Baoc844c062016-12-28 15:15:55 -08001189 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001190
Tao Bao039f2da2016-11-22 16:29:50 -08001191 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001192
Tao Bao612336d2015-08-27 16:41:21 -07001193 allocate(BLOCKSIZE, params.buffer);
1194 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001195
Tao Bao0940fe12015-08-27 16:41:21 -07001196 if (params.canwrite) {
1197 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001198 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1199 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1200 if (!discard_blocks(params.fd, offset, size)) {
1201 return -1;
1202 }
1203
1204 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001205 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001206 }
1207
Tao Bao0940fe12015-08-27 16:41:21 -07001208 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1209 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1210 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001211 }
1212 }
1213 }
1214 }
1215
Tao Bao0940fe12015-08-27 16:41:21 -07001216 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001217 // Update only for the zero command, as the erase command will call
1218 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001219 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001220 }
1221
Tao Bao0940fe12015-08-27 16:41:21 -07001222 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001223}
1224
Tao Bao0940fe12015-08-27 16:41:21 -07001225static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001226 if (params.cpos >= params.tokens.size()) {
1227 LOG(ERROR) << "missing target blocks for new";
1228 return -1;
1229 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001230
Tao Bao60a70af2017-03-26 14:03:52 -07001231 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
1232
1233 if (params.canwrite) {
1234 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
1235
1236 RangeSinkWriter writer(params.fd, tgt);
1237 pthread_mutex_lock(&params.nti.mu);
1238 params.nti.writer = &writer;
1239 pthread_cond_broadcast(&params.nti.cv);
1240
1241 while (params.nti.writer != nullptr) {
1242 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001243 }
1244
Tao Bao60a70af2017-03-26 14:03:52 -07001245 pthread_mutex_unlock(&params.nti.mu);
1246 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001247
Tao Bao60a70af2017-03-26 14:03:52 -07001248 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001249
Tao Bao60a70af2017-03-26 14:03:52 -07001250 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251}
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001254 // <offset> <length>
1255 if (params.cpos + 1 >= params.tokens.size()) {
1256 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1257 return -1;
1258 }
Tao Bao0940fe12015-08-27 16:41:21 -07001259
Tao Baoc0e1c462017-02-01 10:20:10 -08001260 size_t offset;
1261 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1262 LOG(ERROR) << "invalid patch offset";
1263 return -1;
1264 }
Tao Bao0940fe12015-08-27 16:41:21 -07001265
Tao Baoc0e1c462017-02-01 10:20:10 -08001266 size_t len;
1267 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1268 LOG(ERROR) << "invalid patch len";
1269 return -1;
1270 }
Tao Bao0940fe12015-08-27 16:41:21 -07001271
Tao Baoc0e1c462017-02-01 10:20:10 -08001272 RangeSet tgt;
1273 size_t blocks = 0;
1274 bool overlap = false;
1275 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001276
Tao Baoc0e1c462017-02-01 10:20:10 -08001277 if (status == -1) {
1278 LOG(ERROR) << "failed to read blocks for diff";
1279 return -1;
1280 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001281
Tao Baoc0e1c462017-02-01 10:20:10 -08001282 if (status == 0) {
1283 params.foundwrites = true;
1284 } else if (params.foundwrites) {
1285 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1286 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001287
Tao Baoc0e1c462017-02-01 10:20:10 -08001288 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001289 if (status == 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001290 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
1291 Value patch_value(
1292 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001293
Tao Bao60a70af2017-03-26 14:03:52 -07001294 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001295 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao60a70af2017-03-26 14:03:52 -07001296 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1297 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1298 std::placeholders::_2),
1299 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001300 LOG(ERROR) << "Failed to apply image patch.";
1301 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001302 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001303 } else {
Tao Bao60a70af2017-03-26 14:03:52 -07001304 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1305 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1306 std::placeholders::_2),
1307 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001308 LOG(ERROR) << "Failed to apply bsdiff patch.";
1309 return -1;
1310 }
1311 }
1312
1313 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001314 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001315 LOG(ERROR) << "range sink underrun?";
1316 }
1317 } else {
1318 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size << " ["
1319 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001320 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001321 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001322
Tao Baoc0e1c462017-02-01 10:20:10 -08001323 if (!params.freestash.empty()) {
1324 FreeStash(params.stashbase, params.freestash);
1325 params.freestash.clear();
1326 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001327
Tao Baoc0e1c462017-02-01 10:20:10 -08001328 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001329
Tao Baoc0e1c462017-02-01 10:20:10 -08001330 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001331}
1332
Tao Bao0940fe12015-08-27 16:41:21 -07001333static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001334 if (DEBUG_ERASE) {
1335 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001336 }
1337
Tao Bao0940fe12015-08-27 16:41:21 -07001338 struct stat sb;
1339 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001340 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001341 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001342 }
1343
Tao Bao0940fe12015-08-27 16:41:21 -07001344 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001345 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001346 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001347 }
1348
Tao Baobaad2d42015-12-06 16:56:27 -08001349 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001350 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001351 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001352 }
1353
Tao Baoc844c062016-12-28 15:15:55 -08001354 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001355
Tao Bao0940fe12015-08-27 16:41:21 -07001356 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001357 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001358
Tao Bao0940fe12015-08-27 16:41:21 -07001359 for (size_t i = 0; i < tgt.count; ++i) {
1360 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001361 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001362 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001363 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001364 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001365
Tao Bao0940fe12015-08-27 16:41:21 -07001366 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001367 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001368 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001369 }
1370 }
1371 }
1372
Tao Bao0940fe12015-08-27 16:41:21 -07001373 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001374}
1375
1376// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001377typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001378
Tao Bao612336d2015-08-27 16:41:21 -07001379struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001380 const char* name;
1381 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001382};
Sami Tolvanen90221202014-12-09 16:39:47 +00001383
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001384// args:
1385// - block device (or file) to modify in-place
1386// - transfer list (blob)
1387// - new data stream (filename within package.zip)
1388// - patch stream (filename within package.zip, must be uncompressed)
1389
Tianjie Xuc4447322017-03-06 14:44:59 -08001390static Value* PerformBlockImageUpdate(const char* name, State* state,
1391 const std::vector<std::unique_ptr<Expr>>& argv,
1392 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001393 CommandParameters params = {};
1394 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001395
Tao Bao33567772017-03-13 14:57:34 -07001396 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1397 if (state->is_retry) {
1398 is_retry = true;
1399 LOG(INFO) << "This update is a retry.";
1400 }
1401 if (argv.size() != 4) {
1402 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1403 argv.size());
1404 return StringValue("");
1405 }
1406
1407 std::vector<std::unique_ptr<Value>> args;
1408 if (!ReadValueArgs(state, argv, &args)) {
1409 return nullptr;
1410 }
1411
1412 const Value* blockdev_filename = args[0].get();
1413 const Value* transfer_list_value = args[1].get();
1414 const Value* new_data_fn = args[2].get();
1415 const Value* patch_data_fn = args[3].get();
1416
1417 if (blockdev_filename->type != VAL_STRING) {
1418 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1419 return StringValue("");
1420 }
1421 if (transfer_list_value->type != VAL_BLOB) {
1422 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1423 return StringValue("");
1424 }
1425 if (new_data_fn->type != VAL_STRING) {
1426 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1427 return StringValue("");
1428 }
1429 if (patch_data_fn->type != VAL_STRING) {
1430 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1431 return StringValue("");
1432 }
1433
1434 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1435 if (ui == nullptr) {
1436 return StringValue("");
1437 }
1438
1439 FILE* cmd_pipe = ui->cmd_pipe;
1440 ZipArchiveHandle za = ui->package_zip;
1441
1442 if (cmd_pipe == nullptr || za == nullptr) {
1443 return StringValue("");
1444 }
1445
1446 ZipString path_data(patch_data_fn->data.c_str());
1447 ZipEntry patch_entry;
1448 if (FindEntry(za, path_data, &patch_entry) != 0) {
1449 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1450 return StringValue("");
1451 }
1452
1453 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1454 ZipString new_data(new_data_fn->data.c_str());
1455 ZipEntry new_entry;
1456 if (FindEntry(za, new_data, &new_entry) != 0) {
1457 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1458 return StringValue("");
1459 }
1460
1461 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1462 if (params.fd == -1) {
1463 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1464 return StringValue("");
1465 }
1466
1467 if (params.canwrite) {
1468 params.nti.za = za;
1469 params.nti.entry = new_entry;
1470
1471 pthread_mutex_init(&params.nti.mu, nullptr);
1472 pthread_cond_init(&params.nti.cv, nullptr);
1473 pthread_attr_t attr;
1474 pthread_attr_init(&attr);
1475 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1476
1477 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1478 if (error != 0) {
1479 PLOG(ERROR) << "pthread_create failed";
1480 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001481 }
Tao Bao33567772017-03-13 14:57:34 -07001482 }
1483
1484 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1485 if (lines.size() < 2) {
1486 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1487 lines.size());
1488 return StringValue("");
1489 }
1490
1491 // First line in transfer list is the version number.
1492 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1493 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1494 return StringValue("");
1495 }
1496
1497 LOG(INFO) << "blockimg version is " << params.version;
1498
1499 // Second line in transfer list is the total number of blocks we expect to write.
1500 size_t total_blocks;
1501 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1502 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1503 return StringValue("");
1504 }
1505
1506 if (total_blocks == 0) {
1507 return StringValue("t");
1508 }
1509
1510 size_t start = 2;
1511 if (lines.size() < 4) {
1512 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1513 lines.size());
1514 return StringValue("");
1515 }
1516
1517 // Third line is how many stash entries are needed simultaneously.
1518 LOG(INFO) << "maximum stash entries " << lines[2];
1519
1520 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1521 size_t stash_max_blocks;
1522 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1523 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1524 lines[3].c_str());
1525 return StringValue("");
1526 }
1527
1528 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1529 if (res == -1) {
1530 return StringValue("");
1531 }
1532
1533 params.createdstash = res;
1534
1535 start += 2;
1536
1537 // Build a map of the available commands
1538 std::unordered_map<std::string, const Command*> cmd_map;
1539 for (size_t i = 0; i < cmdcount; ++i) {
1540 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1541 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1542 return StringValue(strdup(""));
1543 }
1544 cmd_map[commands[i].name] = &commands[i];
1545 }
1546
1547 int rc = -1;
1548
1549 // Subsequent lines are all individual transfer commands
1550 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1551 const std::string& line(*it);
1552 if (line.empty()) continue;
1553
1554 params.tokens = android::base::Split(line, " ");
1555 params.cpos = 0;
1556 params.cmdname = params.tokens[params.cpos++].c_str();
1557 params.cmdline = line.c_str();
1558
1559 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1560 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1561 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001562 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001563
Tao Bao33567772017-03-13 14:57:34 -07001564 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001565
Tao Bao33567772017-03-13 14:57:34 -07001566 if (cmd->f != nullptr && cmd->f(params) == -1) {
1567 LOG(ERROR) << "failed to execute command [" << line << "]";
1568 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001569 }
1570
Sami Tolvanen90221202014-12-09 16:39:47 +00001571 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001572 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001573 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001574 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001575 goto pbiudone;
1576 }
1577 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1578 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001579 }
Tao Bao33567772017-03-13 14:57:34 -07001580 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001581
Tao Bao33567772017-03-13 14:57:34 -07001582 if (params.canwrite) {
1583 pthread_join(params.thread, nullptr);
1584
1585 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1586 LOG(INFO) << "stashed " << params.stashed << " blocks";
1587 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1588
1589 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1590 if (partition != nullptr && *(partition + 1) != 0) {
1591 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1592 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1593 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001594 }
Tao Bao33567772017-03-13 14:57:34 -07001595 // Delete stash only after successfully completing the update, as it may contain blocks needed
1596 // to complete the update later.
1597 DeleteStash(params.stashbase);
1598 } else {
1599 LOG(INFO) << "verified partition contents; update may be resumed";
1600 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001601
Tao Bao33567772017-03-13 14:57:34 -07001602 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001603
Tao Bao33567772017-03-13 14:57:34 -07001604pbiudone:
1605 if (ota_fsync(params.fd) == -1) {
1606 failure_type = kFsyncFailure;
1607 PLOG(ERROR) << "fsync failed";
1608 }
1609 // params.fd will be automatically closed because it's a unique_fd.
1610
1611 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1612 // created the stash.
1613 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1614 DeleteStash(params.stashbase);
1615 }
1616
1617 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1618 state->cause_code = failure_type;
1619 }
1620
1621 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001622}
1623
Tao Bao33567772017-03-13 14:57:34 -07001624/**
1625 * The transfer list is a text file containing commands to transfer data from one place to another
1626 * on the target partition. We parse it and execute the commands in order:
1627 *
1628 * zero [rangeset]
1629 * - Fill the indicated blocks with zeros.
1630 *
1631 * new [rangeset]
1632 * - Fill the blocks with data read from the new_data file.
1633 *
1634 * erase [rangeset]
1635 * - Mark the given blocks as empty.
1636 *
1637 * move <...>
1638 * bsdiff <patchstart> <patchlen> <...>
1639 * imgdiff <patchstart> <patchlen> <...>
1640 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1641 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1642 *
1643 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1644 *
1645 * stash <stash_id> <src_range>
1646 * - Load the given source range and stash the data in the given slot of the stash table.
1647 *
1648 * free <stash_id>
1649 * - Free the given stash data.
1650 *
1651 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1652 * a patch or move) after it has been written.
1653 *
1654 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1655 * in a move/bsdiff/imgdiff command.
1656 *
1657 * Within one command the source and target ranges may overlap so in general we need to read the
1658 * entire source into memory before writing anything to the target blocks.
1659 *
1660 * All the patch data is concatenated into one patch_data file in the update package. It must be
1661 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1662 * already compressed, we lose very little by not compressing their concatenation.)
1663 *
1664 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1665 * additional hashes before the range parameters, which are used to check if the command has already
1666 * been completed and verify the integrity of the source data.
1667 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001668Value* BlockImageVerifyFn(const char* name, State* state,
1669 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001670 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001671 const Command commands[] = {
1672 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001673 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001674 { "free", PerformCommandFree },
1675 { "imgdiff", PerformCommandDiff },
1676 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001677 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001678 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001679 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001680 };
1681
1682 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001683 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001684 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001685}
1686
Tianjie Xuc4447322017-03-06 14:44:59 -08001687Value* BlockImageUpdateFn(const char* name, State* state,
1688 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001689 const Command commands[] = {
1690 { "bsdiff", PerformCommandDiff },
1691 { "erase", PerformCommandErase },
1692 { "free", PerformCommandFree },
1693 { "imgdiff", PerformCommandDiff },
1694 { "move", PerformCommandMove },
1695 { "new", PerformCommandNew },
1696 { "stash", PerformCommandStash },
1697 { "zero", PerformCommandZero }
1698 };
1699
Tianjie Xuc4447322017-03-06 14:44:59 -08001700 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001701 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001702}
1703
Tianjie Xuc4447322017-03-06 14:44:59 -08001704Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1705 if (argv.size() != 2) {
1706 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1707 argv.size());
1708 return StringValue("");
1709 }
1710
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001711 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001712 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001713 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001714 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001715
1716 const Value* blockdev_filename = args[0].get();
1717 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001718
1719 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001720 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1721 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001722 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001723 }
1724 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001725 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001726 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001727 }
1728
Tianjie Xuaced5d92016-10-12 10:55:04 -07001729 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001730 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001731 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1732 blockdev_filename->data.c_str(), strerror(errno));
1733 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001734 }
1735
Tao Baoc844c062016-12-28 15:15:55 -08001736 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001737
1738 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001739 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001740
Tao Bao612336d2015-08-27 16:41:21 -07001741 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001742 for (size_t i = 0; i < rs.count; ++i) {
1743 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001744 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1745 blockdev_filename->data.c_str(), strerror(errno));
1746 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001747 }
1748
Tao Bao0940fe12015-08-27 16:41:21 -07001749 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001750 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001751 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1752 blockdev_filename->data.c_str(), strerror(errno));
1753 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001754 }
1755
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001756 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001757 }
1758 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001759 uint8_t digest[SHA_DIGEST_LENGTH];
1760 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001761
Tianjie Xuaced5d92016-10-12 10:55:04 -07001762 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001763}
1764
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001765// This function checks if a device has been remounted R/W prior to an incremental
1766// OTA update. This is an common cause of update abortion. The function reads the
1767// 1st block of each partition and check for mounting time/count. It return string "t"
1768// if executes successfully and an empty string otherwise.
1769
Tianjie Xuc4447322017-03-06 14:44:59 -08001770Value* CheckFirstBlockFn(const char* name, State* state,
1771 const std::vector<std::unique_ptr<Expr>>& argv) {
1772 if (argv.size() != 1) {
1773 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1774 argv.size());
1775 return StringValue("");
1776 }
1777
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001778 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001779 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001780 return nullptr;
1781 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001782
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001783 const Value* arg_filename = args[0].get();
1784
1785 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001786 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001787 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001788 }
1789
Tianjie Xuaced5d92016-10-12 10:55:04 -07001790 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001791 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001792 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001793 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001794 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001795 }
1796
1797 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1798 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1799
1800 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001801 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001802 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001803 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001804 }
1805
1806 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1807 // Super block starts from block 0, offset 0x400
1808 // 0x2C: len32 Mount time
1809 // 0x30: len32 Write time
1810 // 0x34: len16 Number of mounts since the last fsck
1811 // 0x38: len16 Magic signature 0xEF53
1812
1813 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1814 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1815
1816 if (mount_count > 0) {
Tao Bao0bbc7642017-03-29 23:57:47 -07001817 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001818 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1819 }
1820
Tianjie Xuaced5d92016-10-12 10:55:04 -07001821 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001822}
1823
1824
Tianjie Xuc4447322017-03-06 14:44:59 -08001825Value* BlockImageRecoverFn(const char* name, State* state,
1826 const std::vector<std::unique_ptr<Expr>>& argv) {
1827 if (argv.size() != 2) {
1828 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1829 argv.size());
1830 return StringValue("");
1831 }
1832
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001833 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001834 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001835 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001836 }
1837
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001838 const Value* filename = args[0].get();
1839 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001840
1841 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001842 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001843 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001844 }
1845 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001846 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001847 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001848 }
1849
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001850 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001851 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001852
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001853 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tao Baod2aecd42017-03-23 14:43:44 -07001854 fec::io fh(filename->data, O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001855
1856 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001857 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001858 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001859 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001860 }
1861
1862 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001863 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001864 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001865 }
1866
1867 fec_status status;
1868
1869 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001870 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001871 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001872 }
1873
Tao Baoc844c062016-12-28 15:15:55 -08001874 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001875
1876 uint8_t buffer[BLOCKSIZE];
1877
1878 for (size_t i = 0; i < rs.count; ++i) {
1879 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1880 // Stay within the data area, libfec validates and corrects metadata
1881 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1882 continue;
1883 }
1884
1885 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001886 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001887 filename->data.c_str(), j, strerror(errno));
1888 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001889 }
1890
1891 // If we want to be able to recover from a situation where rewriting a corrected
1892 // block doesn't guarantee the same data will be returned when re-read later, we
1893 // can save a copy of corrected blocks to /cache. Note:
1894 //
1895 // 1. Maximum space required from /cache is the same as the maximum number of
1896 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1897 // this would be ~16 MiB, for example.
1898 //
1899 // 2. To find out if this block was corrupted, call fec_get_status after each
1900 // read and check if the errors field value has increased.
1901 }
1902 }
Tao Bao039f2da2016-11-22 16:29:50 -08001903 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001904 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001905}
1906
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001907void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001908 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001909 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001910 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001911 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001912 RegisterFunction("range_sha1", RangeSha1Fn);
1913}