blob: 8d74e635bcb40ad9323e0a565827293d78eee3de [file] [log] [blame]
David Benjamin4e78e302017-03-30 10:16:07 -05001/* Copyright (c) 2017, Google Inc.
2 *
3 * Permission to use, copy, modify, and/or distribute this software for any
4 * purpose with or without fee is hereby granted, provided that the above
5 * copyright notice and this permission notice appear in all copies.
6 *
7 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14
Dan McArdle7a817f42021-07-14 17:19:16 -040015#include <openssl/bytestring.h>
16
17#include <errno.h>
David Benjamin4e78e302017-03-30 10:16:07 -050018#include <stdio.h>
Dan McArdle7a817f42021-07-14 17:19:16 -040019#include <string.h>
David Benjamin4e78e302017-03-30 10:16:07 -050020
21#include <algorithm>
22#include <vector>
23
24#include "internal.h"
25
26
27bool 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}
Dan McArdle7a817f42021-07-14 17:19:16 -040055
56bool 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}