/*---------------------------------------------------------------------------* Project: Horizon File: sample_nadl_simple.cpp Copyright (C)2009-2012 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: 46365 $ *---------------------------------------------------------------------------*/ #include #include #include #include #include #include #include #define RESULT_SUCCESS_ASSERT NN_UTIL_PANIC_IF_FAILED #define NN_BOSS_RESULT_HANDLING(result, target) \ do { \ if(result.IsFailure()) \ { \ NN_LOG("Result is err(%08x).(%s)\n", result.GetPrintableBits(), target); \ } \ } while (0) namespace { nn::Result InitializeNetwork(void) { nn::Result result; nn::ac::Config config; nn::fs::Initialize(); result = nn::ac::Initialize(); NN_UTIL_PANIC_IF_FAILED(result); // Create parameters for connection request result = nn::ac::CreateDefaultConfig( &config ); if (result.IsFailure()) { NN_UTIL_PANIC_IF_FAILED(nn::ac::Finalize()); return result; } // Issue connection request result = nn::ac::Connect( config ); if (result.IsFailure()) { NN_UTIL_PANIC_IF_FAILED(nn::ac::Finalize()); return result; } return nn::ResultSuccess(); } nn::Result FinalizeNetwork(void) { nn::Result result; // Create parameters for connection request result = nn::ac::Close(); NN_UTIL_RETURN_IF_FAILED(result); result = nn::ac::Finalize(); NN_UTIL_PANIC_IF_FAILED(result); return nn::ResultSuccess(); } void DumpNsdBody(u8* pBodyBuf, size_t payloadLength) { #ifndef NN_SWITCH_DISABLE_DEBUG_PRINT NN_LOG("---NSD Body Dump (Payload-Length=%d)---\n", payloadLength); int hexCheckCount = 0; for(int i = 0; i < payloadLength; ++i) { NN_LOG("%02x ", pBodyBuf[i]); ++hexCheckCount; if(hexCheckCount == 16) { NN_LOG("\n"); hexCheckCount = 0; } } #else NN_UNUSED_VAR(pBodyBuf); NN_UNUSED_VAR(payloadLength); #endif } } //Expanded save data ID //(Expanded save data is required to use NADL tasks. The expanded save data ID specifies which expanded save data to use and is unique across all applications.) const bit32 APP_EXT_STORAGE_ID = 0x00000011; /* ------------------------------------------------------------------------ Sample code for a BOSS NADL task that downloads Nintendo archive data (in the NSA format) from a Nintendo server. NOTES - NADL tasks download data that is stored in each application's BOSS storage. BOSS storage is created in an application's expanded save data region. The expanded save data region is created on an SD Card. You must therefore insert an SD Card to run this demo. - BOSS tasks do not run unless the user has agreed to the EULA. Note that the user has not agreed to the EULA immediately after a system update. This must be set by the Config tool or some other means. - BOSS tasks run at intervals measured in hours. Although this demo registers a task with the smallest interval of one hour, the task runs for the first time one hour later. If you want to run the task and check behavior immediately, replace the dPolicy.Initialize section in the demo with dPolicy.InitializeWithSecInterval (the commented-out code) immediately below, which uses a test function. This can set the interval in seconds. (Tasks are consequently run for the first time after one second.) - If the NADL task downloads data that already exists in BOSS storage, BOSS deletes the download data. In this case, BOSS does not signal data download notification events waiting in the demo. As a result, when you run this demo continuously it will keep waiting at arriveEvent.Wait(); after it is run for the first time. To check processing that follows arriveEvent.Wait(); after the task is run for the first time, delete the download data in BOSS storage. (The code to delete download data in the demo is marked by the comment "Delete data." It is commented out by default.) ------------------------------------------------------------------------ */ void sampleNADLTaskBgExecute() { //Register BOSS storage. //NOTE: An application must register BOSS storage if it downloads data through NADL tasks. //Because BOSS saves the registered information, the application only needs to register storage when it is launched for the first time. //We therefore recommend that if an application uses BOSS, it is designed to register BOSS storage once when it creates new expanded save data (when nn::fs::CreateExtSaveData is run), as in this demo. // //NOTE: An error is returned if you specify an expanded save data ID to which the application does not have access permissions. //NOTE: Applications also register the maximum data size for BOSS storage. BOSS automatically adjusts the total size of data in BOSS storage so that it does not exceed this size. //(Specifically, when the total size exceeds the maximum data size, old data, or data with small serial IDs, is automatically deleted until the total size is no greater than the maximum size.) const size_t NADL_STORAGE_SIZE = 3*1024*1024; //The amount of the expanded save data region to use as BOSS storage. { nn::Result result = nn::boss::GetStorageInfo(); if(result == nn::boss::ResultStorageNotFound()) { NN_LOG("[BOSS Sample] RegisterStorage BOSS Storage.\n"); result = nn::boss::RegisterStorage(APP_EXT_STORAGE_ID, NADL_STORAGE_SIZE); } NN_BOSS_RESULT_HANDLING(result, "boss::RegisterStorage"); } const char8 DOWNLOAD_TASK_ID[] = "NadlTsk"; //Opt-out settings (The following code sets and accesses the local opt-out flag.) /* { //Set the opt-out flag bool optoutValue = true; nn::Result result = nn::boss::SetOptoutFlag(optoutValue); NN_BOSS_RESULT_HANDLING(result, "nn::boss::SetOptoutFlag"); // Access the opt-out flag result = nn::boss::GetOptoutFlag(&optoutValue); NN_LOG("[BOSS Sample]Optout value is %d\n", optoutValue); NN_BOSS_RESULT_HANDLING(result, "nn::boss::GetOptoutFlag"); } */ //Account for the fact that there may still be a task with the same ID and delete it. /* { nn::boss::Task deleteTargetTask; nn::Result result = deleteTargetTask.Initialize(DOWNLOAD_TASK_ID); NN_BOSS_RESULT_HANDLING(result, "Task::Initialize"); deleteTargetTask.Cancel(); // UnregisterTask fails if the task is currently running. To ensure that it is deleted, call UnregisterTask after Cancel. NN_BOSS_RESULT_HANDLING(result, "Task::Cancel"); result = nn::boss::UnregisterTask(&deleteTargetTask); NN_BOSS_RESULT_HANDLING(result, "boss::UnregisterTask"); } */ //Register and run the NADL task { const char8 TASK_TARGET_URL[] = "https://npdl.cdn.nintendowifi.net/p01/nsa/9x4m4dJwyBBlUc3g/demotask/demofile_notice.dat"; //const char8 TASK_TARGET_URL[] = "https://npdl.cdn.nintendowifi.net/p01/nsa/9x4m4dJwyBBlUc3g/demotask/demofile.dat"; //const char8 TASK_TARGET_URL[] = "https://npdl.cdn.nintendowifi.net/p01/nsa/9x4m4dJwyBBlUc3g/demotask/demofile_message.dat"; const u16 NADL_TASK_EXECUTE_TIME = 1; const u16 NADL_TASK_EXECUTE_COUNT = 1; //Register the NADL task nn::boss::TaskPolicy dPolicy; nn::Result result = dPolicy.Initialize(NADL_TASK_EXECUTE_TIME, NADL_TASK_EXECUTE_COUNT); //nn::Result result = dPolicy.InitializeWithSecInterval(NADL_TASK_EXECUTE_TIME, NADL_TASK_EXECUTE_COUNT); // You can also specify an execution interval in seconds for testing. NN_BOSS_RESULT_HANDLING(result, "TaskPolicy::Initialize"); nn::boss::NsaDownloadAction dAction; result = dAction.Initialize(TASK_TARGET_URL); NN_BOSS_RESULT_HANDLING(result, "NsaDownloadAction::Initialize"); //result = dAction.SetApInfo( nn::boss::APINFOTYPE_APGROUP|nn::boss::APINFOTYPE_APAREA|nn::boss::APINFOTYPE_AP ); // Configure AP information to be given to HTTP queries, as necessary. //result = dAction.AddHeaderField(pLabel, pValue); // Set a unique HTTP request header, as necessary. nn::boss::Task dTask; result = dTask.Initialize(DOWNLOAD_TASK_ID); NN_BOSS_RESULT_HANDLING(result, "Task::Initialize"); //Register the task. //NOTES: RegisterTask returns an error if a task with the same name has already been registered. In this case, enable the code to delete tasks, which is commented out above, and delete the task with the same name. NN_LOG("[BOSS Sample] Register NADL Task.\n"); result = nn::boss::RegisterTask(&dTask, &dPolicy, &dAction); if(result == nn::boss::ResultTaskIdAlreadyExist()) { NN_LOG("[BOSS Sample] RegisterTask failed. A task with the same name (%s) has already been registered. You need to call UnregisterTask before registering it again.\n", DOWNLOAD_TASK_ID); } NN_BOSS_RESULT_HANDLING(result, "RegisterTask"); //Execute task NN_LOG("[BOSS Sample] Start NADL task.\n"); result = dTask.Start(); NN_BOSS_RESULT_HANDLING(result, "Task::Start"); //Wait for NADL download data //// Get a data download notification event from the BOSS daemon nn::os::Event arriveEvent(false); result = nn::boss::RegisterNewArrivalEvent(&arriveEvent); NN_BOSS_RESULT_HANDLING(result, "Task::RegisterNewArrivalEvent"); //Use StartImmediate if you want to run a task immediately without waiting for the next task execution time. //However, because StartImmediate runs a task in the foreground, the application must make an infrastructure network connection. (BOSS is not used.) /* [Infrastructure network connection with nn::ac::Connect] result = dTask.StartImmediate(); NN_BOSS_RESULT_HANDLING(result, "Task::StartImmediate"); (NOTE: Use nn::ac::Close to close the infrastructure network connection after the task finishes processing.) */ //// Wait for new data to be downloaded. NN_LOG("[BOSS Sample] Wait for NSA data to arrive....\n"); arriveEvent.Wait(); NN_LOG("[BOSS Sample] Recognize that NSA data has arrived\n"); //// You can also wait for a task to complete rather than for data to be downloaded. (By "waiting for a task to complete," we mean "waiting for the next task to finish executing." This does not refer to running for the full execution count.) //// Even if you run a task and wait for data to be downloaded, the data is deleted and control does not return when you are not connected to the server, when data already exists, and when the downloaded data is invalid (decryption or signature verification failed). //// //// If you run a task and wait for it to complete, WaitFinish will exit when the task completes even if it had an error. //// Use each method where it suits the purpose. //result = dTask.WaitFinish(); // Wait for the task to complete. (Without a timeout. This will wait indefinitely until processing is complete.) //result = dTask.WaitFinish(nn::fnd::TimeSpan::FromSeconds(60)); // Wait for the task to complete. (With a timeout. ResultWaitfinishTimeout returns when processing does not complete within the specified time.) //// Another way to wait for a task to complete is to poll on the task state using the Task::GetState function. //// After you have detected that the task has completed, you can use the following functions to get information on the completed task. //// Task::GetResult for the execution result //// Task::GetCommErrorCode for the HTTP status code run by the task //// Task::GetError for detailed information on task errors //Processing to download data. //// Before you get a list of data IDs, the application's "update indicator flag" is on. { bool arriveFlag = false; NN_UNUSED_VAR(arriveFlag);//Because this variable is exclusively used for output with NN_LOG, configure it to be unusable in Release builds. result = nn::boss::GetNewArrivalFlag(&arriveFlag); NN_BOSS_RESULT_HANDLING(result, "GetNewArrivalFlag"); NN_LOG("[BOSS Sample] (Before reading data, NewArrivalFlag is %d.)\n", arriveFlag); } //// Get a serial ID list for the downloaded data. (You can use the first argument to GetNsDataIdList to filter the data that is obtained.) static const u32 MAX_DATA_ID = 32; u32 idBuf[MAX_DATA_ID];//Buffer for storing serial IDs. This is prepared by the application. By providing a large buffer, you can get a large number of serial IDs at one time. nn::boss::NsDataIdList serialIdList(idBuf, MAX_DATA_ID);//The number of serial IDs that can be obtained at one time is the same as the number of elements in the array buffer. serialIdList.Initialize(); u32 getNsDataIdListCount = 0; nn::Result getNsDataIdListResult; do { getNsDataIdListResult = nn::boss::GetNsDataIdList(nn::boss::DATA_TYPE_ALL, &serialIdList); //result = nn::boss::GetNsDataIdList(nn::boss::DATA_TYPE_APPDATA|0xffff, &serialIdList); // When you only want to get extra data for the application. if(getNsDataIdListResult == nn::boss::ResultNsDataListUpdated()) { //ResultNsDataListUpdated is returned when NS data is added to or deleted from BOSS storage during the process of getting a list of IDs. Initialize the list and attempt to get a list of serial IDs from the beginning. serialIdList.Initialize(); getNsDataIdListResult = nn::boss::ResultNsDataListSizeShortage();//Update the value of getNsDataIdListResult so that control does not exit the do-while loop. continue; } else if((getNsDataIdListResult.IsFailure()) && (getNsDataIdListResult != nn::boss::ResultNsDataListSizeShortage())) { //Any error other than ResultNsDataListUpdated, ResultNsDataListSizeShortage, or ResultSuccess is an unexpected error. //ResultNsDataListSizeShortage indicates that a list of IDs was successfully obtained, but all of the IDs could not be stored in the NsDataIdList (the function must be run again). ResultSuccess indicates that a list of IDS was successfully obtained (all IDs were obtained). NN_BOSS_RESULT_HANDLING(result, "boss::GetNsDataIdList"); } //Application-specific processing for downloaded data. (This demo dumps the header information and body data for all downloaded data.) ++getNsDataIdListCount; NN_LOG("[BOSS Sample] Dump NSD data(%d). (data number = %d)\n\n", getNsDataIdListCount, serialIdList.GetSize()); for(int i=0; i < serialIdList.GetSize(); ++i) { NN_LOG("===NSD No.%d (Serial ID = %d)===\n", i, serialIdList.GetNsDataId(i)); nn::boss::NsData contentData; result = contentData.Initialize(serialIdList.GetNsDataId(i)); NN_BOSS_RESULT_HANDLING(result, "NsData::Initialize"); //Check the header { nn::fs::TitleId titlleID = 0; result = contentData.GetHeaderInfo(nn::boss::NSD_TITLEID, &titlleID, sizeof(titlleID)); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("TitleID = %llx\n",titlleID); u32 headerInfo = 0; result = contentData.GetHeaderInfo(nn::boss::NSD_SERIALID, &headerInfo, sizeof(headerInfo)); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("Content SerialID = %d\n",headerInfo); result = contentData.GetHeaderInfo(nn::boss::NSD_LENGTH, &headerInfo, sizeof(headerInfo)); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("Payload Length = %d\n",headerInfo); result = contentData.GetHeaderInfo(nn::boss::NSD_VERSION, &headerInfo, sizeof(headerInfo)); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("Content version = %d\n",headerInfo); result = contentData.GetHeaderInfo(nn::boss::NSD_FLAGS, &headerInfo, sizeof(headerInfo)); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("Content Flags = %d\n",headerInfo); result = contentData.GetHeaderInfo(nn::boss::NSD_DATATYPE, &headerInfo, sizeof(headerInfo)); RESULT_SUCCESS_ASSERT(result); NN_BOSS_RESULT_HANDLING(result, "NsData::GetHeaderInfo"); NN_LOG("Content DataType = %d\n",headerInfo); } //Check the data { NN_LOG("---Dump Data---\n"); u8 dDataBuf[4*1024]; memset(dDataBuf, 0, sizeof(dDataBuf)); size_t readSize = 0; u32 readCount = 0; do { ++readCount; NN_LOG("(Read %d)\n", readCount); readSize = contentData.ReadData(reinterpret_cast(dDataBuf), sizeof(dDataBuf)); NN_BOSS_RESULT_HANDLING(result, "NsData::ReadData"); DumpNsdBody(dDataBuf, readSize); }while(readSize != 0); } //Get and set data attribute information { u32 setInfo = 0x100; result = contentData.SetAdditionalInfo(setInfo); NN_BOSS_RESULT_HANDLING(result, "NsData::SetAdditionalInfo"); u32 getInfo; result = contentData.GetAdditionalInfo(&getInfo); NN_BOSS_RESULT_HANDLING(result, "NsData::SetAdditionalInfo"); NN_LOG("[BOSS Sample] AdditionalInfo = %d (Set Info = %d)\n", setInfo, setInfo); } /* * You can also use the data's already-read flag. * Unlike the application's "update indicator flag" obtained by the RegisterNewArrivalEvent function, the data's already-read flag is used for the application to manage unprocessed data. * The flag is off when data is downloaded and stays off as long as the application does not explicitly turn it on. * Use this when the application manages unprocessed data. * NOTE: The GetNewDataNsDataIdList function returns a list of data for which this flag is off. You can use this for different purposes than GetNsDataIdList, which returns a list of all data regardless of their flags. */ { bool nsdReadFlag = true; result = contentData.GetReadFlag(&nsdReadFlag); NN_BOSS_RESULT_HANDLING(result, "NsData::GetReadFlag"); NN_LOG("[BOSS Sample] NSD Read Flag = %d\n", nsdReadFlag); if(nsdReadFlag == false) { //Turn the flag on. (The data's already-read flag does not change unless the application sets it.) result = contentData.SetReadFlag(true); NN_BOSS_RESULT_HANDLING(result, "NsData::SetNewFrag"); } } //Delete data /* { result = contentData.Delete(); NN_BOSS_RESULT_HANDLING(result, "NsData::Delete"); } */ } }while(getNsDataIdListResult == nn::boss::ResultNsDataListSizeShortage());//If this is ResultNsDataListSizeShortage, run GetNsDataIdList again because all of the IDs have still not been obtained. //After you get a list of data IDs, the application's "update indicator flag" is off. { bool arriveFlag = false; result = nn::boss::GetNewArrivalFlag(&arriveFlag); NN_BOSS_RESULT_HANDLING(result, "GetNewArrivalFlag"); NN_LOG("[BOSS Sample] (After reading data, NewArrivalFlag is %d.)\n", arriveFlag); } //If you turn on the already-read flag for all data, the GetNewDataNsDataIdList function will get an empty list (because it gets a list of data for which the already-read flag is off). { result = nn::boss::GetNewDataNsDataIdList(nn::boss::DATA_TYPE_ALL, &serialIdList); NN_BOSS_RESULT_HANDLING(result, "GetNewDataNsDataIdList"); NN_LOG("[BOSS Sample] (After NSD read flag is on, new NSD number is = %d)\n", serialIdList.GetSize()); } /* * When NADL tasks are run periodically, control returns to arriveEvent.Wait (which waits for data to be downloaded) where it waits for the next download. * Once all task processing has finished, the following task is deleted. */ //Delete task { nn::boss::Task deleteTargetTask; result = deleteTargetTask.Initialize(DOWNLOAD_TASK_ID); NN_BOSS_RESULT_HANDLING(result, "Task::Initialize"); result = nn::boss::UnregisterTask(&deleteTargetTask); NN_BOSS_RESULT_HANDLING(result, "UnregisterTask"); } } } extern "C" void nnMain() { // Call only nn::applet::Enable to also allow execution from the HOME Menu // HOME Menu transitions, POWER Button presses, and sleep are all unsupported nn::applet::Enable(); /* =======================================================================     Pre-processing Note: Network configuration process or other processes. You do not need to implement this if the process has already been run when BOSS is used. ======================================================================== */ //Initialize the BOSS library { nn::Result result = nn::boss::Initialize(); NN_BOSS_RESULT_HANDLING(result, "boss::Initialize"); } //Change settings so that the application runs BOSS in the background when we are not sleeping { // Initialize the NDM library nn::Result result = nn::ndm::Initialize(); NN_BOSS_RESULT_HANDLING(result, "ndm::Initialize()"); // Resume BOSS result = nn::ndm::Resume(nn::ndm::DN_BOSS); NN_BOSS_RESULT_HANDLING(result, "ndm::Resume()"); } //Create expanded save data. (Data downloaded by an NADL task is saved in BOSS storage in the expanded save data region. An expanded save data region is therefore required to use NADL tasks.) { const char extSaveDataMountName[] = "test:"; nn::fs::Initialize(); { nn::Result result = nn::fs::MountExtSaveData(extSaveDataMountName, APP_EXT_STORAGE_ID); if(result.IsFailure()) { if(nn::fs::ResultNotFormatted::Includes(result) || nn::fs::ResultBadFormat::Includes(result) || nn::fs::ResultVerificationFailed::Includes(result)) { nn::fs::DeleteExtSaveData(APP_EXT_STORAGE_ID); } if(nn::fs::ResultNotFound::Includes(result) || nn::fs::ResultNotFormatted::Includes(result) || nn::fs::ResultBadFormat::Includes(result) || nn::fs::ResultVerificationFailed::Includes(result)) { NN_LOG("Create ExtSaveData(ID=%lx)\n", APP_EXT_STORAGE_ID); //When you create expanded save data, configure the maximum file count so that it also accounts for the number of files downloaded through BOSS. //Once the maximum number of files already exist in expanded save data, it will no longer be possible to write files downloaded through BOSS. //In SDK 0.14, icon data of some kind must be specified to fs::CreateExtSaveData. u8 iconData[] = {0x01}; result = nn::fs::CreateExtSaveData(APP_EXT_STORAGE_ID, iconData, sizeof(iconData), 10, 100); if(result.IsFailure()) { NN_LOG_ERROR("CreateExtSaveData failed (%08x)\n", result.GetPrintableBits()); NN_UTIL_PANIC_IF_FAILED(result); } result = nn::fs::MountExtSaveData(extSaveDataMountName, APP_EXT_STORAGE_ID); NN_UTIL_PANIC_IF_FAILED(result); } else { NN_LOG_ERROR("MountExtSaveData failed (%08x)\n", result.GetPrintableBits()); NN_UTIL_PANIC_IF_FAILED(result); } } } } NN_LOG("Initializing the network.\n"); // Connect to the network. //Even if the application does not connect to the network, the CTR system periodically attempts to make an infrastructure network connection (to the WAN) and, if it succeeds, BOSS background processes will start. //This corresponds to BOSS processes during Sleep Mode. //This demo will therefore run even if these processes do not, but it will not start until the periodic infrastructure network connection is made. (After roughly several tens of seconds) //This demo connects to the network because BOSS background processes will immediately start using an infrastructure network connection (to the WAN) once it is made by the application. // { nn::Result result = InitializeNetwork(); NN_UTIL_PANIC_IF_FAILED(result); } NN_LOG("BOSS Sample (NadlTaskSimple) Start\n"); sampleNADLTaskBgExecute(); NN_LOG("BOSS Sample (NadlTaskSimple) End\n"); /* =======================================================================     Clean up Note: Network termination processing and other processing. If BOSS will still be used later, this does not need to be run. ======================================================================== */ NN_LOG("Finalizing network.\n"); { nn::Result result = FinalizeNetwork(); NN_UTIL_PANIC_IF_FAILED(result); } //Unregister BOSS storage if BOSS features will not be used later. //(Note that once it is unregistered, you will no longer be able to run NADL tasks or read data from BOSS storage.) /* { nn::Result result = nn::boss::UnregisterStorage(); NN_UTIL_PANIC_IF_FAILED(result); } */ //Finalize the NDM library { nn::Result result = nn::ndm::Finalize(); NN_BOSS_RESULT_HANDLING(result, "ndm::Finalize()"); //When the program exits, pause/resume settings are also restored } //Shut down the library { nn::Result result = nn::boss::Finalize(); NN_UTIL_PANIC_IF_FAILED(result); } NN_LOG("END\n"); }