Compare commits

...

60 Commits

Author SHA1 Message Date
PabloMK7
8260d5527e Merge branch 'httpc' into online 2023-10-07 12:39:44 +02:00
PabloMK7
718ff2546f Merge remote-tracking branch 'origin/master' into httpc 2023-10-06 13:48:54 +02:00
PabloMK7
9a12f84ffa Merge branch 'httpc' into online 2023-10-05 16:13:28 +02:00
PabloMK7
1d27cbf3b6 Revert SplitURL to previous version 2023-10-05 16:13:06 +02:00
PabloMK7
ad786c12cf Merge branch 'httpc' into online 2023-10-05 15:14:54 +02:00
PabloMK7
6708d7c33b Fix format 2023-10-05 15:14:24 +02:00
PabloMK7
cdbcd709d3 Merge branch 'httpc' into online 2023-10-05 14:56:11 +02:00
PabloMK7
b8c3f0648b Apply suggestions 2023-10-05 14:48:02 +02:00
PabloMK7
13418013a4 Fix compilation 2023-10-05 14:16:08 +02:00
PabloMK7
3f640ae662 Apply suggestions 2023-10-05 13:01:50 +02:00
PabloMK7
6f98457888 Apply more suggestions 2023-10-04 22:57:00 +02:00
PabloMK7
937ffb267c Add and use Common::TruncateString 2023-10-04 22:53:42 +02:00
PabloMK7
3ccbe657b1 Create and use ctx.CommandID() 2023-10-04 22:31:14 +02:00
PabloMK7
0fa5357754 Fix compilation issue 2023-10-04 22:20:29 +02:00
PabloMK7
8714eecdb1 Merge remote-tracking branch 'origin/master' into httpc 2023-10-04 22:08:08 +02:00
PabloMK7
0689a4a22f Fix header ordering 2023-10-04 22:03:35 +02:00
PabloMK7
5fb455425c Apply suggestions 2023-10-04 21:59:47 +02:00
PabloMK7
bf5c707a88 Try to fix issue from httplib 2023-10-03 23:10:20 +02:00
PabloMK7
3476fd4565 Make httplib system 2023-10-03 21:40:29 +02:00
PabloMK7
62ee5e2cdc Remove pragmas that do nothing and mark as SYSTEM 2023-10-03 21:18:43 +02:00
PabloMK7
0b11a2b790 Fix defines 2023-10-03 18:24:21 +02:00
PabloMK7
e0373d679c Disable treat errors as warnings for httplib 2023-10-03 17:49:19 +02:00
PabloMK7
f605fb6ba4 Fix compilation issues 2023-10-03 16:05:15 +02:00
PabloMK7
7bef2b56b6 Add cryptopp to cmakelists 2023-10-03 14:27:13 +02:00
PabloMK7
f313dabb93 Merge branch 'httpc' into online 2023-10-03 13:51:32 +02:00
PabloMK7
b2a0cc6429 Revert httplib 2023-10-03 13:49:07 +02:00
PabloMK7
d75538c170 Fix MAC OS 2023-10-03 13:47:42 +02:00
PabloMK7
ffb9a443cd Merge branch 'master' into online 2023-10-03 13:43:48 +02:00
PabloMK7
fdb96932a0 Revert to master for easier merge 2023-10-03 13:40:44 +02:00
PabloMK7
415d0c2abd Organize code 2023-10-03 13:31:11 +02:00
PabloMK7
3afcf52215 Merge branch 'master' into httpc 2023-10-02 20:25:32 +02:00
PabloMK7
5bf960c9ef More implementation details and cleanup. 2023-10-02 20:23:57 +02:00
PabloMK7
b7d8d40b25 Implement missing http:c functionality. 2023-10-01 12:27:31 +02:00
PabloMK7
26d26653af Fix http:c files 2023-09-30 12:25:44 +02:00
PabloMK7
9854cf63dc Merge master 2023-08-23 19:58:18 +02:00
PabloMK7
bf97245c7f Merge master 2023-08-23 19:54:37 +02:00
PabloMK7
4d4c6146e3 Latest online related changes 2023-08-02 23:03:35 +02:00
PabloMK7
38abbd41d7 Implement more http:c and GetServiceLocator 2023-07-31 18:01:40 +02:00
PabloMK7
94d0d689d2 Merge remote-tracking branch 'fltobi/http-fixes' into online 2023-07-31 11:10:46 +02:00
PabloMK7
307e20d43d Merge master 2023-07-31 11:07:21 +02:00
PabloMK7
6cc63061b1 Merge branch 'miirefactor' into online 2023-07-31 11:03:07 +02:00
FearlessTobi
3ba8da15c8 Address review comments 2023-07-31 05:06:44 +02:00
FearlessTobi
87f5aae7dd service: Move all services to folders
Is more consistent and allows for an easier overview of all available services.
2023-07-31 02:33:48 +02:00
FearlessTobi
ab39da18ae http_c: Implement and stub various functions 2023-07-31 02:23:58 +02:00
FearlessTobi
7d9d6c576a http_c: Split url for request
httplib requires the url to be split in a host and path component in order for requests to be made.
2023-07-30 20:04:43 +02:00
FearlessTobi
fea38f824d soc_u: Perform size checking for static buffers
Previously, the buffers pushed were too long and would trigger an ASSERT in our IPC handling code.
2023-07-30 20:03:17 +02:00
PabloMK7
b45d904f64 Change back crc to u16 and set padding to 0. 2023-07-30 13:44:19 +02:00
PabloMK7
650078f70f Apply suggestions 2023-07-30 00:31:43 +02:00
PabloMK7
a230306376 Merge branch 'miirefactor' into online 2023-07-28 22:31:20 +02:00
PabloMK7
e76f480575 Make miidata a struct and crc16 a u32_be as per switch code. 2023-07-28 22:16:11 +02:00
PabloMK7
961136dde6 Remove unused var 2023-07-28 21:40:52 +02:00
PabloMK7
a9345a3569 Fix merge 2023-07-28 19:05:30 +02:00
PabloMK7
5825797a95 Merge miirefactor 2023-07-28 18:56:49 +02:00
PabloMK7
0f4480a232 Add new line at the end of files. 2023-07-28 17:50:21 +02:00
PabloMK7
d89a8466e4 Fix Android side 2023-07-28 15:34:44 +02:00
PabloMK7
bbd923d7a7 Make mii classes trivial and add cast operator 2023-07-28 13:36:55 +02:00
PabloMK7
7143b0652a Fix compile issues 2023-07-28 12:52:00 +02:00
PabloMK7
fa0c99c987 Move mii to own namespace and add checksummed mii data 2023-07-28 00:13:58 +02:00
PabloMK7
4db78f0a9d Fix ipc request headers 2023-07-27 23:20:14 +02:00
PabloMK7
71235bd678
Online (#2)
* Implement SOC_U::GetHostByName and partial SOC_U::GetNetworkOpt

* Implement AC::GetWifiStatus, and get proper network interface.

* Minor fixes

* More minor fixes

* Even more fixes

* Fix Get/Set SockOpt

* Implement SendToOther

* Apply suggestions and fix timer advance

* Fix variable name

* WIP implementation

* More implemented friends/mii/fs stuff

* Add more sockopt values and fix send/recv flags.

* Temporary disable GetFriendPresence

* Fix dontwait logic

* Fix linux build

* Add missing header for linux

* Remove TCP_STDURG

* frd stuff

* Fix poll and add more 3ds <-> platform conversions

* Finish implementing all platform <-> 3ds conversion.

* Disable UDP connreset and fix poll again.

* Fix compile issues

* Apply suggestions

* Fix compiler issues

* Fix compiler errors (again)

* Fix GetAddrInfo

* Use cert from nand files instead of account.

* Implement more frd functionality.

* common: Add thread pool from yuzu

* Is really useful for asynchronous operations like shader compilation and custom textures, will be used in following PRs

* core: Improve ImageInterface

* Provide a default implementation so frontends don't have to duplicate code registering the lodepng version

* Add a dds version too which we will use in the next commit

* rasterizer_cache: Rewrite custom textures

* There's just too much to talk about here, look at the PR description for more details

* rasterizer_cache: Implement basic pack configuration file

* custom_tex_manager: Flip dumped textures

* custom_tex_manager: Optimize custom texture hashing

* If no convertions are needed then we can hash the decoded data directly removing the needed for duplicate decode

* custom_tex_manager: Implement asynchronous texture loading

* The file loading and decoding is offloaded into worker threads, while the upload itself still occurs in the main thread to avoid having to manage shared contexts

* Address review comments

* custom_tex_manager: Introduce custom material support

* Remove files that were not added properly

* fix submodules

* Fix submodules again

* fix more files

---------

Co-authored-by: GPUCode <geoster3d@gmail.com>
2023-07-27 18:19:33 +02:00
19 changed files with 4000 additions and 1091 deletions

View File

@ -199,7 +199,7 @@ if (NOT OPENSSL_FOUND)
set(LIBRESSL_SKIP_INSTALL ON CACHE BOOL "") set(LIBRESSL_SKIP_INSTALL ON CACHE BOOL "")
set(OPENSSLDIR "/etc/ssl/") set(OPENSSLDIR "/etc/ssl/")
add_subdirectory(libressl EXCLUDE_FROM_ALL) add_subdirectory(libressl EXCLUDE_FROM_ALL)
target_include_directories(ssl INTERFACE ./libressl/include) target_include_directories(ssl SYSTEM INTERFACE ./libressl/include)
target_compile_definitions(ssl PRIVATE -DHAVE_INET_NTOP) target_compile_definitions(ssl PRIVATE -DHAVE_INET_NTOP)
get_directory_property(OPENSSL_LIBRARIES get_directory_property(OPENSSL_LIBRARIES
DIRECTORY libressl DIRECTORY libressl
@ -211,13 +211,13 @@ add_library(httplib INTERFACE)
if(USE_SYSTEM_CPP_HTTPLIB) if(USE_SYSTEM_CPP_HTTPLIB)
find_package(CppHttp 0.14.1) find_package(CppHttp 0.14.1)
if(CppHttp_FOUND) if(CppHttp_FOUND)
target_link_libraries(httplib INTERFACE cpp-httplib::cpp-httplib) target_link_libraries(httplib SYSTEM INTERFACE cpp-httplib::cpp-httplib)
else() else()
message(STATUS "Cpp-httplib not found or not suitable version! Falling back to bundled...") message(STATUS "Cpp-httplib not found or not suitable version! Falling back to bundled...")
target_include_directories(httplib INTERFACE ./httplib) target_include_directories(httplib SYSTEM INTERFACE ./httplib)
endif() endif()
else() else()
target_include_directories(httplib INTERFACE ./httplib) target_include_directories(httplib SYSTEM INTERFACE ./httplib)
endif() endif()
target_compile_options(httplib INTERFACE -DCPPHTTPLIB_OPENSSL_SUPPORT) target_compile_options(httplib INTERFACE -DCPPHTTPLIB_OPENSSL_SUPPORT)
target_link_libraries(httplib INTERFACE ${OPENSSL_LIBRARIES}) target_link_libraries(httplib INTERFACE ${OPENSSL_LIBRARIES})

View File

@ -1,4 +1,4 @@
From https://github.com/yhirose/cpp-httplib/commit/8e10d4e8e7febafce0632810262e81e853b2065f From https://github.com/yhirose/cpp-httplib/commit/0a629d739127dcc5d828474a5aedae1f234687d3
MIT License MIT License

File diff suppressed because it is too large Load Diff

View File

@ -6,6 +6,7 @@
#include <algorithm> #include <algorithm>
#include <cstddef> #include <cstddef>
#include <span>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <vector> #include <vector>
@ -84,6 +85,15 @@ std::string UTF16BufferToUTF8(const T& text) {
return UTF16ToUTF8(buffer); return UTF16ToUTF8(buffer);
} }
/**
* Removes trailing null bytes from the string.
*/
inline void TruncateString(std::string& str) {
while (str.size() && str.back() == '\0') {
str.pop_back();
}
}
/** /**
* Creates a std::string from a fixed-size NUL-terminated char buffer. If the buffer isn't * Creates a std::string from a fixed-size NUL-terminated char buffer. If the buffer isn't
* NUL-terminated then the string ends at max_len characters. * NUL-terminated then the string ends at max_len characters.

View File

@ -213,6 +213,11 @@ public:
return {cmd_buf[0]}; return {cmd_buf[0]};
} }
/// Returns the command ID from the IPC command buffer.
u16 CommandID() const {
return static_cast<u16>(CommandHeader().command_id.Value());
}
/** /**
* Returns the session through which this request was made. This can be used as a map key to * Returns the session through which this request was made. This can be used as a map key to
* access per-client data on services. * access per-client data on services.

File diff suppressed because it is too large Load Diff

View File

@ -6,22 +6,28 @@
#include <memory> #include <memory>
#include "common/common_types.h" #include "common/common_types.h"
#include "core/hle/mii.h"
#include "core/hle/service/service.h" #include "core/hle/service/service.h"
namespace Core { namespace Core {
class System; class System;
} }
namespace Kernel {
class Event;
}
namespace Service::FRD { namespace Service::FRD {
constexpr u32 FRIEND_SCREEN_NAME_SIZE = 0xB; ///< 11-short UTF-16 screen name
constexpr u32 FRIEND_COMMENT_SIZE = 0x11; ///< 17-short UTF-16 comment
constexpr u32 FRIEND_GAME_MODE_DESCRIPTION_SIZE = 0x80; ///< 128-short UTF-16 description
constexpr u32 FRIEND_LIST_SIZE = 0x64;
struct FriendKey { struct FriendKey {
u32 friend_id; u32_le friend_id{};
u32 unknown; u32_le unknown{};
u64 friend_code; u64_le friend_code{};
bool operator==(const FriendKey& other) {
return friend_id == other.friend_id;
}
private: private:
template <class Archive> template <class Archive>
@ -33,45 +39,328 @@ private:
friend class boost::serialization::access; friend class boost::serialization::access;
}; };
struct MyPresence { struct TitleData {
u8 unknown[0x12C]; u64_le tid{};
u32_le version{};
u32_le unk{};
private: private:
template <class Archive> template <class Archive>
void serialize(Archive& ar, const unsigned int) { void serialize(Archive& ar, const unsigned int) {
ar& unknown; ar& tid;
ar& version;
ar& unk;
} }
friend class boost::serialization::access; friend class boost::serialization::access;
}; };
struct Profile { struct GameMode {
u8 region; u32_le join_flags{};
u8 country; u32_le type{};
u8 area; u32_le game_ID{};
u8 language; u32_le game_mode{};
u8 platform; u32_le host_principal_ID{};
INSERT_PADDING_BYTES(0x3); u32_le gathering_ID{};
}; std::array<u8, 20> app_args{};
static_assert(sizeof(Profile) == 0x8, "Profile has incorrect size");
struct Game { private:
u64 title_id; template <class Archive>
u16 version; void serialize(Archive& ar, const unsigned int) {
INSERT_PADDING_BYTES(0x6); ar& join_flags;
ar& type;
ar& game_ID;
ar& game_mode;
ar& host_principal_ID;
ar& gathering_ID;
ar& app_args;
}
friend class boost::serialization::access;
}; };
static_assert(sizeof(Game) == 0x10, "Game has inccorect size");
struct ScreenName { struct FriendPlayingGame {
// 20 bytes according to 3dbrew TitleData title{};
std::array<char16_t, 10> name; std::array<u16_le, FRIEND_GAME_MODE_DESCRIPTION_SIZE> description{};
};
static_assert(sizeof(ScreenName) == 0x14, "ScreenName has inccorect size");
struct Comment { private:
// 32 bytes according to 3dbrew template <class Archive>
std::array<char16_t, 16> name; void serialize(Archive& ar, const unsigned int) {
ar& title;
ar& description;
}
friend class boost::serialization::access;
}; };
static_assert(sizeof(Comment) == 0x20, "Comment has inccorect size");
struct MyPresence {
GameMode game_mode{};
std::array<u16_le, FRIEND_GAME_MODE_DESCRIPTION_SIZE> description{};
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& game_mode;
ar& description;
}
friend class boost::serialization::access;
};
struct FriendPresence {
GameMode game_mode{};
u8 is_online{};
u8 unknown{};
u8 is_valid{};
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& game_mode;
ar& is_online;
ar& unknown;
ar& is_valid;
}
friend class boost::serialization::access;
};
struct GameAuthenticationData {
s32_le result{};
s32_le http_status_code{};
std::array<char, 32> server_address{};
u16_le server_port{};
u16_le padding1{};
u32_le unused{};
std::array<char, 256> auth_token{};
u64_le server_time{};
void Init() {
memset(this, 0, sizeof(*this));
}
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& result;
ar& http_status_code;
ar& server_address;
ar& server_port;
ar& padding1;
ar& unused;
ar& auth_token;
ar& server_time;
}
friend class boost::serialization::access;
};
struct ServiceLocatorData {
s32_le result{};
s32_le http_status_code{};
std::array<char, 128> service_host{};
std::array<char, 256> service_token{};
u8 status;
std::array<char, 7> padding{};
u64_le server_time{};
void Init() {
memset(this, 0, sizeof(*this));
}
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& result;
ar& http_status_code;
ar& service_token;
ar& status;
ar& service_host;
ar& server_time;
}
friend class boost::serialization::access;
};
struct UserNameData {
std::array<u16_le, 11> user_name{};
u8 is_bad_word{};
u8 unknown{};
u32_le bad_word_ver{};
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& user_name;
ar& is_bad_word;
ar& unknown;
ar& bad_word_ver;
}
friend class boost::serialization::access;
};
struct FriendProfile {
u8 region{};
u8 country{};
u8 area{};
u8 language{};
u8 platform{};
std::array<u8, 3> padding{};
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& region;
ar& country;
ar& area;
ar& language;
ar& platform;
ar& padding;
}
friend class boost::serialization::access;
};
struct FriendInfo {
FriendKey friend_key{};
s64_le account_creation_timestamp{};
u8 relationship{};
std::array<u8, 3> padding1{};
u32_le padding2{};
FriendProfile friend_profile{};
TitleData favorite_game{};
u32_le principal_ID{};
u16_le comment[FRIEND_COMMENT_SIZE]{};
u16_le padding3{};
s64_le last_online_timestamp{};
std::array<u16_le, FRIEND_SCREEN_NAME_SIZE> screen_name;
u8 font_region{};
u8 padding4{};
Mii::ChecksummedMiiData mii_data{};
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& friend_key;
ar& account_creation_timestamp;
ar& relationship;
ar& padding1;
ar& padding2;
ar& friend_profile;
ar& favorite_game;
ar& principal_ID;
ar& comment;
ar& padding3;
ar& last_online_timestamp;
ar& screen_name;
ar& font_region;
ar& padding4;
ar& mii_data;
}
friend class boost::serialization::access;
};
struct AccountDataV1 {
static constexpr u32 MAGIC_VALUE = 0x54444146;
static constexpr u32 VERSION_VALUE = 0x1;
u32_le magic{MAGIC_VALUE};
u32_le version{VERSION_VALUE};
u32_le reserved{};
u32_le checksum{};
UserNameData device_name{};
u32_le padding1{};
std::array<char, 0x20> password{};
std::array<char, 0x10> pid_HMAC{};
std::array<char, 0x10> serial_number{};
std::array<u8, 6> mac_address{};
u16_le padding2{};
std::array<u8, 0x110> device_cert{};
std::array<char, 0x20> nasc_url{};
std::array<u8, 0x4E0> ctr_common_prod_cert{};
std::array<u8, 0x4C0> ctr_common_prod_key{};
FriendKey my_key{};
u8 my_pref_public_mode{};
u8 my_pref_public_game_name{};
u8 my_pref_public_played_game{};
u8 padding3{};
FriendProfile my_profile{};
std::array<u16_le, FRIEND_SCREEN_NAME_SIZE> my_screen_name{};
u16_le padding4{};
Mii::ChecksummedMiiData my_mii_data{};
u32_le padding5{};
TitleData my_fav_game{};
std::array<u16_le, FRIEND_COMMENT_SIZE> my_comment{};
u16_le my_friend_count{};
u32_le padding6{};
std::array<FriendInfo, FRIEND_LIST_SIZE> friend_info{};
AccountDataV1() {
Init();
}
AccountDataV1& operator=(const AccountDataV1&) = default;
AccountDataV1& operator=(AccountDataV1&&) = default;
u32 GenerateChecksum() {
u32 checksum = 0;
u8* data = reinterpret_cast<u8*>(this);
for (int i = 0; i < sizeof(AccountDataV1); i++) {
checksum = data[i] + checksum * 0x65;
}
return checksum;
}
bool IsValid() {
if (magic != MAGIC_VALUE || version != VERSION_VALUE) {
return false;
}
u32 checksum_backup = checksum;
checksum = 0;
bool good_checksum = GenerateChecksum() == checksum_backup;
checksum = checksum_backup;
return good_checksum;
}
std::optional<const FriendInfo*> GetFriendInfo(const FriendKey& key) {
for (int i = 0; i < my_friend_count; i++) {
if (friend_info[i].friend_key == key) {
return &friend_info[i];
}
}
return std::nullopt;
}
private:
void Init();
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& magic;
ar& version;
ar& reserved;
ar& checksum;
ar& device_name;
ar& padding1;
ar& password;
ar& pid_HMAC;
ar& serial_number;
ar& mac_address;
ar& padding2;
ar& device_cert;
ar& nasc_url;
ar& ctr_common_prod_cert;
ar& ctr_common_prod_key;
ar& my_key;
ar& my_pref_public_mode;
ar& my_pref_public_game_name;
ar& my_pref_public_played_game;
ar& padding3;
ar& my_profile;
ar& my_screen_name;
ar& padding4;
ar& my_mii_data;
ar& padding5;
ar& my_fav_game;
ar& my_comment;
ar& my_friend_count;
ar& padding6;
ar& friend_info;
}
friend class boost::serialization::access;
};
static_assert(sizeof(AccountDataV1) == 25496, "AccountDataV1 has wrong size");
class Module final { class Module final {
public: public:
@ -84,6 +373,28 @@ public:
~Interface(); ~Interface();
protected: protected:
void HasLoggedIn(Kernel::HLERequestContext& ctx);
void IsOnline(Kernel::HLERequestContext& ctx);
void Login(Kernel::HLERequestContext& ctx);
void Logout(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyFriendKey service function
* Inputs:
* none
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-5 : FriendKey
*/
void GetMyFriendKey(Kernel::HLERequestContext& ctx);
void GetMyPreference(Kernel::HLERequestContext& ctx);
void GetMyProfile(Kernel::HLERequestContext& ctx);
/** /**
* FRD::GetMyPresence service function * FRD::GetMyPresence service function
* Inputs: * Inputs:
@ -94,6 +405,28 @@ public:
*/ */
void GetMyPresence(Kernel::HLERequestContext& ctx); void GetMyPresence(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyScreenName service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : UTF16 encoded name (max 11 symbols)
*/
void GetMyScreenName(Kernel::HLERequestContext& ctx);
void GetMyMii(Kernel::HLERequestContext& ctx);
void GetMyLocalAccountId(Kernel::HLERequestContext& ctx);
void GetMyPlayingGame(Kernel::HLERequestContext& ctx);
void GetMyFavoriteGame(Kernel::HLERequestContext& ctx);
void GetMyNcPrincipalId(Kernel::HLERequestContext& ctx);
void GetMyComment(Kernel::HLERequestContext& ctx);
void GetMyPassword(Kernel::HLERequestContext& ctx);
/** /**
* FRD::GetFriendKeyList service function * FRD::GetFriendKeyList service function
* Inputs: * Inputs:
@ -106,6 +439,12 @@ public:
*/ */
void GetFriendKeyList(Kernel::HLERequestContext& ctx); void GetFriendKeyList(Kernel::HLERequestContext& ctx);
void GetFriendPresence(Kernel::HLERequestContext& ctx);
void GetFriendScreenName(Kernel::HLERequestContext& ctx);
void GetFriendMii(Kernel::HLERequestContext& ctx);
/** /**
* FRD::GetFriendProfile service function * FRD::GetFriendProfile service function
* Inputs: * Inputs:
@ -119,6 +458,8 @@ public:
*/ */
void GetFriendProfile(Kernel::HLERequestContext& ctx); void GetFriendProfile(Kernel::HLERequestContext& ctx);
void GetFriendRelationship(Kernel::HLERequestContext& ctx);
/** /**
* FRD::GetFriendAttributeFlags service function * FRD::GetFriendAttributeFlags service function
* Inputs: * Inputs:
@ -131,73 +472,13 @@ public:
*/ */
void GetFriendAttributeFlags(Kernel::HLERequestContext& ctx); void GetFriendAttributeFlags(Kernel::HLERequestContext& ctx);
/** void GetFriendPlayingGame(Kernel::HLERequestContext& ctx);
* FRD::GetMyFriendKey service function
* Inputs:
* none
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-5 : FriendKey
*/
void GetMyFriendKey(Kernel::HLERequestContext& ctx);
/** void GetFriendFavoriteGame(Kernel::HLERequestContext& ctx);
* FRD::GetMyScreenName service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : UTF16 encoded name (max 11 symbols)
*/
void GetMyScreenName(Kernel::HLERequestContext& ctx);
/** void GetFriendInfo(Kernel::HLERequestContext& ctx);
* FRD::GetMyMii service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : MiiStoreData structure
*/
void GetMyMii(Kernel::HLERequestContext& ctx);
/** void IsIncludedInFriendList(Kernel::HLERequestContext& ctx);
* FRD::GetMyProfile service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-3 : Profile structure
*/
void GetMyProfile(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyComment service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : UTF16 encoded comment (max 16 symbols)
*/
void GetMyComment(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyFavoriteGame service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-3 : Game structure
*/
void GetMyFavoriteGame(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyPlayingGame service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-3 : Game structure
*/
void GetMyPlayingGame(Kernel::HLERequestContext& ctx);
/**
* FRD::GetMyPreference service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : Public mode (byte, 0 = private, non-zero = public)
* 3 : Show current game (byte, 0 = don't show, non-zero = show)
* 4 : Show game history (byte, 0 = don't show, non-zero = show)
*/
void GetMyPreference(Kernel::HLERequestContext& ctx);
/** /**
* FRD::UnscrambleLocalFriendCode service function * FRD::UnscrambleLocalFriendCode service function
@ -212,6 +493,26 @@ public:
*/ */
void UnscrambleLocalFriendCode(Kernel::HLERequestContext& ctx); void UnscrambleLocalFriendCode(Kernel::HLERequestContext& ctx);
void UpdateGameModeDescription(Kernel::HLERequestContext& ctx);
void UpdateGameMode(Kernel::HLERequestContext& ctx);
void AttachToEventNotification(Kernel::HLERequestContext& ctx);
void SetNotificationMask(Kernel::HLERequestContext& ctx);
void GetEventNotification(Kernel::HLERequestContext& ctx);
void GetLastResponseResult(Kernel::HLERequestContext& ctx);
void RequestGameAuthentication(Kernel::HLERequestContext& ctx);
void GetGameAuthenticationData(Kernel::HLERequestContext& ctx);
void RequestServiceLocator(Kernel::HLERequestContext& ctx);
void GetServiceLocatorData(Kernel::HLERequestContext& ctx);
/** /**
* FRD::SetClientSdkVersion service function * FRD::SetClientSdkVersion service function
* Inputs: * Inputs:
@ -221,59 +522,29 @@ public:
*/ */
void SetClientSdkVersion(Kernel::HLERequestContext& ctx); void SetClientSdkVersion(Kernel::HLERequestContext& ctx);
/**
* FRD::Login service function
* Inputs:
* 65 : Address of unknown event
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void Login(Kernel::HLERequestContext& ctx);
/**
* FRD::IsOnline service function
* Inputs:
* none
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : Online state (8-bit, 0 = not online, non-zero = online)
*/
void IsOnline(Kernel::HLERequestContext& ctx);
/**
* FRD::HasLoggedIn service function
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : If the user has logged in 1, otherwise 0
*/
void HasLoggedIn(Kernel::HLERequestContext& ctx);
/**
* FRD::GetLastResponseResult service function
* Inputs:
* none
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void GetLastResponseResult(Kernel::HLERequestContext& ctx);
protected: protected:
std::shared_ptr<Module> frd; std::shared_ptr<Module> frd;
}; };
private: private:
FriendKey my_friend_key = {0, 0, 0ull}; AccountDataV1 my_account_data;
MyPresence my_presence = {}; GameAuthenticationData last_game_auth_data{};
bool logged_in = false; ServiceLocatorData last_service_locator_data{};
std::shared_ptr<Kernel::Event> login_event; MyPresence my_presence{};
Core::TimingEventType* login_delay_event;
Core::System& system; Core::System& system;
bool has_logged_in = false;
u32 notif_event_mask = 0xF7;
std::shared_ptr<Kernel::Event> notif_event;
static const u32 fpd_version = 16;
template <class Archive> template <class Archive>
void serialize(Archive& ar, const unsigned int) { void serialize(Archive& ar, const unsigned int) {
ar& my_friend_key; ar& my_account_data;
ar& last_game_auth_data;
ar& my_presence; ar& my_presence;
ar& logged_in;
} }
friend class boost::serialization::access; friend class boost::serialization::access;
}; };

View File

@ -14,44 +14,44 @@ FRD_A::FRD_A(std::shared_ptr<Module> frd) : Module::Interface(std::move(frd), "f
{0x0001, &FRD_A::HasLoggedIn, "HasLoggedIn"}, {0x0001, &FRD_A::HasLoggedIn, "HasLoggedIn"},
{0x0002, &FRD_A::IsOnline, "IsOnline"}, {0x0002, &FRD_A::IsOnline, "IsOnline"},
{0x0003, &FRD_A::Login, "Login"}, {0x0003, &FRD_A::Login, "Login"},
{0x0004, nullptr, "Logout"}, {0x0004, &FRD_A::Logout, "Logout"},
{0x0005, &FRD_A::GetMyFriendKey, "GetMyFriendKey"}, {0x0005, &FRD_A::GetMyFriendKey, "GetMyFriendKey"},
{0x0006, &FRD_A::GetMyPreference, "GetMyPreference"}, {0x0006, &FRD_A::GetMyPreference, "GetMyPreference"},
{0x0007, &FRD_A::GetMyProfile, "GetMyProfile"}, {0x0007, &FRD_A::GetMyProfile, "GetMyProfile"},
{0x0008, &FRD_A::GetMyPresence, "GetMyPresence"}, {0x0008, &FRD_A::GetMyPresence, "GetMyPresence"},
{0x0009, &FRD_A::GetMyScreenName, "GetMyScreenName"}, {0x0009, &FRD_A::GetMyScreenName, "GetMyScreenName"},
{0x000A, &FRD_A::GetMyMii, "GetMyMii"}, {0x000A, &FRD_A::GetMyMii, "GetMyMii"},
{0x000B, nullptr, "GetMyLocalAccountId"}, {0x000B, &FRD_A::GetMyLocalAccountId, "GetMyLocalAccountId"},
{0x000C, &FRD_A::GetMyPlayingGame, "GetMyPlayingGame"}, {0x000C, &FRD_A::GetMyPlayingGame, "GetMyPlayingGame"},
{0x000D, &FRD_A::GetMyFavoriteGame, "GetMyFavoriteGame"}, {0x000D, &FRD_A::GetMyFavoriteGame, "GetMyFavoriteGame"},
{0x000E, nullptr, "GetMyNcPrincipalId"}, {0x000E, &FRD_A::GetMyNcPrincipalId, "GetMyNcPrincipalId"},
{0x000F, &FRD_A::GetMyComment, "GetMyComment"}, {0x000F, &FRD_A::GetMyComment, "GetMyComment"},
{0x0010, nullptr, "GetMyPassword"}, {0x0010, &FRD_A::GetMyPassword, "GetMyPassword"},
{0x0011, &FRD_A::GetFriendKeyList, "GetFriendKeyList"}, {0x0011, &FRD_A::GetFriendKeyList, "GetFriendKeyList"},
{0x0012, nullptr, "GetFriendPresence"}, {0x0012, &FRD_A::GetFriendPresence, "GetFriendPresence"},
{0x0013, nullptr, "GetFriendScreenName"}, {0x0013, &FRD_A::GetFriendScreenName, "GetFriendScreenName"},
{0x0014, nullptr, "GetFriendMii"}, {0x0014, &FRD_A::GetFriendMii, "GetFriendMii"},
{0x0015, &FRD_A::GetFriendProfile, "GetFriendProfile"}, {0x0015, &FRD_A::GetFriendProfile, "GetFriendProfile"},
{0x0016, nullptr, "GetFriendRelationship"}, {0x0016, &FRD_A::GetFriendRelationship, "GetFriendRelationship"},
{0x0017, &FRD_A::GetFriendAttributeFlags, "GetFriendAttributeFlags"}, {0x0017, &FRD_A::GetFriendAttributeFlags, "GetFriendAttributeFlags"},
{0x0018, nullptr, "GetFriendPlayingGame"}, {0x0018, &FRD_A::GetFriendPlayingGame, "GetFriendPlayingGame"},
{0x0019, nullptr, "GetFriendFavoriteGame"}, {0x0019, &FRD_A::GetFriendFavoriteGame, "GetFriendFavoriteGame"},
{0x001A, nullptr, "GetFriendInfo"}, {0x001A, &FRD_A::GetFriendInfo, "GetFriendInfo"},
{0x001B, nullptr, "IsIncludedInFriendList"}, {0x001B, &FRD_A::IsIncludedInFriendList, "IsIncludedInFriendList"},
{0x001C, &FRD_A::UnscrambleLocalFriendCode, "UnscrambleLocalFriendCode"}, {0x001C, &FRD_A::UnscrambleLocalFriendCode, "UnscrambleLocalFriendCode"},
{0x001D, nullptr, "UpdateGameModeDescription"}, {0x001D, &FRD_A::UpdateGameModeDescription, "UpdateGameModeDescription"},
{0x001E, nullptr, "UpdateGameMode"}, {0x001E, &FRD_A::UpdateGameMode, "UpdateGameMode"},
{0x001F, nullptr, "SendInvitation"}, {0x001F, nullptr, "SendInvitation"},
{0x0020, nullptr, "AttachToEventNotification"}, {0x0020, &FRD_A::AttachToEventNotification, "AttachToEventNotification"},
{0x0021, nullptr, "SetNotificationMask"}, {0x0021, &FRD_A::SetNotificationMask, "SetNotificationMask"},
{0x0022, nullptr, "GetEventNotification"}, {0x0022, &FRD_A::GetEventNotification, "GetEventNotification"},
{0x0023, &FRD_A::GetLastResponseResult, "GetLastResponseResult"}, {0x0023, &FRD_A::GetLastResponseResult, "GetLastResponseResult"},
{0x0024, nullptr, "PrincipalIdToFriendCode"}, {0x0024, nullptr, "PrincipalIdToFriendCode"},
{0x0025, nullptr, "FriendCodeToPrincipalId"}, {0x0025, nullptr, "FriendCodeToPrincipalId"},
{0x0026, nullptr, "IsValidFriendCode"}, {0x0026, nullptr, "IsValidFriendCode"},
{0x0027, nullptr, "ResultToErrorCode"}, {0x0027, nullptr, "ResultToErrorCode"},
{0x0028, nullptr, "RequestGameAuthentication"}, {0x0028, &FRD_A::RequestGameAuthentication, "RequestGameAuthentication"},
{0x0029, nullptr, "GetGameAuthenticationData"}, {0x0029, &FRD_A::GetGameAuthenticationData, "GetGameAuthenticationData"},
{0x002A, nullptr, "RequestServiceLocator"}, {0x002A, nullptr, "RequestServiceLocator"},
{0x002B, nullptr, "GetServiceLocatorData"}, {0x002B, nullptr, "GetServiceLocatorData"},
{0x002C, nullptr, "DetectNatProperties"}, {0x002C, nullptr, "DetectNatProperties"},
@ -64,15 +64,23 @@ FRD_A::FRD_A(std::shared_ptr<Module> frd) : Module::Interface(std::move(frd), "f
{0x0033, nullptr, "GetMyApproachContext"}, {0x0033, nullptr, "GetMyApproachContext"},
{0x0034, nullptr, "AddFriendWithApproach"}, {0x0034, nullptr, "AddFriendWithApproach"},
{0x0035, nullptr, "DecryptApproachContext"}, {0x0035, nullptr, "DecryptApproachContext"},
{0x0405, nullptr, "SaveData"}, // frd:a commands start here
{0x0401, nullptr, "CreateLocalAccount"},
{0x0402, nullptr, "DeleteConfig"},
{0x0403, nullptr, "SetLocalAccountId"},
{0x0404, nullptr, "ResetAccountConfig"},
{0x0405, nullptr, "HasUserData"},
{0x0406, nullptr, "AddFriendOnline"}, {0x0406, nullptr, "AddFriendOnline"},
{0x0407, nullptr, "AddFriendOffline"},
{0x0408, nullptr, "SetFriendDisplayName"},
{0x0409, nullptr, "RemoveFriend"}, {0x0409, nullptr, "RemoveFriend"},
{0x040a, nullptr, "UpdatePlayingGame"}, {0x040A, nullptr, "SetPresenseGameKey"},
{0x040b, nullptr, "UpdatePreference"}, {0x040B, nullptr, "SetPrivacySettings"},
{0x040c, nullptr, "UpdateMii"}, {0x040C, nullptr, "SetMyData"},
{0x040d, nullptr, "UpdateFavoriteGame"}, {0x040D, nullptr, "SetMyFavoriteGame"},
{0x040e, nullptr, "UpdateNcPrincipalId"}, {0x040E, nullptr, "SetMyNCPrincipalId"},
{0x040f, nullptr, "UpdateComment"}, {0x040F, nullptr, "SetPersonalComment"},
{0x0410, nullptr, "DecryptApproachContext"},
}; };
RegisterHandlers(functions); RegisterHandlers(functions);
} }

View File

@ -14,46 +14,46 @@ FRD_U::FRD_U(std::shared_ptr<Module> frd) : Module::Interface(std::move(frd), "f
{0x0001, &FRD_U::HasLoggedIn, "HasLoggedIn"}, {0x0001, &FRD_U::HasLoggedIn, "HasLoggedIn"},
{0x0002, &FRD_U::IsOnline, "IsOnline"}, {0x0002, &FRD_U::IsOnline, "IsOnline"},
{0x0003, &FRD_U::Login, "Login"}, {0x0003, &FRD_U::Login, "Login"},
{0x0004, nullptr, "Logout"}, {0x0004, &FRD_U::Logout, "Logout"},
{0x0005, &FRD_U::GetMyFriendKey, "GetMyFriendKey"}, {0x0005, &FRD_U::GetMyFriendKey, "GetMyFriendKey"},
{0x0006, &FRD_U::GetMyPreference, "GetMyPreference"}, {0x0006, &FRD_U::GetMyPreference, "GetMyPreference"},
{0x0007, &FRD_U::GetMyProfile, "GetMyProfile"}, {0x0007, &FRD_U::GetMyProfile, "GetMyProfile"},
{0x0008, &FRD_U::GetMyPresence, "GetMyPresence"}, {0x0008, &FRD_U::GetMyPresence, "GetMyPresence"},
{0x0009, &FRD_U::GetMyScreenName, "GetMyScreenName"}, {0x0009, &FRD_U::GetMyScreenName, "GetMyScreenName"},
{0x000A, &FRD_U::GetMyMii, "GetMyMii"}, {0x000A, &FRD_U::GetMyMii, "GetMyMii"},
{0x000B, nullptr, "GetMyLocalAccountId"}, {0x000B, &FRD_U::GetMyLocalAccountId, "GetMyLocalAccountId"},
{0x000C, &FRD_U::GetMyPlayingGame, "GetMyPlayingGame"}, {0x000C, &FRD_U::GetMyPlayingGame, "GetMyPlayingGame"},
{0x000D, &FRD_U::GetMyFavoriteGame, "GetMyFavoriteGame"}, {0x000D, &FRD_U::GetMyFavoriteGame, "GetMyFavoriteGame"},
{0x000E, nullptr, "GetMyNcPrincipalId"}, {0x000E, &FRD_U::GetMyNcPrincipalId, "GetMyNcPrincipalId"},
{0x000F, &FRD_U::GetMyComment, "GetMyComment"}, {0x000F, &FRD_U::GetMyComment, "GetMyComment"},
{0x0010, nullptr, "GetMyPassword"}, {0x0010, &FRD_U::GetMyPassword, "GetMyPassword"},
{0x0011, &FRD_U::GetFriendKeyList, "GetFriendKeyList"}, {0x0011, &FRD_U::GetFriendKeyList, "GetFriendKeyList"},
{0x0012, nullptr, "GetFriendPresence"}, {0x0012, &FRD_U::GetFriendPresence, "GetFriendPresence"},
{0x0013, nullptr, "GetFriendScreenName"}, {0x0013, &FRD_U::GetFriendScreenName, "GetFriendScreenName"},
{0x0014, nullptr, "GetFriendMii"}, {0x0014, &FRD_U::GetFriendMii, "GetFriendMii"},
{0x0015, &FRD_U::GetFriendProfile, "GetFriendProfile"}, {0x0015, &FRD_U::GetFriendProfile, "GetFriendProfile"},
{0x0016, nullptr, "GetFriendRelationship"}, {0x0016, &FRD_U::GetFriendRelationship, "GetFriendRelationship"},
{0x0017, &FRD_U::GetFriendAttributeFlags, "GetFriendAttributeFlags"}, {0x0017, &FRD_U::GetFriendAttributeFlags, "GetFriendAttributeFlags"},
{0x0018, nullptr, "GetFriendPlayingGame"}, {0x0018, &FRD_U::GetFriendPlayingGame, "GetFriendPlayingGame"},
{0x0019, nullptr, "GetFriendFavoriteGame"}, {0x0019, &FRD_U::GetFriendFavoriteGame, "GetFriendFavoriteGame"},
{0x001A, nullptr, "GetFriendInfo"}, {0x001A, &FRD_U::GetFriendInfo, "GetFriendInfo"},
{0x001B, nullptr, "IsIncludedInFriendList"}, {0x001B, &FRD_U::IsIncludedInFriendList, "IsIncludedInFriendList"},
{0x001C, &FRD_U::UnscrambleLocalFriendCode, "UnscrambleLocalFriendCode"}, {0x001C, &FRD_U::UnscrambleLocalFriendCode, "UnscrambleLocalFriendCode"},
{0x001D, nullptr, "UpdateGameModeDescription"}, {0x001D, &FRD_U::UpdateGameModeDescription, "UpdateGameModeDescription"},
{0x001E, nullptr, "UpdateGameMode"}, {0x001E, &FRD_U::UpdateGameMode, "UpdateGameMode"},
{0x001F, nullptr, "SendInvitation"}, {0x001F, nullptr, "SendInvitation"},
{0x0020, nullptr, "AttachToEventNotification"}, {0x0020, &FRD_U::AttachToEventNotification, "AttachToEventNotification"},
{0x0021, nullptr, "SetNotificationMask"}, {0x0021, &FRD_U::SetNotificationMask, "SetNotificationMask"},
{0x0022, nullptr, "GetEventNotification"}, {0x0022, &FRD_U::GetEventNotification, "GetEventNotification"},
{0x0023, &FRD_U::GetLastResponseResult, "GetLastResponseResult"}, {0x0023, &FRD_U::GetLastResponseResult, "GetLastResponseResult"},
{0x0024, nullptr, "PrincipalIdToFriendCode"}, {0x0024, nullptr, "PrincipalIdToFriendCode"},
{0x0025, nullptr, "FriendCodeToPrincipalId"}, {0x0025, nullptr, "FriendCodeToPrincipalId"},
{0x0026, nullptr, "IsValidFriendCode"}, {0x0026, nullptr, "IsValidFriendCode"},
{0x0027, nullptr, "ResultToErrorCode"}, {0x0027, nullptr, "ResultToErrorCode"},
{0x0028, nullptr, "RequestGameAuthentication"}, {0x0028, &FRD_U::RequestGameAuthentication, "RequestGameAuthentication"},
{0x0029, nullptr, "GetGameAuthenticationData"}, {0x0029, &FRD_U::GetGameAuthenticationData, "GetGameAuthenticationData"},
{0x002A, nullptr, "RequestServiceLocator"}, {0x002A, &FRD_U::RequestServiceLocator, "RequestServiceLocator"},
{0x002B, nullptr, "GetServiceLocatorData"}, {0x002B, &FRD_U::GetServiceLocatorData, "GetServiceLocatorData"},
{0x002C, nullptr, "DetectNatProperties"}, {0x002C, nullptr, "DetectNatProperties"},
{0x002D, nullptr, "GetNatProperties"}, {0x002D, nullptr, "GetNatProperties"},
{0x002E, nullptr, "GetServerTimeInterval"}, {0x002E, nullptr, "GetServerTimeInterval"},

View File

@ -670,6 +670,27 @@ void FS_USER::GetFormatInfo(Kernel::HLERequestContext& ctx) {
rb.Push<bool>(format_info->duplicate_data != 0); rb.Push<bool>(format_info->duplicate_data != 0);
} }
void FS_USER::GetProductInfo(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
u32 process_id = rp.Pop<u32>();
LOG_DEBUG(Service_FS, "process_id={}", process_id);
IPC::RequestBuilder rb = rp.MakeBuilder(6, 0);
ProductInfo product_info;
if (!GetProductInfo(process_id, product_info)) {
rb.Push(ResultCode(FileSys::ErrCodes::ArchiveNotMounted, ErrorModule::FS,
ErrorSummary::NotFound, ErrorLevel::Status));
rb.Skip(5, false);
return;
}
rb.Push(RESULT_SUCCESS);
rb.PushRaw<ProductInfo>(product_info);
}
void FS_USER::GetProgramLaunchInfo(Kernel::HLERequestContext& ctx) { void FS_USER::GetProgramLaunchInfo(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const auto process_id = rp.Pop<u32>(); const auto process_id = rp.Pop<u32>();
@ -775,7 +796,7 @@ void FS_USER::AddSeed(Kernel::HLERequestContext& ctx) {
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
void FS_USER::SetSaveDataSecureValue(Kernel::HLERequestContext& ctx) { void FS_USER::ObsoletedSetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
u64 value = rp.Pop<u64>(); u64 value = rp.Pop<u64>();
u32 secure_value_slot = rp.Pop<u32>(); u32 secure_value_slot = rp.Pop<u32>();
@ -794,7 +815,7 @@ void FS_USER::SetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
void FS_USER::GetSaveDataSecureValue(Kernel::HLERequestContext& ctx) { void FS_USER::ObsoletedGetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
u32 secure_value_slot = rp.Pop<u32>(); u32 secure_value_slot = rp.Pop<u32>();
@ -816,7 +837,85 @@ void FS_USER::GetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
rb.Push<u64>(0); // the secure value rb.Push<u64>(0); // the secure value
} }
void FS_USER::Register(u32 process_id, u64 program_id, const std::string& filepath) { void FS_USER::SetThisSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
u32 secure_value_slot = rp.Pop<u32>();
u64 value = rp.Pop<u64>();
// TODO: Generate and Save the Secure Value
LOG_WARNING(Service_FS,
"(STUBBED) called, value=0x{:016x} secure_value_slot=0x{:08X}",
value, secure_value_slot);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void FS_USER::GetThisSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
u32 secure_value_slot = rp.Pop<u32>();
LOG_WARNING(
Service_FS,
"(STUBBED) called secure_value_slot=0x{:08X}",
secure_value_slot);
IPC::RequestBuilder rb = rp.MakeBuilder(5, 0);
rb.Push(RESULT_SUCCESS);
// TODO: Implement Secure Value Lookup & Generation
rb.Push<bool>(false); // indicates that the secure value doesn't exist
rb.Push<bool>(false); // looks like a boolean value, purpose unknown
rb.Push<u64>(0); // the secure value
}
void FS_USER::SetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
auto archive_handle = rp.PopRaw<ArchiveHandle>();
u32 secure_value_slot = rp.Pop<u32>();
u64 value = rp.Pop<u64>();
bool flush = rp.Pop<bool>();
// TODO: Generate and Save the Secure Value
LOG_WARNING(Service_FS,
"(STUBBED) called, value=0x{:016x} secure_value_slot=0x{:04X} "
"archive_handle=0x{:08X} flush={}",
value, secure_value_slot, archive_handle, flush);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void FS_USER::GetSaveDataSecureValue(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
auto archive_handle = rp.PopRaw<ArchiveHandle>();
u32 secure_value_slot = rp.Pop<u32>();
LOG_WARNING(
Service_FS,
"(STUBBED) called secure_value_slot=0x{:08X} archive_handle=0x{:08X}",
secure_value_slot, archive_handle);
IPC::RequestBuilder rb = rp.MakeBuilder(5, 0);
rb.Push(RESULT_SUCCESS);
// TODO: Implement Secure Value Lookup & Generation
rb.Push<bool>(false); // indicates that the secure value doesn't exist
rb.Push<bool>(false); // looks like a boolean value, purpose unknown
rb.Push<u64>(0); // the secure value
}
void FS_USER::RegisterProgramInfo(u32 process_id, u64 program_id, const std::string& filepath) {
const MediaType media_type = GetMediaTypeFromPath(filepath); const MediaType media_type = GetMediaTypeFromPath(filepath);
program_info_map.insert_or_assign(process_id, ProgramInfo{program_id, media_type}); program_info_map.insert_or_assign(process_id, ProgramInfo{program_id, media_type});
if (media_type == MediaType::GameCard) { if (media_type == MediaType::GameCard) {
@ -828,6 +927,20 @@ std::string FS_USER::GetCurrentGamecardPath() const {
return current_gamecard_path; return current_gamecard_path;
} }
void FS_USER::RegisterProductInfo(u32 process_id, const ProductInfo& product_info) {
product_info_map.insert_or_assign(process_id, product_info);
}
bool FS_USER::GetProductInfo(u32 process_id, ProductInfo& out_product_info) {
auto it = product_info_map.find(process_id);
if (it != product_info_map.end()) {
out_product_info = it->second;
return true;
} else {
return false;
}
}
ResultVal<u16> FS_USER::GetSpecialContentIndexFromGameCard(u64 title_id, SpecialContentType type) { ResultVal<u16> FS_USER::GetSpecialContentIndexFromGameCard(u64 title_id, SpecialContentType type) {
// TODO(B3N30) check if on real 3DS NCSD is checked if partition exists // TODO(B3N30) check if on real 3DS NCSD is checked if partition exists
@ -929,7 +1042,7 @@ FS_USER::FS_USER(Core::System& system)
{0x082B, nullptr, "CardNorDirectRead_4xIO"}, {0x082B, nullptr, "CardNorDirectRead_4xIO"},
{0x082C, nullptr, "CardNorDirectCpuWriteWithoutVerify"}, {0x082C, nullptr, "CardNorDirectCpuWriteWithoutVerify"},
{0x082D, nullptr, "CardNorDirectSectorEraseWithoutVerify"}, {0x082D, nullptr, "CardNorDirectSectorEraseWithoutVerify"},
{0x082E, nullptr, "GetProductInfo"}, {0x082E, &FS_USER::GetProductInfo, "GetProductInfo"},
{0x082F, &FS_USER::GetProgramLaunchInfo, "GetProgramLaunchInfo"}, {0x082F, &FS_USER::GetProgramLaunchInfo, "GetProgramLaunchInfo"},
{0x0830, &FS_USER::ObsoletedCreateExtSaveData, "Obsoleted_3_0_CreateExtSaveData"}, {0x0830, &FS_USER::ObsoletedCreateExtSaveData, "Obsoleted_3_0_CreateExtSaveData"},
{0x0831, nullptr, "CreateSharedExtSaveData"}, {0x0831, nullptr, "CreateSharedExtSaveData"},
@ -984,12 +1097,16 @@ FS_USER::FS_USER(Core::System& system)
{0x0862, &FS_USER::SetPriority, "SetPriority"}, {0x0862, &FS_USER::SetPriority, "SetPriority"},
{0x0863, &FS_USER::GetPriority, "GetPriority"}, {0x0863, &FS_USER::GetPriority, "GetPriority"},
{0x0864, nullptr, "GetNandInfo"}, {0x0864, nullptr, "GetNandInfo"},
{0x0865, &FS_USER::SetSaveDataSecureValue, "SetSaveDataSecureValue"}, {0x0865, &FS_USER::ObsoletedSetSaveDataSecureValue, "SetSaveDataSecureValue"},
{0x0866, &FS_USER::GetSaveDataSecureValue, "GetSaveDataSecureValue"}, {0x0866, &FS_USER::ObsoletedGetSaveDataSecureValue, "GetSaveDataSecureValue"},
{0x0867, nullptr, "ControlSecureSave"}, {0x0867, nullptr, "ControlSecureSave"},
{0x0868, nullptr, "GetMediaType"}, {0x0868, nullptr, "GetMediaType"},
{0x0869, nullptr, "GetNandEraseCount"}, {0x0869, nullptr, "GetNandEraseCount"},
{0x086A, nullptr, "ReadNandReport"}, {0x086A, nullptr, "ReadNandReport"},
{0x086E, &FS_USER::SetThisSaveDataSecureValue, "SetThisSaveDataSecureValue" },
{0x086F, &FS_USER::GetThisSaveDataSecureValue, "GetThisSaveDataSecureValue" },
{0x0875, &FS_USER::SetSaveDataSecureValue, "SetSaveDataSecureValue" },
{0x0876, &FS_USER::GetSaveDataSecureValue, "GetSaveDataSecureValue" },
{0x087A, &FS_USER::AddSeed, "AddSeed"}, {0x087A, &FS_USER::AddSeed, "AddSeed"},
{0x087D, &FS_USER::GetNumSeeds, "GetNumSeeds"}, {0x087D, &FS_USER::GetNumSeeds, "GetNumSeeds"},
{0x0886, nullptr, "CheckUpdatedDat"}, {0x0886, nullptr, "CheckUpdatedDat"},

View File

@ -4,6 +4,7 @@
#pragma once #pragma once
#include "archive.h"
#include <unordered_map> #include <unordered_map>
#include <boost/serialization/base_object.hpp> #include <boost/serialization/base_object.hpp>
#include "common/common_types.h" #include "common/common_types.h"
@ -47,12 +48,22 @@ class FS_USER final : public ServiceFramework<FS_USER, ClientSlot> {
public: public:
explicit FS_USER(Core::System& system); explicit FS_USER(Core::System& system);
// On real HW this is part of FS:Reg. But since that module is only used by loader and pm, which // On real HW this is part of FSReg (FSReg:Register). But since that module is only used by
// we HLEed, we can just directly use it here // loader and pm, which we HLEed, we can just directly use it here
void Register(u32 process_id, u64 program_id, const std::string& filepath); void RegisterProgramInfo(u32 process_id, u64 program_id, const std::string& filepath);
std::string GetCurrentGamecardPath() const; std::string GetCurrentGamecardPath() const;
struct ProductInfo {
std::array<u8, 0x10> product_code;
u16_le maker_code;
u16_le remaster_version;
};
void RegisterProductInfo(u32 process_id, const ProductInfo& product_info);
bool GetProductInfo(u32 process_id, ProductInfo& out_product_info);
/// Gets the registered program info of a process. /// Gets the registered program info of a process.
ResultVal<ProgramInfo> GetProgramLaunchInfo(u32 process_id) const { ResultVal<ProgramInfo> GetProgramLaunchInfo(u32 process_id) const {
auto info = program_info_map.find(process_id); auto info = program_info_map.find(process_id);
@ -509,6 +520,17 @@ private:
*/ */
void GetFormatInfo(Kernel::HLERequestContext& ctx); void GetFormatInfo(Kernel::HLERequestContext& ctx);
/**
* FS_User::GetProductInfo service function.
* Inputs:
* 0 : 0x082E0040
* 1 : Process ID
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-6 : Product info
*/
void GetProductInfo(Kernel::HLERequestContext& ctx);
/** /**
* FS_User::GetProgramLaunchInfo service function. * FS_User::GetProgramLaunchInfo service function.
* Inputs: * Inputs:
@ -600,7 +622,7 @@ private:
* 0 : 0x08650140 * 0 : 0x08650140
* 1 : Result of function, 0 on success, otherwise error code * 1 : Result of function, 0 on success, otherwise error code
*/ */
void SetSaveDataSecureValue(Kernel::HLERequestContext& ctx); void ObsoletedSetSaveDataSecureValue(Kernel::HLERequestContext& ctx);
/** /**
* FS_User::GetSaveDataSecureValue service function. * FS_User::GetSaveDataSecureValue service function.
@ -615,6 +637,39 @@ private:
* 2 : If Secure Value doesn't exist, 0, if it exists, 1 * 2 : If Secure Value doesn't exist, 0, if it exists, 1
* 3-4 : Secure Value * 3-4 : Secure Value
*/ */
void ObsoletedGetSaveDataSecureValue(Kernel::HLERequestContext& ctx);
void SetThisSaveDataSecureValue(Kernel::HLERequestContext& ctx);
void GetThisSaveDataSecureValue(Kernel::HLERequestContext& ctx);
/**
* FS_User::SetSaveDataSecureValue service function.
* Inputs:
* 0 : 0x08750180
* 1-2 : Archive
* 3 : Secure Value Slot
* 4 : value
* 5 : flush
* Outputs:
* 0 : header
* 1 : Result of function, 0 on success, otherwise error code
*/
void SetSaveDataSecureValue(Kernel::HLERequestContext& ctx);
/**
* FS_User::GetSaveDataSecureValue service function.
* Inputs:
* 0 : 0x087600C0
* 1-2 : Archive
* 2 : Secure Value slot
* Outputs:
* 0 : Header
* 1 : Result of function, 0 on success, otherwise error code
* 2 : If Secure Value doesn't exist, 0, if it exists, 1
* 3 : unknown
* 4-5 : Secure Value
*/
void GetSaveDataSecureValue(Kernel::HLERequestContext& ctx); void GetSaveDataSecureValue(Kernel::HLERequestContext& ctx);
static ResultVal<u16> GetSpecialContentIndexFromGameCard(u64 title_id, SpecialContentType type); static ResultVal<u16> GetSpecialContentIndexFromGameCard(u64 title_id, SpecialContentType type);
@ -624,6 +679,8 @@ private:
std::unordered_map<u32, ProgramInfo> program_info_map; std::unordered_map<u32, ProgramInfo> program_info_map;
std::string current_gamecard_path; std::string current_gamecard_path;
std::unordered_map<u32, ProductInfo> product_info_map;
u32 priority = -1; ///< For SetPriority and GetPriority service functions u32 priority = -1; ///< For SetPriority and GetPriority service functions
Core::System& system; Core::System& system;

View File

@ -3,11 +3,15 @@
// Refer to the license.txt file included. // Refer to the license.txt file included.
#include <atomic> #include <atomic>
#include <tuple>
#include <unordered_map> #include <unordered_map>
#include <boost/algorithm/string/replace.hpp>
#include <boost/url/src.hpp>
#include <cryptopp/aes.h> #include <cryptopp/aes.h>
#include <cryptopp/modes.h> #include <cryptopp/modes.h>
#include "common/archives.h" #include "common/archives.h"
#include "common/assert.h" #include "common/assert.h"
#include "common/string_util.h"
#include "core/core.h" #include "core/core.h"
#include "core/file_sys/archive_ncch.h" #include "core/file_sys/archive_ncch.h"
#include "core/file_sys/file_backend.h" #include "core/file_sys/file_backend.h"
@ -28,6 +32,8 @@ enum {
InvalidRequestState = 22, InvalidRequestState = 22,
TooManyContexts = 26, TooManyContexts = 26,
InvalidRequestMethod = 32, InvalidRequestMethod = 32,
HeaderNotFound = 40,
BufferTooSmall = 43,
ContextNotFound = 100, ContextNotFound = 100,
/// This error is returned in multiple situations: when trying to initialize an /// This error is returned in multiple situations: when trying to initialize an
@ -48,6 +54,10 @@ const ResultCode ERROR_NOT_IMPLEMENTED = // 0xD960A3F4
const ResultCode ERROR_TOO_MANY_CLIENT_CERTS = // 0xD8A0A0CB const ResultCode ERROR_TOO_MANY_CLIENT_CERTS = // 0xD8A0A0CB
ResultCode(ErrCodes::TooManyClientCerts, ErrorModule::HTTP, ErrorSummary::InvalidState, ResultCode(ErrCodes::TooManyClientCerts, ErrorModule::HTTP, ErrorSummary::InvalidState,
ErrorLevel::Permanent); ErrorLevel::Permanent);
const ResultCode ERROR_HEADER_NOT_FOUND = ResultCode(
ErrCodes::HeaderNotFound, ErrorModule::HTTP, ErrorSummary::InvalidState, ErrorLevel::Permanent);
const ResultCode ERROR_BUFFER_SMALL = ResultCode(ErrCodes::BufferTooSmall, ErrorModule::HTTP,
ErrorSummary::WouldBlock, ErrorLevel::Permanent);
const ResultCode ERROR_WRONG_CERT_ID = // 0xD8E0B839 const ResultCode ERROR_WRONG_CERT_ID = // 0xD8E0B839
ResultCode(57, ErrorModule::SSL, ErrorSummary::InvalidArgument, ErrorLevel::Permanent); ResultCode(57, ErrorModule::SSL, ErrorSummary::InvalidArgument, ErrorLevel::Permanent);
const ResultCode ERROR_WRONG_CERT_HANDLE = // 0xD8A0A0C9 const ResultCode ERROR_WRONG_CERT_HANDLE = // 0xD8A0A0C9
@ -55,47 +65,127 @@ const ResultCode ERROR_WRONG_CERT_HANDLE = // 0xD8A0A0C9
const ResultCode ERROR_CERT_ALREADY_SET = // 0xD8A0A03D const ResultCode ERROR_CERT_ALREADY_SET = // 0xD8A0A03D
ResultCode(61, ErrorModule::HTTP, ErrorSummary::InvalidState, ErrorLevel::Permanent); ResultCode(61, ErrorModule::HTTP, ErrorSummary::InvalidState, ErrorLevel::Permanent);
static std::pair<std::string, std::string> SplitUrl(const std::string& url) { // Splits URL into its components. Example: https://citra-emu.org:443/index.html
// is_https: true; host: citra-emu.org; port: 443; path: /index.html
static URLInfo SplitUrl(const std::string& url) {
const std::string prefix = "://"; const std::string prefix = "://";
constexpr int default_http_port = 80;
constexpr int default_https_port = 443;
std::string host;
int port = -1;
std::string path;
const auto scheme_end = url.find(prefix); const auto scheme_end = url.find(prefix);
const auto prefix_end = scheme_end == std::string::npos ? 0 : scheme_end + prefix.length(); const auto prefix_end = scheme_end == std::string::npos ? 0 : scheme_end + prefix.length();
bool is_https = scheme_end != std::string::npos && url.starts_with("https");
const auto path_index = url.find("/", prefix_end); const auto path_index = url.find("/", prefix_end);
std::string host;
std::string path;
if (path_index == std::string::npos) { if (path_index == std::string::npos) {
// If no path is specified after the host, set it to "/" // If no path is specified after the host, set it to "/"
host = url; host = url.substr(prefix_end);
const auto port_start = host.find(":");
if (port_start != std::string::npos) {
std::string port_str = host.substr(port_start + 1);
host = host.substr(0, port_start);
char* pEnd = NULL;
port = std::strtol(port_str.c_str(), &pEnd, 10);
if (*pEnd) {
port = -1;
}
}
path = "/"; path = "/";
} else { } else {
host = url.substr(0, path_index); host = url.substr(prefix_end, path_index - prefix_end);
const auto port_start = host.find(":");
if (port_start != std::string::npos) {
std::string port_str = host.substr(port_start + 1);
host = host.substr(0, port_start);
char* pEnd = NULL;
port = std::strtol(port_str.c_str(), &pEnd, 10);
if (*pEnd) {
port = -1;
}
}
path = url.substr(path_index); path = url.substr(path_index);
} }
return std::make_pair(host, path); if (port == -1) {
port = is_https ? default_https_port : default_http_port;
}
return URLInfo{
.is_https = is_https,
.host = host,
.port = port,
.path = path,
};
} }
static ssize_t WriteHeaders(httplib::Stream& strm,
std::span<const Context::RequestHeader> headers) {
ssize_t write_len = 0;
for (const auto& x : headers) {
auto len = strm.write_format("%s: %s\r\n", x.name.c_str(), x.value.c_str());
if (len < 0) {
return len;
}
write_len += len;
}
auto len = strm.write("\r\n");
if (len < 0) {
return len;
}
write_len += len;
return write_len;
}
static size_t HandleHeaderWrite(std::vector<Context::RequestHeader>& pending_headers,
httplib::Stream& strm, httplib::Headers& httplib_headers) {
std::vector<Context::RequestHeader> final_headers;
std::vector<Context::RequestHeader>::iterator it_p;
httplib::Headers::iterator it_h;
auto find_pending_header = [&pending_headers](const std::string& str) {
return std::find_if(pending_headers.begin(), pending_headers.end(),
[&str](Context::RequestHeader& rh) { return rh.name == str; });
};
// Watch out for header ordering!!
// First: Host
it_p = find_pending_header("Host");
if (it_p != pending_headers.end()) {
final_headers.push_back(Context::RequestHeader(it_p->name, it_p->value));
pending_headers.erase(it_p);
} else {
it_h = httplib_headers.find("Host");
if (it_h != httplib_headers.end()) {
final_headers.push_back(Context::RequestHeader(it_h->first, it_h->second));
}
}
// Second, user defined headers
// Third, Content-Type (optional, appended by MakeRequest)
for (const auto& header : pending_headers) {
final_headers.push_back(header);
}
// Fourth: Content-Length
it_p = find_pending_header("Content-Length");
if (it_p != pending_headers.end()) {
final_headers.push_back(Context::RequestHeader(it_p->name, it_p->value));
pending_headers.erase(it_p);
} else {
it_h = httplib_headers.find("Content-Length");
if (it_h != httplib_headers.end()) {
final_headers.push_back(Context::RequestHeader(it_h->first, it_h->second));
}
}
return WriteHeaders(strm, final_headers);
};
void Context::MakeRequest() { void Context::MakeRequest() {
ASSERT(state == RequestState::NotStarted); ASSERT(state == RequestState::NotStarted);
const auto& [host, path] = SplitUrl(url);
const auto client = std::make_unique<httplib::Client>(host);
SSL_CTX* ctx = client->ssl_context();
if (ctx) {
if (auto client_cert = ssl_config.client_cert_ctx.lock()) {
SSL_CTX_use_certificate_ASN1(ctx, static_cast<int>(client_cert->certificate.size()),
client_cert->certificate.data());
SSL_CTX_use_PrivateKey_ASN1(EVP_PKEY_RSA, ctx, client_cert->private_key.data(),
static_cast<long>(client_cert->private_key.size()));
}
// TODO(B3N30): Check for SSLOptions-Bits and set the verify method accordingly
// https://www.3dbrew.org/wiki/SSL_Services#SSLOpt
// Hack: Since for now RootCerts are not implemented we set the VerifyMode to None.
SSL_CTX_set_verify(ctx, SSL_VERIFY_NONE, NULL);
}
state = RequestState::InProgress;
static const std::unordered_map<RequestMethod, std::string> request_method_strings{ static const std::unordered_map<RequestMethod, std::string> request_method_strings{
{RequestMethod::Get, "GET"}, {RequestMethod::Post, "POST"}, {RequestMethod::Get, "GET"}, {RequestMethod::Post, "POST"},
{RequestMethod::Head, "HEAD"}, {RequestMethod::Put, "PUT"}, {RequestMethod::Head, "HEAD"}, {RequestMethod::Put, "PUT"},
@ -103,11 +193,13 @@ void Context::MakeRequest() {
{RequestMethod::PutEmpty, "PUT"}, {RequestMethod::PutEmpty, "PUT"},
}; };
URLInfo url_info = SplitUrl(url);
httplib::Request request; httplib::Request request;
httplib::Error error; std::vector<Context::RequestHeader> pending_headers;
request.method = request_method_strings.at(method); request.method = request_method_strings.at(method);
request.path = path; request.path = url_info.path;
// TODO(B3N30): Add post data body
request.progress = [this](u64 current, u64 total) -> bool { request.progress = [this](u64 current, u64 total) -> bool {
// TODO(B3N30): Is there a state that shows response header are available // TODO(B3N30): Is there a state that shows response header are available
current_download_size_bytes = current; current_download_size_bytes = current;
@ -116,9 +208,40 @@ void Context::MakeRequest() {
}; };
for (const auto& header : headers) { for (const auto& header : headers) {
request.headers.emplace(header.name, header.value); pending_headers.push_back(header);
} }
if (!post_data.empty()) {
pending_headers.push_back(
Context::RequestHeader("Content-Type", "application/x-www-form-urlencoded"));
request.body = httplib::detail::params_to_query_str(post_data);
boost::replace_all(request.body, "*", "%2A");
}
if (!post_data_raw.empty()) {
request.body = post_data_raw;
}
state = RequestState::InProgress;
if (url_info.is_https) {
MakeRequestSSL(request, url_info, pending_headers);
} else {
MakeRequestNonSSL(request, url_info, pending_headers);
}
}
void Context::MakeRequestNonSSL(httplib::Request& request, const URLInfo& url_info,
std::vector<Context::RequestHeader>& pending_headers) {
httplib::Error error{-1};
std::unique_ptr<httplib::Client> client =
std::make_unique<httplib::Client>(url_info.host, url_info.port);
client->set_header_writer(
[&pending_headers](httplib::Stream& strm, httplib::Headers& httplib_headers) {
return HandleHeaderWrite(pending_headers, strm, httplib_headers);
});
if (!client->send(request, response, error)) { if (!client->send(request, response, error)) {
LOG_ERROR(Service_HTTP, "Request failed: {}: {}", error, httplib::to_string(error)); LOG_ERROR(Service_HTTP, "Request failed: {}: {}", error, httplib::to_string(error));
state = RequestState::TimedOut; state = RequestState::TimedOut;
@ -128,6 +251,57 @@ void Context::MakeRequest() {
state = RequestState::ReadyToDownloadContent; state = RequestState::ReadyToDownloadContent;
} }
} }
void Context::MakeRequestSSL(httplib::Request& request, const URLInfo& url_info,
std::vector<Context::RequestHeader>& pending_headers) {
httplib::Error error{-1};
X509* cert = nullptr;
EVP_PKEY* key = nullptr;
{
std::unique_ptr<httplib::SSLClient> client;
if (uses_default_client_cert) {
const unsigned char* tmp_cert_ptr = clcert_data->certificate.data();
const unsigned char* tmp_key_ptr = clcert_data->private_key.data();
cert = d2i_X509(nullptr, &tmp_cert_ptr, (long)clcert_data->certificate.size());
key = d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &tmp_key_ptr,
(long)clcert_data->private_key.size());
client = std::make_unique<httplib::SSLClient>(url_info.host, url_info.port, cert, key);
} else if (auto client_cert = ssl_config.client_cert_ctx.lock()) {
const unsigned char* tmp_cert_ptr = client_cert->certificate.data();
const unsigned char* tmp_key_ptr = client_cert->private_key.data();
cert = d2i_X509(nullptr, &tmp_cert_ptr, (long)client_cert->certificate.size());
key = d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &tmp_key_ptr,
(long)client_cert->private_key.size());
client = std::make_unique<httplib::SSLClient>(url_info.host, url_info.port, cert, key);
} else {
client = std::make_unique<httplib::SSLClient>(url_info.host, url_info.port);
}
// TODO(B3N30): Check for SSLOptions-Bits and set the verify method accordingly
// https://www.3dbrew.org/wiki/SSL_Services#SSLOpt
// Hack: Since for now RootCerts are not implemented we set the VerifyMode to None.
client->enable_server_certificate_verification(false);
client->set_header_writer(
[&pending_headers](httplib::Stream& strm, httplib::Headers& httplib_headers) {
return HandleHeaderWrite(pending_headers, strm, httplib_headers);
});
if (!client->send(request, response, error)) {
LOG_ERROR(Service_HTTP, "Request failed: {}: {}", error, httplib::to_string(error));
state = RequestState::TimedOut;
} else {
LOG_DEBUG(Service_HTTP, "Request successful");
// TODO(B3N30): Verify this state on HW
state = RequestState::ReadyToDownloadContent;
}
}
if (cert) {
X509_free(cert);
}
if (key) {
EVP_PKEY_free(key);
}
}
void HTTP_C::Initialize(Kernel::HLERequestContext& ctx) { void HTTP_C::Initialize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
@ -138,7 +312,7 @@ void HTTP_C::Initialize(Kernel::HLERequestContext& ctx) {
shared_memory->SetName("HTTP_C:shared_memory"); shared_memory->SetName("HTTP_C:shared_memory");
} }
LOG_WARNING(Service_HTTP, "(STUBBED) called, shared memory size: {} pid: {}", shmem_size, pid); LOG_DEBUG(Service_HTTP, "shared memory size: {} pid: {}", shmem_size, pid);
auto* session_data = GetSessionData(ctx.Session()); auto* session_data = GetSessionData(ctx.Session());
ASSERT(session_data); ASSERT(session_data);
@ -198,14 +372,21 @@ void HTTP_C::BeginRequest(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>(); const Context::Handle context_handle = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, context_id={}", context_handle); LOG_DEBUG(Service_HTTP, "context_id={}", context_handle);
if (!PerformStateChecks(ctx, rp, context_handle)) { if (!PerformStateChecks(ctx, rp, context_handle)) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
// This should never happen in real hardware, but can happen on citra.
if (http_context.uses_default_client_cert && !http_context.clcert_data->init) {
LOG_ERROR(Service_HTTP, "failed to begin HTTP request: client cert not found.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(ERROR_STATE_ERROR);
return;
}
// On a 3DS BeginRequest and BeginRequestAsync will push the Request to a worker queue. // On a 3DS BeginRequest and BeginRequestAsync will push the Request to a worker queue.
// You can only enqueue 8 requests at the same time. // You can only enqueue 8 requests at the same time.
@ -214,8 +395,9 @@ void HTTP_C::BeginRequest(Kernel::HLERequestContext& ctx) {
// Then there are 3? worker threads that pop the requests from the queue and send them // Then there are 3? worker threads that pop the requests from the queue and send them
// For now make every request async in it's own thread. // For now make every request async in it's own thread.
itr->second.request_future = http_context.request_future =
std::async(std::launch::async, &Context::MakeRequest, std::ref(itr->second)); std::async(std::launch::async, &Context::MakeRequest, std::ref(http_context));
http_context.current_copied_data = 0;
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
@ -225,14 +407,21 @@ void HTTP_C::BeginRequestAsync(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>(); const Context::Handle context_handle = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, context_id={}", context_handle); LOG_WARNING(Service_HTTP, "context_id={}", context_handle);
if (!PerformStateChecks(ctx, rp, context_handle)) { if (!PerformStateChecks(ctx, rp, context_handle)) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
// This should never happen in real hardware, but can happen on citra.
if (http_context.uses_default_client_cert && !http_context.clcert_data->init) {
LOG_ERROR(Service_HTTP, "failed to begin HTTP request: client cert not found.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(ERROR_STATE_ERROR);
return;
}
// On a 3DS BeginRequest and BeginRequestAsync will push the Request to a worker queue. // On a 3DS BeginRequest and BeginRequestAsync will push the Request to a worker queue.
// You can only enqueue 8 requests at the same time. // You can only enqueue 8 requests at the same time.
@ -241,8 +430,9 @@ void HTTP_C::BeginRequestAsync(Kernel::HLERequestContext& ctx) {
// Then there are 3? worker threads that pop the requests from the queue and send them // Then there are 3? worker threads that pop the requests from the queue and send them
// For now make every request async in it's own thread. // For now make every request async in it's own thread.
itr->second.request_future = http_context.request_future =
std::async(std::launch::async, &Context::MakeRequest, std::ref(itr->second)); std::async(std::launch::async, &Context::MakeRequest, std::ref(http_context));
http_context.current_copied_data = 0;
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
@ -258,30 +448,91 @@ void HTTP_C::ReceiveDataTimeout(Kernel::HLERequestContext& ctx) {
void HTTP_C::ReceiveDataImpl(Kernel::HLERequestContext& ctx, bool timeout) { void HTTP_C::ReceiveDataImpl(Kernel::HLERequestContext& ctx, bool timeout) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
[[maybe_unused]] const u32 buffer_size = rp.Pop<u32>();
u64 timeout_nanos = 0;
if (timeout) {
timeout_nanos = rp.Pop<u64>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, timeout={}", timeout_nanos);
} else {
LOG_WARNING(Service_HTTP, "(STUBBED) called");
}
[[maybe_unused]] Kernel::MappedBuffer& buffer = rp.PopMappedBuffer();
if (!PerformStateChecks(ctx, rp, context_handle)) { struct AsyncData {
// Input
HTTP_C* own;
u64 timeout_nanos = 0;
bool timeout;
Context::Handle context_handle;
u32 buffer_size;
Kernel::MappedBuffer* buffer;
bool is_complete;
// Output
ResultCode async_res = RESULT_SUCCESS;
};
std::shared_ptr<AsyncData> async_data = std::make_shared<AsyncData>();
async_data->own = this;
async_data->timeout = timeout;
async_data->context_handle = rp.Pop<u32>();
async_data->buffer_size = rp.Pop<u32>();
if (timeout) {
async_data->timeout_nanos = rp.Pop<u64>();
LOG_DEBUG(Service_HTTP, "timeout={}", async_data->timeout_nanos);
} else {
LOG_DEBUG(Service_HTTP, "");
}
async_data->buffer = &rp.PopMappedBuffer();
if (!PerformStateChecks(ctx, rp, async_data->context_handle)) {
return; return;
} }
auto itr = contexts.find(context_handle); ctx.RunAsync(
ASSERT(itr != contexts.end()); [async_data](Kernel::HLERequestContext& ctx) {
Context& http_context = async_data->own->GetContext(async_data->context_handle);
if (timeout) { if (async_data->timeout) {
itr->second.request_future.wait_for(std::chrono::nanoseconds(timeout_nanos)); auto wait_res = http_context.request_future.wait_for(
// TODO (flTobi): Return error on timeout std::chrono::nanoseconds(async_data->timeout_nanos));
} else { if (wait_res == std::future_status::timeout) {
itr->second.request_future.wait(); async_data->async_res =
ResultCode(105, ErrorModule::HTTP, ErrorSummary::NothingHappened,
ErrorLevel::Permanent);
} }
} else {
http_context.request_future.wait();
}
// Simulate small delay from HTTP receive.
return 1'000'000;
},
[async_data](Kernel::HLERequestContext& ctx) {
IPC::RequestBuilder rb(ctx, ctx.CommandID(), 1, 0);
if (async_data->async_res != RESULT_SUCCESS) {
rb.Push(async_data->async_res);
return;
}
Context& http_context = async_data->own->GetContext(async_data->context_handle);
size_t remaining_data =
http_context.response.body.size() - http_context.current_copied_data;
if (async_data->buffer_size >= remaining_data) {
async_data->buffer->Write(http_context.response.body.data() +
http_context.current_copied_data,
0, remaining_data);
http_context.current_copied_data += remaining_data;
rb.Push(RESULT_SUCCESS);
} else {
async_data->buffer->Write(http_context.response.body.data() +
http_context.current_copied_data,
0, async_data->buffer_size);
http_context.current_copied_data += async_data->buffer_size;
rb.Push(ERROR_BUFFER_SMALL);
}
LOG_DEBUG(Service_HTTP, "Receive: buffer_size= {}, total_copied={}, total_body={}",
async_data->buffer_size, http_context.current_copied_data,
http_context.response.body.size());
});
}
void HTTP_C::SetProxyDefault(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}", context_handle);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
@ -359,7 +610,7 @@ void HTTP_C::CloseContext(Kernel::HLERequestContext& ctx) {
u32 context_handle = rp.Pop<u32>(); u32 context_handle = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}", context_handle); LOG_DEBUG(Service_HTTP, "handle={}", context_handle);
auto* session_data = EnsureSessionInitialized(ctx, rp); auto* session_data = EnsureSessionInitialized(ctx, rp);
if (!session_data) { if (!session_data) {
@ -389,6 +640,23 @@ void HTTP_C::CloseContext(Kernel::HLERequestContext& ctx) {
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
void HTTP_C::CancelConnection(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const u32 context_handle = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}", context_handle);
const auto* session_data = EnsureSessionInitialized(ctx, rp);
if (!session_data) {
return;
}
[[maybe_unused]] Context& http_context = GetContext(context_handle);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void HTTP_C::AddRequestHeader(Kernel::HLERequestContext& ctx) { void HTTP_C::AddRequestHeader(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const u32 context_handle = rp.Pop<u32>(); const u32 context_handle = rp.Pop<u32>();
@ -411,10 +679,9 @@ void HTTP_C::AddRequestHeader(Kernel::HLERequestContext& ctx) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
if (itr->second.state != RequestState::NotStarted) { if (http_context.state != RequestState::NotStarted) {
LOG_ERROR(Service_HTTP, LOG_ERROR(Service_HTTP,
"Tried to add a request header on a context that has already been started."); "Tried to add a request header on a context that has already been started.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
@ -424,12 +691,7 @@ void HTTP_C::AddRequestHeader(Kernel::HLERequestContext& ctx) {
return; return;
} }
ASSERT(std::find_if(itr->second.headers.begin(), itr->second.headers.end(), http_context.headers.emplace_back(name, value);
[&name](const Context::RequestHeader& m) -> bool {
return m.name == name;
}) == itr->second.headers.end());
itr->second.headers.emplace_back(name, value);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
@ -458,10 +720,9 @@ void HTTP_C::AddPostDataAscii(Kernel::HLERequestContext& ctx) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
if (itr->second.state != RequestState::NotStarted) { if (http_context.state != RequestState::NotStarted) {
LOG_ERROR(Service_HTTP, LOG_ERROR(Service_HTTP,
"Tried to add post data on a context that has already been started."); "Tried to add post data on a context that has already been started.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
@ -471,17 +732,113 @@ void HTTP_C::AddPostDataAscii(Kernel::HLERequestContext& ctx) {
return; return;
} }
ASSERT(std::find_if(itr->second.post_data.begin(), itr->second.post_data.end(), http_context.post_data.emplace(name, value);
[&name](const Context::PostData& m) -> bool { return m.name == name; }) ==
itr->second.post_data.end());
itr->second.post_data.emplace_back(name, value);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2); IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.PushMappedBuffer(value_buffer); rb.PushMappedBuffer(value_buffer);
} }
void HTTP_C::AddPostDataRaw(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const u32 context_handle = rp.Pop<u32>();
const u32 post_data_len = rp.Pop<u32>();
auto buffer = rp.PopMappedBuffer();
LOG_DEBUG(Service_HTTP, "context_handle={}, post_data_len={}", context_handle, post_data_len);
if (!PerformStateChecks(ctx, rp, context_handle)) {
return;
}
Context& http_context = GetContext(context_handle);
if (http_context.state != RequestState::NotStarted) {
LOG_ERROR(Service_HTTP,
"Tried to add post data on a context that has already been started.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(ResultCode(ErrCodes::InvalidRequestState, ErrorModule::HTTP,
ErrorSummary::InvalidState, ErrorLevel::Permanent));
rb.PushMappedBuffer(buffer);
return;
}
http_context.post_data_raw.resize(buffer.GetSize());
buffer.Read(http_context.post_data_raw.data(), 0, buffer.GetSize());
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS);
rb.PushMappedBuffer(buffer);
}
void HTTP_C::GetResponseHeader(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
struct AsyncData {
HTTP_C* own;
u32 context_handle;
u32 name_len;
u32 value_max_len;
std::span<const u8> header_name;
Kernel::MappedBuffer* value_buffer;
};
std::shared_ptr<AsyncData> async_data = std::make_shared<AsyncData>();
async_data->own = this;
async_data->context_handle = rp.Pop<u32>();
async_data->name_len = rp.Pop<u32>();
async_data->value_max_len = rp.Pop<u32>();
async_data->header_name = rp.PopStaticBuffer();
async_data->value_buffer = &rp.PopMappedBuffer();
if (!PerformStateChecks(ctx, rp, async_data->context_handle)) {
return;
}
ctx.RunAsync(
[async_data](Kernel::HLERequestContext& ctx) {
Context& http_context = async_data->own->GetContext(async_data->context_handle);
http_context.request_future.wait();
return 0;
},
[async_data](Kernel::HLERequestContext& ctx) {
std::string header_name_str(
reinterpret_cast<const char*>(async_data->header_name.data()),
async_data->name_len);
Common::TruncateString(header_name_str);
Context& http_context = async_data->own->GetContext(async_data->context_handle);
auto& headers = http_context.response.headers;
u32 copied_size = 0;
LOG_DEBUG(Service_HTTP, "header={}, max_len={}", header_name_str,
async_data->value_buffer->GetSize());
auto header = headers.find(header_name_str);
if (header != headers.end()) {
std::string header_value = header->second;
copied_size = (u32)header_value.size();
if (header_value.size() + 1 > async_data->value_buffer->GetSize()) {
header_value.resize(async_data->value_buffer->GetSize() - 1);
}
header_value.push_back('\0');
async_data->value_buffer->Write(header_value.data(), 0, header_value.size());
} else {
LOG_DEBUG(Service_HTTP, "header={} not found", header_name_str);
IPC::RequestBuilder rb(ctx, ctx.CommandID(), 1, 2);
rb.Push(ERROR_HEADER_NOT_FOUND);
rb.PushMappedBuffer(*async_data->value_buffer);
return;
}
IPC::RequestBuilder rb(ctx, ctx.CommandID(), 2, 2);
rb.Push(RESULT_SUCCESS);
rb.Push(copied_size);
rb.PushMappedBuffer(*async_data->value_buffer);
});
}
void HTTP_C::GetResponseStatusCode(Kernel::HLERequestContext& ctx) { void HTTP_C::GetResponseStatusCode(Kernel::HLERequestContext& ctx) {
GetResponseStatusCodeImpl(ctx, false); GetResponseStatusCodeImpl(ctx, false);
} }
@ -492,34 +849,118 @@ void HTTP_C::GetResponseStatusCodeTimeout(Kernel::HLERequestContext& ctx) {
void HTTP_C::GetResponseStatusCodeImpl(Kernel::HLERequestContext& ctx, bool timeout) { void HTTP_C::GetResponseStatusCodeImpl(Kernel::HLERequestContext& ctx, bool timeout) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
struct AsyncData {
// Input
HTTP_C* own;
Context::Handle context_handle;
bool timeout;
u64 timeout_nanos = 0; u64 timeout_nanos = 0;
// Output
ResultCode async_res = RESULT_SUCCESS;
};
std::shared_ptr<AsyncData> async_data = std::make_shared<AsyncData>();
async_data->own = this;
async_data->context_handle = rp.Pop<u32>();
async_data->timeout = timeout;
if (timeout) { if (timeout) {
timeout_nanos = rp.Pop<u64>(); async_data->timeout_nanos = rp.Pop<u64>();
LOG_INFO(Service_HTTP, "called, timeout={}", timeout_nanos); LOG_INFO(Service_HTTP, "called, timeout={}", async_data->timeout_nanos);
} else { } else {
LOG_INFO(Service_HTTP, "called"); LOG_INFO(Service_HTTP, "called");
} }
if (!PerformStateChecks(ctx, rp, async_data->context_handle)) {
return;
}
ctx.RunAsync(
[async_data](Kernel::HLERequestContext& ctx) {
Context& http_context = async_data->own->GetContext(async_data->context_handle);
if (async_data->timeout) {
auto wait_res = http_context.request_future.wait_for(
std::chrono::nanoseconds(async_data->timeout_nanos));
if (wait_res == std::future_status::timeout) {
LOG_DEBUG(Service_HTTP, "Status code: {}", "timeout");
async_data->async_res =
ResultCode(105, ErrorModule::HTTP, ErrorSummary::NothingHappened,
ErrorLevel::Permanent);
}
} else {
http_context.request_future.wait();
}
return 0;
},
[async_data](Kernel::HLERequestContext& ctx) {
if (async_data->async_res != RESULT_SUCCESS) {
IPC::RequestBuilder rb(ctx, ctx.CommandID(), 1, 0);
rb.Push(async_data->async_res);
return;
}
Context& http_context = async_data->own->GetContext(async_data->context_handle);
const u32 response_code = http_context.response.status;
LOG_DEBUG(Service_HTTP, "Status code: {}, response_code={}", "good", response_code);
IPC::RequestBuilder rb(ctx, ctx.CommandID(), 2, 0);
rb.Push(RESULT_SUCCESS);
rb.Push(response_code);
});
}
void HTTP_C::AddTrustedRootCA(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
[[maybe_unused]] const u32 root_ca_len = rp.Pop<u32>();
auto root_ca_data = rp.PopMappedBuffer();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}", context_handle);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 2);
rb.Push(RESULT_SUCCESS);
rb.PushMappedBuffer(root_ca_data);
}
void HTTP_C::AddDefaultCert(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
const u32 certificate_id = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}, certificate_id={}", context_handle,
certificate_id);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void HTTP_C::SetDefaultClientCert(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const Context::Handle context_handle = rp.Pop<u32>();
const ClientCertID client_cert_id = static_cast<ClientCertID>(rp.Pop<u32>());
LOG_DEBUG(Service_HTTP, "client_cert_id={}", client_cert_id);
if (!PerformStateChecks(ctx, rp, context_handle)) { if (!PerformStateChecks(ctx, rp, context_handle)) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
if (timeout) { if (client_cert_id != ClientCertID::Default) {
itr->second.request_future.wait_for(std::chrono::nanoseconds(timeout)); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
// TODO (flTobi): Return error on timeout rb.Push(ERROR_WRONG_CERT_ID);
} else { return;
itr->second.request_future.wait();
} }
const u32 response_code = itr->second.response.status; http_context.uses_default_client_cert = true;
http_context.clcert_data = &GetClCertA();
IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.Push(response_code);
} }
void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) { void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) {
@ -534,8 +975,7 @@ void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) {
return; return;
} }
auto http_context_itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(http_context_itr != contexts.end());
auto cert_context_itr = client_certs.find(client_cert_handle); auto cert_context_itr = client_certs.find(client_cert_handle);
if (cert_context_itr == client_certs.end()) { if (cert_context_itr == client_certs.end()) {
@ -545,7 +985,7 @@ void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) {
return; return;
} }
if (http_context_itr->second.ssl_config.client_cert_ctx.lock()) { if (http_context.ssl_config.client_cert_ctx.lock()) {
LOG_ERROR(Service_HTTP, LOG_ERROR(Service_HTTP,
"Tried to set a client cert to a context that already has a client cert"); "Tried to set a client cert to a context that already has a client cert");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
@ -553,7 +993,7 @@ void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) {
return; return;
} }
if (http_context_itr->second.state != RequestState::NotStarted) { if (http_context.state != RequestState::NotStarted) {
LOG_ERROR(Service_HTTP, LOG_ERROR(Service_HTTP,
"Tried to set a client cert on a context that has already been started."); "Tried to set a client cert on a context that has already been started.");
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
@ -562,7 +1002,7 @@ void HTTP_C::SetClientCertContext(Kernel::HLERequestContext& ctx) {
return; return;
} }
http_context_itr->second.ssl_config.client_cert_ctx = cert_context_itr->second; http_context.ssl_config.client_cert_ctx = cert_context_itr->second;
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
@ -574,8 +1014,7 @@ void HTTP_C::GetSSLError(Kernel::HLERequestContext& ctx) {
LOG_WARNING(Service_HTTP, "(STUBBED) called, context_handle={}, unk={}", context_handle, unk); LOG_WARNING(Service_HTTP, "(STUBBED) called, context_handle={}, unk={}", context_handle, unk);
auto http_context_itr = contexts.find(context_handle); [[maybe_unused]] Context& http_context = GetContext(context_handle);
ASSERT(http_context_itr != contexts.end());
IPC::RequestBuilder rb = rp.MakeBuilder(2, 0); IPC::RequestBuilder rb = rp.MakeBuilder(2, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
@ -584,6 +1023,17 @@ void HTTP_C::GetSSLError(Kernel::HLERequestContext& ctx) {
rb.Push<u32>(0); rb.Push<u32>(0);
} }
void HTTP_C::SetSSLOpt(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const u32 context_handle = rp.Pop<u32>();
const u32 opts = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, context_handle={}, opts={}", context_handle, opts);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void HTTP_C::OpenClientCertContext(Kernel::HLERequestContext& ctx) { void HTTP_C::OpenClientCertContext(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
u32 cert_size = rp.Pop<u32>(); u32 cert_size = rp.Pop<u32>();
@ -650,7 +1100,7 @@ void HTTP_C::OpenDefaultClientCertContext(Kernel::HLERequestContext& ctx) {
return; return;
} }
constexpr u8 default_cert_id = 0x40; constexpr u8 default_cert_id = static_cast<u8>(ClientCertID::Default);
if (cert_id != default_cert_id) { if (cert_id != default_cert_id) {
LOG_ERROR(Service_HTTP, "called with invalid cert_id {}", cert_id); LOG_ERROR(Service_HTTP, "called with invalid cert_id {}", cert_id);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0); IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
@ -724,6 +1174,17 @@ void HTTP_C::CloseClientCertContext(Kernel::HLERequestContext& ctx) {
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
} }
void HTTP_C::SetKeepAlive(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx);
const u32 context_handle = rp.Pop<u32>();
const u32 option = rp.Pop<u32>();
LOG_WARNING(Service_HTTP, "(STUBBED) called, handle={}, option={}", context_handle, option);
IPC::RequestBuilder rb = rp.MakeBuilder(1, 0);
rb.Push(RESULT_SUCCESS);
}
void HTTP_C::Finalize(Kernel::HLERequestContext& ctx) { void HTTP_C::Finalize(Kernel::HLERequestContext& ctx) {
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
@ -746,26 +1207,27 @@ void HTTP_C::GetDownloadSizeState(Kernel::HLERequestContext& ctx) {
return; return;
} }
auto itr = contexts.find(context_handle); Context& http_context = GetContext(context_handle);
ASSERT(itr != contexts.end());
// On the real console, the current downloaded progress and the total size of the content gets // On the real console, the current downloaded progress and the total size of the content gets
// returned. Since we do not support chunked downloads on the host, always return the content // returned. Since we do not support chunked downloads on the host, always return the content
// length if the download is complete and 0 otherwise. // length if the download is complete and 0 otherwise.
u32 content_length = 0; u32 content_length = 0;
const bool is_complete = itr->second.request_future.wait_for(std::chrono::milliseconds(0)) == const bool is_complete = http_context.request_future.wait_for(std::chrono::milliseconds(0)) ==
std::future_status::ready; std::future_status::ready;
if (is_complete) { if (is_complete) {
const auto& headers = itr->second.response.headers; const auto& headers = http_context.response.headers;
const auto& it = headers.find("Content-Length"); const auto& it = headers.find("Content-Length");
if (it != headers.end()) { if (it != headers.end()) {
content_length = std::stoi(it->second); content_length = std::stoi(it->second);
} }
} }
LOG_DEBUG(Service_HTTP, "current={}, total={}", http_context.current_copied_data,
content_length);
IPC::RequestBuilder rb = rp.MakeBuilder(3, 0); IPC::RequestBuilder rb = rp.MakeBuilder(3, 0);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.Push(content_length); rb.Push(static_cast<u32>(http_context.current_copied_data));
rb.Push(content_length); rb.Push(content_length);
} }
@ -895,7 +1357,7 @@ HTTP_C::HTTP_C() : ServiceFramework("http:C", 32) {
{0x0001, &HTTP_C::Initialize, "Initialize"}, {0x0001, &HTTP_C::Initialize, "Initialize"},
{0x0002, &HTTP_C::CreateContext, "CreateContext"}, {0x0002, &HTTP_C::CreateContext, "CreateContext"},
{0x0003, &HTTP_C::CloseContext, "CloseContext"}, {0x0003, &HTTP_C::CloseContext, "CloseContext"},
{0x0004, nullptr, "CancelConnection"}, {0x0004, &HTTP_C::CancelConnection, "CancelConnection"},
{0x0005, nullptr, "GetRequestState"}, {0x0005, nullptr, "GetRequestState"},
{0x0006, &HTTP_C::GetDownloadSizeState, "GetDownloadSizeState"}, {0x0006, &HTTP_C::GetDownloadSizeState, "GetDownloadSizeState"},
{0x0007, nullptr, "GetRequestError"}, {0x0007, nullptr, "GetRequestError"},
@ -905,13 +1367,13 @@ HTTP_C::HTTP_C() : ServiceFramework("http:C", 32) {
{0x000B, &HTTP_C::ReceiveData, "ReceiveData"}, {0x000B, &HTTP_C::ReceiveData, "ReceiveData"},
{0x000C, &HTTP_C::ReceiveDataTimeout, "ReceiveDataTimeout"}, {0x000C, &HTTP_C::ReceiveDataTimeout, "ReceiveDataTimeout"},
{0x000D, nullptr, "SetProxy"}, {0x000D, nullptr, "SetProxy"},
{0x000E, nullptr, "SetProxyDefault"}, {0x000E, &HTTP_C::SetProxyDefault, "SetProxyDefault"},
{0x000F, nullptr, "SetBasicAuthorization"}, {0x000F, nullptr, "SetBasicAuthorization"},
{0x0010, nullptr, "SetSocketBufferSize"}, {0x0010, nullptr, "SetSocketBufferSize"},
{0x0011, &HTTP_C::AddRequestHeader, "AddRequestHeader"}, {0x0011, &HTTP_C::AddRequestHeader, "AddRequestHeader"},
{0x0012, &HTTP_C::AddPostDataAscii, "AddPostDataAscii"}, {0x0012, &HTTP_C::AddPostDataAscii, "AddPostDataAscii"},
{0x0013, nullptr, "AddPostDataBinary"}, {0x0013, nullptr, "AddPostDataBinary"},
{0x0014, nullptr, "AddPostDataRaw"}, {0x0014, &HTTP_C::AddPostDataRaw, "AddPostDataRaw"},
{0x0015, nullptr, "SetPostDataType"}, {0x0015, nullptr, "SetPostDataType"},
{0x0016, nullptr, "SendPostDataAscii"}, {0x0016, nullptr, "SendPostDataAscii"},
{0x0017, nullptr, "SendPostDataAsciiTimeout"}, {0x0017, nullptr, "SendPostDataAsciiTimeout"},
@ -921,19 +1383,20 @@ HTTP_C::HTTP_C() : ServiceFramework("http:C", 32) {
{0x001B, nullptr, "SendPOSTDataRawTimeout"}, {0x001B, nullptr, "SendPOSTDataRawTimeout"},
{0x001C, nullptr, "SetPostDataEncoding"}, {0x001C, nullptr, "SetPostDataEncoding"},
{0x001D, nullptr, "NotifyFinishSendPostData"}, {0x001D, nullptr, "NotifyFinishSendPostData"},
{0x001E, nullptr, "GetResponseHeader"}, {0x001E, &HTTP_C::GetResponseHeader, "GetResponseHeader"},
{0x001F, nullptr, "GetResponseHeaderTimeout"}, {0x001F, nullptr, "GetResponseHeaderTimeout"},
{0x0020, nullptr, "GetResponseData"}, {0x0020, nullptr, "GetResponseData"},
{0x0021, nullptr, "GetResponseDataTimeout"}, {0x0021, nullptr, "GetResponseDataTimeout"},
{0x0022, &HTTP_C::GetResponseStatusCode, "GetResponseStatusCode"}, {0x0022, &HTTP_C::GetResponseStatusCode, "GetResponseStatusCode"},
{0x0023, &HTTP_C::GetResponseStatusCodeTimeout, "GetResponseStatusCodeTimeout"}, {0x0023, &HTTP_C::GetResponseStatusCodeTimeout, "GetResponseStatusCodeTimeout"},
{0x0024, nullptr, "AddTrustedRootCA"}, {0x0024, &HTTP_C::AddTrustedRootCA, "AddTrustedRootCA"},
{0x0025, nullptr, "AddDefaultCert"}, {0x0025, &HTTP_C::AddDefaultCert, "AddDefaultCert"},
{0x0026, nullptr, "SelectRootCertChain"}, {0x0026, nullptr, "SelectRootCertChain"},
{0x0027, nullptr, "SetClientCert"}, {0x0027, nullptr, "SetClientCert"},
{0x0028, &HTTP_C::SetDefaultClientCert, "SetDefaultClientCert"},
{0x0029, &HTTP_C::SetClientCertContext, "SetClientCertContext"}, {0x0029, &HTTP_C::SetClientCertContext, "SetClientCertContext"},
{0x002A, &HTTP_C::GetSSLError, "GetSSLError"}, {0x002A, &HTTP_C::GetSSLError, "GetSSLError"},
{0x002B, nullptr, "SetSSLOpt"}, {0x002B, &HTTP_C::SetSSLOpt, "SetSSLOpt"},
{0x002C, nullptr, "SetSSLClearOpt"}, {0x002C, nullptr, "SetSSLClearOpt"},
{0x002D, nullptr, "CreateRootCertChain"}, {0x002D, nullptr, "CreateRootCertChain"},
{0x002E, nullptr, "DestroyRootCertChain"}, {0x002E, nullptr, "DestroyRootCertChain"},
@ -945,7 +1408,7 @@ HTTP_C::HTTP_C() : ServiceFramework("http:C", 32) {
{0x0034, &HTTP_C::CloseClientCertContext, "CloseClientCertContext"}, {0x0034, &HTTP_C::CloseClientCertContext, "CloseClientCertContext"},
{0x0035, nullptr, "SetDefaultProxy"}, {0x0035, nullptr, "SetDefaultProxy"},
{0x0036, nullptr, "ClearDNSCache"}, {0x0036, nullptr, "ClearDNSCache"},
{0x0037, nullptr, "SetKeepAlive"}, {0x0037, &HTTP_C::SetKeepAlive, "SetKeepAlive"},
{0x0038, nullptr, "SetPostDataTypeSize"}, {0x0038, nullptr, "SetPostDataTypeSize"},
{0x0039, &HTTP_C::Finalize, "Finalize"}, {0x0039, &HTTP_C::Finalize, "Finalize"},
// clang-format on // clang-format on
@ -955,6 +1418,10 @@ HTTP_C::HTTP_C() : ServiceFramework("http:C", 32) {
DecryptClCertA(); DecryptClCertA();
} }
std::shared_ptr<HTTP_C> GetService(Core::System& system) {
return system.ServiceManager().GetService<HTTP_C>("http:C");
}
void InstallInterfaces(Core::System& system) { void InstallInterfaces(Core::System& system) {
auto& service_manager = system.ServiceManager(); auto& service_manager = system.ServiceManager();
std::make_shared<HTTP_C>()->InstallAsService(service_manager); std::make_shared<HTTP_C>()->InstallAsService(service_manager);

View File

@ -21,6 +21,7 @@
#include <ifaddrs.h> #include <ifaddrs.h>
#endif #endif
#include <httplib.h> #include <httplib.h>
#include "core/hle/ipc_helpers.h"
#include "core/hle/kernel/shared_memory.h" #include "core/hle/kernel/shared_memory.h"
#include "core/hle/service/service.h" #include "core/hle/service/service.h"
@ -56,6 +57,17 @@ enum class RequestState : u8 {
TimedOut = 0xA, // Request timed out? TimedOut = 0xA, // Request timed out?
}; };
enum class ClientCertID : u32 {
Default = 0x40, // Default client cert
};
struct URLInfo {
bool is_https;
std::string host;
int port;
std::string path;
};
/// Represents a client certificate along with its private key, stored as a byte array of DER data. /// Represents a client certificate along with its private key, stored as a byte array of DER data.
/// There can only be at most one client certificate context attached to an HTTP context at any /// There can only be at most one client certificate context attached to an HTTP context at any
/// given time. /// given time.
@ -114,6 +126,12 @@ private:
friend class boost::serialization::access; friend class boost::serialization::access;
}; };
struct ClCertAData {
std::vector<u8> certificate;
std::vector<u8> private_key;
bool init = false;
};
/// Represents an HTTP context. /// Represents an HTTP context.
class Context final { class Context final {
public: public:
@ -123,8 +141,6 @@ public:
Context(const Context&) = delete; Context(const Context&) = delete;
Context& operator=(const Context&) = delete; Context& operator=(const Context&) = delete;
void MakeRequest();
struct Proxy { struct Proxy {
std::string url; std::string url;
std::string username; std::string username;
@ -169,22 +185,6 @@ public:
friend class boost::serialization::access; friend class boost::serialization::access;
}; };
struct PostData {
// TODO(Subv): Support Binary and Raw POST elements.
PostData(std::string name, std::string value) : name(name), value(value){};
PostData() = default;
std::string name;
std::string value;
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& name;
ar& value;
}
friend class boost::serialization::access;
};
struct SSLConfig { struct SSLConfig {
u32 options; u32 options;
std::weak_ptr<ClientCertContext> client_cert_ctx; std::weak_ptr<ClientCertContext> client_cert_ctx;
@ -210,12 +210,22 @@ public:
SSLConfig ssl_config{}; SSLConfig ssl_config{};
u32 socket_buffer_size; u32 socket_buffer_size;
std::vector<RequestHeader> headers; std::vector<RequestHeader> headers;
std::vector<PostData> post_data; const ClCertAData* clcert_data;
httplib::Params post_data;
std::string post_data_raw;
std::future<void> request_future; std::future<void> request_future;
std::atomic<u64> current_download_size_bytes; std::atomic<u64> current_download_size_bytes;
std::atomic<u64> total_download_size_bytes; std::atomic<u64> total_download_size_bytes;
size_t current_copied_data;
bool uses_default_client_cert{};
httplib::Response response; httplib::Response response;
void MakeRequest();
void MakeRequestNonSSL(httplib::Request& request, const URLInfo& url_info,
std::vector<Context::RequestHeader>& pending_headers);
void MakeRequestSSL(httplib::Request& request, const URLInfo& url_info,
std::vector<Context::RequestHeader>& pending_headers);
}; };
struct SessionData : public Kernel::SessionRequestHandler::SessionDataBase { struct SessionData : public Kernel::SessionRequestHandler::SessionDataBase {
@ -252,6 +262,10 @@ class HTTP_C final : public ServiceFramework<HTTP_C, SessionData> {
public: public:
HTTP_C(); HTTP_C();
const ClCertAData& GetClCertA() const {
return ClCertA;
}
private: private:
/** /**
* HTTP_C::Initialize service function * HTTP_C::Initialize service function
@ -288,6 +302,15 @@ private:
*/ */
void CloseContext(Kernel::HLERequestContext& ctx); void CloseContext(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::CancelConnection service function
* Inputs:
* 1 : Context handle
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void CancelConnection(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::GetDownloadSizeState service function * HTTP_C::GetDownloadSizeState service function
* Inputs: * Inputs:
@ -328,6 +351,15 @@ private:
*/ */
void BeginRequestAsync(Kernel::HLERequestContext& ctx); void BeginRequestAsync(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::SetProxyDefault service function
* Inputs:
* 1 : Context handle
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void SetProxyDefault(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::ReceiveData service function * HTTP_C::ReceiveData service function
* Inputs: * Inputs:
@ -389,6 +421,33 @@ private:
*/ */
void AddPostDataAscii(Kernel::HLERequestContext& ctx); void AddPostDataAscii(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::AddPostDataRaw service function
* Inputs:
* 1 : Context handle
* 2 : Post data length
* 3-4: (Mapped buffer) Post data
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-3: (Mapped buffer) Post data
*/
void AddPostDataRaw(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::GetResponseHeader service function
* Inputs:
* 1 : Context handle
* 2 : Header name length
* 3 : Return value length
* 4-5 : (Static buffer) Header name
* 6-7 : (Mapped buffer) Header value
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2 : Header value copied size
* 3-4: (Mapped buffer) Header value
*/
void GetResponseHeader(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::GetResponseStatusCode service function * HTTP_C::GetResponseStatusCode service function
* Inputs: * Inputs:
@ -410,12 +469,44 @@ private:
*/ */
void GetResponseStatusCodeTimeout(Kernel::HLERequestContext& ctx); void GetResponseStatusCodeTimeout(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::AddTrustedRootCA service function
* Inputs:
* 1 : Context handle
* 2 : CA data length
* 3-4: (Mapped buffer) CA data
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
* 2-3: (Mapped buffer) CA data
*/
void AddTrustedRootCA(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::AddDefaultCert service function
* Inputs:
* 1 : Context handle
* 2 : Cert ID
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void AddDefaultCert(Kernel::HLERequestContext& ctx);
/** /**
* GetResponseStatusCodeImpl: * GetResponseStatusCodeImpl:
* Implements GetResponseStatusCode and GetResponseStatusCodeTimeout service functions * Implements GetResponseStatusCode and GetResponseStatusCodeTimeout service functions
*/ */
void GetResponseStatusCodeImpl(Kernel::HLERequestContext& ctx, bool timeout); void GetResponseStatusCodeImpl(Kernel::HLERequestContext& ctx, bool timeout);
/**
* HTTP_C::SetDefaultClientCert service function
* Inputs:
* 1 : Context handle
* 2 : Client cert ID
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void SetDefaultClientCert(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::SetClientCertContext service function * HTTP_C::SetClientCertContext service function
* Inputs: * Inputs:
@ -437,6 +528,16 @@ private:
*/ */
void GetSSLError(Kernel::HLERequestContext& ctx); void GetSSLError(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::SetSSLOpt service function
* Inputs:
* 1 : Context handle
* 2 : SSL Option
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void SetSSLOpt(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::OpenClientCertContext service function * HTTP_C::OpenClientCertContext service function
* Inputs: * Inputs:
@ -470,6 +571,16 @@ private:
*/ */
void CloseClientCertContext(Kernel::HLERequestContext& ctx); void CloseClientCertContext(Kernel::HLERequestContext& ctx);
/**
* HTTP_C::SetKeepAlive service function
* Inputs:
* 1 : Context handle
* 2 : Keep Alive Option
* Outputs:
* 1 : Result of function, 0 on success, otherwise error code
*/
void SetKeepAlive(Kernel::HLERequestContext& ctx);
/** /**
* HTTP_C::Finalize service function * HTTP_C::Finalize service function
* Outputs: * Outputs:
@ -499,14 +610,17 @@ private:
/// Global list of HTTP contexts currently opened. /// Global list of HTTP contexts currently opened.
std::unordered_map<Context::Handle, Context> contexts; std::unordered_map<Context::Handle, Context> contexts;
// Get context from its handle
inline Context& GetContext(const Context::Handle& handle) {
auto it = contexts.find(handle);
ASSERT(it != contexts.end());
return it->second;
}
/// Global list of ClientCert contexts currently opened. /// Global list of ClientCert contexts currently opened.
std::unordered_map<ClientCertContext::Handle, std::shared_ptr<ClientCertContext>> client_certs; std::unordered_map<ClientCertContext::Handle, std::shared_ptr<ClientCertContext>> client_certs;
struct { ClCertAData ClCertA;
std::vector<u8> certificate;
std::vector<u8> private_key;
bool init = false;
} ClCertA;
private: private:
template <class Archive> template <class Archive>
@ -527,6 +641,8 @@ private:
friend class boost::serialization::access; friend class boost::serialization::access;
}; };
std::shared_ptr<HTTP_C> GetService(Core::System& system);
void InstallInterfaces(Core::System& system); void InstallInterfaces(Core::System& system);
} // namespace Service::HTTP } // namespace Service::HTTP

View File

@ -1093,59 +1093,89 @@ void SOC_U::RecvFromOther(Kernel::HLERequestContext& ctx) {
#endif // _WIN32 #endif // _WIN32
u32 addr_len = rp.Pop<u32>(); u32 addr_len = rp.Pop<u32>();
rp.PopPID(); rp.PopPID();
auto& buffer = rp.PopMappedBuffer();
CTRSockAddr ctr_src_addr; bool needs_parallel = GetSocketBlocking(fd_info->second) && !dont_wait;
std::vector<u8> output_buff(len); struct ParallelData {
std::vector<u8> addr_buff(addr_len); SOC_U* own{};
Kernel::MappedBuffer buffer;
s32 ret{};
u32 len{};
u32 flags{};
u32 addr_len{};
std::vector<u8> output_buff;
std::vector<u8> addr_buff;
SocketHolder& fd_info;
#ifdef _WIN32
bool dont_wait;
#endif
bool was_blocking;
int recv_error;
ParallelData(const Kernel::MappedBuffer& buf, SocketHolder& fd)
: buffer(buf), fd_info(fd) {}
};
auto parallel_data = std::make_shared<ParallelData>(rp.PopMappedBuffer(), fd_info->second);
parallel_data->own = this;
parallel_data->ret = -1;
parallel_data->len = len;
parallel_data->flags = flags;
parallel_data->addr_len = addr_len;
parallel_data->output_buff.resize(len);
parallel_data->addr_buff.resize(addr_len);
parallel_data->was_blocking = was_blocking;
#ifdef _WIN32
parallel_data->dont_wait = dont_wait;
#endif
ctx.RunAsync(
[parallel_data](Kernel::HLERequestContext& ctx) {
sockaddr src_addr; sockaddr src_addr;
socklen_t src_addr_len = sizeof(src_addr); socklen_t src_addr_len = sizeof(src_addr);
CTRSockAddr ctr_src_addr;
s32 ret = -1; if (parallel_data->addr_len > 0) {
if (GetSocketBlocking(fd_info->second) && !dont_wait) { parallel_data->ret = static_cast<s32>(
PreTimerAdjust(); ::recvfrom(parallel_data->fd_info.socket_fd,
} reinterpret_cast<char*>(parallel_data->output_buff.data()),
parallel_data->len, parallel_data->flags, &src_addr, &src_addr_len));
if (addr_len > 0) { if (parallel_data->ret >= 0 && src_addr_len > 0) {
ret = static_cast<s32>(::recvfrom(fd_info->second.socket_fd,
reinterpret_cast<char*>(output_buff.data()), len, flags,
&src_addr, &src_addr_len));
if (ret >= 0 && src_addr_len > 0) {
ctr_src_addr = CTRSockAddr::FromPlatform(src_addr); ctr_src_addr = CTRSockAddr::FromPlatform(src_addr);
std::memcpy(addr_buff.data(), &ctr_src_addr, addr_len); std::memcpy(parallel_data->addr_buff.data(), &ctr_src_addr,
parallel_data->addr_len);
} }
} else { } else {
ret = static_cast<s32>(::recvfrom(fd_info->second.socket_fd, parallel_data->ret = static_cast<s32>(
reinterpret_cast<char*>(output_buff.data()), len, flags, ::recvfrom(parallel_data->fd_info.socket_fd,
NULL, 0)); reinterpret_cast<char*>(parallel_data->output_buff.data()),
addr_buff.resize(0); parallel_data->len, parallel_data->flags, NULL, 0));
parallel_data->addr_buff.resize(0);
} }
int recv_error = (ret == SOCKET_ERROR_VALUE) ? GET_ERRNO : 0; parallel_data->recv_error = (parallel_data->ret == SOCKET_ERROR_VALUE) ? GET_ERRNO : 0;
if (GetSocketBlocking(fd_info->second) && !dont_wait) { return 0;
PostTimerAdjust(ctx, "RecvFromOther"); },
[parallel_data](Kernel::HLERequestContext& ctx) {
if (parallel_data->ret == SOCKET_ERROR_VALUE) {
parallel_data->ret = TranslateError(parallel_data->recv_error);
} else {
parallel_data->buffer.Write(parallel_data->output_buff.data(), 0,
parallel_data->ret);
} }
#ifdef _WIN32 #ifdef _WIN32
if (dont_wait && was_blocking) { if (parallel_data->dont_wait && parallel_data->was_blocking) {
SetSocketBlocking(fd_info->second, true); parallel_data->own->SetSocketBlocking(parallel_data->fd_info, true);
} }
#endif #endif
if (ret == SOCKET_ERROR_VALUE) {
ret = TranslateError(recv_error);
} else {
buffer.Write(output_buff.data(), 0, ret);
}
IPC::RequestBuilder rb = rp.MakeBuilder(2, 4); IPC::RequestBuilder rb(ctx, 0x07, 2, 4);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.Push(ret); rb.Push(parallel_data->ret);
rb.PushStaticBuffer(std::move(addr_buff), 0); rb.PushStaticBuffer(std::move(parallel_data->addr_buff), 0);
rb.PushMappedBuffer(buffer); rb.PushMappedBuffer(parallel_data->buffer);
},
needs_parallel);
} }
void SOC_U::RecvFrom(Kernel::HLERequestContext& ctx) { void SOC_U::RecvFrom(Kernel::HLERequestContext& ctx) {
// TODO(Subv): Calling this function on a blocking socket will block the emu thread,
// preventing graceful shutdown when closing the emulator, this can be fixed by always
// performing nonblocking operations and spinlock until the data is available
IPC::RequestParser rp(ctx); IPC::RequestParser rp(ctx);
u32 socket_handle = rp.Pop<u32>(); u32 socket_handle = rp.Pop<u32>();
auto fd_info = open_sockets.find(socket_handle); auto fd_info = open_sockets.find(socket_handle);
@ -1172,55 +1202,86 @@ void SOC_U::RecvFrom(Kernel::HLERequestContext& ctx) {
u32 addr_len = rp.Pop<u32>(); u32 addr_len = rp.Pop<u32>();
rp.PopPID(); rp.PopPID();
CTRSockAddr ctr_src_addr; bool needs_parallel = GetSocketBlocking(fd_info->second) && !dont_wait;
std::vector<u8> output_buff(len); struct ParallelData {
std::vector<u8> addr_buff(addr_len); SOC_U* own;
s32 ret{};
u32 len{};
u32 flags{};
u32 addr_len{};
std::vector<u8> output_buff;
std::vector<u8> addr_buff;
SocketHolder& fd_info;
#ifdef _WIN32
bool dont_wait;
#endif
bool was_blocking;
int recv_error;
ParallelData(SocketHolder& fd) : fd_info(fd) {}
};
auto parallel_data = std::make_shared<ParallelData>(fd_info->second);
parallel_data->own = this;
parallel_data->ret = -1;
parallel_data->len = len;
parallel_data->flags = flags;
parallel_data->addr_len = addr_len;
parallel_data->output_buff.resize(len);
parallel_data->addr_buff.resize(addr_len);
parallel_data->was_blocking = was_blocking;
#ifdef _WIN32
parallel_data->dont_wait = dont_wait;
#endif
ctx.RunAsync(
[parallel_data](Kernel::HLERequestContext& ctx) {
sockaddr src_addr; sockaddr src_addr;
socklen_t src_addr_len = sizeof(src_addr); socklen_t src_addr_len = sizeof(src_addr);
CTRSockAddr ctr_src_addr;
s32 ret = -1; if (parallel_data->addr_len > 0) {
if (GetSocketBlocking(fd_info->second) && !dont_wait) {
PreTimerAdjust();
}
if (addr_len > 0) {
// Only get src adr if input adr available // Only get src adr if input adr available
ret = static_cast<s32>(::recvfrom(fd_info->second.socket_fd, parallel_data->ret = static_cast<s32>(
reinterpret_cast<char*>(output_buff.data()), len, flags, ::recvfrom(parallel_data->fd_info.socket_fd,
&src_addr, &src_addr_len)); reinterpret_cast<char*>(parallel_data->output_buff.data()),
if (ret >= 0 && src_addr_len > 0) { parallel_data->len, parallel_data->flags, &src_addr, &src_addr_len));
if (parallel_data->ret >= 0 && src_addr_len > 0) {
ctr_src_addr = CTRSockAddr::FromPlatform(src_addr); ctr_src_addr = CTRSockAddr::FromPlatform(src_addr);
std::memcpy(addr_buff.data(), &ctr_src_addr, addr_len); std::memcpy(parallel_data->addr_buff.data(), &ctr_src_addr,
parallel_data->addr_len);
} }
} else { } else {
ret = static_cast<s32>(::recvfrom(fd_info->second.socket_fd, parallel_data->ret = static_cast<s32>(
reinterpret_cast<char*>(output_buff.data()), len, flags, ::recvfrom(parallel_data->fd_info.socket_fd,
NULL, 0)); reinterpret_cast<char*>(parallel_data->output_buff.data()),
addr_buff.resize(0); parallel_data->len, parallel_data->flags, NULL, 0));
} parallel_data->addr_buff.resize(0);
int recv_error = (ret == SOCKET_ERROR_VALUE) ? GET_ERRNO : 0;
if (GetSocketBlocking(fd_info->second) && !dont_wait) {
PostTimerAdjust(ctx, "RecvFrom");
} }
parallel_data->recv_error = (parallel_data->ret == SOCKET_ERROR_VALUE) ? GET_ERRNO : 0;
return 0;
},
[parallel_data](Kernel::HLERequestContext& ctx) {
#ifdef _WIN32 #ifdef _WIN32
if (dont_wait && was_blocking) { if (parallel_data->dont_wait && parallel_data->was_blocking) {
SetSocketBlocking(fd_info->second, true); parallel_data->own->SetSocketBlocking(parallel_data->fd_info, true);
} }
#endif #endif
s32 total_received = ret; s32 total_received = parallel_data->ret;
if (ret == SOCKET_ERROR_VALUE) { if (parallel_data->ret == SOCKET_ERROR_VALUE) {
ret = TranslateError(recv_error); parallel_data->ret = TranslateError(parallel_data->recv_error);
total_received = 0; total_received = 0;
} }
// Write only the data we received to avoid overwriting parts of the buffer with zeros // Write only the data we received to avoid overwriting parts of the buffer with zeros
output_buff.resize(total_received); parallel_data->output_buff.resize(total_received);
IPC::RequestBuilder rb = rp.MakeBuilder(3, 4); IPC::RequestBuilder rb(ctx, 0x08, 3, 4);
rb.Push(RESULT_SUCCESS); rb.Push(RESULT_SUCCESS);
rb.Push(ret); rb.Push(parallel_data->ret);
rb.Push(total_received); rb.Push(total_received);
rb.PushStaticBuffer(std::move(output_buff), 0); rb.PushStaticBuffer(std::move(parallel_data->output_buff), 0);
rb.PushStaticBuffer(std::move(addr_buff), 1); rb.PushStaticBuffer(std::move(parallel_data->addr_buff), 1);
},
needs_parallel);
} }
void SOC_U::Poll(Kernel::HLERequestContext& ctx) { void SOC_U::Poll(Kernel::HLERequestContext& ctx) {

View File

@ -282,7 +282,7 @@ ResultStatus AppLoader_THREEDSX::Load(std::shared_ptr<Kernel::Process>& process)
// On real HW this is done with FS:Reg, but we can be lazy // On real HW this is done with FS:Reg, but we can be lazy
auto fs_user = auto fs_user =
Core::System::GetInstance().ServiceManager().GetService<Service::FS::FS_USER>("fs:USER"); Core::System::GetInstance().ServiceManager().GetService<Service::FS::FS_USER>("fs:USER");
fs_user->Register(process->GetObjectId(), process->codeset->program_id, filepath); fs_user->RegisterProgramInfo(process->GetObjectId(), process->codeset->program_id, filepath);
process->Run(48, Kernel::DEFAULT_STACK_SIZE); process->Run(48, Kernel::DEFAULT_STACK_SIZE);

View File

@ -174,7 +174,15 @@ ResultStatus AppLoader_NCCH::LoadExec(std::shared_ptr<Kernel::Process>& process)
auto fs_user = auto fs_user =
Core::System::GetInstance().ServiceManager().GetService<Service::FS::FS_USER>( Core::System::GetInstance().ServiceManager().GetService<Service::FS::FS_USER>(
"fs:USER"); "fs:USER");
fs_user->Register(process->process_id, process->codeset->program_id, filepath); fs_user->RegisterProgramInfo(process->process_id, process->codeset->program_id, filepath);
Service::FS::FS_USER::ProductInfo product_info{};
memcpy(product_info.product_code.data(), overlay_ncch->ncch_header.product_code,
product_info.product_code.size());
std::memcpy(&product_info.remaster_version,
overlay_ncch->exheader_header.codeset_info.flags.remaster_version, 2);
product_info.maker_code = overlay_ncch->ncch_header.maker_code;
fs_user->RegisterProductInfo(process->process_id, product_info);
process->Run(priority, stack_size); process->Run(priority, stack_size);
return ResultStatus::Success; return ResultStatus::Success;

View File

@ -14,6 +14,8 @@ add_library(network STATIC
room_member.h room_member.h
verify_user.cpp verify_user.cpp
verify_user.h verify_user.h
network_clients/nasc.h
network_clients/nasc.cpp
) )
create_target_directory_groups(network) create_target_directory_groups(network)
@ -22,7 +24,7 @@ if (ENABLE_WEB_SERVICE)
target_link_libraries(network PRIVATE web_service) target_link_libraries(network PRIVATE web_service)
endif() endif()
target_link_libraries(network PRIVATE citra_common enet Boost::serialization httplib) target_link_libraries(network PRIVATE citra_common enet Boost::serialization cryptopp httplib)
if (CITRA_USE_PRECOMPILED_HEADERS) if (CITRA_USE_PRECOMPILED_HEADERS)
target_precompile_headers(network PRIVATE precompiled_headers.h) target_precompile_headers(network PRIVATE precompiled_headers.h)

View File

@ -0,0 +1,228 @@
#include <memory>
#include <boost/algorithm/string/replace.hpp>
#include <cryptopp/base64.h>
#include <fmt/format.h>
#include "common/file_util.h"
#include "nasc.h"
namespace NetworkClient::NASC {
constexpr std::size_t TIMEOUT_SECONDS = 15;
void NASCClient::Initialize(const std::vector<u8>& cert, const std::vector<u8>& key) {
Clear();
const unsigned char* tmpCertPtr = cert.data();
const unsigned char* tmpKeyPtr = key.data();
client_cert = d2i_X509(nullptr, &tmpCertPtr, (long)cert.size());
client_priv_key = d2i_PrivateKey(EVP_PKEY_RSA, nullptr, &tmpKeyPtr, (long)key.size());
}
void NASCClient::SetParameterImpl(const std::string& key, const std::vector<u8>& value) {
using namespace CryptoPP;
using Name::EncodingLookupArray;
using Name::InsertLineBreaks;
using Name::Pad;
using Name::PaddingByte;
std::string out;
Base64Encoder encoder;
AlgorithmParameters params =
MakeParameters(EncodingLookupArray(), (const byte*)base64_dict.data())(
InsertLineBreaks(), false)(Pad(), true)(PaddingByte(), (byte)'*');
encoder.IsolatedInitialize(params);
encoder.Attach(new StringSink(out));
encoder.Put(value.data(), value.size());
encoder.MessageEnd();
parameters.emplace(key, out);
}
NASCClient::NASCResult NASCClient::Perform() {
std::unique_ptr<httplib::SSLClient> cli;
httplib::Request request;
NASCResult res;
if (client_cert == nullptr || client_priv_key == nullptr) {
res.log_message = "Missing or invalid client certificate or key.";
return res;
}
cli = std::make_unique<httplib::SSLClient>(nasc_url.c_str(), 443, client_cert, client_priv_key);
cli->set_connection_timeout(TIMEOUT_SECONDS);
cli->set_read_timeout(TIMEOUT_SECONDS);
cli->set_write_timeout(TIMEOUT_SECONDS);
cli->enable_server_certificate_verification(false);
if (!cli->is_valid()) {
res.log_message = fmt::format("Invalid URL \"{}\"", nasc_url);
return res;
}
std::string header_param;
std::string action;
GetParameter(parameters, "action", action);
if (GetParameter(parameters, "gameid", header_param)) {
request.set_header("X-GameId", header_param);
}
header_param.clear();
if (GetParameter(parameters, "fpdver", header_param)) {
request.set_header("User-Agent", fmt::format("CTR FPD/{}", header_param));
}
request.set_header("Content-Type", "application/x-www-form-urlencoded");
request.method = "POST";
request.path = "/ac";
request.body = httplib::detail::params_to_query_str(parameters);
boost::replace_all(request.body, "*", "%2A");
httplib::Result result = cli->send(request);
if (!result) {
res.log_message =
fmt::format("Request to \"{}\" returned error {}", nasc_url, (int)result.error());
return res;
}
httplib::Response response = result.value();
res.http_status = response.status;
if (response.status != 200) {
res.log_message =
fmt::format("Request to \"{}\" returned status {}", nasc_url, response.status);
return res;
}
auto content_type = response.headers.find("content-type");
if (content_type == response.headers.end() ||
content_type->second.find("text/plain") == content_type->second.npos) {
res.log_message = "Unknown response body from NASC server";
return res;
}
httplib::Params out_parameters;
httplib::detail::parse_query_text(response.body, out_parameters);
int nasc_result;
if (!GetParameter(out_parameters, "returncd", nasc_result)) {
res.log_message = "NASC response missing \"returncd\"";
return res;
}
res.result = static_cast<u8>(nasc_result);
if (nasc_result >= 100) {
res.log_message = fmt::format("NASC login failed with code 002-{:04d}", nasc_result);
return res;
}
if (action == "LOGIN") {
std::string locator;
if (!GetParameter(out_parameters, "locator", locator)) {
res.log_message = "NASC response missing \"locator\"";
return res;
}
auto delimiter = locator.find(":");
if (delimiter == locator.npos) {
res.log_message = "NASC response \"locator\" missing port delimiter";
return res;
}
res.server_address = locator.substr(0, delimiter);
std::string port_str = locator.substr(delimiter + 1);
try {
res.server_port = (u16)std::stoi(port_str);
} catch (std::exception) {
}
auto token = out_parameters.find("token");
if (token == out_parameters.end()) {
res.log_message = "NASC response missing \"locator\"";
return res;
}
res.auth_token = token->second;
} else if (action == "SVCLOC") {
auto token = out_parameters.find("servicetoken");
if (token == out_parameters.end()) {
res.log_message = "NASC response missing \"servicetoken\"";
return res;
}
res.service_token = token->second;
std::string status;
if (!GetParameter(out_parameters, "statusdata", status)) {
res.log_message = "NASC response missing \"statusdata\"";
return res;
}
res.service_status = status[0];
std::string svc_host;
if (!GetParameter(out_parameters, "svchost", svc_host)) {
res.log_message = "NASC response missing \"svchost\"";
return res;
}
res.service_host = svc_host;
}
long long server_time;
if (!GetParameter(out_parameters, "datetime", server_time)) {
res.log_message = "NASC response missing \"datetime\"";
return res;
}
res.time_stamp = server_time;
return res;
}
bool NASCClient::GetParameter(const httplib::Params& param, const std::string& key,
std::string& out) {
using namespace CryptoPP;
using Name::DecodingLookupArray;
using Name::Pad;
using Name::PaddingByte;
auto field = param.find(key);
if (field == param.end())
return false;
Base64Decoder decoder;
int lookup[256];
Base64Decoder::InitializeDecodingLookupArray(lookup, (const byte*)base64_dict.data(), 64,
false);
AlgorithmParameters params = MakeParameters(DecodingLookupArray(), (const int*)lookup);
decoder.IsolatedInitialize(params);
decoder.Attach(new StringSink(out));
decoder.Put(reinterpret_cast<const byte*>(field->second.data()), field->second.size());
decoder.MessageEnd();
return true;
}
bool NASCClient::GetParameter(const httplib::Params& param, const std::string& key, int& out) {
std::string out_str;
if (!GetParameter(param, key, out_str)) {
return false;
}
try {
out = std::stoi(out_str);
return true;
} catch (std::exception) {
return false;
}
}
bool NASCClient::GetParameter(const httplib::Params& param, const std::string& key,
long long& out) {
std::string out_str;
if (!GetParameter(param, key, out_str)) {
return false;
}
try {
out = std::stoll(out_str);
return true;
} catch (std::exception) {
return false;
}
}
} // namespace NetworkClient::NASC

View File

@ -0,0 +1,86 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <httplib.h>
#include "common/common_types.h"
#include "map"
#include "string"
#include "vector"
namespace NetworkClient::NASC {
class NASCClient {
public:
struct NASCResult {
u8 result = 0;
int http_status;
std::string log_message;
// LOGIN
std::string server_address;
u16 server_port;
std::string auth_token;
u64 time_stamp;
// SVCLOC
std::string service_token;
std::string service_host;
u8 service_status;
};
NASCClient(const std::string& url, const std::vector<u8>& cert, const std::vector<u8>& key)
: nasc_url(url) {
Initialize(cert, key);
}
~NASCClient() {
if (client_cert) {
X509_free(client_cert);
client_cert = nullptr;
}
if (client_priv_key) {
EVP_PKEY_free(client_priv_key);
client_priv_key = nullptr;
}
}
void Clear() {
parameters.clear();
}
void SetParameter(const std::string& key, int value) {
SetParameter(key, std::to_string(value));
}
void SetParameter(const std::string& key, const std::string& value) {
SetParameter(key, std::vector<u8>(value.cbegin(), value.cend()));
}
void SetParameter(const std::string& key, const std::vector<u8>& value) {
SetParameterImpl(key, value);
}
NASCResult Perform();
private:
const std::string base64_dict =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.-";
std::string nasc_url;
X509* client_cert = nullptr;
EVP_PKEY* client_priv_key = nullptr;
void Initialize(const std::vector<u8>& cert, const std::vector<u8>& key);
httplib::Params parameters;
void SetParameterImpl(const std::string& key, const std::vector<u8>& value);
bool GetParameter(const httplib::Params& param, const std::string& key, std::string& out);
bool GetParameter(const httplib::Params& param, const std::string& key, int& out);
bool GetParameter(const httplib::Params& param, const std::string& key, long long& out);
};
} // namespace NetworkClient::NASC