Debian Codegraph @

io/nativefilestream.cpp

raw symbols SCIP
1 #include "./nativefilestream.h"
2
3 #ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER
4
5 /*!
6 * \class
7 * So one gets e.g. "open failed: Permission denied" instead of
8 just "open failed: iostream error".
9 */
10
11 /*!
12 * \class NativeFileStream
13 * \brief Provides a standard IO stream instantiated using native APIs.
14 *
15 * Using this class instead of `std::fstream` has the following benefits:
16 * - Under Windows, the specified file path is interpreted as UTF-8 and passed to Windows' unicode API
17 * to support any kind of non-ASCII characters in file paths.
18 * - It is possible to open a file from a native file descriptor. This is for instance useful when dealing with
19 * Android's `content://` URLs.
20 * - Better error messages at least when opening a file, e.g. "Permission denied" instead of just "basic_ios::clear".
21 */
22
23 #ifdef PLATFORM_WINDOWS
24 #include "../conversion/stringconversion.h"
25 #endif
26
27 // include header files for file buffer implementation
28 #if defined(CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF)
29 #include <ext/stdio_filebuf.h>
30 #elif defined(CPP_UTILITIES_USE_BOOST_IOSTREAMS)
31 #include <boost/iostreams/device/file_descriptor.hpp>
32 #include <boost/iostreams/stream.hpp>
33 #else
34 #error "Configuration for NativeFileStream backend insufficient."
35 #endif
36
37 // include platform specific header
38 #if defined(PLATFORM_UNIX)
39 #include <fcntl.h>
40 #include <sys/stat.h>
41 #include <sys/types.h>
42 #elif defined(PLATFORM_WINDOWS)
43 #include <fcntl.h>
44 #include <io.h>
45 #include <limits>
46 #include <sys/stat.h> // yes, this is needed under Windows (https://msdn.microsoft.com/en-US/library/5yhhz3y7.aspx)
47 #include <windows.h>
48 #ifdef max
49 #undef max // see explanation in stringconversion.cpp
50 #endif
51 #endif
52
53 #endif
54
55 using namespace std;
56
57 namespace CppUtilities {
58
59 #ifdef CPP_UTILITIES_USE_NATIVE_FILE_BUFFER
60
61 #ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
62 using StreamBuffer = __gnu_cxx::stdio_filebuf<char>;
63 #else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
64 using StreamBuffer = boost::iostreams::stream_buffer<boost::iostreams::file_descriptor>;
65 #endif
66
67 struct NativeFileParams {
68
69 #ifdef PLATFORM_WINDOWS
70 NativeFileParams(ios_base::openmode cppOpenMode)
71 : openMode(cppOpenMode & ios_base::binary ? _O_BINARY : 0)
72 , flags(cppOpenMode & ios_base::binary ? 0 : _O_TEXT)
73 , permissions(0)
74 , access(0)
75 , shareMode(0)
76 , creation(0)
77 {
78 if ((cppOpenMode & ios_base::out) && (cppOpenMode & ios_base::in)) {
79 openMode |= _O_RDWR;
80 access = GENERIC_READ | GENERIC_WRITE;
81 shareMode = FILE_SHARE_READ;
82 creation = OPEN_EXISTING;
83 } else if (cppOpenMode & ios_base::out) {
84 openMode |= _O_WRONLY | _O_CREAT;
85 permissions = _S_IREAD | _S_IWRITE;
86 access = GENERIC_WRITE;
87 creation = OPEN_ALWAYS;
88 } else if (cppOpenMode & ios_base::in) {
89 openMode |= _O_RDONLY;
90 flags |= _O_RDONLY;
91 access = GENERIC_READ;
92 shareMode = FILE_SHARE_READ;
93 creation = OPEN_EXISTING;
94 }
95 if (cppOpenMode & ios_base::app) {
96 openMode |= _O_APPEND;
97 flags |= _O_APPEND;
98 }
99 if (cppOpenMode & ios_base::trunc) {
100 openMode |= _O_TRUNC;
101 creation = (cppOpenMode & ios_base::in) ? TRUNCATE_EXISTING : CREATE_ALWAYS;
102 }
103 }
104
105 int openMode;
106 int flags;
107 int permissions;
108 DWORD access;
109 DWORD shareMode;
110 DWORD creation;
111 #else
112 NativeFileParams(ios_base::openmode cppOpenMode)
113 : openFlags(0)
114 {
115 if ((cppOpenMode & ios_base::in) && (cppOpenMode & ios_base::out)) {
116 if (cppOpenMode & ios_base::app) {
117 openMode = "a+";
118 openFlags = O_RDWR | O_APPEND;
119 } else if (cppOpenMode & ios_base::trunc) {
120 openMode = "w+";
121 openFlags = O_RDWR | O_TRUNC;
122 } else {
123 openMode = "r+";
124 openFlags = O_RDWR;
125 }
126 } else if (cppOpenMode & ios_base::in) {
127 openMode = 'r';
128 openFlags = O_RDONLY;
129 } else if (cppOpenMode & ios_base::out) {
130 if (cppOpenMode & ios_base::app) {
131 openMode = 'a';
132 openFlags = O_WRONLY | O_APPEND;
133 } else if (cppOpenMode & ios_base::trunc) {
134 openMode = 'w';
135 openFlags = O_WRONLY | O_TRUNC | O_CREAT;
136 } else {
137 openMode = "w";
138 openFlags = O_WRONLY | O_CREAT;
139 }
140 }
141 if (cppOpenMode & ios_base::binary) {
142 openMode += 'b';
143 }
144 }
145
146 std::string openMode;
147 int openFlags;
148 #endif
149 };
150
151 /*!
152 * \class NativeFileStream::FileBuffer
153 * \brief The NativeFileStream::FileBuffer class holds an std::basic_streambuf<char> object obtained from a file path or a native file descriptor.
154 */
155
156 /*!
157 * \brief Constructs a new FileBuffer object taking ownership of \a buffer.
158 */
159 NativeFileStream::FileBuffer::FileBuffer(std::basic_streambuf<char> *buffer)
160 : buffer(buffer)
161 {
162 }
163
164 /*!
165 * \brief Opens a file buffer from the specified \a path.
166 * \remarks See NativeFileStream::open() for remarks on how \a path must be encoded.
167 */
168 NativeFileStream::FileBuffer::FileBuffer(const char *path, ios_base::openmode openMode)
169 {
170 #ifdef PLATFORM_WINDOWS
171 // convert path to UTF-16
172 const auto widePath(makeWidePath(path));
173 #endif
174
175 // compute native params
176 const NativeFileParams nativeParams(openMode);
177
178 // open native file handle or descriptor
179 #ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
180 #ifdef PLATFORM_WINDOWS
181 descriptor = _wopen(widePath.get(), nativeParams.openMode, nativeParams.permissions);
182 if (descriptor == -1) {
183 throw std::ios_base::failure("_wopen failed", std::error_code(errno, std::system_category()));
184 }
185 #else
186 descriptor = ::open(path, nativeParams.openFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
187 if (descriptor == -1) {
188 throw std::ios_base::failure("open failed", std::error_code(errno, std::system_category()));
189 }
190 #endif
191 buffer = make_unique<StreamBuffer>(descriptor, openMode);
192 #else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
193 #ifdef PLATFORM_WINDOWS
194 handle = CreateFileW(widePath.get(), nativeParams.access, nativeParams.shareMode, nullptr, nativeParams.creation, FILE_ATTRIBUTE_NORMAL, nullptr);
195 if (handle == INVALID_HANDLE_VALUE) {
196 throw std::ios_base::failure("CreateFileW failed", std::error_code(static_cast<int>(GetLastError()), std::system_category()));
197 }
198 buffer = std::make_unique<StreamBuffer>(handle, boost::iostreams::close_handle);
199 // if we wanted to open assign the descriptor as well: descriptor = _open_osfhandle(reinterpret_cast<std::intptr_t>(handle), nativeParams.flags);
200 #else
201 descriptor = ::open(path, nativeParams.openFlags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
202 if (descriptor == -1) {
203 throw std::ios_base::failure("open failed", std::error_code(errno, std::system_category()));
204 }
205 buffer = make_unique<StreamBuffer>(descriptor, boost::iostreams::close_handle);
206 #endif
207 #endif
208 }
209
210 /*!
211 * \brief Opens a file buffer from the specified \a path.
212 * \remarks See NativeFileStream::open() for remarks on how \a path must be encoded.
213 */
214 NativeFileStream::FileBuffer::FileBuffer(const std::string &path, ios_base::openmode openMode)
215 : NativeFileStream::FileBuffer(path.data(), openMode)
216 {
217 }
218
219 /*!
220 * \brief Opens a file buffer from the specified \a fileDescriptor.
221 * \remarks
222 * The specified \a openMode is only used when using __gnu_cxx::stdio_filebuf<char> and must be in accordance with how \a fileDescriptor
223 * has been opened.
224 */
225 NativeFileStream::FileBuffer::FileBuffer(int fileDescriptor, ios_base::openmode openMode)
226 : descriptor(fileDescriptor)
227 {
228 #ifdef CPP_UTILITIES_USE_GNU_CXX_STDIO_FILEBUF
229 buffer = make_unique<StreamBuffer>(descriptor, openMode);
230 #else // CPP_UTILITIES_USE_BOOST_IOSTREAMS
231 CPP_UTILITIES_UNUSED(openMode)
232 #ifdef PLATFORM_WINDOWS
233 handle = reinterpret_cast<Handle>(_get_osfhandle(descriptor));
234 buffer = make_unique<StreamBuffer>(handle, boost::iostreams::close_handle);
235 #else
236 buffer = make_unique<StreamBuffer>(descriptor, boost::iostreams::close_handle);
237 #endif
238 #endif
239 }
240
241 /*!
242 * \brief Constructs a new NativeFileStream which is initially closed.
243 */
244 NativeFileStream::NativeFileStream()
245 : iostream(new StreamBuffer)
246 , m_data(rdbuf())
247 {
248 }
249
250 /*!
251 * \brief Moves the NativeFileStream.
252 */
253 NativeFileStream::NativeFileStream(NativeFileStream &&other)
254 : iostream(other.m_data.buffer.release())
255 , m_data(rdbuf())
256 {
257 #ifdef PLATFORM_WINDOWS
258 m_data.handle = other.m_data.handle;
259 #endif
260 m_data.descriptor = other.m_data.descriptor;
261 }
262
263 /*!
264 * \brief Destroys the NativeFileStream releasing all underlying resources.
265 */
266 NativeFileStream::~NativeFileStream()
267 {
268 }
269
270 /*!
271 * \brief Returns whether the file is open.
272 */
273 bool NativeFileStream::isOpen() const
274 {
275 return m_data.buffer && static_cast<const StreamBuffer *>(m_data.buffer.get())->is_open();
276 }
277
278 /*!
279 * \brief Opens the file referenced by \a path with the specified \a openMode.
280 * \remarks
281 * - Under Windows \a path is expected to be UTF-8 encoded. It is automatically converted so non-ASCII
282 * characters are treated correctly under Windows (in contrast to std::fstream::open() where only the
283 * current code page is supported).
284 * - Under other platforms the \a path is just passed through so there are no assumptions made about its
285 * encoding.
286 * \todo Maybe use setstate() instead of throwing exceptions directly for consistent error handling
287 * with std::fstream::open(). However, that makes passing specific error messages difficult.
288 */
289 void NativeFileStream::open(const char *path, ios_base::openmode openMode)
290 {
291 setData(FileBuffer(path, openMode), openMode);
292 }
293
294 /*!
295 * \brief Opens the file referenced by \a path with the specified \a openMode.
296 */
297 void NativeFileStream::open(const std::string &path, ios_base::openmode openMode)
298 {
299 open(path.data(), openMode);
300 }
301
302 /*!
303 * \brief Opens the file from the specified \a fileDescriptor with the specified \a openMode.
304 * \throws Throws std::ios_base::failure in the error case.
305 * \todo
306 * - Maybe use setstate() instead of throwing exceptions directly for consistent error handling
307 * with std::fstream::open(). However, that makes passing specific error messages difficult.
308 */
309 void NativeFileStream::open(int fileDescriptor, ios_base::openmode openMode)
310 {
311 setData(FileBuffer(fileDescriptor, openMode), openMode);
312 }
313
314 /*!
315 * \brief Closes the file if opened; otherwise does nothing.
316 */
317 void NativeFileStream::close()
318 {
319 if (m_data.buffer) {
320 static_cast<StreamBuffer *>(m_data.buffer.get())->close();
321 #ifdef PLATFORM_WINDOWS
322 m_data.handle = nullptr;
323 #endif
324 m_data.descriptor = -1;
325 }
326 }
327
328 /*!
329 * \brief Internally called to assign the buffer, file descriptor and handle.
330 */
331 void NativeFileStream::setData(FileBuffer data, std::ios_base::openmode openMode)
332 {
333 rdbuf(data.buffer.get());
334 m_data = std::move(data);
335 m_openMode = openMode;
336 #if defined(PLATFORM_WINDOWS) && defined(CPP_UTILITIES_USE_BOOST_IOSTREAMS)
337 // workaround append flag dysfunctioning
338 if (m_openMode & ios_base::app) {
339 seekp(0, ios_base::end);
340 }
341 #endif
342 }
343
344 #ifdef PLATFORM_WINDOWS
345 /*!
346 * \brief Converts the specified UTF-8 encoded \a path to UTF-16 for passing it to WinAPI functions.
347 * \throws Throws std::ios_base::failure when an encoding error occurs.
348 */
349 std::unique_ptr<wchar_t[]> NativeFileStream::makeWidePath(std::string_view path)
350 {
351 auto ec = std::error_code();
352 auto size = path.size() < static_cast<std::size_t>(std::numeric_limits<int>::max() - 1) ? static_cast<int>(path.size() + 1) : -1;
353 auto widePath = ::CppUtilities::convertMultiByteToWide(ec, path.data(), size);
354 if (!widePath.first) {
355 throw std::ios_base::failure("converting path to UTF-16", ec);
356 }
357 return std::move(widePath.first);
358 }
359
360 /*!
361 * \brief Converts the specified UTF-8 encoded \a path to UTF-16 for passing it to WinAPI functions.
362 * \throws Throws std::ios_base::failure when an encoding error occurs.
363 */
364 std::unique_ptr<wchar_t[]> NativeFileStream::makeWidePath(const std::string &path)
365 {
366 return makeWidePath(std::string_view(path));
367 }
368 #endif
369
370 #else
371
372 // std::fstream is used
373
374 #endif
375 } // namespace CppUtilities