#include "mologram/MediaCache.hpp" #include #include #include #include #include #include #include #include "mologram/Sha256.hpp" namespace mologram { namespace fs = std::filesystem; MediaCache::MediaCache(std::string dir) : dir_(std::move(dir)) {} std::string MediaCache::dirFor(const std::string& token, std::string& stem) const { stem = Sha256::hexOf(token); return dir_ + "/" + stem.substr(0, 2); } static bool writeFile(const std::string& path, const std::string& bytes, std::string& err) { int fd = ::open(path.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600); if (fd < 0) { err = std::string("open: ") + std::strerror(errno); return false; } size_t off = 0; while (off < bytes.size()) { ssize_t n = ::write(fd, bytes.data() + off, bytes.size() - off); if (n < 0) { if (errno == EINTR) continue; err = std::string("write: ") + std::strerror(errno); ::close(fd); return false; } off += (size_t)n; } if (::fsync(fd) != 0) { err = std::string("fsync: ") + std::strerror(errno); ::close(fd); return false; } ::close(fd); return true; } std::string MediaCache::put(const std::string& token, const std::string& bytes, std::string& err) { std::string stem; std::string d = dirFor(token, stem); std::error_code ec; fs::create_directories(d, ec); if (ec) { err = "cannot create " + d + ": " + ec.message(); return ""; } std::string file = d + "/" + stem + ".bin", sum = d + "/" + stem + ".sum"; if (!writeFile(file + ".tmp", bytes, err)) { fs::remove(file + ".tmp", ec); return ""; } if (!writeFile(sum + ".tmp", Sha256::hexOf(bytes), err)) { fs::remove(file + ".tmp", ec); fs::remove(sum + ".tmp", ec); return ""; } fs::rename(file + ".tmp", file, ec); if (ec) { err = "rename: " + ec.message(); return ""; } fs::rename(sum + ".tmp", sum, ec); if (ec) { err = "rename: " + ec.message(); return ""; } return file; } std::optional MediaCache::get(const std::string& token) { std::string stem; std::string d = dirFor(token, stem); std::string file = d + "/" + stem + ".bin", sum = d + "/" + stem + ".sum"; std::error_code ec; if (!fs::exists(file, ec)) return std::nullopt; std::ifstream in(file, std::ios::binary); std::ifstream sin(sum); if (!in || !sin) { rejected_++; return std::nullopt; } std::string bytes((std::istreambuf_iterator(in)), std::istreambuf_iterator()); std::string want((std::istreambuf_iterator(sin)), std::istreambuf_iterator()); if (Sha256::hexOf(bytes) != want) { rejected_++; return std::nullopt; } return file; } } // namespace mologram