blob: ce3cea4f3960d52960fc8d0ef34a735b900d2d93 [file] [log] [blame]
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <ctype.h>
18#include <errno.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000019#include <dirent.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070020#include <fcntl.h>
Tao Bao0bbc7642017-03-29 23:57:47 -070021#include <inttypes.h>
Tao Baoba9a42a2015-06-23 23:23:33 -070022#include <linux/fs.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070023#include <pthread.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <string.h>
Sami Tolvanen90221202014-12-09 16:39:47 +000028#include <sys/stat.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070029#include <sys/types.h>
30#include <sys/wait.h>
31#include <sys/ioctl.h>
32#include <time.h>
33#include <unistd.h>
Sami Tolvanen0a7b4732015-06-25 10:25:36 +010034#include <fec/io.h>
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070035
Tao Baoec8272f2017-03-15 17:39:01 -070036#include <functional>
Tao Baoe6aa3322015-08-05 15:20:27 -070037#include <memory>
38#include <string>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070039#include <unordered_map>
Tao Bao0940fe12015-08-27 16:41:21 -070040#include <vector>
Tao Baoe6aa3322015-08-05 15:20:27 -070041
Tao Bao039f2da2016-11-22 16:29:50 -080042#include <android-base/logging.h>
Elliott Hughes4b166f02015-12-04 15:30:20 -080043#include <android-base/parseint.h>
44#include <android-base/strings.h>
Elliott Hughesbcabd092016-03-22 20:19:22 -070045#include <android-base/unique_fd.h>
Tao Bao51412212016-12-28 14:44:05 -080046#include <applypatch/applypatch.h>
Tianjie Xu107a34f2017-06-29 17:04:21 -070047#include <brotli/decode.h>
Tao Bao51412212016-12-28 14:44:05 -080048#include <openssl/sha.h>
Tianjie Xua946b9e2017-03-21 16:24:57 -070049#include <private/android_filesystem_config.h>
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070050#include <ziparchive/zip_archive.h>
Tao Baoe6aa3322015-08-05 15:20:27 -070051
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070052#include "edify/expr.h"
Tao Baod33b2f82017-09-28 21:29:11 -070053#include "otafault/ota_io.h"
Tao Bao1fc5bf32017-10-06 07:43:41 -070054#include "otautil/error_code.h"
Tao Bao09e468f2017-09-29 14:39:33 -070055#include "otautil/print_sha1.h"
56#include "otautil/rangeset.h"
Tao Bao8f237572017-03-26 13:36:49 -070057#include "updater/install.h"
Tao Bao0c7839a2016-10-10 15:48:37 -070058#include "updater/updater.h"
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070059
Sami Tolvanene82fa182015-06-10 15:58:12 +000060// Set this to 0 to interpret 'erase' transfers to mean do a
61// BLKDISCARD ioctl (the normal behavior). Set to 1 to interpret
62// erase to mean fill the region with zeroes.
63#define DEBUG_ERASE 0
64
Tao Bao51412212016-12-28 14:44:05 -080065static constexpr size_t BLOCKSIZE = 4096;
66static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
67static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
68static constexpr mode_t STASH_FILE_MODE = 0600;
Sami Tolvanen90221202014-12-09 16:39:47 +000069
Tianjie Xu16255832016-04-30 11:49:59 -070070static CauseCode failure_type = kNoCause;
Tianjie Xu7ce287d2016-05-31 09:29:49 -070071static bool is_retry = false;
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -070072static std::unordered_map<std::string, RangeSet> stash_map;
Tianjie Xu7eca97e2016-03-22 18:08:12 -070073
Sami Tolvanen90221202014-12-09 16:39:47 +000074static int read_all(int fd, uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070075 size_t so_far = 0;
76 while (so_far < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -080077 ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
Elliott Hughes7bad7c42015-04-28 17:24:24 -070078 if (r == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -070079 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -080080 PLOG(ERROR) << "read failed";
Sami Tolvanen90221202014-12-09 16:39:47 +000081 return -1;
Tianjie Xu71e182b2016-08-31 18:06:33 -070082 } else if (r == 0) {
83 failure_type = kFreadFailure;
Tao Bao039f2da2016-11-22 16:29:50 -080084 LOG(ERROR) << "read reached unexpected EOF.";
Tianjie Xu71e182b2016-08-31 18:06:33 -070085 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070086 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -070087 so_far += r;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070088 }
Sami Tolvanen90221202014-12-09 16:39:47 +000089 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070090}
91
Tao Bao612336d2015-08-27 16:41:21 -070092static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
93 return read_all(fd, buffer.data(), size);
94}
95
Sami Tolvanen90221202014-12-09 16:39:47 +000096static int write_all(int fd, const uint8_t* data, size_t size) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -070097 size_t written = 0;
98 while (written < size) {
Jed Estepa7b9a462015-12-15 16:04:53 -080099 ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700100 if (w == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700101 failure_type = kFwriteFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800102 PLOG(ERROR) << "write failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000103 return -1;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700104 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700105 written += w;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700106 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000107
Sami Tolvanen90221202014-12-09 16:39:47 +0000108 return 0;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700109}
110
Tao Bao612336d2015-08-27 16:41:21 -0700111static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
112 return write_all(fd, buffer.data(), size);
113}
114
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700115static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700116 // Don't discard blocks unless the update is a retry run.
117 if (!is_retry) {
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700118 return true;
Tao Baobf5b77d2017-03-30 16:57:29 -0700119 }
120
121 uint64_t args[2] = { static_cast<uint64_t>(offset), size };
122 if (ioctl(fd, BLKDISCARD, &args) == -1) {
123 PLOG(ERROR) << "BLKDISCARD ioctl failed";
124 return false;
125 }
126 return true;
Tianjie Xu7ce287d2016-05-31 09:29:49 -0700127}
128
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700129static bool check_lseek(int fd, off64_t offset, int whence) {
130 off64_t rc = TEMP_FAILURE_RETRY(lseek64(fd, offset, whence));
131 if (rc == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700132 failure_type = kLseekFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800133 PLOG(ERROR) << "lseek64 failed";
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700134 return false;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700135 }
Elliott Hughes7bad7c42015-04-28 17:24:24 -0700136 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700137}
138
Tao Bao612336d2015-08-27 16:41:21 -0700139static void allocate(size_t size, std::vector<uint8_t>& buffer) {
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700140 // if the buffer's big enough, reuse it.
Tao Bao612336d2015-08-27 16:41:21 -0700141 if (size <= buffer.size()) return;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700142
Tao Bao612336d2015-08-27 16:41:21 -0700143 buffer.resize(size);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700144}
145
Tao Bao60a70af2017-03-26 14:03:52 -0700146/**
147 * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
148 * given RangeSet.
149 */
150class RangeSinkWriter {
151 public:
152 RangeSinkWriter(int fd, const RangeSet& tgt)
Tianjie Xu107a34f2017-06-29 17:04:21 -0700153 : fd_(fd),
154 tgt_(tgt),
155 next_range_(0),
156 current_range_left_(0),
157 bytes_written_(0) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700158 CHECK_NE(tgt.size(), static_cast<size_t>(0));
Tao Bao60a70af2017-03-26 14:03:52 -0700159 };
Tao Bao0940fe12015-08-27 16:41:21 -0700160
Tao Bao60a70af2017-03-26 14:03:52 -0700161 bool Finished() const {
Tao Baobf5b77d2017-03-30 16:57:29 -0700162 return next_range_ == tgt_.size() && current_range_left_ == 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700163 }
164
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700165 size_t AvailableSpace() const {
166 return tgt_.blocks() * BLOCKSIZE - bytes_written_;
167 }
168
169 // Return number of bytes written; and 0 indicates a writing failure.
170 size_t Write(const uint8_t* data, size_t size) {
Tao Bao60a70af2017-03-26 14:03:52 -0700171 if (Finished()) {
172 LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
173 return 0;
Tao Baof7eb7602017-03-27 15:12:48 -0700174 }
175
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700176 size_t written = 0;
Tao Bao60a70af2017-03-26 14:03:52 -0700177 while (size > 0) {
178 // Move to the next range as needed.
Tianjie Xu107a34f2017-06-29 17:04:21 -0700179 if (!SeekToOutputRange()) {
180 break;
Tao Bao60a70af2017-03-26 14:03:52 -0700181 }
Tao Baof7eb7602017-03-27 15:12:48 -0700182
Tao Bao60a70af2017-03-26 14:03:52 -0700183 size_t write_now = size;
184 if (current_range_left_ < write_now) {
185 write_now = current_range_left_;
186 }
Tao Baof7eb7602017-03-27 15:12:48 -0700187
Tao Bao60a70af2017-03-26 14:03:52 -0700188 if (write_all(fd_, data, write_now) == -1) {
Tao Baof7eb7602017-03-27 15:12:48 -0700189 break;
190 }
Tao Bao60a70af2017-03-26 14:03:52 -0700191
192 data += write_now;
193 size -= write_now;
194
195 current_range_left_ -= write_now;
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700196 written += write_now;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700197 }
Tao Bao60a70af2017-03-26 14:03:52 -0700198
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700199 bytes_written_ += written;
200 return written;
Tao Baof7eb7602017-03-27 15:12:48 -0700201 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700202
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700203 size_t BytesWritten() const {
204 return bytes_written_;
205 }
206
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700207 private:
Tianjie Xu107a34f2017-06-29 17:04:21 -0700208 // Set up the output cursor, move to next range if needed.
209 bool SeekToOutputRange() {
210 // We haven't finished the current range yet.
211 if (current_range_left_ != 0) {
212 return true;
213 }
214 // We can't write any more; let the write function return how many bytes have been written
215 // so far.
216 if (next_range_ >= tgt_.size()) {
217 return false;
218 }
219
220 const Range& range = tgt_[next_range_];
221 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
222 current_range_left_ = (range.second - range.first) * BLOCKSIZE;
223 next_range_++;
224
225 if (!discard_blocks(fd_, offset, current_range_left_)) {
226 return false;
227 }
228 if (!check_lseek(fd_, offset, SEEK_SET)) {
229 return false;
230 }
231 return true;
232 }
233
234 // The output file descriptor.
Tao Bao60a70af2017-03-26 14:03:52 -0700235 int fd_;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700236 // The destination ranges for the data.
Tao Bao60a70af2017-03-26 14:03:52 -0700237 const RangeSet& tgt_;
238 // The next range that we should write to.
239 size_t next_range_;
240 // The number of bytes to write before moving to the next range.
241 size_t current_range_left_;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700242 // Total bytes written by the writer.
243 size_t bytes_written_;
Tao Bao60a70af2017-03-26 14:03:52 -0700244};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700245
Tao Bao60a70af2017-03-26 14:03:52 -0700246/**
247 * All of the data for all the 'new' transfers is contained in one file in the update package,
248 * concatenated together in the order in which transfers.list will need it. We want to stream it out
249 * of the archive (it's compressed) without writing it to a temp file, but we can't write each
250 * section until it's that transfer's turn to go.
251 *
252 * To achieve this, we expand the new data from the archive in a background thread, and block that
253 * threads 'receive uncompressed data' function until the main thread has reached a point where we
254 * want some new data to be written. We signal the background thread with the destination for the
255 * data and block the main thread, waiting for the background thread to complete writing that
256 * section. Then it signals the main thread to wake up and goes back to blocking waiting for a
257 * transfer.
258 *
259 * NewThreadInfo is the struct used to pass information back and forth between the two threads. When
260 * the main thread wants some data written, it sets writer to the destination location and signals
261 * the condition. When the background thread is done writing, it clears writer and signals the
262 * condition again.
263 */
Tao Bao0940fe12015-08-27 16:41:21 -0700264struct NewThreadInfo {
Tao Bao60a70af2017-03-26 14:03:52 -0700265 ZipArchiveHandle za;
266 ZipEntry entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -0700267 bool brotli_compressed;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700268
Tianjie Xu107a34f2017-06-29 17:04:21 -0700269 std::unique_ptr<RangeSinkWriter> writer;
270 BrotliDecoderState* brotli_decoder_state;
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700271 bool receiver_available;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700272
Tao Bao60a70af2017-03-26 14:03:52 -0700273 pthread_mutex_t mu;
274 pthread_cond_t cv;
Tao Bao0940fe12015-08-27 16:41:21 -0700275};
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700276
Tianjie Xu8cf5c8f2016-09-08 20:10:11 -0700277static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
Tao Bao60a70af2017-03-26 14:03:52 -0700278 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700279
Tao Bao60a70af2017-03-26 14:03:52 -0700280 while (size > 0) {
281 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
282 pthread_mutex_lock(&nti->mu);
283 while (nti->writer == nullptr) {
284 pthread_cond_wait(&nti->cv, &nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700285 }
Tao Bao60a70af2017-03-26 14:03:52 -0700286 pthread_mutex_unlock(&nti->mu);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700287
Tao Bao60a70af2017-03-26 14:03:52 -0700288 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
289 // disappear from nti.
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700290 size_t write_now = std::min(size, nti->writer->AvailableSpace());
291 if (nti->writer->Write(data, write_now) != write_now) {
292 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
Tianjie Xu107a34f2017-06-29 17:04:21 -0700293 return false;
294 }
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700295
296 data += write_now;
297 size -= write_now;
298
299 if (nti->writer->Finished()) {
300 // We have written all the bytes desired by this writer.
301
302 pthread_mutex_lock(&nti->mu);
303 nti->writer = nullptr;
304 pthread_cond_broadcast(&nti->cv);
305 pthread_mutex_unlock(&nti->mu);
306 }
307 }
308
309 return true;
310}
311
312static bool receive_brotli_new_data(const uint8_t* data, size_t size, void* cookie) {
313 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
314
315 while (size > 0 || BrotliDecoderHasMoreOutput(nti->brotli_decoder_state)) {
316 // Wait for nti->writer to be non-null, indicating some of this data is wanted.
317 pthread_mutex_lock(&nti->mu);
318 while (nti->writer == nullptr) {
319 pthread_cond_wait(&nti->cv, &nti->mu);
320 }
321 pthread_mutex_unlock(&nti->mu);
322
323 // At this point nti->writer is set, and we own it. The main thread is waiting for it to
324 // disappear from nti.
325
326 size_t buffer_size = std::min<size_t>(32768, nti->writer->AvailableSpace());
327 if (buffer_size == 0) {
328 LOG(ERROR) << "No space left in output range";
329 return false;
330 }
331 uint8_t buffer[buffer_size];
332 size_t available_in = size;
333 size_t available_out = buffer_size;
334 uint8_t* next_out = buffer;
335
336 // The brotli decoder will update |data|, |available_in|, |next_out| and |available_out|.
337 BrotliDecoderResult result = BrotliDecoderDecompressStream(
338 nti->brotli_decoder_state, &available_in, &data, &available_out, &next_out, nullptr);
339
340 if (result == BROTLI_DECODER_RESULT_ERROR) {
341 LOG(ERROR) << "Decompression failed with "
342 << BrotliDecoderErrorString(BrotliDecoderGetErrorCode(nti->brotli_decoder_state));
343 return false;
344 }
345
346 LOG(DEBUG) << "bytes to write: " << buffer_size - available_out << ", bytes consumed "
347 << size - available_in << ", decoder status " << result;
348
349 size_t write_now = buffer_size - available_out;
350 if (nti->writer->Write(buffer, write_now) != write_now) {
351 LOG(ERROR) << "Failed to write " << write_now << " bytes.";
352 return false;
353 }
354
355 // Update the remaining size. The input data ptr is already updated by brotli decoder function.
356 size = available_in;
Tao Bao60a70af2017-03-26 14:03:52 -0700357
358 if (nti->writer->Finished()) {
359 // We have written all the bytes desired by this writer.
360
361 pthread_mutex_lock(&nti->mu);
362 nti->writer = nullptr;
363 pthread_cond_broadcast(&nti->cv);
364 pthread_mutex_unlock(&nti->mu);
365 }
366 }
367
368 return true;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700369}
370
371static void* unzip_new_data(void* cookie) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700372 NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
Tianjie Xu6ed175d2017-07-18 11:29:40 -0700373 if (nti->brotli_compressed) {
374 ProcessZipEntryContents(nti->za, &nti->entry, receive_brotli_new_data, nti);
375 } else {
376 ProcessZipEntryContents(nti->za, &nti->entry, receive_new_data, nti);
377 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -0700378 pthread_mutex_lock(&nti->mu);
379 nti->receiver_available = false;
380 if (nti->writer != nullptr) {
381 pthread_cond_broadcast(&nti->cv);
382 }
383 pthread_mutex_unlock(&nti->mu);
384 return nullptr;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -0700385}
386
Tao Bao612336d2015-08-27 16:41:21 -0700387static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700388 size_t p = 0;
389 for (const auto& range : src) {
390 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
391 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000392 }
393
Tao Baobf5b77d2017-03-30 16:57:29 -0700394 size_t size = (range.second - range.first) * BLOCKSIZE;
395 if (read_all(fd, buffer.data() + p, size) == -1) {
396 return -1;
397 }
398
399 p += size;
400 }
401
402 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000403}
404
Tao Bao612336d2015-08-27 16:41:21 -0700405static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
Tao Bao60a70af2017-03-26 14:03:52 -0700406 size_t written = 0;
Tao Baobf5b77d2017-03-30 16:57:29 -0700407 for (const auto& range : tgt) {
408 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
409 size_t size = (range.second - range.first) * BLOCKSIZE;
Tao Bao60a70af2017-03-26 14:03:52 -0700410 if (!discard_blocks(fd, offset, size)) {
411 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000412 }
413
Tao Bao60a70af2017-03-26 14:03:52 -0700414 if (!check_lseek(fd, offset, SEEK_SET)) {
415 return -1;
416 }
417
418 if (write_all(fd, buffer.data() + written, size) == -1) {
419 return -1;
420 }
421
422 written += size;
423 }
424
425 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000426}
427
Tao Baobaad2d42015-12-06 16:56:27 -0800428// Parameters for transfer list command functions
429struct CommandParameters {
430 std::vector<std::string> tokens;
431 size_t cpos;
432 const char* cmdname;
433 const char* cmdline;
434 std::string freestash;
435 std::string stashbase;
436 bool canwrite;
437 int createdstash;
Elliott Hughesbcabd092016-03-22 20:19:22 -0700438 android::base::unique_fd fd;
Tao Baobaad2d42015-12-06 16:56:27 -0800439 bool foundwrites;
440 bool isunresumable;
441 int version;
442 size_t written;
Tianjie Xudd874b12016-05-13 12:13:15 -0700443 size_t stashed;
Tao Baobaad2d42015-12-06 16:56:27 -0800444 NewThreadInfo nti;
445 pthread_t thread;
446 std::vector<uint8_t> buffer;
447 uint8_t* patch_start;
448};
449
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000450// Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
451// handled separately).
452static void PrintHashForCorruptedSourceBlocks(const CommandParameters& params,
453 const std::vector<uint8_t>& buffer) {
454 LOG(INFO) << "unexpected contents of source blocks in cmd:\n" << params.cmdline;
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000455 CHECK(params.tokens[0] == "move" || params.tokens[0] == "bsdiff" ||
456 params.tokens[0] == "imgdiff");
457
458 size_t pos = 0;
459 // Command example:
460 // move <onehash> <tgt_range> <src_blk_count> <src_range> [<loc_range> <stashed_blocks>]
461 // bsdiff <offset> <len> <src_hash> <tgt_hash> <tgt_range> <src_blk_count> <src_range>
462 // [<loc_range> <stashed_blocks>]
463 if (params.tokens[0] == "move") {
464 // src_range for move starts at the 4th position.
465 if (params.tokens.size() < 5) {
466 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
467 return;
468 }
469 pos = 4;
470 } else {
471 // src_range for diff starts at the 7th position.
472 if (params.tokens.size() < 8) {
473 LOG(ERROR) << "failed to parse source range in cmd:\n" << params.cmdline;
474 return;
475 }
476 pos = 7;
477 }
478
479 // Source blocks in stash only, no work to do.
480 if (params.tokens[pos] == "-") {
481 return;
482 }
483
Tao Bao8f237572017-03-26 13:36:49 -0700484 RangeSet src = RangeSet::Parse(params.tokens[pos++]);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000485
486 RangeSet locs;
487 // If there's no stashed blocks, content in the buffer is consecutive and has the same
488 // order as the source blocks.
489 if (pos == params.tokens.size()) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700490 locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000491 } else {
492 // Otherwise, the next token is the offset of the source blocks in the target range.
493 // Example: for the tokens <4,63946,63947,63948,63979> <4,6,7,8,39> <stashed_blocks>;
494 // We want to print SHA-1 for the data in buffer[6], buffer[8], buffer[9] ... buffer[38];
495 // this corresponds to the 32 src blocks #63946, #63948, #63949 ... #63978.
Tao Bao8f237572017-03-26 13:36:49 -0700496 locs = RangeSet::Parse(params.tokens[pos++]);
Tao Baobf5b77d2017-03-30 16:57:29 -0700497 CHECK_EQ(src.blocks(), locs.blocks());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000498 }
499
Tao Baobf5b77d2017-03-30 16:57:29 -0700500 LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
501 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700502 size_t block_num = src.GetBlockNumber(i);
503 size_t buffer_index = locs.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000504 CHECK_LE((buffer_index + 1) * BLOCKSIZE, buffer.size());
505
506 uint8_t digest[SHA_DIGEST_LENGTH];
507 SHA1(buffer.data() + buffer_index * BLOCKSIZE, BLOCKSIZE, digest);
508 std::string hexdigest = print_sha1(digest);
509 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
510 }
511}
512
513// If the calculated hash for the whole stash doesn't match the stash id, print the SHA-1
514// in hex for each block.
515static void PrintHashForCorruptedStashedBlocks(const std::string& id,
516 const std::vector<uint8_t>& buffer,
517 const RangeSet& src) {
518 LOG(INFO) << "printing hash in hex for stash_id: " << id;
Tao Baobf5b77d2017-03-30 16:57:29 -0700519 CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000520
Tao Baobf5b77d2017-03-30 16:57:29 -0700521 for (size_t i = 0; i < src.blocks(); i++) {
Tao Bao8f237572017-03-26 13:36:49 -0700522 size_t block_num = src.GetBlockNumber(i);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000523
524 uint8_t digest[SHA_DIGEST_LENGTH];
525 SHA1(buffer.data() + i * BLOCKSIZE, BLOCKSIZE, digest);
526 std::string hexdigest = print_sha1(digest);
527 LOG(INFO) << " block number: " << block_num << ", SHA-1: " << hexdigest;
528 }
529}
530
531// If the stash file doesn't exist, read the source blocks this stash contains and print the
532// SHA-1 for these blocks.
533static void PrintHashForMissingStashedBlocks(const std::string& id, int fd) {
534 if (stash_map.find(id) == stash_map.end()) {
535 LOG(ERROR) << "No stash saved for id: " << id;
536 return;
537 }
538
539 LOG(INFO) << "print hash in hex for source blocks in missing stash: " << id;
540 const RangeSet& src = stash_map[id];
Tao Baobf5b77d2017-03-30 16:57:29 -0700541 std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
Tianjie Xu2cd36ba2017-03-15 23:52:46 +0000542 if (ReadBlocks(src, buffer, fd) == -1) {
543 LOG(ERROR) << "failed to read source blocks for stash: " << id;
544 return;
545 }
546 PrintHashForCorruptedStashedBlocks(id, buffer, src);
547}
548
Tao Bao612336d2015-08-27 16:41:21 -0700549static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
Tao Bao0940fe12015-08-27 16:41:21 -0700550 const size_t blocks, bool printerror) {
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800551 uint8_t digest[SHA_DIGEST_LENGTH];
Tao Bao612336d2015-08-27 16:41:21 -0700552 const uint8_t* data = buffer.data();
Sami Tolvanen90221202014-12-09 16:39:47 +0000553
Sen Jiangc48cb5e2016-02-04 16:23:21 +0800554 SHA1(data, blocks * BLOCKSIZE, digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000555
Tao Baoe6aa3322015-08-05 15:20:27 -0700556 std::string hexdigest = print_sha1(digest);
Sami Tolvanen90221202014-12-09 16:39:47 +0000557
Tao Bao0940fe12015-08-27 16:41:21 -0700558 if (hexdigest != expected) {
559 if (printerror) {
Tao Bao039f2da2016-11-22 16:29:50 -0800560 LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
561 << hexdigest << ")";
Tao Bao0940fe12015-08-27 16:41:21 -0700562 }
563 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000564 }
565
Tao Bao0940fe12015-08-27 16:41:21 -0700566 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000567}
568
Tao Bao0940fe12015-08-27 16:41:21 -0700569static std::string GetStashFileName(const std::string& base, const std::string& id,
570 const std::string& postfix) {
Tao Baoe6aa3322015-08-05 15:20:27 -0700571 if (base.empty()) {
572 return "";
Sami Tolvanen90221202014-12-09 16:39:47 +0000573 }
574
Tao Baoe6aa3322015-08-05 15:20:27 -0700575 std::string fn(STASH_DIRECTORY_BASE);
576 fn += "/" + base + "/" + id + postfix;
Sami Tolvanen90221202014-12-09 16:39:47 +0000577
578 return fn;
579}
580
Tao Baoec8272f2017-03-15 17:39:01 -0700581// Does a best effort enumeration of stash files. Ignores possible non-file items in the stash
582// directory and continues despite of errors. Calls the 'callback' function for each file.
583static void EnumerateStash(const std::string& dirname,
584 const std::function<void(const std::string&)>& callback) {
585 if (dirname.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000586
Tao Baoec8272f2017-03-15 17:39:01 -0700587 std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
Sami Tolvanen90221202014-12-09 16:39:47 +0000588
Tao Baoec8272f2017-03-15 17:39:01 -0700589 if (directory == nullptr) {
590 if (errno != ENOENT) {
591 PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000592 }
Tao Bao51412212016-12-28 14:44:05 -0800593 return;
594 }
Tao Baoe6aa3322015-08-05 15:20:27 -0700595
Tao Baoec8272f2017-03-15 17:39:01 -0700596 dirent* item;
597 while ((item = readdir(directory.get())) != nullptr) {
598 if (item->d_type != DT_REG) continue;
599 callback(dirname + "/" + item->d_name);
Tao Bao51412212016-12-28 14:44:05 -0800600 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000601}
602
603// Deletes the stash directory and all files in it. Assumes that it only
604// contains files. There is nothing we can do about unlikely, but possible
605// errors, so they are merely logged.
Tao Baoec8272f2017-03-15 17:39:01 -0700606static void DeleteFile(const std::string& fn) {
607 if (fn.empty()) return;
Sami Tolvanen90221202014-12-09 16:39:47 +0000608
Tao Baoec8272f2017-03-15 17:39:01 -0700609 LOG(INFO) << "deleting " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000610
Tao Baoec8272f2017-03-15 17:39:01 -0700611 if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
612 PLOG(ERROR) << "unlink \"" << fn << "\" failed";
613 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000614}
615
Tao Baoe6aa3322015-08-05 15:20:27 -0700616static void DeleteStash(const std::string& base) {
Tao Baoec8272f2017-03-15 17:39:01 -0700617 if (base.empty()) return;
618
619 LOG(INFO) << "deleting stash " << base;
620
621 std::string dirname = GetStashFileName(base, "", "");
622 EnumerateStash(dirname, DeleteFile);
623
624 if (rmdir(dirname.c_str()) == -1) {
625 if (errno != ENOENT && errno != ENOTDIR) {
626 PLOG(ERROR) << "rmdir \"" << dirname << "\" failed";
Sami Tolvanen90221202014-12-09 16:39:47 +0000627 }
Tao Baoec8272f2017-03-15 17:39:01 -0700628 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000629}
630
Tao Baobcf46492017-03-23 15:28:20 -0700631static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
632 std::vector<uint8_t>& buffer, bool printnoent) {
Tao Baobf5b77d2017-03-30 16:57:29 -0700633 // In verify mode, if source range_set was saved for the given hash, check contents in the source
634 // blocks first. If the check fails, search for the stashed files on /cache as usual.
635 if (!params.canwrite) {
636 if (stash_map.find(id) != stash_map.end()) {
637 const RangeSet& src = stash_map[id];
638 allocate(src.blocks() * BLOCKSIZE, buffer);
Tianjie Xu7eca97e2016-03-22 18:08:12 -0700639
Tao Baobf5b77d2017-03-30 16:57:29 -0700640 if (ReadBlocks(src, buffer, params.fd) == -1) {
641 LOG(ERROR) << "failed to read source blocks in stash map.";
Tao Bao0940fe12015-08-27 16:41:21 -0700642 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700643 }
644 if (VerifyBlocks(id, buffer, src.blocks(), true) != 0) {
645 LOG(ERROR) << "failed to verify loaded source blocks in stash map.";
646 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Tao Bao0940fe12015-08-27 16:41:21 -0700647 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -0700648 }
649 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000650 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700651 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000652
Tao Baobf5b77d2017-03-30 16:57:29 -0700653 size_t blockcount = 0;
654 if (!blocks) {
655 blocks = &blockcount;
656 }
657
658 std::string fn = GetStashFileName(params.stashbase, id, "");
659
660 struct stat sb;
661 if (stat(fn.c_str(), &sb) == -1) {
662 if (errno != ENOENT || printnoent) {
663 PLOG(ERROR) << "stat \"" << fn << "\" failed";
664 PrintHashForMissingStashedBlocks(id, params.fd);
Sami Tolvanen90221202014-12-09 16:39:47 +0000665 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700666 return -1;
667 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000668
Tao Baobf5b77d2017-03-30 16:57:29 -0700669 LOG(INFO) << " loading " << fn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000670
Tao Baobf5b77d2017-03-30 16:57:29 -0700671 if ((sb.st_size % BLOCKSIZE) != 0) {
672 LOG(ERROR) << fn << " size " << sb.st_size << " not multiple of block size " << BLOCKSIZE;
673 return -1;
674 }
675
676 android::base::unique_fd fd(TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_RDONLY)));
677 if (fd == -1) {
678 PLOG(ERROR) << "open \"" << fn << "\" failed";
679 return -1;
680 }
681
682 allocate(sb.st_size, buffer);
683
684 if (read_all(fd, buffer, sb.st_size) == -1) {
685 return -1;
686 }
687
688 *blocks = sb.st_size / BLOCKSIZE;
689
690 if (verify && VerifyBlocks(id, buffer, *blocks, true) != 0) {
691 LOG(ERROR) << "unexpected contents in " << fn;
692 if (stash_map.find(id) == stash_map.end()) {
693 LOG(ERROR) << "failed to find source blocks number for stash " << id
694 << " when executing command: " << params.cmdname;
695 } else {
696 const RangeSet& src = stash_map[id];
697 PrintHashForCorruptedStashedBlocks(id, buffer, src);
Sami Tolvanen90221202014-12-09 16:39:47 +0000698 }
Tao Baobf5b77d2017-03-30 16:57:29 -0700699 DeleteFile(fn);
700 return -1;
701 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000702
Tao Baobf5b77d2017-03-30 16:57:29 -0700703 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000704}
705
Tao Bao612336d2015-08-27 16:41:21 -0700706static int WriteStash(const std::string& base, const std::string& id, int blocks,
Tao Baod2aecd42017-03-23 14:43:44 -0700707 std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
Tao Bao612336d2015-08-27 16:41:21 -0700708 if (base.empty()) {
Tao Bao0940fe12015-08-27 16:41:21 -0700709 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000710 }
711
712 if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
Tao Bao039f2da2016-11-22 16:29:50 -0800713 LOG(ERROR) << "not enough space to write stash";
Tao Bao0940fe12015-08-27 16:41:21 -0700714 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000715 }
716
Tao Bao0940fe12015-08-27 16:41:21 -0700717 std::string fn = GetStashFileName(base, id, ".partial");
718 std::string cn = GetStashFileName(base, id, "");
Sami Tolvanen90221202014-12-09 16:39:47 +0000719
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100720 if (exists) {
Tao Bao0940fe12015-08-27 16:41:21 -0700721 struct stat sb;
722 int res = stat(cn.c_str(), &sb);
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100723
724 if (res == 0) {
725 // The file already exists and since the name is the hash of the contents,
726 // it's safe to assume the contents are identical (accidental hash collisions
727 // are unlikely)
Tao Bao039f2da2016-11-22 16:29:50 -0800728 LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
Tao Bao0940fe12015-08-27 16:41:21 -0700729 *exists = true;
730 return 0;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100731 }
732
Tao Bao0940fe12015-08-27 16:41:21 -0700733 *exists = false;
Sami Tolvanen43b748f2015-04-17 12:50:31 +0100734 }
735
Tao Bao039f2da2016-11-22 16:29:50 -0800736 LOG(INFO) << " writing " << blocks << " blocks to " << cn;
Sami Tolvanen90221202014-12-09 16:39:47 +0000737
Tao Bao039f2da2016-11-22 16:29:50 -0800738 android::base::unique_fd fd(
739 TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
Sami Tolvanen90221202014-12-09 16:39:47 +0000740 if (fd == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800741 PLOG(ERROR) << "failed to create \"" << fn << "\"";
Tao Bao0940fe12015-08-27 16:41:21 -0700742 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000743 }
744
Tianjie Xua946b9e2017-03-21 16:24:57 -0700745 if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) { // system user
746 PLOG(ERROR) << "failed to chown \"" << fn << "\"";
747 return -1;
748 }
749
Sami Tolvanen90221202014-12-09 16:39:47 +0000750 if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
Tao Bao0940fe12015-08-27 16:41:21 -0700751 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000752 }
753
Jed Estepa7b9a462015-12-15 16:04:53 -0800754 if (ota_fsync(fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700755 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800756 PLOG(ERROR) << "fsync \"" << fn << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700757 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000758 }
759
Tao Baoe6aa3322015-08-05 15:20:27 -0700760 if (rename(fn.c_str(), cn.c_str()) == -1) {
Tao Bao039f2da2016-11-22 16:29:50 -0800761 PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700762 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000763 }
764
Tao Bao0940fe12015-08-27 16:41:21 -0700765 std::string dname = GetStashFileName(base, "", "");
Elliott Hughesbcabd092016-03-22 20:19:22 -0700766 android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
767 O_RDONLY | O_DIRECTORY)));
Tao Baodc392262015-07-31 15:56:44 -0700768 if (dfd == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700769 failure_type = kFileOpenFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800770 PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700771 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700772 }
773
Jed Estepa7b9a462015-12-15 16:04:53 -0800774 if (ota_fsync(dfd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -0700775 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -0800776 PLOG(ERROR) << "fsync \"" << dname << "\" failed";
Tao Bao0940fe12015-08-27 16:41:21 -0700777 return -1;
Tao Baodc392262015-07-31 15:56:44 -0700778 }
779
Tao Bao0940fe12015-08-27 16:41:21 -0700780 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000781}
782
783// Creates a directory for storing stash files and checks if the /cache partition
784// hash enough space for the expected amount of blocks we need to store. Returns
785// >0 if we created the directory, zero if it existed already, and <0 of failure.
786
Tao Bao51412212016-12-28 14:44:05 -0800787static int CreateStash(State* state, size_t maxblocks, const std::string& blockdev,
788 std::string& base) {
789 if (blockdev.empty()) {
790 return -1;
791 }
792
793 // Stash directory should be different for each partition to avoid conflicts
794 // when updating multiple partitions at the same time, so we use the hash of
795 // the block device name as the base directory
796 uint8_t digest[SHA_DIGEST_LENGTH];
797 SHA1(reinterpret_cast<const uint8_t*>(blockdev.data()), blockdev.size(), digest);
798 base = print_sha1(digest);
799
800 std::string dirname = GetStashFileName(base, "", "");
801 struct stat sb;
802 int res = stat(dirname.c_str(), &sb);
803 size_t max_stash_size = maxblocks * BLOCKSIZE;
804
805 if (res == -1 && errno != ENOENT) {
806 ErrorAbort(state, kStashCreationFailure, "stat \"%s\" failed: %s\n", dirname.c_str(),
807 strerror(errno));
808 return -1;
809 } else if (res != 0) {
810 LOG(INFO) << "creating stash " << dirname;
811 res = mkdir(dirname.c_str(), STASH_DIRECTORY_MODE);
812
813 if (res != 0) {
814 ErrorAbort(state, kStashCreationFailure, "mkdir \"%s\" failed: %s\n", dirname.c_str(),
815 strerror(errno));
816 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000817 }
818
Tianjie Xua946b9e2017-03-21 16:24:57 -0700819 if (chown(dirname.c_str(), AID_SYSTEM, AID_SYSTEM) != 0) { // system user
820 ErrorAbort(state, kStashCreationFailure, "chown \"%s\" failed: %s\n", dirname.c_str(),
821 strerror(errno));
822 return -1;
823 }
824
Tao Bao51412212016-12-28 14:44:05 -0800825 if (CacheSizeCheck(max_stash_size) != 0) {
826 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu needed)\n",
827 max_stash_size);
828 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000829 }
830
Tao Bao51412212016-12-28 14:44:05 -0800831 return 1; // Created directory
832 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000833
Tao Bao51412212016-12-28 14:44:05 -0800834 LOG(INFO) << "using existing stash " << dirname;
Sami Tolvanen90221202014-12-09 16:39:47 +0000835
Tao Baoec8272f2017-03-15 17:39:01 -0700836 // If the directory already exists, calculate the space already allocated to stash files and check
837 // if there's enough for all required blocks. Delete any partially completed stash files first.
838 EnumerateStash(dirname, [](const std::string& fn) {
839 if (android::base::EndsWith(fn, ".partial")) {
840 DeleteFile(fn);
841 }
842 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000843
Tao Bao51412212016-12-28 14:44:05 -0800844 size_t existing = 0;
Tao Baoec8272f2017-03-15 17:39:01 -0700845 EnumerateStash(dirname, [&existing](const std::string& fn) {
846 if (fn.empty()) return;
847 struct stat sb;
848 if (stat(fn.c_str(), &sb) == -1) {
849 PLOG(ERROR) << "stat \"" << fn << "\" failed";
850 return;
851 }
852 existing += static_cast<size_t>(sb.st_size);
853 });
Sami Tolvanen90221202014-12-09 16:39:47 +0000854
Tao Bao51412212016-12-28 14:44:05 -0800855 if (max_stash_size > existing) {
856 size_t needed = max_stash_size - existing;
857 if (CacheSizeCheck(needed) != 0) {
858 ErrorAbort(state, kStashCreationFailure, "not enough space for stash (%zu more needed)\n",
859 needed);
860 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +0000861 }
Tao Bao51412212016-12-28 14:44:05 -0800862 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000863
Tao Bao51412212016-12-28 14:44:05 -0800864 return 0; // Using existing directory
Sami Tolvanen90221202014-12-09 16:39:47 +0000865}
866
Tao Baobaad2d42015-12-06 16:56:27 -0800867static int FreeStash(const std::string& base, const std::string& id) {
Tao Baoec8272f2017-03-15 17:39:01 -0700868 if (base.empty() || id.empty()) {
869 return -1;
870 }
Sami Tolvanen90221202014-12-09 16:39:47 +0000871
Tao Baoec8272f2017-03-15 17:39:01 -0700872 DeleteFile(GetStashFileName(base, id, ""));
Sami Tolvanen90221202014-12-09 16:39:47 +0000873
Tao Baoec8272f2017-03-15 17:39:01 -0700874 return 0;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700875}
876
Tao Baobf5b77d2017-03-30 16:57:29 -0700877// Source contains packed data, which we want to move to the locations given in locs in the dest
878// buffer. source and dest may be the same buffer.
Tao Bao612336d2015-08-27 16:41:21 -0700879static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
Tao Baobf5b77d2017-03-30 16:57:29 -0700880 const std::vector<uint8_t>& source) {
881 const uint8_t* from = source.data();
882 uint8_t* to = dest.data();
883 size_t start = locs.blocks();
884 // Must do the movement backward.
885 for (auto it = locs.crbegin(); it != locs.crend(); it++) {
886 size_t blocks = it->second - it->first;
887 start -= blocks;
888 memmove(to + (it->first * BLOCKSIZE), from + (start * BLOCKSIZE), blocks * BLOCKSIZE);
889 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700890}
891
Tao Baod2aecd42017-03-23 14:43:44 -0700892/**
893 * We expect to parse the remainder of the parameter tokens as one of:
894 *
895 * <src_block_count> <src_range>
896 * (loads data from source image only)
897 *
898 * <src_block_count> - <[stash_id:stash_range] ...>
899 * (loads data from stashes only)
900 *
901 * <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
902 * (loads data from both source image and stashes)
903 *
904 * On return, params.buffer is filled with the loaded source data (rearranged and combined with
905 * stashed data as necessary). buffer may be reallocated if needed to accommodate the source data.
906 * tgt is the target RangeSet for detecting overlaps. Any stashes required are loaded using
907 * LoadStash.
908 */
909static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
910 bool* overlap) {
911 CHECK(src_blocks != nullptr);
912 CHECK(overlap != nullptr);
Doug Zongker52ae67d2014-09-08 12:22:09 -0700913
Tao Baod2aecd42017-03-23 14:43:44 -0700914 // <src_block_count>
915 const std::string& token = params.tokens[params.cpos++];
916 if (!android::base::ParseUint(token, src_blocks)) {
917 LOG(ERROR) << "invalid src_block_count \"" << token << "\"";
918 return -1;
919 }
Tao Baobaad2d42015-12-06 16:56:27 -0800920
Tao Baod2aecd42017-03-23 14:43:44 -0700921 allocate(*src_blocks * BLOCKSIZE, params.buffer);
922
923 // "-" or <src_range> [<src_loc>]
924 if (params.tokens[params.cpos] == "-") {
925 // no source ranges, only stashes
926 params.cpos++;
927 } else {
Tao Bao8f237572017-03-26 13:36:49 -0700928 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
929 *overlap = src.Overlaps(tgt);
Tao Baod2aecd42017-03-23 14:43:44 -0700930
931 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
932 return -1;
Tao Baobaad2d42015-12-06 16:56:27 -0800933 }
934
Tao Baod2aecd42017-03-23 14:43:44 -0700935 if (params.cpos >= params.tokens.size()) {
936 // no stashes, only source range
937 return 0;
Tao Baobaad2d42015-12-06 16:56:27 -0800938 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700939
Tao Bao8f237572017-03-26 13:36:49 -0700940 RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -0700941 MoveRange(params.buffer, locs, params.buffer);
942 }
Doug Zongker52ae67d2014-09-08 12:22:09 -0700943
Tao Baod2aecd42017-03-23 14:43:44 -0700944 // <[stash_id:stash_range]>
945 while (params.cpos < params.tokens.size()) {
946 // Each word is a an index into the stash table, a colon, and then a RangeSet describing where
947 // in the source block that stashed data should go.
948 std::vector<std::string> tokens = android::base::Split(params.tokens[params.cpos++], ":");
949 if (tokens.size() != 2) {
950 LOG(ERROR) << "invalid parameter";
951 return -1;
Doug Zongker52ae67d2014-09-08 12:22:09 -0700952 }
953
Tao Baod2aecd42017-03-23 14:43:44 -0700954 std::vector<uint8_t> stash;
955 if (LoadStash(params, tokens[0], false, nullptr, stash, true) == -1) {
956 // These source blocks will fail verification if used later, but we
957 // will let the caller decide if this is a fatal failure
958 LOG(ERROR) << "failed to load stash " << tokens[0];
959 continue;
Sami Tolvanen90221202014-12-09 16:39:47 +0000960 }
961
Tao Bao8f237572017-03-26 13:36:49 -0700962 RangeSet locs = RangeSet::Parse(tokens[1]);
Tao Baod2aecd42017-03-23 14:43:44 -0700963 MoveRange(params.buffer, locs, stash);
964 }
965
966 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +0000967}
968
Tao Bao33567772017-03-13 14:57:34 -0700969/**
970 * Do a source/target load for move/bsdiff/imgdiff in version 3.
971 *
972 * We expect to parse the remainder of the parameter tokens as one of:
973 *
974 * <tgt_range> <src_block_count> <src_range>
975 * (loads data from source image only)
976 *
977 * <tgt_range> <src_block_count> - <[stash_id:stash_range] ...>
978 * (loads data from stashes only)
979 *
980 * <tgt_range> <src_block_count> <src_range> <src_loc> <[stash_id:stash_range] ...>
981 * (loads data from both source image and stashes)
982 *
Tao Baod2aecd42017-03-23 14:43:44 -0700983 * 'onehash' tells whether to expect separate source and targe block hashes, or if they are both the
984 * same and only one hash should be expected. params.isunresumable will be set to true if block
Tao Bao33567772017-03-13 14:57:34 -0700985 * verification fails in a way that the update cannot be resumed anymore.
986 *
987 * If the function is unable to load the necessary blocks or their contents don't match the hashes,
988 * the return value is -1 and the command should be aborted.
989 *
990 * If the return value is 1, the command has already been completed according to the contents of the
991 * target blocks, and should not be performed again.
992 *
993 * If the return value is 0, source blocks have expected content and the command can be performed.
994 */
Tao Baod2aecd42017-03-23 14:43:44 -0700995static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
996 bool onehash, bool* overlap) {
997 CHECK(src_blocks != nullptr);
998 CHECK(overlap != nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +0000999
Tao Baod2aecd42017-03-23 14:43:44 -07001000 if (params.cpos >= params.tokens.size()) {
1001 LOG(ERROR) << "missing source hash";
Tao Bao0940fe12015-08-27 16:41:21 -07001002 return -1;
Tao Baod2aecd42017-03-23 14:43:44 -07001003 }
1004
1005 std::string srchash = params.tokens[params.cpos++];
1006 std::string tgthash;
1007
1008 if (onehash) {
1009 tgthash = srchash;
1010 } else {
1011 if (params.cpos >= params.tokens.size()) {
1012 LOG(ERROR) << "missing target hash";
1013 return -1;
1014 }
1015 tgthash = params.tokens[params.cpos++];
1016 }
1017
1018 // At least it needs to provide three parameters: <tgt_range>, <src_block_count> and
1019 // "-"/<src_range>.
1020 if (params.cpos + 2 >= params.tokens.size()) {
1021 LOG(ERROR) << "invalid parameters";
1022 return -1;
1023 }
1024
1025 // <tgt_range>
Tao Bao8f237572017-03-26 13:36:49 -07001026 tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baod2aecd42017-03-23 14:43:44 -07001027
Tao Baobf5b77d2017-03-30 16:57:29 -07001028 std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
Tao Baod2aecd42017-03-23 14:43:44 -07001029 if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1030 return -1;
1031 }
1032
1033 // Return now if target blocks already have expected content.
Tao Baobf5b77d2017-03-30 16:57:29 -07001034 if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
Tao Baod2aecd42017-03-23 14:43:44 -07001035 return 1;
1036 }
1037
1038 // Load source blocks.
1039 if (LoadSourceBlocks(params, tgt, src_blocks, overlap) == -1) {
1040 return -1;
1041 }
1042
1043 if (VerifyBlocks(srchash, params.buffer, *src_blocks, true) == 0) {
1044 // If source and target blocks overlap, stash the source blocks so we can
1045 // resume from possible write errors. In verify mode, we can skip stashing
1046 // because the source blocks won't be overwritten.
1047 if (*overlap && params.canwrite) {
1048 LOG(INFO) << "stashing " << *src_blocks << " overlapping blocks to " << srchash;
1049
1050 bool stash_exists = false;
1051 if (WriteStash(params.stashbase, srchash, *src_blocks, params.buffer, true,
1052 &stash_exists) != 0) {
1053 LOG(ERROR) << "failed to stash overlapping source blocks";
1054 return -1;
1055 }
1056
1057 params.stashed += *src_blocks;
1058 // Can be deleted when the write has completed.
1059 if (!stash_exists) {
1060 params.freestash = srchash;
1061 }
1062 }
1063
1064 // Source blocks have expected content, command can proceed.
1065 return 0;
1066 }
1067
1068 if (*overlap && LoadStash(params, srchash, true, nullptr, params.buffer, true) == 0) {
1069 // Overlapping source blocks were previously stashed, command can proceed. We are recovering
1070 // from an interrupted command, so we don't know if the stash can safely be deleted after this
1071 // command.
1072 return 0;
1073 }
1074
1075 // Valid source data not available, update cannot be resumed.
1076 LOG(ERROR) << "partition has unexpected contents";
1077 PrintHashForCorruptedSourceBlocks(params, params.buffer);
1078
1079 params.isunresumable = true;
1080
1081 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001082}
1083
Tao Bao0940fe12015-08-27 16:41:21 -07001084static int PerformCommandMove(CommandParameters& params) {
Tao Bao33567772017-03-13 14:57:34 -07001085 size_t blocks = 0;
1086 bool overlap = false;
1087 RangeSet tgt;
Tao Baod2aecd42017-03-23 14:43:44 -07001088 int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
Sami Tolvanen90221202014-12-09 16:39:47 +00001089
Tao Bao33567772017-03-13 14:57:34 -07001090 if (status == -1) {
1091 LOG(ERROR) << "failed to read blocks for move";
1092 return -1;
1093 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001094
Tao Bao33567772017-03-13 14:57:34 -07001095 if (status == 0) {
1096 params.foundwrites = true;
1097 } else if (params.foundwrites) {
1098 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1099 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001100
Tao Bao33567772017-03-13 14:57:34 -07001101 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001102 if (status == 0) {
Tao Bao33567772017-03-13 14:57:34 -07001103 LOG(INFO) << " moving " << blocks << " blocks";
1104
1105 if (WriteBlocks(tgt, params.buffer, params.fd) == -1) {
1106 return -1;
1107 }
1108 } else {
1109 LOG(INFO) << "skipping " << blocks << " already moved blocks";
Sami Tolvanen90221202014-12-09 16:39:47 +00001110 }
Tao Bao33567772017-03-13 14:57:34 -07001111 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001112
Tao Bao33567772017-03-13 14:57:34 -07001113 if (!params.freestash.empty()) {
1114 FreeStash(params.stashbase, params.freestash);
1115 params.freestash.clear();
1116 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001117
Tao Baobf5b77d2017-03-30 16:57:29 -07001118 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001119
Tao Bao33567772017-03-13 14:57:34 -07001120 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001121}
1122
Tao Bao0940fe12015-08-27 16:41:21 -07001123static int PerformCommandStash(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001124 // <stash_id> <src_range>
1125 if (params.cpos + 1 >= params.tokens.size()) {
1126 LOG(ERROR) << "missing id and/or src range fields in stash command";
1127 return -1;
1128 }
1129
1130 const std::string& id = params.tokens[params.cpos++];
1131 size_t blocks = 0;
1132 if (LoadStash(params, id, true, &blocks, params.buffer, false) == 0) {
1133 // Stash file already exists and has expected contents. Do not read from source again, as the
1134 // source may have been already overwritten during a previous attempt.
1135 return 0;
1136 }
1137
Tao Bao8f237572017-03-26 13:36:49 -07001138 RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Baobcf46492017-03-23 15:28:20 -07001139
Tao Baobf5b77d2017-03-30 16:57:29 -07001140 allocate(src.blocks() * BLOCKSIZE, params.buffer);
Tao Baobcf46492017-03-23 15:28:20 -07001141 if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1142 return -1;
1143 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001144 blocks = src.blocks();
Tao Baobcf46492017-03-23 15:28:20 -07001145 stash_map[id] = src;
1146
1147 if (VerifyBlocks(id, params.buffer, blocks, true) != 0) {
1148 // Source blocks have unexpected contents. If we actually need this data later, this is an
1149 // unrecoverable error. However, the command that uses the data may have already completed
1150 // previously, so the possible failure will occur during source block verification.
1151 LOG(ERROR) << "failed to load source blocks for stash " << id;
1152 return 0;
1153 }
1154
1155 // In verify mode, we don't need to stash any blocks.
1156 if (!params.canwrite) {
1157 return 0;
1158 }
1159
1160 LOG(INFO) << "stashing " << blocks << " blocks to " << id;
1161 params.stashed += blocks;
1162 return WriteStash(params.stashbase, id, blocks, params.buffer, false, nullptr);
Sami Tolvanen90221202014-12-09 16:39:47 +00001163}
1164
Tao Bao0940fe12015-08-27 16:41:21 -07001165static int PerformCommandFree(CommandParameters& params) {
Tao Baobcf46492017-03-23 15:28:20 -07001166 // <stash_id>
1167 if (params.cpos >= params.tokens.size()) {
1168 LOG(ERROR) << "missing stash id in free command";
1169 return -1;
1170 }
Tao Baobaad2d42015-12-06 16:56:27 -08001171
Tao Baobcf46492017-03-23 15:28:20 -07001172 const std::string& id = params.tokens[params.cpos++];
1173 stash_map.erase(id);
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001174
Tao Baobcf46492017-03-23 15:28:20 -07001175 if (params.createdstash || params.canwrite) {
1176 return FreeStash(params.stashbase, id);
1177 }
Tianjie Xu7eca97e2016-03-22 18:08:12 -07001178
Tao Baobcf46492017-03-23 15:28:20 -07001179 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001180}
1181
Tao Bao0940fe12015-08-27 16:41:21 -07001182static int PerformCommandZero(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001183 if (params.cpos >= params.tokens.size()) {
1184 LOG(ERROR) << "missing target blocks for zero";
1185 return -1;
1186 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001187
Tao Baobf5b77d2017-03-30 16:57:29 -07001188 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1189
1190 LOG(INFO) << " zeroing " << tgt.blocks() << " blocks";
1191
1192 allocate(BLOCKSIZE, params.buffer);
1193 memset(params.buffer.data(), 0, BLOCKSIZE);
1194
1195 if (params.canwrite) {
1196 for (const auto& range : tgt) {
1197 off64_t offset = static_cast<off64_t>(range.first) * BLOCKSIZE;
1198 size_t size = (range.second - range.first) * BLOCKSIZE;
1199 if (!discard_blocks(params.fd, offset, size)) {
Tao Bao0940fe12015-08-27 16:41:21 -07001200 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001201 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001202
Tao Baobf5b77d2017-03-30 16:57:29 -07001203 if (!check_lseek(params.fd, offset, SEEK_SET)) {
1204 return -1;
1205 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001206
Tao Baobf5b77d2017-03-30 16:57:29 -07001207 for (size_t j = range.first; j < range.second; ++j) {
1208 if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1209 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001210 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001211 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001212 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001213 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001214
Tao Baobf5b77d2017-03-30 16:57:29 -07001215 if (params.cmdname[0] == 'z') {
1216 // Update only for the zero command, as the erase command will call
1217 // this if DEBUG_ERASE is defined.
1218 params.written += tgt.blocks();
1219 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001220
Tao Baobf5b77d2017-03-30 16:57:29 -07001221 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001222}
1223
Tao Bao0940fe12015-08-27 16:41:21 -07001224static int PerformCommandNew(CommandParameters& params) {
Tao Bao60a70af2017-03-26 14:03:52 -07001225 if (params.cpos >= params.tokens.size()) {
1226 LOG(ERROR) << "missing target blocks for new";
1227 return -1;
1228 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001229
Tao Bao8f237572017-03-26 13:36:49 -07001230 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
Tao Bao60a70af2017-03-26 14:03:52 -07001231
1232 if (params.canwrite) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001233 LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
Tao Bao60a70af2017-03-26 14:03:52 -07001234
Tao Bao60a70af2017-03-26 14:03:52 -07001235 pthread_mutex_lock(&params.nti.mu);
Tianjie Xu6ed175d2017-07-18 11:29:40 -07001236 params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
Tao Bao60a70af2017-03-26 14:03:52 -07001237 pthread_cond_broadcast(&params.nti.cv);
1238
1239 while (params.nti.writer != nullptr) {
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001240 if (!params.nti.receiver_available) {
1241 LOG(ERROR) << "missing " << (tgt.blocks() * BLOCKSIZE - params.nti.writer->BytesWritten())
1242 << " bytes of new data";
1243 pthread_mutex_unlock(&params.nti.mu);
1244 return -1;
1245 }
Tao Bao60a70af2017-03-26 14:03:52 -07001246 pthread_cond_wait(&params.nti.cv, &params.nti.mu);
Sami Tolvanen90221202014-12-09 16:39:47 +00001247 }
1248
Tao Bao60a70af2017-03-26 14:03:52 -07001249 pthread_mutex_unlock(&params.nti.mu);
1250 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001251
Tao Baobf5b77d2017-03-30 16:57:29 -07001252 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001253
Tao Bao60a70af2017-03-26 14:03:52 -07001254 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001255}
1256
Tao Bao0940fe12015-08-27 16:41:21 -07001257static int PerformCommandDiff(CommandParameters& params) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001258 // <offset> <length>
1259 if (params.cpos + 1 >= params.tokens.size()) {
1260 LOG(ERROR) << "missing patch offset or length for " << params.cmdname;
1261 return -1;
1262 }
Tao Bao0940fe12015-08-27 16:41:21 -07001263
Tao Baoc0e1c462017-02-01 10:20:10 -08001264 size_t offset;
1265 if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1266 LOG(ERROR) << "invalid patch offset";
1267 return -1;
1268 }
Tao Bao0940fe12015-08-27 16:41:21 -07001269
Tao Baoc0e1c462017-02-01 10:20:10 -08001270 size_t len;
1271 if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1272 LOG(ERROR) << "invalid patch len";
1273 return -1;
1274 }
Tao Bao0940fe12015-08-27 16:41:21 -07001275
Tao Baoc0e1c462017-02-01 10:20:10 -08001276 RangeSet tgt;
1277 size_t blocks = 0;
1278 bool overlap = false;
1279 int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
Tao Bao0940fe12015-08-27 16:41:21 -07001280
Tao Baoc0e1c462017-02-01 10:20:10 -08001281 if (status == -1) {
1282 LOG(ERROR) << "failed to read blocks for diff";
1283 return -1;
1284 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001285
Tao Baoc0e1c462017-02-01 10:20:10 -08001286 if (status == 0) {
1287 params.foundwrites = true;
1288 } else if (params.foundwrites) {
1289 LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1290 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001291
Tao Baoc0e1c462017-02-01 10:20:10 -08001292 if (params.canwrite) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001293 if (status == 0) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001294 LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
Tao Baoc0e1c462017-02-01 10:20:10 -08001295 Value patch_value(
1296 VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
Sami Tolvanen90221202014-12-09 16:39:47 +00001297
Tao Bao60a70af2017-03-26 14:03:52 -07001298 RangeSinkWriter writer(params.fd, tgt);
Tao Baoc0e1c462017-02-01 10:20:10 -08001299 if (params.cmdname[0] == 'i') { // imgdiff
Tao Bao60a70af2017-03-26 14:03:52 -07001300 if (ApplyImagePatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value,
1301 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1302 std::placeholders::_2),
1303 nullptr, nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001304 LOG(ERROR) << "Failed to apply image patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001305 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001306 return -1;
Sami Tolvanen90221202014-12-09 16:39:47 +00001307 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001308 } else {
Tao Bao60a70af2017-03-26 14:03:52 -07001309 if (ApplyBSDiffPatch(params.buffer.data(), blocks * BLOCKSIZE, &patch_value, 0,
1310 std::bind(&RangeSinkWriter::Write, &writer, std::placeholders::_1,
1311 std::placeholders::_2),
1312 nullptr) != 0) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001313 LOG(ERROR) << "Failed to apply bsdiff patch.";
Tianjie Xu69575552017-05-16 15:51:46 -07001314 failure_type = kPatchApplicationFailure;
Tao Baoc0e1c462017-02-01 10:20:10 -08001315 return -1;
1316 }
1317 }
1318
1319 // We expect the output of the patcher to fill the tgt ranges exactly.
Tao Bao60a70af2017-03-26 14:03:52 -07001320 if (!writer.Finished()) {
Tao Baoc0e1c462017-02-01 10:20:10 -08001321 LOG(ERROR) << "range sink underrun?";
1322 }
1323 } else {
Tao Baobf5b77d2017-03-30 16:57:29 -07001324 LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
Tao Baoc0e1c462017-02-01 10:20:10 -08001325 << params.cmdline << "]";
Sami Tolvanen90221202014-12-09 16:39:47 +00001326 }
Tao Baoc0e1c462017-02-01 10:20:10 -08001327 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001328
Tao Baoc0e1c462017-02-01 10:20:10 -08001329 if (!params.freestash.empty()) {
1330 FreeStash(params.stashbase, params.freestash);
1331 params.freestash.clear();
1332 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001333
Tao Baobf5b77d2017-03-30 16:57:29 -07001334 params.written += tgt.blocks();
Sami Tolvanen90221202014-12-09 16:39:47 +00001335
Tao Baoc0e1c462017-02-01 10:20:10 -08001336 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001337}
1338
Tao Bao0940fe12015-08-27 16:41:21 -07001339static int PerformCommandErase(CommandParameters& params) {
Tao Baobf5b77d2017-03-30 16:57:29 -07001340 if (DEBUG_ERASE) {
1341 return PerformCommandZero(params);
1342 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001343
Tao Baobf5b77d2017-03-30 16:57:29 -07001344 struct stat sb;
1345 if (fstat(params.fd, &sb) == -1) {
1346 PLOG(ERROR) << "failed to fstat device to erase";
1347 return -1;
1348 }
1349
1350 if (!S_ISBLK(sb.st_mode)) {
1351 LOG(ERROR) << "not a block device; skipping erase";
1352 return -1;
1353 }
1354
1355 if (params.cpos >= params.tokens.size()) {
1356 LOG(ERROR) << "missing target blocks for erase";
1357 return -1;
1358 }
1359
1360 RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1361
1362 if (params.canwrite) {
1363 LOG(INFO) << " erasing " << tgt.blocks() << " blocks";
1364
1365 for (const auto& range : tgt) {
1366 uint64_t blocks[2];
1367 // offset in bytes
1368 blocks[0] = range.first * static_cast<uint64_t>(BLOCKSIZE);
1369 // length in bytes
1370 blocks[1] = (range.second - range.first) * static_cast<uint64_t>(BLOCKSIZE);
1371
1372 if (ioctl(params.fd, BLKDISCARD, &blocks) == -1) {
1373 PLOG(ERROR) << "BLKDISCARD ioctl failed";
Tao Bao0940fe12015-08-27 16:41:21 -07001374 return -1;
Tao Baobf5b77d2017-03-30 16:57:29 -07001375 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001376 }
Tao Baobf5b77d2017-03-30 16:57:29 -07001377 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001378
Tao Baobf5b77d2017-03-30 16:57:29 -07001379 return 0;
Sami Tolvanen90221202014-12-09 16:39:47 +00001380}
1381
1382// Definitions for transfer list command functions
Tao Bao0940fe12015-08-27 16:41:21 -07001383typedef int (*CommandFunction)(CommandParameters&);
Sami Tolvanen90221202014-12-09 16:39:47 +00001384
Tao Bao612336d2015-08-27 16:41:21 -07001385struct Command {
Sami Tolvanen90221202014-12-09 16:39:47 +00001386 const char* name;
1387 CommandFunction f;
Tao Bao612336d2015-08-27 16:41:21 -07001388};
Sami Tolvanen90221202014-12-09 16:39:47 +00001389
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001390// args:
1391// - block device (or file) to modify in-place
1392// - transfer list (blob)
1393// - new data stream (filename within package.zip)
1394// - patch stream (filename within package.zip, must be uncompressed)
1395
Tianjie Xuc4447322017-03-06 14:44:59 -08001396static Value* PerformBlockImageUpdate(const char* name, State* state,
1397 const std::vector<std::unique_ptr<Expr>>& argv,
1398 const Command* commands, size_t cmdcount, bool dryrun) {
Tao Bao33567772017-03-13 14:57:34 -07001399 CommandParameters params = {};
1400 params.canwrite = !dryrun;
Sami Tolvanen90221202014-12-09 16:39:47 +00001401
Tao Bao33567772017-03-13 14:57:34 -07001402 LOG(INFO) << "performing " << (dryrun ? "verification" : "update");
1403 if (state->is_retry) {
1404 is_retry = true;
1405 LOG(INFO) << "This update is a retry.";
1406 }
1407 if (argv.size() != 4) {
1408 ErrorAbort(state, kArgsParsingFailure, "block_image_update expects 4 arguments, got %zu",
1409 argv.size());
1410 return StringValue("");
1411 }
1412
1413 std::vector<std::unique_ptr<Value>> args;
1414 if (!ReadValueArgs(state, argv, &args)) {
1415 return nullptr;
1416 }
1417
Tao Baoc97edcb2017-03-31 01:18:13 -07001418 const std::unique_ptr<Value>& blockdev_filename = args[0];
1419 const std::unique_ptr<Value>& transfer_list_value = args[1];
1420 const std::unique_ptr<Value>& new_data_fn = args[2];
1421 const std::unique_ptr<Value>& patch_data_fn = args[3];
Tao Bao33567772017-03-13 14:57:34 -07001422
1423 if (blockdev_filename->type != VAL_STRING) {
1424 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1425 return StringValue("");
1426 }
1427 if (transfer_list_value->type != VAL_BLOB) {
1428 ErrorAbort(state, kArgsParsingFailure, "transfer_list argument to %s must be blob", name);
1429 return StringValue("");
1430 }
1431 if (new_data_fn->type != VAL_STRING) {
1432 ErrorAbort(state, kArgsParsingFailure, "new_data_fn argument to %s must be string", name);
1433 return StringValue("");
1434 }
1435 if (patch_data_fn->type != VAL_STRING) {
1436 ErrorAbort(state, kArgsParsingFailure, "patch_data_fn argument to %s must be string", name);
1437 return StringValue("");
1438 }
1439
1440 UpdaterInfo* ui = static_cast<UpdaterInfo*>(state->cookie);
1441 if (ui == nullptr) {
1442 return StringValue("");
1443 }
1444
1445 FILE* cmd_pipe = ui->cmd_pipe;
1446 ZipArchiveHandle za = ui->package_zip;
1447
1448 if (cmd_pipe == nullptr || za == nullptr) {
1449 return StringValue("");
1450 }
1451
1452 ZipString path_data(patch_data_fn->data.c_str());
1453 ZipEntry patch_entry;
1454 if (FindEntry(za, path_data, &patch_entry) != 0) {
1455 LOG(ERROR) << name << "(): no file \"" << patch_data_fn->data << "\" in package";
1456 return StringValue("");
1457 }
1458
1459 params.patch_start = ui->package_zip_addr + patch_entry.offset;
1460 ZipString new_data(new_data_fn->data.c_str());
1461 ZipEntry new_entry;
1462 if (FindEntry(za, new_data, &new_entry) != 0) {
1463 LOG(ERROR) << name << "(): no file \"" << new_data_fn->data << "\" in package";
1464 return StringValue("");
1465 }
1466
1467 params.fd.reset(TEMP_FAILURE_RETRY(ota_open(blockdev_filename->data.c_str(), O_RDWR)));
1468 if (params.fd == -1) {
1469 PLOG(ERROR) << "open \"" << blockdev_filename->data << "\" failed";
1470 return StringValue("");
1471 }
1472
1473 if (params.canwrite) {
1474 params.nti.za = za;
1475 params.nti.entry = new_entry;
Tianjie Xu107a34f2017-06-29 17:04:21 -07001476 params.nti.brotli_compressed = android::base::EndsWith(new_data_fn->data, ".br");
1477 if (params.nti.brotli_compressed) {
1478 // Initialize brotli decoder state.
1479 params.nti.brotli_decoder_state = BrotliDecoderCreateInstance(nullptr, nullptr, nullptr);
1480 }
Tianjie Xu3a8d98d2017-04-03 20:01:17 -07001481 params.nti.receiver_available = true;
Tao Bao33567772017-03-13 14:57:34 -07001482
1483 pthread_mutex_init(&params.nti.mu, nullptr);
1484 pthread_cond_init(&params.nti.cv, nullptr);
1485 pthread_attr_t attr;
1486 pthread_attr_init(&attr);
1487 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1488
1489 int error = pthread_create(&params.thread, &attr, unzip_new_data, &params.nti);
1490 if (error != 0) {
1491 PLOG(ERROR) << "pthread_create failed";
1492 return StringValue("");
Tianjie Xu7ce287d2016-05-31 09:29:49 -07001493 }
Tao Bao33567772017-03-13 14:57:34 -07001494 }
1495
1496 std::vector<std::string> lines = android::base::Split(transfer_list_value->data, "\n");
1497 if (lines.size() < 2) {
1498 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zd]\n",
1499 lines.size());
1500 return StringValue("");
1501 }
1502
1503 // First line in transfer list is the version number.
1504 if (!android::base::ParseInt(lines[0], &params.version, 3, 4)) {
1505 LOG(ERROR) << "unexpected transfer list version [" << lines[0] << "]";
1506 return StringValue("");
1507 }
1508
1509 LOG(INFO) << "blockimg version is " << params.version;
1510
1511 // Second line in transfer list is the total number of blocks we expect to write.
1512 size_t total_blocks;
1513 if (!android::base::ParseUint(lines[1], &total_blocks)) {
1514 ErrorAbort(state, kArgsParsingFailure, "unexpected block count [%s]\n", lines[1].c_str());
1515 return StringValue("");
1516 }
1517
1518 if (total_blocks == 0) {
1519 return StringValue("t");
1520 }
1521
1522 size_t start = 2;
1523 if (lines.size() < 4) {
1524 ErrorAbort(state, kArgsParsingFailure, "too few lines in the transfer list [%zu]\n",
1525 lines.size());
1526 return StringValue("");
1527 }
1528
1529 // Third line is how many stash entries are needed simultaneously.
1530 LOG(INFO) << "maximum stash entries " << lines[2];
1531
1532 // Fourth line is the maximum number of blocks that will be stashed simultaneously
1533 size_t stash_max_blocks;
1534 if (!android::base::ParseUint(lines[3], &stash_max_blocks)) {
1535 ErrorAbort(state, kArgsParsingFailure, "unexpected maximum stash blocks [%s]\n",
1536 lines[3].c_str());
1537 return StringValue("");
1538 }
1539
1540 int res = CreateStash(state, stash_max_blocks, blockdev_filename->data, params.stashbase);
1541 if (res == -1) {
1542 return StringValue("");
1543 }
1544
1545 params.createdstash = res;
1546
1547 start += 2;
1548
1549 // Build a map of the available commands
1550 std::unordered_map<std::string, const Command*> cmd_map;
1551 for (size_t i = 0; i < cmdcount; ++i) {
1552 if (cmd_map.find(commands[i].name) != cmd_map.end()) {
1553 LOG(ERROR) << "Error: command [" << commands[i].name << "] already exists in the cmd map.";
1554 return StringValue(strdup(""));
1555 }
1556 cmd_map[commands[i].name] = &commands[i];
1557 }
1558
1559 int rc = -1;
1560
1561 // Subsequent lines are all individual transfer commands
1562 for (auto it = lines.cbegin() + start; it != lines.cend(); it++) {
1563 const std::string& line(*it);
1564 if (line.empty()) continue;
1565
1566 params.tokens = android::base::Split(line, " ");
1567 params.cpos = 0;
1568 params.cmdname = params.tokens[params.cpos++].c_str();
1569 params.cmdline = line.c_str();
1570
1571 if (cmd_map.find(params.cmdname) == cmd_map.end()) {
1572 LOG(ERROR) << "unexpected command [" << params.cmdname << "]";
1573 goto pbiudone;
Tianjie Xuc4447322017-03-06 14:44:59 -08001574 }
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001575
Tao Bao33567772017-03-13 14:57:34 -07001576 const Command* cmd = cmd_map[params.cmdname];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001577
Tao Bao33567772017-03-13 14:57:34 -07001578 if (cmd->f != nullptr && cmd->f(params) == -1) {
1579 LOG(ERROR) << "failed to execute command [" << line << "]";
1580 goto pbiudone;
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001581 }
1582
Sami Tolvanen90221202014-12-09 16:39:47 +00001583 if (params.canwrite) {
Tao Bao33567772017-03-13 14:57:34 -07001584 if (ota_fsync(params.fd) == -1) {
Tianjie Xu16255832016-04-30 11:49:59 -07001585 failure_type = kFsyncFailure;
Tao Bao039f2da2016-11-22 16:29:50 -08001586 PLOG(ERROR) << "fsync failed";
Tao Bao33567772017-03-13 14:57:34 -07001587 goto pbiudone;
1588 }
1589 fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1590 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001591 }
Tao Bao33567772017-03-13 14:57:34 -07001592 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001593
Tao Bao33567772017-03-13 14:57:34 -07001594 if (params.canwrite) {
1595 pthread_join(params.thread, nullptr);
1596
1597 LOG(INFO) << "wrote " << params.written << " blocks; expected " << total_blocks;
1598 LOG(INFO) << "stashed " << params.stashed << " blocks";
1599 LOG(INFO) << "max alloc needed was " << params.buffer.size();
1600
1601 const char* partition = strrchr(blockdev_filename->data.c_str(), '/');
1602 if (partition != nullptr && *(partition + 1) != 0) {
1603 fprintf(cmd_pipe, "log bytes_written_%s: %zu\n", partition + 1, params.written * BLOCKSIZE);
1604 fprintf(cmd_pipe, "log bytes_stashed_%s: %zu\n", partition + 1, params.stashed * BLOCKSIZE);
1605 fflush(cmd_pipe);
Sami Tolvanen90221202014-12-09 16:39:47 +00001606 }
Tao Bao33567772017-03-13 14:57:34 -07001607 // Delete stash only after successfully completing the update, as it may contain blocks needed
1608 // to complete the update later.
1609 DeleteStash(params.stashbase);
1610 } else {
1611 LOG(INFO) << "verified partition contents; update may be resumed";
1612 }
Sami Tolvanen90221202014-12-09 16:39:47 +00001613
Tao Bao33567772017-03-13 14:57:34 -07001614 rc = 0;
Tianjie Xu16255832016-04-30 11:49:59 -07001615
Tao Bao33567772017-03-13 14:57:34 -07001616pbiudone:
1617 if (ota_fsync(params.fd) == -1) {
1618 failure_type = kFsyncFailure;
1619 PLOG(ERROR) << "fsync failed";
1620 }
1621 // params.fd will be automatically closed because it's a unique_fd.
1622
Tianjie Xu107a34f2017-06-29 17:04:21 -07001623 if (params.nti.brotli_decoder_state != nullptr) {
1624 BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1625 }
1626
Tao Bao33567772017-03-13 14:57:34 -07001627 // Only delete the stash if the update cannot be resumed, or it's a verification run and we
1628 // created the stash.
1629 if (params.isunresumable || (!params.canwrite && params.createdstash)) {
1630 DeleteStash(params.stashbase);
1631 }
1632
1633 if (failure_type != kNoCause && state->cause_code == kNoCause) {
1634 state->cause_code = failure_type;
1635 }
1636
1637 return StringValue(rc == 0 ? "t" : "");
Sami Tolvanen90221202014-12-09 16:39:47 +00001638}
1639
Tao Bao33567772017-03-13 14:57:34 -07001640/**
1641 * The transfer list is a text file containing commands to transfer data from one place to another
1642 * on the target partition. We parse it and execute the commands in order:
1643 *
1644 * zero [rangeset]
1645 * - Fill the indicated blocks with zeros.
1646 *
1647 * new [rangeset]
1648 * - Fill the blocks with data read from the new_data file.
1649 *
1650 * erase [rangeset]
1651 * - Mark the given blocks as empty.
1652 *
1653 * move <...>
1654 * bsdiff <patchstart> <patchlen> <...>
1655 * imgdiff <patchstart> <patchlen> <...>
1656 * - Read the source blocks, apply a patch (or not in the case of move), write result to target
1657 * blocks. bsdiff or imgdiff specifies the type of patch; move means no patch at all.
1658 *
1659 * See the comments in LoadSrcTgtVersion3() for a description of the <...> format.
1660 *
1661 * stash <stash_id> <src_range>
1662 * - Load the given source range and stash the data in the given slot of the stash table.
1663 *
1664 * free <stash_id>
1665 * - Free the given stash data.
1666 *
1667 * The creator of the transfer list will guarantee that no block is read (ie, used as the source for
1668 * a patch or move) after it has been written.
1669 *
1670 * The creator will guarantee that a given stash is loaded (with a stash command) before it's used
1671 * in a move/bsdiff/imgdiff command.
1672 *
1673 * Within one command the source and target ranges may overlap so in general we need to read the
1674 * entire source into memory before writing anything to the target blocks.
1675 *
1676 * All the patch data is concatenated into one patch_data file in the update package. It must be
1677 * stored uncompressed because we memory-map it in directly from the archive. (Since patches are
1678 * already compressed, we lose very little by not compressing their concatenation.)
1679 *
1680 * Commands that read data from the partition (i.e. move/bsdiff/imgdiff/stash) have one or more
1681 * additional hashes before the range parameters, which are used to check if the command has already
1682 * been completed and verify the integrity of the source data.
1683 */
Tianjie Xuc4447322017-03-06 14:44:59 -08001684Value* BlockImageVerifyFn(const char* name, State* state,
1685 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Bao0940fe12015-08-27 16:41:21 -07001686 // Commands which are not tested are set to nullptr to skip them completely
Sami Tolvanen90221202014-12-09 16:39:47 +00001687 const Command commands[] = {
1688 { "bsdiff", PerformCommandDiff },
Tao Bao0940fe12015-08-27 16:41:21 -07001689 { "erase", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001690 { "free", PerformCommandFree },
1691 { "imgdiff", PerformCommandDiff },
1692 { "move", PerformCommandMove },
Tao Bao0940fe12015-08-27 16:41:21 -07001693 { "new", nullptr },
Sami Tolvanen90221202014-12-09 16:39:47 +00001694 { "stash", PerformCommandStash },
Tao Bao0940fe12015-08-27 16:41:21 -07001695 { "zero", nullptr }
Sami Tolvanen90221202014-12-09 16:39:47 +00001696 };
1697
1698 // Perform a dry run without writing to test if an update can proceed
Tianjie Xuc4447322017-03-06 14:44:59 -08001699 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001700 sizeof(commands) / sizeof(commands[0]), true);
Sami Tolvanen90221202014-12-09 16:39:47 +00001701}
1702
Tianjie Xuc4447322017-03-06 14:44:59 -08001703Value* BlockImageUpdateFn(const char* name, State* state,
1704 const std::vector<std::unique_ptr<Expr>>& argv) {
Sami Tolvanen90221202014-12-09 16:39:47 +00001705 const Command commands[] = {
1706 { "bsdiff", PerformCommandDiff },
1707 { "erase", PerformCommandErase },
1708 { "free", PerformCommandFree },
1709 { "imgdiff", PerformCommandDiff },
1710 { "move", PerformCommandMove },
1711 { "new", PerformCommandNew },
1712 { "stash", PerformCommandStash },
1713 { "zero", PerformCommandZero }
1714 };
1715
Tianjie Xuc4447322017-03-06 14:44:59 -08001716 return PerformBlockImageUpdate(name, state, argv, commands,
Tao Baoe6aa3322015-08-05 15:20:27 -07001717 sizeof(commands) / sizeof(commands[0]), false);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001718}
1719
Tianjie Xuc4447322017-03-06 14:44:59 -08001720Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001721 if (argv.size() != 2) {
1722 ErrorAbort(state, kArgsParsingFailure, "range_sha1 expects 2 arguments, got %zu", argv.size());
1723 return StringValue("");
1724 }
1725
1726 std::vector<std::unique_ptr<Value>> args;
1727 if (!ReadValueArgs(state, argv, &args)) {
1728 return nullptr;
1729 }
1730
1731 const std::unique_ptr<Value>& blockdev_filename = args[0];
1732 const std::unique_ptr<Value>& ranges = args[1];
1733
1734 if (blockdev_filename->type != VAL_STRING) {
1735 ErrorAbort(state, kArgsParsingFailure, "blockdev_filename argument to %s must be string", name);
1736 return StringValue("");
1737 }
1738 if (ranges->type != VAL_STRING) {
1739 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1740 return StringValue("");
1741 }
1742
1743 android::base::unique_fd fd(ota_open(blockdev_filename->data.c_str(), O_RDWR));
1744 if (fd == -1) {
1745 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", blockdev_filename->data.c_str(),
1746 strerror(errno));
1747 return StringValue("");
1748 }
1749
1750 RangeSet rs = RangeSet::Parse(ranges->data);
1751
1752 SHA_CTX ctx;
1753 SHA1_Init(&ctx);
1754
1755 std::vector<uint8_t> buffer(BLOCKSIZE);
Tao Baobf5b77d2017-03-30 16:57:29 -07001756 for (const auto& range : rs) {
1757 if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001758 ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1759 strerror(errno));
1760 return StringValue("");
1761 }
1762
Tao Baobf5b77d2017-03-30 16:57:29 -07001763 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001764 if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1765 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1766 strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001767 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001768 }
1769
1770 SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
Tianjie Xuc4447322017-03-06 14:44:59 -08001771 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001772 }
1773 uint8_t digest[SHA_DIGEST_LENGTH];
1774 SHA1_Final(digest, &ctx);
Tianjie Xuc4447322017-03-06 14:44:59 -08001775
Tao Baoc97edcb2017-03-31 01:18:13 -07001776 return StringValue(print_sha1(digest));
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001777}
1778
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001779// This function checks if a device has been remounted R/W prior to an incremental
1780// OTA update. This is an common cause of update abortion. The function reads the
1781// 1st block of each partition and check for mounting time/count. It return string "t"
1782// if executes successfully and an empty string otherwise.
1783
Tianjie Xuc4447322017-03-06 14:44:59 -08001784Value* CheckFirstBlockFn(const char* name, State* state,
1785 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001786 if (argv.size() != 1) {
1787 ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1788 argv.size());
1789 return StringValue("");
1790 }
Tianjie Xuc4447322017-03-06 14:44:59 -08001791
Tao Baoc97edcb2017-03-31 01:18:13 -07001792 std::vector<std::unique_ptr<Value>> args;
1793 if (!ReadValueArgs(state, argv, &args)) {
1794 return nullptr;
1795 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001796
Tao Baoc97edcb2017-03-31 01:18:13 -07001797 const std::unique_ptr<Value>& arg_filename = args[0];
Tianjie Xu5fe280a2016-10-17 18:15:20 -07001798
Tao Baoc97edcb2017-03-31 01:18:13 -07001799 if (arg_filename->type != VAL_STRING) {
1800 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1801 return StringValue("");
1802 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001803
Tao Baoc97edcb2017-03-31 01:18:13 -07001804 android::base::unique_fd fd(ota_open(arg_filename->data.c_str(), O_RDONLY));
1805 if (fd == -1) {
1806 ErrorAbort(state, kFileOpenFailure, "open \"%s\" failed: %s", arg_filename->data.c_str(),
1807 strerror(errno));
1808 return StringValue("");
1809 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001810
Tao Baobf5b77d2017-03-30 16:57:29 -07001811 RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
Tao Baoc97edcb2017-03-31 01:18:13 -07001812 std::vector<uint8_t> block0_buffer(BLOCKSIZE);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001813
Tao Baoc97edcb2017-03-31 01:18:13 -07001814 if (ReadBlocks(blk0, block0_buffer, fd) == -1) {
1815 ErrorAbort(state, kFreadFailure, "failed to read %s: %s", arg_filename->data.c_str(),
1816 strerror(errno));
1817 return StringValue("");
1818 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001819
Tao Baoc97edcb2017-03-31 01:18:13 -07001820 // https://ext4.wiki.kernel.org/index.php/Ext4_Disk_Layout
1821 // Super block starts from block 0, offset 0x400
1822 // 0x2C: len32 Mount time
1823 // 0x30: len32 Write time
1824 // 0x34: len16 Number of mounts since the last fsck
1825 // 0x38: len16 Magic signature 0xEF53
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001826
Tao Baoc97edcb2017-03-31 01:18:13 -07001827 time_t mount_time = *reinterpret_cast<uint32_t*>(&block0_buffer[0x400 + 0x2C]);
1828 uint16_t mount_count = *reinterpret_cast<uint16_t*>(&block0_buffer[0x400 + 0x34]);
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001829
Tao Baoc97edcb2017-03-31 01:18:13 -07001830 if (mount_count > 0) {
1831 uiPrintf(state, "Device was remounted R/W %" PRIu16 " times", mount_count);
1832 uiPrintf(state, "Last remount happened on %s", ctime(&mount_time));
1833 }
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001834
Tao Baoc97edcb2017-03-31 01:18:13 -07001835 return StringValue("t");
Tianjie Xu57bed6d2015-12-15 11:47:30 -08001836}
1837
Tianjie Xuc4447322017-03-06 14:44:59 -08001838Value* BlockImageRecoverFn(const char* name, State* state,
1839 const std::vector<std::unique_ptr<Expr>>& argv) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001840 if (argv.size() != 2) {
1841 ErrorAbort(state, kArgsParsingFailure, "block_image_recover expects 2 arguments, got %zu",
1842 argv.size());
1843 return StringValue("");
1844 }
1845
1846 std::vector<std::unique_ptr<Value>> args;
1847 if (!ReadValueArgs(state, argv, &args)) {
1848 return nullptr;
1849 }
1850
1851 const std::unique_ptr<Value>& filename = args[0];
1852 const std::unique_ptr<Value>& ranges = args[1];
1853
1854 if (filename->type != VAL_STRING) {
1855 ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1856 return StringValue("");
1857 }
1858 if (ranges->type != VAL_STRING) {
1859 ErrorAbort(state, kArgsParsingFailure, "ranges argument to %s must be string", name);
1860 return StringValue("");
1861 }
1862
1863 // Output notice to log when recover is attempted
1864 LOG(INFO) << filename->data << " image corrupted, attempting to recover...";
1865
1866 // When opened with O_RDWR, libfec rewrites corrupted blocks when they are read
1867 fec::io fh(filename->data, O_RDWR);
1868
1869 if (!fh) {
1870 ErrorAbort(state, kLibfecFailure, "fec_open \"%s\" failed: %s", filename->data.c_str(),
1871 strerror(errno));
1872 return StringValue("");
1873 }
1874
1875 if (!fh.has_ecc() || !fh.has_verity()) {
1876 ErrorAbort(state, kLibfecFailure, "unable to use metadata to correct errors");
1877 return StringValue("");
1878 }
1879
1880 fec_status status;
Tao Baoc97edcb2017-03-31 01:18:13 -07001881 if (!fh.get_status(status)) {
1882 ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
1883 return StringValue("");
1884 }
1885
Tao Baoc97edcb2017-03-31 01:18:13 -07001886 uint8_t buffer[BLOCKSIZE];
Tao Baobf5b77d2017-03-30 16:57:29 -07001887 for (const auto& range : RangeSet::Parse(ranges->data)) {
1888 for (size_t j = range.first; j < range.second; ++j) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001889 // Stay within the data area, libfec validates and corrects metadata
Tao Baobf5b77d2017-03-30 16:57:29 -07001890 if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001891 continue;
1892 }
1893
Tao Baobf5b77d2017-03-30 16:57:29 -07001894 if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
Tao Baoc97edcb2017-03-31 01:18:13 -07001895 ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1896 filename->data.c_str(), j, strerror(errno));
Tianjie Xuc4447322017-03-06 14:44:59 -08001897 return StringValue("");
Tao Baoc97edcb2017-03-31 01:18:13 -07001898 }
1899
1900 // If we want to be able to recover from a situation where rewriting a corrected
1901 // block doesn't guarantee the same data will be returned when re-read later, we
1902 // can save a copy of corrected blocks to /cache. Note:
1903 //
1904 // 1. Maximum space required from /cache is the same as the maximum number of
1905 // corrupted blocks we can correct. For RS(255, 253) and a 2 GiB partition,
1906 // this would be ~16 MiB, for example.
1907 //
1908 // 2. To find out if this block was corrupted, call fec_get_status after each
1909 // read and check if the errors field value has increased.
Tianjie Xuc4447322017-03-06 14:44:59 -08001910 }
Tao Baoc97edcb2017-03-31 01:18:13 -07001911 }
1912 LOG(INFO) << "..." << filename->data << " image recovered successfully.";
1913 return StringValue("t");
Sami Tolvanen0a7b4732015-06-25 10:25:36 +01001914}
1915
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001916void RegisterBlockImageFunctions() {
Tao Baoc97edcb2017-03-31 01:18:13 -07001917 RegisterFunction("block_image_verify", BlockImageVerifyFn);
1918 RegisterFunction("block_image_update", BlockImageUpdateFn);
1919 RegisterFunction("block_image_recover", BlockImageRecoverFn);
1920 RegisterFunction("check_first_block", CheckFirstBlockFn);
1921 RegisterFunction("range_sha1", RangeSha1Fn);
Doug Zongkerbc7ffed2014-08-15 14:31:52 -07001922}