blob: 885a517ec7483b57a5b1a8bbdb4a8e47c60cb49a [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
21#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tianjie Xu7eca97e2016-03-22 18:08:12 -070036#include <map>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tao Bao0940fe12015-08-27 16:41:21 -070039#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070040
Elliott Hughes4b166f02015-12-04 15:30:20 -080041#include <android-base/parseint.h>
42#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070043#include <android-base/unique_fd.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070044
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070045#include "applypatch/applypatch.h"
46#include "edify/expr.h"
Tianjie Xu57bed6d2015-12-15 11:47:30 -080047#include "install.h"
Sen Jiangc48cb5e2016-02-04 16:23:21 +080048#include "openssl/sha.h"
Sami Tolvanen90221202014-12-09 16:39:47 +000049#include "minzip/Hash.h"
Jed Estep39c1b5e2015-12-15 16:04:53 -080050#include "ota_io.h"
Tao Baoe6aa3322015-08-05 15:20:27 -070051#include "print_sha1.h"
Tao Bao0940fe12015-08-27 16:41:21 -070052#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 Xu7eca97e2016-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 Estepa7b9a462015-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 Estepa7b9a462015-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 {
Chih-Hung Hsieh49c5c792016-04-29 14:16:35 -0700195 explicit RangeSinkState(RangeSet& rs) : tgt(rs) { };
Tao Bao0940fe12015-08-27 16:41:21 -0700196
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;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700371 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800372 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 Xu7eca97e2016-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
Elliott Hughesbcabd092016-03-22 20:19:22 -0700581 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000582 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700583 fprintf(stderr, "open \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700584 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000585 }
586
Tao Bao612336d2015-08-27 16:41:21 -0700587 allocate(sb.st_size, buffer);
Sami Tolvanen90221202014-12-09 16:39:47 +0000588
Tao Bao612336d2015-08-27 16:41:21 -0700589 if (read_all(fd, buffer, sb.st_size) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700590 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000591 }
592
Tao Bao0940fe12015-08-27 16:41:21 -0700593 *blocks = sb.st_size / BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +0000594
Tao Bao612336d2015-08-27 16:41:21 -0700595 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700596 fprintf(stderr, "unexpected contents in %s\n", fn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700597 DeleteFile(fn, nullptr);
598 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000599 }
600
Tao Bao0940fe12015-08-27 16:41:21 -0700601 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000602}
603
Tao Bao612336d2015-08-27 16:41:21 -0700604static int WriteStash(const std::string& base, const std::string& id, int blocks,
605 std::vector<uint8_t>& buffer, bool checkspace, bool *exists) {
606 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700607 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000608 }
609
610 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
611 fprintf(stderr, "not enough space to write stash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700612 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000613 }
614
Tao Bao0940fe12015-08-27 16:41:21 -0700615 std::string fn = GetStashFileName(base, id, ".partial");
616 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000617
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100618 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700619 struct stat sb;
620 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100621
622 if (res == 0) {
623 // The file already exists and since the name is the hash of the contents,
624 // it's safe to assume the contents are identical (accidental hash collisions
625 // are unlikely)
Tao Baoe6aa3322015-08-05 15:20:27 -0700626 fprintf(stderr, " skipping %d existing blocks in %s\n", blocks, cn.c_str());
Tao Bao0940fe12015-08-27 16:41:21 -0700627 *exists = true;
628 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100629 }
630
Tao Bao0940fe12015-08-27 16:41:21 -0700631 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100632 }
633
Tao Baoe6aa3322015-08-05 15:20:27 -0700634 fprintf(stderr, " writing %d blocks to %s\n", blocks, cn.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000635
Elliott Hughesbcabd092016-03-22 20:19:22 -0700636 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(),
637 O_WRONLY | O_CREAT | O_TRUNC,
638 STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000639 if (fd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700640 fprintf(stderr, "failed to create \"%s\": %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700641 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000642 }
643
644 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700645 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000646 }
647
Jed Estepa7b9a462015-12-15 16:04:53 -0800648 if (ota_fsync(fd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700649 fprintf(stderr, "fsync \"%s\" failed: %s\n", fn.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700650 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000651 }
652
Tao Baoe6aa3322015-08-05 15:20:27 -0700653 if (rename(fn.c_str(), cn.c_str()) == -1) {
654 fprintf(stderr, "rename(\"%s\", \"%s\") failed: %s\n", fn.c_str(), cn.c_str(),
655 strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700656 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000657 }
658
Tao Bao0940fe12015-08-27 16:41:21 -0700659 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700660 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
661 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700662 if (dfd == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700663 fprintf(stderr, "failed to open \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700664 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700665 }
666
Jed Estepa7b9a462015-12-15 16:04:53 -0800667 if (ota_fsync(dfd) == -1) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700668 fprintf(stderr, "fsync \"%s\" failed: %s\n", dname.c_str(), strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -0700669 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700670 }
671
Tao Bao0940fe12015-08-27 16:41:21 -0700672 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000673}
674
675// Creates a directory for storing stash files and checks if the /cache partition
676// hash enough space for the expected amount of blocks we need to store. Returns
677// >0 if we created the directory, zero if it existed already, and <0 of failure.
678
Tao Bao0940fe12015-08-27 16:41:21 -0700679static int CreateStash(State* state, int maxblocks, const char* blockdev, std::string& base) {
680 if (blockdev == nullptr) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700681 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000682 }
683
684 // Stash directory should be different for each partition to avoid conflicts
685 // when updating multiple partitions at the same time, so we use the hash of
686 // the block device name as the base directory
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800687 uint8_t digest[SHA_DIGEST_LENGTH];
688 SHA1(reinterpret_cast<const uint8_t*>(blockdev), strlen(blockdev), digest);
Tao Baoe6aa3322015-08-05 15:20:27 -0700689 base = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000690
Tao Baoe6aa3322015-08-05 15:20:27 -0700691 std::string dirname = GetStashFileName(base, "", "");
Tao Bao0940fe12015-08-27 16:41:21 -0700692 struct stat sb;
693 int res = stat(dirname.c_str(), &sb);
Sami Tolvanen90221202014-12-09 16:39:47 +0000694
695 if (res == -1 && errno != ENOENT) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700696 ErrorAbort(state, "stat \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
697 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000698 } else if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700699 fprintf(stderr, "creating stash %s\n", dirname.c_str());
700 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000701
702 if (res != 0) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700703 ErrorAbort(state, "mkdir \"%s\" failed: %s\n", dirname.c_str(), strerror(errno));
704 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000705 }
706
707 if (CacheSizeCheck(maxblocks * BLOCKSIZE) != 0) {
708 ErrorAbort(state, "not enough space for stash\n");
Tao Baoe6aa3322015-08-05 15:20:27 -0700709 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000710 }
711
Tao Baoe6aa3322015-08-05 15:20:27 -0700712 return 1; // Created directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000713 }
714
Tao Baoe6aa3322015-08-05 15:20:27 -0700715 fprintf(stderr, "using existing stash %s\n", dirname.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000716
717 // If the directory already exists, calculate the space already allocated to
718 // stash files and check if there's enough for all required blocks. Delete any
719 // partially completed stash files first.
720
Tao Bao0940fe12015-08-27 16:41:21 -0700721 EnumerateStash(dirname, DeletePartial, nullptr);
Tao Baoe6aa3322015-08-05 15:20:27 -0700722 int size = 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000723 EnumerateStash(dirname, UpdateFileSize, &size);
724
Tao Bao0940fe12015-08-27 16:41:21 -0700725 size = maxblocks * BLOCKSIZE - size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000726
727 if (size > 0 && CacheSizeCheck(size) != 0) {
728 ErrorAbort(state, "not enough space for stash (%d more needed)\n", size);
Tao Baoe6aa3322015-08-05 15:20:27 -0700729 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000730 }
731
Tao Baoe6aa3322015-08-05 15:20:27 -0700732 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000733}
734
Tao Baobaad2d42015-12-06 16:56:27 -0800735static int SaveStash(CommandParameters& params, const std::string& base,
736 std::vector<uint8_t>& buffer, int fd, bool usehash) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000737
Tao Baobaad2d42015-12-06 16:56:27 -0800738 // <stash_id> <src_range>
739 if (params.cpos + 1 >= params.tokens.size()) {
740 fprintf(stderr, "missing id and/or src range fields in stash command\n");
Sami Tolvanen90221202014-12-09 16:39:47 +0000741 return -1;
742 }
Tao Baobaad2d42015-12-06 16:56:27 -0800743 const std::string& id = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000744
Tao Bao0940fe12015-08-27 16:41:21 -0700745 size_t blocks = 0;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700746 if (usehash && LoadStash(params, base, id, true, &blocks, buffer, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000747 // Stash file already exists and has expected contents. Do not
748 // read from source again, as the source may have been already
749 // overwritten during a previous attempt.
750 return 0;
751 }
752
Tao Bao34847b22015-09-08 11:05:49 -0700753 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800754 parse_range(params.tokens[params.cpos++], src);
Tao Bao34847b22015-09-08 11:05:49 -0700755
Tao Bao612336d2015-08-27 16:41:21 -0700756 allocate(src.size * BLOCKSIZE, buffer);
757 if (ReadBlocks(src, buffer, fd) == -1) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000758 return -1;
759 }
Tao Bao34847b22015-09-08 11:05:49 -0700760 blocks = src.size;
Sami Tolvanen90221202014-12-09 16:39:47 +0000761
Tao Bao612336d2015-08-27 16:41:21 -0700762 if (usehash && VerifyBlocks(id, buffer, blocks, true) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000763 // Source blocks have unexpected contents. If we actually need this
764 // data later, this is an unrecoverable error. However, the command
765 // that uses the data may have already completed previously, so the
766 // possible failure will occur during source block verification.
Tao Bao0940fe12015-08-27 16:41:21 -0700767 fprintf(stderr, "failed to load source blocks for stash %s\n", id.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000768 return 0;
769 }
770
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700771 // In verify mode, save source range_set instead of stashing blocks.
772 if (!params.canwrite && usehash) {
773 stash_map[id] = src;
774 return 0;
775 }
776
Tao Bao0940fe12015-08-27 16:41:21 -0700777 fprintf(stderr, "stashing %zu blocks to %s\n", blocks, id.c_str());
Tianjie Xudd874b12016-05-13 12:13:15 -0700778 params.stashed += blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700779 return WriteStash(base, id, blocks, buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000780}
781
Tao Baobaad2d42015-12-06 16:56:27 -0800782static int FreeStash(const std::string& base, const std::string& id) {
783 if (base.empty() || id.empty()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000784 return -1;
785 }
786
Tao Baobaad2d42015-12-06 16:56:27 -0800787 std::string fn = GetStashFileName(base, id, "");
Tao Bao0940fe12015-08-27 16:41:21 -0700788 DeleteFile(fn, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000789
790 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700791}
792
Tao Bao612336d2015-08-27 16:41:21 -0700793static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
794 const std::vector<uint8_t>& source) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700795 // source contains packed data, which we want to move to the
Tao Bao612336d2015-08-27 16:41:21 -0700796 // locations given in locs in the dest buffer. source and dest
Doug Zongker52ae67d2014-09-08 12:22:09 -0700797 // may be the same buffer.
798
Tao Bao612336d2015-08-27 16:41:21 -0700799 const uint8_t* from = source.data();
800 uint8_t* to = dest.data();
Tao Bao0940fe12015-08-27 16:41:21 -0700801 size_t start = locs.size;
802 for (int i = locs.count-1; i >= 0; --i) {
803 size_t blocks = locs.pos[i*2+1] - locs.pos[i*2];
Doug Zongker52ae67d2014-09-08 12:22:09 -0700804 start -= blocks;
Tao Bao612336d2015-08-27 16:41:21 -0700805 memmove(to + (locs.pos[i*2] * BLOCKSIZE), from + (start * BLOCKSIZE),
Doug Zongker52ae67d2014-09-08 12:22:09 -0700806 blocks * BLOCKSIZE);
807 }
808}
809
810// Do a source/target load for move/bsdiff/imgdiff in version 2.
Tao Baobaad2d42015-12-06 16:56:27 -0800811// We expect to parse the remainder of the parameter tokens as one of:
Doug Zongker52ae67d2014-09-08 12:22:09 -0700812//
813// <tgt_range> <src_block_count> <src_range>
814// (loads data from source image only)
815//
816// <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
817// (loads data from stashes only)
818//
819// <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
820// (loads data from both source image and stashes)
821//
822// On return, buffer is filled with the loaded source data (rearranged
823// and combined with stashed data as necessary). buffer may be
824// reallocated if needed to accommodate the source data. *tgt is the
Sami Tolvanen90221202014-12-09 16:39:47 +0000825// target RangeSet. Any stashes required are loaded using LoadStash.
Doug Zongker52ae67d2014-09-08 12:22:09 -0700826
Tao Baobaad2d42015-12-06 16:56:27 -0800827static int LoadSrcTgtVersion2(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao612336d2015-08-27 16:41:21 -0700828 std::vector<uint8_t>& buffer, int fd, const std::string& stashbase, bool* overlap) {
Tao Baobaad2d42015-12-06 16:56:27 -0800829
830 // At least it needs to provide three parameters: <tgt_range>,
831 // <src_block_count> and "-"/<src_range>.
832 if (params.cpos + 2 >= params.tokens.size()) {
833 fprintf(stderr, "invalid parameters\n");
834 return -1;
835 }
836
Tao Bao612336d2015-08-27 16:41:21 -0700837 // <tgt_range>
Tao Baobaad2d42015-12-06 16:56:27 -0800838 parse_range(params.tokens[params.cpos++], tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700839
Tao Bao612336d2015-08-27 16:41:21 -0700840 // <src_block_count>
Tao Baobaad2d42015-12-06 16:56:27 -0800841 const std::string& token = params.tokens[params.cpos++];
842 if (!android::base::ParseUint(token.c_str(), &src_blocks)) {
843 fprintf(stderr, "invalid src_block_count \"%s\"\n", token.c_str());
844 return -1;
845 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700846
Tao Bao612336d2015-08-27 16:41:21 -0700847 allocate(src_blocks * BLOCKSIZE, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700848
Tao Bao612336d2015-08-27 16:41:21 -0700849 // "-" or <src_range> [<src_loc>]
Tao Baobaad2d42015-12-06 16:56:27 -0800850 if (params.tokens[params.cpos] == "-") {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700851 // no source ranges, only stashes
Tao Baobaad2d42015-12-06 16:56:27 -0800852 params.cpos++;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700853 } else {
Tao Bao0940fe12015-08-27 16:41:21 -0700854 RangeSet src;
Tao Baobaad2d42015-12-06 16:56:27 -0800855 parse_range(params.tokens[params.cpos++], src);
Tao Bao612336d2015-08-27 16:41:21 -0700856 int res = ReadBlocks(src, buffer, fd);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700857
Tao Bao34847b22015-09-08 11:05:49 -0700858 if (overlap) {
859 *overlap = range_overlaps(src, tgt);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700860 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000861
Sami Tolvanen90221202014-12-09 16:39:47 +0000862 if (res == -1) {
863 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700864 }
865
Tao Baobaad2d42015-12-06 16:56:27 -0800866 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000867 // no stashes, only source range
868 return 0;
869 }
870
Tao Bao612336d2015-08-27 16:41:21 -0700871 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800872 parse_range(params.tokens[params.cpos++], locs);
Tao Bao612336d2015-08-27 16:41:21 -0700873 MoveRange(buffer, locs, buffer);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700874 }
875
Tao Baobaad2d42015-12-06 16:56:27 -0800876 // <[stash_id:stash_range]>
877 while (params.cpos < params.tokens.size()) {
Doug Zongker52ae67d2014-09-08 12:22:09 -0700878 // Each word is a an index into the stash table, a colon, and
879 // then a rangeset describing where in the source block that
880 // stashed data should go.
Tao Baobaad2d42015-12-06 16:56:27 -0800881 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
882 if (tokens.size() != 2) {
883 fprintf(stderr, "invalid parameter\n");
884 return -1;
885 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000886
Tao Bao612336d2015-08-27 16:41:21 -0700887 std::vector<uint8_t> stash;
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700888 int res = LoadStash(params, stashbase, tokens[0], false, nullptr, stash, true);
Sami Tolvanen90221202014-12-09 16:39:47 +0000889
890 if (res == -1) {
891 // These source blocks will fail verification if used later, but we
892 // will let the caller decide if this is a fatal failure
Tao Baobaad2d42015-12-06 16:56:27 -0800893 fprintf(stderr, "failed to load stash %s\n", tokens[0].c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000894 continue;
895 }
896
Tao Bao612336d2015-08-27 16:41:21 -0700897 RangeSet locs;
Tao Baobaad2d42015-12-06 16:56:27 -0800898 parse_range(tokens[1], locs);
Sami Tolvanen90221202014-12-09 16:39:47 +0000899
Tao Bao612336d2015-08-27 16:41:21 -0700900 MoveRange(buffer, locs, stash);
Sami Tolvanen90221202014-12-09 16:39:47 +0000901 }
902
903 return 0;
904}
905
Sami Tolvanen90221202014-12-09 16:39:47 +0000906// Do a source/target load for move/bsdiff/imgdiff in version 3.
907//
908// Parameters are the same as for LoadSrcTgtVersion2, except for 'onehash', which
909// tells the function whether to expect separate source and targe block hashes, or
910// if they are both the same and only one hash should be expected, and
911// 'isunresumable', which receives a non-zero value if block verification fails in
912// a way that the update cannot be resumed anymore.
913//
914// If the function is unable to load the necessary blocks or their contents don't
915// match the hashes, the return value is -1 and the command should be aborted.
916//
917// If the return value is 1, the command has already been completed according to
918// the contents of the target blocks, and should not be performed again.
919//
920// If the return value is 0, source blocks have expected content and the command
921// can be performed.
922
Tao Bao34847b22015-09-08 11:05:49 -0700923static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t& src_blocks,
Tao Bao0940fe12015-08-27 16:41:21 -0700924 bool onehash, bool& overlap) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000925
Tao Baobaad2d42015-12-06 16:56:27 -0800926 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000927 fprintf(stderr, "missing source hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700928 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000929 }
930
Tao Baobaad2d42015-12-06 16:56:27 -0800931 std::string srchash = params.tokens[params.cpos++];
932 std::string tgthash;
933
Sami Tolvanen90221202014-12-09 16:39:47 +0000934 if (onehash) {
935 tgthash = srchash;
936 } else {
Tao Baobaad2d42015-12-06 16:56:27 -0800937 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000938 fprintf(stderr, "missing target hash\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700939 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000940 }
Tao Baobaad2d42015-12-06 16:56:27 -0800941 tgthash = params.tokens[params.cpos++];
Sami Tolvanen90221202014-12-09 16:39:47 +0000942 }
943
Elliott Hughesbcabd092016-03-22 20:19:22 -0700944 if (LoadSrcTgtVersion2(params, tgt, src_blocks, params.buffer, params.fd,
945 params.stashbase, &overlap) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700946 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000947 }
948
Tao Bao34847b22015-09-08 11:05:49 -0700949 std::vector<uint8_t> tgtbuffer(tgt.size * BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +0000950
Tao Bao612336d2015-08-27 16:41:21 -0700951 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700952 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000953 }
954
Tao Bao612336d2015-08-27 16:41:21 -0700955 if (VerifyBlocks(tgthash, tgtbuffer, tgt.size, false) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000956 // Target blocks already have expected content, command should be skipped
Tao Bao0940fe12015-08-27 16:41:21 -0700957 return 1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000958 }
959
Tao Bao0940fe12015-08-27 16:41:21 -0700960 if (VerifyBlocks(srchash, params.buffer, src_blocks, true) == 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000961 // If source and target blocks overlap, stash the source blocks so we can
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700962 // resume from possible write errors. In verify mode, we can skip stashing
963 // because the source blocks won't be overwritten.
964 if (overlap && params.canwrite) {
Tao Baobaad2d42015-12-06 16:56:27 -0800965 fprintf(stderr, "stashing %zu overlapping blocks to %s\n", src_blocks,
966 srchash.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +0000967
Tao Bao0940fe12015-08-27 16:41:21 -0700968 bool stash_exists = false;
Tao Bao612336d2015-08-27 16:41:21 -0700969 if (WriteStash(params.stashbase, srchash, src_blocks, params.buffer, true,
Tao Bao0940fe12015-08-27 16:41:21 -0700970 &stash_exists) != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +0000971 fprintf(stderr, "failed to stash overlapping source blocks\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700972 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000973 }
974
Tianjie Xudd874b12016-05-13 12:13:15 -0700975 params.stashed += src_blocks;
Sami Tolvanen90221202014-12-09 16:39:47 +0000976 // Can be deleted when the write has completed
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100977 if (!stash_exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700978 params.freestash = srchash;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100979 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000980 }
981
982 // Source blocks have expected content, command can proceed
Tao Bao0940fe12015-08-27 16:41:21 -0700983 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000984 }
985
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700986 if (overlap && LoadStash(params, params.stashbase, srchash, true, nullptr, params.buffer,
987 true) == 0) {
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100988 // Overlapping source blocks were previously stashed, command can proceed.
989 // We are recovering from an interrupted command, so we don't know if the
990 // stash can safely be deleted after this command.
Tao Bao0940fe12015-08-27 16:41:21 -0700991 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000992 }
993
994 // Valid source data not available, update cannot be resumed
995 fprintf(stderr, "partition has unexpected contents\n");
Tao Bao0940fe12015-08-27 16:41:21 -0700996 params.isunresumable = true;
Sami Tolvanen90221202014-12-09 16:39:47 +0000997
Tao Bao0940fe12015-08-27 16:41:21 -0700998 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000999}
1000
Tao Bao0940fe12015-08-27 16:41:21 -07001001static int PerformCommandMove(CommandParameters& params) {
1002 size_t blocks = 0;
Tao Baoe6aa3322015-08-05 15:20:27 -07001003 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001004 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001005 RangeSet tgt;
Sami Tolvanen90221202014-12-09 16:39:47 +00001006
Tao Bao0940fe12015-08-27 16:41:21 -07001007 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001008 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001009 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001010 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001011 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001012 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001013 status = LoadSrcTgtVersion3(params, tgt, blocks, true, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001014 }
1015
1016 if (status == -1) {
1017 fprintf(stderr, "failed to read blocks for move\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001018 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001019 }
1020
1021 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001022 params.foundwrites = true;
1023 } else if (params.foundwrites) {
1024 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001025 }
1026
Tao Bao0940fe12015-08-27 16:41:21 -07001027 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001028 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001029 fprintf(stderr, " moving %zu blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001030
Tao Bao0940fe12015-08-27 16:41:21 -07001031 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1032 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001033 }
1034 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001035 fprintf(stderr, "skipping %zu already moved blocks\n", blocks);
Sami Tolvanen90221202014-12-09 16:39:47 +00001036 }
1037
1038 }
1039
Tao Baobaad2d42015-12-06 16:56:27 -08001040 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001041 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001042 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001043 }
1044
Tao Bao0940fe12015-08-27 16:41:21 -07001045 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001046
Tao Bao0940fe12015-08-27 16:41:21 -07001047 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001048}
1049
Tao Bao0940fe12015-08-27 16:41:21 -07001050static int PerformCommandStash(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001051 return SaveStash(params, params.stashbase, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001052 (params.version >= 3));
Sami Tolvanen90221202014-12-09 16:39:47 +00001053}
1054
Tao Bao0940fe12015-08-27 16:41:21 -07001055static int PerformCommandFree(CommandParameters& params) {
Tao Baobaad2d42015-12-06 16:56:27 -08001056 // <stash_id>
1057 if (params.cpos >= params.tokens.size()) {
1058 fprintf(stderr, "missing stash id in free command\n");
1059 return -1;
1060 }
1061
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001062 const std::string& id = params.tokens[params.cpos++];
1063
1064 if (!params.canwrite && stash_map.find(id) != stash_map.end()) {
1065 stash_map.erase(id);
1066 return 0;
1067 }
1068
Tao Bao0940fe12015-08-27 16:41:21 -07001069 if (params.createdstash || params.canwrite) {
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001070 return FreeStash(params.stashbase, id);
Sami Tolvanen90221202014-12-09 16:39:47 +00001071 }
1072
1073 return 0;
1074}
1075
Tao Bao0940fe12015-08-27 16:41:21 -07001076static int PerformCommandZero(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001077
Tao Baobaad2d42015-12-06 16:56:27 -08001078 if (params.cpos >= params.tokens.size()) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001079 fprintf(stderr, "missing target blocks for zero\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001080 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001081 }
1082
Tao Bao0940fe12015-08-27 16:41:21 -07001083 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001084 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001085
Tao Bao0940fe12015-08-27 16:41:21 -07001086 fprintf(stderr, " zeroing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001087
Tao Bao612336d2015-08-27 16:41:21 -07001088 allocate(BLOCKSIZE, params.buffer);
1089 memset(params.buffer.data(), 0, BLOCKSIZE);
Sami Tolvanen90221202014-12-09 16:39:47 +00001090
Tao Bao0940fe12015-08-27 16:41:21 -07001091 if (params.canwrite) {
1092 for (size_t i = 0; i < tgt.count; ++i) {
1093 if (!check_lseek(params.fd, (off64_t) tgt.pos[i * 2] * BLOCKSIZE, SEEK_SET)) {
1094 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001095 }
1096
Tao Bao0940fe12015-08-27 16:41:21 -07001097 for (size_t j = tgt.pos[i * 2]; j < tgt.pos[i * 2 + 1]; ++j) {
1098 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1099 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001100 }
1101 }
1102 }
1103 }
1104
Tao Bao0940fe12015-08-27 16:41:21 -07001105 if (params.cmdname[0] == 'z') {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001106 // Update only for the zero command, as the erase command will call
1107 // this if DEBUG_ERASE is defined.
Tao Bao0940fe12015-08-27 16:41:21 -07001108 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001109 }
1110
Tao Bao0940fe12015-08-27 16:41:21 -07001111 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001112}
1113
Tao Bao0940fe12015-08-27 16:41:21 -07001114static int PerformCommandNew(CommandParameters& params) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001115
Tao Baobaad2d42015-12-06 16:56:27 -08001116 if (params.cpos >= params.tokens.size()) {
1117 fprintf(stderr, "missing target blocks for new\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001118 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001119 }
1120
Tao Bao0940fe12015-08-27 16:41:21 -07001121 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001122 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001123
Tao Bao0940fe12015-08-27 16:41:21 -07001124 if (params.canwrite) {
1125 fprintf(stderr, " writing %zu blocks of new data\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001126
Tao Bao0940fe12015-08-27 16:41:21 -07001127 RangeSinkState rss(tgt);
1128 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001129 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001130 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001131
Tao Bao0940fe12015-08-27 16:41:21 -07001132 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1133 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001134 }
1135
Tao Bao0940fe12015-08-27 16:41:21 -07001136 pthread_mutex_lock(&params.nti.mu);
1137 params.nti.rss = &rss;
1138 pthread_cond_broadcast(&params.nti.cv);
Sami Tolvanen90221202014-12-09 16:39:47 +00001139
Tao Bao0940fe12015-08-27 16:41:21 -07001140 while (params.nti.rss) {
1141 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001142 }
1143
Tao Bao0940fe12015-08-27 16:41:21 -07001144 pthread_mutex_unlock(&params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001145 }
1146
Tao Bao0940fe12015-08-27 16:41:21 -07001147 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001148
Tao Bao0940fe12015-08-27 16:41:21 -07001149 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001150}
1151
Tao Bao0940fe12015-08-27 16:41:21 -07001152static int PerformCommandDiff(CommandParameters& params) {
Tao Bao0940fe12015-08-27 16:41:21 -07001153
Tao Baobaad2d42015-12-06 16:56:27 -08001154 // <offset> <length>
1155 if (params.cpos + 1 >= params.tokens.size()) {
1156 fprintf(stderr, "missing patch offset or length for %s\n", params.cmdname);
Tao Bao0940fe12015-08-27 16:41:21 -07001157 return -1;
1158 }
1159
Tao Baobaad2d42015-12-06 16:56:27 -08001160 size_t offset;
1161 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &offset)) {
1162 fprintf(stderr, "invalid patch offset\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001163 return -1;
1164 }
1165
Tao Baobaad2d42015-12-06 16:56:27 -08001166 size_t len;
1167 if (!android::base::ParseUint(params.tokens[params.cpos++].c_str(), &len)) {
1168 fprintf(stderr, "invalid patch offset\n");
1169 return -1;
1170 }
Tao Bao0940fe12015-08-27 16:41:21 -07001171
Tao Bao612336d2015-08-27 16:41:21 -07001172 RangeSet tgt;
Tao Bao0940fe12015-08-27 16:41:21 -07001173 size_t blocks = 0;
Tao Bao612336d2015-08-27 16:41:21 -07001174 bool overlap = false;
Sami Tolvanen90221202014-12-09 16:39:47 +00001175 int status = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001176 if (params.version == 1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001177 status = LoadSrcTgtVersion1(params, tgt, blocks, params.buffer, params.fd);
Tao Bao0940fe12015-08-27 16:41:21 -07001178 } else if (params.version == 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001179 status = LoadSrcTgtVersion2(params, tgt, blocks, params.buffer, params.fd,
Tao Bao612336d2015-08-27 16:41:21 -07001180 params.stashbase, nullptr);
Tao Bao0940fe12015-08-27 16:41:21 -07001181 } else if (params.version >= 3) {
Tao Bao34847b22015-09-08 11:05:49 -07001182 status = LoadSrcTgtVersion3(params, tgt, blocks, false, overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001183 }
1184
1185 if (status == -1) {
1186 fprintf(stderr, "failed to read blocks for diff\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001187 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001188 }
1189
1190 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001191 params.foundwrites = true;
1192 } else if (params.foundwrites) {
1193 fprintf(stderr, "warning: commands executed out of order [%s]\n", params.cmdname);
Sami Tolvanen90221202014-12-09 16:39:47 +00001194 }
1195
Tao Bao0940fe12015-08-27 16:41:21 -07001196 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001197 if (status == 0) {
Tao Bao0940fe12015-08-27 16:41:21 -07001198 fprintf(stderr, "patching %zu blocks to %zu\n", blocks, tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001199
Tao Bao0940fe12015-08-27 16:41:21 -07001200 Value patch_value;
Sami Tolvanen90221202014-12-09 16:39:47 +00001201 patch_value.type = VAL_BLOB;
1202 patch_value.size = len;
Tao Bao0940fe12015-08-27 16:41:21 -07001203 patch_value.data = (char*) (params.patch_start + offset);
Sami Tolvanen90221202014-12-09 16:39:47 +00001204
Tao Bao0940fe12015-08-27 16:41:21 -07001205 RangeSinkState rss(tgt);
1206 rss.fd = params.fd;
Sami Tolvanen90221202014-12-09 16:39:47 +00001207 rss.p_block = 0;
Tao Bao0940fe12015-08-27 16:41:21 -07001208 rss.p_remain = (tgt.pos[1] - tgt.pos[0]) * BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001209
Tao Bao0940fe12015-08-27 16:41:21 -07001210 if (!check_lseek(params.fd, (off64_t) tgt.pos[0] * BLOCKSIZE, SEEK_SET)) {
1211 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 }
1213
Tao Bao0940fe12015-08-27 16:41:21 -07001214 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao612336d2015-08-27 16:41:21 -07001215 ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
Tao Bao0940fe12015-08-27 16:41:21 -07001216 &RangeSinkWrite, &rss, nullptr, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001217 } else {
Tao Bao612336d2015-08-27 16:41:21 -07001218 ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1219 &RangeSinkWrite, &rss, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001220 }
1221
1222 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao0940fe12015-08-27 16:41:21 -07001223 if (rss.p_block != tgt.count || rss.p_remain != 0) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001224 fprintf(stderr, "range sink underrun?\n");
1225 }
1226 } else {
Tao Bao0940fe12015-08-27 16:41:21 -07001227 fprintf(stderr, "skipping %zu blocks already patched to %zu [%s]\n",
Tao Baobaad2d42015-12-06 16:56:27 -08001228 blocks, tgt.size, params.cmdline);
Sami Tolvanen90221202014-12-09 16:39:47 +00001229 }
1230 }
1231
Tao Baobaad2d42015-12-06 16:56:27 -08001232 if (!params.freestash.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -07001233 FreeStash(params.stashbase, params.freestash);
Tao Baobaad2d42015-12-06 16:56:27 -08001234 params.freestash.clear();
Sami Tolvanen90221202014-12-09 16:39:47 +00001235 }
1236
Tao Bao0940fe12015-08-27 16:41:21 -07001237 params.written += tgt.size;
Sami Tolvanen90221202014-12-09 16:39:47 +00001238
Tao Bao0940fe12015-08-27 16:41:21 -07001239 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001240}
1241
Tao Bao0940fe12015-08-27 16:41:21 -07001242static int PerformCommandErase(CommandParameters& params) {
Sami Tolvanene82fa182015-06-10 15:58:12 +00001243 if (DEBUG_ERASE) {
1244 return PerformCommandZero(params);
Sami Tolvanen90221202014-12-09 16:39:47 +00001245 }
1246
Tao Bao0940fe12015-08-27 16:41:21 -07001247 struct stat sb;
1248 if (fstat(params.fd, &sb) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001249 fprintf(stderr, "failed to fstat device to erase: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001250 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001251 }
1252
Tao Bao0940fe12015-08-27 16:41:21 -07001253 if (!S_ISBLK(sb.st_mode)) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001254 fprintf(stderr, "not a block device; skipping erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001255 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001256 }
1257
Tao Baobaad2d42015-12-06 16:56:27 -08001258 if (params.cpos >= params.tokens.size()) {
Tao Baoba9a42a2015-06-23 23:23:33 -07001259 fprintf(stderr, "missing target blocks for erase\n");
Tao Bao0940fe12015-08-27 16:41:21 -07001260 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001261 }
1262
Tao Bao0940fe12015-08-27 16:41:21 -07001263 RangeSet tgt;
Tao Baobaad2d42015-12-06 16:56:27 -08001264 parse_range(params.tokens[params.cpos++], tgt);
Sami Tolvanen90221202014-12-09 16:39:47 +00001265
Tao Bao0940fe12015-08-27 16:41:21 -07001266 if (params.canwrite) {
1267 fprintf(stderr, " erasing %zu blocks\n", tgt.size);
Sami Tolvanen90221202014-12-09 16:39:47 +00001268
Tao Bao0940fe12015-08-27 16:41:21 -07001269 for (size_t i = 0; i < tgt.count; ++i) {
1270 uint64_t blocks[2];
Sami Tolvanen90221202014-12-09 16:39:47 +00001271 // offset in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001272 blocks[0] = tgt.pos[i * 2] * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001273 // length in bytes
Tao Bao0940fe12015-08-27 16:41:21 -07001274 blocks[1] = (tgt.pos[i * 2 + 1] - tgt.pos[i * 2]) * (uint64_t) BLOCKSIZE;
Sami Tolvanen90221202014-12-09 16:39:47 +00001275
Tao Bao0940fe12015-08-27 16:41:21 -07001276 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001277 fprintf(stderr, "BLKDISCARD ioctl failed: %s\n", strerror(errno));
Tao Bao0940fe12015-08-27 16:41:21 -07001278 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001279 }
1280 }
1281 }
1282
Tao Bao0940fe12015-08-27 16:41:21 -07001283 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001284}
1285
1286// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001287typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001288
Tao Bao612336d2015-08-27 16:41:21 -07001289struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001290 const char* name;
1291 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001292};
Sami Tolvanen90221202014-12-09 16:39:47 +00001293
1294// CompareCommands and CompareCommandNames are for the hash table
1295
1296static int CompareCommands(const void* c1, const void* c2) {
1297 return strcmp(((const Command*) c1)->name, ((const Command*) c2)->name);
1298}
1299
1300static int CompareCommandNames(const void* c1, const void* c2) {
1301 return strcmp(((const Command*) c1)->name, (const char*) c2);
1302}
1303
1304// HashString is used to hash command names for the hash table
1305
1306static unsigned int HashString(const char *s) {
1307 unsigned int hash = 0;
1308 if (s) {
1309 while (*s) {
1310 hash = hash * 33 + *s++;
1311 }
1312 }
1313 return hash;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001314}
1315
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001316// args:
1317// - block device (or file) to modify in-place
1318// - transfer list (blob)
1319// - new data stream (filename within package.zip)
1320// - patch stream (filename within package.zip, must be uncompressed)
1321
Tao Bao0940fe12015-08-27 16:41:21 -07001322static Value* PerformBlockImageUpdate(const char* name, State* state, int /* argc */, Expr* argv[],
1323 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao73064612016-04-26 17:14:32 -07001324 CommandParameters params = {};
Sami Tolvanen90221202014-12-09 16:39:47 +00001325 params.canwrite = !dryrun;
1326
1327 fprintf(stderr, "performing %s\n", dryrun ? "verification" : "update");
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001328
Tao Bao612336d2015-08-27 16:41:21 -07001329 Value* blockdev_filename = nullptr;
1330 Value* transfer_list_value = nullptr;
1331 Value* new_data_fn = nullptr;
1332 Value* patch_data_fn = nullptr;
Doug Zongker1d5d6092014-08-21 10:47:24 -07001333 if (ReadValueArgs(state, argv, 4, &blockdev_filename, &transfer_list_value,
Sami Tolvanen90221202014-12-09 16:39:47 +00001334 &new_data_fn, &patch_data_fn) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001335 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001336 }
Tao Bao612336d2015-08-27 16:41:21 -07001337 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1338 FreeValue);
1339 std::unique_ptr<Value, decltype(&FreeValue)> transfer_list_value_holder(transfer_list_value,
1340 FreeValue);
1341 std::unique_ptr<Value, decltype(&FreeValue)> new_data_fn_holder(new_data_fn, FreeValue);
1342 std::unique_ptr<Value, decltype(&FreeValue)> patch_data_fn_holder(patch_data_fn, FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001343
1344 if (blockdev_filename->type != VAL_STRING) {
1345 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001346 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001347 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001348 if (transfer_list_value->type != VAL_BLOB) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001349 ErrorAbort(state, "transfer_list argument to %s must be blob", name);
Tao Bao612336d2015-08-27 16:41:21 -07001350 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001351 }
1352 if (new_data_fn->type != VAL_STRING) {
1353 ErrorAbort(state, "new_data_fn argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001354 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001355 }
1356 if (patch_data_fn->type != VAL_STRING) {
1357 ErrorAbort(state, "patch_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
Tao Bao612336d2015-08-27 16:41:21 -07001361 UpdaterInfo* ui = reinterpret_cast<UpdaterInfo*>(state->cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001362
Tao Bao0940fe12015-08-27 16:41:21 -07001363 if (ui == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001364 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001365 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001366
Tao Bao612336d2015-08-27 16:41:21 -07001367 FILE* cmd_pipe = ui->cmd_pipe;
1368 ZipArchive* za = ui->package_zip;
Sami Tolvanen90221202014-12-09 16:39:47 +00001369
Tao Bao0940fe12015-08-27 16:41:21 -07001370 if (cmd_pipe == nullptr || za == nullptr) {
Tao Bao612336d2015-08-27 16:41:21 -07001371 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001372 }
1373
Tao Bao612336d2015-08-27 16:41:21 -07001374 const ZipEntry* patch_entry = mzFindZipEntry(za, patch_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001375 if (patch_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001376 fprintf(stderr, "%s(): no file \"%s\" in package", name, patch_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001377 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001378 }
1379
Sami Tolvanen90221202014-12-09 16:39:47 +00001380 params.patch_start = ui->package_zip_addr + mzGetZipEntryOffset(patch_entry);
Tao Bao612336d2015-08-27 16:41:21 -07001381 const ZipEntry* new_entry = mzFindZipEntry(za, new_data_fn->data);
Tao Bao0940fe12015-08-27 16:41:21 -07001382 if (new_entry == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001383 fprintf(stderr, "%s(): no file \"%s\" in package", name, new_data_fn->data);
Tao Bao612336d2015-08-27 16:41:21 -07001384 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001385 }
1386
Elliott Hughesbcabd092016-03-22 20:19:22 -07001387 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data, O_RDWR)));
Sami Tolvanen90221202014-12-09 16:39:47 +00001388 if (params.fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001389 fprintf(stderr, "open \"%s\" failed: %s\n", blockdev_filename->data, strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001390 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001391 }
1392
Sami Tolvanen90221202014-12-09 16:39:47 +00001393 if (params.canwrite) {
1394 params.nti.za = za;
1395 params.nti.entry = new_entry;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001396
Tao Bao0940fe12015-08-27 16:41:21 -07001397 pthread_mutex_init(&params.nti.mu, nullptr);
1398 pthread_cond_init(&params.nti.cv, nullptr);
Tao Bao612336d2015-08-27 16:41:21 -07001399 pthread_attr_t attr;
Sami Tolvanen90221202014-12-09 16:39:47 +00001400 pthread_attr_init(&attr);
1401 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1402
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001403 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1404 if (error != 0) {
1405 fprintf(stderr, "pthread_create failed: %s\n", strerror(error));
Tao Bao612336d2015-08-27 16:41:21 -07001406 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001407 }
1408 }
1409
Tao Baobaad2d42015-12-06 16:56:27 -08001410 // Copy all the lines in transfer_list_value into std::string for
1411 // processing.
Tao Bao612336d2015-08-27 16:41:21 -07001412 const std::string transfer_list(transfer_list_value->data, transfer_list_value->size);
1413 std::vector<std::string> lines = android::base::Split(transfer_list, "\n");
Tao Baobaad2d42015-12-06 16:56:27 -08001414 if (lines.size() < 2) {
1415 ErrorAbort(state, "too few lines in the transfer list [%zd]\n", lines.size());
1416 return StringValue(strdup(""));
1417 }
Doug Zongker1d5d6092014-08-21 10:47:24 -07001418
Sami Tolvanen90221202014-12-09 16:39:47 +00001419 // First line in transfer list is the version number
Tao Bao1fdec862015-10-21 14:57:44 -07001420 if (!android::base::ParseInt(lines[0].c_str(), &params.version, 1, 4)) {
Tao Bao612336d2015-08-27 16:41:21 -07001421 fprintf(stderr, "unexpected transfer list version [%s]\n", lines[0].c_str());
1422 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001423 }
1424
Sami Tolvanen90221202014-12-09 16:39:47 +00001425 fprintf(stderr, "blockimg version is %d\n", params.version);
1426
1427 // Second line in transfer list is the total number of blocks we expect to write
Tao Baob15fd222015-09-24 11:10:51 -07001428 int total_blocks;
1429 if (!android::base::ParseInt(lines[1].c_str(), &total_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001430 ErrorAbort(state, "unexpected block count [%s]\n", lines[1].c_str());
1431 return StringValue(strdup(""));
Tao Baob15fd222015-09-24 11:10:51 -07001432 }
1433
1434 if (total_blocks == 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001435 return StringValue(strdup("t"));
Sami Tolvanen90221202014-12-09 16:39:47 +00001436 }
1437
Tao Bao612336d2015-08-27 16:41:21 -07001438 size_t start = 2;
Sami Tolvanen90221202014-12-09 16:39:47 +00001439 if (params.version >= 2) {
Tao Baobaad2d42015-12-06 16:56:27 -08001440 if (lines.size() < 4) {
1441 ErrorAbort(state, "too few lines in the transfer list [%zu]\n", lines.size());
1442 return StringValue(strdup(""));
1443 }
1444
Sami Tolvanen90221202014-12-09 16:39:47 +00001445 // Third line is how many stash entries are needed simultaneously
Tao Bao612336d2015-08-27 16:41:21 -07001446 fprintf(stderr, "maximum stash entries %s\n", lines[2].c_str());
Doug Zongker52ae67d2014-09-08 12:22:09 -07001447
Sami Tolvanen90221202014-12-09 16:39:47 +00001448 // Fourth line is the maximum number of blocks that will be stashed simultaneously
Tao Baob15fd222015-09-24 11:10:51 -07001449 int stash_max_blocks;
1450 if (!android::base::ParseInt(lines[3].c_str(), &stash_max_blocks, 0)) {
Tao Bao612336d2015-08-27 16:41:21 -07001451 ErrorAbort(state, "unexpected maximum stash blocks [%s]\n", lines[3].c_str());
1452 return StringValue(strdup(""));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001453 }
1454
Tao Baob15fd222015-09-24 11:10:51 -07001455 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
Tao Baob15fd222015-09-24 11:10:51 -07001456 if (res == -1) {
1457 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001458 }
Tao Bao612336d2015-08-27 16:41:21 -07001459
Tao Baob15fd222015-09-24 11:10:51 -07001460 params.createdstash = res;
1461
Tao Bao612336d2015-08-27 16:41:21 -07001462 start += 2;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001463 }
1464
Sami Tolvanen90221202014-12-09 16:39:47 +00001465 // Build a hash table of the available commands
Tao Bao612336d2015-08-27 16:41:21 -07001466 HashTable* cmdht = mzHashTableCreate(cmdcount, nullptr);
1467 std::unique_ptr<HashTable, decltype(&mzHashTableFree)> cmdht_holder(cmdht, mzHashTableFree);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001468
Tao Bao0940fe12015-08-27 16:41:21 -07001469 for (size_t i = 0; i < cmdcount; ++i) {
1470 unsigned int cmdhash = HashString(commands[i].name);
Sami Tolvanen90221202014-12-09 16:39:47 +00001471 mzHashTableLookup(cmdht, cmdhash, (void*) &commands[i], CompareCommands, true);
1472 }
1473
Tao Bao612336d2015-08-27 16:41:21 -07001474 int rc = -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -07001475
Tao Bao612336d2015-08-27 16:41:21 -07001476 // Subsequent lines are all individual transfer commands
1477 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1478 const std::string& line_str(*it);
Tao Bao6a47dff2015-09-25 17:12:28 -07001479 if (line_str.empty()) {
1480 continue;
1481 }
1482
Tao Baobaad2d42015-12-06 16:56:27 -08001483 params.tokens = android::base::Split(line_str, " ");
1484 params.cpos = 0;
1485 params.cmdname = params.tokens[params.cpos++].c_str();
1486 params.cmdline = line_str.c_str();
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001487
Tao Bao0940fe12015-08-27 16:41:21 -07001488 unsigned int cmdhash = HashString(params.cmdname);
Tao Bao612336d2015-08-27 16:41:21 -07001489 const Command* cmd = reinterpret_cast<const Command*>(mzHashTableLookup(cmdht, cmdhash,
Tao Baobaad2d42015-12-06 16:56:27 -08001490 const_cast<char*>(params.cmdname), CompareCommandNames,
1491 false));
Doug Zongker52ae67d2014-09-08 12:22:09 -07001492
Tao Bao0940fe12015-08-27 16:41:21 -07001493 if (cmd == nullptr) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001494 fprintf(stderr, "unexpected command [%s]\n", params.cmdname);
1495 goto pbiudone;
1496 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001497
Tao Bao0940fe12015-08-27 16:41:21 -07001498 if (cmd->f != nullptr && cmd->f(params) == -1) {
Tao Bao612336d2015-08-27 16:41:21 -07001499 fprintf(stderr, "failed to execute command [%s]\n", line_str.c_str());
Sami Tolvanen90221202014-12-09 16:39:47 +00001500 goto pbiudone;
1501 }
1502
Sami Tolvanen90221202014-12-09 16:39:47 +00001503 if (params.canwrite) {
Jed Estepa7b9a462015-12-15 16:04:53 -08001504 if (ota_fsync(params.fd) == -1) {
Tao Bao187efff2015-07-27 14:07:08 -07001505 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
1506 goto pbiudone;
1507 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001508 fprintf(cmd_pipe, "set_progress %.4f\n", (double) params.written / total_blocks);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001509 fflush(cmd_pipe);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001510 }
1511 }
1512
Sami Tolvanen90221202014-12-09 16:39:47 +00001513 if (params.canwrite) {
Tao Bao0940fe12015-08-27 16:41:21 -07001514 pthread_join(params.thread, nullptr);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001515
Tao Bao0940fe12015-08-27 16:41:21 -07001516 fprintf(stderr, "wrote %zu blocks; expected %d\n", params.written, total_blocks);
Tianjie Xudd874b12016-05-13 12:13:15 -07001517 fprintf(stderr, "stashed %zu blocks\n", params.stashed);
Tao Bao612336d2015-08-27 16:41:21 -07001518 fprintf(stderr, "max alloc needed was %zu\n", params.buffer.size());
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001519
Tianjie Xudd874b12016-05-13 12:13:15 -07001520 const char* partition = strrchr(blockdev_filename->data, '/');
1521 if (partition != nullptr && *(partition+1) != 0) {
1522 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1,
1523 params.written * BLOCKSIZE);
1524 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1,
1525 params.stashed * BLOCKSIZE);
1526 fflush(cmd_pipe);
1527 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001528 // Delete stash only after successfully completing the update, as it
1529 // may contain blocks needed to complete the update later.
1530 DeleteStash(params.stashbase);
1531 } else {
1532 fprintf(stderr, "verified partition contents; update may be resumed\n");
1533 }
1534
1535 rc = 0;
1536
1537pbiudone:
Jed Estepa7b9a462015-12-15 16:04:53 -08001538 if (ota_fsync(params.fd) == -1) {
Tao Baobaad2d42015-12-06 16:56:27 -08001539 fprintf(stderr, "fsync failed: %s\n", strerror(errno));
Sami Tolvanen90221202014-12-09 16:39:47 +00001540 }
Elliott Hughesbcabd092016-03-22 20:19:22 -07001541 // params.fd will be automatically closed because it's a unique_fd.
Sami Tolvanen90221202014-12-09 16:39:47 +00001542
Sami Tolvanen90221202014-12-09 16:39:47 +00001543 // Only delete the stash if the update cannot be resumed, or it's
1544 // a verification run and we created the stash.
1545 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1546 DeleteStash(params.stashbase);
1547 }
1548
Sami Tolvanen90221202014-12-09 16:39:47 +00001549 return StringValue(rc == 0 ? strdup("t") : strdup(""));
1550}
1551
1552// The transfer list is a text file containing commands to
1553// transfer data from one place to another on the target
1554// partition. We parse it and execute the commands in order:
1555//
1556// zero [rangeset]
1557// - fill the indicated blocks with zeros
1558//
1559// new [rangeset]
1560// - fill the blocks with data read from the new_data file
1561//
1562// erase [rangeset]
1563// - mark the given blocks as empty
1564//
1565// move <...>
1566// bsdiff <patchstart> <patchlen> <...>
1567// imgdiff <patchstart> <patchlen> <...>
1568// - read the source blocks, apply a patch (or not in the
1569// case of move), write result to target blocks. bsdiff or
1570// imgdiff specifies the type of patch; move means no patch
1571// at all.
1572//
1573// The format of <...> differs between versions 1 and 2;
1574// see the LoadSrcTgtVersion{1,2}() functions for a
1575// description of what's expected.
1576//
1577// stash <stash_id> <src_range>
1578// - (version 2+ only) load the given source range and stash
1579// the data in the given slot of the stash table.
1580//
Tao Baobaad2d42015-12-06 16:56:27 -08001581// free <stash_id>
1582// - (version 3+ only) free the given stash data.
1583//
Sami Tolvanen90221202014-12-09 16:39:47 +00001584// The creator of the transfer list will guarantee that no block
1585// is read (ie, used as the source for a patch or move) after it
1586// has been written.
1587//
1588// In version 2, the creator will guarantee that a given stash is
1589// loaded (with a stash command) before it's used in a
1590// move/bsdiff/imgdiff command.
1591//
1592// Within one command the source and target ranges may overlap so
1593// in general we need to read the entire source into memory before
1594// writing anything to the target blocks.
1595//
1596// All the patch data is concatenated into one patch_data file in
1597// the update package. It must be stored uncompressed because we
1598// memory-map it in directly from the archive. (Since patches are
1599// already compressed, we lose very little by not compressing
1600// their concatenation.)
1601//
1602// In version 3, commands that read data from the partition (i.e.
1603// move/bsdiff/imgdiff/stash) have one or more additional hashes
1604// before the range parameters, which are used to check if the
1605// command has already been completed and verify the integrity of
1606// the source data.
1607
1608Value* BlockImageVerifyFn(const char* name, State* state, int argc, Expr* argv[]) {
Tao Bao0940fe12015-08-27 16:41:21 -07001609 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001610 const Command commands[] = {
1611 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001612 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001613 { "free", PerformCommandFree },
1614 { "imgdiff", PerformCommandDiff },
1615 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001616 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001617 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001618 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001619 };
1620
1621 // Perform a dry run without writing to test if an update can proceed
1622 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001623 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001624}
1625
1626Value* BlockImageUpdateFn(const char* name, State* state, int argc, Expr* argv[]) {
1627 const Command commands[] = {
1628 { "bsdiff", PerformCommandDiff },
1629 { "erase", PerformCommandErase },
1630 { "free", PerformCommandFree },
1631 { "imgdiff", PerformCommandDiff },
1632 { "move", PerformCommandMove },
1633 { "new", PerformCommandNew },
1634 { "stash", PerformCommandStash },
1635 { "zero", PerformCommandZero }
1636 };
1637
1638 return PerformBlockImageUpdate(name, state, argc, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001639 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001640}
1641
Tao Bao0940fe12015-08-27 16:41:21 -07001642Value* RangeSha1Fn(const char* name, State* state, int /* argc */, Expr* argv[]) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001643 Value* blockdev_filename;
1644 Value* ranges;
Tao Bao0940fe12015-08-27 16:41:21 -07001645
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001646 if (ReadValueArgs(state, argv, 2, &blockdev_filename, &ranges) < 0) {
Tao Bao612336d2015-08-27 16:41:21 -07001647 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001648 }
Tao Bao612336d2015-08-27 16:41:21 -07001649 std::unique_ptr<Value, decltype(&FreeValue)> ranges_holder(ranges, FreeValue);
1650 std::unique_ptr<Value, decltype(&FreeValue)> blockdev_filename_holder(blockdev_filename,
1651 FreeValue);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001652
1653 if (blockdev_filename->type != VAL_STRING) {
1654 ErrorAbort(state, "blockdev_filename argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001655 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001656 }
1657 if (ranges->type != VAL_STRING) {
1658 ErrorAbort(state, "ranges argument to %s must be string", name);
Tao Bao612336d2015-08-27 16:41:21 -07001659 return StringValue(strdup(""));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001660 }
1661
Elliott Hughesbcabd092016-03-22 20:19:22 -07001662 android::base::unique_fd fd(ota_open(blockdev_filename->data, O_RDWR));
1663 if (fd == -1) {
Elliott Hughes1fdd4522015-03-23 13:33:57 -07001664 ErrorAbort(state, "open \"%s\" failed: %s", blockdev_filename->data, strerror(errno));
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 RangeSet rs;
Tao Bao0940fe12015-08-27 16:41:21 -07001669 parse_range(ranges->data, rs);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001670
1671 SHA_CTX ctx;
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001672 SHA1_Init(&ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001673
Tao Bao612336d2015-08-27 16:41:21 -07001674 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Bao0940fe12015-08-27 16:41:21 -07001675 for (size_t i = 0; i < rs.count; ++i) {
1676 if (!check_lseek(fd, (off64_t)rs.pos[i*2] * BLOCKSIZE, SEEK_SET)) {
Tao Bao612336d2015-08-27 16:41:21 -07001677 ErrorAbort(state, "failed to seek %s: %s", blockdev_filename->data, strerror(errno));
1678 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001679 }
1680
Tao Bao0940fe12015-08-27 16:41:21 -07001681 for (size_t j = rs.pos[i*2]; j < rs.pos[i*2+1]; ++j) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001682 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1683 ErrorAbort(state, "failed to read %s: %s", blockdev_filename->data,
Elliott Hughesbcabd092016-03-22 20:19:22 -07001684 strerror(errno));
Tao Bao612336d2015-08-27 16:41:21 -07001685 return StringValue(strdup(""));
Sami Tolvanen90221202014-12-09 16:39:47 +00001686 }
1687
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001688 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001689 }
1690 }
Sen Jiangc48cb5e2016-02-04 16:23:21 +08001691 uint8_t digest[SHA_DIGEST_LENGTH];
1692 SHA1_Final(digest, &ctx);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001693
Tao Bao612336d2015-08-27 16:41:21 -07001694 return StringValue(strdup(print_sha1(digest).c_str()));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001695}
1696
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001697// This function checks if a device has been remounted R/W prior to an incremental
1698// OTA update. This is an common cause of update abortion. The function reads the
1699// 1st block of each partition and check for mounting time/count. It return string "t"
1700// if executes successfully and an empty string otherwise.
1701
1702Value* CheckFirstBlockFn(const char* name, State* state, int argc, Expr* argv[]) {
1703 Value* arg_filename;
1704
1705 if (ReadValueArgs(state, argv, 1, &arg_filename) < 0) {
1706 return nullptr;
1707 }
1708 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1709
1710 if (filename->type != VAL_STRING) {
1711 ErrorAbort(state, "filename argument to %s must be string", name);
1712 return StringValue(strdup(""));
1713 }
1714
Elliott Hughesbcabd092016-03-22 20:19:22 -07001715 android::base::unique_fd fd(ota_open(arg_filename->data, O_RDONLY));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001716 if (fd == -1) {
1717 ErrorAbort(state, "open \"%s\" failed: %s", arg_filename->data, strerror(errno));
1718 return StringValue(strdup(""));
1719 }
1720
1721 RangeSet blk0 {1 /*count*/, 1/*size*/, std::vector<size_t> {0, 1}/*position*/};
1722 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1723
1724 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
Elliott Hughesbcabd092016-03-22 20:19:22 -07001725 ErrorAbort(state, "failed to read %s: %s", arg_filename->data, strerror(errno));
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001726 return StringValue(strdup(""));
1727 }
1728
1729 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1730 // Super block starts from block 0, offset 0x400
1731 // 0x2C: len32 Mount time
1732 // 0x30: len32 Write time
1733 // 0x34: len16 Number of mounts since the last fsck
1734 // 0x38: len16 Magic signature 0xEF53
1735
1736 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400+0x2C]);
1737 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400+0x34]);
1738
1739 if (mount_count > 0) {
1740 uiPrintf(state, "Device was remounted R/W %d times\n", mount_count);
1741 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1742 }
1743
1744 return StringValue(strdup("t"));
1745}
1746
1747
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001748Value* BlockImageRecoverFn(const char* name, State* state, int argc, Expr* argv[]) {
1749 Value* arg_filename;
1750 Value* arg_ranges;
1751
1752 if (ReadValueArgs(state, argv, 2, &arg_filename, &arg_ranges) < 0) {
1753 return NULL;
1754 }
1755
1756 std::unique_ptr<Value, decltype(&FreeValue)> filename(arg_filename, FreeValue);
1757 std::unique_ptr<Value, decltype(&FreeValue)> ranges(arg_ranges, FreeValue);
1758
1759 if (filename->type != VAL_STRING) {
1760 ErrorAbort(state, "filename argument to %s must be string", name);
1761 return StringValue(strdup(""));
1762 }
1763 if (ranges->type != VAL_STRING) {
1764 ErrorAbort(state, "ranges argument to %s must be string", name);
1765 return StringValue(strdup(""));
1766 }
1767
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001768 // Output notice to log when recover is attempted
1769 fprintf(stderr, "%s image corrupted, attempting to recover...\n", filename->data);
1770
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001771 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1772 fec::io fh(filename->data, O_RDWR);
1773
1774 if (!fh) {
1775 ErrorAbort(state, "fec_open \"%s\" failed: %s", filename->data, strerror(errno));
1776 return StringValue(strdup(""));
1777 }
1778
1779 if (!fh.has_ecc() || !fh.has_verity()) {
1780 ErrorAbort(state, "unable to use metadata to correct errors");
1781 return StringValue(strdup(""));
1782 }
1783
1784 fec_status status;
1785
1786 if (!fh.get_status(status)) {
1787 ErrorAbort(state, "failed to read FEC status");
1788 return StringValue(strdup(""));
1789 }
1790
1791 RangeSet rs;
1792 parse_range(ranges->data, rs);
1793
1794 uint8_t buffer[BLOCKSIZE];
1795
1796 for (size_t i = 0; i < rs.count; ++i) {
1797 for (size_t j = rs.pos[i * 2]; j < rs.pos[i * 2 + 1]; ++j) {
1798 // Stay within the data area, libfec validates and corrects metadata
1799 if (status.data_size <= (uint64_t)j * BLOCKSIZE) {
1800 continue;
1801 }
1802
1803 if (fh.pread(buffer, BLOCKSIZE, (off64_t)j * BLOCKSIZE) != BLOCKSIZE) {
Tao Baobaad2d42015-12-06 16:56:27 -08001804 ErrorAbort(state, "failed to recover %s (block %zu): %s", filename->data,
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001805 j, strerror(errno));
1806 return StringValue(strdup(""));
1807 }
1808
1809 // If we want to be able to recover from a situation where rewriting a corrected
1810 // block doesn't guarantee the same data will be returned when re-read later, we
1811 // can save a copy of corrected blocks to /cache. Note:
1812 //
1813 // 1. Maximum space required from /cache is the same as the maximum number of
1814 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1815 // this would be ~16 MiB, for example.
1816 //
1817 // 2. To find out if this block was corrupted, call fec_get_status after each
1818 // read and check if the errors field value has increased.
1819 }
1820 }
Tianjie Xu3b010bc2015-12-09 15:29:45 -08001821 fprintf(stderr, "...%s image recovered successfully.\n", filename->data);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001822 return StringValue(strdup("t"));
1823}
1824
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001825void RegisterBlockImageFunctions() {
Sami Tolvanen90221202014-12-09 16:39:47 +00001826 RegisterFunction("block_image_verify", BlockImageVerifyFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001827 RegisterFunction("block_image_update", BlockImageUpdateFn);
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001828 RegisterFunction("block_image_recover", BlockImageRecoverFn);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001829 RegisterFunction("check_first_block", CheckFirstBlockFn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001830 RegisterFunction("range_sha1", RangeSha1Fn);
1831}