blob: c614ccc471a6c9121245ea2e60feafc7788c07b4 [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 Baoba9a42a2015-06-23 23:23:33 -070021#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070022#include <pthread.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <stdlib.h>
26#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000027#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070028#include <sys/types.h>
29#include <sys/wait.h>
30#include <sys/ioctl.h>
31#include <time.h>
32#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010033#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070034
Tao Baoec8272f2017-03-15 17:39:01 -070035#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070038#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Tao Bao039f2da2016-11-22 16:29:50 -080041#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080042#include <android-base/parseint.h>
43#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070044#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080045#include <applypatch/applypatch.h>
46#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070047#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070048#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070049
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070050#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070051#include "error_code.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070052#include "updater/install.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080053#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070054#include "print_sha1.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070055#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070056
Sami Tolvanene82fa182015-06-10 15:58:12 +000057// Set this to 0 to interpret 'erase' transfers to mean do a
58// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
59// erase to mean fill the region with zeroes.
60#define DEBUG_ERASE 0
61
Tao Bao51412212016-12-28 14:44:05 -080062static constexpr size_t BLOCKSIZE = 4096;
63static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
64static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
65static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000066
Tao Bao0940fe12015-08-27 16:41:21 -070067struct RangeSet {
Tao Baoc844c062016-12-28 15:15:55 -080068 size_t count; // Limit is INT_MAX.
69 size_t size;
70 std::vector<size_t> pos; // Actual limit is INT_MAX.
Tianjie Xu2cd36ba2017-03-15 23:52:46 +000071
72 // Get the block number for the ith(starting from 0) block in the range set.
73 int get_block(size_t idx) const {
74 if (idx >= size) {
75 LOG(ERROR) << "index: " << idx << " is greater than range set size: " << size;
76 return -1;
77 }
78 for (size_t i = 0; i < pos.size(); i += 2) {
79 if (idx < pos[i + 1] - pos[i]) {
80 return pos[i] + idx;
81 }
82 idx -= (pos[i + 1] - pos[i]);
83 }
84 return -1;
85 }
Tao Bao0940fe12015-08-27 16:41:21 -070086};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070087
Tianjie Xu16255832016-04-30 11:49:59 -070088static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070089static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070090static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070091
Tao Baoc844c062016-12-28 15:15:55 -080092static RangeSet parse_range(const std::string& range_text) {
93 RangeSet rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094
Tao Baoc844c062016-12-28 15:15:55 -080095 std::vector<std::string> pieces = android::base::Split(range_text, ",");
96 if (pieces.size() < 3) {
97 goto err;
98 }
99
100 size_t num;
101 if (!android::base::ParseUint(pieces[0], &num, static_cast<size_t>(INT_MAX))) {
102 goto err;
103 }
104
105 if (num == 0 || num % 2) {
106 goto err; // must be even
107 } else if (num != pieces.size() - 1) {
108 goto err;
109 }
110
111 rs.pos.resize(num);
112 rs.count = num / 2;
113 rs.size = 0;
114
115 for (size_t i = 0; i < num; i += 2) {
116 if (!android::base::ParseUint(pieces[i + 1], &rs.pos[i], static_cast<size_t>(INT_MAX))) {
117 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100118 }
119
Tao Baoc844c062016-12-28 15:15:55 -0800120 if (!android::base::ParseUint(pieces[i + 2], &rs.pos[i + 1], static_cast<size_t>(INT_MAX))) {
121 goto err;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122 }
123
Tao Baoc844c062016-12-28 15:15:55 -0800124 if (rs.pos[i] >= rs.pos[i + 1]) {
125 goto err; // empty or negative range
Tao Baob15fd222015-09-24 11:10:51 -0700126 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100127
Tao Baoc844c062016-12-28 15:15:55 -0800128 size_t sz = rs.pos[i + 1] - rs.pos[i];
129 if (rs.size > SIZE_MAX - sz) {
130 goto err; // overflow
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700131 }
132
Tao Baoc844c062016-12-28 15:15:55 -0800133 rs.size += sz;
134 }
135
136 return rs;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100137
138err:
Tao Baoc844c062016-12-28 15:15:55 -0800139 LOG(ERROR) << "failed to parse range '" << range_text << "'";
Tao Bao3da88012017-02-03 13:09:23 -0800140 exit(EXIT_FAILURE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700141}
142
Tao Baoe6aa3322015-08-05 15:20:27 -0700143static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Tao Baoc844c062016-12-28 15:15:55 -0800144 for (size_t i = 0; i < r1.count; ++i) {
145 size_t r1_0 = r1.pos[i * 2];
146 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000147
Tao Baoc844c062016-12-28 15:15:55 -0800148 for (size_t j = 0; j < r2.count; ++j) {
149 size_t r2_0 = r2.pos[j * 2];
150 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000151
Tao Baoc844c062016-12-28 15:15:55 -0800152 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
153 return true;
154 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000155 }
Tao Baoc844c062016-12-28 15:15:55 -0800156 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000157
Tao Baoc844c062016-12-28 15:15:55 -0800158 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000159}
160
161static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700162 size_t so_far = 0;
163 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800164 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700165 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700166 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800167 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000168 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -0700169 } else if (r == 0) {
170 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800171 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -0700172 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700173 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700174 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700175 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000176 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700177}
178
Tao Bao612336d2015-08-27 16:41:21 -0700179static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
180 return read_all(fd, buffer.data(), size);
181}
182
Sami Tolvanen90221202014-12-09 16:39:47 +0000183static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700184 size_t written = 0;
185 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800186 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700187 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700188 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800189 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000190 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700191 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700192 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000194
Sami Tolvanen90221202014-12-09 16:39:47 +0000195 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700196}
197
Tao Bao612336d2015-08-27 16:41:21 -0700198static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
199 return write_all(fd, buffer.data(), size);
200}
201
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700202static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
203 // Don't discard blocks unless the update is a retry run.
204 if (!is_retry) {
205 return true;
206 }
207
208 uint64_t args[2] = {static_cast<uint64_t>(offset), size};
209 int status = ioctl(fd, BLKDISCARD, &args);
210 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800211 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700212 return false;
213 }
214 return true;
215}
216
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700217static bool check_lseek(int fd, off64_t offset, int whence) {
218 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
219 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700220 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800221 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700222 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700224 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700225}
226
Tao Bao612336d2015-08-27 16:41:21 -0700227static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700229 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700230
Tao Bao612336d2015-08-27 16:41:21 -0700231 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700232}
233
Tao Bao0940fe12015-08-27 16:41:21 -0700234struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700235 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700236
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700237 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700238 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530239 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700241};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700242
243static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700244 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245
Tao Bao0940fe12015-08-27 16:41:21 -0700246 if (rss->p_remain == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800247 LOG(ERROR) << "range sink write overrun";
Sami Tolvanen90221202014-12-09 16:39:47 +0000248 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700249 }
250
251 ssize_t written = 0;
252 while (size > 0) {
253 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000254
255 if (rss->p_remain < write_now) {
256 write_now = rss->p_remain;
257 }
258
259 if (write_all(rss->fd, data, write_now) == -1) {
260 break;
261 }
262
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700263 data += write_now;
264 size -= write_now;
265
266 rss->p_remain -= write_now;
267 written += write_now;
268
269 if (rss->p_remain == 0) {
270 // move to the next block
271 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700272 if (rss->p_block < rss->tgt.count) {
273 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
274 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000275
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700276 off64_t offset = static_cast<off64_t>(rss->tgt.pos[rss->p_block*2]) * BLOCKSIZE;
277 if (!discard_blocks(rss->fd, offset, rss->p_remain)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000278 break;
279 }
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700280
281 if (!check_lseek(rss->fd, offset, SEEK_SET)) {
282 break;
283 }
284
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700285 } else {
286 // we can't write any more; return how many bytes have
287 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000288 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700289 }
290 }
291 }
292
293 return written;
294}
295
296// All of the data for all the 'new' transfers is contained in one
297// file in the update package, concatenated together in the order in
298// which transfers.list will need it. We want to stream it out of the
299// archive (it's compressed) without writing it to a temp file, but we
300// can't write each section until it's that transfer's turn to go.
301//
302// To achieve this, we expand the new data from the archive in a
303// background thread, and block that threads 'receive uncompressed
304// data' function until the main thread has reached a point where we
305// want some new data to be written. We signal the background thread
306// with the destination for the data and block the main thread,
307// waiting for the background thread to complete writing that section.
308// Then it signals the main thread to wake up and goes back to
309// blocking waiting for a transfer.
310//
311// NewThreadInfo is the struct used to pass information back and forth
312// between the two threads. When the main thread wants some data
313// written, it sets rss to the destination location and signals the
314// condition. When the background thread is done writing, it clears
315// rss and signals the condition again.
316
Tao Bao0940fe12015-08-27 16:41:21 -0700317struct NewThreadInfo {
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700318 ZipArchiveHandle za;
319 ZipEntry entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700320
321 RangeSinkState* rss;
322
323 pthread_mutex_t mu;
324 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700325};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700326
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700327static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700328 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700329
330 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700331 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700332 // data is wanted.
333 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700334 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700335 pthread_cond_wait(&nti->cv, &nti->mu);
336 }
337 pthread_mutex_unlock(&nti->mu);
338
339 // At this point nti->rss is set, and we own it. The main
340 // thread is waiting for it to disappear from nti.
341 ssize_t written = RangeSinkWrite(data, size, nti->rss);
342 data += written;
343 size -= written;
344
Tao Bao0940fe12015-08-27 16:41:21 -0700345 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700346 // we have written all the bytes desired by this rss.
347
348 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700349 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700350 pthread_cond_broadcast(&nti->cv);
351 pthread_mutex_unlock(&nti->mu);
352 }
353 }
354
355 return true;
356}
357
358static void* unzip_new_data(void* cookie) {
Mikhail Lappo20791bd2017-03-23 21:30:36 +0100359 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700360 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700361 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700362}
363
Tao Bao612336d2015-08-27 16:41:21 -0700364static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000365 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700366 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000367
Tao Bao0940fe12015-08-27 16:41:21 -0700368 for (size_t i = 0; i < src.count; ++i) {
369 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000370 return -1;
371 }
372
Tao Bao0940fe12015-08-27 16:41:21 -0700373 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000374
Tao Bao612336d2015-08-27 16:41:21 -0700375 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000376 return -1;
377 }
378
379 p += size;
380 }
381
382 return 0;
383}
384
Tao Bao612336d2015-08-27 16:41:21 -0700385static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
386 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000387
Tao Bao0940fe12015-08-27 16:41:21 -0700388 size_t p = 0;
389 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700390 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
391 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
392 if (!discard_blocks(fd, offset, size)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000393 return -1;
394 }
395
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700396 if (!check_lseek(fd, offset, SEEK_SET)) {
397 return -1;
398 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000399
Tao Bao612336d2015-08-27 16:41:21 -0700400 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000401 return -1;
402 }
403
404 p += size;
405 }
406
407 return 0;
408}
409
Tao Baobaad2d42015-12-06 16:56:27 -0800410// Parameters for transfer list command functions
411struct CommandParameters {
412 std::vector<std::string> tokens;
413 size_t cpos;
414 const char* cmdname;
415 const char* cmdline;
416 std::string freestash;
417 std::string stashbase;
418 bool canwrite;
419 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700420 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800421 bool foundwrites;
422 bool isunresumable;
423 int version;
424 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700425 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800426 NewThreadInfo nti;
427 pthread_t thread;
428 std::vector<uint8_t> buffer;
429 uint8_t* patch_start;
430};
431
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000432// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
433// handled separately).
434static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
435 const std::vector<uint8_t>& buffer) {
436 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000437 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
438 params.tokens[0] == "imgdiff");
439
440 size_t pos = 0;
441 // Command example:
442 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
443 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
444 // [<loc_range> <stashed_blocks>]
445 if (params.tokens[0] == "move") {
446 // src_range for move starts at the 4th position.
447 if (params.tokens.size() < 5) {
448 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
449 return;
450 }
451 pos = 4;
452 } else {
453 // src_range for diff starts at the 7th position.
454 if (params.tokens.size() < 8) {
455 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
456 return;
457 }
458 pos = 7;
459 }
460
461 // Source blocks in stash only, no work to do.
462 if (params.tokens[pos] == "-") {
463 return;
464 }
465
466 RangeSet src = parse_range(params.tokens[pos++]);
467
468 RangeSet locs;
469 // If there's no stashed blocks, content in the buffer is consecutive and has the same
470 // order as the source blocks.
471 if (pos == params.tokens.size()) {
472 locs.count = 1;
473 locs.size = src.size;
474 locs.pos = { 0, src.size };
475 } else {
476 // Otherwise, the next token is the offset of the source blocks in the target range.
477 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
478 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
479 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
480 locs = parse_range(params.tokens[pos++]);
481 CHECK_EQ(src.size, locs.size);
482 CHECK_EQ(locs.pos.size() % 2, static_cast<size_t>(0));
483 }
484
485 LOG(INFO) << "printing hash in hex for " << src.size << " source blocks";
486 for (size_t i = 0; i < src.size; i++) {
487 int block_num = src.get_block(i);
488 CHECK_NE(block_num, -1);
489 int buffer_index = locs.get_block(i);
490 CHECK_NE(buffer_index, -1);
491 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
492
493 uint8_t digest[SHA_DIGEST_LENGTH];
494 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
495 std::string hexdigest = print_sha1(digest);
496 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
497 }
498}
499
500// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
501// in hex for each block.
502static void PrintHashForCorruptedStashedBlocks(const std::string& id,
503 const std::vector<uint8_t>& buffer,
504 const RangeSet& src) {
505 LOG(INFO) << "printing hash in hex for stash_id: " << id;
506 CHECK_EQ(src.size * BLOCKSIZE, buffer.size());
507
508 for (size_t i = 0; i < src.size; i++) {
509 int block_num = src.get_block(i);
510 CHECK_NE(block_num, -1);
511
512 uint8_t digest[SHA_DIGEST_LENGTH];
513 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
514 std::string hexdigest = print_sha1(digest);
515 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
516 }
517}
518
519// If the stash file doesn't exist, read the source blocks this stash contains and print the
520// SHA-1 for these blocks.
521static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
522 if (stash_map.find(id) == stash_map.end()) {
523 LOG(ERROR) << "No stash saved for id: " << id;
524 return;
525 }
526
527 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
528 const RangeSet& src = stash_map[id];
529 std::vector<uint8_t> buffer(src.size * BLOCKSIZE);
530 if (ReadBlocks(src, buffer, fd) == -1) {
531 LOG(ERROR) << "failed to read source blocks for stash: " << id;
532 return;
533 }
534 PrintHashForCorruptedStashedBlocks(id, buffer, src);
535}
536
Tao Bao612336d2015-08-27 16:41:21 -0700537static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700538 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800539 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700540 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000541
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800542 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000543
Tao Baoe6aa3322015-08-05 15:20:27 -0700544 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000545
Tao Bao0940fe12015-08-27 16:41:21 -0700546 if (hexdigest != expected) {
547 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800548 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
549 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700550 }
551 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000552 }
553
Tao Bao0940fe12015-08-27 16:41:21 -0700554 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000555}
556
Tao Bao0940fe12015-08-27 16:41:21 -0700557static std::string GetStashFileName(const std::string& base, const std::string& id,
558 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700559 if (base.empty()) {
560 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000561 }
562
Tao Baoe6aa3322015-08-05 15:20:27 -0700563 std::string fn(STASH_DIRECTORY_BASE);
564 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000565
566 return fn;
567}
568
Tao Baoec8272f2017-03-15 17:39:01 -0700569// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
570// directory and continues despite of errors. Calls the 'callback' function for each file.
571static void EnumerateStash(const std::string& dirname,
572 const std::function<void(const std::string&)>& callback) {
573 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000574
Tao Baoec8272f2017-03-15 17:39:01 -0700575 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000576
Tao Baoec8272f2017-03-15 17:39:01 -0700577 if (directory == nullptr) {
578 if (errno != ENOENT) {
579 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000580 }
Tao Bao51412212016-12-28 14:44:05 -0800581 return;
582 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700583
Tao Baoec8272f2017-03-15 17:39:01 -0700584 dirent* item;
585 while ((item = readdir(directory.get())) != nullptr) {
586 if (item->d_type != DT_REG) continue;
587 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800588 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000589}
590
591// Deletes the stash directory and all files in it. Assumes that it only
592// contains files. There is nothing we can do about unlikely, but possible
593// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700594static void DeleteFile(const std::string& fn) {
595 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000596
Tao Baoec8272f2017-03-15 17:39:01 -0700597 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000598
Tao Baoec8272f2017-03-15 17:39:01 -0700599 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
600 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
601 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000602}
603
Tao Baoe6aa3322015-08-05 15:20:27 -0700604static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700605 if (base.empty()) return;
606
607 LOG(INFO) << "deleting stash " << base;
608
609 std::string dirname = GetStashFileName(base, "", "");
610 EnumerateStash(dirname, DeleteFile);
611
612 if (rmdir(dirname.c_str()) == -1) {
613 if (errno != ENOENT && errno != ENOTDIR) {
614 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000615 }
Tao Baoec8272f2017-03-15 17:39:01 -0700616 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000617}
618
Tao Baobcf46492017-03-23 15:28:20 -0700619static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
620 std::vector<uint8_t>& buffer, bool printnoent) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700621 // In verify mode, if source range_set was saved for the given hash,
622 // check contents in the source blocks first. If the check fails,
623 // search for the stashed files on /cache as usual.
624 if (!params.canwrite) {
625 if (stash_map.find(id) != stash_map.end()) {
626 const RangeSet& src = stash_map[id];
627 allocate(src.size * BLOCKSIZE, buffer);
628
629 if (ReadBlocks(src, buffer, params.fd) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800630 LOG(ERROR) << "failed to read source blocks in stash map.";
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700631 return -1;
632 }
633 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800634 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000635 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700636 return -1;
637 }
638 return 0;
639 }
640 }
641
Tao Bao0940fe12015-08-27 16:41:21 -0700642 size_t blockcount = 0;
643
Sami Tolvanen90221202014-12-09 16:39:47 +0000644 if (!blocks) {
645 blocks = &blockcount;
646 }
647
Tao Baobcf46492017-03-23 15:28:20 -0700648 std::string fn = GetStashFileName(params.stashbase, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000649
Tao Bao0940fe12015-08-27 16:41:21 -0700650 struct stat sb;
651 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000652
653 if (res == -1) {
654 if (errno != ENOENT || printnoent) {
Tao Bao039f2da2016-11-22 16:29:50 -0800655 PLOG(ERROR) << "stat \"" << fn << "\" failed";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000656 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000657 }
Tao Bao0940fe12015-08-27 16:41:21 -0700658 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000659 }
660
Tao Bao039f2da2016-11-22 16:29:50 -0800661 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000662
Tao Bao0940fe12015-08-27 16:41:21 -0700663 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800664 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
Tao Bao0940fe12015-08-27 16:41:21 -0700665 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000666 }
667
Elliott Hughesbcabd092016-03-22 20:19:22 -0700668 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000669 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800670 PLOG(ERROR) << "open \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000672 }
673
Tao Bao612336d2015-08-27 16:41:21 -0700674 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000675
Tao Bao612336d2015-08-27 16:41:21 -0700676 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700677 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000678 }
679
Tao Bao0940fe12015-08-27 16:41:21 -0700680 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000681
Tao Bao612336d2015-08-27 16:41:21 -0700682 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800683 LOG(ERROR) << "unexpected contents in " << fn;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000684 if (stash_map.find(id) == stash_map.end()) {
685 LOG(ERROR) << "failed to find source blocks number for stash " << id
686 << " when executing command: " << params.cmdname;
687 } else {
688 const RangeSet& src = stash_map[id];
689 PrintHashForCorruptedStashedBlocks(id, buffer, src);
690 }
Tao Baoec8272f2017-03-15 17:39:01 -0700691 DeleteFile(fn);
Tao Bao0940fe12015-08-27 16:41:21 -0700692 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000693 }
694
Tao Bao0940fe12015-08-27 16:41:21 -0700695 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000696}
697
Tao Bao612336d2015-08-27 16:41:21 -0700698static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baobcf46492017-03-23 15:28:20 -0700699 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700700 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700701 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000702 }
703
704 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800705 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700706 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 }
708
Tao Bao0940fe12015-08-27 16:41:21 -0700709 std::string fn = GetStashFileName(base, id, ".partial");
710 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000711
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100712 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700713 struct stat sb;
714 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100715
716 if (res == 0) {
717 // The file already exists and since the name is the hash of the contents,
718 // it's safe to assume the contents are identical (accidental hash collisions
719 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800720 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700721 *exists = true;
722 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100723 }
724
Tao Bao0940fe12015-08-27 16:41:21 -0700725 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100726 }
727
Tao Bao039f2da2016-11-22 16:29:50 -0800728 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000729
Tao Bao039f2da2016-11-22 16:29:50 -0800730 android::base::unique_fd fd(
731 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000732 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800733 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700734 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000735 }
736
Tianjie Xua946b9e2017-03-21 16:24:57 -0700737 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
738 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
739 return -1;
740 }
741
Sami Tolvanen90221202014-12-09 16:39:47 +0000742 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700743 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000744 }
745
Jed Estepa7b9a462015-12-15 16:04:53 -0800746 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700747 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800748 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700749 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 }
751
Tao Baoe6aa3322015-08-05 15:20:27 -0700752 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800753 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700754 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000755 }
756
Tao Bao0940fe12015-08-27 16:41:21 -0700757 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700758 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
759 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700760 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700761 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800762 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700763 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700764 }
765
Jed Estepa7b9a462015-12-15 16:04:53 -0800766 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700767 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800768 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700769 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700770 }
771
Tao Bao0940fe12015-08-27 16:41:21 -0700772 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000773}
774
775// Creates a directory for storing stash files and checks if the /cache partition
776// hash enough space for the expected amount of blocks we need to store. Returns
777// >0 if we created the directory, zero if it existed already, and <0 of failure.
778
Tao Bao51412212016-12-28 14:44:05 -0800779static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
780 std::string& base) {
781 if (blockdev.empty()) {
782 return -1;
783 }
784
785 // Stash directory should be different for each partition to avoid conflicts
786 // when updating multiple partitions at the same time, so we use the hash of
787 // the block device name as the base directory
788 uint8_t digest[SHA_DIGEST_LENGTH];
789 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
790 base = print_sha1(digest);
791
792 std::string dirname = GetStashFileName(base, "", "");
793 struct stat sb;
794 int res = stat(dirname.c_str(), &sb);
795 size_t max_stash_size = maxblocks * BLOCKSIZE;
796
797 if (res == -1 && errno != ENOENT) {
798 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
799 strerror(errno));
800 return -1;
801 } else if (res != 0) {
802 LOG(INFO) << "creating stash " << dirname;
803 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
804
805 if (res != 0) {
806 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
807 strerror(errno));
808 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000809 }
810
Tianjie Xua946b9e2017-03-21 16:24:57 -0700811 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
812 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
813 strerror(errno));
814 return -1;
815 }
816
Tao Bao51412212016-12-28 14:44:05 -0800817 if (CacheSizeCheck(max_stash_size) != 0) {
818 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
819 max_stash_size);
820 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000821 }
822
Tao Bao51412212016-12-28 14:44:05 -0800823 return 1; // Created directory
824 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000825
Tao Bao51412212016-12-28 14:44:05 -0800826 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000827
Tao Baoec8272f2017-03-15 17:39:01 -0700828 // If the directory already exists, calculate the space already allocated to stash files and check
829 // if there's enough for all required blocks. Delete any partially completed stash files first.
830 EnumerateStash(dirname, [](const std::string& fn) {
831 if (android::base::EndsWith(fn, ".partial")) {
832 DeleteFile(fn);
833 }
834 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000835
Tao Bao51412212016-12-28 14:44:05 -0800836 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700837 EnumerateStash(dirname, [&existing](const std::string& fn) {
838 if (fn.empty()) return;
839 struct stat sb;
840 if (stat(fn.c_str(), &sb) == -1) {
841 PLOG(ERROR) << "stat \"" << fn << "\" failed";
842 return;
843 }
844 existing += static_cast<size_t>(sb.st_size);
845 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000846
Tao Bao51412212016-12-28 14:44:05 -0800847 if (max_stash_size > existing) {
848 size_t needed = max_stash_size - existing;
849 if (CacheSizeCheck(needed) != 0) {
850 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
851 needed);
852 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000853 }
Tao Bao51412212016-12-28 14:44:05 -0800854 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000855
Tao Bao51412212016-12-28 14:44:05 -0800856 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000857}
858
Tao Baobaad2d42015-12-06 16:56:27 -0800859static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700860 if (base.empty() || id.empty()) {
861 return -1;
862 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000863
Tao Baoec8272f2017-03-15 17:39:01 -0700864 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000865
Tao Baoec8272f2017-03-15 17:39:01 -0700866 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700867}
868
Tao Bao612336d2015-08-27 16:41:21 -0700869static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
870 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700871 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700872 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700873 // may be the same buffer.
874
Tao Bao612336d2015-08-27 16:41:21 -0700875 const uint8_t* from = source.data();
876 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700877 size_t start = locs.size;
878 for (int i = locs.count-1; i >= 0; --i) {
879 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700880 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700881 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700882 blocks * BLOCKSIZE);
883 }
884}
885
886// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800887// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700888//
889// <tgt_range> <src_block_count> <src_range>
890// (loads data from source image only)
891//
892// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
893// (loads data from stashes only)
894//
895// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
896// (loads data from both source image and stashes)
897//
Tao Baobcf46492017-03-23 15:28:20 -0700898// On return, params.buffer is filled with the loaded source data (rearranged and combined with
899// stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
900// *tgt is the target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700901
Tao Baobaad2d42015-12-06 16:56:27 -0800902static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Baobcf46492017-03-23 15:28:20 -0700903 bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800904
905 // At least it needs to provide three parameters: <tgt_range>,
906 // <src_block_count> and "-"/<src_range>.
907 if (params.cpos + 2 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -0800908 LOG(ERROR) << "invalid parameters";
Tao Baobaad2d42015-12-06 16:56:27 -0800909 return -1;
910 }
911
Tao Bao612336d2015-08-27 16:41:21 -0700912 // <tgt_range>
Tao Baoc844c062016-12-28 15:15:55 -0800913 tgt = parse_range(params.tokens[params.cpos++]);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700914
Tao Bao612336d2015-08-27 16:41:21 -0700915 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800916 const std::string& token = params.tokens[params.cpos++];
917 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
Tao Bao039f2da2016-11-22 16:29:50 -0800918 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
Tao Baobaad2d42015-12-06 16:56:27 -0800919 return -1;
920 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700921
Tao Baobcf46492017-03-23 15:28:20 -0700922 allocate(src_blocks * BLOCKSIZE, params.buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700923
Tao Bao612336d2015-08-27 16:41:21 -0700924 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800925 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700926 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800927 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700928 } else {
Tao Baoc844c062016-12-28 15:15:55 -0800929 RangeSet src = parse_range(params.tokens[params.cpos++]);
Tao Baobcf46492017-03-23 15:28:20 -0700930 int res = ReadBlocks(src, params.buffer, params.fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700931
Tao Bao34847b22015-09-08 11:05:49 -0700932 if (overlap) {
933 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700934 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000935
Sami Tolvanen90221202014-12-09 16:39:47 +0000936 if (res == -1) {
937 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700938 }
939
Tao Baobaad2d42015-12-06 16:56:27 -0800940 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 // no stashes, only source range
942 return 0;
943 }
944
Tao Baoc844c062016-12-28 15:15:55 -0800945 RangeSet locs = parse_range(params.tokens[params.cpos++]);
Tao Baobcf46492017-03-23 15:28:20 -0700946 MoveRange(params.buffer, locs, params.buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700947 }
948
Tao Baobaad2d42015-12-06 16:56:27 -0800949 // <[stash_id:stash_range]>
950 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700951 // Each word is a an index into the stash table, a colon, and
952 // then a rangeset describing where in the source block that
953 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800954 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
955 if (tokens.size() != 2) {
Tao Bao039f2da2016-11-22 16:29:50 -0800956 LOG(ERROR) << "invalid parameter";
Tao Baobaad2d42015-12-06 16:56:27 -0800957 return -1;
958 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000959
Tao Bao612336d2015-08-27 16:41:21 -0700960 std::vector<uint8_t> stash;
Tao Baobcf46492017-03-23 15:28:20 -0700961 int res = LoadStash(params, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000962
963 if (res == -1) {
964 // These source blocks will fail verification if used later, but we
965 // will let the caller decide if this is a fatal failure
Tao Bao039f2da2016-11-22 16:29:50 -0800966 LOG(ERROR) << "failed to load stash " << tokens[0];
Sami Tolvanen90221202014-12-09 16:39:47 +0000967 continue;
968 }
969
Tao Baoc844c062016-12-28 15:15:55 -0800970 RangeSet locs = parse_range(tokens[1]);
Sami Tolvanen90221202014-12-09 16:39:47 +0000971
Tao Baobcf46492017-03-23 15:28:20 -0700972 MoveRange(params.buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000973 }
974
975 return 0;
976}
977
Tao Bao33567772017-03-13 14:57:34 -0700978/**
979 * Do a source/target load for move/bsdiff/imgdiff in version 3.
980 *
981 * We expect to parse the remainder of the parameter tokens as one of:
982 *
983 * <tgt_range> <src_block_count> <src_range>
984 * (loads data from source image only)
985 *
986 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
987 * (loads data from stashes only)
988 *
989 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
990 * (loads data from both source image and stashes)
991 *
992 * Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which tells the function
993 * whether to expect separate source and targe block hashes, or if they are both the same and only
994 * one hash should be expected, and 'isunresumable', which receives a non-zero value if block
995 * verification fails in a way that the update cannot be resumed anymore.
996 *
997 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
998 * the return value is -1 and the command should be aborted.
999 *
1000 * If the return value is 1, the command has already been completed according to the contents of the
1001 * target blocks, and should not be performed again.
1002 *
1003 * If the return value is 0, source blocks have expected content and the command can be performed.
1004 */
Tao Bao34847b22015-09-08 11:05:49 -07001005static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao33567772017-03-13 14:57:34 -07001006 bool onehash, bool& overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -08001007 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001008 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001009 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001010 }
1011
Tao Baobaad2d42015-12-06 16:56:27 -08001012 std::string srchash = params.tokens[params.cpos++];
1013 std::string tgthash;
1014
Sami Tolvanen90221202014-12-09 16:39:47 +00001015 if (onehash) {
1016 tgthash = srchash;
1017 } else {
Tao Baobaad2d42015-12-06 16:56:27 -08001018 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001019 LOG(ERROR) << "missing target hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001020 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001021 }
Tao Baobaad2d42015-12-06 16:56:27 -08001022 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +00001023 }
1024
Tao Baobcf46492017-03-23 15:28:20 -07001025 if (LoadSrcTgtVersion2(params, tgt, src_blocks, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001026 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001027 }
1028
Tao Bao34847b22015-09-08 11:05:49 -07001029 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001030
Tao Bao612336d2015-08-27 16:41:21 -07001031 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -07001032 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001033 }
1034
Tao Bao612336d2015-08-27 16:41:21 -07001035 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001036 // Target blocks already have expected content, command should be skipped.
Tao Bao0940fe12015-08-27 16:41:21 -07001037 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001038 }
1039
Tao Bao0940fe12015-08-27 16:41:21 -07001040 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001041 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001042 // resume from possible write errors. In verify mode, we can skip stashing
1043 // because the source blocks won't be overwritten.
1044 if (overlap && params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001045 LOG(INFO) << "stashing " << src_blocks << " overlapping blocks to " << srchash;
Sami Tolvanen90221202014-12-09 16:39:47 +00001046
Tao Bao0940fe12015-08-27 16:41:21 -07001047 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -07001048 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -07001049 &stash_exists) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001050 LOG(ERROR) << "failed to stash overlapping source blocks";
Tao Bao0940fe12015-08-27 16:41:21 -07001051 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001052 }
1053
Tianjie Xudd874b12016-05-13 12:13:15 -07001054 params.stashed += src_blocks;
Tao Bao33567772017-03-13 14:57:34 -07001055 // Can be deleted when the write has completed.
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001056 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -07001057 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001058 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001059 }
1060
Tao Bao33567772017-03-13 14:57:34 -07001061 // Source blocks have expected content, command can proceed.
Tao Bao0940fe12015-08-27 16:41:21 -07001062 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001063 }
1064
Tao Baobcf46492017-03-23 15:28:20 -07001065 if (overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +01001066 // Overlapping source blocks were previously stashed, command can proceed.
1067 // We are recovering from an interrupted command, so we don't know if the
1068 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001069 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001070 }
1071
Tao Bao33567772017-03-13 14:57:34 -07001072 // Valid source data not available, update cannot be resumed.
Tao Bao039f2da2016-11-22 16:29:50 -08001073 LOG(ERROR) << "partition has unexpected contents";
Tianjie Xu2cd36ba2017-03-15 23:52:46 +00001074 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1075
Tao Bao0940fe12015-08-27 16:41:21 -07001076 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001077
Tao Bao0940fe12015-08-27 16:41:21 -07001078 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001079}
1080
Tao Bao0940fe12015-08-27 16:41:21 -07001081static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001082 size_t blocks = 0;
1083 bool overlap = false;
1084 RangeSet tgt;
1085 int status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001086
Tao Bao33567772017-03-13 14:57:34 -07001087 if (status == -1) {
1088 LOG(ERROR) << "failed to read blocks for move";
1089 return -1;
1090 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001091
Tao Bao33567772017-03-13 14:57:34 -07001092 if (status == 0) {
1093 params.foundwrites = true;
1094 } else if (params.foundwrites) {
1095 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1096 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001097
Tao Bao33567772017-03-13 14:57:34 -07001098 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001099 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001100 LOG(INFO) << " moving " << blocks << " blocks";
1101
1102 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1103 return -1;
1104 }
1105 } else {
1106 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001107 }
Tao Bao33567772017-03-13 14:57:34 -07001108 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001109
Tao Bao33567772017-03-13 14:57:34 -07001110 if (!params.freestash.empty()) {
1111 FreeStash(params.stashbase, params.freestash);
1112 params.freestash.clear();
1113 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001114
Tao Bao33567772017-03-13 14:57:34 -07001115 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001116
Tao Bao33567772017-03-13 14:57:34 -07001117 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001118}
1119
Tao Bao0940fe12015-08-27 16:41:21 -07001120static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001121 // <stash_id> <src_range>
1122 if (params.cpos + 1 >= params.tokens.size()) {
1123 LOG(ERROR) << "missing id and/or src range fields in stash command";
1124 return -1;
1125 }
1126
1127 const std::string& id = params.tokens[params.cpos++];
1128 size_t blocks = 0;
1129 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1130 // Stash file already exists and has expected contents. Do not read from source again, as the
1131 // source may have been already overwritten during a previous attempt.
1132 return 0;
1133 }
1134
1135 RangeSet src = parse_range(params.tokens[params.cpos++]);
1136
1137 allocate(src.size * BLOCKSIZE, params.buffer);
1138 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1139 return -1;
1140 }
1141 blocks = src.size;
1142 stash_map[id] = src;
1143
1144 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1145 // Source blocks have unexpected contents. If we actually need this data later, this is an
1146 // unrecoverable error. However, the command that uses the data may have already completed
1147 // previously, so the possible failure will occur during source block verification.
1148 LOG(ERROR) << "failed to load source blocks for stash " << id;
1149 return 0;
1150 }
1151
1152 // In verify mode, we don't need to stash any blocks.
1153 if (!params.canwrite) {
1154 return 0;
1155 }
1156
1157 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1158 params.stashed += blocks;
1159 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001160}
1161
Tao Bao0940fe12015-08-27 16:41:21 -07001162static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001163 // <stash_id>
1164 if (params.cpos >= params.tokens.size()) {
1165 LOG(ERROR) << "missing stash id in free command";
1166 return -1;
1167 }
Tao Baobaad2d42015-12-06 16:56:27 -08001168
Tao Baobcf46492017-03-23 15:28:20 -07001169 const std::string& id = params.tokens[params.cpos++];
1170 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001171
Tao Baobcf46492017-03-23 15:28:20 -07001172 if (params.createdstash || params.canwrite) {
1173 return FreeStash(params.stashbase, id);
1174 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001175
Tao Baobcf46492017-03-23 15:28:20 -07001176 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001177}
1178
Tao Bao0940fe12015-08-27 16:41:21 -07001179static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001180
Tao Baobaad2d42015-12-06 16:56:27 -08001181 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001182 LOG(ERROR) << "missing target blocks for zero";
Tao Bao0940fe12015-08-27 16:41:21 -07001183 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
Tao Baoc844c062016-12-28 15:15:55 -08001186 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Bao039f2da2016-11-22 16:29:50 -08001188 LOG(INFO) << " zeroing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001189
Tao Bao612336d2015-08-27 16:41:21 -07001190 allocate(BLOCKSIZE, params.buffer);
1191 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001192
Tao Bao0940fe12015-08-27 16:41:21 -07001193 if (params.canwrite) {
1194 for (size_t i = 0; i < tgt.count; ++i) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001195 off64_t offset = static_cast<off64_t>(tgt.pos[i * 2]) * BLOCKSIZE;
1196 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
1197 if (!discard_blocks(params.fd, offset, size)) {
1198 return -1;
1199 }
1200
1201 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001202 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001203 }
1204
Tao Bao0940fe12015-08-27 16:41:21 -07001205 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1206 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1207 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001208 }
1209 }
1210 }
1211 }
1212
Tao Bao0940fe12015-08-27 16:41:21 -07001213 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001214 // Update only for the zero command, as the erase command will call
1215 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001216 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 }
1218
Tao Bao0940fe12015-08-27 16:41:21 -07001219 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001220}
1221
Tao Bao0940fe12015-08-27 16:41:21 -07001222static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001223
Tao Baobaad2d42015-12-06 16:56:27 -08001224 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001225 LOG(ERROR) << "missing target blocks for new";
Tao Bao0940fe12015-08-27 16:41:21 -07001226 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001227 }
1228
Tao Baoc844c062016-12-28 15:15:55 -08001229 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001230
Tao Bao0940fe12015-08-27 16:41:21 -07001231 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001232 LOG(INFO) << " writing " << tgt.size << " blocks of new data";
Sami Tolvanen90221202014-12-09 16:39:47 +00001233
Tao Bao0940fe12015-08-27 16:41:21 -07001234 RangeSinkState rss(tgt);
1235 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001236 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001237 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001238
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001239 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1240 if (!discard_blocks(params.fd, offset, tgt.size * BLOCKSIZE)) {
1241 return -1;
1242 }
1243
1244 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001245 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001246 }
1247
Tao Bao0940fe12015-08-27 16:41:21 -07001248 pthread_mutex_lock(&params.nti.mu);
1249 params.nti.rss = &rss;
1250 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001251
Tao Bao0940fe12015-08-27 16:41:21 -07001252 while (params.nti.rss) {
1253 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 }
1255
Tao Bao0940fe12015-08-27 16:41:21 -07001256 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001257 }
1258
Tao Bao0940fe12015-08-27 16:41:21 -07001259 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001260
Tao Bao0940fe12015-08-27 16:41:21 -07001261 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001262}
1263
Tao Bao0940fe12015-08-27 16:41:21 -07001264static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001265
Tao Baobaad2d42015-12-06 16:56:27 -08001266 // <offset> <length>
1267 if (params.cpos + 1 >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001268 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
Tao Bao0940fe12015-08-27 16:41:21 -07001269 return -1;
1270 }
1271
Tao Baobaad2d42015-12-06 16:56:27 -08001272 size_t offset;
1273 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001274 LOG(ERROR) << "invalid patch offset";
Tao Bao0940fe12015-08-27 16:41:21 -07001275 return -1;
1276 }
1277
Tao Baobaad2d42015-12-06 16:56:27 -08001278 size_t len;
1279 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001280 LOG(ERROR) << "invalid patch len";
Tao Baobaad2d42015-12-06 16:56:27 -08001281 return -1;
1282 }
Tao Bao0940fe12015-08-27 16:41:21 -07001283
Tao Bao612336d2015-08-27 16:41:21 -07001284 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001285 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001286 bool overlap = false;
Tao Bao33567772017-03-13 14:57:34 -07001287 int status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001288
1289 if (status == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001290 LOG(ERROR) << "failed to read blocks for diff";
Tao Bao0940fe12015-08-27 16:41:21 -07001291 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001292 }
1293
1294 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001295 params.foundwrites = true;
1296 } else if (params.foundwrites) {
Tao Bao039f2da2016-11-22 16:29:50 -08001297 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001298 }
1299
Tao Bao0940fe12015-08-27 16:41:21 -07001300 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001301 if (status == 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001302 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.size;
Tianjie Xuaced5d92016-10-12 10:55:04 -07001303 Value patch_value(VAL_BLOB,
1304 std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Tao Bao0940fe12015-08-27 16:41:21 -07001305 RangeSinkState rss(tgt);
1306 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001307 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001308 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001309
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001310 off64_t offset = static_cast<off64_t>(tgt.pos[0]) * BLOCKSIZE;
1311 if (!discard_blocks(params.fd, offset, rss.p_remain)) {
1312 return -1;
1313 }
1314
1315 if (!check_lseek(params.fd, offset, SEEK_SET)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001316 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001317 }
1318
Tao Bao0940fe12015-08-27 16:41:21 -07001319 if (params.cmdname[0] == 'i') { // imgdiff
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001320 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1321 &RangeSinkWrite, &rss, nullptr, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001322 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001323 return -1;
1324 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001325 } else {
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001326 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1327 0, &RangeSinkWrite, &rss, nullptr) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001328 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu31f8cc82016-06-15 11:56:42 -07001329 return -1;
1330 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001331 }
1332
1333 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001334 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -08001335 LOG(ERROR) << "range sink underrun?";
Sami Tolvanen90221202014-12-09 16:39:47 +00001336 }
1337 } else {
Tao Bao039f2da2016-11-22 16:29:50 -08001338 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.size
1339 << " [" << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001340 }
1341 }
1342
Tao Baobaad2d42015-12-06 16:56:27 -08001343 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001344 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001345 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001346 }
1347
Tao Bao0940fe12015-08-27 16:41:21 -07001348 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001349
Tao Bao0940fe12015-08-27 16:41:21 -07001350 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001351}
1352
Tao Bao0940fe12015-08-27 16:41:21 -07001353static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001354 if (DEBUG_ERASE) {
1355 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001356 }
1357
Tao Bao0940fe12015-08-27 16:41:21 -07001358 struct stat sb;
1359 if (fstat(params.fd, &sb) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001360 PLOG(ERROR) << "failed to fstat device to erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001361 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001362 }
1363
Tao Bao0940fe12015-08-27 16:41:21 -07001364 if (!S_ISBLK(sb.st_mode)) {
Tao Bao039f2da2016-11-22 16:29:50 -08001365 LOG(ERROR) << "not a block device; skipping erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001366 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001367 }
1368
Tao Baobaad2d42015-12-06 16:56:27 -08001369 if (params.cpos >= params.tokens.size()) {
Tao Bao039f2da2016-11-22 16:29:50 -08001370 LOG(ERROR) << "missing target blocks for erase";
Tao Bao0940fe12015-08-27 16:41:21 -07001371 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001372 }
1373
Tao Baoc844c062016-12-28 15:15:55 -08001374 RangeSet tgt = parse_range(params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001375
Tao Bao0940fe12015-08-27 16:41:21 -07001376 if (params.canwrite) {
Tao Bao039f2da2016-11-22 16:29:50 -08001377 LOG(INFO) << " erasing " << tgt.size << " blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001378
Tao Bao0940fe12015-08-27 16:41:21 -07001379 for (size_t i = 0; i < tgt.count; ++i) {
1380 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001381 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001382 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001383 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001384 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001385
Tao Bao0940fe12015-08-27 16:41:21 -07001386 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -08001387 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001388 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001389 }
1390 }
1391 }
1392
Tao Bao0940fe12015-08-27 16:41:21 -07001393 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001394}
1395
1396// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001397typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001398
Tao Bao612336d2015-08-27 16:41:21 -07001399struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001400 const char* name;
1401 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001402};
Sami Tolvanen90221202014-12-09 16:39:47 +00001403
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001404// args:
1405// - block device (or file) to modify in-place
1406// - transfer list (blob)
1407// - new data stream (filename within package.zip)
1408// - patch stream (filename within package.zip, must be uncompressed)
1409
Tianjie Xuc4447322017-03-06 14:44:59 -08001410static Value* PerformBlockImageUpdate(const char* name, State* state,
1411 const std::vector<std::unique_ptr<Expr>>& argv,
1412 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001413 CommandParameters params = {};
1414 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001415
Tao Bao33567772017-03-13 14:57:34 -07001416 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1417 if (state->is_retry) {
1418 is_retry = true;
1419 LOG(INFO) << "This update is a retry.";
1420 }
1421 if (argv.size() != 4) {
1422 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1423 argv.size());
1424 return StringValue("");
1425 }
1426
1427 std::vector<std::unique_ptr<Value>> args;
1428 if (!ReadValueArgs(state, argv, &args)) {
1429 return nullptr;
1430 }
1431
1432 const Value* blockdev_filename = args[0].get();
1433 const Value* transfer_list_value = args[1].get();
1434 const Value* new_data_fn = args[2].get();
1435 const Value* patch_data_fn = args[3].get();
1436
1437 if (blockdev_filename->type != VAL_STRING) {
1438 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1439 return StringValue("");
1440 }
1441 if (transfer_list_value->type != VAL_BLOB) {
1442 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1443 return StringValue("");
1444 }
1445 if (new_data_fn->type != VAL_STRING) {
1446 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1447 return StringValue("");
1448 }
1449 if (patch_data_fn->type != VAL_STRING) {
1450 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1451 return StringValue("");
1452 }
1453
1454 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1455 if (ui == nullptr) {
1456 return StringValue("");
1457 }
1458
1459 FILE* cmd_pipe = ui->cmd_pipe;
1460 ZipArchiveHandle za = ui->package_zip;
1461
1462 if (cmd_pipe == nullptr || za == nullptr) {
1463 return StringValue("");
1464 }
1465
1466 ZipString path_data(patch_data_fn->data.c_str());
1467 ZipEntry patch_entry;
1468 if (FindEntry(za, path_data, &patch_entry) != 0) {
1469 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1470 return StringValue("");
1471 }
1472
1473 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1474 ZipString new_data(new_data_fn->data.c_str());
1475 ZipEntry new_entry;
1476 if (FindEntry(za, new_data, &new_entry) != 0) {
1477 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1478 return StringValue("");
1479 }
1480
1481 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1482 if (params.fd == -1) {
1483 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1484 return StringValue("");
1485 }
1486
1487 if (params.canwrite) {
1488 params.nti.za = za;
1489 params.nti.entry = new_entry;
1490
1491 pthread_mutex_init(&params.nti.mu, nullptr);
1492 pthread_cond_init(&params.nti.cv, nullptr);
1493 pthread_attr_t attr;
1494 pthread_attr_init(&attr);
1495 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1496
1497 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1498 if (error != 0) {
1499 PLOG(ERROR) << "pthread_create failed";
1500 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001501 }
Tao Bao33567772017-03-13 14:57:34 -07001502 }
1503
1504 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1505 if (lines.size() < 2) {
1506 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1507 lines.size());
1508 return StringValue("");
1509 }
1510
1511 // First line in transfer list is the version number.
1512 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1513 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1514 return StringValue("");
1515 }
1516
1517 LOG(INFO) << "blockimg version is " << params.version;
1518
1519 // Second line in transfer list is the total number of blocks we expect to write.
1520 size_t total_blocks;
1521 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1522 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1523 return StringValue("");
1524 }
1525
1526 if (total_blocks == 0) {
1527 return StringValue("t");
1528 }
1529
1530 size_t start = 2;
1531 if (lines.size() < 4) {
1532 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1533 lines.size());
1534 return StringValue("");
1535 }
1536
1537 // Third line is how many stash entries are needed simultaneously.
1538 LOG(INFO) << "maximum stash entries " << lines[2];
1539
1540 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1541 size_t stash_max_blocks;
1542 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1543 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1544 lines[3].c_str());
1545 return StringValue("");
1546 }
1547
1548 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1549 if (res == -1) {
1550 return StringValue("");
1551 }
1552
1553 params.createdstash = res;
1554
1555 start += 2;
1556
1557 // Build a map of the available commands
1558 std::unordered_map<std::string, const Command*> cmd_map;
1559 for (size_t i = 0; i < cmdcount; ++i) {
1560 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1561 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1562 return StringValue(strdup(""));
1563 }
1564 cmd_map[commands[i].name] = &commands[i];
1565 }
1566
1567 int rc = -1;
1568
1569 // Subsequent lines are all individual transfer commands
1570 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1571 const std::string& line(*it);
1572 if (line.empty()) continue;
1573
1574 params.tokens = android::base::Split(line, " ");
1575 params.cpos = 0;
1576 params.cmdname = params.tokens[params.cpos++].c_str();
1577 params.cmdline = line.c_str();
1578
1579 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1580 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1581 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001582 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001583
Tao Bao33567772017-03-13 14:57:34 -07001584 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001585
Tao Bao33567772017-03-13 14:57:34 -07001586 if (cmd->f != nullptr && cmd->f(params) == -1) {
1587 LOG(ERROR) << "failed to execute command [" << line << "]";
1588 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001589 }
1590
Sami Tolvanen90221202014-12-09 16:39:47 +00001591 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001592 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001593 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001594 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001595 goto pbiudone;
1596 }
1597 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1598 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001599 }
Tao Bao33567772017-03-13 14:57:34 -07001600 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001601
Tao Bao33567772017-03-13 14:57:34 -07001602 if (params.canwrite) {
1603 pthread_join(params.thread, nullptr);
1604
1605 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1606 LOG(INFO) << "stashed " << params.stashed << " blocks";
1607 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1608
1609 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1610 if (partition != nullptr && *(partition + 1) != 0) {
1611 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1612 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1613 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001614 }
Tao Bao33567772017-03-13 14:57:34 -07001615 // Delete stash only after successfully completing the update, as it may contain blocks needed
1616 // to complete the update later.
1617 DeleteStash(params.stashbase);
1618 } else {
1619 LOG(INFO) << "verified partition contents; update may be resumed";
1620 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001621
Tao Bao33567772017-03-13 14:57:34 -07001622 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001623
Tao Bao33567772017-03-13 14:57:34 -07001624pbiudone:
1625 if (ota_fsync(params.fd) == -1) {
1626 failure_type = kFsyncFailure;
1627 PLOG(ERROR) << "fsync failed";
1628 }
1629 // params.fd will be automatically closed because it's a unique_fd.
1630
1631 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1632 // created the stash.
1633 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1634 DeleteStash(params.stashbase);
1635 }
1636
1637 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1638 state->cause_code = failure_type;
1639 }
1640
1641 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001642}
1643
Tao Bao33567772017-03-13 14:57:34 -07001644/**
1645 * The transfer list is a text file containing commands to transfer data from one place to another
1646 * on the target partition. We parse it and execute the commands in order:
1647 *
1648 * zero [rangeset]
1649 * - Fill the indicated blocks with zeros.
1650 *
1651 * new [rangeset]
1652 * - Fill the blocks with data read from the new_data file.
1653 *
1654 * erase [rangeset]
1655 * - Mark the given blocks as empty.
1656 *
1657 * move <...>
1658 * bsdiff <patchstart> <patchlen> <...>
1659 * imgdiff <patchstart> <patchlen> <...>
1660 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1661 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1662 *
1663 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1664 *
1665 * stash <stash_id> <src_range>
1666 * - Load the given source range and stash the data in the given slot of the stash table.
1667 *
1668 * free <stash_id>
1669 * - Free the given stash data.
1670 *
1671 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1672 * a patch or move) after it has been written.
1673 *
1674 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1675 * in a move/bsdiff/imgdiff command.
1676 *
1677 * Within one command the source and target ranges may overlap so in general we need to read the
1678 * entire source into memory before writing anything to the target blocks.
1679 *
1680 * All the patch data is concatenated into one patch_data file in the update package. It must be
1681 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1682 * already compressed, we lose very little by not compressing their concatenation.)
1683 *
1684 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1685 * additional hashes before the range parameters, which are used to check if the command has already
1686 * been completed and verify the integrity of the source data.
1687 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001688Value* BlockImageVerifyFn(const char* name, State* state,
1689 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001690 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001691 const Command commands[] = {
1692 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001693 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001694 { "free", PerformCommandFree },
1695 { "imgdiff", PerformCommandDiff },
1696 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001697 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001698 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001699 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001700 };
1701
1702 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001703 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001704 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001705}
1706
Tianjie Xuc4447322017-03-06 14:44:59 -08001707Value* BlockImageUpdateFn(const char* name, State* state,
1708 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001709 const Command commands[] = {
1710 { "bsdiff", PerformCommandDiff },
1711 { "erase", PerformCommandErase },
1712 { "free", PerformCommandFree },
1713 { "imgdiff", PerformCommandDiff },
1714 { "move", PerformCommandMove },
1715 { "new", PerformCommandNew },
1716 { "stash", PerformCommandStash },
1717 { "zero", PerformCommandZero }
1718 };
1719
Tianjie Xuc4447322017-03-06 14:44:59 -08001720 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001721 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001722}
1723
Tianjie Xuc4447322017-03-06 14:44:59 -08001724Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1725 if (argv.size() != 2) {
1726 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu",
1727 argv.size());
1728 return StringValue("");
1729 }
1730
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001731 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001732 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001733 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001734 }
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001735
1736 const Value* blockdev_filename = args[0].get();
1737 const Value* ranges = args[1].get();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001738
1739 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001740 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1741 name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001742 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001743 }
1744 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001745 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001746 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001747 }
1748
Tianjie Xuaced5d92016-10-12 10:55:04 -07001749 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
Elliott Hughesbcabd092016-03-22 20:19:22 -07001750 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001751 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s",
1752 blockdev_filename->data.c_str(), strerror(errno));
1753 return StringValue("");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001754 }
1755
Tao Baoc844c062016-12-28 15:15:55 -08001756 RangeSet rs = parse_range(ranges->data);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001757
1758 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001759 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001760
Tao Bao612336d2015-08-27 16:41:21 -07001761 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001762 for (size_t i = 0; i < rs.count; ++i) {
1763 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001764 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s",
1765 blockdev_filename->data.c_str(), strerror(errno));
1766 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001767 }
1768
Tao Bao0940fe12015-08-27 16:41:21 -07001769 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001770 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001771 ErrorAbort(state, kFreadFailure, "failed to read %s: %s",
1772 blockdev_filename->data.c_str(), strerror(errno));
1773 return StringValue("");
Sami Tolvanen90221202014-12-09 16:39:47 +00001774 }
1775
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001776 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001777 }
1778 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001779 uint8_t digest[SHA_DIGEST_LENGTH];
1780 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001781
Tianjie Xuaced5d92016-10-12 10:55:04 -07001782 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001783}
1784
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001785// This function checks if a device has been remounted R/W prior to an incremental
1786// OTA update. This is an common cause of update abortion. The function reads the
1787// 1st block of each partition and check for mounting time/count. It return string "t"
1788// if executes successfully and an empty string otherwise.
1789
Tianjie Xuc4447322017-03-06 14:44:59 -08001790Value* CheckFirstBlockFn(const char* name, State* state,
1791 const std::vector<std::unique_ptr<Expr>>& argv) {
1792 if (argv.size() != 1) {
1793 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1794 argv.size());
1795 return StringValue("");
1796 }
1797
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001798 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001799 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001800 return nullptr;
1801 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001802
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001803 const Value* arg_filename = args[0].get();
1804
1805 if (arg_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001806 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001807 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001808 }
1809
Tianjie Xuaced5d92016-10-12 10:55:04 -07001810 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001811 if (fd == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001812 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001813 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001814 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001815 }
1816
1817 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1818 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1819
1820 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001821 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
Tianjie Xu30bf4762015-12-15 11:47:30 -08001822 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001823 return StringValue("");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001824 }
1825
1826 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1827 // Super block starts from block 0, offset 0x400
1828 // 0x2C: len32 Mount time
1829 // 0x30: len32 Write time
1830 // 0x34: len16 Number of mounts since the last fsck
1831 // 0x38: len16 Magic signature 0xEF53
1832
1833 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1834 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1835
1836 if (mount_count > 0) {
1837 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1838 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1839 }
1840
Tianjie Xuaced5d92016-10-12 10:55:04 -07001841 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001842}
1843
1844
Tianjie Xuc4447322017-03-06 14:44:59 -08001845Value* BlockImageRecoverFn(const char* name, State* state,
1846 const std::vector<std::unique_ptr<Expr>>& argv) {
1847 if (argv.size() != 2) {
1848 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1849 argv.size());
1850 return StringValue("");
1851 }
1852
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001853 std::vector<std::unique_ptr<Value>> args;
Tianjie Xuc4447322017-03-06 14:44:59 -08001854 if (!ReadValueArgs(state, argv, &args)) {
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001855 return nullptr;
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001856 }
1857
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001858 const Value* filename = args[0].get();
1859 const Value* ranges = args[1].get();
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001860
1861 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001862 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001863 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001864 }
1865 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001866 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tianjie Xuaced5d92016-10-12 10:55:04 -07001867 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001868 }
1869
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001870 // Output notice to log when recover is attempted
Tao Bao039f2da2016-11-22 16:29:50 -08001871 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001872
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001873 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
Tianjie Xuaced5d92016-10-12 10:55:04 -07001874 fec::io fh(filename->data.c_str(), O_RDWR);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001875
1876 if (!fh) {
Tianjie Xuaced5d92016-10-12 10:55:04 -07001877 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
Tianjie Xu16255832016-04-30 11:49:59 -07001878 strerror(errno));
Tianjie Xuaced5d92016-10-12 10:55:04 -07001879 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001880 }
1881
1882 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001883 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001884 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001885 }
1886
1887 fec_status status;
1888
1889 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001890 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Tianjie Xuaced5d92016-10-12 10:55:04 -07001891 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001892 }
1893
Tao Baoc844c062016-12-28 15:15:55 -08001894 RangeSet rs = parse_range(ranges->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001895
1896 uint8_t buffer[BLOCKSIZE];
1897
1898 for (size_t i = 0; i < rs.count; ++i) {
1899 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1900 // Stay within the data area, libfec validates and corrects metadata
1901 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1902 continue;
1903 }
1904
1905 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001906 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
Tianjie Xuaced5d92016-10-12 10:55:04 -07001907 filename->data.c_str(), j, strerror(errno));
1908 return StringValue("");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001909 }
1910
1911 // If we want to be able to recover from a situation where rewriting a corrected
1912 // block doesn't guarantee the same data will be returned when re-read later, we
1913 // can save a copy of corrected blocks to /cache. Note:
1914 //
1915 // 1. Maximum space required from /cache is the same as the maximum number of
1916 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1917 // this would be ~16 MiB, for example.
1918 //
1919 // 2. To find out if this block was corrupted, call fec_get_status after each
1920 // read and check if the errors field value has increased.
1921 }
1922 }
Tao Bao039f2da2016-11-22 16:29:50 -08001923 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
Tianjie Xuaced5d92016-10-12 10:55:04 -07001924 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001925}
1926
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001927void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001928 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001929 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001930 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001931 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001932 RegisterFunction("range_sha1", RangeSha1Fn);
1933}