boxcat.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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(DownloadResult res) {
  88. if (res == DownloadResult::Success || res == DownloadResult::NoResponse ||
  89. res == DownloadResult::GeneralWebError || res == DownloadResult::GeneralFSError ||
  90. res == DownloadResult::NoMatchTitleId || res == DownloadResult::InvalidContentType) {
  91. return;
  92. }
  93. const auto& frontend{Core::System::GetInstance().GetAppletManager().GetAppletFrontendSet()};
  94. frontend.error->ShowCustomErrorText(
  95. ResultCode(-1), "There was an error while attempting to use Boxcat.",
  96. DOWNLOAD_RESULT_LOG_MESSAGES[static_cast<std::size_t>(res)], [] {});
  97. }
  98. bool VfsRawCopyProgress(FileSys::VirtualFile src, FileSys::VirtualFile dest,
  99. std::string_view dir_name, ProgressServiceBackend& progress,
  100. std::size_t block_size = 0x1000) {
  101. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  102. return false;
  103. if (!dest->Resize(src->GetSize()))
  104. return false;
  105. progress.StartDownloadingFile(dir_name, src->GetName(), src->GetSize());
  106. std::vector<u8> temp(std::min(block_size, src->GetSize()));
  107. for (std::size_t i = 0; i < src->GetSize(); i += block_size) {
  108. const auto read = std::min(block_size, src->GetSize() - i);
  109. if (src->Read(temp.data(), read, i) != read) {
  110. return false;
  111. }
  112. if (dest->Write(temp.data(), read, i) != read) {
  113. return false;
  114. }
  115. progress.UpdateFileProgress(i);
  116. }
  117. progress.FinishDownloadingFile();
  118. return true;
  119. }
  120. bool VfsRawCopyDProgressSingle(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  121. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  122. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  123. return false;
  124. for (const auto& file : src->GetFiles()) {
  125. const auto out_file = VfsCreateFileWrap(dest, file->GetName());
  126. if (!VfsRawCopyProgress(file, out_file, src->GetName(), progress, block_size)) {
  127. return false;
  128. }
  129. }
  130. progress.CommitDirectory(src->GetName());
  131. return true;
  132. }
  133. bool VfsRawCopyDProgress(FileSys::VirtualDir src, FileSys::VirtualDir dest,
  134. ProgressServiceBackend& progress, std::size_t block_size = 0x1000) {
  135. if (src == nullptr || dest == nullptr || !src->IsReadable() || !dest->IsWritable())
  136. return false;
  137. for (const auto& dir : src->GetSubdirectories()) {
  138. const auto out = dest->CreateSubdirectory(dir->GetName());
  139. if (!VfsRawCopyDProgressSingle(dir, out, progress, block_size)) {
  140. return false;
  141. }
  142. }
  143. return true;
  144. }
  145. } // Anonymous namespace
  146. class Boxcat::Client {
  147. public:
  148. Client(std::string path, u64 title_id, u64 build_id)
  149. : path(std::move(path)), title_id(title_id), build_id(build_id) {}
  150. DownloadResult DownloadDataZip() {
  151. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_DATA, title_id), TIMEOUT_SECONDS,
  152. "application/zip");
  153. }
  154. DownloadResult DownloadLaunchParam() {
  155. return DownloadInternal(fmt::format(BOXCAT_PATHNAME_LAUNCHPARAM, title_id),
  156. TIMEOUT_SECONDS / 3, "application/octet-stream");
  157. }
  158. private:
  159. DownloadResult DownloadInternal(const std::string& resolved_path, u32 timeout_seconds,
  160. const std::string& content_type_name) {
  161. if (client == nullptr) {
  162. client = std::make_unique<httplib::SSLClient>(BOXCAT_HOSTNAME, PORT, timeout_seconds);
  163. }
  164. httplib::Headers headers{
  165. {std::string("Game-Assets-API-Version"), std::string(BOXCAT_API_VERSION)},
  166. {std::string("Boxcat-Client-Type"), std::string(BOXCAT_CLIENT_TYPE)},
  167. {std::string("Game-Build-Id"), fmt::format("{:016X}", build_id)},
  168. };
  169. if (FileUtil::Exists(path)) {
  170. FileUtil::IOFile file{path, "rb"};
  171. if (file.IsOpen()) {
  172. std::vector<u8> bytes(file.GetSize());
  173. file.ReadBytes(bytes.data(), bytes.size());
  174. const auto digest = DigestFile(bytes);
  175. headers.insert({std::string("If-None-Match"), Common::HexToString(digest, false)});
  176. }
  177. }
  178. const auto response = client->Get(resolved_path.c_str(), headers);
  179. if (response == nullptr)
  180. return DownloadResult::NoResponse;
  181. if (response->status == static_cast<int>(ResponseStatus::NoUpdate))
  182. return DownloadResult::Success;
  183. if (response->status == static_cast<int>(ResponseStatus::BadClientVersion))
  184. return DownloadResult::BadClientVersion;
  185. if (response->status == static_cast<int>(ResponseStatus::NoMatchTitleId))
  186. return DownloadResult::NoMatchTitleId;
  187. if (response->status == static_cast<int>(ResponseStatus::NoMatchBuildId))
  188. return DownloadResult::NoMatchBuildId;
  189. if (response->status != static_cast<int>(ResponseStatus::Ok))
  190. return DownloadResult::GeneralWebError;
  191. const auto content_type = response->headers.find("content-type");
  192. if (content_type == response->headers.end() ||
  193. content_type->second.find(content_type_name) == std::string::npos) {
  194. return DownloadResult::InvalidContentType;
  195. }
  196. FileUtil::CreateFullPath(path);
  197. FileUtil::IOFile file{path, "wb"};
  198. if (!file.IsOpen())
  199. return DownloadResult::GeneralFSError;
  200. if (!file.Resize(response->body.size()))
  201. return DownloadResult::GeneralFSError;
  202. if (file.WriteBytes(response->body.data(), response->body.size()) != response->body.size())
  203. return DownloadResult::GeneralFSError;
  204. return DownloadResult::Success;
  205. }
  206. using Digest = std::array<u8, 0x20>;
  207. static Digest DigestFile(std::vector<u8> bytes) {
  208. Digest out{};
  209. mbedtls_sha256(bytes.data(), bytes.size(), out.data(), 0);
  210. return out;
  211. }
  212. std::unique_ptr<httplib::Client> client;
  213. std::string path;
  214. u64 title_id;
  215. u64 build_id;
  216. };
  217. Boxcat::Boxcat(DirectoryGetter getter) : Backend(std::move(getter)) {}
  218. Boxcat::~Boxcat() = default;
  219. void SynchronizeInternal(DirectoryGetter dir_getter, TitleIDVersion title,
  220. ProgressServiceBackend& progress,
  221. std::optional<std::string> dir_name = {}) {
  222. progress.SetNeedHLELock(true);
  223. if (Settings::values.bcat_boxcat_local) {
  224. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping download.");
  225. const auto dir = dir_getter(title.title_id);
  226. if (dir)
  227. progress.SetTotalSize(dir->GetSize());
  228. progress.FinishDownload(RESULT_SUCCESS);
  229. return;
  230. }
  231. const auto zip_path{GetZIPFilePath(title.title_id)};
  232. Boxcat::Client client{zip_path, title.title_id, title.build_id};
  233. progress.StartConnecting();
  234. const auto res = client.DownloadDataZip();
  235. if (res != DownloadResult::Success) {
  236. LOG_ERROR(Service_BCAT, "Boxcat synchronization failed with error '{}'!", res);
  237. if (res == DownloadResult::NoMatchBuildId || res == DownloadResult::NoMatchTitleId) {
  238. FileUtil::Delete(zip_path);
  239. }
  240. HandleDownloadDisplayResult(res);
  241. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  242. return;
  243. }
  244. progress.StartProcessingDataList();
  245. FileUtil::IOFile zip{zip_path, "rb"};
  246. const auto size = zip.GetSize();
  247. std::vector<u8> bytes(size);
  248. if (!zip.IsOpen() || size == 0 || zip.ReadBytes(bytes.data(), bytes.size()) != bytes.size()) {
  249. LOG_ERROR(Service_BCAT, "Boxcat failed to read ZIP file at path '{}'!", zip_path);
  250. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  251. return;
  252. }
  253. const auto extracted = FileSys::ExtractZIP(std::make_shared<FileSys::VectorVfsFile>(bytes));
  254. if (extracted == nullptr) {
  255. LOG_ERROR(Service_BCAT, "Boxcat failed to extract ZIP file!");
  256. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  257. return;
  258. }
  259. if (dir_name == std::nullopt) {
  260. progress.SetTotalSize(extracted->GetSize());
  261. const auto target_dir = dir_getter(title.title_id);
  262. if (target_dir == nullptr || !VfsRawCopyDProgress(extracted, target_dir, progress)) {
  263. LOG_ERROR(Service_BCAT, "Boxcat failed to copy extracted ZIP to target directory!");
  264. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  265. return;
  266. }
  267. } else {
  268. const auto target_dir = dir_getter(title.title_id);
  269. if (target_dir == nullptr) {
  270. LOG_ERROR(Service_BCAT, "Boxcat failed to get directory for title ID!");
  271. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  272. return;
  273. }
  274. const auto target_sub = target_dir->GetSubdirectory(*dir_name);
  275. const auto source_sub = extracted->GetSubdirectory(*dir_name);
  276. progress.SetTotalSize(source_sub->GetSize());
  277. std::vector<std::string> filenames;
  278. {
  279. const auto files = target_sub->GetFiles();
  280. std::transform(files.begin(), files.end(), std::back_inserter(filenames),
  281. [](const auto& vfile) { return vfile->GetName(); });
  282. }
  283. for (const auto& filename : filenames) {
  284. VfsDeleteFileWrap(target_sub, filename);
  285. }
  286. if (target_sub == nullptr || source_sub == nullptr ||
  287. !VfsRawCopyDProgressSingle(source_sub, target_sub, progress)) {
  288. LOG_ERROR(Service_BCAT, "Boxcat failed to copy extracted ZIP to target directory!");
  289. progress.FinishDownload(ERROR_GENERAL_BCAT_FAILURE);
  290. return;
  291. }
  292. }
  293. progress.FinishDownload(RESULT_SUCCESS);
  294. }
  295. bool Boxcat::Synchronize(TitleIDVersion title, ProgressServiceBackend& progress) {
  296. is_syncing.exchange(true);
  297. std::thread([this, title, &progress] { SynchronizeInternal(dir_getter, title, progress); })
  298. .detach();
  299. return true;
  300. }
  301. bool Boxcat::SynchronizeDirectory(TitleIDVersion title, std::string name,
  302. ProgressServiceBackend& progress) {
  303. is_syncing.exchange(true);
  304. std::thread(
  305. [this, title, name, &progress] { SynchronizeInternal(dir_getter, title, progress, name); })
  306. .detach();
  307. return true;
  308. }
  309. bool Boxcat::Clear(u64 title_id) {
  310. if (Settings::values.bcat_boxcat_local) {
  311. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping clear.");
  312. return true;
  313. }
  314. const auto dir = dir_getter(title_id);
  315. std::vector<std::string> dirnames;
  316. for (const auto& subdir : dir->GetSubdirectories())
  317. dirnames.push_back(subdir->GetName());
  318. for (const auto& subdir : dirnames) {
  319. if (!dir->DeleteSubdirectoryRecursive(subdir))
  320. return false;
  321. }
  322. return true;
  323. }
  324. void Boxcat::SetPassphrase(u64 title_id, const Passphrase& passphrase) {
  325. LOG_DEBUG(Service_BCAT, "called, title_id={:016X}, passphrase={}", title_id,
  326. Common::HexToString(passphrase));
  327. }
  328. std::optional<std::vector<u8>> Boxcat::GetLaunchParameter(TitleIDVersion title) {
  329. const auto path{GetBINFilePath(title.title_id)};
  330. if (Settings::values.bcat_boxcat_local) {
  331. LOG_INFO(Service_BCAT, "Boxcat using local data by override, skipping download.");
  332. } else {
  333. Boxcat::Client client{path, title.title_id, title.build_id};
  334. const auto res = client.DownloadLaunchParam();
  335. if (res != DownloadResult::Success) {
  336. LOG_ERROR(Service_BCAT, "Boxcat synchronization failed with error '{}'!", res);
  337. if (res == DownloadResult::NoMatchBuildId || res == DownloadResult::NoMatchTitleId) {
  338. FileUtil::Delete(path);
  339. }
  340. HandleDownloadDisplayResult(res);
  341. return std::nullopt;
  342. }
  343. }
  344. FileUtil::IOFile bin{path, "rb"};
  345. const auto size = bin.GetSize();
  346. std::vector<u8> bytes(size);
  347. if (!bin.IsOpen() || size == 0 || bin.ReadBytes(bytes.data(), bytes.size()) != bytes.size()) {
  348. LOG_ERROR(Service_BCAT, "Boxcat failed to read launch parameter binary at path '{}'!",
  349. path);
  350. return std::nullopt;
  351. }
  352. return bytes;
  353. }
  354. Boxcat::StatusResult Boxcat::GetStatus(std::optional<std::string>& global,
  355. std::map<std::string, EventStatus>& games) {
  356. httplib::SSLClient client{BOXCAT_HOSTNAME, static_cast<int>(PORT),
  357. static_cast<int>(TIMEOUT_SECONDS)};
  358. httplib::Headers headers{
  359. {std::string("Game-Assets-API-Version"), std::string(BOXCAT_API_VERSION)},
  360. {std::string("Boxcat-Client-Type"), std::string(BOXCAT_CLIENT_TYPE)},
  361. };
  362. const auto response = client.Get(BOXCAT_PATHNAME_EVENTS, headers);
  363. if (response == nullptr)
  364. return StatusResult::Offline;
  365. if (response->status == static_cast<int>(ResponseStatus::BadClientVersion))
  366. return StatusResult::BadClientVersion;
  367. try {
  368. nlohmann::json json = nlohmann::json::parse(response->body);
  369. if (!json["online"].get<bool>())
  370. return StatusResult::Offline;
  371. if (json["global"].is_null())
  372. global = std::nullopt;
  373. else
  374. global = json["global"].get<std::string>();
  375. if (json["games"].is_array()) {
  376. for (const auto object : json["games"]) {
  377. if (object.is_object() && object.find("name") != object.end()) {
  378. EventStatus detail{};
  379. if (object["header"].is_string()) {
  380. detail.header = object["header"].get<std::string>();
  381. } else {
  382. detail.header = std::nullopt;
  383. }
  384. if (object["footer"].is_string()) {
  385. detail.footer = object["footer"].get<std::string>();
  386. } else {
  387. detail.footer = std::nullopt;
  388. }
  389. if (object["events"].is_array()) {
  390. for (const auto& event : object["events"]) {
  391. if (!event.is_string())
  392. continue;
  393. detail.events.push_back(event.get<std::string>());
  394. }
  395. }
  396. games.insert_or_assign(object["name"], std::move(detail));
  397. }
  398. }
  399. }
  400. return StatusResult::Success;
  401. } catch (const nlohmann::json::parse_error& e) {
  402. return StatusResult::ParseError;
  403. }
  404. }
  405. } // namespace Service::BCAT