fec_open.cpp revision 0403024cd6763fff3a0118b15e68c0f7fe4766d5
1/*
2 * Copyright (C) 2015 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 <stdlib.h>
18#include <sys/ioctl.h>
19#include <sys/stat.h>
20
21extern "C" {
22    #include <squashfs_utils.h>
23    #include <ext4_sb.h>
24}
25
26#if defined(__linux__)
27    #include <linux/fs.h>
28#elif defined(__APPLE__)
29    #include <sys/disk.h>
30    #define BLKGETSIZE64 DKIOCGETBLOCKCOUNT
31    #define fdatasync(fd) fcntl((fd), F_FULLFSYNC)
32#endif
33
34#include "fec_private.h"
35
36/* used by `find_offset'; returns metadata size for a file size `size' and
37   `roots' Reed-Solomon parity bytes */
38using size_func = uint64_t (*)(uint64_t size, int roots);
39
40/* performs a binary search to find a metadata offset from a file so that
41   the metadata size matches function `get_real_size(size, roots)', using
42   the approximate size returned by `get_appr_size' as a starting point */
43static int find_offset(uint64_t file_size, int roots, uint64_t *offset,
44        size_func get_appr_size, size_func get_real_size)
45{
46    check(offset);
47    check(get_appr_size);
48    check(get_real_size);
49
50    if (file_size % FEC_BLOCKSIZE) {
51        /* must be a multiple of block size */
52        error("file size not multiple of " stringify(FEC_BLOCKSIZE));
53        errno = EINVAL;
54        return -1;
55    }
56
57    uint64_t mi = get_appr_size(file_size, roots);
58    uint64_t lo = file_size - mi * 2;
59    uint64_t hi = file_size - mi / 2;
60
61    while (lo < hi) {
62        mi = ((hi + lo) / (2 * FEC_BLOCKSIZE)) * FEC_BLOCKSIZE;
63        uint64_t total = mi + get_real_size(mi, roots);
64
65        if (total < file_size) {
66            lo = mi + FEC_BLOCKSIZE;
67        } else if (total > file_size) {
68            hi = mi;
69        } else {
70            *offset = mi;
71            debug("file_size = %" PRIu64 " -> offset = %" PRIu64, file_size,
72                mi);
73            return 0;
74        }
75    }
76
77    warn("could not determine offset");
78    errno = ERANGE;
79    return -1;
80}
81
82/* returns verity metadata size for a `size' byte file */
83static uint64_t get_verity_size(uint64_t size, int)
84{
85    return VERITY_METADATA_SIZE + verity_get_size(size, NULL, NULL);
86}
87
88/* computes the verity metadata offset for a file with size `f->size' */
89static int find_verity_offset(fec_handle *f, uint64_t *offset)
90{
91    check(f);
92    check(offset);
93
94    return find_offset(f->data_size, 0, offset, get_verity_size,
95                get_verity_size);
96}
97
98/* attempts to read and validate an ecc header from file position `offset' */
99static int parse_ecc_header(fec_handle *f, uint64_t offset)
100{
101    check(f);
102    check(f->ecc.rsn > 0 && f->ecc.rsn < FEC_RSM);
103    check(f->size > sizeof(fec_header));
104
105    debug("offset = %" PRIu64, offset);
106
107    if (offset > f->size - sizeof(fec_header)) {
108        return -1;
109    }
110
111    fec_header header;
112
113    /* there's obviously no ecc data at this point, so there is no need to
114       call fec_pread to access this data */
115    if (!raw_pread(f, &header, sizeof(fec_header), offset)) {
116        error("failed to read: %s", strerror(errno));
117        return -1;
118    }
119
120    if (header.magic != FEC_MAGIC) {
121        return -1;
122    }
123    if (header.version != FEC_VERSION) {
124        error("unsupported ecc version: %u", header.version);
125        return -1;
126    }
127    if (header.size != sizeof(fec_header)) {
128        error("unexpected ecc header size: %u", header.size);
129        return -1;
130    }
131    if (header.roots == 0 || header.roots >= FEC_RSM) {
132        error("invalid ecc roots: %u", header.roots);
133        return -1;
134    }
135    if (f->ecc.roots != (int)header.roots) {
136        error("unexpected number of roots: %d vs %u", f->ecc.roots,
137            header.roots);
138        return -1;
139    }
140    if (header.fec_size % header.roots ||
141            header.fec_size % FEC_BLOCKSIZE) {
142        error("inconsistent ecc size %u", header.fec_size);
143        return -1;
144    }
145    /* structure: data | ecc | header */
146    if (offset < header.fec_size ||
147            offset - header.fec_size != header.inp_size) {
148        error("unexpected input size: %" PRIu64 " vs %" PRIu64, offset,
149            header.inp_size);
150        return -1;
151    }
152
153    f->data_size = header.inp_size;
154    f->ecc.blocks = fec_div_round_up(f->data_size, FEC_BLOCKSIZE);
155    f->ecc.rounds = fec_div_round_up(f->ecc.blocks, f->ecc.rsn);
156
157    if (header.fec_size !=
158            (uint32_t)f->ecc.rounds * f->ecc.roots * FEC_BLOCKSIZE) {
159        error("inconsistent ecc size %u", header.fec_size);
160        return -1;
161    }
162
163    f->ecc.size = header.fec_size;
164    f->ecc.start = header.inp_size;
165
166    /* validate encoding data; caller may opt not to use it if invalid */
167    SHA256_CTX ctx;
168    SHA256_Init(&ctx);
169
170    uint8_t buf[FEC_BLOCKSIZE];
171    uint32_t n = 0;
172    uint32_t len = FEC_BLOCKSIZE;
173
174    while (n < f->ecc.size) {
175        if (len > f->ecc.size - n) {
176            len = f->ecc.size - n;
177        }
178
179        if (!raw_pread(f, buf, len, f->ecc.start + n)) {
180            error("failed to read ecc: %s", strerror(errno));
181            return -1;
182        }
183
184        SHA256_Update(&ctx, buf, len);
185        n += len;
186    }
187
188    uint8_t hash[SHA256_DIGEST_LENGTH];
189    SHA256_Final(hash, &ctx);
190
191    f->ecc.valid = !memcmp(hash, header.hash, SHA256_DIGEST_LENGTH);
192
193    if (!f->ecc.valid) {
194        warn("ecc data not valid");
195    }
196
197    return 0;
198}
199
200/* attempts to read an ecc header from `offset', and checks for a backup copy
201   at the end of the block if the primary header is not valid */
202static int parse_ecc(fec_handle *f, uint64_t offset)
203{
204    check(f);
205    check(offset % FEC_BLOCKSIZE == 0);
206    check(offset < UINT64_MAX - FEC_BLOCKSIZE);
207
208    /* check the primary header at the beginning of the block */
209    if (parse_ecc_header(f, offset) == 0) {
210        return 0;
211    }
212
213    /* check the backup header at the end of the block */
214    if (parse_ecc_header(f, offset + FEC_BLOCKSIZE - sizeof(fec_header)) == 0) {
215        warn("using backup ecc header");
216        return 0;
217    }
218
219    return -1;
220}
221
222/* reads the squashfs superblock and returns the size of the file system in
223   `offset' */
224static int get_squashfs_size(fec_handle *f, uint64_t *offset)
225{
226    check(f);
227    check(offset);
228
229    size_t sb_size = squashfs_get_sb_size();
230    check(sb_size <= SSIZE_MAX);
231
232    uint8_t buffer[sb_size];
233
234    if (fec_pread(f, buffer, sizeof(buffer), 0) != (ssize_t)sb_size) {
235        error("failed to read superblock: %s", strerror(errno));
236        return -1;
237    }
238
239    squashfs_info sq;
240
241    if (squashfs_parse_sb_buffer(buffer, &sq) < 0) {
242        error("failed to parse superblock: %s", strerror(errno));
243        return -1;
244    }
245
246    *offset = sq.bytes_used_4K_padded;
247    return 0;
248}
249
250/* reads the ext4 superblock and returns the size of the file system in
251   `offset' */
252static int get_ext4_size(fec_handle *f, uint64_t *offset)
253{
254    check(f);
255    check(f->size > 1024 + sizeof(ext4_super_block));
256    check(offset);
257
258    ext4_super_block sb;
259
260    if (fec_pread(f, &sb, sizeof(sb), 1024) != sizeof(sb)) {
261        error("failed to read superblock: %s", strerror(errno));
262        return -1;
263    }
264
265    fs_info info;
266    info.len = 0;  /* only len is set to 0 to ask the device for real size. */
267
268    if (ext4_parse_sb(&sb, &info) != 0) {
269        errno = EINVAL;
270        return -1;
271    }
272
273    *offset = info.len;
274    return 0;
275}
276
277/* attempts to determine file system size, if no fs type is specified in
278   `f->flags', tries all supported types, and returns the size in `offset' */
279static int get_fs_size(fec_handle *f, uint64_t *offset)
280{
281    check(f);
282    check(offset);
283
284    if (f->flags & FEC_FS_EXT4) {
285        return get_ext4_size(f, offset);
286    } else if (f->flags & FEC_FS_SQUASH) {
287        return get_squashfs_size(f, offset);
288    } else {
289        /* try all alternatives */
290        int rc = get_ext4_size(f, offset);
291
292        if (rc == 0) {
293            debug("found ext4fs");
294            return rc;
295        }
296
297        rc = get_squashfs_size(f, offset);
298
299        if (rc == 0) {
300            debug("found squashfs");
301        }
302
303        return rc;
304    }
305}
306
307/* locates, validates, and loads verity metadata from `f->fd' */
308static int load_verity(fec_handle *f)
309{
310    check(f);
311    debug("size = %" PRIu64 ", flags = %d", f->data_size, f->flags);
312
313    uint64_t offset = f->data_size - VERITY_METADATA_SIZE;
314
315    /* verity header is at the end of the data area */
316    if (verity_parse_header(f, offset) == 0) {
317        debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
318            f->verity.hash_start);
319        return 0;
320    }
321
322    debug("trying legacy formats");
323
324    /* legacy format at the end of the partition */
325    if (find_verity_offset(f, &offset) == 0 &&
326            verity_parse_header(f, offset) == 0) {
327        debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
328            f->verity.hash_start);
329        return 0;
330    }
331
332    /* legacy format after the file system, but not at the end */
333    int rc = get_fs_size(f, &offset);
334
335    if (rc == 0) {
336        debug("file system size = %" PRIu64, offset);
337        rc = verity_parse_header(f, offset);
338
339        if (rc == 0) {
340            debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
341                f->verity.hash_start);
342        }
343    }
344
345    return rc;
346}
347
348/* locates, validates, and loads ecc data from `f->fd' */
349static int load_ecc(fec_handle *f)
350{
351    check(f);
352    debug("size = %" PRIu64, f->data_size);
353
354    uint64_t offset = f->data_size - FEC_BLOCKSIZE;
355
356    if (parse_ecc(f, offset) == 0) {
357        debug("found at %" PRIu64 " (start %" PRIu64 ")", offset,
358            f->ecc.start);
359        return 0;
360    }
361
362    return -1;
363}
364
365/* sets `f->size' to the size of the file or block device */
366static int get_size(fec_handle *f)
367{
368    check(f);
369
370    struct stat st;
371
372    if (fstat(f->fd, &st) == -1) {
373        error("fstat failed: %s", strerror(errno));
374        return -1;
375    }
376
377    if (S_ISBLK(st.st_mode)) {
378        debug("block device");
379
380        if (ioctl(f->fd, BLKGETSIZE64, &f->size) == -1) {
381            error("ioctl failed: %s", strerror(errno));
382            return -1;
383        }
384    } else if (S_ISREG(st.st_mode)) {
385        debug("file");
386        f->size = st.st_size;
387    } else {
388        error("unsupported type %d", (int)st.st_mode);
389        errno = EACCES;
390        return -1;
391    }
392
393    return 0;
394}
395
396/* clears fec_handle fiels to safe values */
397static void reset_handle(fec_handle *f)
398{
399    f->fd = -1;
400    f->flags = 0;
401    f->mode = 0;
402    f->errors = 0;
403    f->data_size = 0;
404    f->pos = 0;
405    f->size = 0;
406
407    memset(&f->ecc, 0, sizeof(f->ecc));
408    memset(&f->verity, 0, sizeof(f->verity));
409}
410
411/* closes and flushes `f->fd' and releases any memory allocated for `f' */
412int fec_close(struct fec_handle *f)
413{
414    check(f);
415
416    if (f->fd != -1) {
417        if (f->mode & O_RDWR && fdatasync(f->fd) == -1) {
418            warn("fdatasync failed: %s", strerror(errno));
419        }
420
421        TEMP_FAILURE_RETRY(close(f->fd));
422    }
423
424    if (f->verity.hash) {
425        delete[] f->verity.hash;
426    }
427    if (f->verity.salt) {
428        delete[] f->verity.salt;
429    }
430    if (f->verity.table) {
431        delete[] f->verity.table;
432    }
433
434    pthread_mutex_destroy(&f->mutex);
435
436    reset_handle(f);
437    delete f;
438
439    return 0;
440}
441
442/* populates `data' from the internal data in `f', returns a value <0 if verity
443   metadata is not available in `f->fd' */
444int fec_verity_get_metadata(struct fec_handle *f, struct fec_verity_metadata *data)
445{
446    check(f);
447    check(data);
448
449    if (!f->verity.metadata_start) {
450        return -1;
451    }
452
453    check(f->data_size < f->size);
454    check(f->data_size <= f->verity.hash_start);
455    check(f->data_size <= f->verity.metadata_start);
456    check(f->verity.table);
457
458    data->disabled = f->verity.disabled;
459    data->data_size = f->data_size;
460    memcpy(data->signature, f->verity.header.signature, sizeof(data->signature));
461    data->table = f->verity.table;
462    data->table_length = f->verity.header.length;
463
464    return 0;
465}
466
467/* populates `data' from the internal data in `f', returns a value <0 if ecc
468   metadata is not available in `f->fd' */
469int fec_ecc_get_metadata(struct fec_handle *f, struct fec_ecc_metadata *data)
470{
471    check(f);
472    check(data);
473
474    if (!f->ecc.start) {
475        return -1;
476    }
477
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)
482
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;
488
489    return 0;
490}
491
492/* populates `data' from the internal status in `f' */
493int fec_get_status(struct fec_handle *f, struct fec_status *s)
494{
495    check(f);
496    check(s);
497
498    s->flags = f->flags;
499    s->mode = f->mode;
500    s->errors = f->errors;
501    s->data_size = f->data_size;
502    s->size = f->size;
503
504    return 0;
505}
506
507/* opens `path' using given options and returns a fec_handle in `handle' if
508   successful */
509int fec_open(struct fec_handle **handle, const char *path, int mode, int flags,
510        int roots)
511{
512    check(path);
513    check(handle);
514    check(roots > 0 && roots < FEC_RSM);
515
516    debug("path = %s, mode = %d, flags = %d, roots = %d", path, mode, flags,
517        roots);
518
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);
522        errno = EACCES;
523        return -1;
524    }
525
526    fec::handle f(new (std::nothrow) fec_handle, fec_close);
527
528    if (unlikely(!f)) {
529        error("failed to allocate file handle");
530        errno = ENOMEM;
531        return -1;
532    }
533
534    reset_handle(f.get());
535
536    f->mode = mode;
537    f->ecc.roots = roots;
538    f->ecc.rsn = FEC_RSM - roots;
539    f->flags = flags;
540
541    if (unlikely(pthread_mutex_init(&f->mutex, NULL) != 0)) {
542        error("failed to create a mutex: %s", strerror(errno));
543        return -1;
544    }
545
546    f->fd = TEMP_FAILURE_RETRY(open(path, mode | O_CLOEXEC));
547
548    if (f->fd == -1) {
549        error("failed to open '%s': %s", path, strerror(errno));
550        return -1;
551    }
552
553    if (get_size(f.get()) == -1) {
554        error("failed to get size for '%s': %s", path, strerror(errno));
555        return -1;
556    }
557
558    f->data_size = f->size; /* until ecc and/or verity are loaded */
559
560    if (load_ecc(f.get()) == -1) {
561        debug("error-correcting codes not found from '%s'", path);
562    }
563
564    if (load_verity(f.get()) == -1) {
565        debug("verity metadata not found from '%s'", path);
566    }
567
568    *handle = f.release();
569    return 0;
570}
571