Debian Codegraph @

Source/Core/UpdaterCommon/UpdaterCommon.cpp

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