CacheCheck.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. #include "core/CacheCheck.h"
  2. #include <atomic>
  3. #include <cstdio>
  4. #include <filesystem>
  5. #include <fstream>
  6. #include <iterator>
  7. #include <mutex>
  8. // xxHash 0.8.3 (BSD-2-Clause, third_party/xxhash, unmodified), compiled into this file only
  9. #define XXH_INLINE_ALL
  10. #define XXH_STATIC_LINKING_ONLY
  11. #include "../../third_party/xxhash/xxhash.h"
  12. namespace fs = std::filesystem;
  13. namespace lynx::cachecheck
  14. {
  15. std::uint64_t hash (const void* data, std::size_t bytes) noexcept
  16. {
  17. return (std::uint64_t) XXH3_64bits (data, bytes);
  18. }
  19. struct Hasher::State
  20. {
  21. XXH3_state_t s;
  22. };
  23. Hasher::Hasher() : state (std::make_unique<State>())
  24. {
  25. XXH3_64bits_reset (&state->s);
  26. }
  27. Hasher::~Hasher() = default;
  28. void Hasher::add (const void* data, std::size_t bytes) noexcept
  29. {
  30. if (bytes > 0)
  31. XXH3_64bits_update (&state->s, data, bytes);
  32. }
  33. std::uint64_t Hasher::value() const noexcept
  34. {
  35. return (std::uint64_t) XXH3_64bits_digest (&state->s);
  36. }
  37. const char* describe (Verdict v) noexcept
  38. {
  39. switch (v)
  40. {
  41. case Verdict::ok: return "ok";
  42. case Verdict::oldFormat: return "an older format without a check";
  43. case Verdict::truncated: return "its size does not match: cut short";
  44. case Verdict::mismatch: return "its content hash does not match: a changed byte";
  45. case Verdict::unreadable: return "not a cache file";
  46. }
  47. return "?";
  48. }
  49. // --- the log --------------------------------------------------------------------------------------------------------
  50. namespace
  51. {
  52. std::mutex logLock;
  53. std::string logFile, lastLine;
  54. std::atomic<int> rebuilt { 0 };
  55. fs::path u8path (const std::string& s) { return fs::path ((const char8_t*) s.c_str()); }
  56. template <typename T>
  57. void put (char* at, const T& v) noexcept { std::memcpy (at, &v, sizeof (T)); }
  58. template <typename T>
  59. T get (const char* at) noexcept
  60. {
  61. T v {};
  62. std::memcpy (&v, at, sizeof (T));
  63. return v;
  64. }
  65. } // namespace
  66. void setLogFile (const std::string& path)
  67. {
  68. const std::lock_guard<std::mutex> l (logLock);
  69. logFile = path;
  70. }
  71. namespace
  72. {
  73. void logLine (const std::string& line);
  74. }
  75. void reportRebuilt (const std::string& file, Verdict why)
  76. {
  77. logLine ("cache file " + file + " failed its check (" + describe (why) + ") and was rebuilt");
  78. }
  79. void reportDamaged (const std::string& file, Verdict why, const std::string& outcome)
  80. {
  81. logLine ("cache file " + file + " was damaged (" + describe (why) + "); " + outcome);
  82. }
  83. namespace
  84. {
  85. void logLine (const std::string& line)
  86. {
  87. ++rebuilt;
  88. std::fprintf (stderr, "LYNX: %s\n", line.c_str());
  89. const std::lock_guard<std::mutex> l (logLock);
  90. lastLine = line;
  91. if (logFile.empty())
  92. return;
  93. std::error_code ec;
  94. const auto path = u8path (logFile);
  95. if (fs::exists (path, ec) && fs::file_size (path, ec) > 64 * 1024 && ! ec)
  96. {
  97. // (kept small: the newest half)
  98. std::string text;
  99. {
  100. std::ifstream in (path, std::ios::binary);
  101. text.assign (std::istreambuf_iterator<char> (in), {});
  102. }
  103. const auto cut = text.find ('\n', text.size() / 2);
  104. std::ofstream out (path, std::ios::binary | std::ios::trunc);
  105. if (cut != std::string::npos)
  106. out << text.substr (cut + 1);
  107. }
  108. std::ofstream out (path, std::ios::binary | std::ios::app);
  109. out << line << "\n";
  110. }
  111. } // namespace
  112. int rebuiltCount() noexcept
  113. {
  114. return rebuilt.load();
  115. }
  116. std::string lastReport()
  117. {
  118. const std::lock_guard<std::mutex> l (logLock);
  119. return lastLine;
  120. }
  121. // --- *.str ----------------------------------------------------------------------------------------------------------
  122. namespace str
  123. {
  124. namespace
  125. {
  126. std::uint64_t hashOf (const char* header, const void* payload, std::size_t payloadBytes, const void* second = nullptr,
  127. std::size_t secondBytes = 0) noexcept
  128. {
  129. char zeroed[headerBytes];
  130. std::memcpy (zeroed, header, headerBytes);
  131. put<std::uint64_t> (zeroed + 32, 0);
  132. Hasher h;
  133. h.add (zeroed, headerBytes);
  134. h.add (payload, payloadBytes);
  135. if (second != nullptr)
  136. h.add (second, secondBytes);
  137. return h.value();
  138. }
  139. } // namespace
  140. void makeHeader (char* header, const Info& info, const float* left, const float* right) noexcept
  141. {
  142. std::memset (header, 0, headerBytes);
  143. std::memcpy (header, magic, 8);
  144. put (header + 8, info.sampleRate);
  145. put (header + 16, info.frames);
  146. put (header + 24, info.channels);
  147. const auto channelBytes = (std::size_t) info.frames * sizeof (float);
  148. const auto h = hashOf (header, left, channelBytes, info.channels == 2 ? right : nullptr, info.channels == 2 ? channelBytes : 0);
  149. put (header + 32, h);
  150. }
  151. Verdict readHeader (const void* data, std::size_t available, std::uint64_t fileBytes, Info& info) noexcept
  152. {
  153. const auto* d = static_cast<const char*> (data);
  154. if (available < 8)
  155. return Verdict::truncated;
  156. if (std::memcmp (d, magicV1, 8) == 0)
  157. return Verdict::oldFormat;
  158. if (available < headerBytes || std::memcmp (d, magic, 8) != 0)
  159. return std::memcmp (d, magic, 8) == 0 ? Verdict::truncated : Verdict::unreadable;
  160. info.sampleRate = get<double> (d + 8);
  161. info.frames = get<std::int64_t> (d + 16);
  162. info.channels = get<std::int32_t> (d + 24);
  163. // (a changed bit in the header's shape is a mismatch: the hash would say so too, but the size below must be sane first)
  164. if (info.frames <= 0 || info.frames > ((std::int64_t) 1 << 40) || ! (info.sampleRate > 0.0 && info.sampleRate < 1.0e7)
  165. || (info.channels != 1 && info.channels != 2 && info.channels != stereoSame) || get<std::int32_t> (d + 28) != 0)
  166. return Verdict::mismatch;
  167. for (std::size_t i = 40; i < headerBytes; ++i)
  168. if (d[i] != 0)
  169. return Verdict::mismatch;
  170. if (fileBytes != headerBytes + info.payloadBytes())
  171. return Verdict::truncated;
  172. return Verdict::ok;
  173. }
  174. Verdict verify (const void* file, std::size_t bytes, Info& info) noexcept
  175. {
  176. const auto shape = readHeader (file, bytes, bytes, info);
  177. if (shape != Verdict::ok)
  178. return shape;
  179. char header[headerBytes];
  180. std::memcpy (header, file, headerBytes);
  181. const auto stored = get<std::uint64_t> (header + 32);
  182. return hashOf (header, static_cast<const char*> (file) + headerBytes, (std::size_t) info.payloadBytes()) == stored ? Verdict::ok : Verdict::mismatch;
  183. }
  184. } // namespace str
  185. // --- *.pcm ----------------------------------------------------------------------------------------------------------
  186. namespace pcm
  187. {
  188. void makeHeaderStart (char* header, double sampleRate, std::int64_t frames) noexcept
  189. {
  190. std::memset (header, 0, headerBytes);
  191. std::memcpy (header, magic, 8);
  192. put (header + 8, sampleRate);
  193. put (header + 16, frames);
  194. }
  195. Verdict verify (const void* file, std::size_t bytes, double sampleRate, std::int64_t frames, bool content) noexcept
  196. {
  197. const auto* d = static_cast<const char*> (file);
  198. if (bytes < 8)
  199. return Verdict::truncated;
  200. if (std::memcmp (d, magicV1, 8) == 0)
  201. return Verdict::oldFormat;
  202. if (bytes < headerBytes || std::memcmp (d, magic, 8) != 0)
  203. return std::memcmp (d, magic, 8) == 0 ? Verdict::truncated : Verdict::unreadable;
  204. // (the rate and length are the source file's, from its reader: a header that says otherwise is not this sample's)
  205. if (get<double> (d + 8) != sampleRate || get<std::int64_t> (d + 16) != frames)
  206. return Verdict::mismatch;
  207. if (frames < 0 || (std::uint64_t) bytes != headerBytes + (std::uint64_t) frames * sizeof (float))
  208. return Verdict::truncated;
  209. if (! content)
  210. return Verdict::ok;
  211. Hasher h;
  212. h.add (d, hashOffset);
  213. h.add (d + headerBytes, bytes - headerBytes);
  214. return h.value() == get<std::uint64_t> (d + hashOffset) ? Verdict::ok : Verdict::mismatch;
  215. }
  216. } // namespace pcm
  217. // --- text -----------------------------------------------------------------------------------------------------------
  218. namespace
  219. {
  220. constexpr std::string_view sealPrefix = "lynx-cache-check xxh3 ";
  221. std::string hex16 (std::uint64_t v)
  222. {
  223. static const char* digits = "0123456789abcdef";
  224. std::string s (16, '0');
  225. for (int i = 15; i >= 0; --i, v >>= 4)
  226. s[(std::size_t) i] = digits[v & 15];
  227. return s;
  228. }
  229. } // namespace
  230. std::string sealText (std::string_view body)
  231. {
  232. std::string out (body);
  233. if (! out.empty() && out.back() != '\n')
  234. out += '\n';
  235. const auto h = hash (out.data(), out.size());
  236. out += sealPrefix;
  237. out += hex16 (h);
  238. out += '\n';
  239. return out;
  240. }
  241. Verdict unsealText (std::string_view text, std::string_view& body)
  242. {
  243. body = {};
  244. if (text.empty() || text.back() != '\n')
  245. return Verdict::oldFormat;
  246. const auto lineStart = text.rfind ('\n', text.size() - 2);
  247. const auto start = lineStart == std::string_view::npos ? 0 : lineStart + 1;
  248. const auto line = text.substr (start, text.size() - 1 - start);
  249. if (line.size() != sealPrefix.size() + 16 || line.substr (0, sealPrefix.size()) != sealPrefix)
  250. return Verdict::oldFormat;
  251. const auto content = text.substr (0, start);
  252. if (hex16 (hash (content.data(), content.size())) != line.substr (sealPrefix.size()))
  253. return Verdict::mismatch;
  254. body = content;
  255. return Verdict::ok;
  256. }
  257. std::string sidecarText (const void* data, std::size_t bytes)
  258. {
  259. return std::string (sealPrefix) + hex16 (hash (data, bytes)) + " " + std::to_string ((unsigned long long) bytes) + "\n";
  260. }
  261. Verdict sidecarMatches (std::string_view sidecar, const void* data, std::size_t bytes)
  262. {
  263. if (sidecar.substr (0, sealPrefix.size()) != sealPrefix)
  264. return Verdict::oldFormat;
  265. const auto expected = sidecarText (data, bytes);
  266. if (sidecar == expected)
  267. return Verdict::ok;
  268. // (the size first: a file cut short says so)
  269. const auto space = sidecar.find (' ', sealPrefix.size());
  270. if (space != std::string_view::npos && sidecar.substr (space + 1) != expected.substr (expected.find (' ', sealPrefix.size()) + 1))
  271. return Verdict::truncated;
  272. return Verdict::mismatch;
  273. }
  274. } // namespace lynx::cachecheck