1 /* Copyright (c) 2023, 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
15 #include "file_util.h"
16
17 #include <stdlib.h>
18
19 #if defined(OPENSSL_WINDOWS)
20 OPENSSL_MSVC_PRAGMA(warning(push, 3))
21 #include <windows.h>
OPENSSL_MSVC_PRAGMA(warning (pop))22 OPENSSL_MSVC_PRAGMA(warning(pop))
23 #else
24 #include <fcntl.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 #endif
28
29 #include <openssl/rand.h>
30
31 #include "test_util.h"
32
33
34 #if defined(OPENSSL_WINDOWS)
35 static void PrintLastError(const char *s) {
36 DWORD error = GetLastError();
37 char *buffer;
38 DWORD len = FormatMessageA(
39 FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, 0, error, 0,
40 reinterpret_cast<char *>(&buffer), 0, nullptr);
41 std::string msg = "unknown error";
42 if (len > 0) {
43 msg.assign(buffer, len);
44 while (!msg.empty() && (msg.back() == '\r' || msg.back() == '\n')) {
45 msg.resize(msg.size() - 1);
46 }
47 }
48 LocalFree(buffer);
49 fprintf(stderr, "%s: %s (0x%lx)\n", s, msg.c_str(), error);
50 }
51 #endif // OPENSSL_WINDOWS
52
53 // GetTempDir returns the path to the temporary directory, or the empty string
54 // on error. On success, the result will include the directory separator.
GetTempDir()55 static std::string GetTempDir() {
56 #if defined(OPENSSL_WINDOWS)
57 char buf[MAX_PATH + 1];
58 DWORD len = GetTempPathA(sizeof(buf), buf);
59 return std::string(buf, len);
60 #else
61 const char *tmpdir = getenv("TMPDIR");
62 if (tmpdir != nullptr && *tmpdir != '\0') {
63 std::string ret = tmpdir;
64 if (ret.back() != '/') {
65 ret.push_back('/');
66 }
67 return ret;
68 }
69 #if defined(OPENSSL_ANDROID)
70 return "/data/local/tmp/";
71 #else
72 return "/tmp/";
73 #endif
74 #endif
75 }
76
SkipTempFileTests()77 bool SkipTempFileTests() {
78 #if defined(OPENSSL_ANDROID)
79 // When running in an APK context, /data/local/tmp is unreadable. Android
80 // versions before https://android-review.googlesource.com/c/1821337 do not
81 // set TMPDIR to a suitable replacement.
82 if (getenv("TMPDIR") == nullptr) {
83 static bool should_skip = [] {
84 TemporaryFile file;
85 return !file.Init();
86 }();
87 if (should_skip) {
88 fprintf(stderr, "Skipping tests with temporary files.\n");
89 return true;
90 }
91 }
92 #endif
93 return false;
94 }
95
~TemporaryFile()96 TemporaryFile::~TemporaryFile() {
97 #if defined(OPENSSL_WINDOWS)
98 if (!path_.empty() && !DeleteFileA(path_.c_str())) {
99 PrintLastError("Could not delete file");
100 }
101 #else
102 if (!path_.empty() && unlink(path_.c_str()) != 0) {
103 perror("Could not delete file");
104 }
105 #endif
106 }
107
Init(bssl::Span<const uint8_t> content)108 bool TemporaryFile::Init(bssl::Span<const uint8_t> content) {
109 std::string temp_dir = GetTempDir();
110 if (temp_dir.empty()) {
111 return false;
112 }
113
114 #if defined(OPENSSL_WINDOWS)
115 char path[MAX_PATH];
116 if (GetTempFileNameA(temp_dir.c_str(), "bssl",
117 /*uUnique=*/0, path) == 0) {
118 PrintLastError("Could not create temporary");
119 return false;
120 }
121 path_ = path;
122 #else
123 std::string path = temp_dir + "bssl_tmp_file.XXXXXX";
124 // TODO(davidben): Use |path.data()| when we require C++17.
125 int fd = mkstemp(&path[0]);
126 if (fd < 0) {
127 perror("Could not create temporary file");
128 return false;
129 }
130 close(fd);
131 path_ = std::move(path);
132 #endif
133
134 ScopedFILE file = Open("wb");
135 if (file == nullptr) {
136 perror("Could not open temporary file");
137 return false;
138 }
139 if (!content.empty() &&
140 fwrite(content.data(), content.size(), /*nitems=*/1, file.get()) != 1) {
141 perror("Could not write temporary file");
142 return false;
143 }
144 return true;
145 }
146
Open(const char * mode) const147 ScopedFILE TemporaryFile::Open(const char *mode) const {
148 if (path_.empty()) {
149 return nullptr;
150 }
151 return ScopedFILE(fopen(path_.c_str(), mode));
152 }
153
OpenFD(int flags) const154 ScopedFD TemporaryFile::OpenFD(int flags) const {
155 if (path_.empty()) {
156 return ScopedFD();
157 }
158 #if defined(OPENSSL_WINDOWS)
159 return ScopedFD(_open(path_.c_str(), flags));
160 #else
161 return ScopedFD(open(path_.c_str(), flags));
162 #endif
163 }
164
~TemporaryDirectory()165 TemporaryDirectory::~TemporaryDirectory() {
166 if (path_.empty()) {
167 return;
168 }
169
170 #if defined(OPENSSL_WINDOWS)
171 for (const auto &file : files_) {
172 if (!DeleteFileA(GetFilePath(file).c_str())) {
173 PrintLastError("Could not delete file");
174 }
175 }
176 if (!RemoveDirectoryA(path_.c_str())) {
177 PrintLastError("Could not delete directory");
178 }
179 #else
180 for (const auto &file : files_) {
181 if (unlink(GetFilePath(file).c_str()) != 0) {
182 perror("Could not delete file");
183 }
184 }
185 if (rmdir(path_.c_str()) != 0) {
186 perror("Could not delete directory");
187 }
188 #endif
189 }
190
Init()191 bool TemporaryDirectory::Init() {
192 std::string path = GetTempDir();
193 if (path.empty()) {
194 return false;
195 }
196
197 #if defined(OPENSSL_WINDOWS)
198 // For simplicity, just try the first candidate and assume the directory
199 // doesn't exist. 128 bits of cryptographically secure randomness is plenty.
200 uint8_t buf[16];
201 RAND_bytes(buf, sizeof(buf));
202 path += "bssl_tmp_dir." + EncodeHex(buf);
203 if (!CreateDirectoryA(path.c_str(), /*lpSecurityAttributes=*/nullptr)) {
204 perror("Could not make temporary directory");
205 return false;
206 }
207 #else
208 path += "bssl_tmp_dir.XXXXXX";
209 // TODO(davidben): Use |path.data()| when we require C++17.
210 if (mkdtemp(&path[0]) == nullptr) {
211 perror("Could not make temporary directory");
212 return false;
213 }
214 #endif
215
216 path_ = std::move(path);
217 return true;
218 }
219
AddFile(const std::string & filename,bssl::Span<const uint8_t> content)220 bool TemporaryDirectory::AddFile(const std::string &filename,
221 bssl::Span<const uint8_t> content) {
222 if (path_.empty()) {
223 return false;
224 }
225
226 ScopedFILE file(fopen(GetFilePath(filename).c_str(), "wb"));
227 if (file == nullptr) {
228 perror("Could not open temporary file");
229 return false;
230 }
231 if (!content.empty() &&
232 fwrite(content.data(), content.size(), /*nitems=*/1, file.get()) != 1) {
233 perror("Could not write temporary file");
234 return false;
235 }
236
237 files_.insert(filename);
238 return true;
239 }
240