another try

This commit is contained in:
mgthepro
2022-11-05 13:58:44 +01:00
parent 4a9f2bbf2a
commit 9f63fbe700
2002 changed files with 671171 additions and 671092 deletions

View File

@@ -1,25 +1,25 @@
# SPDX-FileCopyrightText: 2022 yuzu Emulator Project
# SPDX-License-Identifier: GPL-3.0-or-later
add_library(network STATIC
announce_multiplayer_session.cpp
announce_multiplayer_session.h
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)
if (ENABLE_WEB_SERVICE)
target_compile_definitions(network PRIVATE -DENABLE_WEB_SERVICE)
target_link_libraries(network PRIVATE web_service)
endif()
# SPDX-FileCopyrightText: 2022 yuzu Emulator Project
# SPDX-License-Identifier: GPL-3.0-or-later
add_library(network STATIC
announce_multiplayer_session.cpp
announce_multiplayer_session.h
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)
if (ENABLE_WEB_SERVICE)
target_compile_definitions(network PRIVATE -DENABLE_WEB_SERVICE)
target_link_libraries(network PRIVATE web_service)
endif()

View File

@@ -1,164 +1,164 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include <future>
#include <vector>
#include "announce_multiplayer_session.h"
#include "common/announce_multiplayer_room.h"
#include "common/assert.h"
#include "common/settings.h"
#include "network/network.h"
#ifdef ENABLE_WEB_SERVICE
#include "web_service/announce_room_json.h"
#endif
namespace Core {
// Time between room is announced to web_service
static constexpr std::chrono::seconds announce_time_interval(15);
AnnounceMultiplayerSession::AnnounceMultiplayerSession(Network::RoomNetwork& room_network_)
: room_network{room_network_} {
#ifdef ENABLE_WEB_SERVICE
backend = std::make_unique<WebService::RoomJson>(Settings::values.web_api_url.GetValue(),
Settings::values.yuzu_username.GetValue(),
Settings::values.yuzu_token.GetValue());
#else
backend = std::make_unique<AnnounceMultiplayerRoom::NullBackend>();
#endif
}
WebService::WebResult AnnounceMultiplayerSession::Register() {
auto room = room_network.GetRoom().lock();
if (!room) {
return WebService::WebResult{WebService::WebResult::Code::LibError,
"Network is not initialized", ""};
}
if (room->GetState() != Network::Room::State::Open) {
return WebService::WebResult{WebService::WebResult::Code::LibError, "Room is not open", ""};
}
UpdateBackendData(room);
WebService::WebResult result = backend->Register();
if (result.result_code != WebService::WebResult::Code::Success) {
return result;
}
LOG_INFO(WebService, "Room has been registered");
room->SetVerifyUID(result.returned_data);
registered = true;
return WebService::WebResult{WebService::WebResult::Code::Success, "", ""};
}
void AnnounceMultiplayerSession::Start() {
if (announce_multiplayer_thread) {
Stop();
}
shutdown_event.Reset();
announce_multiplayer_thread =
std::make_unique<std::thread>(&AnnounceMultiplayerSession::AnnounceMultiplayerLoop, this);
}
void AnnounceMultiplayerSession::Stop() {
if (announce_multiplayer_thread) {
shutdown_event.Set();
announce_multiplayer_thread->join();
announce_multiplayer_thread.reset();
backend->Delete();
registered = false;
}
}
AnnounceMultiplayerSession::CallbackHandle AnnounceMultiplayerSession::BindErrorCallback(
std::function<void(const WebService::WebResult&)> function) {
std::lock_guard lock(callback_mutex);
auto handle = std::make_shared<std::function<void(const WebService::WebResult&)>>(function);
error_callbacks.insert(handle);
return handle;
}
void AnnounceMultiplayerSession::UnbindErrorCallback(CallbackHandle handle) {
std::lock_guard lock(callback_mutex);
error_callbacks.erase(handle);
}
AnnounceMultiplayerSession::~AnnounceMultiplayerSession() {
Stop();
}
void AnnounceMultiplayerSession::UpdateBackendData(std::shared_ptr<Network::Room> room) {
Network::RoomInformation room_information = room->GetRoomInformation();
std::vector<AnnounceMultiplayerRoom::Member> memberlist = room->GetRoomMemberList();
backend->SetRoomInformation(room_information.name, room_information.description,
room_information.port, room_information.member_slots,
Network::network_version, room->HasPassword(),
room_information.preferred_game);
backend->ClearPlayers();
for (const auto& member : memberlist) {
backend->AddPlayer(member);
}
}
void AnnounceMultiplayerSession::AnnounceMultiplayerLoop() {
// Invokes all current bound error callbacks.
const auto ErrorCallback = [this](WebService::WebResult result) {
std::lock_guard lock(callback_mutex);
for (auto callback : error_callbacks) {
(*callback)(result);
}
};
if (!registered) {
WebService::WebResult result = Register();
if (result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(result);
return;
}
}
auto update_time = std::chrono::steady_clock::now();
std::future<WebService::WebResult> future;
while (!shutdown_event.WaitUntil(update_time)) {
update_time += announce_time_interval;
auto room = room_network.GetRoom().lock();
if (!room) {
break;
}
if (room->GetState() != Network::Room::State::Open) {
break;
}
UpdateBackendData(room);
WebService::WebResult result = backend->Update();
if (result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(result);
}
if (result.result_string == "404") {
registered = false;
// Needs to register the room again
WebService::WebResult register_result = Register();
if (register_result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(register_result);
}
}
}
}
AnnounceMultiplayerRoom::RoomList AnnounceMultiplayerSession::GetRoomList() {
return backend->GetRoomList();
}
bool AnnounceMultiplayerSession::IsRunning() const {
return announce_multiplayer_thread != nullptr;
}
void AnnounceMultiplayerSession::UpdateCredentials() {
ASSERT_MSG(!IsRunning(), "Credentials can only be updated when session is not running");
#ifdef ENABLE_WEB_SERVICE
backend = std::make_unique<WebService::RoomJson>(Settings::values.web_api_url.GetValue(),
Settings::values.yuzu_username.GetValue(),
Settings::values.yuzu_token.GetValue());
#endif
}
} // namespace Core
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include <chrono>
#include <future>
#include <vector>
#include "announce_multiplayer_session.h"
#include "common/announce_multiplayer_room.h"
#include "common/assert.h"
#include "common/settings.h"
#include "network/network.h"
#ifdef ENABLE_WEB_SERVICE
#include "web_service/announce_room_json.h"
#endif
namespace Core {
// Time between room is announced to web_service
static constexpr std::chrono::seconds announce_time_interval(15);
AnnounceMultiplayerSession::AnnounceMultiplayerSession(Network::RoomNetwork& room_network_)
: room_network{room_network_} {
#ifdef ENABLE_WEB_SERVICE
backend = std::make_unique<WebService::RoomJson>(Settings::values.web_api_url.GetValue(),
Settings::values.yuzu_username.GetValue(),
Settings::values.yuzu_token.GetValue());
#else
backend = std::make_unique<AnnounceMultiplayerRoom::NullBackend>();
#endif
}
WebService::WebResult AnnounceMultiplayerSession::Register() {
auto room = room_network.GetRoom().lock();
if (!room) {
return WebService::WebResult{WebService::WebResult::Code::LibError,
"Network is not initialized", ""};
}
if (room->GetState() != Network::Room::State::Open) {
return WebService::WebResult{WebService::WebResult::Code::LibError, "Room is not open", ""};
}
UpdateBackendData(room);
WebService::WebResult result = backend->Register();
if (result.result_code != WebService::WebResult::Code::Success) {
return result;
}
LOG_INFO(WebService, "Room has been registered");
room->SetVerifyUID(result.returned_data);
registered = true;
return WebService::WebResult{WebService::WebResult::Code::Success, "", ""};
}
void AnnounceMultiplayerSession::Start() {
if (announce_multiplayer_thread) {
Stop();
}
shutdown_event.Reset();
announce_multiplayer_thread =
std::make_unique<std::thread>(&AnnounceMultiplayerSession::AnnounceMultiplayerLoop, this);
}
void AnnounceMultiplayerSession::Stop() {
if (announce_multiplayer_thread) {
shutdown_event.Set();
announce_multiplayer_thread->join();
announce_multiplayer_thread.reset();
backend->Delete();
registered = false;
}
}
AnnounceMultiplayerSession::CallbackHandle AnnounceMultiplayerSession::BindErrorCallback(
std::function<void(const WebService::WebResult&)> function) {
std::lock_guard lock(callback_mutex);
auto handle = std::make_shared<std::function<void(const WebService::WebResult&)>>(function);
error_callbacks.insert(handle);
return handle;
}
void AnnounceMultiplayerSession::UnbindErrorCallback(CallbackHandle handle) {
std::lock_guard lock(callback_mutex);
error_callbacks.erase(handle);
}
AnnounceMultiplayerSession::~AnnounceMultiplayerSession() {
Stop();
}
void AnnounceMultiplayerSession::UpdateBackendData(std::shared_ptr<Network::Room> room) {
Network::RoomInformation room_information = room->GetRoomInformation();
std::vector<AnnounceMultiplayerRoom::Member> memberlist = room->GetRoomMemberList();
backend->SetRoomInformation(room_information.name, room_information.description,
room_information.port, room_information.member_slots,
Network::network_version, room->HasPassword(),
room_information.preferred_game);
backend->ClearPlayers();
for (const auto& member : memberlist) {
backend->AddPlayer(member);
}
}
void AnnounceMultiplayerSession::AnnounceMultiplayerLoop() {
// Invokes all current bound error callbacks.
const auto ErrorCallback = [this](WebService::WebResult result) {
std::lock_guard lock(callback_mutex);
for (auto callback : error_callbacks) {
(*callback)(result);
}
};
if (!registered) {
WebService::WebResult result = Register();
if (result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(result);
return;
}
}
auto update_time = std::chrono::steady_clock::now();
std::future<WebService::WebResult> future;
while (!shutdown_event.WaitUntil(update_time)) {
update_time += announce_time_interval;
auto room = room_network.GetRoom().lock();
if (!room) {
break;
}
if (room->GetState() != Network::Room::State::Open) {
break;
}
UpdateBackendData(room);
WebService::WebResult result = backend->Update();
if (result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(result);
}
if (result.result_string == "404") {
registered = false;
// Needs to register the room again
WebService::WebResult register_result = Register();
if (register_result.result_code != WebService::WebResult::Code::Success) {
ErrorCallback(register_result);
}
}
}
}
AnnounceMultiplayerRoom::RoomList AnnounceMultiplayerSession::GetRoomList() {
return backend->GetRoomList();
}
bool AnnounceMultiplayerSession::IsRunning() const {
return announce_multiplayer_thread != nullptr;
}
void AnnounceMultiplayerSession::UpdateCredentials() {
ASSERT_MSG(!IsRunning(), "Credentials can only be updated when session is not running");
#ifdef ENABLE_WEB_SERVICE
backend = std::make_unique<WebService::RoomJson>(Settings::values.web_api_url.GetValue(),
Settings::values.yuzu_username.GetValue(),
Settings::values.yuzu_token.GetValue());
#endif
}
} // namespace Core

