Randall Spangler | d55c645 | 2010-06-10 12:43:51 -0700 | [diff] [blame] | 1 | /* Copyright (c) 2010 The Chromium OS Authors. All rights reserved. |
| 2 | * Use of this source code is governed by a BSD-style license that can be |
| 3 | * found in the LICENSE file. |
| 4 | * |
| 5 | * Host functions for verified boot. |
| 6 | */ |
| 7 | |
| 8 | /* TODO: change all 'return 0', 'return 1' into meaningful return codes */ |
| 9 | |
| 10 | #include <stdio.h> |
| 11 | #include <stdlib.h> |
Randall Spangler | 6a97b3e | 2010-06-10 17:55:02 -0700 | [diff] [blame] | 12 | #include <unistd.h> |
Randall Spangler | d55c645 | 2010-06-10 12:43:51 -0700 | [diff] [blame] | 13 | |
| 14 | #include "host_common.h" |
| 15 | |
| 16 | #include "cryptolib.h" |
| 17 | #include "utility.h" |
| 18 | #include "vboot_common.h" |
| 19 | |
| 20 | |
| 21 | uint8_t* ReadFile(const char* filename, uint64_t* size) { |
| 22 | FILE* f; |
| 23 | uint8_t* buf; |
| 24 | |
| 25 | f = fopen(filename, "rb"); |
| 26 | if (!f) { |
Bill Richardson | abf0550 | 2010-07-01 10:22:06 -0700 | [diff] [blame] | 27 | VBDEBUG(("Unable to open file %s\n", filename)); |
Randall Spangler | d55c645 | 2010-06-10 12:43:51 -0700 | [diff] [blame] | 28 | return NULL; |
| 29 | } |
| 30 | |
| 31 | fseek(f, 0, SEEK_END); |
| 32 | *size = ftell(f); |
| 33 | rewind(f); |
| 34 | |
| 35 | buf = Malloc(*size); |
| 36 | if (!buf) { |
| 37 | fclose(f); |
| 38 | return NULL; |
| 39 | } |
| 40 | |
| 41 | if(1 != fread(buf, *size, 1, f)) { |
Bill Richardson | abf0550 | 2010-07-01 10:22:06 -0700 | [diff] [blame] | 42 | VBDEBUG(("Unable to read from file %s\n", filename)); |
Randall Spangler | d55c645 | 2010-06-10 12:43:51 -0700 | [diff] [blame] | 43 | fclose(f); |
| 44 | Free(buf); |
| 45 | return NULL; |
| 46 | } |
| 47 | |
| 48 | fclose(f); |
| 49 | return buf; |
| 50 | } |
Randall Spangler | 6a97b3e | 2010-06-10 17:55:02 -0700 | [diff] [blame] | 51 | |
| 52 | |
| 53 | int WriteFile(const char* filename, const void *data, uint64_t size) { |
| 54 | FILE *f = fopen(filename, "wb"); |
| 55 | if (!f) { |
Bill Richardson | abf0550 | 2010-07-01 10:22:06 -0700 | [diff] [blame] | 56 | VBDEBUG(("Unable to open file %s\n", filename)); |
Randall Spangler | 6a97b3e | 2010-06-10 17:55:02 -0700 | [diff] [blame] | 57 | return 1; |
| 58 | } |
| 59 | |
| 60 | if (1 != fwrite(data, size, 1, f)) { |
Bill Richardson | abf0550 | 2010-07-01 10:22:06 -0700 | [diff] [blame] | 61 | VBDEBUG(("Unable to write to file %s\n", filename)); |
Randall Spangler | 6a97b3e | 2010-06-10 17:55:02 -0700 | [diff] [blame] | 62 | fclose(f); |
| 63 | unlink(filename); /* Delete any partial file */ |
| 64 | } |
| 65 | |
| 66 | fclose(f); |
| 67 | return 0; |
| 68 | } |