network: Add initial files and enet dependency

This commit is contained in:
FearlessTobi 2022-07-06 02:20:39 +02:00
parent 1bcde9dd98
commit dcfe0a5feb
15 changed files with 2898 additions and 0 deletions

3
.gitmodules vendored
View file

@ -1,3 +1,6 @@
[submodule "enet"]
path = externals/enet
url = https://github.com/lsalzman/enet.git
[submodule "inih"] [submodule "inih"]
path = externals/inih/inih path = externals/inih/inih
url = https://github.com/benhoyt/inih.git url = https://github.com/benhoyt/inih.git

View file

@ -73,6 +73,10 @@ if (YUZU_USE_EXTERNAL_SDL2)
add_library(SDL2 ALIAS SDL2-static) add_library(SDL2 ALIAS SDL2-static)
endif() endif()
# ENet
add_subdirectory(enet)
target_include_directories(enet INTERFACE ./enet/include)
# Cubeb # Cubeb
if(ENABLE_CUBEB) if(ENABLE_CUBEB)
set(BUILD_TESTS OFF CACHE BOOL "") set(BUILD_TESTS OFF CACHE BOOL "")

1
externals/enet vendored Submodule

@ -0,0 +1 @@
Subproject commit 39a72ab1990014eb399cee9d538fd529df99c6a0

View file

@ -156,6 +156,7 @@ add_subdirectory(common)
add_subdirectory(core) add_subdirectory(core)
add_subdirectory(audio_core) add_subdirectory(audio_core)
add_subdirectory(video_core) add_subdirectory(video_core)
add_subdirectory(network)
add_subdirectory(input_common) add_subdirectory(input_common)
add_subdirectory(shader_recompiler) add_subdirectory(shader_recompiler)

View file

@ -0,0 +1,16 @@
add_library(network STATIC
network.cpp
network.h
packet.cpp
packet.h
room.cpp
room.h
room_member.cpp
room_member.h
verify_user.cpp
verify_user.h
)
create_target_directory_groups(network)
target_link_libraries(network PRIVATE common enet Boost::boost)

50
src/network/network.cpp Normal file
View file

@ -0,0 +1,50 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "common/assert.h"
#include "common/logging/log.h"
#include "enet/enet.h"
#include "network/network.h"
namespace Network {
static std::shared_ptr<RoomMember> g_room_member; ///< RoomMember (Client) for network games
static std::shared_ptr<Room> g_room; ///< Room (Server) for network games
// TODO(B3N30): Put these globals into a networking class
bool Init() {
if (enet_initialize() != 0) {
LOG_ERROR(Network, "Error initalizing ENet");
return false;
}
g_room = std::make_shared<Room>();
g_room_member = std::make_shared<RoomMember>();
LOG_DEBUG(Network, "initialized OK");
return true;
}
std::weak_ptr<Room> GetRoom() {
return g_room;
}
std::weak_ptr<RoomMember> GetRoomMember() {
return g_room_member;
}
void Shutdown() {
if (g_room_member) {
if (g_room_member->IsConnected())
g_room_member->Leave();
g_room_member.reset();
}
if (g_room) {
if (g_room->GetState() == Room::State::Open)
g_room->Destroy();
g_room.reset();
}
enet_deinitialize();
LOG_DEBUG(Network, "shutdown OK");
}
} // namespace Network

25
src/network/network.h Normal file
View file

@ -0,0 +1,25 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <memory>
#include "network/room.h"
#include "network/room_member.h"
namespace Network {
/// Initializes and registers the network device, the room, and the room member.
bool Init();
/// Returns a pointer to the room handle
std::weak_ptr<Room> GetRoom();
/// Returns a pointer to the room member handle
std::weak_ptr<RoomMember> GetRoomMember();
/// Unregisters the network device, the room, and the room member and shut them down.
void Shutdown();
} // namespace Network

263
src/network/packet.cpp Normal file
View file

