boxcat.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 <json.hpp>
  7. #include <mbedtls/sha256.h>
  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 {
  20. // Prevents conflicts with windows macro called CreateFile
  21. FileSys::VirtualFile VfsCreateFileWrap(FileSys::VirtualDir dir, std::string_view name) {
  22. return dir->CreateFile(name);
  23. }
  24. // Prevents conflicts with windows macro called DeleteFile
  25. bool VfsDeleteFileWrap(FileSys::VirtualDir dir, std::string_view name) {
  26. return dir->DeleteFile(name);
  27. }
  28. } // Anonymous namespace
  29. namespace Service::BCAT {
  30. constexpr ResultCode ERROR_GENERAL_BCAT_FAILURE{ErrorModule::BCAT, 1};
  31. constexpr char BOXCAT_HOSTNAME[] = "api.yuzu-emu.org";
  32. // Formatted using fmt with arg[0] = hex title id
  33. constexpr char BOXCAT_PATHNAME_DATA[] = "/game-assets/{:016X}/boxcat";
  34. constexpr char BOXCAT_PATHNAME_LAUNCHPARAM[] = "/game-assets/{:016X}/launchparam";
  35. constexpr char BOXCAT_PATHNAME_EVENTS[] = "/game-assets/boxcat/events";
  36. constexpr char BOXCAT_API_VERSION[] = "1";
  37. constexpr char BOXCAT_CLIENT_TYPE[] = "yuzu";
  38. // HTTP status codes for Boxcat
  39. enum class ResponseStatus {
  40. Ok = 200, ///< Operation completed successfully.
  41. BadClientVersion = 301, ///< The Boxcat-Client-Version doesn't match the server.
  42. NoUpdate = 304, ///< The digest provided would match the new data, no need to update.
  43. NoMatchTitleId = 404, ///< The title ID provided doesn't have a boxcat implementation.
  44. NoMatchBuildId = 406, ///< The build ID provided is blacklisted (potentially because of format
  45. ///< issues or whatnot) and has no data.
  46. };
  47. enum class DownloadResult {
  48. Success = 0,
  49. NoResponse,
  50. GeneralWebError,
  51. NoMatchTitleId,
  52. NoMatchBuildId,
  53. InvalidContentType,
  54. GeneralFSError,
  55. BadClientVersion,
  56. };
  57. constexpr std::array<const char*, 8> DOWNLOAD_RESULT_LOG_MESSAGES{
  58. "Success",
  59. "There was no response from the server.",
  60. "There was a general web error code returned from the server.",
  61. "The title ID of the current game doesn't have a boxcat implementation. If you believe an "
  62. "implementation should be added, contact yuzu support.",
  63. "The build ID of the current version of the game is marked as incompatible with the current "
  64. "BCAT distribution. Try upgrading or downgrading your game version or contacting yuzu support.",
  65. "The content type of the web response was invalid.",
  66. "There was a general filesystem error while saving the zip file.",
  67. "The server is either too new or too old to serve the request. Try using the latest version of "
  68. "an official release of yuzu.",
  69. };
  70. std::ostream& operator<<(std::ostream& os, DownloadResult result) {
  71. return os << DOWNLOAD_RESULT_LOG_MESSAGES.at(static_cast<std::size_t>(result));
  72. }
  73. constexpr u32 PORT = 443;
  74. constexpr u32 TIMEOUT_SECONDS = 30;
  75. [[maybe_unused]] constexpr u64 VFS_COPY_BLOCK_SIZE = 1ULL << 24; // 4MB
  76. namespace {
  77. std::string GetBINFilePath(u64 title_id) {
  78. return fmt::format("{}bcat/{:016X}/launchparam.bin",
  79. FileUtil::GetUserPath(FileUtil::UserPath::CacheDir), title_id);
  80. }
  81. std::string GetZIPFilePath(u64 title_id) {
  82. return fmt::format("{}bcat/{:016X}/data.zip",
  83. FileUtil::GetUserPath(FileUtil::UserPath::CacheDir), title_id);
  84. }
  85. // If the error is something the user should know about (build ID mismatch, bad client version),
  86. // display an error.
  87. void HandleDownloadDisplayResult(const AM::Applets::AppletManager& applet_manager,
  88. DownloadResult res) {
  89. if (res == DownloadResult::Success || res == DownloadResult::NoResponse ||
  90. res == DownloadResult::GeneralWebError || res == DownloadResult::GeneralFSError ||
  91. res == DownloadResult::NoMatchTitleId || res == DownloadResult::InvalidContentType) {
  92. return;
  93. }
  94. const auto& frontend{applet_manager.GetAppletFrontendSet()};
  95. frontend.error->ShowCustomErrorText(
  96. RESULT_UNKNOWN, "There was an error while attempting to use Boxcat.",
  97. DOWNLOAD_RESULT_LOG_MESSAGES[static_cast<std::size_t>(res)], [] {});
  98. }
  99. bool VfsRawCopyProgress(FileSys::VirtualFile src, FileSys::VirtualFile dest,
  100. std::string_view dir_name, ProgressServiceBackend& progress,
  101. std::size_t block_size = 0x1000) {
  102. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  103. return false;
  104. if (!dest->Resize(src->GetSize()))
  105. return false;
  106. progress.StartDownloadingFile(dir_name, src->GetName(), src->GetSize());
  107. std::vector<u8> temp(std::min(block_size, src->GetSize()));
  108. for (std::size_t i = 0; i < src->GetSize(); i += block_size) {
  109. const auto read = std::min(block_size, src->GetSize() - i);
  110. if (src->Read(temp.data(), read, i) != read) {
  111. return false;
  112. }
  113. if (dest->Write(temp.data(), read, i) != read) {
  114. return false;
  115. }
  116. progress.UpdateFileProgress(i);
  117. }
  118. progress.FinishDownloadingFile();
  119. return true;
  120. }
  121. bool VfsRawCopyDProgressSingle(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  122. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  123. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  124. return false;
  125. for (const auto& file : src->GetFiles()) {
  126. const auto out_file = VfsCreateFileWrap(dest, file->GetName());
  127. if (!VfsRawCopyProgress(file, out_file, src->GetName(), progress, block_size)) {
  128. return false;
  129. }
  130. }
  131. progress.CommitDirectory(src->GetName());
  132. return true;
  133. }
  134. bool VfsRawCopyDProgress(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  135. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  136. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  137. return false;
  138. for (const auto& dir : src->GetSubdirectories()) {
  139. const auto out = dest->CreateSubdirectory(dir->GetName());
  140. if (!VfsRawCopyDProgressSingle(dir, out, progress, block_size)) {
  141. return false;
  142. }
  143. }
  144. return true;
  145. }
  146. } // Anonymous namespace
  147. class Boxcat::Client {
  148. public:
  149. Client(std::string path, u64 title_id, u64 build_id)
  150. : path(std::move(path)), title_id(title_id), build_id(build_id) {}
  151. DownloadResult DownloadDataZip() {
  152. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_DATA, title_id), TIMEOUT_SECONDS,
  153. "application/zip");
  154. }
  155. DownloadResult DownloadLaunchParam() {
  156. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_LAUNCHPARAM, title_id),
  157. TIMEOUT_SECONDS / 3, "application/octet-stream");
  158. }
  159. private:
  160. DownloadResult DownloadInternal(const std::string& resolved_path, u32 timeout_seconds,
  161. const std::string& content_type_name) {
  162. if (client == nullptr) {
  163. client = std::make_unique<httplib::SSLClient>(BOXCAT_HOSTNAME, PORT);
  164. client->set_timeout_sec(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 (FileUtil::Exists(path)) {
  172. FileUtil::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. FileUtil::CreateFullPath(path);
  199. FileUtil::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::Client> 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. FileUtil::Delete(zip_path);
  242. }
  243. HandleDownloadDisplayResult(applet_manager, res);
  244. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  245. return;
  246. }
  247. progress.StartProcessingDataList();
  248. FileUtil::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. })
  303. .detach();
  304. return true;
  305. }
  306. bool Boxcat::SynchronizeDirectory(TitleIDVersion title, std::string name,
  307. ProgressServiceBackend& progress) {
  308. is_syncing.exchange(true);
  309. std::thread([this, title, name, &progress] {
  310. SynchronizeInternal(applet_manager, dir_getter, title, progress, name);
  311. })
  312. .detach();
  313. return true;
  314. }
  315. bool Boxcat::Clear(u64 title_id) {
  316. if (Settings::values.bcat_boxcat_local) {
  317. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping clear.");
  318. return true;
  319. }
  320. const auto dir = dir_getter(title_id);
  321. std::vector<std::string> dirnames;
  322. for (const auto& subdir : dir->GetSubdirectories())
  323. dirnames.push_back(subdir->GetName());
  324. for (const auto& subdir : dirnames) {
  325. if (!dir->DeleteSubdirectoryRecursive(subdir))
  326. return false;
  327. }
  328. return true;
  329. }
  330. void Boxcat::SetPassphrase(u64 title_id, const Passphrase& passphrase) {
  331. LOG_DEBUG(Service_BCAT, "called, title_id={:016X}, passphrase={}", title_id,
  332. Common::HexToString(passphrase));
  333. }
  334. std::optional<std::vector<u8>> Boxcat::GetLaunchParameter(TitleIDVersion title) {
  335. const auto path{GetBINFilePath(title.title_id)};
  336. if (Settings::values.bcat_boxcat_local) {
  337. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping download.");
  338. } else {
  339. Boxcat::Client client{path, title.title_id, title.build_id};
  340. const auto res = client.DownloadLaunchParam();
  341. if (res != DownloadResult::Success) {
  342. LOG_ERROR(Service_BCAT, "Boxcat synchronization failed with error '{}'!", res);
  343. if (res == DownloadResult::NoMatchBuildId || res == DownloadResult::NoMatchTitleId) {
  344. FileUtil::Delete(path);
  345. }
  346. HandleDownloadDisplayResult(applet_manager, res);
  347. return std::nullopt;
  348. }
  349. }
  350. FileUtil::IOFile bin{path, "rb"};
  351. const auto size = bin.GetSize();
  352. std::vector<u8> bytes(size);
  353. if (!bin.IsOpen() || size == 0 || bin.ReadBytes(bytes.data(), bytes.size()) != bytes.size()) {
  354. LOG_ERROR(Service_BCAT, "Boxcat failed to read launch parameter binary at path '{}'!",
  355. path);
  356. return std::nullopt;
  357. }
  358. return bytes;
  359. }
  360. Boxcat::StatusResult Boxcat::GetStatus(std::optional<std::string>& global,
  361. std::map<std::string, EventStatus>& games) {
  362. httplib::SSLClient client{BOXCAT_HOSTNAME, static_cast<int>(PORT)};
  363. client.set_timeout_sec(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