View File

@@ -1,98 +1,98 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include <thread>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/thread.h"
namespace Network {
class Room;
class RoomNetwork;
} // namespace Network
namespace Core {
/**
* Instruments AnnounceMultiplayerRoom::Backend.
* Creates a thread that regularly updates the room information and submits them
* An async get of room information is also possible
*/
class AnnounceMultiplayerSession {
public:
using CallbackHandle = std::shared_ptr<std::function<void(const WebService::WebResult&)>>;
AnnounceMultiplayerSession(Network::RoomNetwork& room_network_);
~AnnounceMultiplayerSession();
/**
* Allows to bind a function that will get called if the announce encounters an error
* @param function The function that gets called
* @return A handle that can be used the unbind the function
*/
CallbackHandle BindErrorCallback(std::function<void(const WebService::WebResult&)> function);
/**
* Unbind a function from the error callbacks
* @param handle The handle for the function that should get unbind
*/
void UnbindErrorCallback(CallbackHandle handle);
/**
* Registers a room to web services
* @return The result of the registration attempt.
*/
WebService::WebResult Register();
/**
* Starts the announce of a room to web services
*/
void Start();
/**
* Stops the announce to web services
*/
void Stop();
/**
* Returns a list of all room information the backend got
* @param func A function that gets executed when the async get finished, e.g. a signal
* @return a list of rooms received from the web service
*/
AnnounceMultiplayerRoom::RoomList GetRoomList();
/**
* Whether the announce session is still running
*/
bool IsRunning() const;
/**
* Recreates the backend, updating the credentials.
* This can only be used when the announce session is not running.
*/
void UpdateCredentials();
private:
void UpdateBackendData(std::shared_ptr<Network::Room> room);
void AnnounceMultiplayerLoop();
Common::Event shutdown_event;
std::mutex callback_mutex;
std::set<CallbackHandle> error_callbacks;
std::unique_ptr<std::thread> announce_multiplayer_thread;
/// Backend interface that logs fields
std::unique_ptr<AnnounceMultiplayerRoom::Backend> backend;
std::atomic_bool registered = false; ///< Whether the room has been registered
Network::RoomNetwork& room_network;
};
} // namespace Core
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <set>
#include <thread>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/thread.h"
namespace Network {
class Room;
class RoomNetwork;
} // namespace Network
namespace Core {
/**
* Instruments AnnounceMultiplayerRoom::Backend.
* Creates a thread that regularly updates the room information and submits them
* An async get of room information is also possible
*/
class AnnounceMultiplayerSession {
public:
using CallbackHandle = std::shared_ptr<std::function<void(const WebService::WebResult&)>>;
AnnounceMultiplayerSession(Network::RoomNetwork& room_network_);
~AnnounceMultiplayerSession();
/**
* Allows to bind a function that will get called if the announce encounters an error
* @param function The function that gets called
* @return A handle that can be used the unbind the function
*/
CallbackHandle BindErrorCallback(std::function<void(const WebService::WebResult&)> function);
/**
* Unbind a function from the error callbacks
* @param handle The handle for the function that should get unbind
*/
void UnbindErrorCallback(CallbackHandle handle);
/**
* Registers a room to web services
* @return The result of the registration attempt.
*/
WebService::WebResult Register();
/**
* Starts the announce of a room to web services
*/
void Start();
/**
* Stops the announce to web services
*/
void Stop();
/**
* Returns a list of all room information the backend got
* @param func A function that gets executed when the async get finished, e.g. a signal
* @return a list of rooms received from the web service
*/
AnnounceMultiplayerRoom::RoomList GetRoomList();
/**
* Whether the announce session is still running
*/
bool IsRunning() const;
/**
* Recreates the backend, updating the credentials.
* This can only be used when the announce session is not running.
*/
void UpdateCredentials();
private:
void UpdateBackendData(std::shared_ptr<Network::Room> room);
void AnnounceMultiplayerLoop();
Common::Event shutdown_event;
std::mutex callback_mutex;
std::set<CallbackHandle> error_callbacks;
std::unique_ptr<std::thread> announce_multiplayer_thread;
/// Backend interface that logs fields
std::unique_ptr<AnnounceMultiplayerRoom::Backend> backend;
std::atomic_bool registered = false; ///< Whether the room has been registered
Network::RoomNetwork& room_network;
};
} // namespace Core

