-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTemporaryFileScope.cpp
315 lines (260 loc) · 12.3 KB
/
TemporaryFileScope.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#pragma region Apache License 2.0
/*
Nuclex Native Framework
Copyright (C) 2002-2024 Markus Ewald / Nuclex Development Labs
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma endregion // Apache License 2.0
// If the library is compiled as a DLL, this ensures symbols are exported
#define NUCLEX_SUPPORT_SOURCE 1
#include "Nuclex/Support/TemporaryFileScope.h"
#if defined(NUCLEX_SUPPORT_WINDOWS)
#include "Nuclex/Support/ScopeGuard.h" // Closing opened files even if exceptions happen
#include "Nuclex/Support/Text/StringConverter.h" // Conversion between UTF-8 and wide char
#include "./Platform/WindowsApi.h" // Minimalist Windows.h and error handling helpers
#include "./Platform/WindowsPathApi.h" // Basic path manipulation required to join directories
#include "./Platform/WindowsFileApi.h" // Opening files and reading/writing them
#elif defined(NUCLEX_SUPPORT_LINUX)
#include "./Platform/LinuxFileApi.h" // Opening files and reading/writing them
#endif
#if !defined(NUCLEX_SUPPORT_WINDOWS)
#include "./Platform/PosixApi.h" // Posix error handling
#include "./Platform/PosixPathApi.h" // Basic posix path manipulation for temp directory access
#include <unistd.h> // for ::write(), ::close(), ::unlink()
#include <cstdlib> // for ::getenv(), ::mkdtemp()
#endif
#include <vector> // for std::vector
#include <cassert> // for assert()
namespace {
// ------------------------------------------------------------------------------------------- //
#if !defined(NUCLEX_SUPPORT_WINDOWS)
/// <summary>Builds the full template string that's passed to ::mkstemp()</summary>
/// <param name="path">Path vector the template will be stored in</param>
/// <param name="prefix">Prefix for the temporary filename, can be empty</param>
void buildTemplateForMksTemp(std::string &path, const std::string &prefix) {
path.reserve(256); // PATH_MAX would be a bit too bloaty usually...
// Obtain the system's temporary directory (usually /tmp, can be overridden)
// path: "/tmp/"
{
Nuclex::Support::Platform::PosixPathApi::GetTemporaryDirectory(path);
std::string::size_type length = path.size();
if(path[length -1] != u8'/') {
path.push_back(u8'/');
}
}
// Append the user-specified prefix, if any
// path: "/tmp/myapp"
if(!prefix.empty()) {
path.append(prefix);
}
// Append the mandatory placeholder characters
// path: "/tmp/myappXXXXXX"
{
static const std::string placeholder(u8"XXXXXX", 6);
path.append(placeholder);
}
}
#endif // !defined(NUCLEX_SUPPORT_WINDOWS)
// ------------------------------------------------------------------------------------------- //
#if defined(NUCLEX_SUPPORT_LINUX)
/// <summary>Reads the contents of a file into an std::string or std::vector</summary>
/// <param name="fileDescriptor">File number of the open file that will be read</param>
/// <param name="container">Container into which the file's contents will be written</param>
template<typename TVectorOrString>
void readFileIntoContainer(int fileDescriptor, TVectorOrString &container) {
using Nuclex::Support::Platform::LinuxFileApi;
LinuxFileApi::Seek(fileDescriptor, ::off_t(0), SEEK_SET);
container.resize(4096);
for(std::size_t offset = 0;;) {
std::byte *data = reinterpret_cast<std::byte *>(container.data());
std::size_t readByteCount = LinuxFileApi::Read(
fileDescriptor, data + offset, 4096
);
if(readByteCount == 0) { // 0 bytes are only returned at the end of the file
container.resize(offset);
break;
} else { // 1 or more bytes returned, increase buffer for another round
offset += readByteCount;
container.resize(offset + 4096); // extend so that 4k bytes are vailable again
}
}
}
#endif // defined(NUCLEX_SUPPORT_LINUX)
// ------------------------------------------------------------------------------------------- //
#if defined(NUCLEX_SUPPORT_WINDOWS)
/// <summary>Reads the contents of a file into an std::string or std::vector</summary>
/// <param name="path">Path to the file that will be read}</param>
/// <param name="container">Container into which the file's contents will be written</param>
template<typename TVectorOrString>
void readFileIntoContainer(const std::string &path, TVectorOrString &container) {
using Nuclex::Support::Platform::WindowsFileApi;
HANDLE fileHandle = WindowsFileApi::OpenFileForReading(path);
ON_SCOPE_EXIT { WindowsFileApi::CloseFile(fileHandle); };
container.resize(4096);
for(std::size_t offset = 0;;) {
std::uint8_t *data = reinterpret_cast<std::uint8_t *>(container.data());
std::size_t readByteCount = WindowsFileApi::Read(fileHandle, data + offset, 4096);
offset += readByteCount;
if(readByteCount == 0) { // 0 bytes are only returned at the end of the file
container.resize(offset);
break;
} else { // 1 or more bytes returned, increase buffer for another round
container.resize(offset + 4096); // extend so that 4k bytes are vailable again
}
}
}
#endif // defined(NUCLEX_SUPPORT_WINDOWS)
// ------------------------------------------------------------------------------------------- //
} // anonymous namespace
namespace Nuclex { namespace Support {
// ------------------------------------------------------------------------------------------- //
TemporaryFileScope::TemporaryFileScope(const std::string &namePrefix /* = u8"tmp" */) :
path(),
privateImplementationData {0} {
#if defined(NUCLEX_SUPPORT_WINDOWS)
static_assert(
(sizeof(this->privateImplementationData) >= sizeof(HANDLE)),
u8"File handle must fit in the space provided for private implementation data"
);
*reinterpret_cast<HANDLE *>(this->privateImplementationData) = INVALID_HANDLE_VALUE;
std::wstring fullPath = Platform::WindowsPathApi::CreateTemporaryFile(namePrefix);
HANDLE fileHandle = ::CreateFileW(
fullPath.c_str(),
GENERIC_READ | GENERIC_WRITE, // desired access
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, // share mode
nullptr,
CREATE_ALWAYS, // creation disposition
FILE_ATTRIBUTE_NORMAL,
nullptr
);
if(unlikely(fileHandle == INVALID_HANDLE_VALUE)) {
DWORD errorCode = ::GetLastError();
// Something went wrong, kill the temporary file again before throwing the exception
BOOL result = ::DeleteFileW(fullPath.c_str());
NUCLEX_SUPPORT_NDEBUG_UNUSED(result);
assert((result != FALSE) && u8"Temporary file is successfully deleted in error handler");
std::string errorMessage(u8"Could not open temporary file '");
errorMessage.append(Text::StringConverter::Utf8FromWide(fullPath));
errorMessage.append(u8"' for writing");
Platform::WindowsApi::ThrowExceptionForFileSystemError(errorMessage, errorCode);
}
// If we don't close the file, it cannot be accessed unless other code opens
// it with FILE_SHARE_READ | FILE_SHARE_WRITE (the latter is the problem)
::CloseHandle(fileHandle);
this->path = Text::StringConverter::Utf8FromWide(fullPath);
#else
static_assert(
(sizeof(this->privateImplementationData) >= sizeof(int)),
u8"File descriptor must fit in space provided for private implementation data"
);
// Build the path template including the system's temporary directory
std::string pathTemplate;
buildTemplateForMksTemp(pathTemplate, namePrefix);
// Select and open a unique temporary filename
int fileDescriptor = ::mkstemp(pathTemplate.data());
if(unlikely(fileDescriptor == -1)) {
int errorNumber = errno;
std::string errorMessage(u8"Could not create temporary file '");
errorMessage.append(pathTemplate);
errorMessage.append(u8"'");
Platform::PosixApi::ThrowExceptionForFileAccessError(errorMessage, errorNumber);
}
// Store the file handle in the private implementation data block and
// remember the full path for when the user queries it later
*reinterpret_cast<int *>(this->privateImplementationData) = fileDescriptor;
this->path.assign(pathTemplate);
#endif
}
// ------------------------------------------------------------------------------------------- //
TemporaryFileScope::~TemporaryFileScope() {
#if defined(NUCLEX_SUPPORT_WINDOWS)
if(likely(!this->path.empty())) {
std::wstring utf16Path = Text::StringConverter::WideFromUtf8(this->path);
BOOL result = ::DeleteFileW(utf16Path.c_str());
NUCLEX_SUPPORT_NDEBUG_UNUSED(result);
assert((result != FALSE) && u8"Temporary file is successfully deleted after use");
}
#elif defined(NUCLEX_SUPPORT_LINUX)
int fileDescriptor = *reinterpret_cast<int *>(this->privateImplementationData);
// Close the file so we don't leak handles
if(likely(fileDescriptor != 0)) {
int result = ::close(fileDescriptor);
NUCLEX_SUPPORT_NDEBUG_UNUSED(result);
assert((result != -1) && u8"Temporary file is closed successfully");
}
// Delete the file. Even if the close failed, on Linux systems we
// can delete the file and it will be removed from the file index
// (and the data will disppear as soon as the last process closes it).
if(likely(!this->path.empty())) {
int result = ::unlink(this->path.c_str());
NUCLEX_SUPPORT_NDEBUG_UNUSED(result);
assert((result != -1) && u8"Temporary file is deleted successfully");
}
#endif
}
// ------------------------------------------------------------------------------------------- //
std::string TemporaryFileScope::GetFileContentsAsString() const {
std::string contents;
#if defined(NUCLEX_SUPPORT_LINUX)
{
int fileDescriptor = *reinterpret_cast<const int *>(this->privateImplementationData);
assert((fileDescriptor != 0) && u8"File is opened and accessible");
readFileIntoContainer(fileDescriptor, contents);
}
#elif defined(NUCLEX_SUPPORT_WINDOWS)
{
readFileIntoContainer(this->path, contents);
}
#endif
return contents;
}
// ------------------------------------------------------------------------------------------- //
std::vector<std::byte> TemporaryFileScope::GetFileContentsAsVector() const {
std::vector<std::byte> contents;
#if defined(NUCLEX_SUPPORT_LINUX)
{
int fileDescriptor = *reinterpret_cast<const int *>(this->privateImplementationData);
assert((fileDescriptor != 0) && u8"File is opened and accessible");
readFileIntoContainer(fileDescriptor, contents);
}
#elif defined(NUCLEX_SUPPORT_WINDOWS)
{
readFileIntoContainer(this->path, contents);
}
#endif
return contents;
}
// ------------------------------------------------------------------------------------------- //
void TemporaryFileScope::SetFileContents(
const std::byte *contents, std::size_t byteCount
) {
#if defined(NUCLEX_SUPPORT_WINDOWS)
::HANDLE fileHandle = Platform::WindowsFileApi::OpenFileForWriting(this->path);
ON_SCOPE_EXIT {
BOOL result = ::CloseHandle(fileHandle);
NUCLEX_SUPPORT_NDEBUG_UNUSED(result);
assert((result != FALSE) && u8"File handle is closed successfully");
};
Platform::WindowsFileApi::Seek(fileHandle, 0, FILE_BEGIN);
Platform::WindowsFileApi::Write(fileHandle, contents, byteCount);
Platform::WindowsFileApi::SetLengthToFileCursor(fileHandle);
Platform::WindowsFileApi::FlushFileBuffers(fileHandle);
#elif defined(NUCLEX_SUPPORT_LINUX)
int fileDescriptor = *reinterpret_cast<int *>(this->privateImplementationData);
assert((fileDescriptor != 0) && u8"File is opened and accessible");
Platform::LinuxFileApi::Seek(fileDescriptor, ::off_t(0), SEEK_SET);
Platform::LinuxFileApi::Write(fileDescriptor, contents, byteCount);
Platform::LinuxFileApi::SetLength(fileDescriptor, byteCount);
Platform::LinuxFileApi::Flush(fileDescriptor);
#endif
}
// ------------------------------------------------------------------------------------------- //
}} // namespace Nuclex::Support