UpdaterCommon.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793
  1. // Copyright 2019 Dolphin Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "UpdaterCommon/UpdaterCommon.h"
  4. #include <algorithm>
  5. #include <array>
  6. #include <memory>
  7. #include <optional>
  8. #include <OptionParser.h>
  9. #include <ed25519.h>
  10. #include <mbedtls/base64.h>
  11. #include <mbedtls/sha256.h>
  12. #include <zlib.h>
  13. #include "Common/CommonFuncs.h"
  14. #include "Common/CommonPaths.h"
  15. #include "Common/FileUtil.h"
  16. #include "Common/HttpRequest.h"
  17. #include "Common/IOFile.h"
  18. #include "Common/ScopeGuard.h"
  19. #include "Common/StringUtil.h"
  20. #include "UpdaterCommon/Platform.h"
  21. #include "UpdaterCommon/UI.h"
  22. #ifndef _WIN32
  23. #include <sys/stat.h>
  24. #include <sys/types.h>
  25. #endif
  26. #ifdef _WIN32
  27. #include <Windows.h>
  28. #include <filesystem>
  29. #endif
  30. // Refer to docs/autoupdate_overview.md for a detailed overview of the autoupdate process
  31. // Public key used to verify update manifests.
  32. const std::array<u8, 32> UPDATE_PUB_KEY = {
  33. 0x2a, 0xb3, 0xd1, 0xdc, 0x6e, 0xf5, 0x07, 0xf6, 0xa0, 0x6c, 0x7c, 0x54, 0xdf, 0x54, 0xf4, 0x42,
  34. 0x80, 0xa6, 0x28, 0x8b, 0x6d, 0x70, 0x14, 0xb5, 0x4c, 0x34, 0x95, 0x20, 0x4d, 0xd4, 0xd3, 0x5d};
  35. // The private key for UPDATE_PUB_KEY_TEST is in Tools/test-updater.py
  36. const std::array<u8, 32> UPDATE_PUB_KEY_TEST = {
  37. 0x0c, 0x5f, 0xdc, 0xd1, 0x15, 0x71, 0xfb, 0x86, 0x4f, 0x9e, 0x6d, 0xe6, 0x65, 0x39, 0x43, 0xe1,
  38. 0x9e, 0xe0, 0x9b, 0x28, 0xc9, 0x1a, 0x60, 0xb7, 0x67, 0x1c, 0xf3, 0xf6, 0xca, 0x1b, 0xdd, 0x1a};
  39. // Where to log updater output.
  40. static File::IOFile log_file;
  41. void LogToFile(const char* fmt, ...)
  42. {
  43. va_list args;
  44. va_start(args, fmt);
  45. log_file.WriteString(StringFromFormatV(fmt, args));
  46. log_file.Flush();
  47. va_end(args);
  48. }
  49. bool ProgressCallback(s64 total, s64 now, s64, s64)
  50. {
  51. UI::SetCurrentProgress(static_cast<int>(now), static_cast<int>(total));
  52. return true;
  53. }
  54. std::string HexEncode(const u8* buffer, size_t size)
  55. {
  56. std::string out(size * 2, '\0');
  57. for (size_t i = 0; i < size; ++i)
  58. {
  59. out[2 * i] = "0123456789abcdef"[buffer[i] >> 4];
  60. out[2 * i + 1] = "0123456789abcdef"[buffer[i] & 0xF];
  61. }
  62. return out;
  63. }
  64. bool HexDecode(const std::string& hex, u8* buffer, size_t size)
  65. {
  66. if (hex.size() != size * 2)
  67. return false;
  68. auto DecodeNibble = [](char c) -> std::optional<u8> {
  69. if (c >= '0' && c <= '9')
  70. return static_cast<u8>(c - '0');
  71. else if (c >= 'a' && c <= 'f')
  72. return static_cast<u8>(c - 'a' + 10);
  73. else if (c >= 'A' && c <= 'F')
  74. return static_cast<u8>(c - 'A' + 10);
  75. else
  76. return {};
  77. };
  78. for (size_t i = 0; i < size; ++i)
  79. {
  80. std::optional<u8> high = DecodeNibble(hex[2 * i]);
  81. std::optional<u8> low = DecodeNibble(hex[2 * i + 1]);
  82. if (!high || !low)
  83. return false;
  84. buffer[i] = (*high << 4) | *low;
  85. }
  86. return true;
  87. }
  88. std::optional<std::string> GzipInflate(const std::string& data)
  89. {
  90. z_stream zstrm;
  91. zstrm.zalloc = nullptr;
  92. zstrm.zfree = nullptr;
  93. zstrm.opaque = nullptr;
  94. zstrm.avail_in = static_cast<u32>(data.size());
  95. zstrm.next_in = reinterpret_cast<u8*>(const_cast<char*>(data.data()));
  96. // 16 + MAX_WBITS means gzip. Don't ask me.
  97. inflateInit2(&zstrm, 16 + MAX_WBITS);
  98. std::string out;
  99. const size_t buf_len = 20 * 1024 * 1024;
  100. auto buffer = std::make_unique<char[]>(buf_len);
  101. int ret;
  102. do
  103. {
  104. zstrm.avail_out = buf_len;
  105. zstrm.next_out = reinterpret_cast<u8*>(buffer.get());
  106. ret = inflate(&zstrm, 0);
  107. out.append(buffer.get(), buf_len - zstrm.avail_out);
  108. } while (ret == Z_OK);
  109. inflateEnd(&zstrm);
  110. if (ret != Z_STREAM_END)
  111. {
  112. LogToFile("Could not read the data as gzip: error %d.\n", ret);
  113. return {};
  114. }
  115. return out;
  116. }
  117. Manifest::Hash ComputeHash(const std::string& contents)
  118. {
  119. std::array<u8, 32> full;
  120. mbedtls_sha256_ret(reinterpret_cast<const u8*>(contents.data()), contents.size(), full.data(),
  121. false);
  122. Manifest::Hash out;
  123. std::copy_n(full.begin(), 16, out.begin());
  124. return out;
  125. }
  126. bool VerifySignature(const std::string& data, const std::string& b64_signature)
  127. {
  128. u8 signature[64]; // ed25519 sig size.
  129. size_t sig_size;
  130. if (mbedtls_base64_decode(signature, sizeof(signature), &sig_size,
  131. reinterpret_cast<const u8*>(b64_signature.data()),
  132. b64_signature.size()) ||
  133. sig_size != sizeof(signature))
  134. {
  135. LogToFile("Invalid base64: %s\n", b64_signature.c_str());
  136. return false;
  137. }
  138. const auto& pub_key = UI::IsTestMode() ? UPDATE_PUB_KEY_TEST : UPDATE_PUB_KEY;
  139. return ed25519_verify(signature, reinterpret_cast<const u8*>(data.data()), data.size(),
  140. pub_key.data());
  141. }
  142. void FlushLog()
  143. {
  144. log_file.Flush();
  145. log_file.Close();
  146. }
  147. void TodoList::Log() const
  148. {
  149. if (to_update.size())
  150. {
  151. LogToFile("Updating:\n");
  152. for (const auto& op : to_update)
  153. {
  154. std::string old_desc =
  155. op.old_hash ? HexEncode(op.old_hash->data(), op.old_hash->size()) : "(new)";
  156. LogToFile(" - %s: %s -> %s\n", op.filename.c_str(), old_desc.c_str(),
  157. HexEncode(op.new_hash.data(), op.new_hash.size()).c_str());
  158. }
  159. }
  160. if (to_delete.size())
  161. {
  162. LogToFile("Deleting:\n");
  163. for (const auto& op : to_delete)
  164. {
  165. LogToFile(" - %s (%s)\n", op.filename.c_str(),
  166. HexEncode(op.old_hash.data(), op.old_hash.size()).c_str());
  167. }
  168. }
  169. }
  170. bool DownloadContent(const std::vector<TodoList::DownloadOp>& to_download,
  171. const std::string& content_base_url, const std::string& temp_path)
  172. {
  173. Common::HttpRequest req(std::chrono::seconds(30), ProgressCallback);
  174. UI::SetTotalMarquee(false);
  175. for (size_t i = 0; i < to_download.size(); i++)
  176. {
  177. UI::SetTotalProgress(static_cast<int>(i + 1), static_cast<int>(to_download.size()));
  178. auto& download = to_download[i];
  179. std::string hash_filename = HexEncode(download.hash.data(), download.hash.size());
  180. // File already exists, skipping
  181. if (File::Exists(temp_path + DIR_SEP + hash_filename))
  182. continue;
  183. UI::SetDescription("Downloading " + download.filename + "... (File " + std::to_string(i + 1) +
  184. " of " + std::to_string(to_download.size()) + ")");
  185. UI::SetCurrentMarquee(false);
  186. // Add slashes where needed.
  187. std::string content_store_path = hash_filename;
  188. content_store_path.insert(4, "/");
  189. content_store_path.insert(2, "/");
  190. std::string url = content_base_url + content_store_path;
  191. LogToFile("Downloading %s ...\n", url.c_str());
  192. auto resp = req.Get(url);
  193. if (!resp)
  194. return false;
  195. UI::SetCurrentMarquee(true);
  196. UI::SetDescription("Verifying " + download.filename + "...");
  197. std::string contents(reinterpret_cast<char*>(resp->data()), resp->size());
  198. std::optional<std::string> maybe_decompressed = GzipInflate(contents);
  199. if (!maybe_decompressed)
  200. return false;
  201. const std::string decompressed = std::move(*maybe_decompressed);
  202. // Check that the downloaded contents have the right hash.
  203. Manifest::Hash contents_hash = ComputeHash(decompressed);
  204. if (contents_hash != download.hash)
  205. {
  206. LogToFile("Wrong hash on downloaded content %s.\n", url.c_str());
  207. return false;
  208. }
  209. const std::string out = temp_path + DIR_SEP + hash_filename;
  210. if (!File::WriteStringToFile(out, decompressed))
  211. {
  212. LogToFile("Could not write cache file %s.\n", out.c_str());
  213. return false;
  214. }
  215. }
  216. return true;
  217. }
  218. bool PlatformVersionCheck(const std::vector<TodoList::UpdateOp>& to_update,
  219. const std::string& install_base_path, const std::string& temp_dir)
  220. {
  221. UI::SetDescription("Checking platform...");
  222. return Platform::VersionCheck(to_update, install_base_path, temp_dir);
  223. }
  224. TodoList ComputeActionsToDo(Manifest this_manifest, Manifest next_manifest)
  225. {
  226. TodoList todo;
  227. // Delete if present in this manifest but not in next manifest.
  228. for (const auto& entry : this_manifest.entries)
  229. {
  230. if (!next_manifest.entries.contains(entry.first))
  231. {
  232. TodoList::DeleteOp del;
  233. del.filename = entry.first;
  234. del.old_hash = entry.second;
  235. todo.to_delete.push_back(std::move(del));
  236. }
  237. }
  238. // Download and update if present in next manifest with different hash from this manifest.
  239. for (const auto& entry : next_manifest.entries)
  240. {
  241. std::optional<Manifest::Hash> old_hash;
  242. const auto& old_entry = this_manifest.entries.find(entry.first);
  243. if (old_entry != this_manifest.entries.end())
  244. old_hash = old_entry->second;
  245. if (!old_hash || *old_hash != entry.second)
  246. {
  247. TodoList::DownloadOp download;
  248. download.filename = entry.first;
  249. download.hash = entry.second;
  250. todo.to_download.push_back(std::move(download));
  251. TodoList::UpdateOp update;
  252. update.filename = entry.first;
  253. update.old_hash = old_hash;
  254. update.new_hash = entry.second;
  255. todo.to_update.push_back(std::move(update));
  256. }
  257. }
  258. return todo;
  259. }
  260. void CleanUpTempDir(const std::string& temp_dir, const TodoList& todo)
  261. {
  262. // This is best-effort cleanup, we ignore most errors.
  263. for (const auto& download : todo.to_download)
  264. File::Delete(temp_dir + DIR_SEP + HexEncode(download.hash.data(), download.hash.size()));
  265. File::DeleteDir(temp_dir);
  266. }
  267. bool BackupFile(const std::string& path)
  268. {
  269. std::string backup_path = path + ".bak";
  270. LogToFile("Backing up existing %s to .bak.\n", path.c_str());
  271. if (!File::Rename(path, backup_path))
  272. {
  273. LogToFile("Cound not rename %s to %s for backup.\n", path.c_str(), backup_path.c_str());
  274. return false;
  275. }
  276. return true;
  277. }
  278. bool DeleteObsoleteFiles(const std::vector<TodoList::DeleteOp>& to_delete,
  279. const std::string& install_base_path)
  280. {
  281. for (const auto& op : to_delete)
  282. {
  283. std::string path = install_base_path + DIR_SEP + op.filename;
  284. if (!File::Exists(path))
  285. {
  286. LogToFile("File %s is already missing.\n", op.filename.c_str());
  287. continue;
  288. }
  289. else
  290. {
  291. std::string contents;
  292. if (!File::ReadFileToString(path, contents))
  293. {
  294. LogToFile("Could not read file planned for deletion: %s.\n", op.filename.c_str());
  295. return false;
  296. }
  297. Manifest::Hash contents_hash = ComputeHash(contents);
  298. if (contents_hash != op.old_hash)
  299. {
  300. if (!BackupFile(path))
  301. return false;
  302. }
  303. File::Delete(path);
  304. }
  305. }
  306. return true;
  307. }
  308. bool UpdateFiles(const std::vector<TodoList::UpdateOp>& to_update,
  309. const std::string& install_base_path, const std::string& temp_path)
  310. {
  311. #ifdef _WIN32
  312. const auto self_path = std::filesystem::path(Common::GetModuleName(nullptr).value());
  313. const auto self_filename = self_path.filename();
  314. #endif
  315. for (const auto& op : to_update)
  316. {
  317. std::string path = install_base_path + DIR_SEP + op.filename;
  318. if (!File::CreateFullPath(path))
  319. {
  320. LogToFile("Could not create directory structure for %s.\n", op.filename.c_str());
  321. return false;
  322. }
  323. #ifndef _WIN32
  324. // TODO: A new updater protocol version is required to properly mark executable files. For
  325. // now, copy executable bits from existing files. This will break for newly added executables.
  326. std::optional<mode_t> permission;
  327. #endif
  328. if (File::Exists(path))
  329. {
  330. #ifndef _WIN32
  331. struct stat file_stats;
  332. if (lstat(path.c_str(), &file_stats) != 0)
  333. continue;
  334. if (S_ISLNK(file_stats.st_mode))
  335. {
  336. LogToFile("%s is symlink, skipping\n", path.c_str());
  337. continue;
  338. }
  339. permission = file_stats.st_mode;
  340. #endif
  341. #ifdef _WIN32
  342. // If incoming file would overwrite the currently executing file, rename ourself to allow the
  343. // overwrite to complete. Renaming ourself while executing is fine, but deleting ourself is
  344. // rather tricky. The best way to handle that would be to execute the newly-placed Updater.exe
  345. // after entire update has completed, and have it delete our relocated executable. For now we
  346. // just let the relocated file hang around.
  347. // It is enough to match based on filename, don't need File/VolumeId etc.
  348. const bool is_self = op.filename == self_filename;
  349. #else
  350. // On other platforms, the renaming is handled by Dolphin before running the Updater.
  351. const bool is_self = false;
  352. #endif
  353. std::string contents;
  354. if (!File::ReadFileToString(path, contents))
  355. {
  356. LogToFile("Could not read existing file %s.\n", op.filename.c_str());
  357. return false;
  358. }
  359. Manifest::Hash contents_hash = ComputeHash(contents);
  360. if (contents_hash == op.new_hash)
  361. {
  362. LogToFile("File %s was already up to date. Partial update?\n", op.filename.c_str());
  363. continue;
  364. }
  365. else if (!op.old_hash || contents_hash != *op.old_hash || is_self)
  366. {
  367. if (!BackupFile(path))
  368. return false;
  369. }
  370. }
  371. // Now we can safely move the new contents to the location.
  372. std::string content_filename = HexEncode(op.new_hash.data(), op.new_hash.size());
  373. LogToFile("Updating file %s from content %s...\n", op.filename.c_str(),
  374. content_filename.c_str());
  375. #ifdef __APPLE__
  376. // macOS caches the code signature of Mach-O executables when they're first loaded.
  377. // Unfortunately, there is a quirk in the kernel with how it handles the cache: if the file is
  378. // simply overwritten, the cache isn't invalidated and the old code signature is used to verify
  379. // the new file. This causes macOS to kill the process with a code signing error. To workaround
  380. // this, we use File::Rename() instead of File::CopyRegularFile(). However, this also means that
  381. // if two files have the same hash, the first file will succeed, but the second file will fail
  382. // because the source file no longer exists. To deal with this, we copy the content file to a
  383. // temporary file and then rename the temporary file to the destination path.
  384. const std::string temporary_file = temp_path + DIR_SEP + "temporary_file";
  385. if (!File::CopyRegularFile(temp_path + DIR_SEP + content_filename, temporary_file))
  386. {
  387. LogToFile("Could not copy %s to %s.\n", content_filename.c_str(), temporary_file.c_str());
  388. return false;
  389. }
  390. if (!File::Rename(temporary_file, path))
  391. #else
  392. if (!File::CopyRegularFile(temp_path + DIR_SEP + content_filename, path))
  393. #endif
  394. {
  395. LogToFile("Could not update file %s.\n", op.filename.c_str());
  396. return false;
  397. }
  398. #ifndef _WIN32
  399. if (permission.has_value() && chmod(path.c_str(), permission.value()) != 0)
  400. return false;
  401. #endif
  402. }
  403. return true;
  404. }
  405. bool PerformUpdate(const TodoList& todo, const std::string& install_base_path,
  406. const std::string& content_base_url, const std::string& temp_path)
  407. {
  408. LogToFile("Starting download step...\n");
  409. if (!DownloadContent(todo.to_download, content_base_url, temp_path))
  410. return false;
  411. LogToFile("Download step completed.\n");
  412. LogToFile("Starting platform version check step...\n");
  413. if (!PlatformVersionCheck(todo.to_update, install_base_path, temp_path))
  414. return false;
  415. LogToFile("Platform version check step completed.\n");
  416. LogToFile("Starting update step...\n");
  417. if (!UpdateFiles(todo.to_update, install_base_path, temp_path))
  418. return false;
  419. LogToFile("Update step completed.\n");
  420. LogToFile("Starting deletion step...\n");
  421. if (!DeleteObsoleteFiles(todo.to_delete, install_base_path))
  422. return false;
  423. LogToFile("Deletion step completed.\n");
  424. return true;
  425. }
  426. void FatalError(const std::string& message)
  427. {
  428. LogToFile("%s\n", message.c_str());
  429. UI::SetVisible(true);
  430. UI::Error(message);
  431. }
  432. std::optional<Manifest> ParseManifest(const std::string& manifest)
  433. {
  434. Manifest parsed;
  435. size_t pos = 0;
  436. while (pos < manifest.size())
  437. {
  438. size_t filename_end_pos = manifest.find('\t', pos);
  439. if (filename_end_pos == std::string::npos)
  440. {
  441. LogToFile("Manifest entry %zu: could not find filename end.\n", parsed.entries.size());
  442. return {};
  443. }
  444. size_t hash_end_pos = manifest.find('\n', filename_end_pos);
  445. if (hash_end_pos == std::string::npos)
  446. {
  447. LogToFile("Manifest entry %zu: could not find hash end.\n", parsed.entries.size());
  448. return {};
  449. }
  450. std::string filename = manifest.substr(pos, filename_end_pos - pos);
  451. std::string hash = manifest.substr(filename_end_pos + 1, hash_end_pos - filename_end_pos - 1);
  452. if (hash.size() != 32)
  453. {
  454. LogToFile("Manifest entry %zu: invalid hash: \"%s\".\n", parsed.entries.size(), hash.c_str());
  455. return {};
  456. }
  457. Manifest::Hash decoded_hash;
  458. if (!HexDecode(hash, decoded_hash.data(), decoded_hash.size()))
  459. {
  460. LogToFile("Manifest entry %zu: invalid hash: \"%s\".\n", parsed.entries.size(), hash.c_str());
  461. return {};
  462. }
  463. parsed.entries[filename] = decoded_hash;
  464. pos = hash_end_pos + 1;
  465. }
  466. return parsed;
  467. }
  468. // Not showing a progress bar here because this part is just too quick
  469. std::optional<Manifest> FetchAndParseManifest(const std::string& url)
  470. {
  471. Common::HttpRequest http;
  472. Common::HttpRequest::Response resp = http.Get(url);
  473. if (!resp)
  474. {
  475. LogToFile("Manifest download failed.\n");
  476. return {};
  477. }
  478. std::string contents(reinterpret_cast<char*>(resp->data()), resp->size());
  479. std::optional<std::string> maybe_decompressed = GzipInflate(contents);
  480. if (!maybe_decompressed)
  481. return {};
  482. std::string decompressed = std::move(*maybe_decompressed);
  483. // Split into manifest and signature.
  484. size_t boundary = decompressed.rfind("\n\n");
  485. if (boundary == std::string::npos)
  486. {
  487. LogToFile("No signature was found in manifest.\n");
  488. return {};
  489. }
  490. std::string signature_block = decompressed.substr(boundary + 2); // 2 for "\n\n".
  491. decompressed.resize(boundary + 1); // 1 to keep the final "\n".
  492. std::vector<std::string> signatures = SplitString(signature_block, '\n');
  493. bool found_valid_signature = false;
  494. for (const auto& signature : signatures)
  495. {
  496. if (VerifySignature(decompressed, signature))
  497. {
  498. found_valid_signature = true;
  499. break;
  500. }
  501. }
  502. if (!found_valid_signature)
  503. {
  504. LogToFile("Could not verify signature of the manifest.\n");
  505. return {};
  506. }
  507. return ParseManifest(decompressed);
  508. }
  509. struct Options
  510. {
  511. std::string this_manifest_url;
  512. std::string next_manifest_url;
  513. std::string content_store_url;
  514. std::string install_base_path;
  515. std::optional<std::string> binary_to_restart;
  516. std::optional<u32> parent_pid;
  517. std::optional<std::string> log_file;
  518. };
  519. std::optional<Options> ParseCommandLine(std::vector<std::string>& args)
  520. {
  521. using optparse::OptionParser;
  522. OptionParser parser =
  523. OptionParser().prog("Dolphin Updater").description("Dolphin Updater binary");
  524. parser.add_option("--this-manifest-url")
  525. .dest("this-manifest-url")
  526. .help("URL to the update manifest for the currently installed version.")
  527. .metavar("URL");
  528. parser.add_option("--next-manifest-url")
  529. .dest("next-manifest-url")
  530. .help("URL to the update manifest for the to-be-installed version.")
  531. .metavar("URL");
  532. parser.add_option("--content-store-url")
  533. .dest("content-store-url")
  534. .help("Base URL of the content store where files to download are stored.")
  535. .metavar("URL");
  536. parser.add_option("--install-base-path")
  537. .dest("install-base-path")
  538. .help("Base path of the Dolphin install to be updated.")
  539. .metavar("PATH");
  540. parser.add_option("--binary-to-restart")
  541. .dest("binary-to-restart")
  542. .help("Binary to restart after the update is over.")
  543. .metavar("PATH");
  544. parser.add_option("--log-file")
  545. .dest("log-file")
  546. .help("File where to log updater debug output.")
  547. .metavar("PATH");
  548. parser.add_option("--parent-pid")
  549. .dest("parent-pid")
  550. .type("int")
  551. .help("(optional) PID of the parent process. The updater will wait for this process to "
  552. "complete before proceeding.")
  553. .metavar("PID");
  554. optparse::Values options = parser.parse_args(args);
  555. Options opts;
  556. // Required arguments.
  557. std::vector<std::string> required{"this-manifest-url", "next-manifest-url", "content-store-url",
  558. "install-base-path"};
  559. for (const auto& req : required)
  560. {
  561. if (!options.is_set(req))
  562. {
  563. parser.print_help();
  564. return {};
  565. }
  566. }
  567. opts.this_manifest_url = options["this-manifest-url"];
  568. opts.next_manifest_url = options["next-manifest-url"];
  569. opts.content_store_url = options["content-store-url"];
  570. opts.install_base_path = options["install-base-path"];
  571. // Optional arguments.
  572. if (options.is_set("binary-to-restart"))
  573. opts.binary_to_restart = options["binary-to-restart"];
  574. if (options.is_set("parent-pid"))
  575. opts.parent_pid = static_cast<u32>(options.get("parent-pid"));
  576. if (options.is_set("log-file"))
  577. opts.log_file = options["log-file"];
  578. return opts;
  579. }
  580. bool RunUpdater(std::vector<std::string> args)
  581. {
  582. std::optional<Options> maybe_opts = ParseCommandLine(args);
  583. if (!maybe_opts)
  584. {
  585. return false;
  586. }
  587. UI::Init();
  588. UI::SetVisible(false);
  589. Common::ScopeGuard ui_guard{[] { UI::Stop(); }};
  590. Options opts = std::move(*maybe_opts);
  591. if (opts.log_file)
  592. {
  593. if (!log_file.Open(opts.log_file.value(), "w"))
  594. log_file.SetHandle(stderr);
  595. else
  596. atexit(FlushLog);
  597. }
  598. LogToFile("Updating from: %s\n", opts.this_manifest_url.c_str());
  599. LogToFile("Updating to: %s\n", opts.next_manifest_url.c_str());
  600. LogToFile("Install path: %s\n", opts.install_base_path.c_str());
  601. if (!File::IsDirectory(opts.install_base_path))
  602. {
  603. FatalError("Cannot find install base path, or not a directory.");
  604. return false;
  605. }
  606. if (opts.parent_pid)
  607. {
  608. LogToFile("Waiting for parent PID %d to complete...\n", *opts.parent_pid);
  609. auto pid = opts.parent_pid.value();
  610. UI::WaitForPID(static_cast<u32>(pid));
  611. LogToFile("Completed! Proceeding with update.\n");
  612. }
  613. UI::SetVisible(true);
  614. UI::SetDescription("Fetching and parsing manifests...");
  615. Manifest this_manifest, next_manifest;
  616. {
  617. std::optional<Manifest> maybe_manifest = FetchAndParseManifest(opts.this_manifest_url);
  618. if (!maybe_manifest)
  619. {
  620. FatalError("Could not fetch current manifest. Aborting.");
  621. return false;
  622. }
  623. this_manifest = std::move(*maybe_manifest);
  624. maybe_manifest = FetchAndParseManifest(opts.next_manifest_url);
  625. if (!maybe_manifest)
  626. {
  627. FatalError("Could not fetch next manifest. Aborting.");
  628. return false;
  629. }
  630. next_manifest = std::move(*maybe_manifest);
  631. }
  632. UI::SetDescription("Computing what to do...");
  633. TodoList todo = ComputeActionsToDo(this_manifest, next_manifest);
  634. todo.Log();
  635. std::string temp_dir = File::CreateTempDir();
  636. if (temp_dir.empty())
  637. {
  638. FatalError("Could not create temporary directory. Aborting.");
  639. return false;
  640. }
  641. UI::SetDescription("Performing Update...");
  642. bool ok = PerformUpdate(todo, opts.install_base_path, opts.content_store_url, temp_dir);
  643. CleanUpTempDir(temp_dir, todo);
  644. if (!ok)
  645. {
  646. FatalError("Failed to apply the update.");
  647. return false;
  648. }
  649. UI::ResetCurrentProgress();
  650. UI::ResetTotalProgress();
  651. UI::SetCurrentMarquee(false);
  652. UI::SetTotalMarquee(false);
  653. UI::SetCurrentProgress(1, 1);
  654. UI::SetTotalProgress(1, 1);
  655. UI::SetDescription("Done!");
  656. // Let the user process that we are done.
  657. UI::Sleep(1);
  658. if (opts.binary_to_restart)
  659. {
  660. UI::LaunchApplication(opts.binary_to_restart.value());
  661. }
  662. return true;
  663. }