• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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>
19 #include <dirent.h>
20 #include <fcntl.h>
21 #include <inttypes.h>
22 #include <linux/fs.h>
23 #include <pthread.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/stat.h>
29 #include <sys/types.h>
30 #include <sys/wait.h>
31 #include <sys/ioctl.h>
32 #include <time.h>
33 #include <unistd.h>
34 #include <fec/io.h>
35 
36 #include <functional>
37 #include <memory>
38 #include <string>
39 #include <unordered_map>
40 #include <vector>
41 
42 #include <android-base/logging.h>
43 #include <android-base/parseint.h>
44 #include <android-base/strings.h>
45 #include <android-base/unique_fd.h>
46 #include <applypatch/applypatch.h>
47 #include <brotli/decode.h>
48 #include <openssl/sha.h>
49 #include <private/android_filesystem_config.h>
50 #include <ziparchive/zip_archive.h>
51 
52 #include "edify/expr.h"
53 #include "error_code.h"
54 #include "ota_io.h"
55 #include "print_sha1.h"
56 #include "updater/install.h"
57 #include "updater/rangeset.h"
58 #include "updater/updater.h"
59 
60 // 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 
65 static constexpr size_t BLOCKSIZE = 4096;
66 static constexpr const char* STASH_DIRECTORY_BASE = "/cache/recovery";
67 static constexpr mode_t STASH_DIRECTORY_MODE = 0700;
68 static constexpr mode_t STASH_FILE_MODE = 0600;
69 
70 static CauseCode failure_type = kNoCause;
71 static bool is_retry = false;
72 static std::unordered_map<std::string, RangeSet> stash_map;
73 
read_all(int fd,uint8_t * data,size_t size)74 static int read_all(int fd, uint8_t* data, size_t size) {
75     size_t so_far = 0;
76     while (so_far < size) {
77         ssize_t r = TEMP_FAILURE_RETRY(ota_read(fd, data+so_far, size-so_far));
78         if (r == -1) {
79             failure_type = kFreadFailure;
80             PLOG(ERROR) << "read failed";
81             return -1;
82         } else if (r == 0) {
83             failure_type = kFreadFailure;
84             LOG(ERROR) << "read reached unexpected EOF.";
85             return -1;
86         }
87         so_far += r;
88     }
89     return 0;
90 }
91 
read_all(int fd,std::vector<uint8_t> & buffer,size_t size)92 static int read_all(int fd, std::vector<uint8_t>& buffer, size_t size) {
93     return read_all(fd, buffer.data(), size);
94 }
95 
write_all(int fd,const uint8_t * data,size_t size)96 static int write_all(int fd, const uint8_t* data, size_t size) {
97     size_t written = 0;
98     while (written < size) {
99         ssize_t w = TEMP_FAILURE_RETRY(ota_write(fd, data+written, size-written));
100         if (w == -1) {
101             failure_type = kFwriteFailure;
102             PLOG(ERROR) << "write failed";
103             return -1;
104         }
105         written += w;
106     }
107 
108     return 0;
109 }
110 
write_all(int fd,const std::vector<uint8_t> & buffer,size_t size)111 static int write_all(int fd, const std::vector<uint8_t>& buffer, size_t size) {
112     return write_all(fd, buffer.data(), size);
113 }
114 
discard_blocks(int fd,off64_t offset,uint64_t size)115 static bool discard_blocks(int fd, off64_t offset, uint64_t size) {
116   // Don't discard blocks unless the update is a retry run.
117   if (!is_retry) {
118     return true;
119   }
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;
127 }
128 
check_lseek(int fd,off64_t offset,int whence)129 static 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) {
132         failure_type = kLseekFailure;
133         PLOG(ERROR) << "lseek64 failed";
134         return false;
135     }
136     return true;
137 }
138 
allocate(size_t size,std::vector<uint8_t> & buffer)139 static void allocate(size_t size, std::vector<uint8_t>& buffer) {
140     // if the buffer's big enough, reuse it.
141     if (size <= buffer.size()) return;
142 
143     buffer.resize(size);
144 }
145 
146 /**
147  * RangeSinkWriter reads data from the given FD, and writes them to the destination specified by the
148  * given RangeSet.
149  */
150 class RangeSinkWriter {
151  public:
RangeSinkWriter(int fd,const RangeSet & tgt)152   RangeSinkWriter(int fd, const RangeSet& tgt)
153       : fd_(fd),
154         tgt_(tgt),
155         next_range_(0),
156         current_range_left_(0),
157         bytes_written_(0) {
158     CHECK_NE(tgt.size(), static_cast<size_t>(0));
159   };
160 
Finished() const161   bool Finished() const {
162     return next_range_ == tgt_.size() && current_range_left_ == 0;
163   }
164 
AvailableSpace() const165   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.
Write(const uint8_t * data,size_t size)170   size_t Write(const uint8_t* data, size_t size) {
171     if (Finished()) {
172       LOG(ERROR) << "range sink write overrun; can't write " << size << " bytes";
173       return 0;
174     }
175 
176     size_t written = 0;
177     while (size > 0) {
178       // Move to the next range as needed.
179       if (!SeekToOutputRange()) {
180         break;
181       }
182 
183       size_t write_now = size;
184       if (current_range_left_ < write_now) {
185         write_now = current_range_left_;
186       }
187 
188       if (write_all(fd_, data, write_now) == -1) {
189         break;
190       }
191 
192       data += write_now;
193       size -= write_now;
194 
195       current_range_left_ -= write_now;
196       written += write_now;
197     }
198 
199     bytes_written_ += written;
200     return written;
201   }
202 
BytesWritten() const203   size_t BytesWritten() const {
204     return bytes_written_;
205   }
206 
207  private:
208   // Set up the output cursor, move to next range if needed.
SeekToOutputRange()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.
235   int fd_;
236   // The destination ranges for the data.
237   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_;
242   // Total bytes written by the writer.
243   size_t bytes_written_;
244 };
245 
246 /**
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  */
264 struct NewThreadInfo {
265   ZipArchiveHandle za;
266   ZipEntry entry;
267   bool brotli_compressed;
268 
269   std::unique_ptr<RangeSinkWriter> writer;
270   BrotliDecoderState* brotli_decoder_state;
271   bool receiver_available;
272 
273   pthread_mutex_t mu;
274   pthread_cond_t cv;
275 };
276 
receive_new_data(const uint8_t * data,size_t size,void * cookie)277 static bool receive_new_data(const uint8_t* data, size_t size, void* cookie) {
278   NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
279 
280   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);
285     }
286     pthread_mutex_unlock(&nti->mu);
287 
288     // At this point nti->writer is set, and we own it. The main thread is waiting for it to
289     // disappear from nti.
290     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.";
293       return false;
294     }
295 
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 
receive_brotli_new_data(const uint8_t * data,size_t size,void * cookie)312 static 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;
357 
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;
369 }
370 
unzip_new_data(void * cookie)371 static void* unzip_new_data(void* cookie) {
372   NewThreadInfo* nti = static_cast<NewThreadInfo*>(cookie);
373   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   }
378   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;
385 }
386 
ReadBlocks(const RangeSet & src,std::vector<uint8_t> & buffer,int fd)387 static int ReadBlocks(const RangeSet& src, std::vector<uint8_t>& buffer, int fd) {
388   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;
392     }
393 
394     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;
403 }
404 
WriteBlocks(const RangeSet & tgt,const std::vector<uint8_t> & buffer,int fd)405 static int WriteBlocks(const RangeSet& tgt, const std::vector<uint8_t>& buffer, int fd) {
406   size_t written = 0;
407   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;
410     if (!discard_blocks(fd, offset, size)) {
411       return -1;
412     }
413 
414     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;
426 }
427 
428 // Parameters for transfer list command functions
429 struct 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;
438     android::base::unique_fd fd;
439     bool foundwrites;
440     bool isunresumable;
441     int version;
442     size_t written;
443     size_t stashed;
444     NewThreadInfo nti;
445     pthread_t thread;
446     std::vector<uint8_t> buffer;
447     uint8_t* patch_start;
448 };
449 
450 // Print the hash in hex for corrupted source blocks (excluding the stashed blocks which is
451 // handled separately).
PrintHashForCorruptedSourceBlocks(const CommandParameters & params,const std::vector<uint8_t> & buffer)452 static 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;
455   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 
484   RangeSet src = RangeSet::Parse(params.tokens[pos++]);
485 
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()) {
490     locs = RangeSet(std::vector<Range>{ Range{ 0, src.blocks() } });
491   } 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.
496     locs = RangeSet::Parse(params.tokens[pos++]);
497     CHECK_EQ(src.blocks(), locs.blocks());
498   }
499 
500   LOG(INFO) << "printing hash in hex for " << src.blocks() << " source blocks";
501   for (size_t i = 0; i < src.blocks(); i++) {
502     size_t block_num = src.GetBlockNumber(i);
503     size_t buffer_index = locs.GetBlockNumber(i);
504     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.
PrintHashForCorruptedStashedBlocks(const std::string & id,const std::vector<uint8_t> & buffer,const RangeSet & src)515 static 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;
519   CHECK_EQ(src.blocks() * BLOCKSIZE, buffer.size());
520 
521   for (size_t i = 0; i < src.blocks(); i++) {
522     size_t block_num = src.GetBlockNumber(i);
523 
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.
PrintHashForMissingStashedBlocks(const std::string & id,int fd)533 static 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];
541   std::vector<uint8_t> buffer(src.blocks() * BLOCKSIZE);
542   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 
VerifyBlocks(const std::string & expected,const std::vector<uint8_t> & buffer,const size_t blocks,bool printerror)549 static int VerifyBlocks(const std::string& expected, const std::vector<uint8_t>& buffer,
550         const size_t blocks, bool printerror) {
551     uint8_t digest[SHA_DIGEST_LENGTH];
552     const uint8_t* data = buffer.data();
553 
554     SHA1(data, blocks * BLOCKSIZE, digest);
555 
556     std::string hexdigest = print_sha1(digest);
557 
558     if (hexdigest != expected) {
559         if (printerror) {
560             LOG(ERROR) << "failed to verify blocks (expected " << expected << ", read "
561                        << hexdigest << ")";
562         }
563         return -1;
564     }
565 
566     return 0;
567 }
568 
GetStashFileName(const std::string & base,const std::string & id,const std::string & postfix)569 static std::string GetStashFileName(const std::string& base, const std::string& id,
570         const std::string& postfix) {
571     if (base.empty()) {
572         return "";
573     }
574 
575     std::string fn(STASH_DIRECTORY_BASE);
576     fn += "/" + base + "/" + id + postfix;
577 
578     return fn;
579 }
580 
581 // 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.
EnumerateStash(const std::string & dirname,const std::function<void (const std::string &)> & callback)583 static void EnumerateStash(const std::string& dirname,
584                            const std::function<void(const std::string&)>& callback) {
585   if (dirname.empty()) return;
586 
587   std::unique_ptr<DIR, decltype(&closedir)> directory(opendir(dirname.c_str()), closedir);
588 
589   if (directory == nullptr) {
590     if (errno != ENOENT) {
591       PLOG(ERROR) << "opendir \"" << dirname << "\" failed";
592     }
593     return;
594   }
595 
596   dirent* item;
597   while ((item = readdir(directory.get())) != nullptr) {
598     if (item->d_type != DT_REG) continue;
599     callback(dirname + "/" + item->d_name);
600   }
601 }
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.
DeleteFile(const std::string & fn)606 static void DeleteFile(const std::string& fn) {
607   if (fn.empty()) return;
608 
609   LOG(INFO) << "deleting " << fn;
610 
611   if (unlink(fn.c_str()) == -1 && errno != ENOENT) {
612     PLOG(ERROR) << "unlink \"" << fn << "\" failed";
613   }
614 }
615 
DeleteStash(const std::string & base)616 static void DeleteStash(const std::string& base) {
617   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";
627     }
628   }
629 }
630 
LoadStash(CommandParameters & params,const std::string & id,bool verify,size_t * blocks,std::vector<uint8_t> & buffer,bool printnoent)631 static int LoadStash(CommandParameters& params, const std::string& id, bool verify, size_t* blocks,
632                      std::vector<uint8_t>& buffer, bool printnoent) {
633   // 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);
639 
640       if (ReadBlocks(src, buffer, params.fd) == -1) {
641         LOG(ERROR) << "failed to read source blocks in stash map.";
642         return -1;
643       }
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);
647         return -1;
648       }
649       return 0;
650     }
651   }
652 
653   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);
665     }
666     return -1;
667   }
668 
669   LOG(INFO) << " loading " << fn;
670 
671   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);
698     }
699     DeleteFile(fn);
700     return -1;
701   }
702 
703   return 0;
704 }
705 
WriteStash(const std::string & base,const std::string & id,int blocks,std::vector<uint8_t> & buffer,bool checkspace,bool * exists)706 static int WriteStash(const std::string& base, const std::string& id, int blocks,
707                       std::vector<uint8_t>& buffer, bool checkspace, bool* exists) {
708     if (base.empty()) {
709         return -1;
710     }
711 
712     if (checkspace && CacheSizeCheck(blocks * BLOCKSIZE) != 0) {
713         LOG(ERROR) << "not enough space to write stash";
714         return -1;
715     }
716 
717     std::string fn = GetStashFileName(base, id, ".partial");
718     std::string cn = GetStashFileName(base, id, "");
719 
720     if (exists) {
721         struct stat sb;
722         int res = stat(cn.c_str(), &sb);
723 
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)
728             LOG(INFO) << " skipping " << blocks << " existing blocks in " << cn;
729             *exists = true;
730             return 0;
731         }
732 
733         *exists = false;
734     }
735 
736     LOG(INFO) << " writing " << blocks << " blocks to " << cn;
737 
738     android::base::unique_fd fd(
739         TEMP_FAILURE_RETRY(ota_open(fn.c_str(), O_WRONLY | O_CREAT | O_TRUNC, STASH_FILE_MODE)));
740     if (fd == -1) {
741         PLOG(ERROR) << "failed to create \"" << fn << "\"";
742         return -1;
743     }
744 
745     if (fchown(fd, AID_SYSTEM, AID_SYSTEM) != 0) {  // system user
746         PLOG(ERROR) << "failed to chown \"" << fn << "\"";
747         return -1;
748     }
749 
750     if (write_all(fd, buffer, blocks * BLOCKSIZE) == -1) {
751         return -1;
752     }
753 
754     if (ota_fsync(fd) == -1) {
755         failure_type = kFsyncFailure;
756         PLOG(ERROR) << "fsync \"" << fn << "\" failed";
757         return -1;
758     }
759 
760     if (rename(fn.c_str(), cn.c_str()) == -1) {
761         PLOG(ERROR) << "rename(\"" << fn << "\", \"" << cn << "\") failed";
762         return -1;
763     }
764 
765     std::string dname = GetStashFileName(base, "", "");
766     android::base::unique_fd dfd(TEMP_FAILURE_RETRY(ota_open(dname.c_str(),
767                                                              O_RDONLY | O_DIRECTORY)));
768     if (dfd == -1) {
769         failure_type = kFileOpenFailure;
770         PLOG(ERROR) << "failed to open \"" << dname << "\" failed";
771         return -1;
772     }
773 
774     if (ota_fsync(dfd) == -1) {
775         failure_type = kFsyncFailure;
776         PLOG(ERROR) << "fsync \"" << dname << "\" failed";
777         return -1;
778     }
779 
780     return 0;
781 }
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 
CreateStash(State * state,size_t maxblocks,const std::string & blockdev,std::string & base)787 static 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;
817     }
818 
819     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 
825     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;
829     }
830 
831     return 1;  // Created directory
832   }
833 
834   LOG(INFO) << "using existing stash " << dirname;
835 
836   // 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   });
843 
844   size_t existing = 0;
845   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   });
854 
855   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;
861     }
862   }
863 
864   return 0;  // Using existing directory
865 }
866 
FreeStash(const std::string & base,const std::string & id)867 static int FreeStash(const std::string& base, const std::string& id) {
868   if (base.empty() || id.empty()) {
869     return -1;
870   }
871 
872   DeleteFile(GetStashFileName(base, id, ""));
873 
874   return 0;
875 }
876 
877 // 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.
MoveRange(std::vector<uint8_t> & dest,const RangeSet & locs,const std::vector<uint8_t> & source)879 static void MoveRange(std::vector<uint8_t>& dest, const RangeSet& locs,
880                       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   }
890 }
891 
892 /**
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  */
LoadSourceBlocks(CommandParameters & params,const RangeSet & tgt,size_t * src_blocks,bool * overlap)909 static int LoadSourceBlocks(CommandParameters& params, const RangeSet& tgt, size_t* src_blocks,
910                             bool* overlap) {
911   CHECK(src_blocks != nullptr);
912   CHECK(overlap != nullptr);
913 
914   // <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   }
920 
921   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 {
928     RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
929     *overlap = src.Overlaps(tgt);
930 
931     if (ReadBlocks(src, params.buffer, params.fd) == -1) {
932       return -1;
933     }
934 
935     if (params.cpos >= params.tokens.size()) {
936       // no stashes, only source range
937       return 0;
938     }
939 
940     RangeSet locs = RangeSet::Parse(params.tokens[params.cpos++]);
941     MoveRange(params.buffer, locs, params.buffer);
942   }
943 
944   // <[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;
952     }
953 
954     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;
960     }
961 
962     RangeSet locs = RangeSet::Parse(tokens[1]);
963     MoveRange(params.buffer, locs, stash);
964   }
965 
966   return 0;
967 }
968 
969 /**
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  *
983  * '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
985  * 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  */
LoadSrcTgtVersion3(CommandParameters & params,RangeSet & tgt,size_t * src_blocks,bool onehash,bool * overlap)995 static int LoadSrcTgtVersion3(CommandParameters& params, RangeSet& tgt, size_t* src_blocks,
996                               bool onehash, bool* overlap) {
997   CHECK(src_blocks != nullptr);
998   CHECK(overlap != nullptr);
999 
1000   if (params.cpos >= params.tokens.size()) {
1001     LOG(ERROR) << "missing source hash";
1002     return -1;
1003   }
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>
1026   tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1027 
1028   std::vector<uint8_t> tgtbuffer(tgt.blocks() * BLOCKSIZE);
1029   if (ReadBlocks(tgt, tgtbuffer, params.fd) == -1) {
1030     return -1;
1031   }
1032 
1033   // Return now if target blocks already have expected content.
1034   if (VerifyBlocks(tgthash, tgtbuffer, tgt.blocks(), false) == 0) {
1035     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;
1082 }
1083 
PerformCommandMove(CommandParameters & params)1084 static int PerformCommandMove(CommandParameters& params) {
1085   size_t blocks = 0;
1086   bool overlap = false;
1087   RangeSet tgt;
1088   int status = LoadSrcTgtVersion3(params, tgt, &blocks, true, &overlap);
1089 
1090   if (status == -1) {
1091     LOG(ERROR) << "failed to read blocks for move";
1092     return -1;
1093   }
1094 
1095   if (status == 0) {
1096     params.foundwrites = true;
1097   } else if (params.foundwrites) {
1098     LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1099   }
1100 
1101   if (params.canwrite) {
1102     if (status == 0) {
1103       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";
1110     }
1111   }
1112 
1113   if (!params.freestash.empty()) {
1114     FreeStash(params.stashbase, params.freestash);
1115     params.freestash.clear();
1116   }
1117 
1118   params.written += tgt.blocks();
1119 
1120   return 0;
1121 }
1122 
PerformCommandStash(CommandParameters & params)1123 static int PerformCommandStash(CommandParameters& params) {
1124   // <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 
1138   RangeSet src = RangeSet::Parse(params.tokens[params.cpos++]);
1139 
1140   allocate(src.blocks() * BLOCKSIZE, params.buffer);
1141   if (ReadBlocks(src, params.buffer, params.fd) == -1) {
1142     return -1;
1143   }
1144   blocks = src.blocks();
1145   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);
1163 }
1164 
PerformCommandFree(CommandParameters & params)1165 static int PerformCommandFree(CommandParameters& params) {
1166   // <stash_id>
1167   if (params.cpos >= params.tokens.size()) {
1168     LOG(ERROR) << "missing stash id in free command";
1169     return -1;
1170   }
1171 
1172   const std::string& id = params.tokens[params.cpos++];
1173   stash_map.erase(id);
1174 
1175   if (params.createdstash || params.canwrite) {
1176     return FreeStash(params.stashbase, id);
1177   }
1178 
1179   return 0;
1180 }
1181 
PerformCommandZero(CommandParameters & params)1182 static int PerformCommandZero(CommandParameters& params) {
1183   if (params.cpos >= params.tokens.size()) {
1184     LOG(ERROR) << "missing target blocks for zero";
1185     return -1;
1186   }
1187 
1188   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)) {
1200         return -1;
1201       }
1202 
1203       if (!check_lseek(params.fd, offset, SEEK_SET)) {
1204         return -1;
1205       }
1206 
1207       for (size_t j = range.first; j < range.second; ++j) {
1208         if (write_all(params.fd, params.buffer, BLOCKSIZE) == -1) {
1209           return -1;
1210         }
1211       }
1212     }
1213   }
1214 
1215   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   }
1220 
1221   return 0;
1222 }
1223 
PerformCommandNew(CommandParameters & params)1224 static int PerformCommandNew(CommandParameters& params) {
1225   if (params.cpos >= params.tokens.size()) {
1226     LOG(ERROR) << "missing target blocks for new";
1227     return -1;
1228   }
1229 
1230   RangeSet tgt = RangeSet::Parse(params.tokens[params.cpos++]);
1231 
1232   if (params.canwrite) {
1233     LOG(INFO) << " writing " << tgt.blocks() << " blocks of new data";
1234 
1235     pthread_mutex_lock(&params.nti.mu);
1236     params.nti.writer = std::make_unique<RangeSinkWriter>(params.fd, tgt);
1237     pthread_cond_broadcast(&params.nti.cv);
1238 
1239     while (params.nti.writer != nullptr) {
1240       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       }
1246       pthread_cond_wait(&params.nti.cv, &params.nti.mu);
1247     }
1248 
1249     pthread_mutex_unlock(&params.nti.mu);
1250   }
1251 
1252   params.written += tgt.blocks();
1253 
1254   return 0;
1255 }
1256 
PerformCommandDiff(CommandParameters & params)1257 static int PerformCommandDiff(CommandParameters& params) {
1258   // <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   }
1263 
1264   size_t offset;
1265   if (!android::base::ParseUint(params.tokens[params.cpos++], &offset)) {
1266     LOG(ERROR) << "invalid patch offset";
1267     return -1;
1268   }
1269 
1270   size_t len;
1271   if (!android::base::ParseUint(params.tokens[params.cpos++], &len)) {
1272     LOG(ERROR) << "invalid patch len";
1273     return -1;
1274   }
1275 
1276   RangeSet tgt;
1277   size_t blocks = 0;
1278   bool overlap = false;
1279   int status = LoadSrcTgtVersion3(params, tgt, &blocks, false, &overlap);
1280 
1281   if (status == -1) {
1282     LOG(ERROR) << "failed to read blocks for diff";
1283     return -1;
1284   }
1285 
1286   if (status == 0) {
1287     params.foundwrites = true;
1288   } else if (params.foundwrites) {
1289     LOG(WARNING) << "warning: commands executed out of order [" << params.cmdname << "]";
1290   }
1291 
1292   if (params.canwrite) {
1293     if (status == 0) {
1294       LOG(INFO) << "patching " << blocks << " blocks to " << tgt.blocks();
1295       Value patch_value(
1296           VAL_BLOB, std::string(reinterpret_cast<const char*>(params.patch_start + offset), len));
1297 
1298       RangeSinkWriter writer(params.fd, tgt);
1299       if (params.cmdname[0] == 'i') {  // imgdiff
1300         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) {
1304           LOG(ERROR) << "Failed to apply image patch.";
1305           failure_type = kPatchApplicationFailure;
1306           return -1;
1307         }
1308       } else {
1309         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) {
1313           LOG(ERROR) << "Failed to apply bsdiff patch.";
1314           failure_type = kPatchApplicationFailure;
1315           return -1;
1316         }
1317       }
1318 
1319       // We expect the output of the patcher to fill the tgt ranges exactly.
1320       if (!writer.Finished()) {
1321         LOG(ERROR) << "range sink underrun?";
1322       }
1323     } else {
1324       LOG(INFO) << "skipping " << blocks << " blocks already patched to " << tgt.blocks() << " ["
1325                 << params.cmdline << "]";
1326     }
1327   }
1328 
1329   if (!params.freestash.empty()) {
1330     FreeStash(params.stashbase, params.freestash);
1331     params.freestash.clear();
1332   }
1333 
1334   params.written += tgt.blocks();
1335 
1336   return 0;
1337 }
1338 
PerformCommandErase(CommandParameters & params)1339 static int PerformCommandErase(CommandParameters& params) {
1340   if (DEBUG_ERASE) {
1341     return PerformCommandZero(params);
1342   }
1343 
1344   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";
1374         return -1;
1375       }
1376     }
1377   }
1378 
1379   return 0;
1380 }
1381 
1382 // Definitions for transfer list command functions
1383 typedef int (*CommandFunction)(CommandParameters&);
1384 
1385 struct Command {
1386     const char* name;
1387     CommandFunction f;
1388 };
1389 
1390 // 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 
PerformBlockImageUpdate(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv,const Command * commands,size_t cmdcount,bool dryrun)1396 static 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) {
1399   CommandParameters params = {};
1400   params.canwrite = !dryrun;
1401 
1402   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 
1418   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];
1422 
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;
1476     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     }
1481     params.nti.receiver_available = true;
1482 
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("");
1493     }
1494   }
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;
1574     }
1575 
1576     const Command* cmd = cmd_map[params.cmdname];
1577 
1578     if (cmd->f != nullptr && cmd->f(params) == -1) {
1579       LOG(ERROR) << "failed to execute command [" << line << "]";
1580       goto pbiudone;
1581     }
1582 
1583     if (params.canwrite) {
1584       if (ota_fsync(params.fd) == -1) {
1585         failure_type = kFsyncFailure;
1586         PLOG(ERROR) << "fsync failed";
1587         goto pbiudone;
1588       }
1589       fprintf(cmd_pipe, "set_progress %.4f\n", static_cast<double>(params.written) / total_blocks);
1590       fflush(cmd_pipe);
1591     }
1592   }
1593 
1594   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);
1606     }
1607     // 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   }
1613 
1614   rc = 0;
1615 
1616 pbiudone:
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 
1623   if (params.nti.brotli_decoder_state != nullptr) {
1624     BrotliDecoderDestroyInstance(params.nti.brotli_decoder_state);
1625   }
1626 
1627   // 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" : "");
1638 }
1639 
1640 /**
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  */
BlockImageVerifyFn(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)1684 Value* BlockImageVerifyFn(const char* name, State* state,
1685                           const std::vector<std::unique_ptr<Expr>>& argv) {
1686     // Commands which are not tested are set to nullptr to skip them completely
1687     const Command commands[] = {
1688         { "bsdiff",     PerformCommandDiff  },
1689         { "erase",      nullptr             },
1690         { "free",       PerformCommandFree  },
1691         { "imgdiff",    PerformCommandDiff  },
1692         { "move",       PerformCommandMove  },
1693         { "new",        nullptr             },
1694         { "stash",      PerformCommandStash },
1695         { "zero",       nullptr             }
1696     };
1697 
1698     // Perform a dry run without writing to test if an update can proceed
1699     return PerformBlockImageUpdate(name, state, argv, commands,
1700                 sizeof(commands) / sizeof(commands[0]), true);
1701 }
1702 
BlockImageUpdateFn(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)1703 Value* BlockImageUpdateFn(const char* name, State* state,
1704                           const std::vector<std::unique_ptr<Expr>>& argv) {
1705     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 
1716     return PerformBlockImageUpdate(name, state, argv, commands,
1717                 sizeof(commands) / sizeof(commands[0]), false);
1718 }
1719 
RangeSha1Fn(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)1720 Value* RangeSha1Fn(const char* name, State* state, const std::vector<std::unique_ptr<Expr>>& argv) {
1721   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);
1756   for (const auto& range : rs) {
1757     if (!check_lseek(fd, static_cast<off64_t>(range.first) * BLOCKSIZE, SEEK_SET)) {
1758       ErrorAbort(state, kLseekFailure, "failed to seek %s: %s", blockdev_filename->data.c_str(),
1759                  strerror(errno));
1760       return StringValue("");
1761     }
1762 
1763     for (size_t j = range.first; j < range.second; ++j) {
1764       if (read_all(fd, buffer, BLOCKSIZE) == -1) {
1765         ErrorAbort(state, kFreadFailure, "failed to read %s: %s", blockdev_filename->data.c_str(),
1766                    strerror(errno));
1767         return StringValue("");
1768       }
1769 
1770       SHA1_Update(&ctx, buffer.data(), BLOCKSIZE);
1771     }
1772   }
1773   uint8_t digest[SHA_DIGEST_LENGTH];
1774   SHA1_Final(digest, &ctx);
1775 
1776   return StringValue(print_sha1(digest));
1777 }
1778 
1779 // 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 
CheckFirstBlockFn(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)1784 Value* CheckFirstBlockFn(const char* name, State* state,
1785                          const std::vector<std::unique_ptr<Expr>>& argv) {
1786   if (argv.size() != 1) {
1787     ErrorAbort(state, kArgsParsingFailure, "check_first_block expects 1 argument, got %zu",
1788                argv.size());
1789     return StringValue("");
1790   }
1791 
1792   std::vector<std::unique_ptr<Value>> args;
1793   if (!ReadValueArgs(state, argv, &args)) {
1794     return nullptr;
1795   }
1796 
1797   const std::unique_ptr<Value>& arg_filename = args[0];
1798 
1799   if (arg_filename->type != VAL_STRING) {
1800     ErrorAbort(state, kArgsParsingFailure, "filename argument to %s must be string", name);
1801     return StringValue("");
1802   }
1803 
1804   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   }
1810 
1811   RangeSet blk0(std::vector<Range>{ Range{ 0, 1 } });
1812   std::vector<uint8_t> block0_buffer(BLOCKSIZE);
1813 
1814   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   }
1819 
1820   // 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
1826 
1827   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]);
1829 
1830   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   }
1834 
1835   return StringValue("t");
1836 }
1837 
BlockImageRecoverFn(const char * name,State * state,const std::vector<std::unique_ptr<Expr>> & argv)1838 Value* BlockImageRecoverFn(const char* name, State* state,
1839                            const std::vector<std::unique_ptr<Expr>>& argv) {
1840   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;
1881   if (!fh.get_status(status)) {
1882     ErrorAbort(state, kLibfecFailure, "failed to read FEC status");
1883     return StringValue("");
1884   }
1885 
1886   uint8_t buffer[BLOCKSIZE];
1887   for (const auto& range : RangeSet::Parse(ranges->data)) {
1888     for (size_t j = range.first; j < range.second; ++j) {
1889       // Stay within the data area, libfec validates and corrects metadata
1890       if (status.data_size <= static_cast<uint64_t>(j) * BLOCKSIZE) {
1891         continue;
1892       }
1893 
1894       if (fh.pread(buffer, BLOCKSIZE, static_cast<off64_t>(j) * BLOCKSIZE) != BLOCKSIZE) {
1895         ErrorAbort(state, kLibfecFailure, "failed to recover %s (block %zu): %s",
1896                    filename->data.c_str(), j, strerror(errno));
1897         return StringValue("");
1898       }
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.
1910     }
1911   }
1912   LOG(INFO) << "..." << filename->data << " image recovered successfully.";
1913   return StringValue("t");
1914 }
1915 
RegisterBlockImageFunctions()1916 void RegisterBlockImageFunctions() {
1917   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);
1922 }
1923