Files
repertory/support/src/utils/file_file.cpp
2024-08-20 08:48:29 -05:00

479 lines
12 KiB
C++

/*
Copyright <2018-2024> <scott.e.graves@protonmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "utils/file.hpp"
#include "utils/encryption.hpp"
#include "utils/error.hpp"
#include "utils/path.hpp"
#include "utils/string.hpp"
#include "utils/time.hpp"
namespace repertory::utils::file {
// auto file::attach_file(native_handle handle,
// bool read_only) -> fs_file_t {
// static constexpr const std::string_view function_name{
// static_cast<const char *>(__FUNCTION__),
// };
//
// try {
// std::string path;
//
// #if defined(_WIN32)
// path.resize(repertory::max_path_length + 1);
// ::GetFinalPathNameByHandleA(handle, path.data(),
// static_cast<DWORD>(path.size()),
// FILE_NAME_NORMALIZED | VOLUME_NAME_DOS);
// #else // !defined(_WIN32)
// path.resize(repertory::max_path_length + 1);
//
// #if defined(__APPLE__)
// fcntl(handle, F_GETPATH, source_path.data());
// #else // !defined(__APPLE__)
// readlink(("/proc/self/fd/" + std::to_string(handle)).c_str(),
// path.data(),
// path.size());
// #endif // defined(__APPLE__)
// #endif // defined(_WIN32)
//
// path = path.c_str();
//
// #if defined(_WIN32)
// auto *ptr = _fdopen(
// static_cast<int>(_open_osfhandle(reinterpret_cast<intptr_t>(handle),
// read_only ? _O_RDONLY : _O_RDWR)),
// read_only ? "rb" : "rb+");
// #else // !defined(_WIN32)
// auto *ptr = fdopen(handle, read_only ? "rb" : "rb+");
// #endif // defined(_WIN32)
//
// return fs_file_t(new file{
// file_t{ptr},
// utils::path::absolute(path),
// read_only,
// });
// } catch (const std::exception &e) {
// utils::error::handle_exception(function_name, e);
// } catch (...) {
// utils::error::handle_exception(function_name);
// }
//
// return nullptr;
// }
void file::open() {
if (not is_file(path_)) {
throw std::runtime_error("file not found: " + path_);
}
#if defined(_WIN32)
file_.reset(_fsopen(path_.c_str(), read_only_ ? "rb" : "rb+", _SH_DENYNO));
#else // !defined(_WIN32)
file_.reset(fopen(path_.c_str(), read_only_ ? "rb" : "rb+"));
#endif // defined(_WIN32)
}
auto file::open_file(std::string_view path, bool read_only) -> fs_file_t {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
auto *ptr = new file{
nullptr,
utils::path::absolute(path),
read_only,
};
auto new_file = fs_file_t(ptr);
try {
ptr->open();
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
return new_file;
}
auto file::open_or_create_file(std::string_view path,
bool read_only) -> fs_file_t {
auto abs_path = utils::path::absolute(path);
if (not is_file(abs_path)) {
#if defined(_WIN32)
int old_mode{};
_umask_s(077, &old_mode);
#else // !defined(_WIN32)
auto old_mode = umask(077);
#endif // defined(_WIN32)
#if defined(_WIN32)
auto *ptr = _fsopen(abs_path.c_str(), "ab+", _SH_DENYNO);
#else // !defined(_WIN32)
auto *ptr = fopen(abs_path.c_str(), "ab+");
#endif // defined(_WIN32)
if (ptr != nullptr) {
fclose(ptr);
}
#if defined(_WIN32)
_umask_s(old_mode, nullptr);
#else // !defined(_WIN32)
umask(old_mode);
#endif // defined(_WIN32)
}
return open_file(abs_path, read_only);
}
void file::close() {
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
file_.reset();
}
auto file::exists() const -> bool {
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
return is_file(path_);
}
void file::flush() const {
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
if (file_) {
fflush(file_.get());
}
}
auto file::get_handle() const -> native_handle {
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
if (file_) {
#if defined(_WIN32)
return reinterpret_cast<native_handle>(
_get_osfhandle(_fileno(file_.get())));
#else // !defined(_WIN32)
return fileno(file_.get());
#endif // defined(_WIN32)
}
return INVALID_HANDLE_VALUE;
}
auto file::get_time(time_types type) const -> std::uint64_t {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
try {
#if defined(_WIN32)
#else // !defined(_WIN32)
struct stat st {};
stat(path_.c_str(), &st);
#endif // defined(_WIN32)
switch (type) {
case time_types::access:
#if defined(_WIN32)
break;
#else // !defined(_WIN32)
return static_cast<std::uint64_t>(st.st_atim.tv_nsec +
st.st_atim.tv_sec *
utils::time::NANOS_PER_SECOND);
#endif // defined(_WIN32)
case time_types::creation:
#if defined(_WIN32)
break;
#else // !defined(_WIN32)
return static_cast<std::uint64_t>(st.st_ctim.tv_nsec +
st.st_ctim.tv_sec *
utils::time::NANOS_PER_SECOND);
#endif // defined(_WIN32)
case time_types::modified:
#if defined(_WIN32)
break;
#else // !defined(_WIN32)
return static_cast<std::uint64_t>(st.st_mtim.tv_nsec +
st.st_mtim.tv_sec *
utils::time::NANOS_PER_SECOND);
#endif // defined(_WIN32)
case time_types::write:
#if defined(_WIN32)
break;
#else // !defined(_WIN32)
return static_cast<std::uint64_t>(st.st_mtim.tv_nsec +
st.st_mtim.tv_sec *
utils::time::NANOS_PER_SECOND);
#endif // defined(_WIN32)
}
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
return false;
}
auto file::move_to(std::string_view path) -> bool {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
auto abs_path = utils::path::absolute(path);
auto reopen{false};
if (file_) {
reopen = true;
close();
}
auto success{false};
#if defined(_WIN32)
success = !!::MoveFileExA(path_.c_str(), abs_path.c_str(),
MOVEFILE_REPLACE_EXISTING);
#else // !// defined(_WIN32)
std::error_code ec{};
std::filesystem::rename(path_, abs_path, ec);
success = ec.value() == 0;
#endif // defined(_WIN32)
if (success) {
path_ = abs_path;
}
if (reopen) {
try {
open();
return success;
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
}
return false;
}
auto file::read(unsigned char *data, std::size_t to_read, std::uint64_t offset,
std::size_t *total_read) -> bool {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
if (total_read != nullptr) {
(*total_read) = 0U;
}
try {
if (not file_) {
throw std::runtime_error("file is not open for reading");
}
auto res = fseeko(file_.get(), static_cast<std::int64_t>(offset), SEEK_SET);
if (res == -1) {
throw std::runtime_error("failed to seek before read");
}
auto bytes_read = fread(data, 1U, to_read, file_.get());
if (not feof(file_.get()) && ferror(file_.get())) {
throw std::runtime_error("failed to read file bytes");
}
if (total_read != nullptr) {
(*total_read) = bytes_read;
}
return true;
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
return false;
}
auto file::remove() -> bool {
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
close();
if (not exists()) {
return true;
}
#if defined(_WIN32)
return !!::DeleteFileA(path_.c_str());
#else // !defined(_WIN32)
std::error_code ec{};
return std::filesystem::remove(path_, ec);
#endif // defined(_WIN32)
}
auto file::truncate(std::size_t size) -> bool {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
auto reopen{false};
if (file_) {
reopen = true;
close();
}
std::error_code ec{};
std::filesystem::resize_file(path_, size, ec);
auto success{ec.value() == 0};
if (reopen) {
try {
open();
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
success = false;
} catch (...) {
utils::error::handle_exception(function_name);
success = false;
}
}
return success;
}
auto file::write(const unsigned char *data, std::size_t to_write,
std::size_t offset, std::size_t *total_written) -> bool {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
if (total_written != nullptr) {
(*total_written) = 0U;
}
try {
if (not file_) {
throw std::runtime_error("file is not open for writing");
}
auto res = fseeko(file_.get(), static_cast<std::int64_t>(offset), SEEK_SET);
if (res == -1) {
throw std::runtime_error("failed to seek before write");
}
auto bytes_written =
fwrite(reinterpret_cast<const char *>(data), 1U, to_write, file_.get());
if (not feof(file_.get()) && ferror(file_.get())) {
throw std::runtime_error("failed to write file bytes");
}
flush();
if (total_written != nullptr) {
(*total_written) = bytes_written;
}
return true;
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
return false;
}
auto file::size() const -> std::uint64_t {
static constexpr const std::string_view function_name{
static_cast<const char *>(__FUNCTION__),
};
#if defined(_WIN32)
recur_mutex_lock lock{*mtx_};
#endif // defined(_WIN32)
try {
if (file_) {
if (fseeko(file_.get(), 0, SEEK_END) == -1) {
throw std::runtime_error("failed to seek");
}
auto size = ftello(file_.get());
if (size == -1) {
throw std::runtime_error("failed to get position");
}
return static_cast<std::uint64_t>(size);
}
std::uint64_t size{};
if (not get_file_size(path_, size)) {
throw std::runtime_error("failed to get file size");
}
return size;
} catch (const std::exception &e) {
utils::error::handle_exception(function_name, e);
} catch (...) {
utils::error::handle_exception(function_name);
}
return 0U;
}
} // namespace repertory::utils::file