View File

@@ -1,50 +1,50 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "common/assert.h"
#include "common/logging/log.h"
#include "enet/enet.h"
#include "network/network.h"
namespace Network {
RoomNetwork::RoomNetwork() {
m_room = std::make_shared<Room>();
m_room_member = std::make_shared<RoomMember>();
}
bool RoomNetwork::Init() {
if (enet_initialize() != 0) {
LOG_ERROR(Network, "Error initializing ENet");
return false;
}
m_room = std::make_shared<Room>();
m_room_member = std::make_shared<RoomMember>();
LOG_DEBUG(Network, "initialized OK");
return true;
}
std::weak_ptr<Room> RoomNetwork::GetRoom() {
return m_room;
}
std::weak_ptr<RoomMember> RoomNetwork::GetRoomMember() {
return m_room_member;
}
void RoomNetwork::Shutdown() {
if (m_room_member) {
if (m_room_member->IsConnected())
m_room_member->Leave();
m_room_member.reset();
}
if (m_room) {
if (m_room->GetState() == Room::State::Open)
m_room->Destroy();
m_room.reset();
}
enet_deinitialize();
LOG_DEBUG(Network, "shutdown OK");
}
} // namespace Network
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#include "common/assert.h"
#include "common/logging/log.h"
#include "enet/enet.h"
#include "network/network.h"
namespace Network {
RoomNetwork::RoomNetwork() {
m_room = std::make_shared<Room>();
m_room_member = std::make_shared<RoomMember>();
}
bool RoomNetwork::Init() {
if (enet_initialize() != 0) {
LOG_ERROR(Network, "Error initializing ENet");
return false;
}
m_room = std::make_shared<Room>();
m_room_member = std::make_shared<RoomMember>();
LOG_DEBUG(Network, "initialized OK");
return true;
}
std::weak_ptr<Room> RoomNetwork::GetRoom() {
return m_room;
}
std::weak_ptr<RoomMember> RoomNetwork::GetRoomMember() {
return m_room_member;
}
void RoomNetwork::Shutdown() {
if (m_room_member) {
if (m_room_member->IsConnected())
m_room_member->Leave();
m_room_member.reset();
}
if (m_room) {
if (m_room->GetState() == Room::State::Open)
m_room->Destroy();
m_room.reset();
}
enet_deinitialize();
LOG_DEBUG(Network, "shutdown OK");
}
} // namespace Network