@ -0,0 +1,263 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include "network/packet.h"
namespace Network {
#ifndef htonll
u64 htonll(u64 x) {
return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32));
}
#endif
#ifndef ntohll
u64 ntohll(u64 x) {
return ((1 == ntohl(1)) ? (x) : ((uint64_t)ntohl((x)&0xFFFFFFFF) << 32) | ntohl((x) >> 32));
}
#endif
void Packet::Append(const void* in_data, std::size_t size_in_bytes) {
if (in_data && (size_in_bytes > 0)) {
std::size_t start = data.size();
data.resize(start + size_in_bytes);
std::memcpy(&data[start], in_data, size_in_bytes);
}
}
void Packet::Read(void* out_data, std::size_t size_in_bytes) {
if (out_data && CheckSize(size_in_bytes)) {
std::memcpy(out_data, &data[read_pos], size_in_bytes);
read_pos += size_in_bytes;
}
}
void Packet::Clear() {
data.clear();
read_pos = 0;
is_valid = true;
}
const void* Packet::GetData() const {
return !data.empty() ? &data[0] : nullptr;
}
void Packet::IgnoreBytes(u32 length) {
read_pos += length;
}
std::size_t Packet::GetDataSize() const {
return data.size();
}
bool Packet::EndOfPacket() const {
return read_pos >= data.size();
}
Packet::operator bool() const {
return is_valid;
}
Packet& Packet::operator>>(bool& out_data) {
u8 value;
if (*this >> value) {
out_data = (value != 0);
}
return *this;
}
Packet& Packet::operator>>(s8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(u8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(s16& out_data) {
s16 value;
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::operator>>(u16& out_data) {
u16 value;
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::operator>>(s32& out_data) {
s32 value;
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::operator>>(u32& out_data) {
u32 value;
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::operator>>(s64& out_data) {
s64 value;
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::operator>>(u64& out_data) {
u64 value;
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::operator>>(float& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(double& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::operator>>(char* out_data) {
// First extract string length
u32 length = 0;
*this >> length;
if ((length > 0) && CheckSize(length)) {
// Then extract characters
std::memcpy(out_data, &data[read_pos], length);
out_data[length] = '\0';
// Update reading position
read_pos += length;
}
return *this;
}
Packet& Packet::operator>>(std::string& out_data) {
// First extract string length
u32 length = 0;
*this >> length;
out_data.clear();
if ((length > 0) && CheckSize(length)) {
// Then extract characters
out_data.assign(&data[read_pos], length);
// Update reading position
read_pos += length;
}
return *this;
}
Packet& Packet::operator<<(bool in_data) {
*this << static_cast<u8>(in_data);
return *this;
}
Packet& Packet::operator<<(s8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(u8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(s16 in_data) {
s16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u16 in_data) {
u16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(s32 in_data) {
s32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u32 in_data) {
u32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(s64 in_data) {
s64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(u64 in_data) {
u64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::operator<<(float in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(double in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::operator<<(const char* in_data) {
// First insert string length
u32 length = static_cast<u32>(std::strlen(in_data));
*this << length;
// Then insert characters
Append(in_data, length * sizeof(char));
return *this;
}
Packet& Packet::operator<<(const std::string& in_data) {
// First insert string length
u32 length = static_cast<u32>(in_data.size());
*this << length;
// Then insert characters
if (length > 0)
Append(in_data.c_str(), length * sizeof(std::string::value_type));
return *this;
}
bool Packet::CheckSize(std::size_t size) {
is_valid = is_valid && (read_pos + size <= data.size());
return is_valid;
}
} // namespace Network

166
src/network/packet.h Normal file
View file

@ -0,0 +1,166 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <vector>
#include "common/common_types.h"
namespace Network {
/// A class that serializes data for network transfer. It also handles endianess
class Packet {
public:
Packet() = default;
~Packet() = default;
/**
* Append data to the end of the packet
* @param data Pointer to the sequence of bytes to append
* @param size_in_bytes Number of bytes to append
*/
void Append(const void* data, std::size_t size_in_bytes);
/**
* Reads data from the current read position of the packet
* @param out_data Pointer where the data should get written to
* @param size_in_bytes Number of bytes to read
*/
void Read(void* out_data, std::size_t size_in_bytes);
/**
* Clear the packet
* After calling Clear, the packet is empty.
*/
void Clear();
/**
* Ignores bytes while reading
* @param length THe number of bytes to ignore
*/
void IgnoreBytes(u32 length);
/**
* Get a pointer to the data contained in the packet
* @return Pointer to the data
*/
const void* GetData() const;
/**
* This function returns the number of bytes pointed to by
* what getData returns.
* @return Data size, in bytes
*/
std::size_t GetDataSize() const;
/**
* This function is useful to know if there is some data
* left to be read, without actually reading it.
* @return True if all data was read, false otherwise
*/
bool EndOfPacket() const;
explicit operator bool() const;
/// Overloads of operator >> to read data from the packet
Packet& operator>>(bool& out_data);
Packet& operator>>(s8& out_data);
Packet& operator>>(u8& out_data);
Packet& operator>>(s16& out_data);
Packet& operator>>(u16& out_data);
Packet& operator>>(s32& out_data);
Packet& operator>>(u32& out_data);
Packet& operator>>(s64& out_data);
Packet& operator>>(u64& out_data);
Packet& operator>>(float& out_data);
Packet& operator>>(double& out_data);
Packet& operator>>(char* out_data);
Packet& operator>>(std::string& out_data);
template <typename T>
Packet& operator>>(std::vector<T>& out_data);
template <typename T, std::size_t S>
Packet& operator>>(std::array<T, S>& out_data);
/// Overloads of operator << to write data into the packet
Packet& operator<<(bool in_data);
Packet& operator<<(s8 in_data);
Packet& operator<<(u8 in_data);
Packet& operator<<(s16 in_data);
Packet& operator<<(u16 in_data);
Packet& operator<<(s32 in_data);
Packet& operator<<(u32 in_data);
Packet& operator<<(s64 in_data);
Packet& operator<<(u64 in_data);
Packet& operator<<(float in_data);
Packet& operator<<(double in_data);
Packet& operator<<(const char* in_data);
Packet& operator<<(const std::string& in_data);
template <typename T>
Packet& operator<<(const std::vector<T>& in_data);
template <typename T, std::size_t S>
Packet& operator<<(const std::array<T, S>& data);
private:
/**
* Check if the packet can extract a given number of bytes
* This function updates accordingly the state of the packet.
* @param size Size to check
* @return True if size bytes can be read from the packet
*/
bool CheckSize(std::size_t size);
// Member data
std::vector<char> data; ///< Data stored in the packet
std::size_t read_pos = 0; ///< Current reading position in the packet
bool is_valid = true; ///< Reading state of the packet
};
template <typename T>
Packet& Packet::operator>>(std::vector<T>& out_data) {
// First extract the size
u32 size = 0;
*this >> size;
out_data.resize(size);
// Then extract the data
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
*this >> character;
out_data[i] = character;
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::operator>>(std::array<T, S>& out_data) {
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
*this >> character;
out_data[i] = character;
}
return *this;
}
template <typename T>
Packet& Packet::operator<<(const std::vector<T>& in_data) {
// First insert the size
*this << static_cast<u32>(in_data.size());
// Then insert the data
for (std::size_t i = 0; i < in_data.size(); ++i) {
*this << in_data[i];
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::operator<<(const std::array<T, S>& in_data) {
for (std::size_t i = 0; i < in_data.size(); ++i) {
*this << in_data[i];
}
return *this;
}
} // namespace Network

1111
src/network/room.cpp Normal file

File diff suppressed because it is too large Load diff

173
src/network/room.h Normal file
View file

@ -0,0 +1,173 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <array>
#include <memory>
#include <string>
#include <vector>
#include "common/common_types.h"
#include "network/verify_user.h"
namespace Network {
constexpr u32 network_version = 4; ///< The version of this Room and RoomMember
constexpr u16 DefaultRoomPort = 24872;
constexpr u32 MaxMessageSize = 500;
/// Maximum number of concurrent connections allowed to this room.
static constexpr u32 MaxConcurrentConnections = 254;
constexpr std::size_t NumChannels = 1; // Number of channels used for the connection
struct RoomInformation {
std::string name; ///< Name of the server
std::string description; ///< Server description
u32 member_slots; ///< Maximum number of members in this room
u16 port; ///< The port of this room
std::string preferred_game; ///< Game to advertise that you want to play
u64 preferred_game_id; ///< Title ID for the advertised game
std::string host_username; ///< Forum username of the host
bool enable_citra_mods; ///< Allow Citra Moderators to moderate on this room
};
struct GameInfo {
std::string name{""};
u64 id{0};
};
using MacAddress = std::array<u8, 6>;
/// A special MAC address that tells the room we're joining to assign us a MAC address
/// automatically.
constexpr MacAddress NoPreferredMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// 802.11 broadcast MAC address
constexpr MacAddress BroadcastMac = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};
// The different types of messages that can be sent. The first byte of each packet defines the type
enum RoomMessageTypes : u8 {
IdJoinRequest = 1,
IdJoinSuccess,
IdRoomInformation,
IdSetGameInfo,
IdWifiPacket,
IdChatMessage,
IdNameCollision,
IdMacCollision,
IdVersionMismatch,
IdWrongPassword,
IdCloseRoom,
IdRoomIsFull,
IdConsoleIdCollision,
IdStatusMessage,
IdHostKicked,
IdHostBanned,
/// Moderation requests
IdModKick,
IdModBan,
IdModUnban,
IdModGetBanList,
// Moderation responses
IdModBanListResponse,
IdModPermissionDenied,
IdModNoSuchUser,
IdJoinSuccessAsMod,
};
/// Types of system status messages
enum StatusMessageTypes : u8 {
IdMemberJoin = 1, ///< Member joining
IdMemberLeave, ///< Member leaving
IdMemberKicked, ///< A member is kicked from the room
IdMemberBanned, ///< A member is banned from the room
IdAddressUnbanned, ///< A username / ip address is unbanned from the room
};
/// This is what a server [person creating a server] would use.
class Room final {
public:
enum class State : u8 {
Open, ///< The room is open and ready to accept connections.
Closed, ///< The room is not opened and can not accept connections.
};
struct Member {
std::string nickname; ///< The nickname of the member.
std::string username; ///< The web services username of the member. Can be empty.
std::string display_name; ///< The web services display name of the member. Can be empty.
std::string avatar_url; ///< Url to the member's avatar. Can be empty.
GameInfo game_info; ///< The current game of the member
MacAddress mac_address; ///< The assigned mac address of the member.
};
Room();
~Room();
/**
* Gets the current state of the room.
*/
State GetState() const;
/**
* Gets the room information of the room.
*/
const RoomInformation& GetRoomInformation() const;
/**
* Gets the verify UID of this room.
*/
std::string GetVerifyUID() const;
/**
* Gets a list of the mbmers connected to the room.
*/
std::vector<Member> GetRoomMemberList() const;
/**
* Checks if the room is password protected
*/
bool HasPassword() const;
using UsernameBanList = std::vector<std::string>;
using IPBanList = std::vector<std::string>;
using BanList = std::pair<UsernameBanList, IPBanList>;
/**
* Creates the socket for this room. Will bind to default address if
* server is empty string.
*/
bool Create(const std::string& name, const std::string& description = "",
const std::string& server = "", u16 server_port = DefaultRoomPort,
const std::string& password = "",
const u32 max_connections = MaxConcurrentConnections,
const std::string& host_username = "", const std::string& preferred_game = "",
u64 preferred_game_id = 0,
std::unique_ptr<VerifyUser::Backend> verify_backend = nullptr,
const BanList& ban_list = {}, bool enable_citra_mods = false);
/**
* Sets the verification GUID of the room.
*/
void SetVerifyUID(const std::string& uid);
/**
* Gets the ban list (including banned forum usernames and IPs) of the room.
*/
BanList GetBanList() const;
/**
* Destroys the socket
*/
void Destroy();
private:
class RoomImpl;
std::unique_ptr<RoomImpl> room_impl;
};
} // namespace Network

694
src/network/room_member.cpp Normal file
View file

@ -0,0 +1,694 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include <atomic>
#include <list>
#include <mutex>
#include <set>
#include <thread>
#include "common/assert.h"
#include "enet/enet.h"
#include "network/packet.h"
#include "network/room_member.h"
namespace Network {
constexpr u32 ConnectionTimeoutMs = 5000;
class RoomMember::RoomMemberImpl {
public:
ENetHost* client = nullptr; ///< ENet network interface.
ENetPeer* server = nullptr; ///< The server peer the client is connected to
/// Information about the clients connected to the same room as us.
MemberList member_information;
/// Information about the room we're connected to.
RoomInformation room_information;
/// The current game name, id and version
GameInfo current_game_info;
std::atomic<State> state{State::Idle}; ///< Current state of the RoomMember.
void SetState(const State new_state);
void SetError(const Error new_error);
bool IsConnected() const;
std::string nickname; ///< The nickname of this member.
std::string username; ///< The username of this member.
mutable std::mutex username_mutex; ///< Mutex for locking username.
MacAddress mac_address; ///< The mac_address of this member.
std::mutex network_mutex; ///< Mutex that controls access to the `client` variable.
/// Thread that receives and dispatches network packets
std::unique_ptr<std::thread> loop_thread;
std::mutex send_list_mutex; ///< Mutex that controls access to the `send_list` variable.
std::list<Packet> send_list; ///< A list that stores all packets to send the async
template <typename T>
using CallbackSet = std::set<CallbackHandle<T>>;
std::mutex callback_mutex; ///< The mutex used for handling callbacks
class Callbacks {
public:
template <typename T>
CallbackSet<T>& Get();
private:
CallbackSet<WifiPacket> callback_set_wifi_packet;
CallbackSet<ChatEntry> callback_set_chat_messages;
CallbackSet<StatusMessageEntry> callback_set_status_messages;
CallbackSet<RoomInformation> callback_set_room_information;
CallbackSet<State> callback_set_state;
CallbackSet<Error> callback_set_error;
CallbackSet<Room::BanList> callback_set_ban_list;
};
Callbacks callbacks; ///< All CallbackSets to all events
void MemberLoop();
void StartLoop();
/**
* Sends data to the room. It will be send on channel 0 with flag RELIABLE
* @param packet The data to send
*/
void Send(Packet&& packet);
/**
* Sends a request to the server, asking for permission to join a room with the specified
* nickname and preferred mac.
* @params nickname The desired nickname.
* @params console_id_hash A hash of the Console ID.
* @params preferred_mac The preferred MAC address to use in the room, the NoPreferredMac tells
* @params password The password for the room
* the server to assign one for us.
*/
void SendJoinRequest(const std::string& nickname, const std::string& console_id_hash,
const MacAddress& preferred_mac = NoPreferredMac,
const std::string& password = "", const std::string& token = "");
/**
* Extracts a MAC Address from a received ENet packet.
* @param event The ENet event that was received.
*/
void HandleJoinPacket(const ENetEvent* event);
/**
* Extracts RoomInformation and MemberInformation from a received ENet packet.
* @param event The ENet event that was received.
*/
void HandleRoomInformationPacket(const ENetEvent* event);
/**
* Extracts a WifiPacket from a received ENet packet.
* @param event The ENet event that was received.
*/
void HandleWifiPackets(const ENetEvent* event);
/**
* Extracts a chat entry from a received ENet packet and adds it to the chat queue.
* @param event The ENet event that was received.
*/
void HandleChatPacket(const ENetEvent* event);
/**
* Extracts a system message entry from a received ENet packet and adds it to the system message
* queue.
* @param event The ENet event that was received.
*/
void HandleStatusMessagePacket(const ENetEvent* event);
/**
* Extracts a ban list request response from a received ENet packet.
* @param event The ENet event that was received.
*/
void HandleModBanListResponsePacket(const ENetEvent* event);
/**
* Disconnects the RoomMember from the Room
*/
void Disconnect();
template <typename T>
void Invoke(const T& data);
template <typename T>
CallbackHandle<T> Bind(std::function<void(const T&)> callback);
};
// RoomMemberImpl
void RoomMember::RoomMemberImpl::SetState(const State new_state) {
if (state != new_state) {
state = new_state;
Invoke<State>(state);
}
}
void RoomMember::RoomMemberImpl::SetError(const Error new_error) {
Invoke<Error>(new_error);
}
bool RoomMember::RoomMemberImpl::IsConnected() const {
return state == State::Joining || state == State::Joined || state == State::Moderator;
}
void RoomMember::RoomMemberImpl::MemberLoop() {
// Receive packets while the connection is open
while (IsConnected()) {
std::lock_guard lock(network_mutex);
ENetEvent event;
if (enet_host_service(client, &event, 100) > 0) {
switch (event.type) {
case ENET_EVENT_TYPE_RECEIVE:
switch (event.packet->data[0]) {
case IdWifiPacket:
HandleWifiPackets(&event);
break;
case IdChatMessage:
HandleChatPacket(&event);
break;
case IdStatusMessage:
HandleStatusMessagePacket(&event);
break;
case IdRoomInformation:
HandleRoomInformationPacket(&event);
break;
case IdJoinSuccess:
case IdJoinSuccessAsMod:
// The join request was successful, we are now in the room.
// If we joined successfully, there must be at least one client in the room: us.
ASSERT_MSG(member_information.size() > 0,
"We have not yet received member information.");
HandleJoinPacket(&event); // Get the MAC Address for the client
if (event.packet->data[0] == IdJoinSuccessAsMod) {
SetState(State::Moderator);
} else {
SetState(State::Joined);
}
break;
case IdModBanListResponse:
HandleModBanListResponsePacket(&event);
break;
case IdRoomIsFull:
SetState(State::Idle);
SetError(Error::RoomIsFull);
break;
case IdNameCollision:
SetState(State::Idle);
SetError(Error::NameCollision);
break;
case IdMacCollision:
SetState(State::Idle);
SetError(Error::MacCollision);
break;
case IdConsoleIdCollision:
SetState(State::Idle);
SetError(Error::ConsoleIdCollision);
break;
case IdVersionMismatch:
SetState(State::Idle);
SetError(Error::WrongVersion);
break;
case IdWrongPassword:
SetState(State::Idle);
SetError(Error::WrongPassword);
break;
case IdCloseRoom:
SetState(State::Idle);
SetError(Error::LostConnection);
break;
case IdHostKicked:
SetState(State::Idle);
SetError(Error::HostKicked);
break;
case IdHostBanned:
SetState(State::Idle);
SetError(Error::HostBanned);
break;
case IdModPermissionDenied:
SetError(Error::PermissionDenied);
break;
case IdModNoSuchUser:
SetError(Error::NoSuchUser);
break;
}
enet_packet_destroy(event.packet);
break;
case ENET_EVENT_TYPE_DISCONNECT:
if (state == State::Joined || state == State::Moderator) {
SetState(State::Idle);
SetError(Error::LostConnection);
}
break;
case ENET_EVENT_TYPE_NONE:
break;
case ENET_EVENT_TYPE_CONNECT:
// The ENET_EVENT_TYPE_CONNECT event can not possibly happen here because we're
// already connected
ASSERT_MSG(false, "Received unexpected connect event while already connected");
break;
}
}
{
std::lock_guard lock(send_list_mutex);
for (const auto& packet : send_list) {
ENetPacket* enetPacket = enet_packet_create(packet.GetData(), packet.GetDataSize(),
ENET_PACKET_FLAG_RELIABLE);
enet_peer_send(server, 0, enetPacket);
}
enet_host_flush(client);
send_list.clear();
}
}
Disconnect();
};
void RoomMember::RoomMemberImpl::StartLoop() {
loop_thread = std::make_unique<std::thread>(&RoomMember::RoomMemberImpl::MemberLoop, this);
}
void RoomMember::RoomMemberImpl::Send(Packet&& packet) {
std::lock_guard lock(send_list_mutex);
send_list.push_back(std::move(packet));
}
void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname,
const std::string& console_id_hash,
const MacAddress& preferred_mac,
const std::string& password,
const std::string& token) {
Packet packet;
packet << static_cast<u8>(IdJoinRequest);
packet << nickname;
packet << console_id_hash;
packet << preferred_mac;
packet << network_version;
packet << password;
packet << token;
Send(std::move(packet));
}
void RoomMember::RoomMemberImpl::HandleRoomInformationPacket(const ENetEvent* event) {
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8)); // Ignore the message type
RoomInformation info{};
packet >> info.name;
packet >> info.description;
packet >> info.member_slots;
packet >> info.port;
packet >> info.preferred_game;
packet >> info.host_username;
room_information.name = info.name;
room_information.description = info.description;
room_information.member_slots = info.member_slots;
room_information.port = info.port;
room_information.preferred_game = info.preferred_game;
room_information.host_username = info.host_username;
u32 num_members;
packet >> num_members;
member_information.resize(num_members);
for (auto& member : member_information) {
packet >> member.nickname;
packet >> member.mac_address;
packet >> member.game_info.name;
packet >> member.game_info.id;
packet >> member.username;
packet >> member.display_name;
packet >> member.avatar_url;
{
std::lock_guard lock(username_mutex);
if (member.nickname == nickname) {
username = member.username;
}
}
}
Invoke(room_information);
}
void RoomMember::RoomMemberImpl::HandleJoinPacket(const ENetEvent* event) {
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8)); // Ignore the message type
// Parse the MAC Address from the packet
packet >> mac_address;
}
void RoomMember::RoomMemberImpl::HandleWifiPackets(const ENetEvent* event) {
WifiPacket wifi_packet{};
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8)); // Ignore the message type
// Parse the WifiPacket from the packet
u8 frame_type;
packet >> frame_type;
WifiPacket::PacketType type = static_cast<WifiPacket::PacketType>(frame_type);
wifi_packet.type = type;
packet >> wifi_packet.channel;
packet >> wifi_packet.transmitter_address;
packet >> wifi_packet.destination_address;
packet >> wifi_packet.data;
Invoke<WifiPacket>(wifi_packet);
}
void RoomMember::RoomMemberImpl::HandleChatPacket(const ENetEvent* event) {
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8));
ChatEntry chat_entry{};
packet >> chat_entry.nickname;
packet >> chat_entry.username;
packet >> chat_entry.message;
Invoke<ChatEntry>(chat_entry);
}
void RoomMember::RoomMemberImpl::HandleStatusMessagePacket(const ENetEvent* event) {
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8));
StatusMessageEntry status_message_entry{};
u8 type{};
packet >> type;
status_message_entry.type = static_cast<StatusMessageTypes>(type);
packet >> status_message_entry.nickname;
packet >> status_message_entry.username;
Invoke<StatusMessageEntry>(status_message_entry);
}
void RoomMember::RoomMemberImpl::HandleModBanListResponsePacket(const ENetEvent* event) {
Packet packet;
packet.Append(event->packet->data, event->packet->dataLength);
// Ignore the first byte, which is the message id.
packet.IgnoreBytes(sizeof(u8));
Room::BanList ban_list = {};
packet >> ban_list.first;
packet >> ban_list.second;
Invoke<Room::BanList>(ban_list);
}
void RoomMember::RoomMemberImpl::Disconnect() {
member_information.clear();
room_information.member_slots = 0;
room_information.name.clear();
if (!server)
return;
enet_peer_disconnect(server, 0);
ENetEvent event;
while (enet_host_service(client, &event, ConnectionTimeoutMs) > 0) {
switch (event.type) {
case ENET_EVENT_TYPE_RECEIVE:
enet_packet_destroy(event.packet); // Ignore all incoming data
break;
case ENET_EVENT_TYPE_DISCONNECT:
server = nullptr;
return;
case ENET_EVENT_TYPE_NONE:
case ENET_EVENT_TYPE_CONNECT:
break;
}
}
// didn't disconnect gracefully force disconnect
enet_peer_reset(server);
server = nullptr;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<WifiPacket>& RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_wifi_packet;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<RoomMember::State>&
RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_state;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<RoomMember::Error>&
RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_error;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<RoomInformation>&
RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_room_information;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<ChatEntry>& RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_chat_messages;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<StatusMessageEntry>&
RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_status_messages;
}
template <>
RoomMember::RoomMemberImpl::CallbackSet<Room::BanList>&
RoomMember::RoomMemberImpl::Callbacks::Get() {
return callback_set_ban_list;
}
template <typename T>
void RoomMember::RoomMemberImpl::Invoke(const T& data) {
std::lock_guard lock(callback_mutex);
CallbackSet<T> callback_set = callbacks.Get<T>();
for (auto const& callback : callback_set)
(*callback)(data);
}
template <typename T>
RoomMember::CallbackHandle<T> RoomMember::RoomMemberImpl::Bind(
std::function<void(const T&)> callback) {
std::lock_guard lock(callback_mutex);
CallbackHandle<T> handle;
handle = std::make_shared<std::function<void(const T&)>>(callback);
callbacks.Get<T>().insert(handle);
return handle;
}
// RoomMember
RoomMember::RoomMember() : room_member_impl{std::make_unique<RoomMemberImpl>()} {}
RoomMember::~RoomMember() {
ASSERT_MSG(!IsConnected(), "RoomMember is being destroyed while connected");
if (room_member_impl->loop_thread) {
Leave();
}
}
RoomMember::State RoomMember::GetState() const {
return room_member_impl->state;
}
const RoomMember::MemberList& RoomMember::GetMemberInformation() const {
return room_member_impl->member_information;
}
const std::string& RoomMember::GetNickname() const {
return room_member_impl->nickname;
}
const std::string& RoomMember::GetUsername() const {
std::lock_guard lock(room_member_impl->username_mutex);
return room_member_impl->username;
}
const MacAddress& RoomMember::GetMacAddress() const {
ASSERT_MSG(IsConnected(), "Tried to get MAC address while not connected");
return room_member_impl->mac_address;
}
RoomInformation RoomMember::GetRoomInformation() const {
return room_member_impl->room_information;
}
void RoomMember::Join(const std::string& nick, const std::string& console_id_hash,
const char* server_addr, u16 server_port, u16 client_port,
const MacAddress& preferred_mac, const std::string& password,
const std::string& token) {
// If the member is connected, kill the connection first
if (room_member_impl->loop_thread && room_member_impl->loop_thread->joinable()) {
Leave();
}
// If the thread isn't running but the ptr still exists, reset it
else if (room_member_impl->loop_thread) {
room_member_impl->loop_thread.reset();
}
if (!room_member_impl->client) {
room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0);
ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client");
}
room_member_impl->SetState(State::Joining);
ENetAddress address{};
enet_address_set_host(&address, server_addr);
address.port = server_port;
room_member_impl->server =
enet_host_connect(room_member_impl->client, &address, NumChannels, 0);
if (!room_member_impl->server) {
room_member_impl->SetState(State::Idle);
room_member_impl->SetError(Error::UnknownError);
return;
}
ENetEvent event{};
int net = enet_host_service(room_member_impl->client, &event, ConnectionTimeoutMs);
if (net > 0 && event.type == ENET_EVENT_TYPE_CONNECT) {
room_member_impl->nickname = nick;
room_member_impl->StartLoop();
room_member_impl->SendJoinRequest(nick, console_id_hash, preferred_mac, password, token);
SendGameInfo(room_member_impl->current_game_info);
} else {
enet_peer_disconnect(room_member_impl->server, 0);
room_member_impl->SetState(State::Idle);
room_member_impl->SetError(Error::CouldNotConnect);
}
}
bool RoomMember::IsConnected() const {
return room_member_impl->IsConnected();
}
void RoomMember::SendWifiPacket(const WifiPacket& wifi_packet) {
Packet packet;
packet << static_cast<u8>(IdWifiPacket);
packet << static_cast<u8>(wifi_packet.type);
packet << wifi_packet.channel;
packet << wifi_packet.transmitter_address;
packet << wifi_packet.destination_address;
packet << wifi_packet.data;
room_member_impl->Send(std::move(packet));
}
void RoomMember::SendChatMessage(const std::string& message) {
Packet packet;
packet << static_cast<u8>(IdChatMessage);
packet << message;
room_member_impl->Send(std::move(packet));
}
void RoomMember::SendGameInfo(const GameInfo& game_info) {
room_member_impl->current_game_info = game_info;
if (!IsConnected())
return;
Packet packet;
packet << static_cast<u8>(IdSetGameInfo);
packet << game_info.name;
packet << game_info.id;
room_member_impl->Send(std::move(packet));
}
void RoomMember::SendModerationRequest(RoomMessageTypes type, const std::string& nickname) {
ASSERT_MSG(type == IdModKick || type == IdModBan || type == IdModUnban,
"type is not a moderation request");
if (!IsConnected())
return;
Packet packet;
packet << static_cast<u8>(type);
packet << nickname;
room_member_impl->Send(std::move(packet));
}
void RoomMember::RequestBanList() {
if (!IsConnected())
return;
Packet packet;
packet << static_cast<u8>(IdModGetBanList);
room_member_impl->Send(std::move(packet));
}
RoomMember::CallbackHandle<RoomMember::State> RoomMember::BindOnStateChanged(
std::function<void(const RoomMember::State&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<RoomMember::Error> RoomMember::BindOnError(
std::function<void(const RoomMember::Error&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<WifiPacket> RoomMember::BindOnWifiPacketReceived(
std::function<void(const WifiPacket&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<RoomInformation> RoomMember::BindOnRoomInformationChanged(
std::function<void(const RoomInformation&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<ChatEntry> RoomMember::BindOnChatMessageRecieved(
std::function<void(const ChatEntry&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<StatusMessageEntry> RoomMember::BindOnStatusMessageReceived(
std::function<void(const StatusMessageEntry&)> callback) {
return room_member_impl->Bind(callback);
}
RoomMember::CallbackHandle<Room::BanList> RoomMember::BindOnBanListReceived(
std::function<void(const Room::BanList&)> callback) {
return room_member_impl->Bind(callback);
}
template <typename T>
void RoomMember::Unbind(CallbackHandle<T> handle) {
std::lock_guard lock(room_member_impl->callback_mutex);
room_member_impl->callbacks.Get<T>().erase(handle);
}
void RoomMember::Leave() {
room_member_impl->SetState(State::Idle);
room_member_impl->loop_thread->join();
room_member_impl->loop_thread.reset();
enet_host_destroy(room_member_impl->client);
room_member_impl->client = nullptr;
}
template void RoomMember::Unbind(CallbackHandle<WifiPacket>);
template void RoomMember::Unbind(CallbackHandle<RoomMember::State>);
template void RoomMember::Unbind(CallbackHandle<RoomMember::Error>);
template void RoomMember::Unbind(CallbackHandle<RoomInformation>);
template void RoomMember::Unbind(CallbackHandle<ChatEntry>);
template void RoomMember::Unbind(CallbackHandle<StatusMessageEntry>);
template void RoomMember::Unbind(CallbackHandle<Room::BanList>);
} // namespace Network

327
src/network/room_member.h Normal file
View file

@ -0,0 +1,327 @@
// Copyright 2017 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include <boost/serialization/vector.hpp>
#include "common/common_types.h"
#include "network/room.h"
namespace Network {
/// Information about the received WiFi packets.
/// Acts as our own 802.11 header.
struct WifiPacket {
enum class PacketType : u8 {
Beacon,
Data,
Authentication,
AssociationResponse,
Deauthentication,
NodeMap
};
PacketType type; ///< The type of 802.11 frame.
std::vector<u8> data; ///< Raw 802.11 frame data, starting at the management frame header
/// for management frames.
MacAddress transmitter_address; ///< Mac address of the transmitter.
MacAddress destination_address; ///< Mac address of the receiver.
u8 channel; ///< WiFi channel where this frame was transmitted.
private:
template <class Archive>
void serialize(Archive& ar, const unsigned int) {
ar& type;
ar& data;
ar& transmitter_address;
ar& destination_address;
ar& channel;
}
friend class boost::serialization::access;
};
/// Represents a chat message.
struct ChatEntry {
std::string nickname; ///< Nickname of the client who sent this message.
/// Web services username of the client who sent this message, can be empty.
std::string username;
std::string message; ///< Body of the message.
};
/// Represents a system status message.
struct StatusMessageEntry {
StatusMessageTypes type; ///< Type of the message
/// Subject of the message. i.e. the user who is joining/leaving/being banned, etc.
std::string nickname;
std::string username;
};
/**
* This is what a client [person joining a server] would use.
* It also has to be used if you host a game yourself (You'd create both, a Room and a
* RoomMembership for yourself)
*/
class RoomMember final {
public:
enum class State : u8 {
Uninitialized, ///< Not initialized
Idle, ///< Default state (i.e. not connected)
Joining, ///< The client is attempting to join a room.
Joined, ///< The client is connected to the room and is ready to send/receive packets.
Moderator, ///< The client is connnected to the room and is granted mod permissions.
};
enum class Error : u8 {
// Reasons why connection was closed
LostConnection, ///< Connection closed
HostKicked, ///< Kicked by the host
// Reasons why connection was rejected
UnknownError, ///< Some error [permissions to network device missing or something]
NameCollision, ///< Somebody is already using this name
MacCollision, ///< Somebody is already using that mac-address
ConsoleIdCollision, ///< Somebody in the room has the same Console ID
WrongVersion, ///< The room version is not the same as for this RoomMember
WrongPassword, ///< The password doesn't match the one from the Room
CouldNotConnect, ///< The room is not responding to a connection attempt
RoomIsFull, ///< Room is already at the maximum number of players
HostBanned, ///< The user is banned by the host
// Reasons why moderation request failed
PermissionDenied, ///< The user does not have mod permissions
NoSuchUser, ///< The nickname the user attempts to kick/ban does not exist
};
struct MemberInformation {
std::string nickname; ///< Nickname of the member.
std::string username; ///< The web services username of the member. Can be empty.
std::string display_name; ///< The web services display name of the member. Can be empty.
std::string avatar_url; ///< Url to the member's avatar. Can be empty.
GameInfo game_info; ///< Name of the game they're currently playing, or empty if they're
/// not playing anything.
MacAddress mac_address; ///< MAC address associated with this member.
};
using MemberList = std::vector<MemberInformation>;
// The handle for the callback functions
template <typename T>
using CallbackHandle = std::shared_ptr<std::function<void(const T&)>>;
/**
* Unbinds a callback function from the events.
* @param handle The connection handle to disconnect
*/
template <typename T>
void Unbind(CallbackHandle<T> handle);
RoomMember();
~RoomMember();
/**
* Returns the status of our connection to the room.
*/
State GetState() const;
/**
* Returns information about the members in the room we're currently connected to.
*/
const MemberList& GetMemberInformation() const;
/**
* Returns the nickname of the RoomMember.
*/
const std::string& GetNickname() const;
/**
* Returns the username of the RoomMember.
*/
const std::string& GetUsername() const;
/**
* Returns the MAC address of the RoomMember.
*/
const MacAddress& GetMacAddress() const;
/**
* Returns information about the room we're currently connected to.
*/
RoomInformation GetRoomInformation() const;
/**
* Returns whether we're connected to a server or not.
*/
bool IsConnected() const;
/**
* Attempts to join a room at the specified address and port, using the specified nickname.
* A console ID hash is passed in to check console ID conflicts.
* This may fail if the username or console ID is already taken.
*/
void Join(const std::string& nickname, const std::string& console_id_hash,
const char* server_addr = "127.0.0.1", u16 server_port = DefaultRoomPort,
u16 client_port = 0, const MacAddress& preferred_mac = NoPreferredMac,
const std::string& password = "", const std::string& token = "");
/**
* Sends a WiFi packet to the room.
* @param packet The WiFi packet to send.
*/
void SendWifiPacket(const WifiPacket& packet);
/**
* Sends a chat message to the room.
* @param message The contents of the message.
*/
void SendChatMessage(const std::string& message);
/**
* Sends the current game info to the room.
* @param game_info The game information.
*/
void SendGameInfo(const GameInfo& game_info);
/**
* Sends a moderation request to the room.
* @param type Moderation request type.
* @param nickname The subject of the request. (i.e. the user you want to kick/ban)
*/
void SendModerationRequest(RoomMessageTypes type, const std::string& nickname);
/**
* Attempts to retrieve ban list from the room.
* If success, the ban list callback would be called. Otherwise an error would be emitted.
*/
void RequestBanList();
/**
* Binds a function to an event that will be triggered every time the State of the member
* changed. The function wil be called every time the event is triggered. The callback function
* must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<State> BindOnStateChanged(std::function<void(const State&)> callback);
/**
* Binds a function to an event that will be triggered every time an error happened. The
* function wil be called every time the event is triggered. The callback function must not bind
* or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<Error> BindOnError(std::function<void(const Error&)> callback);
/**
* Binds a function to an event that will be triggered every time a WifiPacket is received.
* The function wil be called everytime the event is triggered.
* The callback function must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<WifiPacket> BindOnWifiPacketReceived(
std::function<void(const WifiPacket&)> callback);
/**
* Binds a function to an event that will be triggered every time the RoomInformation changes.
* The function wil be called every time the event is triggered.
* The callback function must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<RoomInformation> BindOnRoomInformationChanged(
std::function<void(const RoomInformation&)> callback);
/**
* Binds a function to an event that will be triggered every time a ChatMessage is received.
* The function wil be called every time the event is triggered.
* The callback function must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<ChatEntry> BindOnChatMessageRecieved(
std::function<void(const ChatEntry&)> callback);
/**
* Binds a function to an event that will be triggered every time a StatusMessage is
* received. The function will be called every time the event is triggered. The callback
* function must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<StatusMessageEntry> BindOnStatusMessageReceived(
std::function<void(const StatusMessageEntry&)> callback);
/**
* Binds a function to an event that will be triggered every time a requested ban list
* received. The function will be called every time the event is triggered. The callback
* function must not bind or unbind a function. Doing so will cause a deadlock
* @param callback The function to call
* @return A handle used for removing the function from the registered list
*/
CallbackHandle<Room::BanList> BindOnBanListReceived(
std::function<void(const Room::BanList&)> callback);
/**
* Leaves the current room.
*/
void Leave();
private:
class RoomMemberImpl;
std::unique_ptr<RoomMemberImpl> room_member_impl;
};
inline const char* GetStateStr(const RoomMember::State& s) {
switch (s) {
case RoomMember::State::Uninitialized:
return "Uninitialized";
case RoomMember::State::Idle:
return "Idle";
case RoomMember::State::Joining:
return "Joining";
case RoomMember::State::Joined:
return "Joined";
case RoomMember::State::Moderator:
return "Moderator";
}
return "Unknown";
}
inline const char* GetErrorStr(const RoomMember::Error& e) {
switch (e) {
case RoomMember::Error::LostConnection:
return "LostConnection";
case RoomMember::Error::HostKicked:
return "HostKicked";
case RoomMember::Error::UnknownError:
return "UnknownError";
case RoomMember::Error::NameCollision:
return "NameCollision";
case RoomMember::Error::MacCollision:
return "MaxCollision";
case RoomMember::Error::ConsoleIdCollision:
return "ConsoleIdCollision";
case RoomMember::Error::WrongVersion:
return "WrongVersion";
case RoomMember::Error::WrongPassword:
return "WrongPassword";
case RoomMember::Error::CouldNotConnect:
return "CouldNotConnect";
case RoomMember::Error::RoomIsFull:
return "RoomIsFull";
case RoomMember::Error::HostBanned:
return "HostBanned";
case RoomMember::Error::PermissionDenied:
return "PermissionDenied";
case RoomMember::Error::NoSuchUser:
return "NoSuchUser";
default:
return "Unknown";
}
}
} // namespace Network

View file

@ -0,0 +1,18 @@
// Copyright 2018 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#include "network/verify_user.h"
namespace Network::VerifyUser {
Backend::~Backend() = default;
NullBackend::~NullBackend() = default;
UserData NullBackend::LoadUserData([[maybe_unused]] const std::string& verify_UID,
[[maybe_unused]] const std::string& token) {
return {};
}
} // namespace Network::VerifyUser

46
src/network/verify_user.h Normal file
View file

@ -0,0 +1,46 @@
// Copyright 2018 Citra Emulator Project
// Licensed under GPLv2 or any later version
// Refer to the license.txt file included.
#pragma once
#include <string>
#include "common/logging/log.h"
namespace Network::VerifyUser {
struct UserData {
std::string username;
std::string display_name;
std::string avatar_url;
bool moderator = false; ///< Whether the user is a Citra Moderator.
};
/**
* A backend used for verifying users and loading user data.
*/
class Backend {
public:
virtual ~Backend();
/**
* Verifies the given token and loads the information into a UserData struct.
* @param verify_UID A GUID that may be used for verification.
* @param token A token that contains user data and verification data. The format and content is
* decided by backends.
*/
virtual UserData LoadUserData(const std::string& verify_UID, const std::string& token) = 0;
};
/**
* A null backend where the token is ignored.
* No verification is performed here and the function returns an empty UserData.
*/
class NullBackend final : public Backend {
public:
~NullBackend();
UserData LoadUserData(const std::string& verify_UID, const std::string& token) override;
};
} // namespace Network::VerifyUser