blob: f78342d365a695326c8b456688f13c594e11c8e5 [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>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu7eca97e2016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070043#include <android-base/unique_fd.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070044
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070045#include "applypatch/applypatch.h"
46#include "edify/expr.h"
Tianjie Xu16255832016-04-30 11:49:59 -070047#include "error_code.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080048#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080049#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000050#include "minzip/Hash.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080051#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070052#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070053#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070054
55#define BLOCKSIZE 4096
56
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
Sami Tolvanen90221202014-12-09 16:39:47 +000062#define STASH_DIRECTORY_BASE "/cache/recovery"
63#define STASH_DIRECTORY_MODE 0700
64#define STASH_FILE_MODE 0600
65
Tao Bao0940fe12015-08-27 16:41:21 -070066struct RangeSet {
67 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053068 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070069 std::vector<size_t> pos; // Actual limit is INT_MAX.
70};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070071
Tianjie Xu16255832016-04-30 11:49:59 -070072static CauseCode failure_type = kNoCause;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070073static std::map<std::string, RangeSet> stash_map;
74
Tao Baobaad2d42015-12-06 16:56:27 -080075static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010076
Tao Baobaad2d42015-12-06 16:56:27 -080077 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070078 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010079 goto err;
80 }
81
Tao Baob15fd222015-09-24 11:10:51 -070082 size_t num;
83 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010084 goto err;
85 }
86
Tao Baob15fd222015-09-24 11:10:51 -070087 if (num == 0 || num % 2) {
88 goto err; // must be even
89 } else if (num != pieces.size() - 1) {
90 goto err;
91 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010092
Tao Bao0940fe12015-08-27 16:41:21 -070093 rs.pos.resize(num);
94 rs.count = num / 2;
95 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010096
Tao Bao0940fe12015-08-27 16:41:21 -070097 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070098 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
99 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100100 goto err;
101 }
102
Tao Baob15fd222015-09-24 11:10:51 -0700103 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
104 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530105 goto err;
106 }
107
Tao Bao0940fe12015-08-27 16:41:21 -0700108 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530109 goto err; // empty or negative range
110 }
111
Tao Bao0940fe12015-08-27 16:41:21 -0700112 size_t sz = rs.pos[i+1] - rs.pos[i];
113 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530114 goto err; // overflow
115 }
116
Tao Bao0940fe12015-08-27 16:41:21 -0700117 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700118 }
119
Tao Bao0940fe12015-08-27 16:41:21 -0700120 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100121
122err:
Tao Baobaad2d42015-12-06 16:56:27 -0800123 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100124 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700125}
126
Tao Baoe6aa3322015-08-05 15:20:27 -0700127static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530128 for (size_t i = 0; i < r1.count; ++i) {
129 size_t r1_0 = r1.pos[i * 2];
130 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000131
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530132 for (size_t j = 0; j < r2.count; ++j) {
133 size_t r2_0 = r2.pos[j * 2];
134 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000135
Tao Baoc0f56ad2015-06-25 14:00:31 -0700136 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700137 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000138 }
139 }
140 }
141
Tao Baoe6aa3322015-08-05 15:20:27 -0700142 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000143}
144
145static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700146 size_t so_far = 0;
147 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800148 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700149 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700150 failure_type = kFreadFailure;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700151 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000152 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700153 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700154 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700155 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000156 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700157}
158
Tao Bao612336d2015-08-27 16:41:21 -0700159static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
160 return read_all(fd, buffer.data(), size);
161}
162
Sami Tolvanen90221202014-12-09 16:39:47 +0000163static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700164 size_t written = 0;
165 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -0800166 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700167 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700168 failure_type = kFwriteFailure;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700169 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000170 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700171 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700172 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700173 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000174
Sami Tolvanen90221202014-12-09 16:39:47 +0000175 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700176}
177
Tao Bao612336d2015-08-27 16:41:21 -0700178static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
179 return write_all(fd, buffer.data(), size);
180}
181
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700182static bool check_lseek(int fd, off64_t offset, int whence) {
183 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
184 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700185 failure_type = kLseekFailure;
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700186 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
187 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700188 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700189 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700190}
191
Tao Bao612336d2015-08-27 16:41:21 -0700192static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700193 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700194 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700195
Tao Bao612336d2015-08-27 16:41:21 -0700196 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197}
198
Tao Bao0940fe12015-08-27 16:41:21 -0700199struct RangeSinkState {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700200 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700201
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700203 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530204 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700206};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207
208static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700209 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700210
Tao Bao0940fe12015-08-27 16:41:21 -0700211 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700212 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000213 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700214 }
215
216 ssize_t written = 0;
217 while (size > 0) {
218 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000219
220 if (rss->p_remain < write_now) {
221 write_now = rss->p_remain;
222 }
223
224 if (write_all(rss->fd, data, write_now) == -1) {
225 break;
226 }
227
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700228 data += write_now;
229 size -= write_now;
230
231 rss->p_remain -= write_now;
232 written += write_now;
233
234 if (rss->p_remain == 0) {
235 // move to the next block
236 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700237 if (rss->p_block < rss->tgt.count) {
238 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
239 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000240
Tao Bao0940fe12015-08-27 16:41:21 -0700241 if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700242 SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000243 break;
244 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245 } else {
246 // we can't write any more; return how many bytes have
247 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000248 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700249 }
250 }
251 }
252
253 return written;
254}
255
256// All of the data for all the 'new' transfers is contained in one
257// file in the update package, concatenated together in the order in
258// which transfers.list will need it. We want to stream it out of the
259// archive (it's compressed) without writing it to a temp file, but we
260// can't write each section until it's that transfer's turn to go.
261//
262// To achieve this, we expand the new data from the archive in a
263// background thread, and block that threads 'receive uncompressed
264// data' function until the main thread has reached a point where we
265// want some new data to be written. We signal the background thread
266// with the destination for the data and block the main thread,
267// waiting for the background thread to complete writing that section.
268// Then it signals the main thread to wake up and goes back to
269// blocking waiting for a transfer.
270//
271// NewThreadInfo is the struct used to pass information back and forth
272// between the two threads. When the main thread wants some data
273// written, it sets rss to the destination location and signals the
274// condition. When the background thread is done writing, it clears
275// rss and signals the condition again.
276
Tao Bao0940fe12015-08-27 16:41:21 -0700277struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700278 ZipArchive* za;
279 const ZipEntry* entry;
280
281 RangeSinkState* rss;
282
283 pthread_mutex_t mu;
284 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700285};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700286
287static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700288 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700289
290 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700291 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700292 // data is wanted.
293 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700294 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700295 pthread_cond_wait(&nti->cv, &nti->mu);
296 }
297 pthread_mutex_unlock(&nti->mu);
298
299 // At this point nti->rss is set, and we own it. The main
300 // thread is waiting for it to disappear from nti.
301 ssize_t written = RangeSinkWrite(data, size, nti->rss);
302 data += written;
303 size -= written;
304
Tao Bao0940fe12015-08-27 16:41:21 -0700305 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700306 // we have written all the bytes desired by this rss.
307
308 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700309 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700310 pthread_cond_broadcast(&nti->cv);
311 pthread_mutex_unlock(&nti->mu);
312 }
313 }
314
315 return true;
316}
317
318static void* unzip_new_data(void* cookie) {
319 NewThreadInfo* nti = (NewThreadInfo*) cookie;
320 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700321 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700322}
323
Tao Bao612336d2015-08-27 16:41:21 -0700324static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000325 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700326 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000327
Tao Bao0940fe12015-08-27 16:41:21 -0700328 for (size_t i = 0; i < src.count; ++i) {
329 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000330 return -1;
331 }
332
Tao Bao0940fe12015-08-27 16:41:21 -0700333 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000334
Tao Bao612336d2015-08-27 16:41:21 -0700335 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000336 return -1;
337 }
338
339 p += size;
340 }
341
342 return 0;
343}
344
Tao Bao612336d2015-08-27 16:41:21 -0700345static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
346 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000347
Tao Bao0940fe12015-08-27 16:41:21 -0700348 size_t p = 0;
349 for (size_t i = 0; i < tgt.count; ++i) {
350 if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000351 return -1;
352 }
353
Tao Bao0940fe12015-08-27 16:41:21 -0700354 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000355
Tao Bao612336d2015-08-27 16:41:21 -0700356 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000357 return -1;
358 }
359
360 p += size;
361 }
362
363 return 0;
364}
365
Tao Baobaad2d42015-12-06 16:56:27 -0800366// Parameters for transfer list command functions
367struct CommandParameters {
368 std::vector<std::string> tokens;
369 size_t cpos;
370 const char* cmdname;
371 const char* cmdline;
372 std::string freestash;
373 std::string stashbase;
374 bool canwrite;
375 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700376 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800377 bool foundwrites;
378 bool isunresumable;
379 int version;
380 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700381 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800382 NewThreadInfo nti;
383 pthread_t thread;
384 std::vector<uint8_t> buffer;
385 uint8_t* patch_start;
386};
387
Doug Zongker52ae67d2014-09-08 12:22:09 -0700388// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800389// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700390//
391// <src_range> <tgt_range>
392//
393// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700394// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700395
Tao Baobaad2d42015-12-06 16:56:27 -0800396static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700397 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800398
399 if (params.cpos + 1 >= params.tokens.size()) {
400 fprintf(stderr, "invalid parameters\n");
401 return -1;
402 }
403
Tao Bao612336d2015-08-27 16:41:21 -0700404 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700405 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800406 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700407
Tao Bao612336d2015-08-27 16:41:21 -0700408 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800409 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700410
Tao Bao612336d2015-08-27 16:41:21 -0700411 allocate(src.size * BLOCKSIZE, buffer);
412 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700413 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000414
Sami Tolvanen90221202014-12-09 16:39:47 +0000415 return rc;
416}
417
Tao Bao612336d2015-08-27 16:41:21 -0700418static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700419 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800420 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700421 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000422
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800423 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000424
Tao Baoe6aa3322015-08-05 15:20:27 -0700425 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000426
Tao Bao0940fe12015-08-27 16:41:21 -0700427 if (hexdigest != expected) {
428 if (printerror) {
429 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
430 expected.c_str(), hexdigest.c_str());
431 }
432 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000433 }
434
Tao Bao0940fe12015-08-27 16:41:21 -0700435 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000436}
437
Tao Bao0940fe12015-08-27 16:41:21 -0700438static std::string GetStashFileName(const std::string& base, const std::string& id,
439 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700440 if (base.empty()) {
441 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000442 }
443
Tao Baoe6aa3322015-08-05 15:20:27 -0700444 std::string fn(STASH_DIRECTORY_BASE);
445 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000446
447 return fn;
448}
449
Tao Baoe6aa3322015-08-05 15:20:27 -0700450typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000451
452// Does a best effort enumeration of stash files. Ignores possible non-file
453// items in the stash directory and continues despite of errors. Calls the
454// 'callback' function for each file and passes 'data' to the function as a
455// parameter.
456
Tao Baoe6aa3322015-08-05 15:20:27 -0700457static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700458 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000459 return;
460 }
461
Tao Baoe6aa3322015-08-05 15:20:27 -0700462 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000463
Tao Bao0940fe12015-08-27 16:41:21 -0700464 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000465 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700466 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000467 }
468 return;
469 }
470
Tao Baoe6aa3322015-08-05 15:20:27 -0700471 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700472 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000473 if (item->d_type != DT_REG) {
474 continue;
475 }
476
Tao Baoe6aa3322015-08-05 15:20:27 -0700477 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000478 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000479 }
480}
481
Tao Baoe6aa3322015-08-05 15:20:27 -0700482static void UpdateFileSize(const std::string& fn, void* data) {
483 if (fn.empty() || !data) {
484 return;
485 }
486
Tao Bao0940fe12015-08-27 16:41:21 -0700487 struct stat sb;
488 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700489 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000490 return;
491 }
492
Tao Baoe6aa3322015-08-05 15:20:27 -0700493 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700494 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000495}
496
497// Deletes the stash directory and all files in it. Assumes that it only
498// contains files. There is nothing we can do about unlikely, but possible
499// errors, so they are merely logged.
500
Tao Bao0940fe12015-08-27 16:41:21 -0700501static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700502 if (!fn.empty()) {
503 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000504
Tao Baoe6aa3322015-08-05 15:20:27 -0700505 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
506 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000507 }
508 }
509}
510
Tao Baoe6aa3322015-08-05 15:20:27 -0700511static void DeletePartial(const std::string& fn, void* data) {
512 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000513 DeleteFile(fn, data);
514 }
515}
516
Tao Baoe6aa3322015-08-05 15:20:27 -0700517static void DeleteStash(const std::string& base) {
518 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000519 return;
520 }
521
Tao Baoe6aa3322015-08-05 15:20:27 -0700522 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000523
Tao Baoe6aa3322015-08-05 15:20:27 -0700524 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700525 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000526
Tao Baoe6aa3322015-08-05 15:20:27 -0700527 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000528 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700529 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000530 }
531 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000532}
533
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700534static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
535 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
536 // In verify mode, if source range_set was saved for the given hash,
537 // check contents in the source blocks first. If the check fails,
538 // search for the stashed files on /cache as usual.
539 if (!params.canwrite) {
540 if (stash_map.find(id) != stash_map.end()) {
541 const RangeSet& src = stash_map[id];
542 allocate(src.size * BLOCKSIZE, buffer);
543
544 if (ReadBlocks(src, buffer, params.fd) == -1) {
545 fprintf(stderr, "failed to read source blocks in stash map.\n");
546 return -1;
547 }
548 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
549 fprintf(stderr, "failed to verify loaded source blocks in stash map.\n");
550 return -1;
551 }
552 return 0;
553 }
554 }
555
Tao Bao612336d2015-08-27 16:41:21 -0700556 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700557 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000558 }
559
Tao Bao0940fe12015-08-27 16:41:21 -0700560 size_t blockcount = 0;
561
Sami Tolvanen90221202014-12-09 16:39:47 +0000562 if (!blocks) {
563 blocks = &blockcount;
564 }
565
Tao Bao0940fe12015-08-27 16:41:21 -0700566 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000567
Tao Bao0940fe12015-08-27 16:41:21 -0700568 struct stat sb;
569 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000570
571 if (res == -1) {
572 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700573 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000574 }
Tao Bao0940fe12015-08-27 16:41:21 -0700575 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000576 }
577
Tao Baoe6aa3322015-08-05 15:20:27 -0700578 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000579
Tao Bao0940fe12015-08-27 16:41:21 -0700580 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700581 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700582 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
583 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000584 }
585
Elliott Hughesbcabd092016-03-22 20:19:22 -0700586 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000587 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700588 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700589 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000590 }
591
Tao Bao612336d2015-08-27 16:41:21 -0700592 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000593
Tao Bao612336d2015-08-27 16:41:21 -0700594 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700595 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000596 }
597
Tao Bao0940fe12015-08-27 16:41:21 -0700598 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000599
Tao Bao612336d2015-08-27 16:41:21 -0700600 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700601 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700602 DeleteFile(fn, nullptr);
603 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000604 }
605
Tao Bao0940fe12015-08-27 16:41:21 -0700606 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000607}
608
Tao Bao612336d2015-08-27 16:41:21 -0700609static int WriteStash(const std::string& base, const std::string& id, int blocks,
610 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
611 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700612 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000613 }
614
615 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
616 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700617 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000618 }
619
Tao Bao0940fe12015-08-27 16:41:21 -0700620 std::string fn = GetStashFileName(base, id, ".partial");
621 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000622
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100623 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700624 struct stat sb;
625 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100626
627 if (res == 0) {
628 // The file already exists and since the name is the hash of the contents,
629 // it's safe to assume the contents are identical (accidental hash collisions
630 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700631 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700632 *exists = true;
633 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100634 }
635
Tao Bao0940fe12015-08-27 16:41:21 -0700636 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100637 }
638
Tao Baoe6aa3322015-08-05 15:20:27 -0700639 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000640
Elliott Hughesbcabd092016-03-22 20:19:22 -0700641 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(),
642 O_WRONLY | O_CREAT | O_TRUNC,
643 STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000644 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700645 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700646 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000647 }
648
649 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700650 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000651 }
652
Jed Estepa7b9a462015-12-15 16:04:53 -0800653 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700654 failure_type = kFsyncFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700655 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700656 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000657 }
658
Tao Baoe6aa3322015-08-05 15:20:27 -0700659 if (rename(fn.c_str(), cn.c_str()) == -1) {
660 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
661 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700662 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000663 }
664
Tao Bao0940fe12015-08-27 16:41:21 -0700665 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700666 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
667 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700668 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700669 failure_type = kFileOpenFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700670 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700671 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700672 }
673
Jed Estepa7b9a462015-12-15 16:04:53 -0800674 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700675 failure_type = kFsyncFailure;
Tao Baoe6aa3322015-08-05 15:20:27 -0700676 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700677 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700678 }
679
Tao Bao0940fe12015-08-27 16:41:21 -0700680 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000681}
682
683// Creates a directory for storing stash files and checks if the /cache partition
684// hash enough space for the expected amount of blocks we need to store. Returns
685// >0 if we created the directory, zero if it existed already, and <0 of failure.
686
Tao Bao0940fe12015-08-27 16:41:21 -0700687static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
688 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700689 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000690 }
691
692 // Stash directory should be different for each partition to avoid conflicts
693 // when updating multiple partitions at the same time, so we use the hash of
694 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800695 uint8_t digest[SHA_DIGEST_LENGTH];
696 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700697 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000698
Tao Baoe6aa3322015-08-05 15:20:27 -0700699 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700700 struct stat sb;
701 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000702
703 if (res == -1 && errno != ENOENT) {
Tianjie Xu16255832016-04-30 11:49:59 -0700704 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n",
705 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700706 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700708 fprintf(stderr, "creating stash %s\n", dirname.c_str());
709 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000710
711 if (res != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700712 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n",
713 dirname.c_str(), strerror(errno));
Tao Baoe6aa3322015-08-05 15:20:27 -0700714 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
716
717 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700718 ErrorAbort(state, kStashCreationFailure, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700719 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000720 }
721
Tao Baoe6aa3322015-08-05 15:20:27 -0700722 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000723 }
724
Tao Baoe6aa3322015-08-05 15:20:27 -0700725 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000726
727 // If the directory already exists, calculate the space already allocated to
728 // stash files and check if there's enough for all required blocks. Delete any
729 // partially completed stash files first.
730
Tao Bao0940fe12015-08-27 16:41:21 -0700731 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700732 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733 EnumerateStash(dirname, UpdateFileSize, &size);
734
Tao Bao0940fe12015-08-27 16:41:21 -0700735 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000736
737 if (size > 0 && CacheSizeCheck(size) != 0) {
Tianjie Xu16255832016-04-30 11:49:59 -0700738 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%d more needed)\n",
739 size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700740 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 }
742
Tao Baoe6aa3322015-08-05 15:20:27 -0700743 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000744}
745
Tao Baobaad2d42015-12-06 16:56:27 -0800746static int SaveStash(CommandParameters& params, const std::string& base,
747 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000748
Tao Baobaad2d42015-12-06 16:56:27 -0800749 // <stash_id> <src_range>
750 if (params.cpos + 1 >= params.tokens.size()) {
751 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000752 return -1;
753 }
Tao Baobaad2d42015-12-06 16:56:27 -0800754 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000755
Tao Bao0940fe12015-08-27 16:41:21 -0700756 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700757 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000758 // Stash file already exists and has expected contents. Do not
759 // read from source again, as the source may have been already
760 // overwritten during a previous attempt.
761 return 0;
762 }
763
Tao Bao34847b22015-09-08 11:05:49 -0700764 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800765 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700766
Tao Bao612336d2015-08-27 16:41:21 -0700767 allocate(src.size * BLOCKSIZE, buffer);
768 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000769 return -1;
770 }
Tao Bao34847b22015-09-08 11:05:49 -0700771 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000772
Tao Bao612336d2015-08-27 16:41:21 -0700773 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000774 // Source blocks have unexpected contents. If we actually need this
775 // data later, this is an unrecoverable error. However, the command
776 // that uses the data may have already completed previously, so the
777 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700778 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000779 return 0;
780 }
781
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700782 // In verify mode, save source range_set instead of stashing blocks.
783 if (!params.canwrite && usehash) {
784 stash_map[id] = src;
785 return 0;
786 }
787
Tao Bao0940fe12015-08-27 16:41:21 -0700788 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tianjie Xudd874b12016-05-13 12:13:15 -0700789 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700790 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000791}
792
Tao Baobaad2d42015-12-06 16:56:27 -0800793static int FreeStash(const std::string& base, const std::string& id) {
794 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000795 return -1;
796 }
797
Tao Baobaad2d42015-12-06 16:56:27 -0800798 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700799 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000800
801 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700802}
803
Tao Bao612336d2015-08-27 16:41:21 -0700804static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
805 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700806 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700807 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700808 // may be the same buffer.
809
Tao Bao612336d2015-08-27 16:41:21 -0700810 const uint8_t* from = source.data();
811 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700812 size_t start = locs.size;
813 for (int i = locs.count-1; i >= 0; --i) {
814 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700815 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700816 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700817 blocks * BLOCKSIZE);
818 }
819}
820
821// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800822// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700823//
824// <tgt_range> <src_block_count> <src_range>
825// (loads data from source image only)
826//
827// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
828// (loads data from stashes only)
829//
830// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
831// (loads data from both source image and stashes)
832//
833// On return, buffer is filled with the loaded source data (rearranged
834// and combined with stashed data as necessary). buffer may be
835// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000836// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700837
Tao Baobaad2d42015-12-06 16:56:27 -0800838static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700839 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800840
841 // At least it needs to provide three parameters: <tgt_range>,
842 // <src_block_count> and "-"/<src_range>.
843 if (params.cpos + 2 >= params.tokens.size()) {
844 fprintf(stderr, "invalid parameters\n");
845 return -1;
846 }
847
Tao Bao612336d2015-08-27 16:41:21 -0700848 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800849 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700850
Tao Bao612336d2015-08-27 16:41:21 -0700851 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800852 const std::string& token = params.tokens[params.cpos++];
853 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
854 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
855 return -1;
856 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700857
Tao Bao612336d2015-08-27 16:41:21 -0700858 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700859
Tao Bao612336d2015-08-27 16:41:21 -0700860 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800861 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700862 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800863 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700864 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700865 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800866 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700867 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700868
Tao Bao34847b22015-09-08 11:05:49 -0700869 if (overlap) {
870 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700871 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000872
Sami Tolvanen90221202014-12-09 16:39:47 +0000873 if (res == -1) {
874 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700875 }
876
Tao Baobaad2d42015-12-06 16:56:27 -0800877 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000878 // no stashes, only source range
879 return 0;
880 }
881
Tao Bao612336d2015-08-27 16:41:21 -0700882 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800883 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700884 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700885 }
886
Tao Baobaad2d42015-12-06 16:56:27 -0800887 // <[stash_id:stash_range]>
888 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700889 // Each word is a an index into the stash table, a colon, and
890 // then a rangeset describing where in the source block that
891 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800892 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
893 if (tokens.size() != 2) {
894 fprintf(stderr, "invalid parameter\n");
895 return -1;
896 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000897
Tao Bao612336d2015-08-27 16:41:21 -0700898 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700899 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000900
901 if (res == -1) {
902 // These source blocks will fail verification if used later, but we
903 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800904 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000905 continue;
906 }
907
Tao Bao612336d2015-08-27 16:41:21 -0700908 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800909 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000910
Tao Bao612336d2015-08-27 16:41:21 -0700911 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000912 }
913
914 return 0;
915}
916
Sami Tolvanen90221202014-12-09 16:39:47 +0000917// Do a source/target load for move/bsdiff/imgdiff in version 3.
918//
919// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
920// tells the function whether to expect separate source and targe block hashes, or
921// if they are both the same and only one hash should be expected, and
922// 'isunresumable', which receives a non-zero value if block verification fails in
923// a way that the update cannot be resumed anymore.
924//
925// If the function is unable to load the necessary blocks or their contents don't
926// match the hashes, the return value is -1 and the command should be aborted.
927//
928// If the return value is 1, the command has already been completed according to
929// the contents of the target blocks, and should not be performed again.
930//
931// If the return value is 0, source blocks have expected content and the command
932// can be performed.
933
Tao Bao34847b22015-09-08 11:05:49 -0700934static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700935 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000936
Tao Baobaad2d42015-12-06 16:56:27 -0800937 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000938 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700939 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000940 }
941
Tao Baobaad2d42015-12-06 16:56:27 -0800942 std::string srchash = params.tokens[params.cpos++];
943 std::string tgthash;
944
Sami Tolvanen90221202014-12-09 16:39:47 +0000945 if (onehash) {
946 tgthash = srchash;
947 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800948 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000949 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700950 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000951 }
Tao Baobaad2d42015-12-06 16:56:27 -0800952 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000953 }
954
Elliott Hughesbcabd092016-03-22 20:19:22 -0700955 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
956 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700957 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000958 }
959
Tao Bao34847b22015-09-08 11:05:49 -0700960 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000961
Tao Bao612336d2015-08-27 16:41:21 -0700962 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700963 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000964 }
965
Tao Bao612336d2015-08-27 16:41:21 -0700966 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000967 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700968 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000969 }
970
Tao Bao0940fe12015-08-27 16:41:21 -0700971 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000972 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700973 // resume from possible write errors. In verify mode, we can skip stashing
974 // because the source blocks won't be overwritten.
975 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -0800976 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
977 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000978
Tao Bao0940fe12015-08-27 16:41:21 -0700979 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700980 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700981 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000982 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700983 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000984 }
985
Tianjie Xudd874b12016-05-13 12:13:15 -0700986 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +0000987 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100988 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700989 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100990 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000991 }
992
993 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700994 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000995 }
996
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700997 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
998 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100999 // Overlapping source blocks were previously stashed, command can proceed.
1000 // We are recovering from an interrupted command, so we don't know if the
1001 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -07001002 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001003 }
1004
1005 // Valid source data not available, update cannot be resumed
1006 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001007 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001008
Tao Bao0940fe12015-08-27 16:41:21 -07001009 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001010}
1011
Tao Bao0940fe12015-08-27 16:41:21 -07001012static int PerformCommandMove(CommandParameters& params) {
1013 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001014 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001015 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001016 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001017
Tao Bao0940fe12015-08-27 16:41:21 -07001018 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001019 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001020 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001021 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001022 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001023 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001024 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001025 }
1026
1027 if (status == -1) {
1028 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001029 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001030 }
1031
1032 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001033 params.foundwrites = true;
1034 } else if (params.foundwrites) {
1035 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001036 }
1037
Tao Bao0940fe12015-08-27 16:41:21 -07001038 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001039 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001040 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001041
Tao Bao0940fe12015-08-27 16:41:21 -07001042 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1043 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001044 }
1045 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001046 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001047 }
1048
1049 }
1050
Tao Baobaad2d42015-12-06 16:56:27 -08001051 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001052 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001053 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001054 }
1055
Tao Bao0940fe12015-08-27 16:41:21 -07001056 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001057
Tao Bao0940fe12015-08-27 16:41:21 -07001058 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001059}
1060
Tao Bao0940fe12015-08-27 16:41:21 -07001061static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001062 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001063 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001064}
1065
Tao Bao0940fe12015-08-27 16:41:21 -07001066static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001067 // <stash_id>
1068 if (params.cpos >= params.tokens.size()) {
1069 fprintf(stderr, "missing stash id in free command\n");
1070 return -1;
1071 }
1072
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001073 const std::string& id = params.tokens[params.cpos++];
1074
1075 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1076 stash_map.erase(id);
1077 return 0;
1078 }
1079
Tao Bao0940fe12015-08-27 16:41:21 -07001080 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001081 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001082 }
1083
1084 return 0;
1085}
1086
Tao Bao0940fe12015-08-27 16:41:21 -07001087static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001088
Tao Baobaad2d42015-12-06 16:56:27 -08001089 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001090 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001091 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001092 }
1093
Tao Bao0940fe12015-08-27 16:41:21 -07001094 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001095 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001096
Tao Bao0940fe12015-08-27 16:41:21 -07001097 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001098
Tao Bao612336d2015-08-27 16:41:21 -07001099 allocate(BLOCKSIZE, params.buffer);
1100 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001101
Tao Bao0940fe12015-08-27 16:41:21 -07001102 if (params.canwrite) {
1103 for (size_t i = 0; i < tgt.count; ++i) {
1104 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1105 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001106 }
1107
Tao Bao0940fe12015-08-27 16:41:21 -07001108 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1109 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1110 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001111 }
1112 }
1113 }
1114 }
1115
Tao Bao0940fe12015-08-27 16:41:21 -07001116 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001117 // Update only for the zero command, as the erase command will call
1118 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001119 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001120 }
1121
Tao Bao0940fe12015-08-27 16:41:21 -07001122 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001123}
1124
Tao Bao0940fe12015-08-27 16:41:21 -07001125static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001126
Tao Baobaad2d42015-12-06 16:56:27 -08001127 if (params.cpos >= params.tokens.size()) {
1128 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001129 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001130 }
1131
Tao Bao0940fe12015-08-27 16:41:21 -07001132 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001133 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001134
Tao Bao0940fe12015-08-27 16:41:21 -07001135 if (params.canwrite) {
1136 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001137
Tao Bao0940fe12015-08-27 16:41:21 -07001138 RangeSinkState rss(tgt);
1139 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001140 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001141 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001142
Tao Bao0940fe12015-08-27 16:41:21 -07001143 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1144 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001145 }
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147 pthread_mutex_lock(&params.nti.mu);
1148 params.nti.rss = &rss;
1149 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001150
Tao Bao0940fe12015-08-27 16:41:21 -07001151 while (params.nti.rss) {
1152 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001153 }
1154
Tao Bao0940fe12015-08-27 16:41:21 -07001155 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001156 }
1157
Tao Bao0940fe12015-08-27 16:41:21 -07001158 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001159
Tao Bao0940fe12015-08-27 16:41:21 -07001160 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001161}
1162
Tao Bao0940fe12015-08-27 16:41:21 -07001163static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001164
Tao Baobaad2d42015-12-06 16:56:27 -08001165 // <offset> <length>
1166 if (params.cpos + 1 >= params.tokens.size()) {
1167 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001168 return -1;
1169 }
1170
Tao Baobaad2d42015-12-06 16:56:27 -08001171 size_t offset;
1172 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1173 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001174 return -1;
1175 }
1176
Tao Baobaad2d42015-12-06 16:56:27 -08001177 size_t len;
1178 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1179 fprintf(stderr, "invalid patch offset\n");
1180 return -1;
1181 }
Tao Bao0940fe12015-08-27 16:41:21 -07001182
Tao Bao612336d2015-08-27 16:41:21 -07001183 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001184 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001185 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001186 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001187 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001188 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001189 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001190 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001191 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001192 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001193 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001194 }
1195
1196 if (status == -1) {
1197 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001198 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001199 }
1200
1201 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001202 params.foundwrites = true;
1203 } else if (params.foundwrites) {
1204 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001205 }
1206
Tao Bao0940fe12015-08-27 16:41:21 -07001207 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001208 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001209 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001210
Tao Bao0940fe12015-08-27 16:41:21 -07001211 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 patch_value.type = VAL_BLOB;
1213 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001214 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001215
Tao Bao0940fe12015-08-27 16:41:21 -07001216 RangeSinkState rss(tgt);
1217 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001218 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001219 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001220
Tao Bao0940fe12015-08-27 16:41:21 -07001221 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1222 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001223 }
1224
Tao Bao0940fe12015-08-27 16:41:21 -07001225 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001226 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001227 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001228 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001229 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1230 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001231 }
1232
1233 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001234 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001235 fprintf(stderr, "range sink underrun?\n");
1236 }
1237 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001238 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001239 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001240 }
1241 }
1242
Tao Baobaad2d42015-12-06 16:56:27 -08001243 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001244 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001245 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001246 }
1247
Tao Bao0940fe12015-08-27 16:41:21 -07001248 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001249
Tao Bao0940fe12015-08-27 16:41:21 -07001250 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251}
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001254 if (DEBUG_ERASE) {
1255 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001256 }
1257
Tao Bao0940fe12015-08-27 16:41:21 -07001258 struct stat sb;
1259 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001260 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001261 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001262 }
1263
Tao Bao0940fe12015-08-27 16:41:21 -07001264 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001265 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001266 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001267 }
1268
Tao Baobaad2d42015-12-06 16:56:27 -08001269 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001270 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001271 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001272 }
1273
Tao Bao0940fe12015-08-27 16:41:21 -07001274 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001275 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001276
Tao Bao0940fe12015-08-27 16:41:21 -07001277 if (params.canwrite) {
1278 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001279
Tao Bao0940fe12015-08-27 16:41:21 -07001280 for (size_t i = 0; i < tgt.count; ++i) {
1281 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001282 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001283 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001285 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001286
Tao Bao0940fe12015-08-27 16:41:21 -07001287 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001288 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001289 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001290 }
1291 }
1292 }
1293
Tao Bao0940fe12015-08-27 16:41:21 -07001294 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001295}
1296
1297// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001298typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001299
Tao Bao612336d2015-08-27 16:41:21 -07001300struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001301 const char* name;
1302 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001303};
Sami Tolvanen90221202014-12-09 16:39:47 +00001304
1305// CompareCommands and CompareCommandNames are for the hash table
1306
1307static int CompareCommands(const void* c1, const void* c2) {
1308 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1309}
1310
1311static int CompareCommandNames(const void* c1, const void* c2) {
1312 return strcmp(((const Command*) c1)->name, (const char*) c2);
1313}
1314
1315// HashString is used to hash command names for the hash table
1316
1317static unsigned int HashString(const char *s) {
1318 unsigned int hash = 0;
1319 if (s) {
1320 while (*s) {
1321 hash = hash * 33 + *s++;
1322 }
1323 }
1324 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001325}
1326
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001327// args:
1328// - block device (or file) to modify in-place
1329// - transfer list (blob)
1330// - new data stream (filename within package.zip)
1331// - patch stream (filename within package.zip, must be uncompressed)
1332
Tao Bao0940fe12015-08-27 16:41:21 -07001333static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1334 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001335 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001336 params.canwrite = !dryrun;
1337
1338 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001339
Tao Bao612336d2015-08-27 16:41:21 -07001340 Value* blockdev_filename = nullptr;
1341 Value* transfer_list_value = nullptr;
1342 Value* new_data_fn = nullptr;
1343 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001344 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001345 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001346 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347 }
Tao Bao612336d2015-08-27 16:41:21 -07001348 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1349 FreeValue);
1350 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1351 FreeValue);
1352 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1353 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001354
1355 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001356 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1357 name);
Tao Bao612336d2015-08-27 16:41:21 -07001358 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001359 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001360 if (transfer_list_value->type != VAL_BLOB) {
Tianjie Xu16255832016-04-30 11:49:59 -07001361 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001362 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001363 }
1364 if (new_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001365 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001366 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001367 }
1368 if (patch_data_fn->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001369 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string",
1370 name);
Tao Bao612336d2015-08-27 16:41:21 -07001371 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001372 }
1373
Tao Bao612336d2015-08-27 16:41:21 -07001374 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001375
Tao Bao0940fe12015-08-27 16:41:21 -07001376 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001377 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001378 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001379
Tao Bao612336d2015-08-27 16:41:21 -07001380 FILE* cmd_pipe = ui->cmd_pipe;
1381 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001382
Tao Bao0940fe12015-08-27 16:41:21 -07001383 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001384 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001385 }
1386
Tao Bao612336d2015-08-27 16:41:21 -07001387 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001388 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001389 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001390 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001391 }
1392
Sami Tolvanen90221202014-12-09 16:39:47 +00001393 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001394 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001395 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001396 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001397 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001398 }
1399
Elliott Hughesbcabd092016-03-22 20:19:22 -07001400 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001401 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001402 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001403 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001404 }
1405
Sami Tolvanen90221202014-12-09 16:39:47 +00001406 if (params.canwrite) {
1407 params.nti.za = za;
1408 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001409
Tao Bao0940fe12015-08-27 16:41:21 -07001410 pthread_mutex_init(&params.nti.mu, nullptr);
1411 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001412 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001413 pthread_attr_init(&attr);
1414 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1415
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001416 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1417 if (error != 0) {
1418 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001419 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001420 }
1421 }
1422
Tao Baobaad2d42015-12-06 16:56:27 -08001423 // Copy all the lines in transfer_list_value into std::string for
1424 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001425 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1426 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001427 if (lines.size() < 2) {
Tianjie Xu16255832016-04-30 11:49:59 -07001428 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1429 lines.size());
Tao Baobaad2d42015-12-06 16:56:27 -08001430 return StringValue(strdup(""));
1431 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001432
Sami Tolvanen90221202014-12-09 16:39:47 +00001433 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001434 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001435 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1436 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001437 }
1438
Sami Tolvanen90221202014-12-09 16:39:47 +00001439 fprintf(stderr, "blockimg version is %d\n", params.version);
1440
1441 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001442 int total_blocks;
1443 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001444 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
Tao Bao612336d2015-08-27 16:41:21 -07001445 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001446 }
1447
1448 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001449 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001450 }
1451
Tao Bao612336d2015-08-27 16:41:21 -07001452 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001453 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001454 if (lines.size() < 4) {
Tianjie Xu16255832016-04-30 11:49:59 -07001455 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1456 lines.size());
Tao Baobaad2d42015-12-06 16:56:27 -08001457 return StringValue(strdup(""));
1458 }
1459
Sami Tolvanen90221202014-12-09 16:39:47 +00001460 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001461 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001462
Sami Tolvanen90221202014-12-09 16:39:47 +00001463 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001464 int stash_max_blocks;
1465 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001466 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1467 lines[3].c_str());
Tao Bao612336d2015-08-27 16:41:21 -07001468 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001469 }
1470
Tao Baob15fd222015-09-24 11:10:51 -07001471 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001472 if (res == -1) {
1473 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001474 }
Tao Bao612336d2015-08-27 16:41:21 -07001475
Tao Baob15fd222015-09-24 11:10:51 -07001476 params.createdstash = res;
1477
Tao Bao612336d2015-08-27 16:41:21 -07001478 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001479 }
1480
Sami Tolvanen90221202014-12-09 16:39:47 +00001481 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001482 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1483 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001484
Tao Bao0940fe12015-08-27 16:41:21 -07001485 for (size_t i = 0; i < cmdcount; ++i) {
1486 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001487 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1488 }
1489
Tao Bao612336d2015-08-27 16:41:21 -07001490 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001491
Tao Bao612336d2015-08-27 16:41:21 -07001492 // Subsequent lines are all individual transfer commands
1493 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1494 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001495 if (line_str.empty()) {
1496 continue;
1497 }
1498
Tao Baobaad2d42015-12-06 16:56:27 -08001499 params.tokens = android::base::Split(line_str, " ");
1500 params.cpos = 0;
1501 params.cmdname = params.tokens[params.cpos++].c_str();
1502 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001503
Tao Bao0940fe12015-08-27 16:41:21 -07001504 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001505 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001506 const_cast<char*>(params.cmdname), CompareCommandNames,
1507 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001508
Tao Bao0940fe12015-08-27 16:41:21 -07001509 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001510 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1511 goto pbiudone;
1512 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001513
Tao Bao0940fe12015-08-27 16:41:21 -07001514 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001515 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001516 goto pbiudone;
1517 }
1518
Sami Tolvanen90221202014-12-09 16:39:47 +00001519 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001520 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001521 failure_type = kFsyncFailure;
Tao Bao187efff2015-07-27 14:07:08 -07001522 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1523 goto pbiudone;
1524 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001525 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001526 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001527 }
1528 }
1529
Sami Tolvanen90221202014-12-09 16:39:47 +00001530 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001531 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001532
Tao Bao0940fe12015-08-27 16:41:21 -07001533 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tianjie Xudd874b12016-05-13 12:13:15 -07001534 fprintf(stderr, "stashed %zu blocks\n", params.stashed);
Tao Bao612336d2015-08-27 16:41:21 -07001535 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001536
Tianjie Xudd874b12016-05-13 12:13:15 -07001537 const char* partition = strrchr(blockdev_filename->data, '/');
1538 if (partition != nullptr && *(partition+1) != 0) {
1539 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1540 params.written * BLOCKSIZE);
1541 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1542 params.stashed * BLOCKSIZE);
1543 fflush(cmd_pipe);
1544 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001545 // Delete stash only after successfully completing the update, as it
1546 // may contain blocks needed to complete the update later.
1547 DeleteStash(params.stashbase);
1548 } else {
1549 fprintf(stderr, "verified partition contents; update may be resumed\n");
1550 }
1551
1552 rc = 0;
1553
1554pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001555 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001556 failure_type = kFsyncFailure;
Tao Baobaad2d42015-12-06 16:56:27 -08001557 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001558 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001559 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001560
Sami Tolvanen90221202014-12-09 16:39:47 +00001561 // Only delete the stash if the update cannot be resumed, or it's
1562 // a verification run and we created the stash.
1563 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1564 DeleteStash(params.stashbase);
1565 }
1566
Tianjie Xu16255832016-04-30 11:49:59 -07001567 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1568 state->cause_code = failure_type;
1569 }
1570
Sami Tolvanen90221202014-12-09 16:39:47 +00001571 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1572}
1573
1574// The transfer list is a text file containing commands to
1575// transfer data from one place to another on the target
1576// partition. We parse it and execute the commands in order:
1577//
1578// zero [rangeset]
1579// - fill the indicated blocks with zeros
1580//
1581// new [rangeset]
1582// - fill the blocks with data read from the new_data file
1583//
1584// erase [rangeset]
1585// - mark the given blocks as empty
1586//
1587// move <...>
1588// bsdiff <patchstart> <patchlen> <...>
1589// imgdiff <patchstart> <patchlen> <...>
1590// - read the source blocks, apply a patch (or not in the
1591// case of move), write result to target blocks. bsdiff or
1592// imgdiff specifies the type of patch; move means no patch
1593// at all.
1594//
1595// The format of <...> differs between versions 1 and 2;
1596// see the LoadSrcTgtVersion{1,2}() functions for a
1597// description of what's expected.
1598//
1599// stash <stash_id> <src_range>
1600// - (version 2+ only) load the given source range and stash
1601// the data in the given slot of the stash table.
1602//
Tao Baobaad2d42015-12-06 16:56:27 -08001603// free <stash_id>
1604// - (version 3+ only) free the given stash data.
1605//
Sami Tolvanen90221202014-12-09 16:39:47 +00001606// The creator of the transfer list will guarantee that no block
1607// is read (ie, used as the source for a patch or move) after it
1608// has been written.
1609//
1610// In version 2, the creator will guarantee that a given stash is
1611// loaded (with a stash command) before it's used in a
1612// move/bsdiff/imgdiff command.
1613//
1614// Within one command the source and target ranges may overlap so
1615// in general we need to read the entire source into memory before
1616// writing anything to the target blocks.
1617//
1618// All the patch data is concatenated into one patch_data file in
1619// the update package. It must be stored uncompressed because we
1620// memory-map it in directly from the archive. (Since patches are
1621// already compressed, we lose very little by not compressing
1622// their concatenation.)
1623//
1624// In version 3, commands that read data from the partition (i.e.
1625// move/bsdiff/imgdiff/stash) have one or more additional hashes
1626// before the range parameters, which are used to check if the
1627// command has already been completed and verify the integrity of
1628// the source data.
1629
1630Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001631 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001632 const Command commands[] = {
1633 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001634 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001635 { "free", PerformCommandFree },
1636 { "imgdiff", PerformCommandDiff },
1637 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001638 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001639 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001640 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001641 };
1642
1643 // Perform a dry run without writing to test if an update can proceed
1644 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001645 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001646}
1647
1648Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1649 const Command commands[] = {
1650 { "bsdiff", PerformCommandDiff },
1651 { "erase", PerformCommandErase },
1652 { "free", PerformCommandFree },
1653 { "imgdiff", PerformCommandDiff },
1654 { "move", PerformCommandMove },
1655 { "new", PerformCommandNew },
1656 { "stash", PerformCommandStash },
1657 { "zero", PerformCommandZero }
1658 };
1659
1660 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001661 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001662}
1663
Tao Bao0940fe12015-08-27 16:41:21 -07001664Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001665 Value* blockdev_filename;
1666 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001667
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001668 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001669 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001670 }
Tao Bao612336d2015-08-27 16:41:21 -07001671 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1672 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1673 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001674
1675 if (blockdev_filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001676 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string",
1677 name);
Tao Bao612336d2015-08-27 16:41:21 -07001678 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001679 }
1680 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001681 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001682 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001683 }
1684
Elliott Hughesbcabd092016-03-22 20:19:22 -07001685 android::base::unique_fd fd(ota_open(blockdev_filename->data, O_RDWR));
1686 if (fd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001687 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data,
1688 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001689 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001690 }
1691
Tao Bao612336d2015-08-27 16:41:21 -07001692 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001693 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001694
1695 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001696 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001697
Tao Bao612336d2015-08-27 16:41:21 -07001698 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001699 for (size_t i = 0; i < rs.count; ++i) {
1700 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001701 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data,
1702 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001703 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001704 }
1705
Tao Bao0940fe12015-08-27 16:41:21 -07001706 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001707 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001708 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001709 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001710 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001711 }
1712
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001713 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001714 }
1715 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001716 uint8_t digest[SHA_DIGEST_LENGTH];
1717 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001718
Tao Bao612336d2015-08-27 16:41:21 -07001719 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001720}
1721
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001722// This function checks if a device has been remounted R/W prior to an incremental
1723// OTA update. This is an common cause of update abortion. The function reads the
1724// 1st block of each partition and check for mounting time/count. It return string "t"
1725// if executes successfully and an empty string otherwise.
1726
1727Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1728 Value* arg_filename;
1729
1730 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1731 return nullptr;
1732 }
1733 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1734
1735 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001736 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001737 return StringValue(strdup(""));
1738 }
1739
Elliott Hughesbcabd092016-03-22 20:19:22 -07001740 android::base::unique_fd fd(ota_open(arg_filename->data, O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001741 if (fd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001742 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data,
1743 strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001744 return StringValue(strdup(""));
1745 }
1746
1747 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1748 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1749
1750 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001751 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data,
Tianjie Xu30bf4762015-12-15 11:47:30 -08001752 strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001753 return StringValue(strdup(""));
1754 }
1755
1756 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1757 // Super block starts from block 0, offset 0x400
1758 // 0x2C: len32 Mount time
1759 // 0x30: len32 Write time
1760 // 0x34: len16 Number of mounts since the last fsck
1761 // 0x38: len16 Magic signature 0xEF53
1762
1763 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1764 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1765
1766 if (mount_count > 0) {
1767 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1768 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1769 }
1770
1771 return StringValue(strdup("t"));
1772}
1773
1774
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001775Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1776 Value* arg_filename;
1777 Value* arg_ranges;
1778
1779 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1780 return NULL;
1781 }
1782
1783 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1784 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1785
1786 if (filename->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001787 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001788 return StringValue(strdup(""));
1789 }
1790 if (ranges->type != VAL_STRING) {
Tianjie Xu16255832016-04-30 11:49:59 -07001791 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001792 return StringValue(strdup(""));
1793 }
1794
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001795 // Output notice to log when recover is attempted
1796 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1797
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001798 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1799 fec::io fh(filename->data, O_RDWR);
1800
1801 if (!fh) {
Tianjie Xu16255832016-04-30 11:49:59 -07001802 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data,
1803 strerror(errno));
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001804 return StringValue(strdup(""));
1805 }
1806
1807 if (!fh.has_ecc() || !fh.has_verity()) {
Tianjie Xu16255832016-04-30 11:49:59 -07001808 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001809 return StringValue(strdup(""));
1810 }
1811
1812 fec_status status;
1813
1814 if (!fh.get_status(status)) {
Tianjie Xu16255832016-04-30 11:49:59 -07001815 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001816 return StringValue(strdup(""));
1817 }
1818
1819 RangeSet rs;
1820 parse_range(ranges->data, rs);
1821
1822 uint8_t buffer[BLOCKSIZE];
1823
1824 for (size_t i = 0; i < rs.count; ++i) {
1825 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1826 // Stay within the data area, libfec validates and corrects metadata
1827 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1828 continue;
1829 }
1830
1831 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tianjie Xu16255832016-04-30 11:49:59 -07001832 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1833 filename->data, j, strerror(errno));
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001834 return StringValue(strdup(""));
1835 }
1836
1837 // If we want to be able to recover from a situation where rewriting a corrected
1838 // block doesn't guarantee the same data will be returned when re-read later, we
1839 // can save a copy of corrected blocks to /cache. Note:
1840 //
1841 // 1. Maximum space required from /cache is the same as the maximum number of
1842 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1843 // this would be ~16 MiB, for example.
1844 //
1845 // 2. To find out if this block was corrupted, call fec_get_status after each
1846 // read and check if the errors field value has increased.
1847 }
1848 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001849 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001850 return StringValue(strdup("t"));
1851}
1852
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001853void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001854 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001855 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001856 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001857 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001858 RegisterFunction("range_sha1", RangeSha1Fn);
1859}