View File

@@ -1,33 +1,33 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <memory>
#include "network/room.h"
#include "network/room_member.h"
namespace Network {
class RoomNetwork {
public:
RoomNetwork();
/// 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();
private:
std::shared_ptr<RoomMember> m_room_member; ///< RoomMember (Client) for network games
std::shared_ptr<Room> m_room; ///< Room (Server) for network games
};
} // namespace Network
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <memory>
#include "network/room.h"
#include "network/room_member.h"
namespace Network {
class RoomNetwork {
public:
RoomNetwork();
/// 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();
private:
std::shared_ptr<RoomMember> m_room_member; ///< RoomMember (Client) for network games
std::shared_ptr<Room> m_room; ///< Room (Server) for network games
};
} // namespace Network

View File

@@ -1,262 +1,262 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include "network/packet.h"
namespace Network {
#ifndef htonll
static u64 htonll(u64 x) {
return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32));
}
#endif
#ifndef ntohll
static 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::Read(bool& out_data) {
u8 value{};
if (Read(value)) {
out_data = (value != 0);
}
return *this;
}
Packet& Packet::Read(s8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(u8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(s16& out_data) {
s16 value{};
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::Read(u16& out_data) {
u16 value{};
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::Read(s32& out_data) {
s32 value{};
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::Read(u32& out_data) {
u32 value{};
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::Read(s64& out_data) {
s64 value{};
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::Read(u64& out_data) {
u64 value{};
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::Read(float& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(double& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(char* out_data) {
// First extract string length
u32 length = 0;
Read(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::Read(std::string& out_data) {
// First extract string length
u32 length = 0;
Read(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::Write(bool in_data) {
Write(static_cast<u8>(in_data));
return *this;
}
Packet& Packet::Write(s8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(u8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(s16 in_data) {
s16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u16 in_data) {
u16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(s32 in_data) {
s32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u32 in_data) {
u32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(s64 in_data) {
s64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u64 in_data) {
u64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(float in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(double in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(const char* in_data) {
// First insert string length
u32 length = static_cast<u32>(std::strlen(in_data));
Write(length);
// Then insert characters
Append(in_data, length * sizeof(char));
return *this;
}
Packet& Packet::Write(const std::string& in_data) {
// First insert string length
u32 length = static_cast<u32>(in_data.size());
Write(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
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#ifdef _WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <cstring>
#include <string>
#include "network/packet.h"
namespace Network {
#ifndef htonll
static u64 htonll(u64 x) {
return ((1 == htonl(1)) ? (x) : ((uint64_t)htonl((x)&0xFFFFFFFF) << 32) | htonl((x) >> 32));
}
#endif
#ifndef ntohll
static 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::Read(bool& out_data) {
u8 value{};
if (Read(value)) {
out_data = (value != 0);
}
return *this;
}
Packet& Packet::Read(s8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(u8& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(s16& out_data) {
s16 value{};
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::Read(u16& out_data) {
u16 value{};
Read(&value, sizeof(value));
out_data = ntohs(value);
return *this;
}
Packet& Packet::Read(s32& out_data) {
s32 value{};
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::Read(u32& out_data) {
u32 value{};
Read(&value, sizeof(value));
out_data = ntohl(value);
return *this;
}
Packet& Packet::Read(s64& out_data) {
s64 value{};
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::Read(u64& out_data) {
u64 value{};
Read(&value, sizeof(value));
out_data = ntohll(value);
return *this;
}
Packet& Packet::Read(float& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(double& out_data) {
Read(&out_data, sizeof(out_data));
return *this;
}
Packet& Packet::Read(char* out_data) {
// First extract string length
u32 length = 0;
Read(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::Read(std::string& out_data) {
// First extract string length
u32 length = 0;
Read(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::Write(bool in_data) {
Write(static_cast<u8>(in_data));
return *this;
}
Packet& Packet::Write(s8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(u8 in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(s16 in_data) {
s16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u16 in_data) {
u16 toWrite = htons(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(s32 in_data) {
s32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u32 in_data) {
u32 toWrite = htonl(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(s64 in_data) {
s64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(u64 in_data) {
u64 toWrite = htonll(in_data);
Append(&toWrite, sizeof(toWrite));
return *this;
}
Packet& Packet::Write(float in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(double in_data) {
Append(&in_data, sizeof(in_data));
return *this;
}
Packet& Packet::Write(const char* in_data) {
// First insert string length
u32 length = static_cast<u32>(std::strlen(in_data));
Write(length);
// Then insert characters
Append(in_data, length * sizeof(char));
return *this;
}
Packet& Packet::Write(const std::string& in_data) {
// First insert string length
u32 length = static_cast<u32>(in_data.size());
Write(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

View File

@@ -1,165 +1,165 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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 read function to read data from the packet
Packet& Read(bool& out_data);
Packet& Read(s8& out_data);
Packet& Read(u8& out_data);
Packet& Read(s16& out_data);
Packet& Read(u16& out_data);
Packet& Read(s32& out_data);
Packet& Read(u32& out_data);
Packet& Read(s64& out_data);
Packet& Read(u64& out_data);
Packet& Read(float& out_data);
Packet& Read(double& out_data);
Packet& Read(char* out_data);
Packet& Read(std::string& out_data);
template <typename T>
Packet& Read(std::vector<T>& out_data);
template <typename T, std::size_t S>
Packet& Read(std::array<T, S>& out_data);
/// Overloads of write function to write data into the packet
Packet& Write(bool in_data);
Packet& Write(s8 in_data);
Packet& Write(u8 in_data);
Packet& Write(s16 in_data);
Packet& Write(u16 in_data);
Packet& Write(s32 in_data);
Packet& Write(u32 in_data);
Packet& Write(s64 in_data);
Packet& Write(u64 in_data);
Packet& Write(float in_data);
Packet& Write(double in_data);
Packet& Write(const char* in_data);
Packet& Write(const std::string& in_data);
template <typename T>
Packet& Write(const std::vector<T>& in_data);
template <typename T, std::size_t S>
Packet& Write(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::Read(std::vector<T>& out_data) {
// First extract the size
u32 size = 0;
Read(size);
out_data.resize(size);
// Then extract the data
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
Read(character);
out_data[i] = character;
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::Read(std::array<T, S>& out_data) {
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
Read(character);
out_data[i] = character;
}
return *this;
}
template <typename T>
Packet& Packet::Write(const std::vector<T>& in_data) {
// First insert the size
Write(static_cast<u32>(in_data.size()));
// Then insert the data
for (std::size_t i = 0; i < in_data.size(); ++i) {
Write(in_data[i]);
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::Write(const std::array<T, S>& in_data) {
for (std::size_t i = 0; i < in_data.size(); ++i) {
Write(in_data[i]);
}
return *this;
}
} // namespace Network
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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 read function to read data from the packet
Packet& Read(bool& out_data);
Packet& Read(s8& out_data);
Packet& Read(u8& out_data);
Packet& Read(s16& out_data);
Packet& Read(u16& out_data);
Packet& Read(s32& out_data);
Packet& Read(u32& out_data);
Packet& Read(s64& out_data);
Packet& Read(u64& out_data);
Packet& Read(float& out_data);
Packet& Read(double& out_data);
Packet& Read(char* out_data);
Packet& Read(std::string& out_data);
template <typename T>
Packet& Read(std::vector<T>& out_data);
template <typename T, std::size_t S>
Packet& Read(std::array<T, S>& out_data);
/// Overloads of write function to write data into the packet
Packet& Write(bool in_data);
Packet& Write(s8 in_data);
Packet& Write(u8 in_data);
Packet& Write(s16 in_data);
Packet& Write(u16 in_data);
Packet& Write(s32 in_data);
Packet& Write(u32 in_data);
Packet& Write(s64 in_data);
Packet& Write(u64 in_data);
Packet& Write(float in_data);
Packet& Write(double in_data);
Packet& Write(const char* in_data);
Packet& Write(const std::string& in_data);
template <typename T>
Packet& Write(const std::vector<T>& in_data);
template <typename T, std::size_t S>
Packet& Write(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::Read(std::vector<T>& out_data) {
// First extract the size
u32 size = 0;
Read(size);
out_data.resize(size);
// Then extract the data
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
Read(character);
out_data[i] = character;
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::Read(std::array<T, S>& out_data) {
for (std::size_t i = 0; i < out_data.size(); ++i) {
T character;
Read(character);
out_data[i] = character;
}
return *this;
}
template <typename T>
Packet& Packet::Write(const std::vector<T>& in_data) {
// First insert the size
Write(static_cast<u32>(in_data.size()));
// Then insert the data
for (std::size_t i = 0; i < in_data.size(); ++i) {
Write(in_data[i]);
}
return *this;
}
template <typename T, std::size_t S>
Packet& Packet::Write(const std::array<T, S>& in_data) {
for (std::size_t i = 0; i < in_data.size(); ++i) {
Write(in_data[i]);
}
return *this;
}
} // namespace Network

File diff suppressed because it is too large Load Diff

View File

@@ -1,148 +1,148 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <memory>
#include <string>
#include <vector>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/socket_types.h"
#include "network/verify_user.h"
namespace Network {
using AnnounceMultiplayerRoom::GameInfo;
using AnnounceMultiplayerRoom::Member;
using AnnounceMultiplayerRoom::RoomInformation;
constexpr u32 network_version = 1; ///< 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
/// A special IP address that tells the room we're joining to assign us a IP address
/// automatically.
constexpr IPv4Address NoPreferredIP = {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,
IdProxyPacket,
IdLdnPacket,
IdChatMessage,
IdNameCollision,
IdIpCollision,
IdVersionMismatch,
IdWrongPassword,
IdCloseRoom,
IdRoomIsFull,
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.
};
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 GameInfo = {},
std::unique_ptr<VerifyUser::Backend> verify_backend = nullptr,
const BanList& ban_list = {}, bool enable_yuzu_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
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <array>
#include <memory>
#include <string>
#include <vector>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/socket_types.h"
#include "network/verify_user.h"
namespace Network {
using AnnounceMultiplayerRoom::GameInfo;
using AnnounceMultiplayerRoom::Member;
using AnnounceMultiplayerRoom::RoomInformation;
constexpr u32 network_version = 1; ///< 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
/// A special IP address that tells the room we're joining to assign us a IP address
/// automatically.
constexpr IPv4Address NoPreferredIP = {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,
IdProxyPacket,
IdLdnPacket,
IdChatMessage,
IdNameCollision,
IdIpCollision,
IdVersionMismatch,
IdWrongPassword,
IdCloseRoom,
IdRoomIsFull,
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.
};
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 GameInfo = {},
std::unique_ptr<VerifyUser::Backend> verify_backend = nullptr,
const BanList& ban_list = {}, bool enable_yuzu_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

File diff suppressed because it is too large Load Diff

View File

@@ -1,337 +1,337 @@
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/socket_types.h"
#include "network/room.h"
namespace Network {
using AnnounceMultiplayerRoom::GameInfo;
using AnnounceMultiplayerRoom::RoomInformation;
enum class LDNPacketType : u8 {
Scan,
ScanResp,
Connect,
SyncNetwork,
Disconnect,
DestroyNetwork,
};
struct LDNPacket {
LDNPacketType type;
IPv4Address local_ip;
IPv4Address remote_ip;
bool broadcast;
std::vector<u8> data;
};
/// Information about the received proxy packets.
struct ProxyPacket {
SockAddrIn local_endpoint;
SockAddrIn remote_endpoint;
Protocol protocol;
bool broadcast;
std::vector<u8> data;
};
/// 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
IpCollision, ///< Somebody is already using that fake-ip-address
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.
IPv4Address fake_ip; ///< Fake Ip 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 IPv4Address& GetFakeIpAddress() 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.
*/
void Join(const std::string& nickname, const char* server_addr = "127.0.0.1",
u16 server_port = DefaultRoomPort, u16 client_port = 0,
const IPv4Address& preferred_fake_ip = NoPreferredIP,
const std::string& password = "", const std::string& token = "");
/**
* Sends a Proxy packet to the room.
* @param packet The WiFi packet to send.
*/
void SendProxyPacket(const ProxyPacket& packet);
/**
* Sends an LDN packet to the room.
* @param packet The WiFi packet to send.
*/
void SendLdnPacket(const LDNPacket& 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 ProxyPacket 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<ProxyPacket> BindOnProxyPacketReceived(
std::function<void(const ProxyPacket&)> callback);
/**
* Binds a function to an event that will be triggered every time an LDNPacket 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<LDNPacket> BindOnLdnPacketReceived(
std::function<void(const LDNPacket&)> 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::IpCollision:
return "IpCollision";
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
// SPDX-FileCopyrightText: Copyright 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#pragma once
#include <functional>
#include <memory>
#include <string>
#include <vector>
#include "common/announce_multiplayer_room.h"
#include "common/common_types.h"
#include "common/socket_types.h"
#include "network/room.h"
namespace Network {
using AnnounceMultiplayerRoom::GameInfo;
using AnnounceMultiplayerRoom::RoomInformation;
enum class LDNPacketType : u8 {
Scan,
ScanResp,
Connect,
SyncNetwork,
Disconnect,
DestroyNetwork,
};
struct LDNPacket {
LDNPacketType type;
IPv4Address local_ip;
IPv4Address remote_ip;
bool broadcast;
std::vector<u8> data;
};
/// Information about the received proxy packets.
struct ProxyPacket {
SockAddrIn local_endpoint;
SockAddrIn remote_endpoint;
Protocol protocol;
bool broadcast;
std::vector<u8> data;
};
/// 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
IpCollision, ///< Somebody is already using that fake-ip-address
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.
IPv4Address fake_ip; ///< Fake Ip 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 IPv4Address& GetFakeIpAddress() 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.
*/
void Join(const std::string& nickname, const char* server_addr = "127.0.0.1",
u16 server_port = DefaultRoomPort, u16 client_port = 0,
const IPv4Address& preferred_fake_ip = NoPreferredIP,
const std::string& password = "", const std::string& token = "");
/**
* Sends a Proxy packet to the room.
* @param packet The WiFi packet to send.
*/
void SendProxyPacket(const ProxyPacket& packet);
/**
* Sends an LDN packet to the room.
* @param packet The WiFi packet to send.
*/
void SendLdnPacket(const LDNPacket& 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 ProxyPacket 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<ProxyPacket> BindOnProxyPacketReceived(
std::function<void(const ProxyPacket&)> callback);
/**
* Binds a function to an event that will be triggered every time an LDNPacket 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<LDNPacket> BindOnLdnPacketReceived(
std::function<void(const LDNPacket&)> 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::IpCollision:
return "IpCollision";
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

@@ -1,17 +1,17 @@
// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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
// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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

View File

@@ -1,45 +1,45 @@
// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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 yuzu 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
// SPDX-FileCopyrightText: Copyright 2018 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later
#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 yuzu 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