boxcat.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. // Copyright 2019 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <fmt/ostream.h>
  5. #include <httplib.h>
  6. #include <mbedtls/sha256.h>
  7. #include <nlohmann/json.hpp>
  8. #include "common/hex_util.h"
  9. #include "common/logging/backend.h"
  10. #include "common/logging/log.h"
  11. #include "core/core.h"
  12. #include "core/file_sys/vfs.h"
  13. #include "core/file_sys/vfs_libzip.h"
  14. #include "core/file_sys/vfs_vector.h"
  15. #include "core/frontend/applets/error.h"
  16. #include "core/hle/service/am/applets/applets.h"
  17. #include "core/hle/service/bcat/backend/boxcat.h"
  18. #include "core/settings.h"
  19. namespace Service::BCAT {
  20. namespace {
  21. // Prevents conflicts with windows macro called CreateFile
  22. FileSys::VirtualFile VfsCreateFileWrap(FileSys::VirtualDir dir, std::string_view name) {
  23. return dir->CreateFile(name);
  24. }
  25. // Prevents conflicts with windows macro called DeleteFile
  26. bool VfsDeleteFileWrap(FileSys::VirtualDir dir, std::string_view name) {
  27. return dir->DeleteFile(name);
  28. }
  29. constexpr ResultCode ERROR_GENERAL_BCAT_FAILURE{ErrorModule::BCAT, 1};
  30. constexpr char BOXCAT_HOSTNAME[] = "api.yuzu-emu.org";
  31. // Formatted using fmt with arg[0] = hex title id
  32. constexpr char BOXCAT_PATHNAME_DATA[] = "/game-assets/{:016X}/boxcat";
  33. constexpr char BOXCAT_PATHNAME_LAUNCHPARAM[] = "/game-assets/{:016X}/launchparam";
  34. constexpr char BOXCAT_PATHNAME_EVENTS[] = "/game-assets/boxcat/events";
  35. constexpr char BOXCAT_API_VERSION[] = "1";
  36. constexpr char BOXCAT_CLIENT_TYPE[] = "yuzu";
  37. // HTTP status codes for Boxcat
  38. enum class ResponseStatus {
  39. Ok = 200, ///< Operation completed successfully.
  40. BadClientVersion = 301, ///< The Boxcat-Client-Version doesn't match the server.
  41. NoUpdate = 304, ///< The digest provided would match the new data, no need to update.
  42. NoMatchTitleId = 404, ///< The title ID provided doesn't have a boxcat implementation.
  43. NoMatchBuildId = 406, ///< The build ID provided is blacklisted (potentially because of format
  44. ///< issues or whatnot) and has no data.
  45. };
  46. enum class DownloadResult {
  47. Success = 0,
  48. NoResponse,
  49. GeneralWebError,
  50. NoMatchTitleId,
  51. NoMatchBuildId,
  52. InvalidContentType,
  53. GeneralFSError,
  54. BadClientVersion,
  55. };
  56. constexpr std::array<const char*, 8> DOWNLOAD_RESULT_LOG_MESSAGES{
  57. "Success",
  58. "There was no response from the server.",
  59. "There was a general web error code returned from the server.",
  60. "The title ID of the current game doesn't have a boxcat implementation. If you believe an "
  61. "implementation should be added, contact yuzu support.",
  62. "The build ID of the current version of the game is marked as incompatible with the current "
  63. "BCAT distribution. Try upgrading or downgrading your game version or contacting yuzu support.",
  64. "The content type of the web response was invalid.",
  65. "There was a general filesystem error while saving the zip file.",
  66. "The server is either too new or too old to serve the request. Try using the latest version of "
  67. "an official release of yuzu.",
  68. };
  69. std::ostream& operator<<(std::ostream& os, DownloadResult result) {
  70. return os << DOWNLOAD_RESULT_LOG_MESSAGES.at(static_cast<std::size_t>(result));
  71. }
  72. constexpr u32 PORT = 443;
  73. constexpr u32 TIMEOUT_SECONDS = 30;
  74. [[maybe_unused]] constexpr u64 VFS_COPY_BLOCK_SIZE = 1ULL << 24; // 4MB
  75. std::string GetBINFilePath(u64 title_id) {
  76. return fmt::format("{}bcat/{:016X}/launchparam.bin",
  77. Common::FS::GetUserPath(Common::FS::UserPath::CacheDir), title_id);
  78. }
  79. std::string GetZIPFilePath(u64 title_id) {
  80. return fmt::format("{}bcat/{:016X}/data.zip",
  81. Common::FS::GetUserPath(Common::FS::UserPath::CacheDir), title_id);
  82. }
  83. // If the error is something the user should know about (build ID mismatch, bad client version),
  84. // display an error.
  85. void HandleDownloadDisplayResult(const AM::Applets::AppletManager& applet_manager,
  86. DownloadResult res) {
  87. if (res == DownloadResult::Success || res == DownloadResult::NoResponse ||
  88. res == DownloadResult::GeneralWebError || res == DownloadResult::GeneralFSError ||
  89. res == DownloadResult::NoMatchTitleId || res == DownloadResult::InvalidContentType) {
  90. return;
  91. }
  92. const auto& frontend{applet_manager.GetAppletFrontendSet()};
  93. frontend.error->ShowCustomErrorText(
  94. RESULT_UNKNOWN, "There was an error while attempting to use Boxcat.",
  95. DOWNLOAD_RESULT_LOG_MESSAGES[static_cast<std::size_t>(res)], [] {});
  96. }
  97. bool VfsRawCopyProgress(FileSys::VirtualFile src, FileSys::VirtualFile dest,
  98. std::string_view dir_name, ProgressServiceBackend& progress,
  99. std::size_t block_size = 0x1000) {
  100. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  101. return false;
  102. if (!dest->Resize(src->GetSize()))
  103. return false;
  104. progress.StartDownloadingFile(dir_name, src->GetName(), src->GetSize());
  105. std::vector<u8> temp(std::min(block_size, src->GetSize()));
  106. for (std::size_t i = 0; i < src->GetSize(); i += block_size) {
  107. const auto read = std::min(block_size, src->GetSize() - i);
  108. if (src->Read(temp.data(), read, i) != read) {
  109. return false;
  110. }
  111. if (dest->Write(temp.data(), read, i) != read) {
  112. return false;
  113. }
  114. progress.UpdateFileProgress(i);
  115. }
  116. progress.FinishDownloadingFile();
  117. return true;
  118. }
  119. bool VfsRawCopyDProgressSingle(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  120. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  121. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  122. return false;
  123. for (const auto& file : src->GetFiles()) {
  124. const auto out_file = VfsCreateFileWrap(dest, file->GetName());
  125. if (!VfsRawCopyProgress(file, out_file, src->GetName(), progress, block_size)) {
  126. return false;
  127. }
  128. }
  129. progress.CommitDirectory(src->GetName());
  130. return true;
  131. }
  132. bool VfsRawCopyDProgress(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  133. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  134. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  135. return false;
  136. for (const auto& dir : src->GetSubdirectories()) {
  137. const auto out = dest->CreateSubdirectory(dir->GetName());
  138. if (!VfsRawCopyDProgressSingle(dir, out, progress, block_size)) {
  139. return false;
  140. }
  141. }
  142. return true;
  143. }
  144. } // Anonymous namespace
  145. class Boxcat::Client {
  146. public:
  147. Client(std::string path, u64 title_id, u64 build_id)
  148. : path(std::move(path)), title_id(title_id), build_id(build_id) {}
  149. DownloadResult DownloadDataZip() {
  150. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_DATA, title_id), TIMEOUT_SECONDS,
  151. "application/zip");
  152. }
  153. DownloadResult DownloadLaunchParam() {
  154. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_LAUNCHPARAM, title_id),
  155. TIMEOUT_SECONDS / 3, "application/octet-stream");
  156. }
  157. private:
  158. DownloadResult DownloadInternal(const std::string& resolved_path, u32 timeout_seconds,
  159. const std::string& content_type_name) {
  160. if (client == nullptr) {
  161. client = std::make_unique<httplib::SSLClient>(BOXCAT_HOSTNAME, PORT);
  162. client->set_connection_timeout(timeout_seconds);
  163. client->set_read_timeout(timeout_seconds);
  164. client->set_write_timeout(timeout_seconds);
  165. }
  166. httplib::Headers headers{
  167. {std::string("Game-Assets-API-Version"), std::string(BOXCAT_API_VERSION)},
  168. {std::string("Boxcat-Client-Type"), std::string(BOXCAT_CLIENT_TYPE)},
  169. {std::string("Game-Build-Id"), fmt::format("{:016X}", build_id)},
  170. };
  171. if (Common::FS::Exists(path)) {
  172. Common::FS::IOFile file{path, "rb"};
  173. if (file.IsOpen()) {
  174. std::vector<u8> bytes(file.GetSize());
  175. file.ReadBytes(bytes.data(), bytes.size());
  176. const auto digest = DigestFile(bytes);
  177. headers.insert({std::string("If-None-Match"), Common::HexToString(digest, false)});
  178. }
  179. }
  180. const auto response = client->Get(resolved_path.c_str(), headers);
  181. if (response == nullptr)
  182. return DownloadResult::NoResponse;
  183. if (response->status == static_cast<int>(ResponseStatus::NoUpdate))
  184. return DownloadResult::Success;
  185. if (response->status == static_cast<int>(ResponseStatus::BadClientVersion))
  186. return DownloadResult::BadClientVersion;
  187. if (response->status == static_cast<int>(ResponseStatus::NoMatchTitleId))
  188. return DownloadResult::NoMatchTitleId;
  189. if (response->status == static_cast<int>(ResponseStatus::NoMatchBuildId))
  190. return DownloadResult::NoMatchBuildId;
  191. if (response->status != static_cast<int>(ResponseStatus::Ok))
  192. return DownloadResult::GeneralWebError;
  193. const auto content_type = response->headers.find("content-type");
  194. if (content_type == response->headers.end() ||
  195. content_type->second.find(content_type_name) == std::string::npos) {
  196. return DownloadResult::InvalidContentType;
  197. }
  198. Common::FS::CreateFullPath(path);
  199. Common::FS::IOFile file{path, "wb"};
  200. if (!file.IsOpen())
  201. return DownloadResult::GeneralFSError;
  202. if (!file.Resize(response->body.size()))
  203. return DownloadResult::GeneralFSError;
  204. if (file.WriteBytes(response->body.data(), response->body.size()) != response->body.size())
  205. return DownloadResult::GeneralFSError;
  206. return DownloadResult::Success;
  207. }
  208. using Digest = std::array<u8, 0x20>;
  209. static Digest DigestFile(std::vector<u8> bytes) {
  210. Digest out{};
  211. mbedtls_sha256_ret(bytes.data(), bytes.size(), out.data(), 0);
  212. return out;
  213. }
  214. std::unique_ptr<httplib::SSLClient> client;
  215. std::string path;
  216. u64 title_id;
  217. u64 build_id;
  218. };
  219. Boxcat::Boxcat(AM::Applets::AppletManager& applet_manager_, DirectoryGetter getter)
  220. : Backend(std::move(getter)), applet_manager{applet_manager_} {}
  221. Boxcat::~Boxcat() = default;
  222. void SynchronizeInternal(AM::Applets::AppletManager& applet_manager, DirectoryGetter dir_getter,
  223. TitleIDVersion title, ProgressServiceBackend& progress,
  224. std::optional<std::string> dir_name = {}) {
  225. progress.SetNeedHLELock(true);
  226. if (Settings::values.bcat_boxcat_local) {
  227. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping download.");
  228. const auto dir = dir_getter(title.title_id);
  229. if (dir)
  230. progress.SetTotalSize(dir->GetSize());
  231. progress.FinishDownload(RESULT_SUCCESS);
  232. return;
  233. }
  234. const auto zip_path{GetZIPFilePath(title.title_id)};
  235. Boxcat::Client client{zip_path, title.title_id, title.build_id};
  236. progress.StartConnecting();
  237. const auto res = client.DownloadDataZip();
  238. if (res != DownloadResult::Success) {
  239. LOG_ERROR(Service_BCAT, "Boxcat synchronization failed with error '{}'!", res);
  240. if (res == DownloadResult::NoMatchBuildId || res == DownloadResult::NoMatchTitleId) {
  241. Common::FS::Delete(zip_path);
  242. }
  243. HandleDownloadDisplayResult(applet_manager, res);
  244. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  245. return;
  246. }
  247. progress.StartProcessingDataList();
  248. Common::FS::IOFile zip{zip_path, "rb"};
  249. const auto size = zip.GetSize();
  250. std::vector<u8> bytes(size);
  251. if (!zip.IsOpen() || size == 0 || zip.ReadBytes(bytes.data(), bytes.size()) != bytes.size()) {
  252. LOG_ERROR(Service_BCAT, "Boxcat failed to read ZIP file at path '{}'!", zip_path);
  253. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  254. return;
  255. }
  256. const auto extracted = FileSys::ExtractZIP(std::make_shared<FileSys::VectorVfsFile>(bytes));
  257. if (extracted == nullptr) {
  258. LOG_ERROR(Service_BCAT, "Boxcat failed to extract ZIP file!");
  259. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  260. return;
  261. }
  262. if (dir_name == std::nullopt) {
  263. progress.SetTotalSize(extracted->GetSize());
  264. const auto target_dir = dir_getter(title.title_id);
  265. if (target_dir == nullptr || !VfsRawCopyDProgress(extracted, target_dir, progress)) {
  266. LOG_ERROR(Service_BCAT, "Boxcat failed to copy extracted ZIP to target directory!");
  267. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  268. return;
  269. }
  270. } else {
  271. const auto target_dir = dir_getter(title.title_id);
  272. if (target_dir == nullptr) {
  273. LOG_ERROR(Service_BCAT, "Boxcat failed to get directory for title ID!");
  274. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  275. return;
  276. }
  277. const auto target_sub = target_dir->GetSubdirectory(*dir_name);
  278. const auto source_sub = extracted->GetSubdirectory(*dir_name);
  279. progress.SetTotalSize(source_sub->GetSize());
  280. std::vector<std::string> filenames;
  281. {
  282. const auto files = target_sub->GetFiles();
  283. std::transform(files.begin(), files.end(), std::back_inserter(filenames),
  284. [](const auto& vfile) { return vfile->GetName(); });
  285. }
  286. for (const auto& filename : filenames) {
  287. VfsDeleteFileWrap(target_sub, filename);
  288. }
  289. if (target_sub == nullptr || source_sub == nullptr ||
  290. !VfsRawCopyDProgressSingle(source_sub, target_sub, progress)) {
  291. LOG_ERROR(Service_BCAT, "Boxcat failed to copy extracted ZIP to target directory!");
  292. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  293. return;
  294. }
  295. }
  296. progress.FinishDownload(RESULT_SUCCESS);
  297. }
  298. bool Boxcat::Synchronize(TitleIDVersion title, ProgressServiceBackend& progress) {
  299. is_syncing.exchange(true);
  300. std::thread([this, title, &progress] {
  301. SynchronizeInternal(applet_manager, dir_getter, title, progress);
  302. }).detach();
  303. return true;
  304. }
  305. bool Boxcat::SynchronizeDirectory(TitleIDVersion title, std::string name,
  306. ProgressServiceBackend& progress) {
  307. is_syncing.exchange(true);
  308. std::thread([this, title, name, &progress] {
  309. SynchronizeInternal(applet_manager, dir_getter, title, progress, name);
  310. }).detach();
  311. return true;
  312. }
  313. bool Boxcat::Clear(u64 title_id) {
  314. if (Settings::values.bcat_boxcat_local) {
  315. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping clear.");
  316. return true;
  317. }
  318. const auto dir = dir_getter(title_id);
  319. std::vector<std::string> dirnames;
  320. for (const auto& subdir : dir->GetSubdirectories())
  321. dirnames.push_back(subdir->GetName());
  322. for (const auto& subdir : dirnames) {
  323. if (!dir->DeleteSubdirectoryRecursive(subdir))
  324. return false;
  325. }
  326. return true;
  327. }
  328. void Boxcat::SetPassphrase(u64 title_id, const Passphrase& passphrase) {
  329. LOG_DEBUG(Service_BCAT, "called, title_id={:016X}, passphrase={}", title_id,
  330. Common::HexToString(passphrase));
  331. }
  332. std::optional<std::vector<u8>> Boxcat::GetLaunchParameter(TitleIDVersion title) {
  333. const auto path{GetBINFilePath(title.title_id)};
  334. if (Settings::values.bcat_boxcat_local) {
  335. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping download.");
  336. } else {
  337. Boxcat::Client client{path, title.title_id, title.build_id};
  338. const auto res = client.DownloadLaunchParam();
  339. if (res != DownloadResult::Success) {
  340. LOG_ERROR(Service_BCAT, "Boxcat synchronization failed with error '{}'!", res);
  341. if (res == DownloadResult::NoMatchBuildId || res == DownloadResult::NoMatchTitleId) {
  342. Common::FS::Delete(path);
  343. }
  344. HandleDownloadDisplayResult(applet_manager, res);
  345. return std::nullopt;
  346. }
  347. }
  348. Common::FS::IOFile bin{path, "rb"};
  349. const auto size = bin.GetSize();
  350. std::vector<u8> bytes(size);
  351. if (!bin.IsOpen() || size == 0 || bin.ReadBytes(bytes.data(), bytes.size()) != bytes.size()) {
  352. LOG_ERROR(Service_BCAT, "Boxcat failed to read launch parameter binary at path '{}'!",
  353. path);
  354. return std::nullopt;
  355. }
  356. return bytes;
  357. }
  358. Boxcat::StatusResult Boxcat::GetStatus(std::optional<std::string>& global,
  359. std::map<std::string, EventStatus>& games) {
  360. httplib::SSLClient client{BOXCAT_HOSTNAME, static_cast<int>(PORT)};
  361. client.set_connection_timeout(static_cast<int>(TIMEOUT_SECONDS));
  362. client.set_read_timeout(static_cast<int>(TIMEOUT_SECONDS));
  363. client.set_write_timeout(static_cast<int>(TIMEOUT_SECONDS));
  364. httplib::Headers headers{
  365. {std::string("Game-Assets-API-Version"), std::string(BOXCAT_API_VERSION)},
  366. {std::string("Boxcat-Client-Type"), std::string(BOXCAT_CLIENT_TYPE)},
  367. };
  368. const auto response = client.Get(BOXCAT_PATHNAME_EVENTS, headers);
  369. if (response == nullptr)
  370. return StatusResult::Offline;
  371. if (response->status == static_cast<int>(ResponseStatus::BadClientVersion))
  372. return StatusResult::BadClientVersion;
  373. try {
  374. nlohmann::json json = nlohmann::json::parse(response->body);
  375. if (!json["online"].get<bool>())
  376. return StatusResult::Offline;
  377. if (json["global"].is_null())
  378. global = std::nullopt;
  379. else
  380. global = json["global"].get<std::string>();
  381. if (json["games"].is_array()) {
  382. for (const auto object : json["games"]) {
  383. if (object.is_object() && object.find("name") != object.end()) {
  384. EventStatus detail{};
  385. if (object["header"].is_string()) {
  386. detail.header = object["header"].get<std::string>();
  387. } else {
  388. detail.header = std::nullopt;
  389. }
  390. if (object["footer"].is_string()) {
  391. detail.footer = object["footer"].get<std::string>();
  392. } else {
  393. detail.footer = std::nullopt;
  394. }
  395. if (object["events"].is_array()) {
  396. for (const auto& event : object["events"]) {
  397. if (!event.is_string())
  398. continue;
  399. detail.events.push_back(event.get<std::string>());
  400. }
  401. }
  402. games.insert_or_assign(object["name"], std::move(detail));
  403. }
  404. }
  405. }
  406. return StatusResult::Success;
  407. } catch (const nlohmann::json::parse_error& error) {
  408. LOG_ERROR(Service_BCAT, "{}", error.what());
  409. return StatusResult::ParseError;
  410. }
  411. }
  412. } // namespace Service::BCAT