From 5eae6090693ddb5adf056be45e50922bd90a647e Mon Sep 17 00:00:00 2001 From: N2614 Date: Wed, 9 Apr 2014 02:32:38 +0000 Subject: [PATCH] =?UTF-8?q?=E4=B8=8D=E8=A6=81=E3=81=AA=E3=83=95=E3=82=A1?= =?UTF-8?q?=E3=82=A4=E3=83=AB=E3=83=BB=E3=82=B3=E3=83=BC=E3=83=89=E3=82=92?= =?UTF-8?q?=E5=89=8A=E9=99=A4=20NUP=E3=81=AE=E3=81=BF=E8=A1=8C=E3=81=86?= =?UTF-8?q?=E3=82=88=E3=81=86=E3=81=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git-svn-id: file:///Volumes/Transfer/gigaleak_20231201/2020-05-23%20-%20ctr.7z%20+%20svn_v1.068.zip/ctr/svn/ctr_Repair@779 385bec56-5757-e545-9c3a-d8741f4650f1 --- .../sources/NetworkUpdater/ActCompleter.cpp | 92 - .../sources/NetworkUpdater/ActCompleter.h | 46 - .../sources/NetworkUpdater/ConsoleRestore.cpp | 146 +- .../sources/NetworkUpdater/Controller.cpp | 1751 +---------------- .../sources/NetworkUpdater/Controller.h | 8 +- .../sources/NetworkUpdater/Importer.cpp | 1609 +-------------- .../sources/NetworkUpdater/Importer.h | 90 +- .../sources/NetworkUpdater/NtpClient.cpp | 309 --- .../sources/NetworkUpdater/NtpClient.h | 33 - .../sources/NetworkUpdater/OMakefile | 12 +- .../NetworkUpdater/PreinstallImporter.cpp | 83 - .../NetworkUpdater/PreinstallImporter.h | 42 - .../NetworkUpdater/RegionIdModifier.cpp | 153 -- .../sources/NetworkUpdater/RegionIdModifier.h | 89 - .../sources/NetworkUpdater/Shop.cpp | 503 ----- .../sources/NetworkUpdater/Shop.h | 68 - .../NetworkUpdater/TitleDownloader.cpp | 441 ----- .../sources/NetworkUpdater/TitleDownloader.h | 97 - 18 files changed, 98 insertions(+), 5474 deletions(-) delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.h delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.h delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.h delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.h delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/Shop.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/Shop.h delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.cpp delete mode 100644 trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.h diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.cpp deleted file mode 100644 index 73f8576..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: ActCompleter.cpp - - Copyright (C)2013 Nintendo Co., Ltd. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#include "ActCompleter.h" -#include "Util.h" -#include "CommonLogger.h" -#include -#include -#include -#include - -namespace ConsoleRestore -{ -nn::Result ActCompleter::s_Result; -const size_t ActCompleter::STACK_SIZE; -nn::os::Thread ActCompleter::s_Thread; -nn::os::StackBuffer ActCompleter::s_ThreadStack; - - -ActCompleter::ActCompleter() -{ - // TODO 自動生成されたコンストラクター・スタブ - -} - -ActCompleter::~ActCompleter() -{ - // TODO Auto-generated destructor stub -} - -nn::Result ActCompleter::GetResult() -{ - return s_Result; -} - -void ActCompleter::Start() -{ - s_Thread.Start(Exec, s_ThreadStack); -} - -bool ActCompleter::IsFinished() -{ - return s_Thread.IsValid() && !s_Thread.IsAlive(); -} - -void ActCompleter::Finish() -{ - s_Thread.Join(); - s_Thread.Finalize(); -} - -void ActCompleter::Exec() -{ - s_Result = ExecImpl(); -} - -nn::Result ActCompleter::ExecImpl() -{ - if(!nn::ac::IsConnected()) - { - NN_UTIL_RETURN_IF_FAILED( - common::InitializeNetwork()); - } - - NN_UTIL_RETURN_IF_FAILED( - nn::act::InitializeAdmin()); - - NN_UTIL_RETURN_IF_FAILED( - nn::act::CompleteTransfer()); - - NN_UTIL_RETURN_IF_FAILED( - nn::act::FinalizeAdmin()); - - NN_UTIL_RETURN_IF_FAILED( - common::FinalizeNetwork()); - - return nn::ResultSuccess(); -} - -} /* namespace ConsoleRestore */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.h b/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.h deleted file mode 100644 index d4b7f91..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/ActCompleter.h +++ /dev/null @@ -1,46 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: ActCompleter.h - - Copyright (C)2013 Nintendo Co., Ltd. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#ifndef ACTCOMPLETER_H_ -#define ACTCOMPLETER_H_ - -#include - -namespace ConsoleRestore -{ - -class ActCompleter -{ -public: - ActCompleter(); - virtual ~ActCompleter(); - - static nn::Result GetResult(); - static void Start(); - static bool IsFinished(); - static void Finish(); - -private: - static void Exec(); - static nn::Result ExecImpl(); - static nn::Result s_Result; - static const size_t STACK_SIZE = 0x1000; - static nn::os::Thread s_Thread; - static nn::os::StackBuffer s_ThreadStack; - -}; - -} /* namespace ConsoleRestore */ -#endif /* ACTCOMPLETER_H_ */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/ConsoleRestore.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/ConsoleRestore.cpp index 23e577c..daeac99 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/ConsoleRestore.cpp +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/ConsoleRestore.cpp @@ -48,7 +48,6 @@ #include "ResFont.h" #include "HardwareStateManager.h" #include "OperationMessage.h" -#include "QrImage.h" // バージョン表示用 #include "version.h" @@ -181,7 +180,6 @@ extern "C" void nnMain(void) bool flip = false; - bool qr = false; InitializeState(); for(;;) @@ -199,14 +197,6 @@ extern "C" void nnMain(void) { nextStep = true; } - // YボタンでBMS操作完了 - // Yボタンで強制プリインストール - if(padStatus.trigger & nn::hid::BUTTON_Y) - { - operateBmsDone = true; - forcePreinstall = true; - unregister = true; - } // LまたはRボタンで上下画面フリップ if(padStatus.trigger & nn::hid::BUTTON_R || @@ -215,14 +205,6 @@ extern "C" void nnMain(void) flip = !flip; } - - - // 左ボタンでQR切替 - if(padStatus.trigger & nn::hid::BUTTON_RIGHT) - { - qr = !qr; - } - // コンソールスクロール if(padStatus.hold & nn::hid::BUTTON_UP) { @@ -252,108 +234,42 @@ extern "C" void nnMain(void) common::OperationMessage operationMessage; - if(qr) + ControlState(manager, operationMessage, nextStep, operateBmsDone, forcePreinstall, unregister); + + nn::util::FloatColor titleColor; + titleColor.r = 0.2f; + titleColor.g = 0.2f; + titleColor.b = 0.8f; + + // 上画面表示 + common::DrawSystemState("CTR Network Updater", s_RenderSystem, titleColor, flip, adapterState, + s_HwUtility.GetCupMajorVersion(), s_HwUtility.GetCupMinorVersion(), s_HwUtility.GetCupMicroVersion(), + s_HwUtility.GetNupVersion(), s_HwUtility.GetBatteryRemain(), s_HwUtility.GetInfraDeviceId(), + s_HwUtility.GetFriendcode(), GetProgress(), IsRestoreFailed(), IsRestoreSucceeded(), false, + s_HwUtility.GetMacAddress(), operationMessage, s_HwUtility.GetRegion(), s_HwUtility.GetSerialNumber(), + s_HwUtility.HasReadFriendCode(), s_HwUtility.IsWifiOn()); + + s_RenderSystem.SwapBuffers(); + + // デフォルトで下画面に描画するもの + s_RenderSystem.SetRenderTarget(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip)); + if (IsRestoreSucceeded()) { - u8 serial[nn::cfg::CTR::CFG_SECURE_INFO_SERIAL_NO_LEN]; - s_HwUtility.GetSerialNumberWithoutCD(serial); - common::QrImage::Draw(s_RenderSystem, s_HwUtility.GetInfraDeviceId(), serial, flip); + s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), SUCCESS_COLOR); + } + else if (IsRestoreFailed()) + { + s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), FAIL_COLOR); } else { - ControlState(manager, operationMessage, nextStep, operateBmsDone, forcePreinstall, unregister); - - nn::util::FloatColor titleColor; - - if (GetRestoreMode() == RESTORE_MODE_RESTORE) - { - titleColor.r = 0.1f; - titleColor.g = 0.25f; - titleColor.b = 0.1f; - } - else if (GetRestoreMode() == RESTORE_MODE_NUP_ONLY) - { - titleColor.r = 0.35f; - titleColor.g = 0.35f; - titleColor.b = 0.f; - } - else if (GetRestoreMode() == RESTORE_MODE_GET_IVS) - { - titleColor.r = 1.0f; - titleColor.g = 0.2f; - titleColor.b = 0.2f; - } - else if (GetRestoreMode() == RESTORE_MODE_CHECK_SD) - { - titleColor.r = 0.2f; - titleColor.g = 0.2f; - titleColor.b = 1.2f; - } - else if (GetRestoreMode() == RESTORE_MODE_DOWNLOAD_PREINSTALL) - { - titleColor.r = 1.0f; - titleColor.g = 0.55f; - titleColor.b = 1.0f; - } - - // 上画面表示 - common::DrawSystemState("CTR Console Restore", s_RenderSystem, titleColor, flip, adapterState, - s_HwUtility.GetCupMajorVersion(), s_HwUtility.GetCupMinorVersion(), - s_HwUtility.GetCupMicroVersion(), s_HwUtility.GetNupVersion(), s_HwUtility.GetBatteryRemain(), - s_HwUtility.GetInfraDeviceId(), s_HwUtility.GetFriendcode(), GetProgress(), IsRestoreFailed(), - IsRestoreSucceeded(), false, s_HwUtility.GetMacAddress(), operationMessage, s_HwUtility.GetRegion(), - s_HwUtility.GetSerialNumber(), s_HwUtility.HasReadFriendCode(), s_HwUtility.IsWifiOn()); - - if (GetRestoreMode() != RESTORE_MODE_RESTORE) - { - const u8 spaceSize = 10; - const u8 lineBottom = 23; - const u32 screenWidth = 400; - - s_RenderSystem.SetColor(1.f, 1.f, 1.f); - - if (GetRestoreMode() == RESTORE_MODE_NUP_ONLY) - { - s_RenderSystem.DrawText(0, lineBottom * spaceSize, "NUP-Only Mode"); - } - else if (GetRestoreMode() == RESTORE_MODE_GET_IVS) - { - s_RenderSystem.DrawText(0, lineBottom * spaceSize, "GET-SDCI Mode"); - } - else if (GetRestoreMode() == RESTORE_MODE_CHECK_SD) - { - s_RenderSystem.DrawText(0, lineBottom * spaceSize, "CHECK-SD Mode"); - } - else if (GetRestoreMode() == RESTORE_MODE_DOWNLOAD_PREINSTALL) - { - s_RenderSystem.DrawText(0, lineBottom * spaceSize, "DL_PREINATALL Mode"); - } - - s_RenderSystem.SetColor(titleColor.r, titleColor.g, titleColor.b); - s_RenderSystem.FillRectangle(0, lineBottom * spaceSize, screenWidth, spaceSize); - s_RenderSystem.SetColor(1.f, 1.f, 1.f); - } - s_RenderSystem.SwapBuffers(); - - // デフォルトで下画面に描画するもの - s_RenderSystem.SetRenderTarget(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip)); - if (IsRestoreSucceeded()) - { - s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), SUCCESS_COLOR); - } - else if (IsRestoreFailed()) - { - s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), FAIL_COLOR); - } - else - { - s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), NORMAL_COLOR); - } - s_RenderSystem.Clear(); - s_RenderSystem.SetColor(1.f, 1.f, 1.f); - - common::Logger::GetLoggerInstance()->DrawConsole(); - s_RenderSystem.SwapBuffers(); + s_RenderSystem.SetClearColor(common::Util::GetRenderTarget(NN_GX_DISPLAY1, flip), NORMAL_COLOR); } + s_RenderSystem.Clear(); + s_RenderSystem.SetColor(1.f, 1.f, 1.f); + + common::Logger::GetLoggerInstance()->DrawConsole(); + s_RenderSystem.SwapBuffers(); s_RenderSystem.WaitVsync(NN_GX_DISPLAY_BOTH); diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.cpp index 6df956c..e092dd6 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.cpp +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.cpp @@ -30,11 +30,6 @@ #include "CommonLogger.h" #include "Importer.h" #include "Updater.h" -#include "NtpClient.h" -#include "TitleDownloader.h" -#include "Shop.h" -#include "Util.h" -#include "ActCompleter.h" namespace ConsoleRestore { @@ -46,18 +41,6 @@ namespace bool s_ReadSettingDone = false; // インターネット設定を読んだ結果 bool s_ReadSettingIsSuccess = false; -// NUP専用モードかどうか -bool s_NupOnlyMode = false; -// IVS取得専用モードかどうか -bool s_GetIvsOnlyMode = false; -// SDカード確認専用モード -bool s_CheckSdOnlyMode = false; -// NUPスキップモードかどうか -bool s_SkipNupMode = false; -// プリインストール書き込みモードかどうか -bool s_DownloadPreinstallMode = false; -// 強制プリインストール書き込みモードかどうか -bool s_ForceDownloadPreinstall = false; // 失敗サウンドを鳴らしたかどうか bool s_PlayedFailSound = false; @@ -66,33 +49,6 @@ bool s_PlayedFailSound = false; bool s_ExecuteFgNup = false; // FGNUPを何回リトライしたか u32 s_FgNupRetryCount = 0; -// 時計同期モードかどうか -bool s_IsSyncClock = false; -// TWLタイトルのダウンロードを開始したかどうか -bool s_ExecuteTwlTitleDownload = false; -// TWLタイトルのダウンロードを何回リトライしたか -u32 s_TwlTitleDownloadRetryCount = 0; - -// NNA転送完了を何回リトライしたか -u32 s_NNATransferRetryCount = 0; - -// プリインストールタイトルのダウンロード準備を開始したかどうか -bool s_ExecutePreparePreinstallTitleDownload = false; -// プリインストールタイトルのダウンロード準備を何回リトライしたか -u32 s_PreparePreinstallTitleDownloadRetryCount = 0; - - -// プリインストールタイトルのダウンロードを開始したかどうか -bool s_ExecutePreinstallTitleDownload = false; -// プリインストールタイトルのダウンロードを何回リトライしたか -u32 s_PreinstallTitleDownloadRetryCount = 0; -// プリインストールタイトルのダウンロードが成功したかどうか -bool s_PreinstallTitleDownloadSuccess = false; - -// ショップ処理を開始したかどうか -bool s_ShopOperationExecuted[SHOP_OPERATION_NUM_MAX]; -// ショップ処理を何回リトライしたか -u32 s_ShopOperationRetryCount[SHOP_OPERATION_NUM_MAX]; void PutAliveMessage(common::OperationMessage& operationMessage, const char* str); bool CheckAndReadAPSetting(common::OperationMessage& operationMessage); @@ -102,80 +58,15 @@ bool NeedsAcAdater(common::HardwareStateManager& manager) return manager.IsBatteryLower() && !manager.IsAdapterConnected(); } -bool HasValidRtcData() -{ - return !s_CheckSdOnlyMode && !s_NupOnlyMode && !s_GetIvsOnlyMode && !s_DownloadPreinstallMode; -} - -bool HasDeviceIdFile() -{ - return HasValidRtcData(); -} - typedef enum RestoreState { STARTUP, // 初期値 - INITIALIZE_CONSOLE, // セーブデータ領域のNAND初期化を行う - SERIAL_IS_NOT_IN_SD, // シリアルナンバーファイルがSDカードにないことを表示 WAIT_START_UPDATE, // アップデート開始入力待ち - WAIT_START_IMPORT, // 書き込み開始入力待ち - WAIT_START_SYNC_CLOCK, // 時計合わせ開始入力待ち - IMPORT_RTC, // RTC同期 UPDATE_IN_PROGRESS, // アップデート中 UPDATE_DONE, // アップデート完了 - NUP_ONLY_WAIT_SD_EJECT, // NUP_ONLYモードでSDカード抜き待ち - NUP_ONLY_WAIT_NEXT, // NUP_ONLYモードでキー入力待ち - WAIT_START_TRANSFER_ACCOUNT, // アカウント転送開始入力まち - TRANSFER_ACCOUNT, // アカウント転送を完了させる - TRANSFER_ACCOUNT_DONE, // アカウント転送完了 - DOWNLOAD_IVS, // インフラからIVSを取得する - DOWNLOAD_IVS_DONE, // インフラからIVSを取得完了 - DOWNLOAD_IVS_WAIT_NEXT, // IVS取得モードでキー入力待ち - CHECK_IVS, // IVSとSDカードのセーブデータディレクトリの一致を確認 - CHECK_SD_DIRECTORY, // SDカードのIVS依存ディレクトリを探す - CHECK_SD_DIRECTORY_SUCCESS, // SDカードのIVS依存ディレクトリチェック完了 - CHECK_SD_DIRECTORY_FAIL, // SDカードのIVS依存ディレクトリが見つからなかった - WAIT_START_DELETE_ACCOUNT, // ショップアカウント削除開始入力待ち, - DELETE_ACCOUNT, // ショップアカウントを削除する - DELETE_ACCOUNT_DONE, // ショップアカウント削除完了 - SYNC_TICKET, // eTicketを同期する - READ_FILELIST, // ファイル一覧の読み込み - RESTORE_TWL_NAND, // TWL NANDの書き込み中 - RESTORE_TWL_SOUND, // TWLサウンドの書き込み中 - RESTORE_TWL_PHOTO, // TWL写真の書き込み中 - RESTORE_IN_PROGRESS, // 書き込み中 - POST_RESTORE, // 書き込み後の処理 - RESTORE_DONE, // 書き込み完了 - REBOOTING, // 再起動を行う - ERASE, // 削除処理を行う - COMPLETE_ACT, // actアカウント移行完了処理を行う - COMPLETE_ACT_WAIT, // actアカウント移行完了処理の完了待ち - RESTORE_CAL, // cfgの一部をcal値で上書きする - REPAIR_SIMPLE_ADDRESS_ID, // 本ツールで過去に破壊されたSimpleAddress.idを修正する - TIME_ADJUST, // 時計あわせを行う - DOWNLOAD_TWL, // TWLアプリ本体をダウンロードする - WAIT_SD_EJECT, // SDカードぬき待ち - ALL_DONE, // すべて完了 - INITIALIZE_AND_SHUTDOWN, // 本体初期化後にシャットダウン中 + SHUTDOWN, // シャットダウン FAIL, // 失敗 - // プリインストールダウンロードモード - PREINSTALL_WAIT_START_UPDATE, // NUP開始待ち - PREINSTALL_WAIT_SYNC_TICKET, // 開始ボタン待ち - PREINSTALL_DELETE_PERSONALIZED_TICKET, // Personalized eTicketの削除 - PREINSTALL_WAIT_USER_SD_INSERT, // ユーザSD挿入待ち - PREINSTALL_WAIT_USER_SD_INSERT_WAIT_NEXT, // ユーザSD挿入後Aボタン待ち - PREINSTALL_CHECK_USER_SD_INSERT, // ユーザSDの挿入チェック - PREINSTALL_CHECK_USER_SD, // ユーザSDのチェック - PREINSTALL_CHECK_USER_SD_ALREADY_INITIALIZED, // ユーザSDのチェック、既に初期化済み - PREINSTALL_CHECK_SD_FAIL, // ユーザSDのチェック失敗 - PREINSTALL_FAIL_CHECK_REPAIR_SD, // ユーザSDのチェック失敗後の修理用SDのチェック - PREINSTALL_DOWNLOAD_APP, // アプリダウンロード - PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE, // アプリダウンロード失敗、空き容量不足 - PREINSTALL_WAIT_USER_SD_EJECT, // ユーザSD抜き出し待ち - PREINSTALL_CHECK_REPAIR_SD_WAIT_NEXT, // 修理用SDのチェック・Aボタン待ち - PREINSTALL_CHECK_REPAIR_SD, // 修理用SDのチェック - RESTORE_STATE_MAX } RestoreState; @@ -217,48 +108,15 @@ void PlayAnnotationSound(AnnotationSound index) break;\ }\ - -// SD挿抜が起こらなかった時のみ次の状態に遷移する -void ChangeState(RestoreState saved, RestoreState& current, RestoreState next) -{ - if(saved == current) - { - current = next; - s_PlayedCursorSound[next] = false; - } -} - // Restore状態管理 RestoreState s_RestoreState = STARTUP; // Restoreモード管理 -RestoreMode s_RestoreMode = RESTORE_MODE_RESTORE; +RestoreMode s_RestoreMode = RESTORE_MODE_NUP_WITHOUT_REBOOT; void CheckSdInserted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); void CheckAcAdapter(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); void CheckSdWritable(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); void CheckApSetting(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckNupExecuted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckDownloadIvs(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckAccountDeleted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckAccountTransfered(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckWriteFinished(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckReadIvs(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckConsoleInitialized(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckExistsSerialNumber(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckIvsinSd(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); -void CheckRegioinSd(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep); - -bool DisplaySerialNumberinSD(common::OperationMessage& message) -{ - u8 serial[nn::cfg::CTR::CFG_SECURE_INFO_SERIAL_NO_LEN]; - COMMON_LOGGER_RETURN_FALSE_IF_FAILED( - ReadSerialNumber(serial)); - - ::std::string serialStr(reinterpret_cast(serial)); - message.Add((::std::string("Serial Number in SD : ") + serialStr).c_str()); - return true; -} - // SDカード挿入チェック void CheckSdInserted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) @@ -314,7 +172,7 @@ void CheckApSetting(common::HardwareStateManager& manager, common::OperationMess if (CheckAndReadAPSetting(message)) { - s_RestoreState = IMPORT_RTC; + s_RestoreState = WAIT_START_UPDATE; } else { @@ -322,374 +180,6 @@ void CheckApSetting(common::HardwareStateManager& manager, common::OperationMess } } -// NUP済みかどうかチェック -void CheckNupExecuted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - if (common::ExistsUpdateCheckedFile()) - { - if (s_NupOnlyMode) - { - s_RestoreState = WAIT_START_DELETE_ACCOUNT; - } - else if(s_DownloadPreinstallMode) - { - s_RestoreState = PREINSTALL_WAIT_SYNC_TICKET; - } - else - { - CheckAccountDeleted(manager, message, goNextStep); - } - } - else - { - // NUPを実行 - if (CheckAndReadAPSetting(message)) - { - if (nn::nwm::CTR::IsWifiOn()) - { - if(s_DownloadPreinstallMode) - { - s_RestoreState = PREINSTALL_WAIT_START_UPDATE; - } - else - { - // ネットワークアップデートを行う - s_RestoreState = WAIT_START_UPDATE; - } - } - else - { - PlayAnnotationSound(ANNOTATION_WIFI_OFF); - message.Add("Wireless is Off\n"); - s_RestoreState = STARTUP; - } - } - } -} - -// インフラからIVS取得済みかチェック -void CheckDownloadIvs(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - NN_UNUSED_VAR(message); - NN_UNUSED_VAR(goNextStep); - - // IVS取得確認ファイルがあるか? - if (common::ExistsDownloadIvsCheckedFile()) - { - if(s_GetIvsOnlyMode) - { - s_RestoreState = DOWNLOAD_IVS_WAIT_NEXT; - } - else - { - CheckWriteFinished(manager, message, goNextStep); - } - } - else - { - COMMON_LOGGER("Download SDCI\n"); - s_RestoreState = DOWNLOAD_IVS; - } - -} - -// アカウント削除済みかチェック -void CheckAccountDeleted(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - // アカウント削除確認ファイルがあるか? - if (common::ExistsDeleteAccountChecked()) - { - CheckAccountTransfered(manager, message, goNextStep); - } - else - { - if(HasDeviceIdFile()) - { - if (ExistsDeviceIdFile().IsFailure()) - { - // 異常なのでFAIL - COMMON_LOGGER("Can't Read Device Id!!"); - s_RestoreState = FAIL; - return; - } - - // 同一本体下記書き戻しの場合はアカウント削除しない - if (EqualsDeviceIdFileandDeviceId(manager)) - { - CheckAccountTransfered(manager, message, goNextStep); - } - else - { - s_RestoreState = WAIT_START_DELETE_ACCOUNT; - } - } - else - { - s_RestoreState = WAIT_START_DELETE_ACCOUNT; - } - } -} - -// アカウント移行済みかチェック -void CheckAccountTransfered(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - // アカウント移行確認ファイルがあるか? - if (common::ExistsTransferAccountChecked()) - { - CheckDownloadIvs(manager, message, goNextStep); - } - else - { - s_RestoreState = WAIT_START_TRANSFER_ACCOUNT; - } -} - -// 書き込み完了かどうかチェック -void CheckWriteFinished(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - NN_UNUSED_VAR(goNextStep); - - // SDカードに書き込み完了ファイルがあるか? - if (common::ExistsWriteFinishedFile()) - { - if (CheckAndReadAPSetting(message)) - { - if (nn::nwm::CTR::IsWifiOn()) - { - // 削除処理を行う - s_RestoreState = WAIT_START_SYNC_CLOCK; - } - else - { - PlayAnnotationSound(ANNOTATION_WIFI_OFF); - message.Add("Wireless is Off\n"); - } - } - } - else - { - CheckReadIvs(manager, message, goNextStep); - } -} - -// IVSを読めるかどうかチェック -void CheckReadIvs(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - // IVSを読めるか? - if (manager.CanReadIvs()) - { - CheckConsoleInitialized(manager, message, goNextStep); - } - else - { - s_RestoreState = FAIL; - COMMON_LOGGER("Can't Read SDCI!!"); - } -} - -// 本体初期化済みかどうかチェック -void CheckConsoleInitialized(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - // 本体初期化完了ファイルがあるか? - if (common::ExistsConsoleInitializedFile()) - { - CheckRegioinSd(manager, message, goNextStep); - } - else - { - CheckIvsinSd(manager, message, goNextStep); - } -} - -// シリアルナンバーがあるかどうかチェック -void CheckExistsSerialNumber(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - NN_UNUSED_VAR(manager); - NN_UNUSED_VAR(message); - NN_UNUSED_VAR(goNextStep); - - - // SDカードにシリアルナンバーがあるか? - if (common::ExistsSerialNumberFile()) - { - u8 serial[nn::cfg::CTR::CFG_SECURE_INFO_SERIAL_NO_LEN]; - nn::Result result = ReadSerialNumber(serial); - if (result.IsSuccess()) - { - s_RestoreState = WAIT_START_IMPORT; - } - else - { - s_RestoreState = FAIL; - } - } - else - { - COMMON_LOGGER("Can't Read Serial Number in SD Card!!\n"); - s_RestoreState = SERIAL_IS_NOT_IN_SD; - } -} - -// SDカードにIVSがあるかどうかチェック -void CheckIvsinSd(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - NN_UNUSED_VAR(manager); - NN_UNUSED_VAR(message); - NN_UNUSED_VAR(goNextStep); - - if (common::ExistsIVSFile()) - { - s_RestoreState = INITIALIZE_CONSOLE; - } - else - { - // 移行不能なのでFAIL - COMMON_LOGGER("Can't Read SDCI in SD Card!!\n"); - s_RestoreState = FAIL; - } -} - -// SDカードにリージョンデータがあるかどうかチェック -void CheckRegioinSd(common::HardwareStateManager& manager, common::OperationMessage& message, bool& goNextStep) -{ - NN_UNUSED_VAR(message); - NN_UNUSED_VAR(goNextStep); - - // SDカードにリージョンデータがあるか? - if (common::ExistsRegionData()) - { - // リージョンデータは一致しているか? - if (EqualsRegionDataandRegion().IsFailure()) - { - COMMON_LOGGER("Current Region and Region in SD differ!!\n"); - s_RestoreState = FAIL; - } - else - { - CheckExistsSerialNumber(manager, message, goNextStep); - } - - } - else - { - // 移行不能なのでFAIL - COMMON_LOGGER("Can't Read Region in SD Card!!\n"); - s_RestoreState = FAIL; - } -} - -void ShopOperationSuccess(ShopOperation op, const char* logMessage, RestoreState nextState) -{ - COMMON_LOGGER("%s", logMessage); - if (op == SHOP_OPERATION_UNREGISTER || op == SHOP_OPERATION_FORCE_UNREGISTER) - { - CreateDeleteAccountFinishedFile(); - } - else if (op == SHOP_OPERATION_GET_IVS) - { - CreateTransferAccountFinishedFile(); - CreateDownloadIvsFinishedFile(); - } - - s_RestoreState = nextState; - -} - -void ShopOperationSingleTemplate( - common::HardwareStateManager& manager, - common::OperationMessage& message, - ShopOperation op, - const char* aliveMessage, - const char* logMessage, - const char* retryLogMessage, - RestoreState nextState - ) -{ - // ACアダプタが必要か? - if (NeedsAcAdater(manager)) - { - message.Add("Connect AC Adapter!!"); - } - - // アップデートを行う - if (!s_ShopOperationExecuted[op]) - { - if (ImportCountryLanguageData().IsSuccess()) - { - StartShopOperationSingle(op); - s_ShopOperationExecuted[op] = true; - } - else - { - s_RestoreState = FAIL; - } - } - - // 動いていることを表示 - { - PutAliveMessage(message, aliveMessage); - } - - if (IsShopOperationSingleFinished()) - { - FinalizeShopOperationSingle(); - // エラーがあったら表示する - if (GetShopOperationSingleResult().IsSuccess()) - { - ShopOperationSuccess(op, logMessage, nextState); - } - // IVSがアップロードされていない場合もあるため - // IVSを取得できない状況も成功として扱う - // IVSサイズが違う場合も成功として扱う - else if(op == SHOP_OPERATION_GET_IVS && ( GetShopOperationSingleResult() == nn::nim::ResultCannotGetIvs() || - GetShopOperationSingleResult() == nn::nim::ResultInvalidData() - )) - { - ShopOperationSuccess(op, logMessage, nextState); - } - else if(op == SHOP_OPERATION_CONNECT && nextState == TRANSFER_ACCOUNT_DONE && - GetShopOperationSingleResult() == nn::nim::ResultNeedGetIvs()) - - { - NN_LOG("ResultNeedGetIvs\n"); - ShopOperationSuccess(op, logMessage, nextState); - } - else - { - if (GetShopOperationSingleResult().IsFailure()) - { - if (GetShopOperationSingleResult() == nn::ac::ResultFailedConnectAp()) - { - COMMON_LOGGER("Failed Connect AccesPoint."); - nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromSeconds(5)); - } - - - // APが見つからない - if (GetUpdateResult() == nn::ac::ResultNotFoundAccessPoint()) - { - COMMON_LOGGER("No Access Point Found!"); - } - } - - if (s_ShopOperationRetryCount[op]++ < RETRY_MAX) - { - // エラーのためやり直す - COMMON_LOGGER_RESULT_IF_FAILED(GetShopOperationSingleResult()); - COMMON_LOGGER("%s %d\n", retryLogMessage, s_ShopOperationRetryCount[op]); - - // スレッドを作るとこからやり直し - s_ShopOperationExecuted[op] = false; - } - else - { - s_RestoreState = FAIL; - } - } - - } -} - void UpdateOperation(common::HardwareStateManager& manager, common::OperationMessage& message, RestoreState nextState) { // ACアダプタが必要か? @@ -735,8 +225,7 @@ void UpdateOperation(common::HardwareStateManager& manager, common::OperationMes COMMON_LOGGER("Network Update Finished.\n"); if(nextState == UPDATE_DONE) { - // アップデート完了ファイルを作成 - CreateUpdateFinishedFile(); + } s_RestoreState = nextState; @@ -776,42 +265,7 @@ bool CheckAndReadAPSetting(common::OperationMessage& operationMessage) if (!s_ReadSettingDone) { s_ReadSettingDone = true; - s_ReadSettingIsSuccess = ReadSetting(&s_NupOnlyMode, &s_GetIvsOnlyMode, &s_CheckSdOnlyMode, &s_SkipNupMode, &s_DownloadPreinstallMode); - } - - if (s_NupOnlyMode && s_GetIvsOnlyMode - || s_GetIvsOnlyMode && s_CheckSdOnlyMode - || s_CheckSdOnlyMode && s_NupOnlyMode) - { - operationMessage.Add("Only one special mode setting is valid!!"); - s_ReadSettingIsSuccess = false; - } - else if(s_NupOnlyMode && s_SkipNupMode) - { - operationMessage.Add("Both NUP_ONLY and SKIP_NUP are described!!"); - s_ReadSettingIsSuccess = false; - } - else - { - if (s_NupOnlyMode) - { - s_RestoreMode = RESTORE_MODE_NUP_ONLY; - } - - if (s_GetIvsOnlyMode) - { - s_RestoreMode = RESTORE_MODE_GET_IVS; - } - - if(s_CheckSdOnlyMode) - { - s_RestoreMode = RESTORE_MODE_CHECK_SD; - } - - if(s_DownloadPreinstallMode) - { - s_RestoreMode = RESTORE_MODE_DOWNLOAD_PREINSTALL; - } + s_ReadSettingIsSuccess = ReadSetting(); } if (!s_ReadSettingIsSuccess) @@ -846,27 +300,15 @@ void PutAliveMessage(common::OperationMessage& operationMessage, const char* str i += 4; } -nn::Result ExecSyncMcuRtc(common::HardwareStateManager& manager) -{ - nn::Result result = nn::ResultSuccess(); - if(!common::ExistsRtcSyncFinishedFile()) - { - result = ImportMcuRtc(manager); - if(result.IsSuccess()) - { - // RTCを同期完了ファイルを作る - CreateRtcSyncFinishedFile(); - } - } - - return result; -} - } // namespace void ControlState(common::HardwareStateManager& manager, common::OperationMessage& operationMessage, bool& nextStep, bool operateBmsDone, bool forcePreinstall, bool unregister) { + NN_UNUSED_VAR(operateBmsDone); + NN_UNUSED_VAR(forcePreinstall); + NN_UNUSED_VAR(unregister); + using namespace common; nn::Result result; @@ -881,34 +323,8 @@ void ControlState(common::HardwareStateManager& manager, common::OperationMessag break; - case INITIALIZE_CONSOLE: - { - COMMON_LOGGER("Initialize Console\n"); - - // 本体初期化完了ファイルを作る - CreateConsoleInitializedFile(); - - // ファイルシステムの初期化を行う - if(InitializeFileSystem()) - { - s_RestoreState = REBOOTING; - } - else - { - s_RestoreState = FAIL; - } - - } - break; - case WAIT_START_UPDATE: { - //シリアルが存在しない場合がある - if (common::ExistsSerialNumberFile() && !DisplaySerialNumberinSD(operationMessage)) - { - s_RestoreState = FAIL; - } - operationMessage.Add("Push A or START Button"); operationMessage.Add("Network Update Mode"); PlayCursorSound(WAIT_START_UPDATE); @@ -925,97 +341,7 @@ void ControlState(common::HardwareStateManager& manager, common::OperationMessag } break; - case WAIT_START_IMPORT: - { - // 必ずシリアルが存在するはず - if(!DisplaySerialNumberinSD(operationMessage)) - { - s_RestoreState = FAIL; - } - - operationMessage.Add("Push A or START Button"); - operationMessage.Add("Import Data Mode"); - PlayCursorSound(WAIT_START_IMPORT); - - if (nextStep) - { - s_RestoreState = READ_FILELIST; - } - } - break; - - case WAIT_START_SYNC_CLOCK: - { - operationMessage.Add("Push A or START Button"); - operationMessage.Add("DownLoad Twl Title and Clock Sync Mode"); - PlayCursorSound(WAIT_START_SYNC_CLOCK); - - if (nextStep) - { - COMMON_LOGGER("Erase Trash\n"); - s_RestoreState = ERASE; - } - } - break; - - // ここから各設定で処理が分岐する - case IMPORT_RTC: - { - result = nn::ResultSuccess(); - if (HasValidRtcData()) - { - result = ExecSyncMcuRtc(manager); - if (result <= nn::fs::ResultVerificationFailed()) - { - s_RestoreState = FAIL; - } - else - { - if (s_SkipNupMode) - { - CheckAccountTransfered(manager, operationMessage, nextStep); - } - else - { - CheckNupExecuted(manager, operationMessage, nextStep); - } - } - } - else - { - if(s_SkipNupMode) - { - CheckAccountTransfered(manager, operationMessage, nextStep); - } - else if (s_CheckSdOnlyMode) - { - s_RestoreState = CHECK_IVS; - } - else - { - CheckNupExecuted(manager, operationMessage, nextStep); - } - } - } - break; - - // シリアルナンバーがSDカードにないこと警告 - case SERIAL_IS_NOT_IN_SD: - { - operationMessage.Add("Serial Number Is Not In SD Card"); - operationMessage.Add("Push A or START Button"); - operationMessage.Add("Import Data Mode"); - - PlayAnnotationSound(ANNOTATION_SERIAL_NUMBER_NOT_IN_SD); - - if (nextStep) - { - s_RestoreState = READ_FILELIST; - } - } - break; - - // アップデート中 + // アップデート中 case UPDATE_IN_PROGRESS: { UpdateOperation(manager, operationMessage, UPDATE_DONE); @@ -1026,606 +352,31 @@ void ControlState(common::HardwareStateManager& manager, common::OperationMessag case UPDATE_DONE: { operationMessage.Add("Network Update Done."); - operationMessage.Add("Press A or START Button to Reboot"); + operationMessage.Add("Press A or START Button to Shutdown"); + PlayCursorSound(UPDATE_DONE); if (nextStep) { - s_RestoreState = REBOOTING; + s_RestoreState = SHUTDOWN; } } break; - case DOWNLOAD_IVS: + case SHUTDOWN: { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_GET_IVS, "Get SDCI", - "Get SDCI Finished.\n", "Get SDCI Failed. Retrying...", DOWNLOAD_IVS_DONE); + // シャットダウンする + nn::ptm::CTR::ShutdownAsync(0, nn::fnd::TimeSpan::FromSeconds(0)); } break; - - case DOWNLOAD_IVS_DONE: - { - operationMessage.Add("Get SDCI Done."); - operationMessage.Add("Press A or START Button to Reboot"); - PlayCursorSound(DOWNLOAD_IVS_DONE); - - if (nextStep) - { - s_RestoreState = REBOOTING; - } - } - break; - - case CHECK_IVS: - { - operationMessage.Add("Insert User's SD Card"); - } - break; - - case CHECK_SD_DIRECTORY: - { - if (nn::fs::IsSdmcInserted()) - { - NN_LOG("Check User's SD Card\n"); - // ユーザのSDカードにはAP設定ファイルは無いはず - if (ExistsAPSetting()) - { - NN_LOG("AP Setting Exists. Retry\n"); - s_RestoreState = CHECK_IVS; - } - else - { - NN_LOG("Read User's SD Card\n"); - std::string sysSaveRoot; - common::Util::GetSaveDataDirectoryRoot(sysSaveRoot); - if (ExistsIvsDirectory(sysSaveRoot)) - { - s_RestoreState = CHECK_SD_DIRECTORY_SUCCESS; - } - else - { - s_RestoreState = CHECK_SD_DIRECTORY_FAIL; - } - } - } - } - break; - - case CHECK_SD_DIRECTORY_SUCCESS: - { - operationMessage.Add("Check User's SD Card Succeeded."); - operationMessage.Add("Pull Out SD Card"); - } - break; - - case CHECK_SD_DIRECTORY_FAIL: - { - operationMessage.Add("Check User's SD Card Failed."); - operationMessage.Add("Pull Out SD Card"); - } - break; - - case WAIT_START_TRANSFER_ACCOUNT: - { - if(s_SkipNupMode) - { - operationMessage.Add("After Operating BMS Account Transfer,"); - } - - operationMessage.Add("Push A or START Button"); - operationMessage.Add("Transfer Account Mode"); - PlayCursorSound(WAIT_START_TRANSFER_ACCOUNT); - - if (nextStep) - { - COMMON_LOGGER("Transfer Account\n"); - s_RestoreState = TRANSFER_ACCOUNT; - } - } - break; - - case TRANSFER_ACCOUNT: - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_GET_IVS, "Transfer Account", - "Transfer Account Finished.\n", "Transfer Account Failed. Retrying...", DOWNLOAD_IVS_DONE); - } - break; - - case WAIT_START_DELETE_ACCOUNT: - { - operationMessage.Add("Delete Account Mode.", nn::util::Color8(255, 153, 0, 255)); - operationMessage.Add("Press Y Button to Continue"); - PlayCursorSound(WAIT_START_DELETE_ACCOUNT); - - if (unregister) - { - COMMON_LOGGER("Delete Account\n"); - s_RestoreState = DELETE_ACCOUNT; - } - } - break; - - case DELETE_ACCOUNT: - { - if(s_NupOnlyMode) - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_FORCE_UNREGISTER, "Deleting Account", - "Delete Account Finished.\n", "Delete Account Failed. Retrying...", DELETE_ACCOUNT_DONE); - - } - else - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_UNREGISTER, "Deleting Account", - "Delete Account Finished.\n", "Delete Account Failed. Retrying...", DELETE_ACCOUNT_DONE); - } - } - break; - - case DELETE_ACCOUNT_DONE: - { - if(s_NupOnlyMode) - { - s_RestoreState = NUP_ONLY_WAIT_SD_EJECT; - - // リストア状態チェックファイルをすべて削除 - DeleteAllCheckFiles(); - } - else - { - operationMessage.Add("Delete Account Done."); - operationMessage.Add("Operate BMS and NNAS management Tool.", nn::util::Color8(0, 255, 255, 255)); - operationMessage.Add(""); - operationMessage.Add("Press Y Button to Continue"); - PlayCursorSound(DELETE_ACCOUNT_DONE); - - if (operateBmsDone) - { - s_RestoreState = STARTUP; - } - } - } - break; - - case READ_FILELIST: - { - result = SetupVersionAndFileList(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - if (result.IsSuccess()) - { - if (s_IsSyncClock) - { - s_RestoreState = RESTORE_TWL_NAND; - } - else - { - s_RestoreState = RESTORE_TWL_SOUND; - } - - } - else - { - s_RestoreState = FAIL; - } - } - break; - - // TWLサウンド領域の書き込み中 - case RESTORE_TWL_SOUND: - { - static bool init = true; - if (init) - { - // データを書き込む - ImportTwlSoundData(); - init = false; - } - - PutAliveMessage(operationMessage, "Importing TWL Sound Data"); - - // 処理が完了した - if (IsImportThreadFinished()) - { - FinalizeImportThread(); - if(IsImportSucceeded()) - { - s_RestoreState = RESTORE_TWL_PHOTO; - } - else - { - s_RestoreState = FAIL; - } - - } - } - break; - - // TWL写真領域の書き込み - case RESTORE_TWL_PHOTO: - { - static bool init = true; - if (init) - { - // データを書き込む - ImportTwlPhotoData(); - init = false; - } - - PutAliveMessage(operationMessage, "Importing TWL Photo Data"); - - // 処理が完了した - if (IsImportThreadFinished()) - { - FinalizeImportThread(); - if(IsImportSucceeded()) - { - s_RestoreState = RESTORE_IN_PROGRESS; - } - else - { - s_RestoreState = FAIL; - } - - } - } - break; - - // 書き込み中 - case RESTORE_IN_PROGRESS: - { - // ACアダプタが必要か? - if (NeedsAcAdater(manager)) - { - operationMessage.Add("Connect AC Adapter!!"); - } - - // データを読み込む - if (ImportData().IsFailure()) - { - s_RestoreState = FAIL; - } - else - { - PutAliveMessage(operationMessage, "Importing Nand Data"); - - // 処理が完了した - if (!NeedsAcAdater(manager) && IsImportThreadFinished()) - { - if (IsImportSucceeded()) - { - - COMMON_LOGGER("Import NAND Data Finished.\n"); - - if (GetProgress() > 99) - { - s_RestoreState = POST_RESTORE; - } - else - { - s_RestoreState = FAIL; - } - } - else - { - s_RestoreState = FAIL; - } - } - } - } - break; - - // リブート中 - case REBOOTING: - { - static bool init = true; - - if (init) - { - // ErrDispから引用 - result = nn::ns::CTR::InitializeForShell(); - if (result.IsSuccess()) - { - COMMON_LOGGER("System Reboot.\n"); - - nn::ns::CTR::HardwareResetAsync(nn::CTR::MEMORY_ARRANGE_NORMAL); - while (!nn::applet::IsExpectedToCloseApplication()) - { - nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(5)); - } - - nn::ns::CTR::FinalizeForShell(); - - // INFO: リブートは非同期のため処理は継続 - } - init = false; - } - } - break; - - // 書き込み後の処理 - case POST_RESTORE: - { - operationMessage.Add("Post Process..."); - - // SDカードのIVSファイルを書き込む - if(ImportIvsData()) - { - // 書き込み完了ファイルを作成 - CreateWriteFinishedFile(); - - s_RestoreState = RESTORE_DONE; - } - else - { - s_RestoreState = FAIL; - } - } - break; - - // 書き込み完了 - case RESTORE_DONE: - { - operationMessage.Add("Restore Done."); - operationMessage.Add("Press A or START Button to Reboot"); - PlayCursorSound(RESTORE_DONE); - - if (nextStep) - { - s_RestoreState = REBOOTING; - } - } - break; - - // 削除処理 - case ERASE: - { - Cleanup(); - s_RestoreState = RESTORE_CAL; - } - break; - - // 削除処理 - case RESTORE_CAL: - { - // ptmのセーブデータ移行後に時計を無効化する - nn::ptm::CTR::InvalidateSystemTime(); - - // cfgの本体固有値をcal値で初期化する - result = InitializeHardwareDependentSetting(); - if (result.IsFailure()) - { - COMMON_LOGGER_RESULT(result, __func__); - s_RestoreState = FAIL; - } - else - { - s_RestoreState = COMPLETE_ACT; - } - } - break; - - case COMPLETE_ACT: - { - COMMON_LOGGER("Complete NNA Transfer\n"); - if (ImportCountryLanguageData().IsSuccess()) - { - ActCompleter::Start(); - s_RestoreState = COMPLETE_ACT_WAIT; - } - else - { - s_RestoreState = FAIL; - } - } - break; - - case COMPLETE_ACT_WAIT: - { - PutAliveMessage(operationMessage, "Complete NNA Transfer"); - if (ActCompleter::IsFinished()) - { - ActCompleter::Finish(); - result = ActCompleter::GetResult(); - if (result.IsFailure()) - { - if(++s_NNATransferRetryCount >= RETRY_MAX) - { - COMMON_LOGGER_RESULT(result, __func__); - s_RestoreState = FAIL; - } - else - { - COMMON_LOGGER("Complete NNA Transfer failed, Retrying..."); - s_RestoreState = COMPLETE_ACT; - } - } - else - { - COMMON_LOGGER("Sync eTicket\n"); - s_RestoreState = SYNC_TICKET; - } - } - } - break; - - case SYNC_TICKET: - { - if(s_GetIvsOnlyMode) - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_CONNECT, "Shop Connect", - "Shop Connect Finished.\n", "Shop Connect Failed. Retrying...", WAIT_SD_EJECT); - } - else if(s_DownloadPreinstallMode) - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_CONNECT, "Shop Connect", - "Shop Connect Finished.\n", "Shop Connect Failed. Retrying...", REPAIR_SIMPLE_ADDRESS_ID); - } - else - { - ShopOperationSingleTemplate(manager, operationMessage, SHOP_OPERATION_CONNECT, "Shop Connect", - "Shop Connect Finished.\n", "Shop Connect Failed. Retrying...", DOWNLOAD_TWL); - } - } - break; - - case DOWNLOAD_TWL: - { - // ファイルリストがなければ次へ - if( !ExistsTwlTitleListFile()) - { - s_IsSyncClock = true; - s_RestoreState = READ_FILELIST; - } - else - { - if (!s_ExecuteTwlTitleDownload) - { - COMMON_LOGGER("Download Twl Title\n"); - s_ExecuteTwlTitleDownload = true; - StartTwlTitleDownload(); - } - - // 動いていることを表示 - { - PutAliveMessage(operationMessage, "Download Twl Title"); - } - - if (IsDownloadTitleFinished()) - { - FinalizeTitleDownload(); - if (DownloadTitleSucceeded()) - { - s_IsSyncClock = true; - s_RestoreState = READ_FILELIST; - } - else - { - if (s_TwlTitleDownloadRetryCount++ < RETRY_MAX) - { - // エラーのためやり直す - COMMON_LOGGER_RESULT_IF_FAILED(GetTitleDownloadResult()); - COMMON_LOGGER("Download Twl Title Failed. Retrying... %d\n", s_TwlTitleDownloadRetryCount); - - s_ExecuteTwlTitleDownload = false; - } - else - { - s_RestoreState = FAIL; - } - } - } - } - } - break; - - // TWL NAND領域の書き込み中 - case RESTORE_TWL_NAND: - { - static bool init = true; - if (init) - { - // データを書き込む - ImportTwlSaveData(); - init = false; - } - - PutAliveMessage(operationMessage, "Importing TWL SaveData"); - - // 処理が完了した - if (IsImportThreadFinished()) - { - FinalizeImportThread(); - s_RestoreState = REPAIR_SIMPLE_ADDRESS_ID; - } - } - break; - - case REPAIR_SIMPLE_ADDRESS_ID: - { - RepairSimpleAddress(); - s_RestoreState = TIME_ADJUST; - } - break; - - // 時計あわせ - case TIME_ADJUST: - { - static bool init = true; - if (init) - { - COMMON_LOGGER("Adjust Time\n"); - AdjustTime(); - init = false; - } - - // 動いていることを表示 - { - PutAliveMessage(operationMessage, "Sync Clock"); - } - - if (IsTimeAdjustFinished()) - { - if (IsTimeAdjustSuccessed()) - { - if(s_DownloadPreinstallMode) - { - s_RestoreState = PREINSTALL_WAIT_USER_SD_INSERT; - } - else - { - s_RestoreState = WAIT_SD_EJECT; - - // インターネット設定を元に戻す - RestoreCurrentInternetSetting(); - - // リストア状態チェックファイルをすべて削除 - DeleteAllCheckFiles(); - } - } - else - { - // インターネット設定を元に戻す - RestoreCurrentInternetSetting(); - - s_RestoreState = FAIL; - } - } - } - break; - - // すべて完了 - case WAIT_SD_EJECT: - { - operationMessage.Add("ALL Done. Pull Out SD Card."); - // SDカード抜けのみで次の状態に遷移する - PlayCursorSound(WAIT_SD_EJECT); - - } - break; - - // すべて完了 - case ALL_DONE: - { - operationMessage.Add("Restore Succeeded!!"); - static bool init = true; - if (init) - { - PlaySound(SOUND_OK); - manager.SetWifiOff(); - init = false; - } - } - break; - - // 書き込み失敗 + // 失敗 case FAIL: { static bool init = true; if (init) { // 状態初期化 - DeleteAllCheckFiles(); manager.SetWifiOff(); init = false; } @@ -1638,375 +389,12 @@ void ControlState(common::HardwareStateManager& manager, common::OperationMessag } } break; - - case NUP_ONLY_WAIT_SD_EJECT: - { - static bool init = true; - if(init) - { - manager.SetWifiOff(); - init = false; - } - operationMessage.Add("Update Done. Pull Out SD Card."); - PlayCursorSound(NUP_ONLY_WAIT_SD_EJECT); - } - break; - - case DOWNLOAD_IVS_WAIT_NEXT: - { - operationMessage.Add("Press A or START Button to Continue."); - if(nextStep) - { - s_RestoreState = COMPLETE_ACT; - DeleteAllCheckFiles(); - } - } - break; - - case NUP_ONLY_WAIT_NEXT: - { - operationMessage.Add("Press A or START Button to Shutdown."); - - if (nextStep) - { - s_RestoreState = INITIALIZE_AND_SHUTDOWN; - } - } - break; - - case INITIALIZE_AND_SHUTDOWN: - { - // 本体初期化を行う - if(!InitializeFileSystem()) - { - s_RestoreState = FAIL; - } - - // シャットダウンする - nn::ptm::CTR::ShutdownAsync(0, nn::fnd::TimeSpan::FromSeconds(0)); - } - break; - - case PREINSTALL_WAIT_START_UPDATE: - { - operationMessage.Add("Operate BMS to Transfer PreInstalled Application", nn::util::Color8(0, 255, 255, 255)); - operationMessage.Add("and NNAS management Tool.", nn::util::Color8(0, 255, 255, 255)); - operationMessage.Add("Press Y Button to Continue."); - PlayCursorSound(PREINSTALL_WAIT_START_UPDATE); - - if (operateBmsDone) - { - s_RestoreState = WAIT_START_UPDATE; - } - } - break; - - - case PREINSTALL_WAIT_SYNC_TICKET: - { - operationMessage.Add("Press A or START Button to Continue."); - PlayCursorSound(PREINSTALL_WAIT_SYNC_TICKET); - if(nextStep) - { - s_RestoreState = COMPLETE_ACT; - } - } - break; - - case PREINSTALL_WAIT_USER_SD_INSERT: - { - PlayCursorSound(PREINSTALL_WAIT_USER_SD_INSERT); - operationMessage.Add("Insert User's SD Card"); - operationMessage.Add("and Press A or START Button."); - } - break; - - case PREINSTALL_WAIT_USER_SD_INSERT_WAIT_NEXT: - { - operationMessage.Add("Insert User's SD Card"); - operationMessage.Add("and Press A or START Button."); - - if(nextStep) - { - s_RestoreState = PREINSTALL_CHECK_USER_SD_INSERT; - } - } - break; - - case PREINSTALL_CHECK_USER_SD_INSERT: - { - RestoreState saved = PREINSTALL_CHECK_USER_SD_INSERT; - if (nn::fs::IsSdmcInserted()) - { - NN_LOG("Check User's SD Card\n"); - // ユーザのSDカードにはAP設定ファイルは無いはず - if (ExistsAPSetting()) - { - NN_LOG("AP Setting Exists. Retry\n"); - ChangeState(saved, s_RestoreState, PREINSTALL_WAIT_USER_SD_INSERT); - } - else - { - // SD挿抜が起こったら抜ける - BREAK_IF_STATE_CHANGED(saved, s_RestoreState); - ChangeState(saved, s_RestoreState, PREINSTALL_CHECK_USER_SD); - } - } - } - break; - - case PREINSTALL_CHECK_USER_SD: - { - if (!s_ExecutePreparePreinstallTitleDownload) - { - COMMON_LOGGER("Checking User's SD Card\n"); - s_ExecutePreparePreinstallTitleDownload = true; - StartPreparePreinstallTitleDownload(s_ForceDownloadPreinstall); - } - - // 動いていることを表示 - { - PutAliveMessage(operationMessage, "Checking User's SD Card"); - } - - if (IsDownloadTitleFinished()) - { - FinalizeTitleDownload(); - if (DownloadTitleSucceeded()) - { - s_RestoreState = PREINSTALL_DOWNLOAD_APP; - } - else - { - if (s_PreparePreinstallTitleDownloadRetryCount++ < RETRY_MAX) - { - COMMON_LOGGER_RESULT_IF_FAILED(GetTitleDownloadResult()); - if (GetTitleDownloadResult() - == nn::MakePermanentResult(nn::Result::SUMMARY_OUT_OF_RESOURCE, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_OUT_OF_MEMORY)) - { - // SDカード容量不足 - s_RestoreState = PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE; - } - else if(GetTitleDownloadResult() <= nn::fs::ResultNotEnoughSpace()) - { - // SDカード容量不足 - // 作成したデータを削除する - COMMON_LOGGER_RESULT_IF_FAILED(nn::fs::DeleteSdmcRoot()); - s_RestoreState = PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE; - } - else if (GetTitleDownloadResult() - == nn::MakePermanentResult(nn::Result::SUMMARY_INVALID_STATE, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_ALREADY_INITIALIZED)) - { - // ユーザSDが初期化済み - s_RestoreState = PREINSTALL_CHECK_USER_SD_ALREADY_INITIALIZED; - } - else if (GetTitleDownloadResult() - == nn::MakePermanentResult(nn::Result::SUMMARY_NOT_FOUND, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_NOT_FOUND)) - { - // プリインストールテーブルが無い - COMMON_LOGGER("No PreInstalled Application Found\n"); - s_RestoreState = PREINSTALL_CHECK_SD_FAIL; - } - else - { - // エラーのためやり直す - COMMON_LOGGER("Checking User's SD Card Failed. Retrying... %d\n", s_PreinstallTitleDownloadRetryCount); - s_ExecutePreparePreinstallTitleDownload = false; - } - } - else - { - s_RestoreState = PREINSTALL_CHECK_SD_FAIL; - } - } - } - } - break; - - case PREINSTALL_CHECK_USER_SD_ALREADY_INITIALIZED: - { - operationMessage.Add("User's SD Card is already initialized."); - operationMessage.Add("Press Y Button to Continue.", nn::util::Color8(0, 255, 255, 255)); - operationMessage.Add("Press A or START Button to Abort"); - if(nextStep) - { - s_RestoreState = PREINSTALL_CHECK_SD_FAIL; - } - else if(forcePreinstall) - { - s_RestoreState = PREINSTALL_CHECK_USER_SD; - s_ExecutePreparePreinstallTitleDownload = false; - s_ForceDownloadPreinstall = true; - } - } - break; - - case PREINSTALL_CHECK_SD_FAIL: - { - PlayCursorSound(PREINSTALL_CHECK_SD_FAIL); - operationMessage.Add("Check User's SD Card Failed."); - operationMessage.Add("Pull Out User's SD Card"); - operationMessage.Add("and Insert Repairing SD Card"); - } - break; - - case PREINSTALL_FAIL_CHECK_REPAIR_SD: - { - operationMessage.Add("Press A or START Button to Continue."); - if(!nextStep) - { - break; - } - - RestoreState saved = PREINSTALL_FAIL_CHECK_REPAIR_SD; - if (nn::fs::IsSdmcInserted()) - { - NN_LOG("Check SD Card\n"); - // 修理用SDカードにはAP設定ファイルがあるはず - if (ExistsAPSetting()) - { - NN_LOG("AP Setting Exists. OK\n"); - COMMON_LOGGER("Download PreInstalled Application failed\n"); - - // インターネット設定を元に戻す - RestoreCurrentInternetSetting(); - - ChangeState(saved, s_RestoreState, FAIL); - } - else - { - // SD挿抜が起こったら抜ける - BREAK_IF_STATE_CHANGED(saved, s_RestoreState); - ChangeState(saved, s_RestoreState, PREINSTALL_CHECK_SD_FAIL); - } - } - } - break; - - case PREINSTALL_DOWNLOAD_APP: - { - if (!s_ExecutePreinstallTitleDownload) - { - COMMON_LOGGER("Download PreInstalled Application\n"); - s_ExecutePreinstallTitleDownload = true; - StartPreinstallTitleDownload(); - } - - // 動いていることを表示 - { - PutAliveMessage(operationMessage, "Download PreInstalled Title"); - } - - if (IsDownloadTitleFinished()) - { - FinalizeTitleDownload(); - if (DownloadTitleSucceeded()) - { - s_PreinstallTitleDownloadSuccess = true; - s_RestoreState = PREINSTALL_WAIT_USER_SD_EJECT; - } - else - { - if (s_PreinstallTitleDownloadRetryCount++ < RETRY_MAX) - { - // エラーのためやり直す - COMMON_LOGGER_RESULT_IF_FAILED(GetTitleDownloadResult()); - if(GetTitleDownloadResult() <= nn::fs::ResultNotEnoughSpace()) - { - // SDカード容量不足 - // 作成したデータを削除する - COMMON_LOGGER_RESULT_IF_FAILED(nn::fs::DeleteSdmcRoot()); - s_RestoreState = PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE; - } - else - { - COMMON_LOGGER("Download PreInstalled Title Failed. Retrying... %d\n", s_PreinstallTitleDownloadRetryCount); - - s_ExecutePreinstallTitleDownload = false; - } - } - else - { - s_RestoreState = PREINSTALL_WAIT_USER_SD_EJECT; - } - } - } - } - break; - - case PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE: - { - PlayCursorSound(PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE); - operationMessage.Add("Not enough space on User's SD Card"); - operationMessage.Add("Pull out User's SD Card"); - operationMessage.Add("and Insert Repairing SD Card"); - } - break; - - case PREINSTALL_WAIT_USER_SD_EJECT: - { - PlayCursorSound(PREINSTALL_WAIT_USER_SD_EJECT); - operationMessage.Add("Pull out User's SD Card"); - operationMessage.Add("and Insert Repairing SD Card"); - } - break; - - case PREINSTALL_CHECK_REPAIR_SD: - { - operationMessage.Add("Press A or START Button to Continue."); - if(!nextStep) - { - break; - } - - RestoreState saved = PREINSTALL_CHECK_REPAIR_SD; - if (nn::fs::IsSdmcInserted()) - { - NN_LOG("Check SD Card\n"); - // 修理用SDカードにはAP設定ファイルがあるはず - if (ExistsAPSetting()) - { - NN_LOG("AP Setting Exists. OK\n"); - // インターネット設定を元に戻す - RestoreCurrentInternetSetting(); - - if(s_PreinstallTitleDownloadSuccess) - { - COMMON_LOGGER("Download PreInstalled Application done\n"); - ChangeState(saved, s_RestoreState, WAIT_SD_EJECT); - // リストア状態チェックファイルをすべて削除 - DeleteAllCheckFiles(); - } - else - { - COMMON_LOGGER("Download PreInstalled Application failed\n"); - ChangeState(saved, s_RestoreState, FAIL); - } - } - else - { - // SD挿抜が起こったら抜ける - BREAK_IF_STATE_CHANGED(saved, s_RestoreState); - ChangeState(saved, s_RestoreState, PREINSTALL_WAIT_USER_SD_EJECT); - } - } - } - break; - } } -bool InProgress() -{ - return s_RestoreState == RESTORE_IN_PROGRESS; -} - bool IsRestoreSucceeded() { - return s_RestoreState == ALL_DONE; + return s_RestoreState == UPDATE_DONE; } bool IsRestoreFailed() @@ -2016,81 +404,16 @@ bool IsRestoreFailed() void OnSdEjected() { - if (s_RestoreState == WAIT_SD_EJECT || s_RestoreState == ALL_DONE || s_RestoreState == CHECK_SD_DIRECTORY_SUCCESS) - { - s_RestoreState = ALL_DONE; - } - else if (s_RestoreState == NUP_ONLY_WAIT_SD_EJECT || s_RestoreState == NUP_ONLY_WAIT_NEXT) - { - s_RestoreState = NUP_ONLY_WAIT_NEXT; - } - // ユーザのSDが抜かれてからFAILにする - else if (s_RestoreState == CHECK_SD_DIRECTORY_FAIL) - { - s_RestoreState = FAIL; - } - else if(s_RestoreState == PREINSTALL_CHECK_USER_SD_INSERT) - { - s_RestoreState = PREINSTALL_WAIT_USER_SD_INSERT; - } - else if(s_RestoreState == PREINSTALL_CHECK_REPAIR_SD) - { - s_RestoreState = PREINSTALL_WAIT_USER_SD_EJECT; - } - else if(s_RestoreState == PREINSTALL_FAIL_CHECK_REPAIR_SD) - { - s_RestoreState = PREINSTALL_CHECK_SD_FAIL; - } - // FAILのときは一旦電源を切らないと動かないようにしておく - // IVSチェック時はユーザのSDカードを挿入してもらうため - // プリインストール時はユーザのSDカードを挿入してもらうため - else if (s_RestoreState != FAIL && s_RestoreState != CHECK_IVS && s_RestoreState != PREINSTALL_WAIT_USER_SD_INSERT - && s_RestoreState != PREINSTALL_WAIT_USER_SD_EJECT && s_RestoreState != PREINSTALL_CHECK_SD_FAIL && - s_RestoreState != PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE && s_RestoreState != PREINSTALL_WAIT_USER_SD_INSERT_WAIT_NEXT) - { - InitializeState(); - ClearFileReadResult(); - } } void OnSdInserted() { - if(s_RestoreState == CHECK_IVS) - { - // SDカードが変わるのでファイルチェックは初期化する - common::InitializeFileCheck(); - s_RestoreState = CHECK_SD_DIRECTORY; - } - else if(s_RestoreState == PREINSTALL_WAIT_USER_SD_INSERT) - { - // SDカードが変わるのでファイルチェックは初期化する - common::InitializeFileCheck(); - s_RestoreState = PREINSTALL_WAIT_USER_SD_INSERT_WAIT_NEXT; - } - else if(s_RestoreState == PREINSTALL_WAIT_USER_SD_EJECT) - { - // SDカードが変わるのでファイルチェックは初期化する - common::InitializeFileCheck(); - s_RestoreState = PREINSTALL_CHECK_REPAIR_SD; - } - else if(s_RestoreState == PREINSTALL_CHECK_SD_FAIL || s_RestoreState == PREINSTALL_DOWNLOAD_APP_NOT_ENOUGH_SPACE) - { - // SDカードが変わるのでファイルチェックは初期化する - common::InitializeFileCheck(); - s_RestoreState = PREINSTALL_FAIL_CHECK_REPAIR_SD; - } } void InitializeState() { s_RestoreState = STARTUP; - s_RestoreMode = RESTORE_MODE_RESTORE; - - for(u32 i = 0; i < SHOP_OPERATION_NUM_MAX; i++) - { - s_ShopOperationExecuted[i] = false; - s_ShopOperationRetryCount[i] = 0; - } + s_RestoreMode = RESTORE_MODE_NUP_WITHOUT_REBOOT; for(u32 i = 0; i < RESTORE_STATE_MAX; i++) { @@ -2102,50 +425,16 @@ void InitializeState() s_PlayedAnnotationSound[i] = false; } - common::InitializeFileCheck(); - s_ReadSettingDone = false; s_ReadSettingIsSuccess = false; s_PlayedFailSound = false; s_ExecuteFgNup = false; s_FgNupRetryCount = 0; - s_NupOnlyMode = false; - s_GetIvsOnlyMode = false; - s_CheckSdOnlyMode = false; - s_SkipNupMode = false; - s_ExecutePreparePreinstallTitleDownload = false; - s_ExecutePreinstallTitleDownload = false; - s_PreinstallTitleDownloadSuccess = false; } u32 GetProgress() { - if(s_RestoreState == RESTORE_TWL_SOUND || - s_RestoreState == RESTORE_TWL_PHOTO || - s_RestoreState == RESTORE_IN_PROGRESS || - s_RestoreState == POST_RESTORE || - s_RestoreState == RESTORE_DONE) - { - return GetImportProgress(); - } - else if (s_RestoreState == RESTORE_TWL_NAND) - { - return GetImportProgressTwlNand(); - } - else if(s_RestoreState == UPDATE_IN_PROGRESS || - s_RestoreState == UPDATE_DONE) - { - return GetUpdateProgress(); - } - else if (s_RestoreState == DOWNLOAD_TWL || s_RestoreState == PREINSTALL_DOWNLOAD_APP) - { - return GetTitleDownloadProgress(); - } - else - { - return 0; - } - + return GetUpdateProgress(); } RestoreMode GetRestoreMode() diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.h b/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.h index 58d82f6..5e72962 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.h +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/Controller.h @@ -27,11 +27,9 @@ namespace ConsoleRestore typedef enum RestoreMode { - RESTORE_MODE_RESTORE, - RESTORE_MODE_NUP_ONLY, - RESTORE_MODE_GET_IVS, - RESTORE_MODE_CHECK_SD, - RESTORE_MODE_DOWNLOAD_PREINSTALL + RESTORE_MODE_NUP_WITHOUT_REBOOT, + + RESTORE_MODE_MAX } RestoreMode; diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.cpp index d8b1f11..af982ec 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.cpp +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.cpp @@ -43,307 +43,19 @@ #include "Importer.h" #include "SdMountManager.h" #include "HeapManager.h" -#include "SdReaderWriter.h" #include "CommonLogger.h" -#include "FileTransfer.h" #include "common_Types.h" -#include "Aes_define.h" #include "configLoader.h" #include "FileChecker.h" #include "VersionDetect.h" -#include "SaveDataMover.h" -#include "RegionIdModifier.h" #include #include namespace ConsoleRestore { -namespace -{ -const size_t IMPORT_THREAD_STACK_SIZE = 0x4000; -nn::os::Thread s_ImportThread; -nn::os::StackBuffer s_ImportThreadStack; -bool s_IsImportSucceeded; - -const size_t TIME_ZONE_LENGTH = 9; // "+23:45" -char s_TimeZoneStr[TIME_ZONE_LENGTH]; - -TimeZone s_TimeZone; -const size_t NTP_SERVER_NAME_LENGTH = 256; -char s_NtpServerName[NTP_SERVER_NAME_LENGTH]; - -bool s_CheckedEqualsRegionDataandRegion = false; -bool s_ReadSerialNumber = false; - -struct SdFileSize -{ - s64 totalFileSize; - s64 twlFileSize; - s64 twlSoundFileSize; - s64 twlPhotoFileSize; - s64 ctrFileSize; -}; - -SdFileSize s_SdFileSize; - -// シリアルナンバー -u8 s_SerialNo[nn::cfg::CTR::CFG_SECURE_INFO_SERIAL_NO_LEN]; - -// 空のファイルを作成する -bool CreateEmptyFile(const wchar_t* path); -// SDからNANDにセーブデータをコピーする -void ImportSaveData(); -// SDからNORにNORデータをコピーする -nn::Result ImportNorData(); - -// SDカードに保存してあるバージョン情報 -common::VerDef s_SDVersionData; - -// SDカードから読み込んだファイル一覧 -common::ImportDataList s_FileLists; - -u64 s_ImportProgress = 0; - -} - -// SDからファイル一覧を読み込む -nn::Result ReadFileList(SdFileSize* sdFileSize, common::ImportDataList* fileList); - -bool RequiresImportApi(); - CheckedNetworkSetting s_CurrentNetowrkSetting1; -void ConvertTimeZoneString(const char* str) -{ - s_TimeZone.hour = 0; - s_TimeZone.minutes = 0; - s_TimeZone.isMinus = false; - - bool hour = true; - bool ten = true; - u32 count = 0; - for(u32 i = 0; i < TIME_ZONE_LENGTH && count < 2; i++) - { - switch (str[i]) - { - case ':': - { - hour = false; - } - break; - - case '"': - { - // 2回読んだら終了 - count++; - } - break; - - case '+': - { - s_TimeZone.isMinus = false; - } - break; - - case '-': - { - s_TimeZone.isMinus = true; - } - break; - - default: - { - if(hour) - { - if(ten) - { - s_TimeZone.hour += (str[i] - '0') * 10; - ten = false; - } - else - { - s_TimeZone.hour += str[i] - '0'; - ten = true; - } - } - else - { - if(ten) - { - s_TimeZone.minutes += (str[i] - '0') * 10; - ten = false; - } - else - { - s_TimeZone.minutes += str[i] - '0'; - ten = true; - } - } - } - break; - } - } - - - NN_LOG("Converted TimeZone = "); - if(s_TimeZone.isMinus) - { - NN_LOG("-"); - } - NN_LOG("%02d:%02d\n", s_TimeZone.hour, s_TimeZone.minutes); - -} - -namespace -{ - -bool CreateEmptyFile(const wchar_t* path) -{ - nn::Result result; - bool create = false; - result = common::SdMountManager::Mount(); - - if (result.IsSuccess()) - { - nn::fs::FileOutputStream fos; - - result = fos.TryInitialize(path, true); - if(result.IsSuccess()) - { - fos.TryFlush(); - create = true; - } - fos.Finalize(); - } - - common::SdMountManager::Unmount(); - - return create; -} - -} - -nn::Result ReadSerialNumber(u8* serial) -{ - static nn::Result result = nn::ResultSuccess(); - - if(s_ReadSerialNumber) - { - std::memcpy(serial, s_SerialNo, sizeof(s_SerialNo)); - return result; - } - - COMMON_LOGGER("Read Serial Number in SD.\n"); - - size_t readSize; - common::SdReaderWriter sdReader; - size_t bufSize = 1024; - common::HeapManager readHeap(bufSize); - void* buf = readHeap.GetAddr(); - if(buf != NULL) - { - result = sdReader.ReadBufWithCmac(common::SERIAL_PATHNAME, buf, bufSize, &readSize); - if(result.IsSuccess()) - { - std::memcpy(s_SerialNo, buf, sizeof(s_SerialNo)); - std::memcpy(serial, s_SerialNo, sizeof(s_SerialNo)); - s_ReadSerialNumber = true; - } - } - else - { - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - return result; -} - -nn::Result ExistsDeviceIdFile() -{ - common::SdReaderWriter sdReader; - size_t totalSize; - size_t bufSize = 1024; - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if(buf == NULL) - { - return nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return sdReader.ReadBufWithCmac(common::DEVICE_ID_PATHNAME, buf, bufSize, &totalSize); -} - -bool EqualsDeviceIdFileandDeviceId(common::HardwareStateManager& manager) -{ - COMMON_LOGGER("Check Device Id\n"); - - bit32 sdDeviceId; - common::SdReaderWriter sdReader; - size_t totalSize; - size_t bufSize = 1024; - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf == NULL) - { - return false; - } - - COMMON_LOGGER_RETURN_FALSE_IF_FAILED( - sdReader.ReadBufWithCmac(common::DEVICE_ID_PATHNAME, buf, bufSize, &totalSize)); - - std::memcpy(&sdDeviceId, buf, sizeof(sdDeviceId)); - return (manager.GetDeviceId() == sdDeviceId); -} - -nn::Result EqualsRegionDataandRegion() -{ - static nn::Result result = nn::ResultSuccess(); - - if(s_CheckedEqualsRegionDataandRegion) - { - return result; - } - - COMMON_LOGGER("Check Region\n"); - - nn::cfg::CTR::CfgRegionCode region; - region = nn::cfg::CTR::GetRegion(); - - nn::cfg::CTR::CfgRegionCode sdRegion; - common::SdReaderWriter sdReader; - size_t readSize; - size_t bufSize = 1024; - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - result = sdReader.ReadBufWithCmac(common::REGION_DATA_PATHNAME, buf, bufSize, &readSize); - if (result.IsSuccess()) - { - std::memcpy(&sdRegion, buf, sizeof(sdRegion)); - s_CheckedEqualsRegionDataandRegion = true; - if(region == sdRegion) - { - result = nn::ResultSuccess(); - } - else - { - result = nn::Result(nn::Result::LEVEL_STATUS, nn::Result::SUMMARY_INVALID_RESULT_VALUE, - nn::Result::MODULE_COMMON, nn::Result::DESCRIPTION_INVALID_RESULT_VALUE); - } - } - } - else - { - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return result; -} - void SetCountry(nn::cfg::CTR::CfgCountryCode countryCode) { using namespace nn::cfg::CTR; @@ -385,694 +97,58 @@ nn::Result ImportCountryLanguageData() { nn::Result result = nn::ResultSuccess(); - // 設定済みなら何もしない - if(nn::cfg::CTR::GetCountry() != nn::cfg::CTR::CFG_COUNTRY_UNKNOWN && nn::cfg::CTR::GetCountry() != nn::cfg::CFG_COUNTRY_UNDEFINED) + // リージョンから適当な国を指定する + nn::cfg::CTR::CfgRegionCode region; + region = nn::cfg::CTR::GetRegion(); + NN_LOG("Country Setting does not exist. Use Default Setting\n"); + switch (region) { - return result; - } - - if (common::ExistsCountryLanguageFile()) - { - size_t bufSize = 1024; - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) + case nn::cfg::CTR::CFG_REGION_JAPAN: { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::COUNTRY_SETTING_PATHNAME, buf, bufSize, &readSize); - if (result.IsSuccess()) - { - // SDから読み出し成功 - SetCountry(reinterpret_cast (buf)->country); - - SetLanguage(reinterpret_cast (buf)->language); - } - - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); + SetCountry(nn::cfg::CTR::CFG_COUNTRY_JAPAN); } - } - else - { - // リージョンから適当な国を指定する - nn::cfg::CTR::CfgRegionCode region; - region = nn::cfg::CTR::GetRegion(); - NN_LOG("Country Setting does not exist. Use Default Setting\n"); - switch(region) + break; + + case nn::cfg::CTR::CFG_REGION_AMERICA: { - case nn::cfg::CTR::CFG_REGION_JAPAN: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_JAPAN); - } - break; - - case nn::cfg::CTR::CFG_REGION_AMERICA: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_UNITED_STATES); - } - break; - - case nn::cfg::CTR::CFG_REGION_EUROPE: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_FRANCE); - } - break; - - case nn::cfg::CTR::CFG_REGION_AUSTRALIA: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_AUSTRALIA); - } - break; - - case nn::cfg::CTR::CFG_REGION_CHINA: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_CHINA); - } - break; - - case nn::cfg::CTR::CFG_REGION_KOREA: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_SOUTH_KOREA); - } - break; - - case nn::cfg::CTR::CFG_REGION_TAIWAN: - { - SetCountry(nn::cfg::CTR::CFG_COUNTRY_TAIWAN); - } - break; + SetCountry(nn::cfg::CTR::CFG_COUNTRY_UNITED_STATES); } + break; + case nn::cfg::CTR::CFG_REGION_EUROPE: + { + SetCountry(nn::cfg::CTR::CFG_COUNTRY_FRANCE); + } + break; + + case nn::cfg::CTR::CFG_REGION_AUSTRALIA: + { + SetCountry(nn::cfg::CTR::CFG_COUNTRY_AUSTRALIA); + } + break; + + case nn::cfg::CTR::CFG_REGION_CHINA: + { + SetCountry(nn::cfg::CTR::CFG_COUNTRY_CHINA); + } + break; + + case nn::cfg::CTR::CFG_REGION_KOREA: + { + SetCountry(nn::cfg::CTR::CFG_COUNTRY_SOUTH_KOREA); + } + break; + + case nn::cfg::CTR::CFG_REGION_TAIWAN: + { + SetCountry(nn::cfg::CTR::CFG_COUNTRY_TAIWAN); + } + break; } return result; } -inline u8 DecimalToBcd(u8 param) -{ - u8 theTen, theOne; - theTen = param / 10; - theOne = param - theTen * 10; - return (theTen << 4 | theOne); -} - -nn::Result ImportMcuRtc(common::HardwareStateManager& manager) -{ - COMMON_LOGGER("Import RTC Data.\n"); - nn::Result result = nn::ResultSuccess(); - nn::Handle handle = manager.GetMcuHandle(); - - if(handle.IsValid()) - { - if (common::CheckFileExists(common::MCU_RTC_PATHNAME)) - { - size_t bufSize = 1024; - NN_LOG("AllocatableSize = %d\n", bufSize); - - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::MCU_RTC_PATHNAME, buf, bufSize, &readSize); - if (result.IsSuccess()) - { - // mcuを使ってセットする - nn::mcu::CTR::HwCheck mcu(handle); - nn::mcu::CTR::RtcData* rtc = reinterpret_cast (buf); - NN_LOG("RTC = 20%02d/%02d/%02d %02d:%02d:%02d\n", rtc->m_Year, rtc->m_Month, rtc->m_Day, rtc->m_Hour, rtc->m_Minute, rtc->m_Second); - - // BCD変換が必要 - - size_t RTC_PARAM_SIZE = sizeof(nn::mcu::CTR::RtcData); - u8 bcd[RTC_PARAM_SIZE]; - for (int i = 0; i < RTC_PARAM_SIZE; i++) - { - bcd[i] = DecimalToBcd(reinterpret_cast (rtc)[i]); - } - - const u8 RETRY = 10; - for (u8 i = 0; i < RETRY; i++) - { - result = mcu.WriteBySend(nn::drivers::mcu::CTR::MCU_RTC_SEC_ADDR, bcd, RTC_PARAM_SIZE); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - if(result.IsSuccess()) - { - break; - } - nn::os::Thread::Sleep( - nn::fnd::TimeSpan::FromMilliSeconds( - nn::os::Tick::GetSystemCurrent().ToTimeSpan().GetMilliSeconds() % 100)); - - } - } - - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - COMMON_LOGGER("Failed Allocate Heap!!\n"); - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - } - } - else - { - result = nn::Result(nn::Result::LEVEL_PERMANENT, nn::Result::SUMMARY_INVALID_STATE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_INVALID_HANDLE); - } - - return result; -} - -bool InitializeFileSystem() -{ - nn::Result result; - - for (u32 i = 0; i < common::TWL_PATHNAME_MAX; i++) - { - result = nn::fs::MountSpecialArchive(common::TWL_ARCHIVE_NAME_TABLE[i], common::TWL_FS_ARCHIVE_KIND[i]); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - - nn::fs::Directory dir; - std::vector entryList; //カレントディレクトリのエントリ一覧を格納 - std::vector::iterator entryIndex; - - std::wstring currentDirectory = common::NAND_TWL_ROOT_PATHNAME_WITH_SLASH_TABLE[i]; - result = dir.TryInitialize(currentDirectory.c_str()); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - - nn::fs::DirectoryEntry entry; - s32 numEntry; - for (;;) - { - result = dir.TryRead(&numEntry, &entry, 1); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - - if (numEntry == 0) - { - // ルートディレクトリを閉じる - dir.Finalize(); - - // ルートディレクトリの子を開く - for (entryIndex = entryList.begin(); entryIndex != entryList.end(); entryIndex++) - { - // ディレクトリなら削除する - if (entryIndex->attributes.isDirectory) - { - NN_LOG("Try Delete %ls%ls/\n", currentDirectory.c_str(), entryIndex->entryName); - result = nn::fs::TryDeleteDirectoryRecursively( - (currentDirectory + ::std::wstring(entryIndex->entryName)).c_str()); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - - } - // ファイルなら削除する - else - { - NN_LOG("Try Delete %ls%ls\n", currentDirectory.c_str(), entryIndex->entryName); - result = nn::fs::TryDeleteFile( - (currentDirectory + ::std::wstring(entryIndex->entryName)).c_str()); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - } - } - - // 削除完了 - break; - } - else - { - // vectorに保存する - entryList.push_back(entry); - if (entry.attributes.isDirectory) - { - NN_LOG("%ls%ls/\n", currentDirectory.c_str(), entry.entryName); - } - else - { - NN_LOG("%ls%ls\n", currentDirectory.c_str(), entry.entryName); - } - } - } - - result = nn::fs::Unmount(common::TWL_ARCHIVE_NAME_TABLE[i]); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - } - - result = nn::am::DeleteAllTwlUserPrograms(); - COMMON_LOGGER_RETURN_FALSE_IF_FAILED(result); - nn::fs::InitializeCtrFileSystem(); - return true; -} - -nn::Result ImportIvs() -{ - nn::Result result = nn::ResultSuccess(); - nn::fs::FileOutputStream fos; - - size_t bufSize = 1024; - common::HeapManager encHeap(bufSize); - void* enc = encHeap.GetAddr(); - if (enc != NULL) - { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::IVS_PATHNAME, enc, bufSize, &readSize); - if(result.IsSuccess()) - { - // SDから読み出し成功 - result = nn::fs::MountSpecialArchive(common::NAND_ARCHIVE_NAME, nn::fs::CTR::ARCHIVE_TYPE_CTR_NAND); - if (result.IsSuccess()) - { - common::HeapManager decHeap(bufSize); - void *dec = decHeap.GetAddr(); - if (dec != NULL) - { - // AES復号化する - nn::crypto::SwAesCtrContext swAesCtrContest; - - swAesCtrContest.Initialize(common::iv, common::key, sizeof(common::key)); - swAesCtrContest.Decrypt(dec, enc, readSize); - - // IVS書き込み - result = fos.TryInitialize(common::IVS_NAND_PATHNAME, true); - if (result.IsSuccess()) - { - if (result.IsSuccess()) - { - // 2ndNUPからはAPI経由で書き込む - if (RequiresImportApi()) - { - result = nn::fs::CTR::ImportIntegrityVerificationSeed( - *reinterpret_cast(dec)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - COMMON_LOGGER("Import SDCI.\n"); - } - else - { - s32 writeSize; - result = fos.TryWrite(&writeSize, dec, readSize, true); - if (result.IsSuccess()) - { - COMMON_LOGGER("Import SDCI.\n"); - } - } - } - } - } - else - { - COMMON_LOGGER("Failed Allocate Heap!!\n"); - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - } - nn::fs::Unmount(common::NAND_ARCHIVE_NAME); - } - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - COMMON_LOGGER("Failed Allocate Heap!!\n"); - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return result; -} - -bool ImportIvsData() -{ - return ImportIvs().IsSuccess(); -} - -bool RequiresImportApi() -{ - return common::CUP_MAJOR_VER_2ND_NUP <= s_SDVersionData.cup.majorVersion; -} - -void ImportThreadFunc() -{ - nn::Result result; - s_IsImportSucceeded = true; - - result = nn::fs::MountSpecialArchive(common::NAND_ARCHIVE_NAME, nn::fs::CTR::ARCHIVE_TYPE_CTR_NAND); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - result = common::SdMountManager::Mount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - size_t bufSize = common::GetAllocatableSize(AES_BLOCK_SIZE * 2); - NN_LOG("AllocatableSize = %d\n", bufSize); - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - - common::HeapManager heap(bufSize, AES_BLOCK_SIZE * 2); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - // 吸い出したバージョンによって書き込み関数を変える - if(RequiresImportApi()) - { - common::SaveDataMover saveDataMover; - saveDataMover.StartImport(buf, bufSize, &s_ImportProgress); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED( - saveDataMover.GetLastResult(), s_IsImportSucceeded - ); - } - else - { - if (!common::CopyDirectory( - &s_FileLists, - (::std::wstring(common::SDMC_ROOT_DIRECTORY_PATH) + ::std::wstring(common::SD_SAVEDATA_ROOT_NAME)).c_str(), - common::NAND_DATA_ROOT_PATHNAME_WITH_SLASH, buf, bufSize, false, NULL, NULL)) - { - s_IsImportSucceeded = false; - return; - } - } - } - - common::SdMountManager::Unmount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - nn::fs::Unmount(common::NAND_ARCHIVE_NAME); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - NN_LOG("Import Thread Finalize\n"); -} - -namespace -{ - -void ImportSaveData() -{ - // SDカードからNANDに読み込み - nn::Result result; - - // ファイルサイズ設定 - common::InitializeTransferProgress(s_SdFileSize.ctrFileSize); - - // SDカードにあるセーブデータディレクトリ以下のデータをNANDにコピー - COMMON_LOGGER("Import NAND Data Start...\n"); - s_ImportThread.Start(ImportThreadFunc, s_ImportThreadStack); - -} - -nn::Result ImportNorData() -{ - COMMON_LOGGER("Import NOR Data.\n"); - - nn::Result result = nn::ResultSuccess(); - - nn::cfg::nor::CTR::Initialize(); - - size_t bufSize = common::GetAllocatableSize() / 2; - NN_LOG("AllocatableSize = %d\n", bufSize); - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::NOR_PATHNAME, buf, bufSize, &readSize); - if(result.IsSuccess()) - { - // cfgを使ってセットする - result = nn::cfg::nor::CTR::SetNtrSetting(&reinterpret_cast(buf)->ntrConfig.ncd, - &reinterpret_cast(buf)->ntrConfig.ncd_ex); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // WiFiコネクションIDが仮の値であればWiFi設定は移行しない - // TWL修理に準拠している - u64 attestedUserId1 = 0; - u64 attestedUserId2 = 0; - const u32 WIFI_CONNECTION_USERID_OFFSET1 = 0xf0; - const u32 WIFI_CONNECTION_USERID_OFFSET2 = 0x1f0; - const u32 USERID_SIZE = 6; - const bit64 USERID_MASK = 0x7FFFFFFFFFF; // 43bit - - - void* NtrWifiSettingAddr = &reinterpret_cast(buf)->NtrWiFiSetting; - std::memcpy(&attestedUserId1, - &reinterpret_cast(NtrWifiSettingAddr)[WIFI_CONNECTION_USERID_OFFSET1], - USERID_SIZE); - attestedUserId1 &= USERID_MASK; - - std::memcpy(&attestedUserId2, - &reinterpret_cast(NtrWifiSettingAddr)[WIFI_CONNECTION_USERID_OFFSET2], - USERID_SIZE); - attestedUserId2 &= USERID_MASK; - - if (attestedUserId1 == attestedUserId2 && attestedUserId1 != 0) - { - // TWL WiFi設定 - result = nn::cfg::nor::CTR::WriteTwlWifiSetting(0, - reinterpret_cast (buf)->TwlWiFiSetting, common::TWL_WIFI_SETTING_SIZE); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // NTR WiFi設定 - result = nn::cfg::nor::CTR::WriteNtrWifiSetting(0, - reinterpret_cast (buf)->NtrWiFiSetting, common::NTR_WIFI_SETTING_SIZE); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - // クリアしておく - result = nn::cfg::nor::CTR::ClearTwlWifiSetting(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::nor::CTR::ClearNtrWifiSetting(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - } - - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - COMMON_LOGGER("Failed Allocate Heap!!\n"); - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return result; -} - - -} - -nn::Result ReadVersionData() -{ - nn::Result result = nn::ResultSuccess(); - std::memset(&s_SDVersionData, 0, sizeof(common::VerDef)); - - size_t bufSize = common::GetAllocatableSize() / 2; - NN_LOG("AllocatableSize = %d\n", bufSize); - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::VERSION_DATA_PATHNAME, buf, bufSize, &readSize); - if(result.IsSuccess()) - { - // バージョン情報を保持する - std::memcpy(&s_SDVersionData, buf, readSize); - NN_LOG("SD Version = %02d.%02d.%02d-%02d\n", s_SDVersionData.cup.majorVersion, - s_SDVersionData.cup.minorVersion, - s_SDVersionData.cup.microVersion, - s_SDVersionData.nup.majorVersion); - } - - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - COMMON_LOGGER("Failed Allocate Heap!!\n"); - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return result; -} - -bool ExistsIvsDirectory(std::string& ivsRoot) -{ - nn::Result result; - nn::fs::Directory dir; - - common::SdMountManager::Mount(); - - result = dir.TryInitialize(common::SD_NINTENDO_3DS_ROOT_PATH); - if(result.IsFailure()) - { - COMMON_LOGGER_RESULT_IF_FAILED(result); - common::SdMountManager::Unmount(); - return false; - } - - wchar_t ivs[34]; - std::mbstowcs(ivs, ivsRoot.c_str(), ivsRoot.size() + 1); - - nn::fs::DirectoryEntry entry; - s32 numEntry; - for (;;) - { - result = dir.TryRead(&numEntry, &entry, 1); - if (result.IsFailure()) - { - dir.Finalize(); - common::SdMountManager::Unmount(); - return false; - } - if (numEntry == 0) - { - dir.Finalize(); - common::SdMountManager::Unmount(); - return false; - } - else - { - // 比較する - if (entry.attributes.isDirectory) - { - NN_LOG("%ls\n", entry.entryName); - if(std::wcscmp(ivs, entry.entryName) == 0) - { - common::SdMountManager::Unmount(); - return true; - } - } - } - } -} - -nn::Result Cleanup() -{ - nn::Result result; - bool execCleanup; - - result = nn::am::NeedsCleanup(&execCleanup, nn::fs::MEDIA_TYPE_NAND); - if(result.IsSuccess()) - { - if(execCleanup) - { - COMMON_LOGGER("Cleanup NAND\n"); - return nn::am::DoCleanup(nn::fs::MEDIA_TYPE_NAND); - } - } - - return result; -} - -void DeleteAllCheckFiles() -{ - nn::Result result; - common::SdMountManager::Mount(); - - for(u32 i = 0; i < sizeof(CHECK_FILENAME_TABLE) / sizeof(CHECK_FILENAME_TABLE[0]); i++) - { - if(common::CheckFileExists(CHECK_FILENAME_TABLE[i])) - { - result = nn::fs::TryDeleteFile(CHECK_FILENAME_TABLE[i]); - COMMON_LOGGER_RESULT_IF_FAILED(result); - } - } - common::SdMountManager::Unmount(); -} - -void FinalizeImportThread() -{ - s_ImportThread.Join(); - s_ImportThread.Finalize(); -} - -bool IsImportThreadFinished() -{ - return s_ImportThread.IsValid() && !s_ImportThread.IsAlive(); -} - -void CreateWriteFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_WRITE_FINISHED]); - common::ClearFileCheck(common::EXISTS_WRITE_FINISHED); -} - -void CreateConsoleInitializedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_CONSOLE_INTIALIZED]); - common::ClearFileCheck(common::EXISTS_CONSOLE_INTIALIZED); -} - -void CreateUpdateFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_UPDATE_FINISHED]); - common::ClearFileCheck(common::EXISTS_UPDATE_FINISHED); -} - -void CreateRtcSyncFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_RTC_SYNC_FINISHED]); - common::ClearFileCheck(common::EXISTS_RTC_SYNC_FINISHED); -} - -void CreateDownloadIvsFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_DOWNLOAD_IVS]); - common::ClearFileCheck(common::EXISTS_DOWNLOAD_IVS); -} - -void CreateDeleteAccountFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_DELETE_ACCOUNT]); - common::ClearFileCheck(common::EXISTS_DELETE_ACCOUNT); - -} - -void CreateTransferAccountFinishedFile() -{ - CreateEmptyFile(common::FILENAME_TABLE[common::EXISTS_TRANSFER_ACCOUNT]); - common::ClearFileCheck(common::EXISTS_TRANSFER_ACCOUNT); -} - -u32 GetImportProgress() -{ - if(RequiresImportApi()) - { - return s_ImportProgress; - } - else - { - return common::GetProgress(); - } -} - -u32 GetImportProgressTwlNand() -{ - return common::GetProgress(); -} - bool UpdateNetworkSetting(nn::ac::NetworkSetting& networkSetting) { nn::Result result; @@ -1141,7 +217,7 @@ void ReadSettingFlag(common::ConfigFileLoader* loader, const wchar_t* paramName, } } -bool ReadSetting(bool* nupOnly, bool* getIvs, bool* checkSd, bool* skipNup, bool* dlPreinstall) +bool ReadSetting() { nn::Result result; bool retval = true; @@ -1411,44 +487,6 @@ bool ReadSetting(bool* nupOnly, bool* getIvs, bool* checkSd, bool* skipNup, bool } } - { - const char* ntpServerName = configfileLoader.ReadAsChar(L"NTPSRV"); // NTPサーバ - if(ntpServerName == NULL) - { - COMMON_LOGGER("NTPSRV: is missing\n"); - retval = false; - } - else - { - std::strlcpy(s_NtpServerName, ntpServerName, sizeof(s_NtpServerName)); - COMMON_LOGGER("NTPSRV = %s\n", s_NtpServerName); - } - - - } - - { - const char* timeZone = configfileLoader.ReadAsChar(L"TIMEZONE"); // タイムゾーン - if(timeZone == NULL) - { - COMMON_LOGGER("TIMEZONE: is missing\n"); - retval = false; - } - else - { - std::strlcpy(s_TimeZoneStr, timeZone, sizeof(s_TimeZoneStr)); - COMMON_LOGGER("TIMEZONE = %s\n", s_TimeZoneStr); - ConvertTimeZoneString(s_TimeZoneStr); - } - - } - - ReadSettingFlag(&configfileLoader, L"NUP_ONLY", nupOnly, "NUP Only Mode.\n"); - ReadSettingFlag(&configfileLoader, L"GET_SDCI", getIvs, "GET SDCI Mode.\n"); - ReadSettingFlag(&configfileLoader, L"CHECK_SD", checkSd, "CHECK SD Mode.\n"); - ReadSettingFlag(&configfileLoader, L"SKIP_NUP", skipNup, "Skip NUP Mode.\n"); - ReadSettingFlag(&configfileLoader, L"DL_PREINSTALL", dlPreinstall, "Download PreInstall Application Mode.\n"); - configfileLoader.Finalize(); // 書き込み完了しなければfalse @@ -1476,572 +514,9 @@ bool ReadSetting(bool* nupOnly, bool* getIvs, bool* checkSd, bool* skipNup, bool return retval; } -char* GetNtpServerName() -{ - return s_NtpServerName; -} - -TimeZone GetTimeZone() -{ - return s_TimeZone; -} - CheckedNetworkSetting* GetTempNetworkSetting() { return &s_CurrentNetowrkSetting1; } -void ImportTwlData(enum common::TWL_PATH_INDEX path, s64 fileSize) -{ - NN_ASSERT(path < common::TWL_PATHNAME_MAX); - - nn::Result result; - s_IsImportSucceeded = true; - - result = nn::fs::MountSpecialArchive(common::TWL_ARCHIVE_NAME_TABLE[path], common::TWL_FS_ARCHIVE_KIND[path]); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - result = common::SdMountManager::Mount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - size_t bufSize = common::GetAllocatableSize(AES_BLOCK_SIZE * 2); - NN_LOG("AllocatableSize = %d\n", bufSize); - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - - // ファイルサイズ設定 - common::InitializeTransferProgress(fileSize); - - common::HeapManager heap(bufSize, AES_BLOCK_SIZE * 2); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - wchar_t archiveName[nn::fs::MAX_FILE_PATH_LENGTH]; - ::std::mbstowcs(archiveName, common::TWL_ARCHIVE_NAME_TABLE[path], std::strlen(common::TWL_ARCHIVE_NAME_TABLE[path]) + 1); - std::wstring archiveString(archiveName); - if(!common::CopyDirectory( - &s_FileLists, - (::std::wstring(common::SDMC_ROOT_DIRECTORY_PATH) + ::std::wstring(common::SD_TWL_ROOTNAME_TABLE[path])).c_str(), - (archiveString + ::std::wstring(L"/")).c_str(), - buf, bufSize, false, NULL, NULL)) - { - s_IsImportSucceeded = false; - return; - } - } - - common::SdMountManager::Unmount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - nn::fs::Unmount(common::TWL_ARCHIVE_NAME_TABLE[path]); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); -} - -void ImportTwlTitleSaveData(s64 fileSize) -{ - nn::Result result; - s_IsImportSucceeded = true; - - result = nn::fs::MountSpecialArchive(common::NAND_TWL_ARCHIVE_NAME, nn::fs::CTR::ARCHIVE_TYPE_TWL_NAND); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - result = common::SdMountManager::Mount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - - size_t bufSize = common::GetAllocatableSize(AES_BLOCK_SIZE * 2); - NN_LOG("AllocatableSize = %d\n", bufSize); - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - - // ファイルサイズ設定 - common::InitializeTransferProgress(fileSize); - - common::HeapManager heap(bufSize, AES_BLOCK_SIZE * 2); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - if(!common::CopyDirectory( - &s_FileLists, - (::std::wstring(common::SDMC_ROOT_DIRECTORY_PATH) + ::std::wstring(common::SD_SAVEDATA_TWL_ROOT_NAME)).c_str(), - (std::wstring(common::NAND_TWL_DATA_ROOT_PATHNAME_WITHOUT_SLASH) + ::std::wstring(L"/")).c_str(), - buf, bufSize, false, NULL, NULL)) - { - s_IsImportSucceeded = false; - return; - } - } - - common::SdMountManager::Unmount(); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); - nn::fs::Unmount(common::NAND_TWL_ARCHIVE_NAME); - COMMON_LOGGER_RETURN_VOID_SET_BOOL_IF_FAILED(result, s_IsImportSucceeded); -} - -void ImportTwlPhotoDataFunc() -{ - COMMON_LOGGER("Import Twl Photo Data.\n"); - ImportTwlData(common::TWL_PHOTO, s_SdFileSize.twlPhotoFileSize); -} - -void ImportTwlSoundDataFunc() -{ - COMMON_LOGGER("Import Twl Sound Data.\n"); - ImportTwlData(common::TWL_SOUND, s_SdFileSize.twlSoundFileSize); -} - -void ImportTwlSaveDataFunc() -{ - COMMON_LOGGER("Import Twl Save Data.\n"); - ImportTwlTitleSaveData(s_SdFileSize.twlFileSize); -} - -void ImportTwlPhotoData() -{ - s_ImportThread.Start(ImportTwlPhotoDataFunc, s_ImportThreadStack); -} - -void ImportTwlSoundData() -{ - s_ImportThread.Start(ImportTwlSoundDataFunc, s_ImportThreadStack); -} - -void ImportTwlSaveData() -{ - s_ImportThread.Start(ImportTwlSaveDataFunc, s_ImportThreadStack); -} - - -void ClearFileReadResult() -{ - s_CheckedEqualsRegionDataandRegion = false; - s_ReadSerialNumber = false; -} - -nn::Result ExportCalData() -{ - using namespace nn::cfg::CTR::detail; - - nn::Result result; - common::CfgCalData cfgCalData; - common::SdReaderWriter sdWriter; - - COMMON_LOGGER("Export CalData\n"); - - result = common::SdMountManager::Mount(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.touchPanelCfgData, sizeof(TouchPanelCfgData), - GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_TOUCHPANEL)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.lcdFlickerCfgData, sizeof(LcdFlickerCfgData), - GET_CFG_KEY(NN_CFG_LCD, NN_CFG_LCD_CAL_FLICKER)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.fcramCfgData, sizeof(FcramCfgData), - GET_CFG_KEY(NN_CFG_FCRAM, NN_CFG_FCRAM_CAL_DELAY)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.rtcCfgData, sizeof(RtcCfgData), - GET_CFG_KEY(NN_CFG_RTC, NN_CFG_RTC_CAL_COMPENSATION)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.gyroscopeCfgData, sizeof(GyroscopeCfgData), - GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_GYROSCOPE)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.accelCfgData, sizeof(AccelCfgData), - GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_ACCELEROMETER)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.codecCfgData, sizeof(CodecCfgData), - GET_CFG_KEY(NN_CFG_CODEC, NN_CFG_CODEC_CAL)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::GetConfig(&cfgCalData.mcuSlideVolumeRangeCfgData, sizeof(McuSlideVolumeRangeCfgData), - GET_CFG_KEY(NN_CFG_MCU, NN_CFG_MCU_SLIDE_VOLUME)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = sdWriter.WriteBufWithCmac(common::CFG_CALIBRATION_PATHNAME, &cfgCalData, sizeof(cfgCalData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = common::SdMountManager::Unmount(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - return nn::ResultSuccess(); -} - -nn::Result ImportCalData(common::CfgCalData *data) -{ - using namespace nn::cfg::CTR::detail; - - nn::Result result = nn::ResultSuccess(); - - COMMON_LOGGER("Import CalData\n"); - - common::SdMountManager::Mount(); - - size_t bufSize = common::GetAllocatableSize() / 2; - if(bufSize > common::FILE_COPY_HEAP_SIZE) - { - bufSize = common::FILE_COPY_HEAP_SIZE; - } - common::HeapManager heap(bufSize); - void* buf = heap.GetAddr(); - if (buf != NULL) - { - common::SdReaderWriter sdReader; - - size_t readSize; - result = sdReader.ReadBufWithCmac(common::CFG_CALIBRATION_PATHNAME, buf, bufSize, &readSize); - if(result.IsSuccess()) - { - // SDから読み出し成功 - std::memcpy(data, buf, readSize); - } - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - } - else - { - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - common::SdMountManager::Unmount(); - return result; -} - -nn::Result InitializeHardwareDependentSetting() -{ - using namespace nn::cfg::CTR::detail; - nn::Result result = nn::ResultSuccess(); - - common::CfgCalData cfgCalData; - result = ImportCalData(&cfgCalData); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_TOUCHPANEL), - &cfgCalData.touchPanelCfgData, sizeof(TouchPanelCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_LCD, NN_CFG_LCD_CAL_FLICKER), - &cfgCalData.lcdFlickerCfgData, sizeof(LcdFlickerCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_FCRAM, NN_CFG_FCRAM_CAL_DELAY), &cfgCalData.fcramCfgData, - sizeof(FcramCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_RTC, NN_CFG_RTC_CAL_COMPENSATION), - &cfgCalData.rtcCfgData, sizeof(RtcCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_GYROSCOPE), - &cfgCalData.gyroscopeCfgData, sizeof(GyroscopeCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_HID, NN_CFG_HID_CAL_ACCELEROMETER), - &cfgCalData.accelCfgData, sizeof(AccelCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_CODEC, NN_CFG_CODEC_CAL), &cfgCalData.codecCfgData, - sizeof(CodecCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = nn::cfg::CTR::init::SetConfig(GET_CFG_KEY(NN_CFG_MCU, NN_CFG_MCU_SLIDE_VOLUME), - &cfgCalData.mcuSlideVolumeRangeCfgData, sizeof(McuSlideVolumeRangeCfgData)); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - NN_LOG("Set cfgCalData\n"); - - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - nn::cfg::CTR::init::ResetCameraCalibration(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - nn::cfg::CTR::init::ResetAnalogStickCalibration(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - return result; -} - -nn::Result SetupVersionAndFileList() -{ - std::memset(&s_SdFileSize, 0, sizeof(s_SdFileSize)); - - // ファイル一覧を読み込む - nn::Result result = ReadFileList(&s_SdFileSize, &s_FileLists); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // バージョンデータを読み込む - result = ReadVersionData(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - return result; -} - -nn::Result ReadFileList(SdFileSize* sdFiles, common::ImportDataList* fileList) -{ - nn::Result result = nn::ResultSuccess(); - - COMMON_LOGGER("Read File List\n"); - - size_t readSize; - common::SdReaderWriter sdReader; - s64 fileSize; - { - nn::fs::FileInputStream file; - - // サイズ取得のため一時的に開く - result = file.TryInitialize(common::FILE_LIST_PATHNAME); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - result = file.TryGetSize(&fileSize); - if (result.IsFailure()) - { - file.Finalize(); - return result; - } - file.Finalize(); - } - - // 初期化状態の場合は空 - if(fileSize == nn::crypto::AES_CMAC_MAC_SIZE) - { - sdFiles->ctrFileSize = 0; - sdFiles->totalFileSize = 0; - sdFiles->twlFileSize = 0; - sdFiles->twlPhotoFileSize = 0; - sdFiles->twlSoundFileSize = 0; - return nn::ResultSuccess(); - } - - common::HeapManager heap(fileSize); - void* buf = heap.GetAddr(); - if(buf != NULL) - { - result = sdReader.ReadBufWithCmac(common::FILE_LIST_PATHNAME, buf, fileSize, &readSize); - if(result.IsSuccess()) - { - // ファイル一覧 - const char comma[] = ","; - const char newLine[] = "\n"; - char *token = NULL; - token = std::strtok(reinterpret_cast(buf), comma); - bool parseFileName = false; - common::ImportDataEntry entry; - - entry.fileName = std::string(token); - while( token != NULL) - { - if(parseFileName) - { - token = std::strtok(NULL, comma); - if(token != NULL) - { - entry.fileName = std::string(token); - } - } - else - { - token = std::strtok(NULL, newLine); - if(token != NULL) - { - s64 size = std::atoll(token); - if(size != -1) - { - entry.isDirectory = false; - sdFiles->totalFileSize += size; - - wchar_t wcToken[nn::fs::MAX_FILE_PATH_LENGTH]; - if(std::mbstowcs(wcToken, entry.fileName.c_str(), entry.fileName.size()) != entry.fileName.size() - 1) - { - if(std::wcsstr(wcToken, common::SD_SAVEDATA_ROOT_NAME) != NULL) - { - sdFiles->ctrFileSize += size; - } - else if(std::wcsstr(wcToken, common::SD_SAVEDATA_TWL_PHOTO_ROOT_NAME) != NULL) - { - sdFiles->twlPhotoFileSize += size; - } - else if(std::wcsstr(wcToken, common::SD_SAVEDATA_TWL_SOUND_ROOT_NAME) != NULL) - { - sdFiles->twlSoundFileSize += size; - } - else if(std::wcsstr(wcToken, common::SD_SAVEDATA_TWL_ROOT_NAME) != NULL) - { - sdFiles->twlFileSize += size; - } - } - } - else - { - entry.isDirectory = true; - } - - fileList->push_back(entry); - } - } - parseFileName = !parseFileName; - - } - - } - } - else - { - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - return result; - -} - -bool IsImportSucceeded() -{ - return s_IsImportSucceeded; -} - -void ReadRegionFile(const wchar_t* path, void** decode, size_t* size) -{ - if(path == NULL) - { - return; - } - - char filePath[256]; - std::wcstombs(filePath, path, sizeof(filePath)); - - char prefix[] = "rom:/regionData/"; - - char fullPath[256]; - std::memset(fullPath, 0, sizeof(fullPath)); - strlcpy(fullPath, prefix, sizeof(fullPath)); - strlcat(fullPath, filePath, 256 - strlen(fullPath)); - NN_LOG("regionData: %s\n", fullPath); - - nn::fs::FileInputStream file; - file.Initialize(fullPath); - - s64 fileSize = file.GetSize(); - common::HeapManager heap(fileSize, AES_BLOCK_SIZE); - void* buf = heap.GetAddr(); - - file.Read(buf, fileSize); - - *size = nn::cx::GetUncompressedSize(buf); - nn::cx::UncompressLZ(buf, *decode); -} - -void RepairSimpleAddress() -{ - nn::cfg::CTR::SimpleAddress sa; - nn::cfg::CTR::GetSimpleAddress(&sa); - - RegionIdModifier rim(sa.id >> 16, s_SDVersionData.nup.majorVersion, nn::cfg::CTR::GetRegion(), sa.regionName[0]); - if(rim.IsValid()) - { - // 壊れていなければ何もしない - return; - } - - COMMON_LOGGER("Repair SimpleAddress.\n"); - - size_t size; - PathList filePath[3]; - u8 modifiedId; - - common::HeapManager heap(common::FILE_COPY_HEAP_SIZE / 8 , AES_BLOCK_SIZE); - void* buf = heap.GetAddr(); - - size_t fileNum = rim.GetFilePathNum(); - - std::memset(filePath, 0, sizeof(filePath)); - std::memcpy(filePath, rim.GetFilePath(), sizeof(PathList) * fileNum); - - for (u8 i = 0; i < fileNum; i++) - { - ReadRegionFile(filePath[fileNum - i - 1].path, &buf, &size); - if (rim.GetValidRegionId(buf, size, &modifiedId)) - { - NN_LOG("CurrentRegionId = %02x\n", (sa.id >> 16) & 0x00ff); - NN_LOG("ValidRegionId = %02x\n", modifiedId); - using namespace nn::cfg::CTR; - using namespace nn::cfg::CTR::detail; - - nn::cfg::CTR::system::Initialize(); - - SimpleAddressIdCfgData simpleAddressId; - NN_UTIL_PANIC_IF_FAILED(nn::cfg::CTR::system::GetConfig(&simpleAddressId, sizeof(SimpleAddressIdCfgData), GET_CFG_KEY(NN_CFG_SIMPLE_ADDRESS, NN_CFG_SIMPLE_ADDRESS_ID))); - - simpleAddressId.id = (simpleAddressId.id & 0xff00ffff) | (modifiedId << CFG_SIMPLE_ADDRESS_ID_REGION_SHIFT); - - NN_UTIL_PANIC_IF_FAILED(nn::cfg::CTR::system::SetConfig(GET_CFG_KEY(NN_CFG_SIMPLE_ADDRESS, NN_CFG_SIMPLE_ADDRESS_ID), &simpleAddressId, sizeof(SimpleAddressIdCfgData))); - - NN_UTIL_PANIC_IF_FAILED(nn::cfg::CTR::system::FlushConfig()); - nn::cfg::CTR::system::Finalize(); - } - } -} - -void RestoreCurrentInternetSetting() -{ - COMMON_LOGGER("Restore Current Internet Setting\n"); - nn::Result result; - if (GetTempNetworkSetting()->isValid) - { - result = nn::ac::CTR::UpdateNetworkSetting(0, GetTempNetworkSetting()->setting); - COMMON_LOGGER_RESULT_IF_FAILED(result); - } - else - { - // 無効の場合は消去しておく - result = nn::ac::CTR::RemoveNetworkSetting(0); - COMMON_LOGGER_RESULT_IF_FAILED(result); - } - - result = nn::ac::FlushNetworkSetting(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - result = nn::ac::FinalizeInternal(); - COMMON_LOGGER_RESULT_IF_FAILED(result); -} - - - -nn::Result ImportData() -{ - static nn::Result result = nn::ResultSuccess(); - static bool init = true; - if(init) - { - init = false; - - // インポート前にACを止める - result = nn::ndm::SuspendScheduler(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // NANDのごみを削除する - result = Cleanup(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // NORデータを書き込む - result = ImportNorData(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // 固体固有calLデータをSDカードに出力する - // 本体初期化後はcal値が設定されている - result = ExportCalData(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - // SDカードのセーブデータをNANDに書き込む - ImportSaveData(); - } - - return result; -} - } diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.h b/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.h index 0f2d782..0d76c2b 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.h +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/Importer.h @@ -25,86 +25,6 @@ namespace ConsoleRestore { -// SDカードのデバイスIDファイルが存在するか -nn::Result ExistsDeviceIdFile(); - -// SDカードのデバイスIDファイルと本体のデバイスIDが一致しているかどうか -bool EqualsDeviceIdFileandDeviceId(common::HardwareStateManager& manager); - -// SDカードのリージョンと本体のリージョンが一致しているかどうか -nn::Result EqualsRegionDataandRegion(); - -// シリアルナンバーを取得する -nn::Result ReadSerialNumber(u8* serial); - -// 出力ファイル一覧を読み込む -nn::Result SetupVersionAndFileList(); - -// インポート用のスレッドを終了する -void FinalizeImportThread(); - -// インポート用のスレッドが終了したかどうか -bool IsImportThreadFinished(); - -// 新たにスレッドを立て、TWLサウンド領域をインポートする -void ImportTwlSoundData(); - -// 新たにスレッドを立て、TWL-NAND領域をインポートする -void ImportTwlSaveData(); - -// 新たにスレッドを立て、TWL写真領域をインポートする -void ImportTwlPhotoData(); - -// 本体固有データを読み込む -// 新たにスレッドを立て、CTRセーブデータ領域をインポートする -nn::Result ImportData(); - -// インポート完了ファイルを作る -void CreateWriteFinishedFile(); - -// ネットワークアップデート完了ファイルを作る -void CreateUpdateFinishedFile(); - -// 本体初期化完了ファイルを作る -void CreateConsoleInitializedFile(); - -// RTC書き込み完了ファイルを作る -void CreateRtcSyncFinishedFile(); - -// IVSダウンロード完了ファイルを作る -void CreateDownloadIvsFinishedFile(); - -// アカウント削除完了ファイルを作る -void CreateDeleteAccountFinishedFile(); - -// アカウント移行完了ファイルを作る -void CreateTransferAccountFinishedFile(); - -// インポートスレッドの進捗を取得する -u32 GetImportProgress(); - -// インポートスレッドの進捗を取得する -u32 GetImportProgressTwlNand(); - -// NANDのごみを削除する -nn::Result Cleanup(); - - -// ファイルが存在するかどうか確認するためのテーブル -const wchar_t* const CHECK_FILENAME_TABLE[] = -{ - common::UPDATE_CHECK_PATHNAME, - common::INITIALIZED_CHECK_PATHNAME, - common::WRITE_FINISHED_CHECK_PATHNAME, - common::RTC_SYNC_CHECK_PATHNAME, - common::DOWNLOAD_IVS_CHECK_PATHNAME, - common::DELETE_ACCOUNT_CHECK_PATHNAME, - common::TRANSFER_ACCOUNT_CHECK_PATHNAME -}; - -// ファイル存在確認をクリアする -void DeleteAllCheckFiles(); - struct TimeZone { u32 hour; @@ -114,15 +34,7 @@ struct TimeZone }; // ネットワーク設定ファイルを読み込む -bool ReadSetting(bool* nupOnly, bool* getIvs, bool* checkSd, bool* skipNup, bool* dlPreinstall); - -// ネットワーク設定ファイルからNTPサーバの名前を取得する -// 先にReadSettingが成功している必要がある -char* GetNtpServerName(); - -// ネットワーク設定ファイルからタイムゾーンを取得する -// 先にReadSettingが成功している必要がある -TimeZone GetTimeZone(); +bool ReadSetting(); // インターネット設定をユーザの設定に戻す void RestoreCurrentInternetSetting(); diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.cpp deleted file mode 100644 index f91848a..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: NtpClient.cpp - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Importer.h" -#include "CommonLogger.h" - -namespace ConsoleRestore -{ - -namespace { - -const size_t NTP_THREAD_STACK_SIZE = 0x1000; -nn::os::Thread s_NtpThread; -nn::os::StackBuffer s_NtpThreadStack; -bool s_NtpSyncSuccessed = false; - - -struct NTP_Packet{ // NTPパケット - u32 controlWord; - u32 rootDelay; - u32 rootDispersion; - u32 referenceId; - s64 referenceTimestamp; - s64 startTimestamp; - s64 receiveTimestamp; - u32 transmitTimestampSeconds; - u32 transmitTimestampFractions; -}; - -const size_t TIMEOUT_MILLISECOND = 5000; // タイムアウト ミリ秒数 -NTP_Packet s_NTPSendPacket; // 送信するNTPパケット -NTP_Packet s_NTPRecvPacket; // 受信するNTPパケット -const u32 NTP_PORT_NUM = 123; - -bool GetNtpTime(u32* ntpTime) -{ - nn::Result result; - - bool retval = true; - NN_LOG("Initializing network.\n"); - - // 本体に書き込まれているネットワーク設定を使ってネットワーク接続を初期化 - if(!nn::ac::IsConnected()) - { - result = common::InitializeNetwork(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - } - - { - NN_LOG("Initializing socket..\n"); - - // 一つのスレッドからソケット API を利用する - const s32 sessionCount = 1; - // ソケットの送受信バッファとして 64 KB を割り当て - const size_t bufferSizeForSockets = 65536; - // ソケットライブラリに必要なワークサイズを求める - const size_t workSizeForLibrary = nn::socket::GetRequiredMemorySize(bufferSizeForSockets, sessionCount); - - // ワークメモリを確保して 4KB にアラインにする - u8* pWorkMemory = new u8[workSizeForLibrary + 4096]; - uptr workMemoryAddress = nn::math::RoundUp(reinterpret_cast (pWorkMemory), 4096); - - // ソケットライブラリの初期化 - result = nn::socket::Initialize(workMemoryAddress, workSizeForLibrary, bufferSizeForSockets, sessionCount); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - { - s32 ret; - nn::socket::InAddr addr, netmask; - ret = nn::socket::GetPrimaryAddress(reinterpret_cast (&addr), reinterpret_cast (&netmask)); - NN_ASSERT(ret == 0); - COMMON_LOGGER("host : %s\n", nn::socket::InetNtoA(addr)); - COMMON_LOGGER("netmask : %s\n", nn::socket::InetNtoA(netmask)); - - nn::socket::InAddr dns1, dns2; - ret = nn::socket::GetResolver(reinterpret_cast (&dns1), reinterpret_cast (&dns2)); - if (ret == 0) - { - COMMON_LOGGER("dns1 : %s\n", nn::socket::InetNtoA(dns1)); - COMMON_LOGGER("dns2 : %s\n", nn::socket::InetNtoA(dns2)); - } - - nn::socket::InAddr gateway; - ret = nn::socket::GetDefaultGateway(reinterpret_cast (&gateway)); - if (ret == 0) - { - COMMON_LOGGER("gateway : %s\n", nn::socket::InetNtoA(gateway)); - } - - COMMON_LOGGER("\n"); -#ifndef NN_SWITCH_DISABLE_DEBUG_PRINT - nn::socket::DumpRoutingTable(); -#endif - } - - { - s32 socket = nn::socket::Socket(nn::socket::PF_INET, nn::socket::SOCK_DGRAM, 0); - NN_LOG("socket = %d\n", socket); - - // クライアントアドレスの設定 - nn::socket::SockAddrIn host_addr; - host_addr.len = sizeof(nn::socket::SockAddrIn); - host_addr.family = nn::socket::AF_INET; - host_addr.addr.addr = 0; - host_addr.port = nn::socket::HtoNs(NTP_PORT_NUM); - - // ローカルアドレスをバインド - s32 ret = nn::socket::Bind(socket, &host_addr); - NN_LOG("bind = %d\n", ret); - - // ******************************************************************************** - // NTPパケットを生成して送る - // ******************************************************************************** - - // サーバアドレスの設定 - nn::socket::SockAddrIn serverSockAddrIn; - serverSockAddrIn.len = sizeof(nn::socket::SockAddrIn); - serverSockAddrIn.family = nn::socket::AF_INET; - - // GetHostByNameを使う場合 - nn::socket::HostEnt* serverHostent; - u64 serveraddr = 0; - serverHostent = nn::socket::GetHostByName(GetNtpServerName()); - if (serverHostent == NULL) - { - COMMON_LOGGER("Error: GetHostByName %s\n", GetNtpServerName()); - retval = false; - } - else - { - // サーバのホスト情報からIPアドレスをコピー - serveraddr = *(reinterpret_cast (serverHostent->addrList[0])); - } - serverSockAddrIn.addr.addr = serveraddr; - COMMON_LOGGER("Destination address: %s\n", nn::socket::InetNtoA(serverSockAddrIn.addr)); - serverSockAddrIn.port = nn::socket::HtoNs(NTP_PORT_NUM); // ポート番号 - - // NTPパケットをSNTP用に初期化する - s_NTPSendPacket.controlWord = nn::socket::HtoNl(0x0B000000); - s_NTPSendPacket.rootDelay = 0; - s_NTPSendPacket.rootDispersion = 0; - s_NTPSendPacket.referenceId = 0; - s_NTPSendPacket.referenceTimestamp = 0; - s_NTPSendPacket.startTimestamp = 0; - s_NTPSendPacket.receiveTimestamp = 0; - s_NTPSendPacket.transmitTimestampSeconds = 0; - s_NTPSendPacket.transmitTimestampFractions = 0; - - // サーバを指定してNTPパケットを送信する - if ((ret = nn::socket::SendTo(socket, reinterpret_cast (&s_NTPSendPacket), sizeof(s_NTPSendPacket), 0, - &serverSockAddrIn)) < 0) - { - COMMON_LOGGER("Error: Failed Send to Server, %d\n", ret); - retval = false; - } - - NN_LOG("SendTo finished\n"); - - // 受信待ち - nn::socket::PollFd pollFd; - pollFd.fd = socket; - pollFd.events = nn::socket::POLLRDNORM; - if ((ret = nn::socket::Poll(&pollFd, 1, TIMEOUT_MILLISECOND)) < 0) - { - COMMON_LOGGER("Error: recv error, %d\n", ret); - retval = false; - } - - NN_LOG("Poll Finished\n"); - - switch (pollFd.revents) - { - case nn::socket::POLLERR: // ソケットにエラーが発生しました。 - COMMON_LOGGER("Error: POLLERR %s %d\n", __func__, __LINE__); - retval = false; - break; - case nn::socket::POLLHUP: // ストリーム・ソケットが未接続です。 - COMMON_LOGGER("Error: POLLHUP %s %d\n", __func__, __LINE__); - retval = false; - break; - case nn::socket::POLLNVAL: // 不正なソケット記述子です。 - COMMON_LOGGER("Error: POLLNVAL %s %d\n", __func__, __LINE__); - retval = false; - break; - default: - break; - } - - // サーバから時刻情報を受信する - // サーバを指定して受信を行う - // 受信するまで待たされる - if ((ret = nn::socket::RecvFrom(socket, reinterpret_cast (&s_NTPRecvPacket), sizeof(s_NTPRecvPacket), nn::socket::MSG_DONTWAIT, - &serverSockAddrIn)) < 0) - { - COMMON_LOGGER("Error: RecvFrom, %d\n", ret); - retval = false; - } - - NN_LOG("RecvFrom finished\n"); - - // NTPサーバから取得した時刻を現地時間に変換する - *ntpTime = nn::socket::NtoHl(s_NTPRecvPacket.transmitTimestampSeconds) - 2208988800; /* 1970/01/01 からの秒数に変換 */ - NN_LOG("ntp_time = %d\n", ntpTime); - - nn::socket::Close(socket); - NN_UNUSED_VAR(ret); - } - - NN_LOG("Finalizing socket..\n"); - // ソケットライブラリの終了 - result = nn::socket::Finalize(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - } - - NN_LOG("Finalizing network.\n"); - result = common::FinalizeNetwork(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - return retval; -} - -} - -void NtpThreadFunc() -{ - // NTP時間を取得する - u32 ntpTime; - if (GetNtpTime(&ntpTime)) - { - // タイムゾーンを考慮してDateTimeに変換する - TimeZone timeZone = GetTimeZone(); - - // 1970/01/01 - nn::fnd::DateTime utc = nn::fnd::DateTime(1970, 1, 1, 0, 0, 0, 0); - nn::fnd::DateTime current = utc + nn::fnd::TimeSpan::FromSeconds(ntpTime); - - if (timeZone.isMinus) - { - current -= (nn::fnd::TimeSpan::FromHours(timeZone.hour) + nn::fnd::TimeSpan::FromMinutes(timeZone.minutes)); - } - else - { - current += nn::fnd::TimeSpan::FromHours(timeZone.hour) + nn::fnd::TimeSpan::FromMinutes(timeZone.minutes); - } - - // SWCを書き込む - nn::ptm::CTR::SetUserTime(current); - - COMMON_LOGGER("Set User Time %04d/%02d/%02d %02d:%02d:%02d\n", - current.GetYear(), current.GetMonth(), current.GetDay(), current.GetHour(), current.GetMinute(), current.GetSecond()); - - s_NtpSyncSuccessed = true; - } - else - { - COMMON_LOGGER("Failed Get Ntp Time\n"); - s_NtpSyncSuccessed = false; - } -} - -bool IsTimeAdjustFinished() -{ - // Initialize済みかつ終了 - return s_NtpThread.IsValid() && !s_NtpThread.IsAlive(); -} - -bool IsTimeAdjustSuccessed() -{ - return s_NtpSyncSuccessed; -} - -void AdjustTime() -{ - nn::Result result; - - result = nn::ac::CTR::InitializeInternal(); - COMMON_LOGGER_RESULT_IF_FAILED(result); - - if(IsTimeAdjustFinished()) - { - s_NtpThread.Join(); - s_NtpThread.Finalize(); - } - s_NtpThread.Start( NtpThreadFunc, s_NtpThreadStack); -} - -} diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.h b/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.h deleted file mode 100644 index ecc2c1e..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/NtpClient.h +++ /dev/null @@ -1,33 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: NtpClient.h - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#ifndef NTPCLIENT_H_ -#define NTPCLIENT_H_ - -namespace ConsoleRestore -{ - -// 新たにスレッドを立て、NTPサーバと同期する -u32 AdjustTime(); - -// NTPサーバとの同期が終了したかどうか -bool IsTimeAdjustFinished(); - -// NTPサーバとの同期が完了したかどうか -bool IsTimeAdjustSuccessed(); - -} - -#endif /* NTPCLIENT_H_ */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/OMakefile b/trunk/NetworkUpdater/sources/NetworkUpdater/OMakefile index a9dc6e4..08d4e38 100644 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/OMakefile +++ b/trunk/NetworkUpdater/sources/NetworkUpdater/OMakefile @@ -28,17 +28,9 @@ SOURCES[] = Controller.cpp Importer.cpp Updater.cpp - Ntpclient.cpp - TitleDownloader.cpp - Shop.cpp - RegionIdModifier.cpp - PreinstallImporter.cpp - ActCompleter.cpp ../common/Util.cpp - ../common/DrawSystemState.cpp - ../common/FileTransfer.cpp ../common/FileChecker.cpp - ../common/SdReaderWriter.cpp + ../common/DrawSystemState.cpp ../common/HeapManager.cpp ../common/SdLogger.cpp ../common/wave.cpp @@ -50,9 +42,7 @@ SOURCES[] = ../common/VersionDetect.cpp ../common/ResFont.cpp ../common/HardwareStateManager.cpp - ../common/SaveDataMover.cpp ../common/OperationMessage.cpp - ../common/QrImage.cpp include $(ROOT)/common/BuildSwitch.om diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.cpp deleted file mode 100644 index 577dda5..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: PreinstallImporter.cpp - - Copyright 2009-2011 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#include "CommonLogger.h" -#include "HeapManager.h" -#include "PreinstallImporter.h" -#include -#include - -namespace ConsoleRestore -{ - -PreinstallImporter::PreinstallImporter() -{ - // TODO 自動生成されたコンストラクター・スタブ - -} - -PreinstallImporter::~PreinstallImporter() -{ - // TODO Auto-generated destructor stub -} - -nn::Result PreinstallImporter::SetupSd(bool* isAlreadyAvailable, bool forcePreinstall) -{ - // SDカードがインポート可能状態かどうかチェック - COMMON_LOGGER_RETURN_RESULT_IF_FAILED( - nn::am::QueryAvailableExternalTitleDatabase(isAlreadyAvailable) - ); - - // タイトルデータベースを作成する - if (!*isAlreadyAvailable) - { - COMMON_LOGGER_RETURN_RESULT_IF_FAILED( - nn::am::InitializeExternalTitleDatabase() - ); - } - - if(forcePreinstall) - { - // 未初期化として返す - *isAlreadyAvailable = false; - } - return nn::ResultSuccess(); -} - -nn::Result PreinstallImporter::ListTitlesBasedOnTickets(nn::ProgramId* list, size_t* num) -{ - s32 personalizedTicketNum; - nn::am::TicketInfo ticketInfo[256]; - COMMON_LOGGER_RETURN_RESULT_IF_FAILED( - nn::am::GetPersonalizedTicketInfoList(&personalizedTicketNum, ticketInfo, 256) - ); - - if(personalizedTicketNum == 0) - { - return nn::MakePermanentResult(nn::Result::SUMMARY_NOT_FOUND, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_NOT_FOUND); - } - - *num = 0; - for(s32 i = 0; i < personalizedTicketNum; i++) - { - list[*num] = ticketInfo[i].titleId; - (*num)++; - } - - return nn::ResultSuccess(); -} - -} /* namespace ConsoleRestore */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.h b/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.h deleted file mode 100644 index 8156e05..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/PreinstallImporter.h +++ /dev/null @@ -1,42 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: PreinstallImporter.h - - Copyright 2009-2011 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#ifndef PREINSTALLIMPORTER_H_ -#define PREINSTALLIMPORTER_H_ - -#include -#include - -namespace ConsoleRestore -{ - -//! @brief プリインストールをSDカードに書き込むためのクラスです -class PreinstallImporter -{ -public: - PreinstallImporter(); - virtual ~PreinstallImporter(); - - //! @brief 外部タイトルデータベースを作成します - //! @param[out] list    SDカードが初期化済みかどうか - //! @param[in] forcePreinstall    SDカードが初期化済みでもプリインストールを書き込むかどうか - nn::Result SetupSd(bool* isAlreadyAvailable, bool forcePreinstall); - - //!@ brief プリインストールタイトルをeTicketに基づいてリストアップする - nn::Result ListTitlesBasedOnTickets(nn::ProgramId* list, size_t* num); -}; - -} /* namespace ConsoleRestore */ -#endif /* PREINSTALLIMPORTER_H_ */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.cpp deleted file mode 100644 index 9f5fa7b..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.cpp +++ /dev/null @@ -1,153 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: RegionIdModifier.cpp - - Copyright (C)2011 Nintendo Co., Ltd. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev:$ - *---------------------------------------------------------------------------*/ -#include "RegionIdModifier.h" -#include -#include - -struct CountryData -{ - u32 id; // 上記定数にあるように、国IDと地域IDを組み合わせたID - u16 regionName[nn::cfg::CTR::CFG_SIMPLE_ADDRESS_NUM_LANGUAGES][nn::cfg::CTR::CFG_SIMPLE_ADDRESS_NAME_LENGTH]; // NULL終端込み - u8 order[nn::cfg::CTR::CFG_SIMPLE_ADDRESS_NUM_LANGUAGES]; // 言語ごとの地域名並び順(「未設定」が0になるので、最初の地域は1) - u16 latitude; // リストの値を 65536/360 倍して格納して下さい - u16 longitude; // リストの値を 65536/360 倍して格納して下さい -}; - -const size_t NUP_VERSION_TO_REGIONNUM[] = -{ - 1, // ローンチ(0) - 1, // 0thNUP(1) - 2, // 1stNUP(2) - 2, // 1.05NUP(3) - 2, // 1.1NUP(4) - 3, // 2ndNUP(5) - 3, // 2.1NUP(6) -}; - -const wchar_t* DIR_PATH[] = -{ - L"0/JP/", - L"0/US/", - L"0/EU/", - L"2/JP/", - L"2/US/", - L"2/EU/", - L"5/JP/", - L"5/US/", - L"5/EU/" -}; - -RegionIdModifier::RegionIdModifier(u16 id, u8 nupVersion, u8 regionCode, const wchar_t* regionName) -{ - m_Id = id; - m_NupVersion = nupVersion; - m_RegionCode = regionCode; - if (regionName != NULL) - { - std::wcsncpy(m_RegionName, regionName, sizeof(m_RegionName) / sizeof(wchar_t)); - } -} - -bool RegionIdModifier::IsValid() -{ - return (m_Id & 0x00ff) != 0x01; -} - -const PathList* RegionIdModifier::GetDirectoryPath() -{ - // 範囲外のリージョン - if (nn::cfg::CTR::CFG_REGION_EUROPE < m_RegionCode) - { - return NULL; - } - - for (u8 i = 0; i < nn::cfg::CTR::CFG_REGION_EUROPE + 1; i++) - { - std::wcsncpy(m_DirectoryPathBuf[i].path, DIR_PATH[m_RegionCode + i * (nn::cfg::CTR::CFG_REGION_EUROPE + 1)], - PATHLIST_LENGTH); - } - - return m_DirectoryPathBuf; -} - -size_t RegionIdModifier::GetDirectoryPathNum() -{ - // 範囲外のリージョン - if (nn::cfg::CTR::CFG_REGION_EUROPE < m_RegionCode) - { - return 0; - } - - const size_t countryNum = sizeof(NUP_VERSION_TO_REGIONNUM) / sizeof(NUP_VERSION_TO_REGIONNUM[0]); - if (m_NupVersion > countryNum - 1) - { - return NUP_VERSION_TO_REGIONNUM[countryNum - 1]; - } - else - { - return NUP_VERSION_TO_REGIONNUM[m_NupVersion]; - } -} - -const wchar_t* RegionIdModifier::GetFileName() -{ - std::swprintf(m_FileNameBuf, sizeof(m_FileNameBuf), L"%d_LZ.bin", m_Id >> 8); - return m_FileNameBuf; -} - -const PathList* RegionIdModifier::GetFilePath() -{ - std::memset(m_FilePathBuf, 0, sizeof(m_FilePathBuf)); - GetDirectoryPath(); - for (u8 i = 0; i < GetDirectoryPathNum(); i++) - { - size_t writeSize = std::wcslen(m_DirectoryPathBuf[i].path); - std::wcsncpy(m_FilePathBuf[i].path, m_DirectoryPathBuf[i].path, writeSize); - std::wcsncat(m_FilePathBuf[i].path, GetFileName(), PATHLIST_LENGTH - writeSize); - } - - return m_FilePathBuf; -} - -size_t RegionIdModifier::GetFilePathNum() -{ - return GetDirectoryPathNum(); -} - -bool RegionIdModifier::GetValidRegionId(void* buf, size_t size, u8* id) -{ - if (buf == NULL || size == 0) - { - return false; - } - - u32 numRegion; // その国に含まれる地域の数 - numRegion = *reinterpret_cast(buf); - - CountryData* pCountry; - pCountry = reinterpret_cast(&reinterpret_cast(buf)[1]); - - for (u32 i = 0; i < numRegion + 1; i++) - { - if (std::wcscmp(m_RegionName, reinterpret_cast(pCountry->regionName[0])) == 0) - { - *id = (pCountry->id >> 16) & 0x00ff; - return true; - } - pCountry++; - } - - return false; -} diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.h b/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.h deleted file mode 100644 index 69c78fc..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/RegionIdModifier.h +++ /dev/null @@ -1,89 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: RegionIdModifier.h - - Copyright (C)2011 Nintendo Co., Ltd. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev:$ - *---------------------------------------------------------------------------*/ -#ifndef _REGION_ID_MODIFIER_H_ -#define _REGION_ID_MODIFIER_H_ - -#if defined(__ARMCC_VERSION) -#include -#include -#else -#include "test_common.h" -#endif - -const size_t PATHLIST_LENGTH = 32; -struct PathList -{ - wchar_t path[PATHLIST_LENGTH]; -}; - -//! @brief データ移行ツールで破壊した地域idを修正するためのクラスです -class RegionIdModifier -{ - public: - //! @brief パラメータを与えて初期化します。 - //! @param[in] id SimpleAddressの上位16ビット - //! @param[in] nupVersion NUPバージョン - //! @param[in] regionCode リージョン - //! @param[in] regionName 地域名 - RegionIdModifier(u16 id, u8 nupVersion, u8 regionCode, const wchar_t* regionName); - ~RegionIdModifier() {}; - - //! @brief 正しいIDかどうか - bool IsValid(); - - //! @brief バージョン、リージョンに応じたディレクトリパスの配列を取得します - //! @return パス名。バージョン・リージョンが正しくない場合はNULL - const PathList* GetDirectoryPath(); - - //! @brief バージョン、リージョンに応じたディレクトリパス数を取得します - size_t GetDirectoryPathNum(); - - //! @brief 国idに応じたファイル名を取得します - const wchar_t* GetFileName(); - - //! @brief バージョン、リージョン、国idに応じたファイルパスの配列を取得します - const PathList* GetFilePath(); - - //! @brief バージョン、リージョン、国idに応じたファイルパス数を取得します - size_t GetFilePathNum(); - - //! @brief 与えられたバッファから正しい地域idを取得します - //! @param[in] buf 展開済みの地域データの入ったバッファ - //! @param[in] size バッファサイズ - //! @param[out] id 正しいid - //! @return 正しいidが見つかったかどうか - bool GetValidRegionId(void* buf , size_t size, u8* id); - - private: - //! @brief SimpleAddressの上位16ビット - // 上位8ビットが国id,下位8ビットが地域 - u16 m_Id; - - //! @brief NUPバージョン番号 - u8 m_NupVersion; - //! @brief リージョンコード - u8 m_RegionCode; - //! @brief 地域名 - wchar_t m_RegionName[nn::cfg::CTR::CFG_SIMPLE_ADDRESS_NAME_LENGTH]; - - //! @brief ファイル名を保存するバッファ - wchar_t m_FileNameBuf[PATHLIST_LENGTH]; - //! @brief ディレクトリパスを保存するバッファ - PathList m_DirectoryPathBuf[nn::cfg::CTR::CFG_REGION_EUROPE + 1]; - //! @brief ファイルパスを保存するバッファ - PathList m_FilePathBuf[nn::cfg::CTR::CFG_REGION_EUROPE + 1]; -}; - -#endif // _REGION_ID_MODIFIER_H_ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.cpp deleted file mode 100644 index 6fa251e..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.cpp +++ /dev/null @@ -1,503 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: Shop.cpp - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "Shop.h" -#include "CommonLogger.h" -#include "Util.h" - -using namespace ES_NAMESPACE; -using namespace EC_NAMESPACE; - -#define NIM_SHOP_RESULT_CHECK(result) \ -do { \ - ::nn::Result shopResult = (result); \ - if (shopResult.IsFailure()) \ - { \ - ECCustomerSupportCode csc; \ - nn::nim::Shop::GetCustomerSupportCode(&csc); \ - if(csc != 0)\ - {\ - COMMON_LOGGER("CSCode: %d\n", csc); \ - }\ - COMMON_LOGGER_RESULT_IF_FAILED(shopResult); \ - NN_DBG_PRINT_RESULT(shopResult); \ - COMMON_LOGGER_DETAIL("Result = %08X\n", shopResult.GetPrintableBits()); \ - s_ShopResult = shopResult; \ - return; \ - } \ -} while(0) -namespace -{ - -nn::Result s_ShopResult = nn::ResultSuccess(); - -const size_t SHOP_OPERATION_THREAD_STACK_SIZE = 0x1000; -nn::os::Thread s_ShopOperationThread; -nn::os::StackBuffer s_ShopOperationThreadStack; - -const size_t EC_BUFFER_SIZE = 128 * 1024; -u8 s_EcBufffer[EC_BUFFER_SIZE]; -bool s_IsNimShopInitialized = false; - -struct ShopThreadParam -{ - ConsoleRestore::ShopOperation op; - NN_PADDING3; - NN_PADDING4; - nn::nim::TitleConfig config; -}; - -// TitleProgress の ==, != を定義 -bool operator==( - nn::nim::TitleProgress& lhs, - nn::nim::TitleProgress& rhs) -{ - return (lhs.state == rhs.state && - lhs.lastResult == rhs.lastResult && - lhs.downloadedSize == rhs.downloadedSize && - lhs.totalSize == rhs.totalSize); -} - -bool operator!=( - nn::nim::TitleProgress& lhs, - nn::nim::TitleProgress& rhs) -{ - return (! (lhs == rhs)); -} - -// TitleState の文字列を取得 -#ifdef COMMON_LOGGER_DETAIL_ENABLE -const char* GetTitleStateString(nn::nim::TitleState state) -{ - switch (state) - { - case nn::nim::TITLE_STATE_NOT_INITIALIZED: - return "NOT_INITIALIZED"; - case nn::nim::TITLE_STATE_INITIALIZED: - return "INITIALIZED"; - case nn::nim::TITLE_STATE_DOWNLOAD_TMD: - return "DOWNLOAD_TMD"; - case nn::nim::TITLE_STATE_PREPARE_SAVE_DATA: - return "PREPARE_SAVE_DATA"; - case nn::nim::TITLE_STATE_DOWNLOAD_CONTENTS: - return "DOWNLOAD_CONTENTS"; - case nn::nim::TITLE_STATE_WAIT_COMMIT: - return "WAIT_COMMIT"; - case nn::nim::TITLE_STATE_COMMITTING: - return "COMMITTING"; - case nn::nim::TITLE_STATE_FINISHED: - return "FINISHED"; - case nn::nim::TITLE_STATE_VERSION_MISMATCH: - return "VERSION_MISMATCH"; - default: - return "UNKNOWN"; - } -} -#endif - - -// 空文字列と NULL ポインタをそれぞれ と NULL として返す -#ifdef COMMON_LOGGER_DETAIL_ENABLE -const char* Cstr(const char* p) -{ - return p ? (p[0] ? p : "") : "NULL"; -} -#endif - -// ECTicketVersions を出力 -void PrintECTicketVersions(const ECTicketVersions& ticketVersions) -{ - if (ticketVersions.nTicketVersions == 0) - { - COMMON_LOGGER_DETAIL("No TicketVersions\n"); - return; - } - - COMMON_LOGGER_DETAIL("----- ECTicketVersions -----\n"); - for (u32 i = 0; i < ticketVersions.nTicketVersions; i++) - { -#ifdef COMMON_LOGGER_DETAIL_ENABLE - ECTicketVersion version = ticketVersions.ticketVersions[i]; -#endif - COMMON_LOGGER_DETAIL("%03d: 0x%016llx v%d\n", i, version.ticketId, version.version); - } - COMMON_LOGGER_DETAIL("---------------------------\n"); -} - -// ECAccountInfo の情報を出力 -void PrintECAccountInfo(const ECAccountInfo& accountInfo) -{ - COMMON_LOGGER_DETAIL("========== ECAccountInfo ==========\n"); - - COMMON_LOGGER_DETAIL("accountId\n %s\n", Cstr(accountInfo.accountId)); - - COMMON_LOGGER_DETAIL("accountStatus\n %s\n", Cstr(accountInfo.accountStatus)); - - if (accountInfo.accountBalance == NULL) - { - COMMON_LOGGER_DETAIL("accountBalance\n NULL\n"); - } - else - { - COMMON_LOGGER_DETAIL("accountBalance->amount\n %s\n", - Cstr(accountInfo.accountBalance->amount)); - COMMON_LOGGER_DETAIL("accountBalance->currency\n %s\n", - Cstr(accountInfo.accountBalance->currency)); - } - - if (accountInfo.agreedEULAVersion == NULL) - { - COMMON_LOGGER_DETAIL("agreedEULAVersion\n NULL\n"); - } - else - { - COMMON_LOGGER_DETAIL("agreedEULAVersion\n %lld\n", - *accountInfo.agreedEULAVersion); - } - - if (accountInfo.latestEULAVersion == NULL) - { - COMMON_LOGGER_DETAIL("latestEULAVersion\n NULL\n"); - } - else - { - COMMON_LOGGER_DETAIL("latestEULAVersion\n %lld\n", - *accountInfo.latestEULAVersion); - } - - COMMON_LOGGER_DETAIL("country\n %s\n", Cstr(accountInfo.country)); - - COMMON_LOGGER_DETAIL("extAccountId\n %s\n", Cstr(accountInfo.extAccountId)); - - COMMON_LOGGER_DETAIL("deviceToken\n %s\n", Cstr(accountInfo.deviceToken)); - - COMMON_LOGGER_DETAIL("weakToken\n %s\n", Cstr(accountInfo.weakToken)); - - COMMON_LOGGER_DETAIL("isStandbyMode\n %d\n", accountInfo.isStandbyMode); - - if (accountInfo.owned == NULL) - { - COMMON_LOGGER_DETAIL("owned\n NULL\n"); - } - else - { - PrintECTicketVersions(*(accountInfo.owned)); - } -} - -} - - -namespace ConsoleRestore{ - -nn::Result ShopOperationConnect(); -nn::Result ShopOperationFinalize(); - - -nn::Result CheckStandbyMode(s32 isStandbyMode) -{ - if(isStandbyMode) - { - COMMON_LOGGER("Shop is Standby Mode\n"); - return nn::MakePermanentResult(nn::Result::SUMMARY_INVALID_STATE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_NOT_AUTHORIZED); - } - else - { - return nn::ResultSuccess(); - } -} - -nn::Result ShopOperationConnect(ECAccountInfo** pAccountInfo) -{ - nn::Result result = nn::ResultSuccess(); - - /* ------------------------------------------------------------------- - Connect - -------------------------------------------------------------------- */ - COMMON_LOGGER_DETAIL("nim::Shop::Connect\n"); - result = nn::nim::Shop::Connect(pAccountInfo, s_EcBufffer, EC_BUFFER_SIZE); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - result = CheckStandbyMode((*pAccountInfo)->isStandbyMode); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - PrintECAccountInfo(**pAccountInfo); - COMMON_LOGGER_DETAIL("\n"); - - return result; -} - -nn::Result ShopOperationInitialize() -{ - nn::Result result = nn::ResultSuccess(); - - /* ------------------------------------------------------------------- - Initialize - -------------------------------------------------------------------- */ - if (!s_IsNimShopInitialized) - { - COMMON_LOGGER_DETAIL("nim::InitializeForShop\n"); - result = nn::nim::InitializeForShop(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - s_IsNimShopInitialized = true; - } - - /* ------------------------------------------------------------------- - SetParameter - -------------------------------------------------------------------- */ - COMMON_LOGGER_DETAIL("nim::Shop::SetApplication Id\n"); - - nn::nim::Shop::SetApplicationId(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - COMMON_LOGGER_DETAIL("nim::Shop::SetTIN\n"); - result = nn::nim::Shop::SetTin(CONSOLE_RESTORE_TIN); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - return result; -} - -nn::Result ShopOperationConnect() -{ - nn::Result result; - result = ShopOperationInitialize(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - /* ------------------------------------------------------------------- - Connect - -------------------------------------------------------------------- */ - ECAccountInfo* pAccountInfo; - result = ShopOperationConnect(&pAccountInfo); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - - return result; -} - -nn::Result ShopOperationFinalize() -{ - nn::Result result = nn::ResultSuccess(); - - /* ------------------------------------------------------------------- - Finalize - -------------------------------------------------------------------- */ - COMMON_LOGGER_DETAIL("nim::FinalizeForShop\n"); - result = nn::nim::FinalizeForShop(); - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(result); - s_IsNimShopInitialized = false; - - return result; -} - -namespace -{ - -void ShopOperationUnregisterCore(bool force) -{ - nn::Result result; - result = ShopOperationInitialize(); - NIM_SHOP_RESULT_CHECK(result); - ECAccountInfo* pAccountInfo; - result = ShopOperationConnect(&pAccountInfo); - NIM_SHOP_RESULT_CHECK(result); - if (force) - { - if (pAccountInfo->accountStatus && (pAccountInfo->accountStatus[0] == 'R' || pAccountInfo->accountStatus[0] - == 'T')) - { - COMMON_LOGGER_DETAIL("nim::Shop::Unregister\n"); - result = nn::nim::Shop::Unregister(); - NIM_SHOP_RESULT_CHECK(result); - } - } - else - { - if (pAccountInfo->accountStatus && (pAccountInfo->accountStatus[0] == 'R')) - { - COMMON_LOGGER_DETAIL("nim::Shop::Unregister\n"); - result = nn::nim::Shop::Unregister(); - NIM_SHOP_RESULT_CHECK(result); - } - else - { - COMMON_LOGGER_DETAIL("Not registered.\n"); - } - } -} - -// メイン関数 -void ShopOperationSingleThreadFunc(ShopThreadParam param) -{ - nn::Result result; - - s_ShopResult = nn::ResultSuccess(); - - if(!nn::ac::IsConnected()) - { - COMMON_LOGGER_DETAIL("util::ac::Initialize\n"); - result = common::InitializeNetwork(); - NIM_SHOP_RESULT_CHECK(result); - } - - switch(param.op) - { - case SHOP_OPERATION_CONNECT: - { - result = ShopOperationConnect(); - NIM_SHOP_RESULT_CHECK(result); - } - break; - - case SHOP_OPERATION_GET_IVS: - { - result = ShopOperationInitialize(); - NIM_SHOP_RESULT_CHECK(result); - // IVSを取得する - result = nn::nim::Shop::ImportIvsFromInfrastructure(); - NIM_SHOP_RESULT_CHECK(result); - } - break; - - case SHOP_OPERATION_UNREGISTER: - { - ShopOperationUnregisterCore(false); - } - break; - - case SHOP_OPERATION_FORCE_UNREGISTER: - { - ShopOperationUnregisterCore(true); - } - break; - - case SHOP_OPERATION_CONNECT_WITHOUT_CLOSE: - { - result = ShopOperationConnect(); - NIM_SHOP_RESULT_CHECK(result); - return; - } - - - { - case SHOP_OPERATION_DOWNLOAD_TITLE: - COMMON_LOGGER_DETAIL("Try Download %016llx\n", param.config.titleId); - result = nn::nim::Shop::StartDownload(param.config); - - if (result == nn::nim::ResultBusy() || result == nn::nim::ResultAlreadyDone()) - { - COMMON_LOGGER("Download Content -> Nim is busy\n"); - } - else if (result == nn::nim::ResultInvalidTitle()) - { - COMMON_LOGGER("Download Content -> Invalid Title\n"); - } - else if (result.IsFailure()) - { - COMMON_LOGGER("Download Content -> Failure %x\n", result.GetPrintableBits()); - } - - /* ------------------------------------------------------------------- - GetProgress - -------------------------------------------------------------------- */ - - COMMON_LOGGER_DETAIL("nim::Shop::GetProgress()\n"); - nn::nim::TitleProgress before; - nn::nim::TitleProgress latest; - while (true) - { - result = nn::nim::Shop::GetProgress(&latest); - - NIM_SHOP_RESULT_CHECK(result); - NIM_SHOP_RESULT_CHECK(latest.lastResult); - - // Print progress - if (latest != before) - { - COMMON_LOGGER_DETAIL("%8lld / %8lld (%d:%s)\n", - latest.downloadedSize, - latest.totalSize, - latest.state.Get(), - GetTitleStateString(latest.state)); - - if (latest.state == nn::nim::TITLE_STATE_FINISHED) - { - COMMON_LOGGER_DETAIL("Finished Download\n"); - break; - } - - before = latest; - } - - // あまりにも頻繁に GetProgress を呼ぶと、ダウンロード処理の速度に - // 影響が出てしまいます。少なくとも数フレーム以上の間隔をあけて - // GetProgress することを推奨します。 - nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(100)); - } - } - break; - } - - result = ShopOperationFinalize(); - NIM_SHOP_RESULT_CHECK(result); -} - -} - -void StartShopOperationSingle(ShopOperation op, nn::nim::TitleConfig config) -{ - COMMON_LOGGER_DETAIL("Start ShopOperationSingle, %s\n", SHOP_OPERATION_STR[op]); - - ShopThreadParam param; - param.op = op; - param.config = config; - s_ShopOperationThread.Start(ShopOperationSingleThreadFunc, param, s_ShopOperationThreadStack); -} - -void StartShopOperationSingle(ShopOperation op) -{ - ShopThreadParam param; - param.op = op; - - COMMON_LOGGER_DETAIL("Start ShopOperationSingle, %s\n", SHOP_OPERATION_STR[op]); - s_ShopOperationThread.Start(ShopOperationSingleThreadFunc, param, s_ShopOperationThreadStack); -} - -void FinalizeShopOperationSingle() -{ - COMMON_LOGGER_DETAIL("Finalize ShopOperationSingle\n"); - s_ShopOperationThread.Join(); - s_ShopOperationThread.Finalize(); -} - -bool IsShopOperationSingleFinished() -{ - return s_ShopOperationThread.IsValid() && !s_ShopOperationThread.IsAlive(); -} - -nn::Result GetShopOperationSingleResult() -{ - return s_ShopResult; -} - -} diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.h b/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.h deleted file mode 100644 index b928134..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/Shop.h +++ /dev/null @@ -1,68 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: Shop.h - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#ifndef SHOP_H_ -#define SHOP_H_ - -#include -#include - -namespace ConsoleRestore -{ - -// ショップサーバにConsoleResotoreが接続するためのTINコード -const char* const CONSOLE_RESTORE_TIN = "987654321"; - -typedef enum SHOP_OPERATION -{ - SHOP_OPERATION_CONNECT, // Shop::ConnectしてCloseするだけ - SHOP_OPERATION_GET_IVS, // Shop::ImportIvsFromInfrastructureを実行 - SHOP_OPERATION_UNREGISTER, // Shop::Unregisterを実行 - SHOP_OPERATION_FORCE_UNREGISTER, // アカウント移行後でもUnregisterを実行 - SHOP_OPERATION_CONNECT_WITHOUT_CLOSE, // Shop::ConnectしてCloseしない - SHOP_OPERATION_DOWNLOAD_TITLE, // Titleをダウンロードする - SHOP_OPERATION_NUM_MAX - -} ShopOperation; - -// ショップ操作のモード表示用文字列(デバッグ用) -const char* const SHOP_OPERATION_STR[] = -{ - "Connect", - "Get SDCI", - "Unregister", - "Force Unregister", - "Connect Without Close", - "Download Title" -}; - -// 新たにスレッドを立て、ショップ操作を開始する -void StartShopOperationSingle(ShopOperation op, nn::nim::TitleConfig config); - -// 新たにスレッドを立て、ショップ操作を開始する -void StartShopOperationSingle(ShopOperation op); - -// ショップ操作スレッドを終了する -void FinalizeShopOperationSingle(); - -// ショップ操作スレッドが終了したかどうか -bool IsShopOperationSingleFinished(); - -// ショップ操作のResultを取得する -nn::Result GetShopOperationSingleResult(); - -} - -#endif /* SHOP_H_ */ diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.cpp b/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.cpp deleted file mode 100644 index 4dedbcf..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.cpp +++ /dev/null @@ -1,441 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: TitleDownloader.cpp - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#include -#include -#include -#include -#include - -#include "SdMountManager.h" -#include "common_Types.h" -#include "FileName.h" -#include "CommonLogger.h" -#include "HeapManager.h" -#include "TitleDownloader.h" -#include "Shop.h" -#include "SdReaderWriter.h" -#include "PreinstallImporter.h" - - -namespace -{ - -bit8 s_buffer1[400 * 1024]; - -// ダウンロードするタイトルの個数 -size_t s_ProgramIdNum = 0; -// ダウンロードするタイトルのProgramIdの配列 -nn::ProgramId s_ProgramIdList[256]; -// ダウンロード済みのタイトルの個数 -size_t s_FinishedTitleNum = 0; - -const size_t TITLE_DOWNLOADER_STACK_SIZE = 0x2000; -nn::os::Thread s_TitleDownloaderThread; -nn::os::StackBuffer s_TitleDownloaderThreadStack; -u64 s_Progress; - -nn::fs::MediaType GetMediaType(const ES_NAMESPACE::ESTitleId titleId) -{ - return (nn::CTR::IsTwlApp(titleId)) ? - nn::fs::MEDIA_TYPE_NAND : nn::fs::MEDIA_TYPE_SDMC; -} - -const char *GetAttribute(EC_NAMESPACE::ECNameValuePair *attributes, u32 nAttributes, const char *attributeName) -{ - for(int i=0; inEntries == 1) - { - *entry = &(titleCatalog->entries[0]); - } - else - { - return nn::MakeStatusResult(nn::Result::SUMMARY_NOT_FOUND, nn::Result::MODULE_COMMON, nn::Result::DESCRIPTION_NOT_FOUND); - } - - } - return result; -} - -nn::Result GetTitleConfig(const ES_NAMESPACE::ESTitleId titleId, nn::nim::TitleConfig *titleConfig, s64* requiredSize) -{ - EC_NAMESPACE::ECTitleCatalogEntry *entry; - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(GetEntry(titleId, &entry)); - - titleConfig->titleId =titleId; - titleConfig->version=std::strtoull(GetAttribute(entry->attributes, entry->nAttributes, "Version"), NULL, 10); - titleConfig->ratingAge=0; - titleConfig->media=GetMediaType(titleId); - *requiredSize=std::strtoull(GetAttribute(entry->attributes, entry->nAttributes, "MaxUserFileSize"), NULL, 10); - - COMMON_LOGGER_DETAIL("titleId : 0x%016llx\n", titleConfig->titleId); - COMMON_LOGGER_DETAIL("version : %lld\n" , titleConfig->version); - COMMON_LOGGER_DETAIL("ratingAge : %d\n" , titleConfig->ratingAge); - COMMON_LOGGER_DETAIL("media : %d\n" , titleConfig->media); - COMMON_LOGGER_DETAIL("size : %lld\n" , *requiredSize); - - - return nn::ResultSuccess(); -} - - -} // namespace - -namespace ConsoleRestore -{ - -nn::Result TitleDownloader::m_Result = nn::ResultSuccess(); - -void TwlTitleDownloaderThreadFunc() -{ - TitleDownloader TwlTitleDownloader; - - s_Progress = 0; - TitleDownloader::m_Result = ListUpTwlTitles(s_ProgramIdList, &s_ProgramIdNum); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(TitleDownloader::m_Result); - TwlTitleDownloader.SetupTitleList(s_ProgramIdList, s_ProgramIdNum, s_FinishedTitleNum); - TwlTitleDownloader.Start(); - s_FinishedTitleNum = TwlTitleDownloader.GetFinishedTitleNum(); -} - -void PreinstallTitleDownloaderThreadFunc() -{ - TitleDownloader PreinstallTitleDownloader; - - s_Progress = 0; - s_FinishedTitleNum = 0; - PreinstallTitleDownloader.SetupTitleList(s_ProgramIdList, s_ProgramIdNum, s_FinishedTitleNum); - PreinstallTitleDownloader.Start(); - s_FinishedTitleNum = PreinstallTitleDownloader.GetFinishedTitleNum(); -} - -void StartTwlTitleDownload() -{ - s_TitleDownloaderThread.Start(TwlTitleDownloaderThreadFunc, s_TitleDownloaderThreadStack); -} - - -void PreparePreinstallTitleDownloadThreadFunc(PreinstallListupParam param) -{ - PreinstallImporter importer; - bool isAlreadyAvailable = false; - TitleDownloader preinstallTitleDownloader; - preinstallTitleDownloader.m_Result = importer.ListTitlesBasedOnTickets(s_ProgramIdList, &s_ProgramIdNum); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(preinstallTitleDownloader.m_Result); - - preinstallTitleDownloader.SetupTitleList(s_ProgramIdList, s_ProgramIdNum, s_FinishedTitleNum); - - s64 requiredSize; - preinstallTitleDownloader.CalculateRequiredSize(&requiredSize); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(preinstallTitleDownloader.m_Result); - s64 total; - s64 free; - preinstallTitleDownloader.m_Result= common::SdMountManager::Mount(); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(preinstallTitleDownloader.m_Result); - preinstallTitleDownloader.m_Result = nn::fs::GetSdmcSize(&total, &free); - NN_LOG("total = %lld, free = %lld\n", total, free); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(preinstallTitleDownloader.m_Result); - preinstallTitleDownloader.m_Result= common::SdMountManager::Unmount(); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(preinstallTitleDownloader.m_Result); - NN_LOG("requiredSize = %lld\n", requiredSize + 8 * 1024 * 1024); - - // TODO: SDデータベースの正確なサイズを反映する - if(free < requiredSize + 8 * 1024 * 1024) - { - preinstallTitleDownloader.m_Result = nn::MakePermanentResult(nn::Result::SUMMARY_OUT_OF_RESOURCE, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_OUT_OF_MEMORY); - return; - } - - preinstallTitleDownloader.m_Result = importer.SetupSd(&isAlreadyAvailable, param.forcePreinstall); - if(isAlreadyAvailable) - { - preinstallTitleDownloader.m_Result = nn::MakePermanentResult(nn::Result::SUMMARY_INVALID_STATE, - nn::Result::MODULE_APPLICATION, nn::Result::DESCRIPTION_ALREADY_INITIALIZED); - return; - } - -} - -void StartPreparePreinstallTitleDownload(bool forcePreinstall) -{ - PreinstallListupParam param; - param.forcePreinstall = forcePreinstall; - - s_TitleDownloaderThread.Start(PreparePreinstallTitleDownloadThreadFunc, param, s_TitleDownloaderThreadStack); -} - -void StartPreinstallTitleDownload() -{ - s_TitleDownloaderThread.Start(PreinstallTitleDownloaderThreadFunc, s_TitleDownloaderThreadStack); -} - -bool IsDownloadTitleFinished() -{ - return s_TitleDownloaderThread.IsValid() && !s_TitleDownloaderThread.IsAlive(); -} - -void FinalizeTitleDownload() -{ - s_TitleDownloaderThread.Join(); - s_TitleDownloaderThread.Finalize(); -} - -bool DownloadTitleSucceeded() -{ - return TitleDownloader::m_Result.IsSuccess(); -} - -nn::Result GetTitleDownloadResult() -{ - return TitleDownloader::m_Result; -} - -u32 GetTitleDownloadProgress() -{ - return s_Progress; -} - - -TitleDownloader::TitleDownloader() : m_TiteNum(0), m_FinishedTitleNum(0) -{ - for(u32 i = 0; i < IMPORTABLE_TITLE_MAX; i++) - { - m_ProgramIdList[i] = 0; - } - -} - -TitleDownloader::~TitleDownloader() -{ - -} - -nn::Result ListUpTwlTitles(nn::ProgramId* list, size_t* num) -{ - nn::Result result; - COMMON_LOGGER("Read TwlTitle List.\n"); - - *num = 0; - size_t heapSize = common::GetAllocatableSize(); - if(heapSize > common::FILE_COPY_HEAP_SIZE) - { - heapSize = common::FILE_COPY_HEAP_SIZE; - } - common::HeapManager heap(heapSize); - char* titleListBuf = reinterpret_cast (heap.GetAddr()); - - size_t readSize = 0; - if (titleListBuf != NULL) - { - common::SdReaderWriter sdReader; - result = sdReader.ReadBufWithCmac(common::TWL_TITLELIST_PATHNAME, titleListBuf, heapSize, &readSize); - COMMON_LOGGER_RESULT_IF_FAILED(result); - if (result.IsSuccess()) - { - u32 listHead = 0; - for (u32 i = 0; i < readSize; i++) - { - if (titleListBuf[i] == '\n') - { - char ProgramIdStr[32]; - char *error; - std::memcpy(ProgramIdStr, &titleListBuf[listHead], i - listHead); - list[*num] = std::strtoull(ProgramIdStr, &error, 16); - (*num)++; - COMMON_LOGGER_DETAIL("%016llx\n", list[*num - 1]); - - listHead = i + 1; - } - } - } - COMMON_LOGGER("%d Title(s) found.\n", *num); - } - else - { - result = nn::Result(nn::Result::LEVEL_FATAL, nn::Result::SUMMARY_OUT_OF_RESOURCE, nn::Result::MODULE_COMMON, - nn::Result::DESCRIPTION_OUT_OF_MEMORY); - } - - return result; -} - -nn::Result WaitCancelled() -{ - nn::nim::TitleProgress progress; - while(true) - { - // キャンセルがResultとして返ってくる / ダウンロード終了まで待つ - COMMON_LOGGER_RETURN_RESULT_IF_FAILED(nn::nim::Shop::GetProgress(&progress)); - if(progress.lastResult==nn::nim::ResultCancelRequested() || progress.state==nn::nim::TITLE_STATE_FINISHED) - { - break; - } - nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(100)); - } - return nn::ResultSuccess(); -} - -void WaitShopOperationAndFinalize() -{ - while (!IsShopOperationSingleFinished()) - { - nn::os::Thread::Sleep(nn::fnd::TimeSpan::FromMilliSeconds(100)); - } - - FinalizeShopOperationSingle(); -} - -void StartShopOperationSingleRetry(ShopOperation op, u32 retryCount) -{ - for(u32 i = 0; i < retryCount; i++) - { - StartShopOperationSingle(op); - WaitShopOperationAndFinalize(); - if(GetShopOperationSingleResult().IsSuccess()) - { - break; - } - } -} - -void TitleDownloader::Start() -{ - COMMON_LOGGER("Download %d Title(s).\n", m_TiteNum); - for(u8 i = m_FinishedTitleNum; i < m_TiteNum; i++) - { - s_Progress = i * 100 / m_TiteNum; - - nn::am::ProgramInfo info; - - // 既にインポート済みならスキップ - if (nn::CTR::IsTwlApp(m_ProgramIdList[i])) - { - m_Result = nn::am::GetProgramInfos(&info, nn::fs::MEDIA_TYPE_NAND, &m_ProgramIdList[i], 1); - if (m_Result.IsSuccess()) - { - m_FinishedTitleNum++; - continue; - } - } - else if(nn::CTR::IsCtr(m_ProgramIdList[i])) - { - m_Result = nn::am::GetProgramInfos(&info, nn::fs::MEDIA_TYPE_SDMC, &m_ProgramIdList[i], 1); - if (m_Result.IsSuccess()) - { - m_FinishedTitleNum++; - continue; - } - } - - StartShopOperationSingle(SHOP_OPERATION_CONNECT_WITHOUT_CLOSE); - WaitShopOperationAndFinalize(); - m_Result = GetShopOperationSingleResult(); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(m_Result); - - nn::nim::TitleConfig config; - s64 requiredSize; - m_Result = GetTitleConfig(m_ProgramIdList[i], &config, &requiredSize); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(m_Result); - - StartShopOperationSingle(SHOP_OPERATION_DOWNLOAD_TITLE, config); - WaitShopOperationAndFinalize(); - - m_Result = GetShopOperationSingleResult(); - // ダウンロード済みならスキップ - if(m_Result == nn::nim::ResultAlreadyDownloaded()) - { - m_FinishedTitleNum++; - continue; - } - COMMON_LOGGER_RETURN_VOID_IF_FAILED(m_Result); - m_FinishedTitleNum++; - } - // 成功にセットしておく - m_Result = nn::ResultSuccess(); -} - -void TitleDownloader::SetupTitleList(nn::ProgramId* list, size_t num, u32 index) -{ - const size_t listNum = nn::math::Min(num, IMPORTABLE_TITLE_MAX); - for(u32 i = 0; i < listNum; i++) - { - m_ProgramIdList[i] = list[i]; - } - m_TiteNum = listNum; - m_FinishedTitleNum = index; -} - -void TitleDownloader::CalculateRequiredSize(s64* requiredSize) -{ - *requiredSize = 0; - for(u8 i = 0; i < m_TiteNum; i++) - { - s_Progress = i * 100 / m_TiteNum; - StartShopOperationSingleRetry(SHOP_OPERATION_CONNECT_WITHOUT_CLOSE, 3); - m_Result = GetShopOperationSingleResult(); - COMMON_LOGGER_RETURN_VOID_IF_FAILED(m_Result); - - nn::nim::TitleConfig config; - s64 size; - for(u8 j = 0; j < 3; j++) - { - m_Result = GetTitleConfig(m_ProgramIdList[i], &config, &size); - if(m_Result.IsSuccess()) - { - break; - } - - } - COMMON_LOGGER_RETURN_VOID_IF_FAILED(m_Result); - *requiredSize += size; - } -} - -u32 TitleDownloader::GetFinishedTitleNum() -{ - return m_FinishedTitleNum; -} - -} diff --git a/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.h b/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.h deleted file mode 100644 index b283d03..0000000 --- a/trunk/NetworkUpdater/sources/NetworkUpdater/TitleDownloader.h +++ /dev/null @@ -1,97 +0,0 @@ -/*---------------------------------------------------------------------------* - Project: Horizon - File: TitleDownloader.h - - Copyright 2009 Nintendo. All rights reserved. - - These coded instructions, statements, and computer programs contain - proprietary information of Nintendo of America Inc. and/or Nintendo - Company Ltd., and are protected by Federal copyright law. They may - not be disclosed to third parties or copied or duplicated in any form, - in whole or in part, without the prior written consent of Nintendo. - - $Rev$ - *---------------------------------------------------------------------------*/ - -#ifndef TITLEDOWNLOADER_H_ -#define TITLEDOWNLOADER_H_ - -#include - -namespace ConsoleRestore -{ - -// 新たにスレッドを立て、TWLタイトルのダウンロードを開始する -void StartTwlTitleDownload(); - -//! @brief プリインストールタイトルをSDカードにインポート可能かどうかサイズを確認し、
-//! 可能であればSDカードをインポート可能状態にします -//! @param[in] serialNo 強制的にプリインストールを書き込むかどうか -//! @return 正常に初期化できたかどうか -void StartPreparePreinstallTitleDownload(bool forcePreinstall); - -//! @brief 新たにスレッドを立て、プリインストールタイトルのダウンロードを開始します
-//! SDカードはインポート可能な状態にしておく必要があります。 -void StartPreinstallTitleDownload(); - - -// プリインストール情報取得に必要なパラメータをまとめた構造体 -struct PreinstallListupParam -{ - bool forcePreinstall; -}; - -//! @brief ダウンロードするTWLタイトルをSDカードからリストアップする -nn::Result ListUpTwlTitles(nn::ProgramId* list, size_t* num); - -// タイトルのダウンロードスレッドが終了したかどうか -bool IsDownloadTitleFinished(); - -// タイトルのダウンロードスレッドが成功したかどうか -bool DownloadTitleSucceeded(); - -// タイトルのダウンロード結果を取得する -nn::Result GetTitleDownloadResult(); - -// タイトルのダウンロードスレッドを終了する -void FinalizeTitleDownload(); - -// タイトルダウンロードの進捗を取得する -u32 GetTitleDownloadProgress(); - -// ショップからタイトルをダウンロードするためのクラス -class TitleDownloader -{ -public: - TitleDownloader(); - virtual ~TitleDownloader(); - - //! @brief タイトルリストを設定する - void SetupTitleList(nn::ProgramId* list, size_t num, u32 index); - - //! @brief タイトルをダウンロードするのに必要なサイズを計算します - void CalculateRequiredSize(s64* requiredSize); - - //! @brief ダウンロードが完了したタイトルの数を取得します - u32 GetFinishedTitleNum(); - - // タイトルのダウンロードを開始する - void Start(); - - NN_PADDING4; - static nn::Result m_Result; - -private: - - static const size_t IMPORTABLE_TITLE_MAX = 256; - - nn::ProgramID m_ProgramIdList[IMPORTABLE_TITLE_MAX]; - u32 m_TiteNum; - u32 m_FinishedTitleNum; - - -}; - -} - -#endif /* TITLEDOWNLOADER_H_ */