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.
35 // This API is NOT thread-safe and requires proper synchronization when used by
36 // multiple threads, especially when they can happen to be reading from the same
37 // file.
LoadFile(const std::string & filename,bool add_null_terminator)38 absl::StatusOr<Slice> LoadFile(const std::string& filename,
39 bool add_null_terminator) {
40 unsigned char* contents = nullptr;
41 size_t contents_size = 0;
42 FILE* file;
43 size_t bytes_read = 0;
44 absl::Status error = absl::OkStatus();
45 auto sock_cleanup = absl::MakeCleanup([&file]() -> void {
46 if (file != nullptr) {
47 fclose(file);
48 }
49 });
50
51 file = fopen(filename.c_str(), "rb");
52 if (file == nullptr) {
53 error = absl::InternalError(
54 absl::StrCat("Failed to load file: ", filename,
55 " due to error(fdopen): ", strerror(errno)));
56 return error;
57 }
58 fseek(file, 0, SEEK_END);
59 // Converting to size_t on the assumption that it will not fail.
60 contents_size = static_cast<size_t>(ftell(file));
61 fseek(file, 0, SEEK_SET);
62 contents = static_cast<unsigned char*>(
63 gpr_malloc(contents_size + (add_null_terminator ? 1 : 0)));
64 bytes_read = fread(contents, 1, contents_size, file);
65 if (bytes_read < contents_size) {
66 gpr_free(contents);
67 error = absl::InternalError(
68 absl::StrCat("Failed to load file: ", filename,
69 " due to error(fread): ", strerror(errno)));
70 return error;
71 }
72 if (add_null_terminator) {
73 contents[contents_size++] = 0;
74 }
75 return Slice(grpc_slice_new(contents, contents_size, gpr_free));
76 }
77
78 } // namespace grpc_core
79