blob: d67af664a4b3101fc44c44370341a8da15593172 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu01889352016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070043
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070044#include "applypatch/applypatch.h"
45#include "edify/expr.h"
Tianjie Xu30bf4762015-12-15 11:47:30 -080046#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080047#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000048#include "minzip/Hash.h"
Jed Estepf73abf32015-12-15 16:04:53 -080049#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070050#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070051#include "unique_fd.h"
52#include "updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070053
54#define BLOCKSIZE 4096
55
Sami Tolvanene82fa182015-06-10 15:58:12 +000056// Set this to 0 to interpret 'erase' transfers to mean do a
57// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
58// erase to mean fill the region with zeroes.
59#define DEBUG_ERASE 0
60
Sami Tolvanen90221202014-12-09 16:39:47 +000061#define STASH_DIRECTORY_BASE "/cache/recovery"
62#define STASH_DIRECTORY_MODE 0700
63#define STASH_FILE_MODE 0600
64
Tao Bao0940fe12015-08-27 16:41:21 -070065struct RangeSet {
66 size_t count; // Limit is INT_MAX.
Shrinivas Sahukara6153df2015-08-19 13:01:45 +053067 size_t size;
Tao Bao0940fe12015-08-27 16:41:21 -070068 std::vector<size_t> pos; // Actual limit is INT_MAX.
69};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070070
Tianjie Xu01889352016-03-22 18:08:12 -070071static std::map<std::string, RangeSet> stash_map;
72
Tao Baobaad2d42015-12-06 16:56:27 -080073static void parse_range(const std::string& range_text, RangeSet& rs) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010074
Tao Baobaad2d42015-12-06 16:56:27 -080075 std::vector<std::string> pieces = android::base::Split(range_text, ",");
Tao Bao0940fe12015-08-27 16:41:21 -070076 if (pieces.size() < 3) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010077 goto err;
78 }
79
Tao Baob15fd222015-09-24 11:10:51 -070080 size_t num;
81 if (!android::base::ParseUint(pieces[0].c_str(), &num, static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010082 goto err;
83 }
84
Tao Baob15fd222015-09-24 11:10:51 -070085 if (num == 0 || num % 2) {
86 goto err; // must be even
87 } else if (num != pieces.size() - 1) {
88 goto err;
89 }
Sami Tolvanenf2bac042015-05-12 12:48:46 +010090
Tao Bao0940fe12015-08-27 16:41:21 -070091 rs.pos.resize(num);
92 rs.count = num / 2;
93 rs.size = 0;
Sami Tolvanenf2bac042015-05-12 12:48:46 +010094
Tao Bao0940fe12015-08-27 16:41:21 -070095 for (size_t i = 0; i < num; i += 2) {
Tao Baob15fd222015-09-24 11:10:51 -070096 if (!android::base::ParseUint(pieces[i+1].c_str(), &rs.pos[i],
97 static_cast<size_t>(INT_MAX))) {
Sami Tolvanenf2bac042015-05-12 12:48:46 +010098 goto err;
99 }
100
Tao Baob15fd222015-09-24 11:10:51 -0700101 if (!android::base::ParseUint(pieces[i+2].c_str(), &rs.pos[i+1],
102 static_cast<size_t>(INT_MAX))) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530103 goto err;
104 }
105
Tao Bao0940fe12015-08-27 16:41:21 -0700106 if (rs.pos[i] >= rs.pos[i+1]) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530107 goto err; // empty or negative range
108 }
109
Tao Bao0940fe12015-08-27 16:41:21 -0700110 size_t sz = rs.pos[i+1] - rs.pos[i];
111 if (rs.size > SIZE_MAX - sz) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530112 goto err; // overflow
113 }
114
Tao Bao0940fe12015-08-27 16:41:21 -0700115 rs.size += sz;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700116 }
117
Tao Bao0940fe12015-08-27 16:41:21 -0700118 return;
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100119
120err:
Tao Baobaad2d42015-12-06 16:56:27 -0800121 fprintf(stderr, "failed to parse range '%s'\n", range_text.c_str());
Sami Tolvanenf2bac042015-05-12 12:48:46 +0100122 exit(1);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700123}
124
Tao Baoe6aa3322015-08-05 15:20:27 -0700125static bool range_overlaps(const RangeSet& r1, const RangeSet& r2) {
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530126 for (size_t i = 0; i < r1.count; ++i) {
127 size_t r1_0 = r1.pos[i * 2];
128 size_t r1_1 = r1.pos[i * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000129
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530130 for (size_t j = 0; j < r2.count; ++j) {
131 size_t r2_0 = r2.pos[j * 2];
132 size_t r2_1 = r2.pos[j * 2 + 1];
Sami Tolvanen90221202014-12-09 16:39:47 +0000133
Tao Baoc0f56ad2015-06-25 14:00:31 -0700134 if (!(r2_0 >= r1_1 || r1_0 >= r2_1)) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700135 return true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000136 }
137 }
138 }
139
Tao Baoe6aa3322015-08-05 15:20:27 -0700140 return false;
Sami Tolvanen90221202014-12-09 16:39:47 +0000141}
142
143static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700144 size_t so_far = 0;
145 while (so_far < size) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800146 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700147 if (r == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700148 fprintf(stderr, "read failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000149 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700150 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700151 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700152 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000153 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700154}
155
Tao Bao612336d2015-08-27 16:41:21 -0700156static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
157 return read_all(fd, buffer.data(), size);
158}
159
Sami Tolvanen90221202014-12-09 16:39:47 +0000160static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700161 size_t written = 0;
162 while (written < size) {
Jed Estepf1fc48c2015-12-15 16:04:53 -0800163 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700164 if (w == -1) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700165 fprintf(stderr, "write failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000166 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700167 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700168 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700169 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000170
Sami Tolvanen90221202014-12-09 16:39:47 +0000171 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700172}
173
Tao Bao612336d2015-08-27 16:41:21 -0700174static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
175 return write_all(fd, buffer.data(), size);
176}
177
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700178static bool check_lseek(int fd, off64_t offset, int whence) {
179 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
180 if (rc == -1) {
181 fprintf(stderr, "lseek64 failed: %s\n", strerror(errno));
182 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700183 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700184 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700185}
186
Tao Bao612336d2015-08-27 16:41:21 -0700187static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700188 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700189 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700190
Tao Bao612336d2015-08-27 16:41:21 -0700191 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700192}
193
Tao Bao0940fe12015-08-27 16:41:21 -0700194struct RangeSinkState {
195 RangeSinkState(RangeSet& rs) : tgt(rs) { };
196
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197 int fd;
Tao Bao0940fe12015-08-27 16:41:21 -0700198 const RangeSet& tgt;
Shrinivas Sahukara6153df2015-08-19 13:01:45 +0530199 size_t p_block;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700200 size_t p_remain;
Tao Bao0940fe12015-08-27 16:41:21 -0700201};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202
203static ssize_t RangeSinkWrite(const uint8_t* data, ssize_t size, void* token) {
Tao Bao0940fe12015-08-27 16:41:21 -0700204 RangeSinkState* rss = reinterpret_cast<RangeSinkState*>(token);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700205
Tao Bao0940fe12015-08-27 16:41:21 -0700206 if (rss->p_remain == 0) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700207 fprintf(stderr, "range sink write overrun");
Sami Tolvanen90221202014-12-09 16:39:47 +0000208 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700209 }
210
211 ssize_t written = 0;
212 while (size > 0) {
213 size_t write_now = size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000214
215 if (rss->p_remain < write_now) {
216 write_now = rss->p_remain;
217 }
218
219 if (write_all(rss->fd, data, write_now) == -1) {
220 break;
221 }
222
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700223 data += write_now;
224 size -= write_now;
225
226 rss->p_remain -= write_now;
227 written += write_now;
228
229 if (rss->p_remain == 0) {
230 // move to the next block
231 ++rss->p_block;
Tao Bao0940fe12015-08-27 16:41:21 -0700232 if (rss->p_block < rss->tgt.count) {
233 rss->p_remain = (rss->tgt.pos[rss->p_block * 2 + 1] -
234 rss->tgt.pos[rss->p_block * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000235
Tao Bao0940fe12015-08-27 16:41:21 -0700236 if (!check_lseek(rss->fd, (off64_t)rss->tgt.pos[rss->p_block*2] * BLOCKSIZE,
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700237 SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000238 break;
239 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700240 } else {
241 // we can't write any more; return how many bytes have
242 // been written so far.
Sami Tolvanen90221202014-12-09 16:39:47 +0000243 break;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700244 }
245 }
246 }
247
248 return written;
249}
250
251// All of the data for all the 'new' transfers is contained in one
252// file in the update package, concatenated together in the order in
253// which transfers.list will need it. We want to stream it out of the
254// archive (it's compressed) without writing it to a temp file, but we
255// can't write each section until it's that transfer's turn to go.
256//
257// To achieve this, we expand the new data from the archive in a
258// background thread, and block that threads 'receive uncompressed
259// data' function until the main thread has reached a point where we
260// want some new data to be written. We signal the background thread
261// with the destination for the data and block the main thread,
262// waiting for the background thread to complete writing that section.
263// Then it signals the main thread to wake up and goes back to
264// blocking waiting for a transfer.
265//
266// NewThreadInfo is the struct used to pass information back and forth
267// between the two threads. When the main thread wants some data
268// written, it sets rss to the destination location and signals the
269// condition. When the background thread is done writing, it clears
270// rss and signals the condition again.
271
Tao Bao0940fe12015-08-27 16:41:21 -0700272struct NewThreadInfo {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700273 ZipArchive* za;
274 const ZipEntry* entry;
275
276 RangeSinkState* rss;
277
278 pthread_mutex_t mu;
279 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700280};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700281
282static bool receive_new_data(const unsigned char* data, int size, void* cookie) {
Tao Bao0940fe12015-08-27 16:41:21 -0700283 NewThreadInfo* nti = reinterpret_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700284
285 while (size > 0) {
Tao Bao0940fe12015-08-27 16:41:21 -0700286 // Wait for nti->rss to be non-null, indicating some of this
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287 // data is wanted.
288 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700289 while (nti->rss == nullptr) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700290 pthread_cond_wait(&nti->cv, &nti->mu);
291 }
292 pthread_mutex_unlock(&nti->mu);
293
294 // At this point nti->rss is set, and we own it. The main
295 // thread is waiting for it to disappear from nti.
296 ssize_t written = RangeSinkWrite(data, size, nti->rss);
297 data += written;
298 size -= written;
299
Tao Bao0940fe12015-08-27 16:41:21 -0700300 if (nti->rss->p_block == nti->rss->tgt.count) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700301 // we have written all the bytes desired by this rss.
302
303 pthread_mutex_lock(&nti->mu);
Tao Bao0940fe12015-08-27 16:41:21 -0700304 nti->rss = nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700305 pthread_cond_broadcast(&nti->cv);
306 pthread_mutex_unlock(&nti->mu);
307 }
308 }
309
310 return true;
311}
312
313static void* unzip_new_data(void* cookie) {
314 NewThreadInfo* nti = (NewThreadInfo*) cookie;
315 mzProcessZipEntryContents(nti->za, nti->entry, receive_new_data, nti);
Tao Bao0940fe12015-08-27 16:41:21 -0700316 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700317}
318
Tao Bao612336d2015-08-27 16:41:21 -0700319static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000320 size_t p = 0;
Tao Bao612336d2015-08-27 16:41:21 -0700321 uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000322
Tao Bao0940fe12015-08-27 16:41:21 -0700323 for (size_t i = 0; i < src.count; ++i) {
324 if (!check_lseek(fd, (off64_t) src.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000325 return -1;
326 }
327
Tao Bao0940fe12015-08-27 16:41:21 -0700328 size_t size = (src.pos[i * 2 + 1] - src.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000329
Tao Bao612336d2015-08-27 16:41:21 -0700330 if (read_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000331 return -1;
332 }
333
334 p += size;
335 }
336
337 return 0;
338}
339
Tao Bao612336d2015-08-27 16:41:21 -0700340static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
341 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000342
Tao Bao0940fe12015-08-27 16:41:21 -0700343 size_t p = 0;
344 for (size_t i = 0; i < tgt.count; ++i) {
345 if (!check_lseek(fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000346 return -1;
347 }
348
Tao Bao0940fe12015-08-27 16:41:21 -0700349 size_t size = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000350
Tao Bao612336d2015-08-27 16:41:21 -0700351 if (write_all(fd, data + p, size) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000352 return -1;
353 }
354
355 p += size;
356 }
357
358 return 0;
359}
360
Tao Baobaad2d42015-12-06 16:56:27 -0800361// Parameters for transfer list command functions
362struct CommandParameters {
363 std::vector<std::string> tokens;
364 size_t cpos;
365 const char* cmdname;
366 const char* cmdline;
367 std::string freestash;
368 std::string stashbase;
369 bool canwrite;
370 int createdstash;
371 int fd;
372 bool foundwrites;
373 bool isunresumable;
374 int version;
375 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700376 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800377 NewThreadInfo nti;
378 pthread_t thread;
379 std::vector<uint8_t> buffer;
380 uint8_t* patch_start;
381};
382
Doug Zongker52ae67d2014-09-08 12:22:09 -0700383// Do a source/target load for move/bsdiff/imgdiff in version 1.
Tao Baobaad2d42015-12-06 16:56:27 -0800384// We expect to parse the remainder of the parameter tokens as:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700385//
386// <src_range> <tgt_range>
387//
388// The source range is loaded into the provided buffer, reallocating
Tao Bao34847b22015-09-08 11:05:49 -0700389// it to make it larger if necessary.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700390
Tao Baobaad2d42015-12-06 16:56:27 -0800391static int LoadSrcTgtVersion1(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700392 std::vector<uint8_t>& buffer, int fd) {
Tao Baobaad2d42015-12-06 16:56:27 -0800393
394 if (params.cpos + 1 >= params.tokens.size()) {
395 fprintf(stderr, "invalid parameters\n");
396 return -1;
397 }
398
Tao Bao612336d2015-08-27 16:41:21 -0700399 // <src_range>
Tao Bao0940fe12015-08-27 16:41:21 -0700400 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800401 parse_range(params.tokens[params.cpos++], src);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700402
Tao Bao612336d2015-08-27 16:41:21 -0700403 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800404 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700405
Tao Bao612336d2015-08-27 16:41:21 -0700406 allocate(src.size * BLOCKSIZE, buffer);
407 int rc = ReadBlocks(src, buffer, fd);
Tao Bao0940fe12015-08-27 16:41:21 -0700408 src_blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000409
Sami Tolvanen90221202014-12-09 16:39:47 +0000410 return rc;
411}
412
Tao Bao612336d2015-08-27 16:41:21 -0700413static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700414 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800415 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700416 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000417
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800418 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000419
Tao Baoe6aa3322015-08-05 15:20:27 -0700420 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000421
Tao Bao0940fe12015-08-27 16:41:21 -0700422 if (hexdigest != expected) {
423 if (printerror) {
424 fprintf(stderr, "failed to verify blocks (expected %s, read %s)\n",
425 expected.c_str(), hexdigest.c_str());
426 }
427 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000428 }
429
Tao Bao0940fe12015-08-27 16:41:21 -0700430 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000431}
432
Tao Bao0940fe12015-08-27 16:41:21 -0700433static std::string GetStashFileName(const std::string& base, const std::string& id,
434 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700435 if (base.empty()) {
436 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000437 }
438
Tao Baoe6aa3322015-08-05 15:20:27 -0700439 std::string fn(STASH_DIRECTORY_BASE);
440 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000441
442 return fn;
443}
444
Tao Baoe6aa3322015-08-05 15:20:27 -0700445typedef void (*StashCallback)(const std::string&, void*);
Sami Tolvanen90221202014-12-09 16:39:47 +0000446
447// Does a best effort enumeration of stash files. Ignores possible non-file
448// items in the stash directory and continues despite of errors. Calls the
449// 'callback' function for each file and passes 'data' to the function as a
450// parameter.
451
Tao Baoe6aa3322015-08-05 15:20:27 -0700452static void EnumerateStash(const std::string& dirname, StashCallback callback, void* data) {
Tao Bao0940fe12015-08-27 16:41:21 -0700453 if (dirname.empty() || callback == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000454 return;
455 }
456
Tao Baoe6aa3322015-08-05 15:20:27 -0700457 std::unique_ptr<DIR, int(*)(DIR*)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000458
Tao Bao0940fe12015-08-27 16:41:21 -0700459 if (directory == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000460 if (errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700461 fprintf(stderr, "opendir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000462 }
463 return;
464 }
465
Tao Baoe6aa3322015-08-05 15:20:27 -0700466 struct dirent* item;
Tao Bao0940fe12015-08-27 16:41:21 -0700467 while ((item = readdir(directory.get())) != nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000468 if (item->d_type != DT_REG) {
469 continue;
470 }
471
Tao Baoe6aa3322015-08-05 15:20:27 -0700472 std::string fn = dirname + "/" + std::string(item->d_name);
Sami Tolvanen90221202014-12-09 16:39:47 +0000473 callback(fn, data);
Sami Tolvanen90221202014-12-09 16:39:47 +0000474 }
475}
476
Tao Baoe6aa3322015-08-05 15:20:27 -0700477static void UpdateFileSize(const std::string& fn, void* data) {
478 if (fn.empty() || !data) {
479 return;
480 }
481
Tao Bao0940fe12015-08-27 16:41:21 -0700482 struct stat sb;
483 if (stat(fn.c_str(), &sb) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700484 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000485 return;
486 }
487
Tao Baoe6aa3322015-08-05 15:20:27 -0700488 int* size = reinterpret_cast<int*>(data);
Tao Bao0940fe12015-08-27 16:41:21 -0700489 *size += sb.st_size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000490}
491
492// Deletes the stash directory and all files in it. Assumes that it only
493// contains files. There is nothing we can do about unlikely, but possible
494// errors, so they are merely logged.
495
Tao Bao0940fe12015-08-27 16:41:21 -0700496static void DeleteFile(const std::string& fn, void* /* data */) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700497 if (!fn.empty()) {
498 fprintf(stderr, "deleting %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000499
Tao Baoe6aa3322015-08-05 15:20:27 -0700500 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
501 fprintf(stderr, "unlink \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000502 }
503 }
504}
505
Tao Baoe6aa3322015-08-05 15:20:27 -0700506static void DeletePartial(const std::string& fn, void* data) {
507 if (android::base::EndsWith(fn, ".partial")) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000508 DeleteFile(fn, data);
509 }
510}
511
Tao Baoe6aa3322015-08-05 15:20:27 -0700512static void DeleteStash(const std::string& base) {
513 if (base.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000514 return;
515 }
516
Tao Baoe6aa3322015-08-05 15:20:27 -0700517 fprintf(stderr, "deleting stash %s\n", base.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000518
Tao Baoe6aa3322015-08-05 15:20:27 -0700519 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700520 EnumerateStash(dirname, DeleteFile, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000521
Tao Baoe6aa3322015-08-05 15:20:27 -0700522 if (rmdir(dirname.c_str()) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000523 if (errno != ENOENT && errno != ENOTDIR) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700524 fprintf(stderr, "rmdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000525 }
526 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000527}
528
Tianjie Xu01889352016-03-22 18:08:12 -0700529static int LoadStash(CommandParameters& params, const std::string& base, const std::string& id,
530 bool verify, size_t* blocks, std::vector<uint8_t>& buffer, bool printnoent) {
531 // In verify mode, if source range_set was saved for the given hash,
532 // check contents in the source blocks first. If the check fails,
533 // search for the stashed files on /cache as usual.
534 if (!params.canwrite) {
535 if (stash_map.find(id) != stash_map.end()) {
536 const RangeSet& src = stash_map[id];
537 allocate(src.size * BLOCKSIZE, buffer);
538
539 if (ReadBlocks(src, buffer, params.fd) == -1) {
540 fprintf(stderr, "failed to read source blocks in stash map.\n");
541 return -1;
542 }
543 if (VerifyBlocks(id, buffer, src.size, true) != 0) {
544 fprintf(stderr, "failed to verify loaded source blocks in stash map.\n");
545 return -1;
546 }
547 return 0;
548 }
549 }
550
Tao Bao612336d2015-08-27 16:41:21 -0700551 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700552 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000553 }
554
Tao Bao0940fe12015-08-27 16:41:21 -0700555 size_t blockcount = 0;
556
Sami Tolvanen90221202014-12-09 16:39:47 +0000557 if (!blocks) {
558 blocks = &blockcount;
559 }
560
Tao Bao0940fe12015-08-27 16:41:21 -0700561 std::string fn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000562
Tao Bao0940fe12015-08-27 16:41:21 -0700563 struct stat sb;
564 int res = stat(fn.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000565
566 if (res == -1) {
567 if (errno != ENOENT || printnoent) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700568 fprintf(stderr, "stat \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +0000569 }
Tao Bao0940fe12015-08-27 16:41:21 -0700570 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000571 }
572
Tao Baoe6aa3322015-08-05 15:20:27 -0700573 fprintf(stderr, " loading %s\n", fn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000574
Tao Bao0940fe12015-08-27 16:41:21 -0700575 if ((sb.st_size % BLOCKSIZE) != 0) {
Tao Baoba9a42a2015-06-23 23:23:33 -0700576 fprintf(stderr, "%s size %" PRId64 " not multiple of block size %d",
Tao Bao0940fe12015-08-27 16:41:21 -0700577 fn.c_str(), static_cast<int64_t>(sb.st_size), BLOCKSIZE);
578 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000579 }
580
Tao Bao0940fe12015-08-27 16:41:21 -0700581 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_RDONLY));
582 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000583
584 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700585 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700586 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000587 }
588
Tao Bao612336d2015-08-27 16:41:21 -0700589 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000590
Tao Bao612336d2015-08-27 16:41:21 -0700591 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700592 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000593 }
594
Tao Bao0940fe12015-08-27 16:41:21 -0700595 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000596
Tao Bao612336d2015-08-27 16:41:21 -0700597 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700598 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700599 DeleteFile(fn, nullptr);
600 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000601 }
602
Tao Bao0940fe12015-08-27 16:41:21 -0700603 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000604}
605
Tao Bao612336d2015-08-27 16:41:21 -0700606static int WriteStash(const std::string& base, const std::string& id, int blocks,
607 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
608 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700609 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000610 }
611
612 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
613 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700614 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000615 }
616
Tao Bao0940fe12015-08-27 16:41:21 -0700617 std::string fn = GetStashFileName(base, id, ".partial");
618 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000619
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100620 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700621 struct stat sb;
622 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100623
624 if (res == 0) {
625 // The file already exists and since the name is the hash of the contents,
626 // it's safe to assume the contents are identical (accidental hash collisions
627 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700628 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700629 *exists = true;
630 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100631 }
632
Tao Bao0940fe12015-08-27 16:41:21 -0700633 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100634 }
635
Tao Baoe6aa3322015-08-05 15:20:27 -0700636 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000637
Tao Bao0940fe12015-08-27 16:41:21 -0700638 int fd = TEMP_FAILURE_RETRY(open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE));
639 unique_fd fd_holder(fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000640
641 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700642 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700643 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000644 }
645
646 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700647 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000648 }
649
Jed Estepf1fc48c2015-12-15 16:04:53 -0800650 if (ota_fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700651 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700652 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000653 }
654
Tao Baoe6aa3322015-08-05 15:20:27 -0700655 if (rename(fn.c_str(), cn.c_str()) == -1) {
656 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
657 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700658 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000659 }
660
Tao Bao0940fe12015-08-27 16:41:21 -0700661 std::string dname = GetStashFileName(base, "", "");
662 int dfd = TEMP_FAILURE_RETRY(open(dname.c_str(), O_RDONLY | O_DIRECTORY));
663 unique_fd dfd_holder(dfd);
Tao Baodc392262015-07-31 15:56:44 -0700664
665 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700666 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700667 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700668 }
669
Jed Estepf1fc48c2015-12-15 16:04:53 -0800670 if (ota_fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700671 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700672 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700673 }
674
Tao Bao0940fe12015-08-27 16:41:21 -0700675 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000676}
677
678// Creates a directory for storing stash files and checks if the /cache partition
679// hash enough space for the expected amount of blocks we need to store. Returns
680// >0 if we created the directory, zero if it existed already, and <0 of failure.
681
Tao Bao0940fe12015-08-27 16:41:21 -0700682static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
683 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700684 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000685 }
686
687 // Stash directory should be different for each partition to avoid conflicts
688 // when updating multiple partitions at the same time, so we use the hash of
689 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800690 uint8_t digest[SHA_DIGEST_LENGTH];
691 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700692 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000693
Tao Baoe6aa3322015-08-05 15:20:27 -0700694 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700695 struct stat sb;
696 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000697
698 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700699 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
700 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000701 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700702 fprintf(stderr, "creating stash %s\n", dirname.c_str());
703 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000704
705 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700706 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
707 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000708 }
709
710 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
711 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700712 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000713 }
714
Tao Baoe6aa3322015-08-05 15:20:27 -0700715 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000716 }
717
Tao Baoe6aa3322015-08-05 15:20:27 -0700718 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000719
720 // If the directory already exists, calculate the space already allocated to
721 // stash files and check if there's enough for all required blocks. Delete any
722 // partially completed stash files first.
723
Tao Bao0940fe12015-08-27 16:41:21 -0700724 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700725 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000726 EnumerateStash(dirname, UpdateFileSize, &size);
727
Tao Bao0940fe12015-08-27 16:41:21 -0700728 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000729
730 if (size > 0 && CacheSizeCheck(size) != 0) {
731 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700732 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000733 }
734
Tao Baoe6aa3322015-08-05 15:20:27 -0700735 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000736}
737
Tao Baobaad2d42015-12-06 16:56:27 -0800738static int SaveStash(CommandParameters& params, const std::string& base,
739 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000740
Tao Baobaad2d42015-12-06 16:56:27 -0800741 // <stash_id> <src_range>
742 if (params.cpos + 1 >= params.tokens.size()) {
743 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000744 return -1;
745 }
Tao Baobaad2d42015-12-06 16:56:27 -0800746 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000747
Tao Bao0940fe12015-08-27 16:41:21 -0700748 size_t blocks = 0;
Tianjie Xu01889352016-03-22 18:08:12 -0700749 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 // Stash file already exists and has expected contents. Do not
751 // read from source again, as the source may have been already
752 // overwritten during a previous attempt.
753 return 0;
754 }
755
Tao Bao34847b22015-09-08 11:05:49 -0700756 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800757 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700758
Tao Bao612336d2015-08-27 16:41:21 -0700759 allocate(src.size * BLOCKSIZE, buffer);
760 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000761 return -1;
762 }
Tao Bao34847b22015-09-08 11:05:49 -0700763 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000764
Tao Bao612336d2015-08-27 16:41:21 -0700765 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000766 // Source blocks have unexpected contents. If we actually need this
767 // data later, this is an unrecoverable error. However, the command
768 // that uses the data may have already completed previously, so the
769 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700770 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000771 return 0;
772 }
773
Tianjie Xu01889352016-03-22 18:08:12 -0700774 // In verify mode, save source range_set instead of stashing blocks.
775 if (!params.canwrite && usehash) {
776 stash_map[id] = src;
777 return 0;
778 }
779
Tao Bao0940fe12015-08-27 16:41:21 -0700780 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tianjie Xudd874b12016-05-13 12:13:15 -0700781 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700782 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000783}
784
Tao Baobaad2d42015-12-06 16:56:27 -0800785static int FreeStash(const std::string& base, const std::string& id) {
786 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000787 return -1;
788 }
789
Tao Baobaad2d42015-12-06 16:56:27 -0800790 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700791 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000792
793 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700794}
795
Tao Bao612336d2015-08-27 16:41:21 -0700796static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
797 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700798 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700799 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700800 // may be the same buffer.
801
Tao Bao612336d2015-08-27 16:41:21 -0700802 const uint8_t* from = source.data();
803 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700804 size_t start = locs.size;
805 for (int i = locs.count-1; i >= 0; --i) {
806 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700807 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700808 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700809 blocks * BLOCKSIZE);
810 }
811}
812
813// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800814// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700815//
816// <tgt_range> <src_block_count> <src_range>
817// (loads data from source image only)
818//
819// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
820// (loads data from stashes only)
821//
822// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
823// (loads data from both source image and stashes)
824//
825// On return, buffer is filled with the loaded source data (rearranged
826// and combined with stashed data as necessary). buffer may be
827// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000828// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700829
Tao Baobaad2d42015-12-06 16:56:27 -0800830static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700831 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800832
833 // At least it needs to provide three parameters: <tgt_range>,
834 // <src_block_count> and "-"/<src_range>.
835 if (params.cpos + 2 >= params.tokens.size()) {
836 fprintf(stderr, "invalid parameters\n");
837 return -1;
838 }
839
Tao Bao612336d2015-08-27 16:41:21 -0700840 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800841 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700842
Tao Bao612336d2015-08-27 16:41:21 -0700843 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800844 const std::string& token = params.tokens[params.cpos++];
845 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
846 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
847 return -1;
848 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700849
Tao Bao612336d2015-08-27 16:41:21 -0700850 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700851
Tao Bao612336d2015-08-27 16:41:21 -0700852 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800853 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700854 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800855 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700856 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700857 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800858 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700859 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700860
Tao Bao34847b22015-09-08 11:05:49 -0700861 if (overlap) {
862 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700863 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000864
Sami Tolvanen90221202014-12-09 16:39:47 +0000865 if (res == -1) {
866 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700867 }
868
Tao Baobaad2d42015-12-06 16:56:27 -0800869 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000870 // no stashes, only source range
871 return 0;
872 }
873
Tao Bao612336d2015-08-27 16:41:21 -0700874 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800875 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700876 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700877 }
878
Tao Baobaad2d42015-12-06 16:56:27 -0800879 // <[stash_id:stash_range]>
880 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700881 // Each word is a an index into the stash table, a colon, and
882 // then a rangeset describing where in the source block that
883 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800884 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
885 if (tokens.size() != 2) {
886 fprintf(stderr, "invalid parameter\n");
887 return -1;
888 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000889
Tao Bao612336d2015-08-27 16:41:21 -0700890 std::vector<uint8_t> stash;
Tianjie Xu01889352016-03-22 18:08:12 -0700891 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000892
893 if (res == -1) {
894 // These source blocks will fail verification if used later, but we
895 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800896 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000897 continue;
898 }
899
Tao Bao612336d2015-08-27 16:41:21 -0700900 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800901 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000902
Tao Bao612336d2015-08-27 16:41:21 -0700903 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000904 }
905
906 return 0;
907}
908
Sami Tolvanen90221202014-12-09 16:39:47 +0000909// Do a source/target load for move/bsdiff/imgdiff in version 3.
910//
911// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
912// tells the function whether to expect separate source and targe block hashes, or
913// if they are both the same and only one hash should be expected, and
914// 'isunresumable', which receives a non-zero value if block verification fails in
915// a way that the update cannot be resumed anymore.
916//
917// If the function is unable to load the necessary blocks or their contents don't
918// match the hashes, the return value is -1 and the command should be aborted.
919//
920// If the return value is 1, the command has already been completed according to
921// the contents of the target blocks, and should not be performed again.
922//
923// If the return value is 0, source blocks have expected content and the command
924// can be performed.
925
Tao Bao34847b22015-09-08 11:05:49 -0700926static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700927 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000928
Tao Baobaad2d42015-12-06 16:56:27 -0800929 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000930 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700931 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000932 }
933
Tao Baobaad2d42015-12-06 16:56:27 -0800934 std::string srchash = params.tokens[params.cpos++];
935 std::string tgthash;
936
Sami Tolvanen90221202014-12-09 16:39:47 +0000937 if (onehash) {
938 tgthash = srchash;
939 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800940 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000941 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700942 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000943 }
Tao Baobaad2d42015-12-06 16:56:27 -0800944 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000945 }
946
Tao Baobaad2d42015-12-06 16:56:27 -0800947 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd, params.stashbase,
948 &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700949 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000950 }
951
Tao Bao34847b22015-09-08 11:05:49 -0700952 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000953
Tao Bao612336d2015-08-27 16:41:21 -0700954 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700955 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 }
957
Tao Bao612336d2015-08-27 16:41:21 -0700958 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000959 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700960 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000961 }
962
Tao Bao0940fe12015-08-27 16:41:21 -0700963 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000964 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu01889352016-03-22 18:08:12 -0700965 // resume from possible write errors. In verify mode, we can skip stashing
966 // because the source blocks won't be overwritten.
967 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -0800968 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
969 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000970
Tao Bao0940fe12015-08-27 16:41:21 -0700971 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700972 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700973 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000974 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700975 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000976 }
977
Tianjie Xudd874b12016-05-13 12:13:15 -0700978 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +0000979 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100980 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700981 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100982 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000983 }
984
985 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700986 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000987 }
988
Tianjie Xu01889352016-03-22 18:08:12 -0700989 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
990 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100991 // Overlapping source blocks were previously stashed, command can proceed.
992 // We are recovering from an interrupted command, so we don't know if the
993 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700994 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000995 }
996
997 // Valid source data not available, update cannot be resumed
998 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700999 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +00001000
Tao Bao0940fe12015-08-27 16:41:21 -07001001 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001002}
1003
Tao Bao0940fe12015-08-27 16:41:21 -07001004static int PerformCommandMove(CommandParameters& params) {
1005 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001006 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001007 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001008 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001009
Tao Bao0940fe12015-08-27 16:41:21 -07001010 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001011 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001012 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001013 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001014 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001015 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001016 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001017 }
1018
1019 if (status == -1) {
1020 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001021 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001022 }
1023
1024 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001025 params.foundwrites = true;
1026 } else if (params.foundwrites) {
1027 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001028 }
1029
Tao Bao0940fe12015-08-27 16:41:21 -07001030 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001031 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001032 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001033
Tao Bao0940fe12015-08-27 16:41:21 -07001034 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1035 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001036 }
1037 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001038 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001039 }
1040
1041 }
1042
Tao Baobaad2d42015-12-06 16:56:27 -08001043 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001044 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001045 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001046 }
1047
Tao Bao0940fe12015-08-27 16:41:21 -07001048 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001049
Tao Bao0940fe12015-08-27 16:41:21 -07001050 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001051}
1052
Tao Bao0940fe12015-08-27 16:41:21 -07001053static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001054 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001055 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001056}
1057
Tao Bao0940fe12015-08-27 16:41:21 -07001058static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001059 // <stash_id>
1060 if (params.cpos >= params.tokens.size()) {
1061 fprintf(stderr, "missing stash id in free command\n");
1062 return -1;
1063 }
1064
Tianjie Xu01889352016-03-22 18:08:12 -07001065 const std::string& id = params.tokens[params.cpos++];
1066
1067 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1068 stash_map.erase(id);
1069 return 0;
1070 }
1071
Tao Bao0940fe12015-08-27 16:41:21 -07001072 if (params.createdstash || params.canwrite) {
Tianjie Xu01889352016-03-22 18:08:12 -07001073 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001074 }
1075
1076 return 0;
1077}
1078
Tao Bao0940fe12015-08-27 16:41:21 -07001079static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001080
Tao Baobaad2d42015-12-06 16:56:27 -08001081 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001082 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001083 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001084 }
1085
Tao Bao0940fe12015-08-27 16:41:21 -07001086 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001087 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001088
Tao Bao0940fe12015-08-27 16:41:21 -07001089 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001090
Tao Bao612336d2015-08-27 16:41:21 -07001091 allocate(BLOCKSIZE, params.buffer);
1092 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001093
Tao Bao0940fe12015-08-27 16:41:21 -07001094 if (params.canwrite) {
1095 for (size_t i = 0; i < tgt.count; ++i) {
1096 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1097 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001098 }
1099
Tao Bao0940fe12015-08-27 16:41:21 -07001100 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1101 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1102 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001103 }
1104 }
1105 }
1106 }
1107
Tao Bao0940fe12015-08-27 16:41:21 -07001108 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001109 // Update only for the zero command, as the erase command will call
1110 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001111 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112 }
1113
Tao Bao0940fe12015-08-27 16:41:21 -07001114 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001115}
1116
Tao Bao0940fe12015-08-27 16:41:21 -07001117static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001118
Tao Baobaad2d42015-12-06 16:56:27 -08001119 if (params.cpos >= params.tokens.size()) {
1120 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001121 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001122 }
1123
Tao Bao0940fe12015-08-27 16:41:21 -07001124 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001125 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001126
Tao Bao0940fe12015-08-27 16:41:21 -07001127 if (params.canwrite) {
1128 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001129
Tao Bao0940fe12015-08-27 16:41:21 -07001130 RangeSinkState rss(tgt);
1131 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001132 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001133 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001134
Tao Bao0940fe12015-08-27 16:41:21 -07001135 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1136 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001137 }
1138
Tao Bao0940fe12015-08-27 16:41:21 -07001139 pthread_mutex_lock(&params.nti.mu);
1140 params.nti.rss = &rss;
1141 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001142
Tao Bao0940fe12015-08-27 16:41:21 -07001143 while (params.nti.rss) {
1144 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001145 }
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001148 }
1149
Tao Bao0940fe12015-08-27 16:41:21 -07001150 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001151
Tao Bao0940fe12015-08-27 16:41:21 -07001152 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001153}
1154
Tao Bao0940fe12015-08-27 16:41:21 -07001155static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001156
Tao Baobaad2d42015-12-06 16:56:27 -08001157 // <offset> <length>
1158 if (params.cpos + 1 >= params.tokens.size()) {
1159 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001160 return -1;
1161 }
1162
Tao Baobaad2d42015-12-06 16:56:27 -08001163 size_t offset;
1164 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1165 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001166 return -1;
1167 }
1168
Tao Baobaad2d42015-12-06 16:56:27 -08001169 size_t len;
1170 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1171 fprintf(stderr, "invalid patch offset\n");
1172 return -1;
1173 }
Tao Bao0940fe12015-08-27 16:41:21 -07001174
Tao Bao612336d2015-08-27 16:41:21 -07001175 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001176 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001177 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001178 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001179 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001180 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001181 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001182 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001183 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001184 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001185 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001186 }
1187
1188 if (status == -1) {
1189 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001190 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001191 }
1192
1193 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001194 params.foundwrites = true;
1195 } else if (params.foundwrites) {
1196 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001197 }
1198
Tao Bao0940fe12015-08-27 16:41:21 -07001199 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001200 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001201 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Bao0940fe12015-08-27 16:41:21 -07001203 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001204 patch_value.type = VAL_BLOB;
1205 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001206 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001207
Tao Bao0940fe12015-08-27 16:41:21 -07001208 RangeSinkState rss(tgt);
1209 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001210 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001211 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212
Tao Bao0940fe12015-08-27 16:41:21 -07001213 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1214 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001215 }
1216
Tao Bao0940fe12015-08-27 16:41:21 -07001217 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001218 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001219 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001220 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001221 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1222 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001223 }
1224
1225 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001226 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001227 fprintf(stderr, "range sink underrun?\n");
1228 }
1229 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001230 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001231 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001232 }
1233 }
1234
Tao Baobaad2d42015-12-06 16:56:27 -08001235 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001236 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001237 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001238 }
1239
Tao Bao0940fe12015-08-27 16:41:21 -07001240 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001241
Tao Bao0940fe12015-08-27 16:41:21 -07001242 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001243}
1244
Tao Bao0940fe12015-08-27 16:41:21 -07001245static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001246 if (DEBUG_ERASE) {
1247 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001248 }
1249
Tao Bao0940fe12015-08-27 16:41:21 -07001250 struct stat sb;
1251 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001252 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001253 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 }
1255
Tao Bao0940fe12015-08-27 16:41:21 -07001256 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001257 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001258 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001259 }
1260
Tao Baobaad2d42015-12-06 16:56:27 -08001261 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001262 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001263 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001264 }
1265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001267 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001268
Tao Bao0940fe12015-08-27 16:41:21 -07001269 if (params.canwrite) {
1270 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001271
Tao Bao0940fe12015-08-27 16:41:21 -07001272 for (size_t i = 0; i < tgt.count; ++i) {
1273 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001274 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001275 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001276 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001277 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001278
Tao Bao0940fe12015-08-27 16:41:21 -07001279 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001280 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001281 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001282 }
1283 }
1284 }
1285
Tao Bao0940fe12015-08-27 16:41:21 -07001286 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001287}
1288
1289// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001290typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001291
Tao Bao612336d2015-08-27 16:41:21 -07001292struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001293 const char* name;
1294 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001295};
Sami Tolvanen90221202014-12-09 16:39:47 +00001296
1297// CompareCommands and CompareCommandNames are for the hash table
1298
1299static int CompareCommands(const void* c1, const void* c2) {
1300 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1301}
1302
1303static int CompareCommandNames(const void* c1, const void* c2) {
1304 return strcmp(((const Command*) c1)->name, (const char*) c2);
1305}
1306
1307// HashString is used to hash command names for the hash table
1308
1309static unsigned int HashString(const char *s) {
1310 unsigned int hash = 0;
1311 if (s) {
1312 while (*s) {
1313 hash = hash * 33 + *s++;
1314 }
1315 }
1316 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001317}
1318
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001319// args:
1320// - block device (or file) to modify in-place
1321// - transfer list (blob)
1322// - new data stream (filename within package.zip)
1323// - patch stream (filename within package.zip, must be uncompressed)
1324
Tao Bao0940fe12015-08-27 16:41:21 -07001325static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1326 const Command* commands, size_t cmdcount, bool dryrun) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001327 CommandParameters params;
Sami Tolvanen90221202014-12-09 16:39:47 +00001328 memset(&params, 0, sizeof(params));
1329 params.canwrite = !dryrun;
1330
1331 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001332
Tao Bao612336d2015-08-27 16:41:21 -07001333 Value* blockdev_filename = nullptr;
1334 Value* transfer_list_value = nullptr;
1335 Value* new_data_fn = nullptr;
1336 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001337 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001338 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001339 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001340 }
Tao Bao612336d2015-08-27 16:41:21 -07001341 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1342 FreeValue);
1343 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1344 FreeValue);
1345 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1346 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347
1348 if (blockdev_filename->type != VAL_STRING) {
1349 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001350 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001351 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001352 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001353 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001354 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001355 }
1356 if (new_data_fn->type != VAL_STRING) {
1357 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001358 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001359 }
1360 if (patch_data_fn->type != VAL_STRING) {
1361 ErrorAbort(state, "patch_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001362 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001363 }
1364
Tao Bao612336d2015-08-27 16:41:21 -07001365 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001366
Tao Bao0940fe12015-08-27 16:41:21 -07001367 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001368 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001369 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001370
Tao Bao612336d2015-08-27 16:41:21 -07001371 FILE* cmd_pipe = ui->cmd_pipe;
1372 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001373
Tao Bao0940fe12015-08-27 16:41:21 -07001374 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001375 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001376 }
1377
Tao Bao612336d2015-08-27 16:41:21 -07001378 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001379 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001380 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001381 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001382 }
1383
Sami Tolvanen90221202014-12-09 16:39:47 +00001384 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001385 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001386 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001387 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001388 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001389 }
1390
Sami Tolvanen90221202014-12-09 16:39:47 +00001391 params.fd = TEMP_FAILURE_RETRY(open(blockdev_filename->data, O_RDWR));
Tao Bao612336d2015-08-27 16:41:21 -07001392 unique_fd fd_holder(params.fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001393
Sami Tolvanen90221202014-12-09 16:39:47 +00001394 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001395 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001396 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001397 }
1398
Sami Tolvanen90221202014-12-09 16:39:47 +00001399 if (params.canwrite) {
1400 params.nti.za = za;
1401 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001402
Tao Bao0940fe12015-08-27 16:41:21 -07001403 pthread_mutex_init(&params.nti.mu, nullptr);
1404 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001405 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001406 pthread_attr_init(&attr);
1407 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1408
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001409 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1410 if (error != 0) {
1411 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001412 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001413 }
1414 }
1415
Tao Baobaad2d42015-12-06 16:56:27 -08001416 // Copy all the lines in transfer_list_value into std::string for
1417 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001418 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1419 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001420 if (lines.size() < 2) {
1421 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1422 return StringValue(strdup(""));
1423 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001424
Sami Tolvanen90221202014-12-09 16:39:47 +00001425 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001426 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001427 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1428 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001429 }
1430
Sami Tolvanen90221202014-12-09 16:39:47 +00001431 fprintf(stderr, "blockimg version is %d\n", params.version);
1432
1433 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001434 int total_blocks;
1435 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001436 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1437 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001438 }
1439
1440 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001441 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001442 }
1443
Tao Bao612336d2015-08-27 16:41:21 -07001444 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001445 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001446 if (lines.size() < 4) {
1447 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1448 return StringValue(strdup(""));
1449 }
1450
Sami Tolvanen90221202014-12-09 16:39:47 +00001451 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001452 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001453
Sami Tolvanen90221202014-12-09 16:39:47 +00001454 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001455 int stash_max_blocks;
1456 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001457 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1458 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001459 }
1460
Tao Baob15fd222015-09-24 11:10:51 -07001461 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001462 if (res == -1) {
1463 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001464 }
Tao Bao612336d2015-08-27 16:41:21 -07001465
Tao Baob15fd222015-09-24 11:10:51 -07001466 params.createdstash = res;
1467
Tao Bao612336d2015-08-27 16:41:21 -07001468 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001469 }
1470
Sami Tolvanen90221202014-12-09 16:39:47 +00001471 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001472 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1473 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001474
Tao Bao0940fe12015-08-27 16:41:21 -07001475 for (size_t i = 0; i < cmdcount; ++i) {
1476 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001477 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1478 }
1479
Tao Bao612336d2015-08-27 16:41:21 -07001480 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001481
Tao Bao612336d2015-08-27 16:41:21 -07001482 // Subsequent lines are all individual transfer commands
1483 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1484 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001485 if (line_str.empty()) {
1486 continue;
1487 }
1488
Tao Baobaad2d42015-12-06 16:56:27 -08001489 params.tokens = android::base::Split(line_str, " ");
1490 params.cpos = 0;
1491 params.cmdname = params.tokens[params.cpos++].c_str();
1492 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001493
Tao Bao0940fe12015-08-27 16:41:21 -07001494 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001495 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001496 const_cast<char*>(params.cmdname), CompareCommandNames,
1497 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001498
Tao Bao0940fe12015-08-27 16:41:21 -07001499 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001500 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1501 goto pbiudone;
1502 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001503
Tao Bao0940fe12015-08-27 16:41:21 -07001504 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001505 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001506 goto pbiudone;
1507 }
1508
Sami Tolvanen90221202014-12-09 16:39:47 +00001509 if (params.canwrite) {
Jed Estepf1fc48c2015-12-15 16:04:53 -08001510 if (ota_fsync(params.fd) == -1) {
Tao Bao187efff2015-07-27 14:07:08 -07001511 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1512 goto pbiudone;
1513 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001514 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001515 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001516 }
1517 }
1518
Sami Tolvanen90221202014-12-09 16:39:47 +00001519 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001520 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001521
Tao Bao0940fe12015-08-27 16:41:21 -07001522 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tianjie Xudd874b12016-05-13 12:13:15 -07001523 fprintf(stderr, "stashed %zu blocks\n", params.stashed);
Tao Bao612336d2015-08-27 16:41:21 -07001524 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001525
Tianjie Xudd874b12016-05-13 12:13:15 -07001526 const char* partition = strrchr(blockdev_filename->data, '/');
1527 if (partition != nullptr && *(partition+1) != 0) {
1528 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1529 params.written * BLOCKSIZE);
1530 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1531 params.stashed * BLOCKSIZE);
1532 fflush(cmd_pipe);
1533 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001534 // Delete stash only after successfully completing the update, as it
1535 // may contain blocks needed to complete the update later.
1536 DeleteStash(params.stashbase);
1537 } else {
1538 fprintf(stderr, "verified partition contents; update may be resumed\n");
1539 }
1540
1541 rc = 0;
1542
1543pbiudone:
Jed Estepf1fc48c2015-12-15 16:04:53 -08001544 if (ota_fsync(params.fd) == -1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001545 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001546 }
Tao Baobaad2d42015-12-06 16:56:27 -08001547 // params.fd will be automatically closed because of the fd_holder above.
Sami Tolvanen90221202014-12-09 16:39:47 +00001548
Sami Tolvanen90221202014-12-09 16:39:47 +00001549 // Only delete the stash if the update cannot be resumed, or it's
1550 // a verification run and we created the stash.
1551 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1552 DeleteStash(params.stashbase);
1553 }
1554
Sami Tolvanen90221202014-12-09 16:39:47 +00001555 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1556}
1557
1558// The transfer list is a text file containing commands to
1559// transfer data from one place to another on the target
1560// partition. We parse it and execute the commands in order:
1561//
1562// zero [rangeset]
1563// - fill the indicated blocks with zeros
1564//
1565// new [rangeset]
1566// - fill the blocks with data read from the new_data file
1567//
1568// erase [rangeset]
1569// - mark the given blocks as empty
1570//
1571// move <...>
1572// bsdiff <patchstart> <patchlen> <...>
1573// imgdiff <patchstart> <patchlen> <...>
1574// - read the source blocks, apply a patch (or not in the
1575// case of move), write result to target blocks. bsdiff or
1576// imgdiff specifies the type of patch; move means no patch
1577// at all.
1578//
1579// The format of <...> differs between versions 1 and 2;
1580// see the LoadSrcTgtVersion{1,2}() functions for a
1581// description of what's expected.
1582//
1583// stash <stash_id> <src_range>
1584// - (version 2+ only) load the given source range and stash
1585// the data in the given slot of the stash table.
1586//
Tao Baobaad2d42015-12-06 16:56:27 -08001587// free <stash_id>
1588// - (version 3+ only) free the given stash data.
1589//
Sami Tolvanen90221202014-12-09 16:39:47 +00001590// The creator of the transfer list will guarantee that no block
1591// is read (ie, used as the source for a patch or move) after it
1592// has been written.
1593//
1594// In version 2, the creator will guarantee that a given stash is
1595// loaded (with a stash command) before it's used in a
1596// move/bsdiff/imgdiff command.
1597//
1598// Within one command the source and target ranges may overlap so
1599// in general we need to read the entire source into memory before
1600// writing anything to the target blocks.
1601//
1602// All the patch data is concatenated into one patch_data file in
1603// the update package. It must be stored uncompressed because we
1604// memory-map it in directly from the archive. (Since patches are
1605// already compressed, we lose very little by not compressing
1606// their concatenation.)
1607//
1608// In version 3, commands that read data from the partition (i.e.
1609// move/bsdiff/imgdiff/stash) have one or more additional hashes
1610// before the range parameters, which are used to check if the
1611// command has already been completed and verify the integrity of
1612// the source data.
1613
1614Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001615 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001616 const Command commands[] = {
1617 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001618 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001619 { "free", PerformCommandFree },
1620 { "imgdiff", PerformCommandDiff },
1621 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001622 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001623 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001624 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001625 };
1626
1627 // Perform a dry run without writing to test if an update can proceed
1628 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001629 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001630}
1631
1632Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1633 const Command commands[] = {
1634 { "bsdiff", PerformCommandDiff },
1635 { "erase", PerformCommandErase },
1636 { "free", PerformCommandFree },
1637 { "imgdiff", PerformCommandDiff },
1638 { "move", PerformCommandMove },
1639 { "new", PerformCommandNew },
1640 { "stash", PerformCommandStash },
1641 { "zero", PerformCommandZero }
1642 };
1643
1644 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001645 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001646}
1647
Tao Bao0940fe12015-08-27 16:41:21 -07001648Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001649 Value* blockdev_filename;
1650 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001651
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001652 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001653 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001654 }
Tao Bao612336d2015-08-27 16:41:21 -07001655 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1656 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1657 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001658
1659 if (blockdev_filename->type != VAL_STRING) {
1660 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001661 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001662 }
1663 if (ranges->type != VAL_STRING) {
1664 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001665 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001666 }
1667
Tao Bao612336d2015-08-27 16:41:21 -07001668 int fd = open(blockdev_filename->data, O_RDWR);
1669 unique_fd fd_holder(fd);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001670 if (fd < 0) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001671 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001672 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001673 }
1674
Tao Bao612336d2015-08-27 16:41:21 -07001675 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001676 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001677
1678 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001679 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001680
Tao Bao612336d2015-08-27 16:41:21 -07001681 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001682 for (size_t i = 0; i < rs.count; ++i) {
1683 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001684 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1685 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001686 }
1687
Tao Bao0940fe12015-08-27 16:41:21 -07001688 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001689 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1690 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Tao Bao0940fe12015-08-27 16:41:21 -07001691 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001692 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001693 }
1694
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001695 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001696 }
1697 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001698 uint8_t digest[SHA_DIGEST_LENGTH];
1699 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001700
Tao Bao612336d2015-08-27 16:41:21 -07001701 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001702}
1703
Tianjie Xu30bf4762015-12-15 11:47:30 -08001704// This function checks if a device has been remounted R/W prior to an incremental
1705// OTA update. This is an common cause of update abortion. The function reads the
1706// 1st block of each partition and check for mounting time/count. It return string "t"
1707// if executes successfully and an empty string otherwise.
1708
1709Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1710 Value* arg_filename;
1711
1712 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1713 return nullptr;
1714 }
1715 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1716
1717 if (filename->type != VAL_STRING) {
1718 ErrorAbort(state, "filename argument to %s must be string", name);
1719 return StringValue(strdup(""));
1720 }
1721
1722 int fd = open(arg_filename->data, O_RDONLY);
1723 unique_fd fd_holder(fd);
1724 if (fd == -1) {
1725 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1726 return StringValue(strdup(""));
1727 }
1728
1729 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1730 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1731
1732 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1733 ErrorAbort(state, "failed to read %s: %s", arg_filename->data,
1734 strerror(errno));
1735 return StringValue(strdup(""));
1736 }
1737
1738 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1739 // Super block starts from block 0, offset 0x400
1740 // 0x2C: len32 Mount time
1741 // 0x30: len32 Write time
1742 // 0x34: len16 Number of mounts since the last fsck
1743 // 0x38: len16 Magic signature 0xEF53
1744
1745 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1746 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1747
1748 if (mount_count > 0) {
1749 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1750 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1751 }
1752
1753 return StringValue(strdup("t"));
1754}
1755
1756
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001757Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1758 Value* arg_filename;
1759 Value* arg_ranges;
1760
1761 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1762 return NULL;
1763 }
1764
1765 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1766 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1767
1768 if (filename->type != VAL_STRING) {
1769 ErrorAbort(state, "filename argument to %s must be string", name);
1770 return StringValue(strdup(""));
1771 }
1772 if (ranges->type != VAL_STRING) {
1773 ErrorAbort(state, "ranges argument to %s must be string", name);
1774 return StringValue(strdup(""));
1775 }
1776
Tianjie Xub686ba22015-12-09 15:29:45 -08001777 // Output notice to log when recover is attempted
1778 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1779
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001780 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1781 fec::io fh(filename->data, O_RDWR);
1782
1783 if (!fh) {
1784 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1785 return StringValue(strdup(""));
1786 }
1787
1788 if (!fh.has_ecc() || !fh.has_verity()) {
1789 ErrorAbort(state, "unable to use metadata to correct errors");
1790 return StringValue(strdup(""));
1791 }
1792
1793 fec_status status;
1794
1795 if (!fh.get_status(status)) {
1796 ErrorAbort(state, "failed to read FEC status");
1797 return StringValue(strdup(""));
1798 }
1799
1800 RangeSet rs;
1801 parse_range(ranges->data, rs);
1802
1803 uint8_t buffer[BLOCKSIZE];
1804
1805 for (size_t i = 0; i < rs.count; ++i) {
1806 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1807 // Stay within the data area, libfec validates and corrects metadata
1808 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1809 continue;
1810 }
1811
1812 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001813 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001814 j, strerror(errno));
1815 return StringValue(strdup(""));
1816 }
1817
1818 // If we want to be able to recover from a situation where rewriting a corrected
1819 // block doesn't guarantee the same data will be returned when re-read later, we
1820 // can save a copy of corrected blocks to /cache. Note:
1821 //
1822 // 1. Maximum space required from /cache is the same as the maximum number of
1823 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1824 // this would be ~16 MiB, for example.
1825 //
1826 // 2. To find out if this block was corrupted, call fec_get_status after each
1827 // read and check if the errors field value has increased.
1828 }
1829 }
Tianjie Xub686ba22015-12-09 15:29:45 -08001830 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001831 return StringValue(strdup("t"));
1832}
1833
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001834void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001835 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001836 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001837 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu30bf4762015-12-15 11:47:30 -08001838 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001839 RegisterFunction("range_sha1", RangeSha1Fn);
1840}