blob: c898ac6f615b820f20ec88c3a2d3c8a06fdc6457 [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
Tao Baoe6aa3322015-08-05 15:20:27 -070036#include <memory>
37#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070038#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070039
Elliott Hughes4b166f02015-12-04 15:30:20 -080040#include <android-base/parseint.h>
41#include <android-base/strings.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070042
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070043#include "applypatch/applypatch.h"
44#include "edify/expr.h"
Tianjie Xu30bf4762015-12-15 11:47:30 -080045#include "install.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070046#include "mincrypt/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000047#include "minzip/Hash.h"
Jed Estepf1fc48c2015-12-15 16:04:53 -080048#include "otafault/ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070049#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070050#include "unique_fd.h"
51#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070052
53#define BLOCKSIZE 4096
54
Sami Tolvanene82fa182015-06-10 15:58:12 +000055// Set this to 0 to interpret 'erase' transfers to mean do a
56// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
57// erase to mean fill the region with zeroes.
58#define DEBUG_ERASE 0
59
Sami Tolvanen90221202014-12-09 16:39:47 +000060#define STASH_DIRECTORY_BASE "/cache/recovery"
61#define STASH_DIRECTORY_MODE 0700
62#define STASH_FILE_MODE 0600
63
Tao Bao0940fe12015-08-27 16:41:21 -070064struct RangeSet {
65 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053066 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070067 std::vector<size_t> pos; // Actual limit is INT_MAX.
68};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070069
Tao Baobaad2d42015-12-06 16:56:27 -080070static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010071
Tao Baobaad2d42015-12-06 16:56:27 -080072 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070073 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010074 goto err;
75 }
76
Tao Baob15fd222015-09-24 11:10:51 -070077 size_t num;
78 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010079 goto err;
80 }
81
Tao Baob15fd222015-09-24 11:10:51 -070082 if (num == 0 || num % 2) {
83 goto err; // must be even
84 } else if (num != pieces.size() - 1) {
85 goto err;
86 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010087
Tao Bao0940fe12015-08-27 16:41:21 -070088 rs.pos.resize(num);
89 rs.count = num / 2;
90 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010091
Tao Bao0940fe12015-08-27 16:41:21 -070092 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070093 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
94 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010095 goto err;
96 }
97
Tao Baob15fd222015-09-24 11:10:51 -070098 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
99 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530100 goto err;
101 }
102
Tao Bao0940fe12015-08-27 16:41:21 -0700103 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530104 goto err; // empty or negative range
105 }
106
Tao Bao0940fe12015-08-27 16:41:21 -0700107 size_t sz = rs.pos[i+1] - rs.pos[i];
108 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530109 goto err; // overflow
110 }
111
Tao Bao0940fe12015-08-27 16:41:21 -0700112 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700113 }
114
Tao Bao0940fe12015-08-27 16:41:21 -0700115 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100116
117err:
Tao Baobaad2d42015-12-06 16:56:27 -0800118 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100119 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700120}
121
Tao Baoe6aa3322015-08-05 15:20:27 -0700122static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530123 for (size_t i = 0; i < r1.count; ++i) {
124 size_t r1_0 = r1.pos[i * 2];
125 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000126
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530127 for (size_t j = 0; j < r2.count; ++j) {
128 size_t r2_0 = r2.pos[j * 2];
129 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000130
Tao Baoc0f56ad2015-06-25 14:00:31 -0700131 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700132 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000133 }
134 }
135 }
136
Tao Baoe6aa3322015-08-05 15:20:27 -0700137 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000138}
139
140static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700141 size_t so_far = 0;
142 while (so_far < size) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800143 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700144 if (r == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700145 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000146 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700147 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700148 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700149 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000150 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700151}
152
Tao Bao612336d2015-08-27 16:41:21 -0700153static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
154 return read_all(fd, buffer.data(), size);
155}
156
Sami Tolvanen90221202014-12-09 16:39:47 +0000157static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700158 size_t written = 0;
159 while (written < size) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800160 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700161 if (w == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700162 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000163 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700164 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700165 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700166 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000167
Sami Tolvanen90221202014-12-09 16:39:47 +0000168 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700169}
170
Tao Bao612336d2015-08-27 16:41:21 -0700171static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
172 return write_all(fd, buffer.data(), size);
173}
174
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700175static bool check_lseek(int fd, off64_t offset, int whence) {
176 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
177 if (rc == -1) {
178 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
179 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700180 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700181 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700182}
183
Tao Bao612336d2015-08-27 16:41:21 -0700184static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700186 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700187
Tao Bao612336d2015-08-27 16:41:21 -0700188 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700189}
190
Tao Bao0940fe12015-08-27 16:41:21 -0700191struct RangeSinkState {
192 RangeSinkState(RangeSet& rs) : tgt(rs) { };
193
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700194 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700195 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530196 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700198};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700199
200static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700201 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202
Tao Bao0940fe12015-08-27 16:41:21 -0700203 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700204 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000205 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700206 }
207
208 ssize_t written = 0;
209 while (size > 0) {
210 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000211
212 if (rss->p_remain < write_now) {
213 write_now = rss->p_remain;
214 }
215
216 if (write_all(rss->fd, data, write_now) == -1) {
217 break;
218 }
219
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700220 data += write_now;
221 size -= write_now;
222
223 rss->p_remain -= write_now;
224 written += write_now;
225
226 if (rss->p_remain == 0) {
227 // move to the next block
228 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700229 if (rss->p_block < rss->tgt.count) {
230 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
231 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000232
Tao Bao0940fe12015-08-27 16:41:21 -0700233 if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700234 SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000235 break;
236 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700237 } else {
238 // we can't write any more; return how many bytes have
239 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000240 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700241 }
242 }
243 }
244
245 return written;
246}
247
248// All of the data for all the 'new' transfers is contained in one
249// file in the update package, concatenated together in the order in
250// which transfers.list will need it. We want to stream it out of the
251// archive (it's compressed) without writing it to a temp file, but we
252// can't write each section until it's that transfer's turn to go.
253//
254// To achieve this, we expand the new data from the archive in a
255// background thread, and block that threads 'receive uncompressed
256// data' function until the main thread has reached a point where we
257// want some new data to be written. We signal the background thread
258// with the destination for the data and block the main thread,
259// waiting for the background thread to complete writing that section.
260// Then it signals the main thread to wake up and goes back to
261// blocking waiting for a transfer.
262//
263// NewThreadInfo is the struct used to pass information back and forth
264// between the two threads. When the main thread wants some data
265// written, it sets rss to the destination location and signals the
266// condition. When the background thread is done writing, it clears
267// rss and signals the condition again.
268
Tao Bao0940fe12015-08-27 16:41:21 -0700269struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700270 ZipArchive* za;
271 const ZipEntry* entry;
272
273 RangeSinkState* rss;
274
275 pthread_mutex_t mu;
276 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700277};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700278
279static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700280 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700281
282 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700283 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700284 // data is wanted.
285 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700286 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287 pthread_cond_wait(&nti->cv, &nti->mu);
288 }
289 pthread_mutex_unlock(&nti->mu);
290
291 // At this point nti->rss is set, and we own it. The main
292 // thread is waiting for it to disappear from nti.
293 ssize_t written = RangeSinkWrite(data, size, nti->rss);
294 data += written;
295 size -= written;
296
Tao Bao0940fe12015-08-27 16:41:21 -0700297 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700298 // we have written all the bytes desired by this rss.
299
300 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700301 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700302 pthread_cond_broadcast(&nti->cv);
303 pthread_mutex_unlock(&nti->mu);
304 }
305 }
306
307 return true;
308}
309
310static void* unzip_new_data(void* cookie) {
311 NewThreadInfo* nti = (NewThreadInfo*) cookie;
312 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700313 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700314}
315
Tao Bao612336d2015-08-27 16:41:21 -0700316static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000317 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700318 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000319
Tao Bao0940fe12015-08-27 16:41:21 -0700320 for (size_t i = 0; i < src.count; ++i) {
321 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000322 return -1;
323 }
324
Tao Bao0940fe12015-08-27 16:41:21 -0700325 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000326
Tao Bao612336d2015-08-27 16:41:21 -0700327 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000328 return -1;
329 }
330
331 p += size;
332 }
333
334 return 0;
335}
336
Tao Bao612336d2015-08-27 16:41:21 -0700337static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
338 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000339
Tao Bao0940fe12015-08-27 16:41:21 -0700340 size_t p = 0;
341 for (size_t i = 0; i < tgt.count; ++i) {
342 if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000343 return -1;
344 }
345
Tao Bao0940fe12015-08-27 16:41:21 -0700346 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000347
Tao Bao612336d2015-08-27 16:41:21 -0700348 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000349 return -1;
350 }
351
352 p += size;
353 }
354
355 return 0;
356}
357
Tao Baobaad2d42015-12-06 16:56:27 -0800358// Parameters for transfer list command functions
359struct CommandParameters {
360 std::vector<std::string> tokens;
361 size_t cpos;
362 const char* cmdname;
363 const char* cmdline;
364 std::string freestash;
365 std::string stashbase;
366 bool canwrite;
367 int createdstash;
368 int fd;
369 bool foundwrites;
370 bool isunresumable;
371 int version;
372 size_t written;
373 NewThreadInfo nti;
374 pthread_t thread;
375 std::vector<uint8_t> buffer;
376 uint8_t* patch_start;
377};
378
Doug Zongker52ae67d2014-09-08 12:22:09 -0700379// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800380// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700381//
382// <src_range> <tgt_range>
383//
384// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700385// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700386
Tao Baobaad2d42015-12-06 16:56:27 -0800387static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700388 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800389
390 if (params.cpos + 1 >= params.tokens.size()) {
391 fprintf(stderr, "invalid parameters\n");
392 return -1;
393 }
394
Tao Bao612336d2015-08-27 16:41:21 -0700395 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700396 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800397 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700398
Tao Bao612336d2015-08-27 16:41:21 -0700399 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800400 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700401
Tao Bao612336d2015-08-27 16:41:21 -0700402 allocate(src.size * BLOCKSIZE, buffer);
403 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700404 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000405
Sami Tolvanen90221202014-12-09 16:39:47 +0000406 return rc;
407}
408
Tao Bao612336d2015-08-27 16:41:21 -0700409static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700410 const size_t blocks, bool printerror) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000411 uint8_t digest[SHA_DIGEST_SIZE];
Tao Bao612336d2015-08-27 16:41:21 -0700412 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000413
Tao Bao612336d2015-08-27 16:41:21 -0700414 SHA_hash(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000415
Tao Baoe6aa3322015-08-05 15:20:27 -0700416 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000417
Tao Bao0940fe12015-08-27 16:41:21 -0700418 if (hexdigest != expected) {
419 if (printerror) {
420 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
421 expected.c_str(), hexdigest.c_str());
422 }
423 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000424 }
425
Tao Bao0940fe12015-08-27 16:41:21 -0700426 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000427}
428
Tao Bao0940fe12015-08-27 16:41:21 -0700429static std::string GetStashFileName(const std::string& base, const std::string& id,
430 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700431 if (base.empty()) {
432 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000433 }
434
Tao Baoe6aa3322015-08-05 15:20:27 -0700435 std::string fn(STASH_DIRECTORY_BASE);
436 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000437
438 return fn;
439}
440
Tao Baoe6aa3322015-08-05 15:20:27 -0700441typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000442
443// Does a best effort enumeration of stash files. Ignores possible non-file
444// items in the stash directory and continues despite of errors. Calls the
445// 'callback' function for each file and passes 'data' to the function as a
446// parameter.
447
Tao Baoe6aa3322015-08-05 15:20:27 -0700448static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700449 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000450 return;
451 }
452
Tao Baoe6aa3322015-08-05 15:20:27 -0700453 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000454
Tao Bao0940fe12015-08-27 16:41:21 -0700455 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000456 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700457 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000458 }
459 return;
460 }
461
Tao Baoe6aa3322015-08-05 15:20:27 -0700462 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700463 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000464 if (item->d_type != DT_REG) {
465 continue;
466 }
467
Tao Baoe6aa3322015-08-05 15:20:27 -0700468 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000469 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000470 }
471}
472
Tao Baoe6aa3322015-08-05 15:20:27 -0700473static void UpdateFileSize(const std::string& fn, void* data) {
474 if (fn.empty() || !data) {
475 return;
476 }
477
Tao Bao0940fe12015-08-27 16:41:21 -0700478 struct stat sb;
479 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700480 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000481 return;
482 }
483
Tao Baoe6aa3322015-08-05 15:20:27 -0700484 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700485 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000486}
487
488// Deletes the stash directory and all files in it. Assumes that it only
489// contains files. There is nothing we can do about unlikely, but possible
490// errors, so they are merely logged.
491
Tao Bao0940fe12015-08-27 16:41:21 -0700492static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700493 if (!fn.empty()) {
494 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000495
Tao Baoe6aa3322015-08-05 15:20:27 -0700496 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
497 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000498 }
499 }
500}
501
Tao Baoe6aa3322015-08-05 15:20:27 -0700502static void DeletePartial(const std::string& fn, void* data) {
503 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000504 DeleteFile(fn, data);
505 }
506}
507
Tao Baoe6aa3322015-08-05 15:20:27 -0700508static void DeleteStash(const std::string& base) {
509 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000510 return;
511 }
512
Tao Baoe6aa3322015-08-05 15:20:27 -0700513 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000514
Tao Baoe6aa3322015-08-05 15:20:27 -0700515 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700516 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000517
Tao Baoe6aa3322015-08-05 15:20:27 -0700518 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000519 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700520 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000521 }
522 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000523}
524
Tao Bao0940fe12015-08-27 16:41:21 -0700525static int LoadStash(const std::string& base, const std::string& id, bool verify, size_t* blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700526 std::vector<uint8_t>& buffer, bool printnoent) {
527 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700528 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000529 }
530
Tao Bao0940fe12015-08-27 16:41:21 -0700531 size_t blockcount = 0;
532
Sami Tolvanen90221202014-12-09 16:39:47 +0000533 if (!blocks) {
534 blocks = &blockcount;
535 }
536
Tao Bao0940fe12015-08-27 16:41:21 -0700537 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000538
Tao Bao0940fe12015-08-27 16:41:21 -0700539 struct stat sb;
540 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000541
542 if (res == -1) {
543 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700544 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000545 }
Tao Bao0940fe12015-08-27 16:41:21 -0700546 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000547 }
548
Tao Baoe6aa3322015-08-05 15:20:27 -0700549 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000550
Tao Bao0940fe12015-08-27 16:41:21 -0700551 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700552 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700553 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
554 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000555 }
556
Tao Bao0940fe12015-08-27 16:41:21 -0700557 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY));
558 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000559
560 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700561 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700562 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000563 }
564
Tao Bao612336d2015-08-27 16:41:21 -0700565 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000566
Tao Bao612336d2015-08-27 16:41:21 -0700567 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700568 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000569 }
570
Tao Bao0940fe12015-08-27 16:41:21 -0700571 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000572
Tao Bao612336d2015-08-27 16:41:21 -0700573 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700574 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700575 DeleteFile(fn, nullptr);
576 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000577 }
578
Tao Bao0940fe12015-08-27 16:41:21 -0700579 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000580}
581
Tao Bao612336d2015-08-27 16:41:21 -0700582static int WriteStash(const std::string& base, const std::string& id, int blocks,
583 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
584 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700585 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000586 }
587
588 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
589 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700590 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000591 }
592
Tao Bao0940fe12015-08-27 16:41:21 -0700593 std::string fn = GetStashFileName(base, id, ".partial");
594 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000595
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100596 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700597 struct stat sb;
598 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100599
600 if (res == 0) {
601 // The file already exists and since the name is the hash of the contents,
602 // it's safe to assume the contents are identical (accidental hash collisions
603 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700604 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700605 *exists = true;
606 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100607 }
608
Tao Bao0940fe12015-08-27 16:41:21 -0700609 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100610 }
611
Tao Baoe6aa3322015-08-05 15:20:27 -0700612 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000613
Tao Bao0940fe12015-08-27 16:41:21 -0700614 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE));
615 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000616
617 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700618 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700619 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000620 }
621
622 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700623 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000624 }
625
Jed Estepf1fc48c2015-12-15 16:04:53 -0800626 if (ota_fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700627 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700628 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000629 }
630
Tao Baoe6aa3322015-08-05 15:20:27 -0700631 if (rename(fn.c_str(), cn.c_str()) == -1) {
632 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
633 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700634 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000635 }
636
Tao Bao0940fe12015-08-27 16:41:21 -0700637 std::string dname = GetStashFileName(base, "", "");
638 int dfd = TEMP_FAILURE_RETRY(open(dname.c_str(), O_RDONLY | O_DIRECTORY));
639 unique_fd dfd_holder(dfd);
Tao Baodc392262015-07-31 15:56:44 -0700640
641 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700642 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700643 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700644 }
645
Jed Estepf1fc48c2015-12-15 16:04:53 -0800646 if (ota_fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700647 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700648 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700649 }
650
Tao Bao0940fe12015-08-27 16:41:21 -0700651 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000652}
653
654// Creates a directory for storing stash files and checks if the /cache partition
655// hash enough space for the expected amount of blocks we need to store. Returns
656// >0 if we created the directory, zero if it existed already, and <0 of failure.
657
Tao Bao0940fe12015-08-27 16:41:21 -0700658static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
659 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700660 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000661 }
662
663 // Stash directory should be different for each partition to avoid conflicts
664 // when updating multiple partitions at the same time, so we use the hash of
665 // the block device name as the base directory
Tao Baoe6aa3322015-08-05 15:20:27 -0700666 SHA_CTX ctx;
Sami Tolvanen90221202014-12-09 16:39:47 +0000667 SHA_init(&ctx);
668 SHA_update(&ctx, blockdev, strlen(blockdev));
Tao Baoe6aa3322015-08-05 15:20:27 -0700669 const uint8_t* digest = SHA_final(&ctx);
670 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000671
Tao Baoe6aa3322015-08-05 15:20:27 -0700672 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700673 struct stat sb;
674 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000675
676 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700677 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
678 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000679 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700680 fprintf(stderr, "creating stash %s\n", dirname.c_str());
681 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000682
683 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700684 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
685 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000686 }
687
688 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
689 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700690 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000691 }
692
Tao Baoe6aa3322015-08-05 15:20:27 -0700693 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000694 }
695
Tao Baoe6aa3322015-08-05 15:20:27 -0700696 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000697
698 // If the directory already exists, calculate the space already allocated to
699 // stash files and check if there's enough for all required blocks. Delete any
700 // partially completed stash files first.
701
Tao Bao0940fe12015-08-27 16:41:21 -0700702 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700703 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704 EnumerateStash(dirname, UpdateFileSize, &size);
705
Tao Bao0940fe12015-08-27 16:41:21 -0700706 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000707
708 if (size > 0 && CacheSizeCheck(size) != 0) {
709 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700710 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000711 }
712
Tao Baoe6aa3322015-08-05 15:20:27 -0700713 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000714}
715
Tao Baobaad2d42015-12-06 16:56:27 -0800716static int SaveStash(CommandParameters& params, const std::string& base,
717 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000718
Tao Baobaad2d42015-12-06 16:56:27 -0800719 // <stash_id> <src_range>
720 if (params.cpos + 1 >= params.tokens.size()) {
721 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000722 return -1;
723 }
Tao Baobaad2d42015-12-06 16:56:27 -0800724 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000725
Tao Bao0940fe12015-08-27 16:41:21 -0700726 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700727 if (usehash && LoadStash(base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000728 // Stash file already exists and has expected contents. Do not
729 // read from source again, as the source may have been already
730 // overwritten during a previous attempt.
731 return 0;
732 }
733
Tao Bao34847b22015-09-08 11:05:49 -0700734 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800735 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700736
Tao Bao612336d2015-08-27 16:41:21 -0700737 allocate(src.size * BLOCKSIZE, buffer);
738 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000739 return -1;
740 }
Tao Bao34847b22015-09-08 11:05:49 -0700741 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000742
Tao Bao612336d2015-08-27 16:41:21 -0700743 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000744 // Source blocks have unexpected contents. If we actually need this
745 // data later, this is an unrecoverable error. However, the command
746 // that uses the data may have already completed previously, so the
747 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700748 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000749 return 0;
750 }
751
Tao Bao0940fe12015-08-27 16:41:21 -0700752 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tao Bao612336d2015-08-27 16:41:21 -0700753 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000754}
755
Tao Baobaad2d42015-12-06 16:56:27 -0800756static int FreeStash(const std::string& base, const std::string& id) {
757 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000758 return -1;
759 }
760
Tao Baobaad2d42015-12-06 16:56:27 -0800761 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700762 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000763
764 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700765}
766
Tao Bao612336d2015-08-27 16:41:21 -0700767static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
768 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700769 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700770 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700771 // may be the same buffer.
772
Tao Bao612336d2015-08-27 16:41:21 -0700773 const uint8_t* from = source.data();
774 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700775 size_t start = locs.size;
776 for (int i = locs.count-1; i >= 0; --i) {
777 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700778 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700779 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700780 blocks * BLOCKSIZE);
781 }
782}
783
784// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800785// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700786//
787// <tgt_range> <src_block_count> <src_range>
788// (loads data from source image only)
789//
790// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
791// (loads data from stashes only)
792//
793// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
794// (loads data from both source image and stashes)
795//
796// On return, buffer is filled with the loaded source data (rearranged
797// and combined with stashed data as necessary). buffer may be
798// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000799// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700800
Tao Baobaad2d42015-12-06 16:56:27 -0800801static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700802 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800803
804 // At least it needs to provide three parameters: <tgt_range>,
805 // <src_block_count> and "-"/<src_range>.
806 if (params.cpos + 2 >= params.tokens.size()) {
807 fprintf(stderr, "invalid parameters\n");
808 return -1;
809 }
810
Tao Bao612336d2015-08-27 16:41:21 -0700811 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800812 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700813
Tao Bao612336d2015-08-27 16:41:21 -0700814 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800815 const std::string& token = params.tokens[params.cpos++];
816 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
817 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
818 return -1;
819 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700820
Tao Bao612336d2015-08-27 16:41:21 -0700821 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700822
Tao Bao612336d2015-08-27 16:41:21 -0700823 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800824 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700825 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800826 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700827 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700828 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800829 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700830 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700831
Tao Bao34847b22015-09-08 11:05:49 -0700832 if (overlap) {
833 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700834 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000835
Sami Tolvanen90221202014-12-09 16:39:47 +0000836 if (res == -1) {
837 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700838 }
839
Tao Baobaad2d42015-12-06 16:56:27 -0800840 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000841 // no stashes, only source range
842 return 0;
843 }
844
Tao Bao612336d2015-08-27 16:41:21 -0700845 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800846 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700847 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700848 }
849
Tao Baobaad2d42015-12-06 16:56:27 -0800850 // <[stash_id:stash_range]>
851 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700852 // Each word is a an index into the stash table, a colon, and
853 // then a rangeset describing where in the source block that
854 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800855 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
856 if (tokens.size() != 2) {
857 fprintf(stderr, "invalid parameter\n");
858 return -1;
859 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000860
Tao Bao612336d2015-08-27 16:41:21 -0700861 std::vector<uint8_t> stash;
Tao Baobaad2d42015-12-06 16:56:27 -0800862 int res = LoadStash(stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000863
864 if (res == -1) {
865 // These source blocks will fail verification if used later, but we
866 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800867 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000868 continue;
869 }
870
Tao Bao612336d2015-08-27 16:41:21 -0700871 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800872 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000873
Tao Bao612336d2015-08-27 16:41:21 -0700874 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000875 }
876
877 return 0;
878}
879
Sami Tolvanen90221202014-12-09 16:39:47 +0000880// Do a source/target load for move/bsdiff/imgdiff in version 3.
881//
882// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
883// tells the function whether to expect separate source and targe block hashes, or
884// if they are both the same and only one hash should be expected, and
885// 'isunresumable', which receives a non-zero value if block verification fails in
886// a way that the update cannot be resumed anymore.
887//
888// If the function is unable to load the necessary blocks or their contents don't
889// match the hashes, the return value is -1 and the command should be aborted.
890//
891// If the return value is 1, the command has already been completed according to
892// the contents of the target blocks, and should not be performed again.
893//
894// If the return value is 0, source blocks have expected content and the command
895// can be performed.
896
Tao Bao34847b22015-09-08 11:05:49 -0700897static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700898 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000899
Tao Baobaad2d42015-12-06 16:56:27 -0800900 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000901 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700902 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000903 }
904
Tao Baobaad2d42015-12-06 16:56:27 -0800905 std::string srchash = params.tokens[params.cpos++];
906 std::string tgthash;
907
Sami Tolvanen90221202014-12-09 16:39:47 +0000908 if (onehash) {
909 tgthash = srchash;
910 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800911 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000912 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700913 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000914 }
Tao Baobaad2d42015-12-06 16:56:27 -0800915 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000916 }
917
Tao Baobaad2d42015-12-06 16:56:27 -0800918 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, params.stashbase,
919 &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700920 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000921 }
922
Tao Bao34847b22015-09-08 11:05:49 -0700923 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000924
Tao Bao612336d2015-08-27 16:41:21 -0700925 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700926 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 }
928
Tao Bao612336d2015-08-27 16:41:21 -0700929 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000930 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700931 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 }
933
Tao Bao0940fe12015-08-27 16:41:21 -0700934 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000935 // If source and target blocks overlap, stash the source blocks so we can
936 // resume from possible write errors
Tao Bao0940fe12015-08-27 16:41:21 -0700937 if (overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800938 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
939 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000940
Tao Bao0940fe12015-08-27 16:41:21 -0700941 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700942 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700943 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000944 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700945 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000946 }
947
948 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100949 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700950 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100951 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000952 }
953
954 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700955 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 }
957
Tao Bao612336d2015-08-27 16:41:21 -0700958 if (overlap && LoadStash(params.stashbase, srchash, true, nullptr, params.buffer, true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100959 // Overlapping source blocks were previously stashed, command can proceed.
960 // We are recovering from an interrupted command, so we don't know if the
961 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700962 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000963 }
964
965 // Valid source data not available, update cannot be resumed
966 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700967 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000968
Tao Bao0940fe12015-08-27 16:41:21 -0700969 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000970}
971
Tao Bao0940fe12015-08-27 16:41:21 -0700972static int PerformCommandMove(CommandParameters& params) {
973 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -0700974 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000975 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -0700976 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +0000977
Tao Bao0940fe12015-08-27 16:41:21 -0700978 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -0800979 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700980 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -0800981 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -0700982 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -0700983 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -0700984 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +0000985 }
986
987 if (status == -1) {
988 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700989 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000990 }
991
992 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700993 params.foundwrites = true;
994 } else if (params.foundwrites) {
995 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +0000996 }
997
Tao Bao0940fe12015-08-27 16:41:21 -0700998 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000999 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001000 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001001
Tao Bao0940fe12015-08-27 16:41:21 -07001002 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1003 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001004 }
1005 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001006 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001007 }
1008
1009 }
1010
Tao Baobaad2d42015-12-06 16:56:27 -08001011 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001012 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001013 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001014 }
1015
Tao Bao0940fe12015-08-27 16:41:21 -07001016 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001017
Tao Bao0940fe12015-08-27 16:41:21 -07001018 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001019}
1020
Tao Bao0940fe12015-08-27 16:41:21 -07001021static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001022 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001023 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001024}
1025
Tao Bao0940fe12015-08-27 16:41:21 -07001026static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001027 // <stash_id>
1028 if (params.cpos >= params.tokens.size()) {
1029 fprintf(stderr, "missing stash id in free command\n");
1030 return -1;
1031 }
1032
Tao Bao0940fe12015-08-27 16:41:21 -07001033 if (params.createdstash || params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -08001034 return FreeStash(params.stashbase, params.tokens[params.cpos++]);
Sami Tolvanen90221202014-12-09 16:39:47 +00001035 }
1036
1037 return 0;
1038}
1039
Tao Bao0940fe12015-08-27 16:41:21 -07001040static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001041
Tao Baobaad2d42015-12-06 16:56:27 -08001042 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001043 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001044 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001045 }
1046
Tao Bao0940fe12015-08-27 16:41:21 -07001047 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001048 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001049
Tao Bao0940fe12015-08-27 16:41:21 -07001050 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001051
Tao Bao612336d2015-08-27 16:41:21 -07001052 allocate(BLOCKSIZE, params.buffer);
1053 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001054
Tao Bao0940fe12015-08-27 16:41:21 -07001055 if (params.canwrite) {
1056 for (size_t i = 0; i < tgt.count; ++i) {
1057 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1058 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001059 }
1060
Tao Bao0940fe12015-08-27 16:41:21 -07001061 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1062 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1063 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001064 }
1065 }
1066 }
1067 }
1068
Tao Bao0940fe12015-08-27 16:41:21 -07001069 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001070 // Update only for the zero command, as the erase command will call
1071 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001072 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001073 }
1074
Tao Bao0940fe12015-08-27 16:41:21 -07001075 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001076}
1077
Tao Bao0940fe12015-08-27 16:41:21 -07001078static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001079
Tao Baobaad2d42015-12-06 16:56:27 -08001080 if (params.cpos >= params.tokens.size()) {
1081 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001082 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001083 }
1084
Tao Bao0940fe12015-08-27 16:41:21 -07001085 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001086 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Bao0940fe12015-08-27 16:41:21 -07001088 if (params.canwrite) {
1089 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001090
Tao Bao0940fe12015-08-27 16:41:21 -07001091 RangeSinkState rss(tgt);
1092 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001093 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001094 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001095
Tao Bao0940fe12015-08-27 16:41:21 -07001096 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1097 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001098 }
1099
Tao Bao0940fe12015-08-27 16:41:21 -07001100 pthread_mutex_lock(&params.nti.mu);
1101 params.nti.rss = &rss;
1102 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001103
Tao Bao0940fe12015-08-27 16:41:21 -07001104 while (params.nti.rss) {
1105 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001106 }
1107
Tao Bao0940fe12015-08-27 16:41:21 -07001108 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001109 }
1110
Tao Bao0940fe12015-08-27 16:41:21 -07001111 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Bao0940fe12015-08-27 16:41:21 -07001113 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001114}
1115
Tao Bao0940fe12015-08-27 16:41:21 -07001116static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001117
Tao Baobaad2d42015-12-06 16:56:27 -08001118 // <offset> <length>
1119 if (params.cpos + 1 >= params.tokens.size()) {
1120 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001121 return -1;
1122 }
1123
Tao Baobaad2d42015-12-06 16:56:27 -08001124 size_t offset;
1125 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1126 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001127 return -1;
1128 }
1129
Tao Baobaad2d42015-12-06 16:56:27 -08001130 size_t len;
1131 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1132 fprintf(stderr, "invalid patch offset\n");
1133 return -1;
1134 }
Tao Bao0940fe12015-08-27 16:41:21 -07001135
Tao Bao612336d2015-08-27 16:41:21 -07001136 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001137 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001138 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001139 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001140 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001141 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001142 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001143 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001144 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001145 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001146 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001147 }
1148
1149 if (status == -1) {
1150 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001151 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001152 }
1153
1154 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001155 params.foundwrites = true;
1156 } else if (params.foundwrites) {
1157 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001158 }
1159
Tao Bao0940fe12015-08-27 16:41:21 -07001160 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001161 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001162 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001163
Tao Bao0940fe12015-08-27 16:41:21 -07001164 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001165 patch_value.type = VAL_BLOB;
1166 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001167 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001168
Tao Bao0940fe12015-08-27 16:41:21 -07001169 RangeSinkState rss(tgt);
1170 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001171 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001172 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001173
Tao Bao0940fe12015-08-27 16:41:21 -07001174 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1175 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001176 }
1177
Tao Bao0940fe12015-08-27 16:41:21 -07001178 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001179 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001180 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001181 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001182 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1183 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001184 }
1185
1186 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001187 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001188 fprintf(stderr, "range sink underrun?\n");
1189 }
1190 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001191 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001192 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001193 }
1194 }
1195
Tao Baobaad2d42015-12-06 16:56:27 -08001196 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001197 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001198 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001199 }
1200
Tao Bao0940fe12015-08-27 16:41:21 -07001201 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Bao0940fe12015-08-27 16:41:21 -07001203 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001204}
1205
Tao Bao0940fe12015-08-27 16:41:21 -07001206static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001207 if (DEBUG_ERASE) {
1208 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001209 }
1210
Tao Bao0940fe12015-08-27 16:41:21 -07001211 struct stat sb;
1212 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001213 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001214 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001215 }
1216
Tao Bao0940fe12015-08-27 16:41:21 -07001217 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001218 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001219 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001220 }
1221
Tao Baobaad2d42015-12-06 16:56:27 -08001222 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001223 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001224 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001225 }
1226
Tao Bao0940fe12015-08-27 16:41:21 -07001227 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001228 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001229
Tao Bao0940fe12015-08-27 16:41:21 -07001230 if (params.canwrite) {
1231 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001232
Tao Bao0940fe12015-08-27 16:41:21 -07001233 for (size_t i = 0; i < tgt.count; ++i) {
1234 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001235 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001236 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001237 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001238 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001239
Tao Bao0940fe12015-08-27 16:41:21 -07001240 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001241 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001242 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001243 }
1244 }
1245 }
1246
Tao Bao0940fe12015-08-27 16:41:21 -07001247 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001248}
1249
1250// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001251typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001252
Tao Bao612336d2015-08-27 16:41:21 -07001253struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 const char* name;
1255 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001256};
Sami Tolvanen90221202014-12-09 16:39:47 +00001257
1258// CompareCommands and CompareCommandNames are for the hash table
1259
1260static int CompareCommands(const void* c1, const void* c2) {
1261 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1262}
1263
1264static int CompareCommandNames(const void* c1, const void* c2) {
1265 return strcmp(((const Command*) c1)->name, (const char*) c2);
1266}
1267
1268// HashString is used to hash command names for the hash table
1269
1270static unsigned int HashString(const char *s) {
1271 unsigned int hash = 0;
1272 if (s) {
1273 while (*s) {
1274 hash = hash * 33 + *s++;
1275 }
1276 }
1277 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001278}
1279
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001280// args:
1281// - block device (or file) to modify in-place
1282// - transfer list (blob)
1283// - new data stream (filename within package.zip)
1284// - patch stream (filename within package.zip, must be uncompressed)
1285
Tao Bao0940fe12015-08-27 16:41:21 -07001286static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1287 const Command* commands, size_t cmdcount, bool dryrun) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001288 CommandParameters params;
Sami Tolvanen90221202014-12-09 16:39:47 +00001289 memset(&params, 0, sizeof(params));
1290 params.canwrite = !dryrun;
1291
1292 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001293
Tao Bao612336d2015-08-27 16:41:21 -07001294 Value* blockdev_filename = nullptr;
1295 Value* transfer_list_value = nullptr;
1296 Value* new_data_fn = nullptr;
1297 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001298 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001299 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001300 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001301 }
Tao Bao612336d2015-08-27 16:41:21 -07001302 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1303 FreeValue);
1304 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1305 FreeValue);
1306 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1307 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001308
1309 if (blockdev_filename->type != VAL_STRING) {
1310 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001311 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001312 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001313 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001314 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001315 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001316 }
1317 if (new_data_fn->type != VAL_STRING) {
1318 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001319 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001320 }
1321 if (patch_data_fn->type != VAL_STRING) {
1322 ErrorAbort(state, "patch_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001323 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001324 }
1325
Tao Bao612336d2015-08-27 16:41:21 -07001326 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001327
Tao Bao0940fe12015-08-27 16:41:21 -07001328 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001329 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001330 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001331
Tao Bao612336d2015-08-27 16:41:21 -07001332 FILE* cmd_pipe = ui->cmd_pipe;
1333 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001334
Tao Bao0940fe12015-08-27 16:41:21 -07001335 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001336 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001337 }
1338
Tao Bao612336d2015-08-27 16:41:21 -07001339 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001340 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001341 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001342 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001343 }
1344
Sami Tolvanen90221202014-12-09 16:39:47 +00001345 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001346 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001347 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001348 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001349 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001350 }
1351
Sami Tolvanen90221202014-12-09 16:39:47 +00001352 params.fd = TEMP_FAILURE_RETRY(open(blockdev_filename->data, O_RDWR));
Tao Bao612336d2015-08-27 16:41:21 -07001353 unique_fd fd_holder(params.fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001354
Sami Tolvanen90221202014-12-09 16:39:47 +00001355 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001356 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001357 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001358 }
1359
Sami Tolvanen90221202014-12-09 16:39:47 +00001360 if (params.canwrite) {
1361 params.nti.za = za;
1362 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001363
Tao Bao0940fe12015-08-27 16:41:21 -07001364 pthread_mutex_init(&params.nti.mu, nullptr);
1365 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001366 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001367 pthread_attr_init(&attr);
1368 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1369
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001370 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1371 if (error != 0) {
1372 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001373 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001374 }
1375 }
1376
Tao Baobaad2d42015-12-06 16:56:27 -08001377 // Copy all the lines in transfer_list_value into std::string for
1378 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001379 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1380 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001381 if (lines.size() < 2) {
1382 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1383 return StringValue(strdup(""));
1384 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001385
Sami Tolvanen90221202014-12-09 16:39:47 +00001386 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001387 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001388 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1389 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001390 }
1391
Sami Tolvanen90221202014-12-09 16:39:47 +00001392 fprintf(stderr, "blockimg version is %d\n", params.version);
1393
1394 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001395 int total_blocks;
1396 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001397 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1398 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001399 }
1400
1401 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001402 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001403 }
1404
Tao Bao612336d2015-08-27 16:41:21 -07001405 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001406 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001407 if (lines.size() < 4) {
1408 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1409 return StringValue(strdup(""));
1410 }
1411
Sami Tolvanen90221202014-12-09 16:39:47 +00001412 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001413 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001414
Sami Tolvanen90221202014-12-09 16:39:47 +00001415 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001416 int stash_max_blocks;
1417 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001418 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1419 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001420 }
1421
Tao Baob15fd222015-09-24 11:10:51 -07001422 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001423 if (res == -1) {
1424 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001425 }
Tao Bao612336d2015-08-27 16:41:21 -07001426
Tao Baob15fd222015-09-24 11:10:51 -07001427 params.createdstash = res;
1428
Tao Bao612336d2015-08-27 16:41:21 -07001429 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001430 }
1431
Sami Tolvanen90221202014-12-09 16:39:47 +00001432 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001433 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1434 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001435
Tao Bao0940fe12015-08-27 16:41:21 -07001436 for (size_t i = 0; i < cmdcount; ++i) {
1437 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001438 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1439 }
1440
Tao Bao612336d2015-08-27 16:41:21 -07001441 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001442
Tao Bao612336d2015-08-27 16:41:21 -07001443 // Subsequent lines are all individual transfer commands
1444 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1445 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001446 if (line_str.empty()) {
1447 continue;
1448 }
1449
Tao Baobaad2d42015-12-06 16:56:27 -08001450 params.tokens = android::base::Split(line_str, " ");
1451 params.cpos = 0;
1452 params.cmdname = params.tokens[params.cpos++].c_str();
1453 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001454
Tao Bao0940fe12015-08-27 16:41:21 -07001455 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001456 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001457 const_cast<char*>(params.cmdname), CompareCommandNames,
1458 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001459
Tao Bao0940fe12015-08-27 16:41:21 -07001460 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001461 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1462 goto pbiudone;
1463 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001464
Tao Bao0940fe12015-08-27 16:41:21 -07001465 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001466 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001467 goto pbiudone;
1468 }
1469
Sami Tolvanen90221202014-12-09 16:39:47 +00001470 if (params.canwrite) {
Jed Estepf1fc48c2015-12-15 16:04:53 -08001471 if (ota_fsync(params.fd) == -1) {
Tao Bao187efff2015-07-27 14:07:08 -07001472 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1473 goto pbiudone;
1474 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001475 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001476 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001477 }
1478 }
1479
Sami Tolvanen90221202014-12-09 16:39:47 +00001480 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001481 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001482
Tao Bao0940fe12015-08-27 16:41:21 -07001483 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tao Bao612336d2015-08-27 16:41:21 -07001484 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001485
Sami Tolvanen90221202014-12-09 16:39:47 +00001486 // Delete stash only after successfully completing the update, as it
1487 // may contain blocks needed to complete the update later.
1488 DeleteStash(params.stashbase);
1489 } else {
1490 fprintf(stderr, "verified partition contents; update may be resumed\n");
1491 }
1492
1493 rc = 0;
1494
1495pbiudone:
Jed Estepf1fc48c2015-12-15 16:04:53 -08001496 if (ota_fsync(params.fd) == -1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001497 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001498 }
Tao Baobaad2d42015-12-06 16:56:27 -08001499 // params.fd will be automatically closed because of the fd_holder above.
Sami Tolvanen90221202014-12-09 16:39:47 +00001500
Sami Tolvanen90221202014-12-09 16:39:47 +00001501 // Only delete the stash if the update cannot be resumed, or it's
1502 // a verification run and we created the stash.
1503 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1504 DeleteStash(params.stashbase);
1505 }
1506
Sami Tolvanen90221202014-12-09 16:39:47 +00001507 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1508}
1509
1510// The transfer list is a text file containing commands to
1511// transfer data from one place to another on the target
1512// partition. We parse it and execute the commands in order:
1513//
1514// zero [rangeset]
1515// - fill the indicated blocks with zeros
1516//
1517// new [rangeset]
1518// - fill the blocks with data read from the new_data file
1519//
1520// erase [rangeset]
1521// - mark the given blocks as empty
1522//
1523// move <...>
1524// bsdiff <patchstart> <patchlen> <...>
1525// imgdiff <patchstart> <patchlen> <...>
1526// - read the source blocks, apply a patch (or not in the
1527// case of move), write result to target blocks. bsdiff or
1528// imgdiff specifies the type of patch; move means no patch
1529// at all.
1530//
1531// The format of <...> differs between versions 1 and 2;
1532// see the LoadSrcTgtVersion{1,2}() functions for a
1533// description of what's expected.
1534//
1535// stash <stash_id> <src_range>
1536// - (version 2+ only) load the given source range and stash
1537// the data in the given slot of the stash table.
1538//
Tao Baobaad2d42015-12-06 16:56:27 -08001539// free <stash_id>
1540// - (version 3+ only) free the given stash data.
1541//
Sami Tolvanen90221202014-12-09 16:39:47 +00001542// The creator of the transfer list will guarantee that no block
1543// is read (ie, used as the source for a patch or move) after it
1544// has been written.
1545//
1546// In version 2, the creator will guarantee that a given stash is
1547// loaded (with a stash command) before it's used in a
1548// move/bsdiff/imgdiff command.
1549//
1550// Within one command the source and target ranges may overlap so
1551// in general we need to read the entire source into memory before
1552// writing anything to the target blocks.
1553//
1554// All the patch data is concatenated into one patch_data file in
1555// the update package. It must be stored uncompressed because we
1556// memory-map it in directly from the archive. (Since patches are
1557// already compressed, we lose very little by not compressing
1558// their concatenation.)
1559//
1560// In version 3, commands that read data from the partition (i.e.
1561// move/bsdiff/imgdiff/stash) have one or more additional hashes
1562// before the range parameters, which are used to check if the
1563// command has already been completed and verify the integrity of
1564// the source data.
1565
1566Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001567 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001568 const Command commands[] = {
1569 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001570 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001571 { "free", PerformCommandFree },
1572 { "imgdiff", PerformCommandDiff },
1573 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001574 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001575 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001576 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001577 };
1578
1579 // Perform a dry run without writing to test if an update can proceed
1580 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001581 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001582}
1583
1584Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1585 const Command commands[] = {
1586 { "bsdiff", PerformCommandDiff },
1587 { "erase", PerformCommandErase },
1588 { "free", PerformCommandFree },
1589 { "imgdiff", PerformCommandDiff },
1590 { "move", PerformCommandMove },
1591 { "new", PerformCommandNew },
1592 { "stash", PerformCommandStash },
1593 { "zero", PerformCommandZero }
1594 };
1595
1596 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001597 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001598}
1599
Tao Bao0940fe12015-08-27 16:41:21 -07001600Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001601 Value* blockdev_filename;
1602 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001603
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001604 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001605 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001606 }
Tao Bao612336d2015-08-27 16:41:21 -07001607 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1608 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1609 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001610
1611 if (blockdev_filename->type != VAL_STRING) {
1612 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001613 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001614 }
1615 if (ranges->type != VAL_STRING) {
1616 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001617 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001618 }
1619
Tao Bao612336d2015-08-27 16:41:21 -07001620 int fd = open(blockdev_filename->data, O_RDWR);
1621 unique_fd fd_holder(fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001622 if (fd < 0) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001623 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001624 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001625 }
1626
Tao Bao612336d2015-08-27 16:41:21 -07001627 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001628 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001629
1630 SHA_CTX ctx;
1631 SHA_init(&ctx);
1632
Tao Bao612336d2015-08-27 16:41:21 -07001633 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001634 for (size_t i = 0; i < rs.count; ++i) {
1635 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001636 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1637 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001638 }
1639
Tao Bao0940fe12015-08-27 16:41:21 -07001640 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001641 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1642 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001643 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001644 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001645 }
1646
Tao Bao612336d2015-08-27 16:41:21 -07001647 SHA_update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001648 }
1649 }
Tao Bao612336d2015-08-27 16:41:21 -07001650 const uint8_t* digest = SHA_final(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001651
Tao Bao612336d2015-08-27 16:41:21 -07001652 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001653}
1654
Tianjie Xu30bf4762015-12-15 11:47:30 -08001655// This function checks if a device has been remounted R/W prior to an incremental
1656// OTA update. This is an common cause of update abortion. The function reads the
1657// 1st block of each partition and check for mounting time/count. It return string "t"
1658// if executes successfully and an empty string otherwise.
1659
1660Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1661 Value* arg_filename;
1662
1663 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1664 return nullptr;
1665 }
1666 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1667
1668 if (filename->type != VAL_STRING) {
1669 ErrorAbort(state, "filename argument to %s must be string", name);
1670 return StringValue(strdup(""));
1671 }
1672
1673 int fd = open(arg_filename->data, O_RDONLY);
1674 unique_fd fd_holder(fd);
1675 if (fd == -1) {
1676 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1677 return StringValue(strdup(""));
1678 }
1679
1680 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1681 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1682
1683 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1684 ErrorAbort(state, "failed to read %s: %s", arg_filename->data,
1685 strerror(errno));
1686 return StringValue(strdup(""));
1687 }
1688
1689 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1690 // Super block starts from block 0, offset 0x400
1691 // 0x2C: len32 Mount time
1692 // 0x30: len32 Write time
1693 // 0x34: len16 Number of mounts since the last fsck
1694 // 0x38: len16 Magic signature 0xEF53
1695
1696 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1697 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1698
1699 if (mount_count > 0) {
1700 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1701 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1702 }
1703
1704 return StringValue(strdup("t"));
1705}
1706
1707
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001708Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1709 Value* arg_filename;
1710 Value* arg_ranges;
1711
1712 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1713 return NULL;
1714 }
1715
1716 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1717 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1718
1719 if (filename->type != VAL_STRING) {
1720 ErrorAbort(state, "filename argument to %s must be string", name);
1721 return StringValue(strdup(""));
1722 }
1723 if (ranges->type != VAL_STRING) {
1724 ErrorAbort(state, "ranges argument to %s must be string", name);
1725 return StringValue(strdup(""));
1726 }
1727
Tianjie Xub686ba22015-12-09 15:29:45 -08001728 // Output notice to log when recover is attempted
1729 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1730
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001731 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1732 fec::io fh(filename->data, O_RDWR);
1733
1734 if (!fh) {
1735 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1736 return StringValue(strdup(""));
1737 }
1738
1739 if (!fh.has_ecc() || !fh.has_verity()) {
1740 ErrorAbort(state, "unable to use metadata to correct errors");
1741 return StringValue(strdup(""));
1742 }
1743
1744 fec_status status;
1745
1746 if (!fh.get_status(status)) {
1747 ErrorAbort(state, "failed to read FEC status");
1748 return StringValue(strdup(""));
1749 }
1750
1751 RangeSet rs;
1752 parse_range(ranges->data, rs);
1753
1754 uint8_t buffer[BLOCKSIZE];
1755
1756 for (size_t i = 0; i < rs.count; ++i) {
1757 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1758 // Stay within the data area, libfec validates and corrects metadata
1759 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1760 continue;
1761 }
1762
1763 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001764 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001765 j, strerror(errno));
1766 return StringValue(strdup(""));
1767 }
1768
1769 // If we want to be able to recover from a situation where rewriting a corrected
1770 // block doesn't guarantee the same data will be returned when re-read later, we
1771 // can save a copy of corrected blocks to /cache. Note:
1772 //
1773 // 1. Maximum space required from /cache is the same as the maximum number of
1774 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1775 // this would be ~16 MiB, for example.
1776 //
1777 // 2. To find out if this block was corrupted, call fec_get_status after each
1778 // read and check if the errors field value has increased.
1779 }
1780 }
Tianjie Xub686ba22015-12-09 15:29:45 -08001781 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001782 return StringValue(strdup("t"));
1783}
1784
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001785void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001786 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001787 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001788 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu30bf4762015-12-15 11:47:30 -08001789 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001790 RegisterFunction("range_sha1", RangeSha1Fn);
1791}