| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 |
| 15 | #include <openssl/bytestring.h> |
| 16 |
| 17 | #include <errno.h> |
| 18 | #include <stdio.h> |
| 19 | #include <string.h> |
| 20 |
| 21 | #include <algorithm> |
| 22 | #include <vector> |
| 23 |
| 24 | #include "internal.h" |
| 25 |
| 26 |
| 27 | bool ReadAll(std::vector<uint8_t> *out, FILE *file) { |
| 28 | out->clear(); |
| 29 |
| 30 | constexpr size_t kMaxSize = 1024 * 1024; |
| 31 | size_t len = 0; |
| 32 | out->resize(128); |
| 33 |
| 34 | for (;;) { |
| 35 | len += fread(out->data() + len, 1, out->size() - len, file); |
| 36 |
| 37 | if (feof(file)) { |
| 38 | out->resize(len); |
| 39 | return true; |
| 40 | } |
| 41 | if (ferror(file)) { |
| 42 | return false; |
| 43 | } |
| 44 |
| 45 | if (len == out->size()) { |
| 46 | if (out->size() == kMaxSize) { |
| 47 | fprintf(stderr, "Input too large.\n"); |
| 48 | return false; |
| 49 | } |
| 50 | size_t cap = std::min(out->size() * 2, kMaxSize); |
| 51 | out->resize(cap); |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 |
| 56 | bool WriteToFile(const std::string &path, bssl::Span<const uint8_t> in) { |
| 57 | ScopedFILE file(fopen(path.c_str(), "wb")); |
| 58 | if (!file) { |
| 59 | fprintf(stderr, "Failed to open '%s': %s\n", path.c_str(), strerror(errno)); |
| 60 | return false; |
| 61 | } |
| 62 | if (fwrite(in.data(), in.size(), 1, file.get()) != 1) { |
| 63 | fprintf(stderr, "Failed to write to '%s': %s\n", path.c_str(), |
| 64 | strerror(errno)); |
| 65 | return false; |
| 66 | } |
| 67 | return true; |
| 68 | } |
| 69 |