1 // Copyright 2022 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://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 <grpc/support/port_platform.h>
16
17 #include "src/core/lib/gprpp/load_file.h"
18
19 #include <errno.h>
20 #include <stdio.h>
21 #include <string.h>
22
23 #include "absl/cleanup/cleanup.h"
24 #include "absl/status/status.h"
25 #include "absl/strings/str_cat.h"
26
27 #include <grpc/slice.h>
28 #include <grpc/support/alloc.h>
29 #include <grpc/support/log.h>
30
31 namespace grpc_core {
32
33 // Loads the content of a file into a slice. add_null_terminator will add a NULL
34 // terminator if true.
LoadFile(std::string filename,bool add_null_terminator)35 absl::StatusOr<Slice> LoadFile(std::string filename, bool add_null_terminator) {
36 unsigned char* contents = nullptr;
37 size_t contents_size = 0;
38 FILE* file;
39 size_t bytes_read = 0;
40 absl::Status error = absl::OkStatus();
41 auto sock_cleanup = absl::MakeCleanup([&file]() -> void {
42 if (file != nullptr) {
43 fclose(file);
44 }
45 });
46
47 file = fopen(filename.c_str(), "rb");
48 if (file == nullptr) {
49 error = absl::InternalError(
50 absl::StrCat("Failed to load file: ", filename,
51 " due to error(fdopen): ", strerror(errno)));
52 return error;
53 }
54 fseek(file, 0, SEEK_END);
55 // Converting to size_t on the assumption that it will not fail.
56 contents_size = static_cast<size_t>(ftell(file));
57 fseek(file, 0, SEEK_SET);
58 contents = static_cast<unsigned char*>(
59 gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
60 bytes_read = fread(contents, 1, contents_size, file);
61 if (bytes_read < contents_size) {
62 gpr_free(contents);
63 GPR_ASSERT(ferror(file));
64 error = absl::InternalError(
65 absl::StrCat("Failed to load file: ", filename,
66 " due to error(fread): ", strerror(errno)));
67 return error;
68 }
69 if (add_null_terminator) {
70 contents[contents_size++] = 0;
71 }
72 return Slice(grpc_slice_new(contents, contents_size, gpr_free));
73 }
74
75 } // namespace grpc_core
76