2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <sys/ioctl.h>
21 #include <ext4_utils/ext4_sb.h>
24 #include <squashfs_utils.h>
27 #if defined(__linux__)
29 #elif defined(__APPLE__)
31 #define BLKGETSIZE64 DKIOCGETBLOCKCOUNT
32 #define fdatasync(fd) fcntl((fd), F_FULLFSYNC)
35 #include "fec_private.h"
37 /* used by `find_offset'; returns metadata size for a file size `size' and
38 `roots' Reed-Solomon parity bytes */
39 using size_func = uint64_t (*)(uint64_t size, int roots);
41 /* performs a binary search to find a metadata offset from a file so that
42 the metadata size matches function `get_real_size(size, roots)', using
43 the approximate size returned by `get_appr_size' as a starting point */
44 static int find_offset(uint64_t file_size, int roots, uint64_t *offset,
45 size_func get_appr_size, size_func get_real_size)
51 if (file_size % FEC_BLOCKSIZE) {
52 /* must be a multiple of block size */
53 error("file size not multiple of " stringify(FEC_BLOCKSIZE));
58 uint64_t mi = get_appr_size(file_size, roots);
59 uint64_t lo = file_size - mi * 2;
60 uint64_t hi = file_size - mi / 2;
63 mi = ((hi + lo) / (2 * FEC_BLOCKSIZE)) * FEC_BLOCKSIZE;
64 uint64_t total = mi + get_real_size(mi, roots);
66 if (total < file_size) {
67 lo = mi + FEC_BLOCKSIZE;
68 } else if (total > file_size) {
72 debug("file_size = %" PRIu64 " -> offset = %" PRIu64, file_size,
78 warn("could not determine offset");
83 /* returns verity metadata size for a `size' byte file */
84 static uint64_t get_verity_size(uint64_t size, int)
86 return VERITY_METADATA_SIZE + verity_get_size(size, NULL, NULL);
89 /* computes the verity metadata offset for a file with size `f->size' */
90 static int find_verity_offset(fec_handle *f, uint64_t *offset)
95 return find_offset(f->data_size, 0, offset, get_verity_size,
99 /* attempts to read and validate an ecc header from file position `offset' */
100 static int parse_ecc_header(fec_handle *f, uint64_t offset)
103 check(f->ecc.rsn > 0 && f->ecc.rsn < FEC_RSM);
104 check(f->size > sizeof(fec_header));
106 debug("offset = %" PRIu64, offset);
108 if (offset > f->size - sizeof(fec_header)) {
114 /* there's obviously no ecc data at this point, so there is no need to
115 call fec_pread to access this data */
116 if (!raw_pread(f, &header, sizeof(fec_header), offset)) {
117 error("failed to read: %s", strerror(errno));
121 /* move offset back to the beginning of the block for validating header */
122 offset -= offset % FEC_BLOCKSIZE;
124 if (header.magic != FEC_MAGIC) {
127 if (header.version != FEC_VERSION) {
128 error("unsupported ecc version: %u", header.version);
131 if (header.size != sizeof(fec_header)) {
132 error("unexpected ecc header size: %u", header.size);
135 if (header.roots == 0 || header.roots >= FEC_RSM) {
136 error("invalid ecc roots: %u", header.roots);
139 if (f->ecc.roots != (int)header.roots) {
140 error("unexpected number of roots: %d vs %u", f->ecc.roots,
144 if (header.fec_size % header.roots ||
145 header.fec_size % FEC_BLOCKSIZE) {
146 error("inconsistent ecc size %u", header.fec_size);
150 f->data_size = header.inp_size;
151 f->ecc.blocks = fec_div_round_up(f->data_size, FEC_BLOCKSIZE);
152 f->ecc.rounds = fec_div_round_up(f->ecc.blocks, f->ecc.rsn);
154 if (header.fec_size !=
155 (uint32_t)f->ecc.rounds * f->ecc.roots * FEC_BLOCKSIZE) {
156 error("inconsistent ecc size %u", header.fec_size);
160 f->ecc.size = header.fec_size;
161 f->ecc.start = header.inp_size;
163 /* validate encoding data; caller may opt not to use it if invalid */
167 uint8_t buf[FEC_BLOCKSIZE];
169 uint32_t len = FEC_BLOCKSIZE;
171 while (n < f->ecc.size) {
172 if (len > f->ecc.size - n) {
173 len = f->ecc.size - n;
176 if (!raw_pread(f, buf, len, f->ecc.start + n)) {
177 error("failed to read ecc: %s", strerror(errno));
181 SHA256_Update(&ctx, buf, len);
185 uint8_t hash[SHA256_DIGEST_LENGTH];
186 SHA256_Final(hash, &ctx);
188 f->ecc.valid = !memcmp(hash, header.hash, SHA256_DIGEST_LENGTH);
191 warn("ecc data not valid");
197 /* attempts to read an ecc header from `offset', and checks for a backup copy
198 at the end of the block if the primary header is not valid */
199 static int parse_ecc(fec_handle *f, uint64_t offset)
202 check(offset % FEC_BLOCKSIZE == 0);
203 check(offset < UINT64_MAX - FEC_BLOCKSIZE);
205 /* check the primary header at the beginning of the block */
206 if (parse_ecc_header(f, offset) == 0) {
210 /* check the backup header at the end of the block */
211 if (parse_ecc_header(f, offset + FEC_BLOCKSIZE - sizeof(fec_header)) == 0) {
212 warn("using backup ecc header");
219 /* reads the squashfs superblock and returns the size of the file system in
221 static int get_squashfs_size(fec_handle *f, uint64_t *offset)
226 size_t sb_size = squashfs_get_sb_size();
227 check(sb_size <= SSIZE_MAX);
229 uint8_t buffer[sb_size];
231 if (fec_pread(f, buffer, sizeof(buffer), 0) != (ssize_t)sb_size) {
232 error("failed to read superblock: %s", strerror(errno));
238 if (squashfs_parse_sb_buffer(buffer, &sq) < 0) {
239 error("failed to parse superblock: %s", strerror(errno));
243 *offset = sq.bytes_used_4K_padded;
247 /* reads the ext4 superblock and returns the size of the file system in
249 static int get_ext4_size(fec_handle *f, uint64_t *offset)
252 check(f->size > 1024 + sizeof(ext4_super_block));
257 if (fec_pread(f, &sb, sizeof(sb), 1024) != sizeof(sb)) {
258 error("failed to read superblock: %s", strerror(errno));
263 info.len = 0; /* only len is set to 0 to ask the device for real size. */
265 if (ext4_parse_sb(&sb, &info) != 0) {
274 /* attempts to determine file system size, if no fs type is specified in
275 `f->flags', tries all supported types, and returns the size in `offset' */
276 static int get_fs_size(fec_handle *f, uint64_t *offset)
281 if (f->flags & FEC_FS_EXT4) {
282 return get_ext4_size(f, offset);
283 } else if (f->flags & FEC_FS_SQUASH) {
284 return get_squashfs_size(f, offset);
286 /* try all alternatives */
287 int rc = get_ext4_size(f, offset);
290 debug("found ext4fs");
294 rc = get_squashfs_size(f, offset);
297 debug("found squashfs");
304 /* locates, validates, and loads verity metadata from `f->fd' */
305 static int load_verity(fec_handle *f)
308 debug("size = %" PRIu64 ", flags = %d", f->data_size, f->flags);
310 uint64_t offset = f->data_size - VERITY_METADATA_SIZE;
312 /* verity header is at the end of the data area */
313 if (verity_parse_header(f, offset) == 0) {
314 debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
315 f->verity.hash_start);
319 debug("trying legacy formats");
321 /* legacy format at the end of the partition */
322 if (find_verity_offset(f, &offset) == 0 &&
323 verity_parse_header(f, offset) == 0) {
324 debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
325 f->verity.hash_start);
329 /* legacy format after the file system, but not at the end */
330 int rc = get_fs_size(f, &offset);
333 debug("file system size = %" PRIu64, offset);
334 rc = verity_parse_header(f, offset);
337 debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
338 f->verity.hash_start);
345 /* locates, validates, and loads ecc data from `f->fd' */
346 static int load_ecc(fec_handle *f)
349 debug("size = %" PRIu64, f->data_size);
351 uint64_t offset = f->data_size - FEC_BLOCKSIZE;
353 if (parse_ecc(f, offset) == 0) {
354 debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
362 /* sets `f->size' to the size of the file or block device */
363 static int get_size(fec_handle *f)
369 if (fstat(f->fd, &st) == -1) {
370 error("fstat failed: %s", strerror(errno));
374 if (S_ISBLK(st.st_mode)) {
375 debug("block device");
377 if (ioctl(f->fd, BLKGETSIZE64, &f->size) == -1) {
378 error("ioctl failed: %s", strerror(errno));
381 } else if (S_ISREG(st.st_mode)) {
383 f->size = st.st_size;
385 error("unsupported type %d", (int)st.st_mode);
393 /* clears fec_handle fiels to safe values */
394 static void reset_handle(fec_handle *f)
404 memset(&f->ecc, 0, sizeof(f->ecc));
405 memset(&f->verity, 0, sizeof(f->verity));
408 /* closes and flushes `f->fd' and releases any memory allocated for `f' */
409 int fec_close(struct fec_handle *f)
414 if (f->mode & O_RDWR && fdatasync(f->fd) == -1) {
415 warn("fdatasync failed: %s", strerror(errno));
421 if (f->verity.hash) {
422 delete[] f->verity.hash;
424 if (f->verity.salt) {
425 delete[] f->verity.salt;
427 if (f->verity.table) {
428 delete[] f->verity.table;
431 pthread_mutex_destroy(&f->mutex);
439 /* populates `data' from the internal data in `f', returns a value <0 if verity
440 metadata is not available in `f->fd' */
441 int fec_verity_get_metadata(struct fec_handle *f, struct fec_verity_metadata *data)
446 if (!f->verity.metadata_start) {
450 check(f->data_size < f->size);
451 check(f->data_size <= f->verity.hash_start);
452 check(f->data_size <= f->verity.metadata_start);
453 check(f->verity.table);
455 data->disabled = f->verity.disabled;
456 data->data_size = f->data_size;
457 memcpy(data->signature, f->verity.header.signature,
458 sizeof(data->signature));
459 memcpy(data->ecc_signature, f->verity.ecc_header.signature,
460 sizeof(data->ecc_signature));
461 data->table = f->verity.table;
462 data->table_length = f->verity.header.length;
467 /* populates `data' from the internal data in `f', returns a value <0 if ecc
468 metadata is not available in `f->fd' */
469 int fec_ecc_get_metadata(struct fec_handle *f, struct fec_ecc_metadata *data)
478 check(f->data_size < f->size);
479 check(f->ecc.start >= f->data_size);
480 check(f->ecc.start < f->size);
481 check(f->ecc.start % FEC_BLOCKSIZE == 0)
483 data->valid = f->ecc.valid;
484 data->roots = f->ecc.roots;
485 data->blocks = f->ecc.blocks;
486 data->rounds = f->ecc.rounds;
487 data->start = f->ecc.start;
492 /* populates `data' from the internal status in `f' */
493 int fec_get_status(struct fec_handle *f, struct fec_status *s)
500 s->errors = f->errors;
501 s->data_size = f->data_size;
507 /* opens `path' using given options and returns a fec_handle in `handle' if
509 int fec_open(struct fec_handle **handle, const char *path, int mode, int flags,
514 check(roots > 0 && roots < FEC_RSM);
516 debug("path = %s, mode = %d, flags = %d, roots = %d", path, mode, flags,
519 if (mode & (O_CREAT | O_TRUNC | O_EXCL | O_WRONLY)) {
520 /* only reading and updating existing files is supported */
521 error("failed to open '%s': (unsupported mode %d)", path, mode);
526 fec::handle f(new (std::nothrow) fec_handle, fec_close);
529 error("failed to allocate file handle");
534 reset_handle(f.get());
537 f->ecc.roots = roots;
538 f->ecc.rsn = FEC_RSM - roots;
541 if (unlikely(pthread_mutex_init(&f->mutex, NULL) != 0)) {
542 error("failed to create a mutex: %s", strerror(errno));
546 f->fd = TEMP_FAILURE_RETRY(open(path, mode | O_CLOEXEC));
549 error("failed to open '%s': %s", path, strerror(errno));
553 if (get_size(f.get()) == -1) {
554 error("failed to get size for '%s': %s", path, strerror(errno));
558 f->data_size = f->size; /* until ecc and/or verity are loaded */
560 if (load_ecc(f.get()) == -1) {
561 debug("error-correcting codes not found from '%s'", path);
564 if (load_verity(f.get()) == -1) {
565 debug("verity metadata not found from '%s'", path);
568 *handle = f.release();