boxcat.cpp 20 KB

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