diff options
-rw-r--r-- | src/citra/CMakeLists.txt | 2 | ||||
-rw-r--r-- | src/citra/emu_window/emu_window_sdl2.cpp | 4 | ||||
-rw-r--r-- | src/network/CMakeLists.txt | 2 | ||||
-rw-r--r-- | src/network/packet.cpp | 225 | ||||
-rw-r--r-- | src/network/packet.h | 162 | ||||
-rw-r--r-- | src/network/room.cpp | 402 | ||||
-rw-r--r-- | src/network/room.h | 26 | ||||
-rw-r--r-- | src/network/room_member.cpp | 334 | ||||
-rw-r--r-- | src/network/room_member.h | 70 |
9 files changed, 1206 insertions, 21 deletions
diff --git a/src/citra/CMakeLists.txt b/src/citra/CMakeLists.txt index d72d2b5f4..a885f22f8 100644 --- a/src/citra/CMakeLists.txt +++ b/src/citra/CMakeLists.txt @@ -16,7 +16,7 @@ set(HEADERS create_directory_groups(${SRCS} ${HEADERS}) add_executable(citra ${SRCS} ${HEADERS}) -target_link_libraries(citra PRIVATE common core input_common) +target_link_libraries(citra PRIVATE common core input_common network) target_link_libraries(citra PRIVATE inih glad) if (MSVC) target_link_libraries(citra PRIVATE getopt) diff --git a/src/citra/emu_window/emu_window_sdl2.cpp b/src/citra/emu_window/emu_window_sdl2.cpp index 47aadd60c..b0f808399 100644 --- a/src/citra/emu_window/emu_window_sdl2.cpp +++ b/src/citra/emu_window/emu_window_sdl2.cpp @@ -16,6 +16,7 @@ #include "core/settings.h" #include "input_common/keyboard.h" #include "input_common/main.h" +#include "network/network.h" void EmuWindow_SDL2::OnMouseMotion(s32 x, s32 y) { TouchMoved((unsigned)std::max(x, 0), (unsigned)std::max(y, 0)); @@ -58,6 +59,7 @@ void EmuWindow_SDL2::OnResize() { EmuWindow_SDL2::EmuWindow_SDL2() { InputCommon::Init(); + Network::Init(); motion_emu = std::make_unique<Motion::MotionEmu>(*this); @@ -116,6 +118,8 @@ EmuWindow_SDL2::~EmuWindow_SDL2() { SDL_GL_DeleteContext(gl_context); SDL_Quit(); motion_emu = nullptr; + + Network::Shutdown(); InputCommon::Shutdown(); } diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt index aeabe430e..ac9d028da 100644 --- a/src/network/CMakeLists.txt +++ b/src/network/CMakeLists.txt @@ -1,11 +1,13 @@ set(SRCS network.cpp + packet.cpp room.cpp room_member.cpp ) set(HEADERS network.h + packet.h room.h room_member.h ) diff --git a/src/network/packet.cpp b/src/network/packet.cpp new file mode 100644 index 000000000..660e92c0d --- /dev/null +++ b/src/network/packet.cpp @@ -0,0 +1,225 @@ +// 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 { + +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::CheckSize : nullptr; +} + +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>>(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<<(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 = 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 diff --git a/src/network/packet.h b/src/network/packet.h new file mode 100644 index 000000000..94b351ab1 --- /dev/null +++ b/src/network/packet.h @@ -0,0 +1,162 @@ +// 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>>(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<<(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 = 0; + *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 = 0; + *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 diff --git a/src/network/room.cpp b/src/network/room.cpp index 48de2f5cb..8b7915bb7 100644 --- a/src/network/room.cpp +++ b/src/network/room.cpp @@ -2,7 +2,13 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include <algorithm> +#include <atomic> +#include <random> +#include <thread> +#include <vector> #include "enet/enet.h" +#include "network/packet.h" #include "network/room.h" namespace Network { @@ -12,12 +18,395 @@ static constexpr u32 MaxConcurrentConnections = 10; class Room::RoomImpl { public: + // This MAC address is used to generate a 'Nintendo' like Mac address. + const MacAddress NintendoOUI = {0x00, 0x1F, 0x32, 0x00, 0x00, 0x00}; + std::mt19937 random_gen; ///< Random number generator. Used for GenerateMacAddress + ENetHost* server = nullptr; ///< Network interface. std::atomic<State> state{State::Closed}; ///< Current state of the room. RoomInformation room_information; ///< Information about this room. + + struct Member { + std::string nickname; ///< The nickname of the member. + std::string game_name; ///< The current game of the member + MacAddress mac_address; ///< The assigned mac address of the member. + ENetPeer* peer; ///< The remote peer. + }; + using MemberList = std::vector<Member>; + MemberList members; ///< Information about the members of this room. + + RoomImpl() : random_gen(std::random_device()()) {} + + /// Thread that receives and dispatches network packets + std::unique_ptr<std::thread> room_thread; + + /// Thread function that will receive and dispatch messages until the room is destroyed. + void ServerLoop(); + void StartLoop(); + + /** + * Parses and answers a room join request from a client. + * Validates the uniqueness of the username and assigns the MAC address + * that the client will use for the remainder of the connection. + */ + void HandleJoinRequest(const ENetEvent* event); + + /** + * Returns whether the nickname is valid, ie. isn't already taken by someone else in the room. + */ + bool IsValidNickname(const std::string& nickname) const; + + /** + * Returns whether the MAC address is valid, ie. isn't already taken by someone else in the + * room. + */ + bool IsValidMacAddress(const MacAddress& address) const; + + /** + * Sends a ID_ROOM_NAME_COLLISION message telling the client that the name is invalid. + */ + void SendNameCollision(ENetPeer* client); + + /** + * Sends a ID_ROOM_MAC_COLLISION message telling the client that the MAC is invalid. + */ + void SendMacCollision(ENetPeer* client); + + /** + * Sends a ID_ROOM_VERSION_MISMATCH message telling the client that the version is invalid. + */ + void SendVersionMismatch(ENetPeer* client); + + /** + * Notifies the member that its connection attempt was successful, + * and it is now part of the room. + */ + void SendJoinSuccess(ENetPeer* client, MacAddress mac_address); + + /** + * Notifies the members that the room is closed, + */ + void SendCloseMessage(); + + /** + * Sends the information about the room, along with the list of members + * to every connected client in the room. + * The packet has the structure: + * <MessageID>ID_ROOM_INFORMATION + * <String> room_name + * <u32> member_slots: The max number of clients allowed in this room + * <u32> num_members: the number of currently joined clients + * This is followed by the following three values for each member: + * <String> nickname of that member + * <MacAddress> mac_address of that member + * <String> game_name of that member + */ + void BroadcastRoomInformation(); + + /** + * Generates a free MAC address to assign to a new client. + * The first 3 bytes are the NintendoOUI 0x00, 0x1F, 0x32 + */ + MacAddress GenerateMacAddress(); + + /** + * Broadcasts this packet to all members except the sender. + * @param event The ENet event containing the data + */ + void HandleWifiPacket(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 the game name from a received ENet packet and broadcasts it. + * @param event The ENet event that was received. + */ + void HandleGameNamePacket(const ENetEvent* event); + + /** + * Removes the client from the members list if it was in it and announces the change + * to all other clients. + */ + void HandleClientDisconnection(ENetPeer* client); }; +// RoomImpl +void Room::RoomImpl::ServerLoop() { + while (state != State::Closed) { + ENetEvent event; + if (enet_host_service(server, &event, 100) > 0) { + switch (event.type) { + case ENET_EVENT_TYPE_RECEIVE: + switch (event.packet->data[0]) { + case IdJoinRequest: + HandleJoinRequest(&event); + break; + case IdSetGameName: + HandleGameNamePacket(&event); + break; + case IdWifiPacket: + HandleWifiPacket(&event); + break; + case IdChatMessage: + HandleChatPacket(&event); + break; + } + enet_packet_destroy(event.packet); + break; + case ENET_EVENT_TYPE_DISCONNECT: + HandleClientDisconnection(event.peer); + break; + } + } + } + // Close the connection to all members: + SendCloseMessage(); +} + +void Room::RoomImpl::StartLoop() { + room_thread = std::make_unique<std::thread>(&Room::RoomImpl::ServerLoop, this); +} + +void Room::RoomImpl::HandleJoinRequest(const ENetEvent* event) { + Packet packet; + packet.Append(event->packet->data, event->packet->dataLength); + packet.IgnoreBytes(sizeof(u8)); // Igonore the message type + std::string nickname; + packet >> nickname; + + MacAddress preferred_mac; + packet >> preferred_mac; + + u32 client_version; + packet >> client_version; + + if (!IsValidNickname(nickname)) { + SendNameCollision(event->peer); + return; + } + + if (preferred_mac != NoPreferredMac) { + // Verify if the preferred mac is available + if (!IsValidMacAddress(preferred_mac)) { + SendMacCollision(event->peer); + return; + } + } else { + // Assign a MAC address of this client automatically + preferred_mac = GenerateMacAddress(); + } + + if (client_version != network_version) { + SendVersionMismatch(event->peer); + return; + } + + // At this point the client is ready to be added to the room. + Member member{}; + member.mac_address = preferred_mac; + member.nickname = nickname; + member.peer = event->peer; + + members.push_back(std::move(member)); + + // Notify everyone that the room information has changed. + BroadcastRoomInformation(); + SendJoinSuccess(event->peer, preferred_mac); +} + +bool Room::RoomImpl::IsValidNickname(const std::string& nickname) const { + // A nickname is valid if it is not already taken by anybody else in the room. + // TODO(B3N30): Check for empty names, spaces, etc. + return std::all_of(members.begin(), members.end(), + [&nickname](const auto& member) { return member.nickname != nickname; }); +} + +bool Room::RoomImpl::IsValidMacAddress(const MacAddress& address) const { + // A MAC address is valid if it is not already taken by anybody else in the room. + return std::all_of(members.begin(), members.end(), + [&address](const auto& member) { return member.mac_address != address; }); +} + +void Room::RoomImpl::SendNameCollision(ENetPeer* client) { + Packet packet; + packet << static_cast<u8>(IdNameCollision); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendMacCollision(ENetPeer* client) { + Packet packet; + packet << static_cast<u8>(IdMacCollision); + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendVersionMismatch(ENetPeer* client) { + Packet packet; + packet << static_cast<u8>(IdVersionMismatch); + packet << network_version; + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendJoinSuccess(ENetPeer* client, MacAddress mac_address) { + Packet packet; + packet << static_cast<u8>(IdJoinSuccess); + packet << mac_address; + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_peer_send(client, 0, enet_packet); + enet_host_flush(server); +} + +void Room::RoomImpl::SendCloseMessage() { + Packet packet; + packet << static_cast<u8>(IdCloseRoom); + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + for (auto& member : members) { + enet_peer_send(member.peer, 0, enet_packet); + } + enet_host_flush(server); + for (auto& member : members) { + enet_peer_disconnect(member.peer, 0); + } +} + +void Room::RoomImpl::BroadcastRoomInformation() { + Packet packet; + packet << static_cast<u8>(IdRoomInformation); + packet << room_information.name; + packet << room_information.member_slots; + + packet << static_cast<u32>(members.size()); + for (const auto& member : members) { + packet << member.nickname; + packet << member.mac_address; + packet << member.game_name; + } + + ENetPacket* enet_packet = + enet_packet_create(packet.GetData(), packet.GetDataSize(), ENET_PACKET_FLAG_RELIABLE); + enet_host_broadcast(server, 0, enet_packet); + enet_host_flush(server); +} + +MacAddress Room::RoomImpl::GenerateMacAddress() { + MacAddress result_mac = + NintendoOUI; // The first three bytes of each MAC address will be the NintendoOUI + std::uniform_int_distribution<> dis(0x00, 0xFF); // Random byte between 0 and 0xFF + do { + for (size_t i = 3; i < result_mac.size(); ++i) { + result_mac[i] = dis(random_gen); + } + } while (!IsValidMacAddress(result_mac)); + return result_mac; +} + +void Room::RoomImpl::HandleWifiPacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + in_packet.IgnoreBytes(sizeof(u8)); // Message type + in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Type + in_packet.IgnoreBytes(sizeof(u8)); // WifiPacket Channel + in_packet.IgnoreBytes(sizeof(MacAddress)); // WifiPacket Transmitter Address + MacAddress destination_address; + in_packet >> destination_address; + + Packet out_packet; + out_packet.Append(event->packet->data, event->packet->dataLength); + ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + + if (destination_address == BroadcastMac) { // Send the data to everyone except the sender + for (const auto& member : members) { + if (member.peer != event->peer) + enet_peer_send(member.peer, 0, enet_packet); + } + } else { // Send the data only to the destination client + auto member = std::find_if(members.begin(), members.end(), + [destination_address](const Member& member) -> bool { + return member.mac_address == destination_address; + }); + if (member != members.end()) { + enet_peer_send(member->peer, 0, enet_packet); + } + } + enet_host_flush(server); +} + +void Room::RoomImpl::HandleChatPacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + + in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type + std::string message; + in_packet >> message; + auto CompareNetworkAddress = [event](const Member member) -> bool { + return member.peer == event->peer; + }; + const auto sending_member = std::find_if(members.begin(), members.end(), CompareNetworkAddress); + if (sending_member == members.end()) { + return; // Received a chat message from a unknown sender + } + + Packet out_packet; + out_packet << static_cast<u8>(IdChatMessage); + out_packet << sending_member->nickname; + out_packet << message; + + ENetPacket* enet_packet = enet_packet_create(out_packet.GetData(), out_packet.GetDataSize(), + ENET_PACKET_FLAG_RELIABLE); + for (const auto& member : members) { + if (member.peer != event->peer) + enet_peer_send(member.peer, 0, enet_packet); + } + enet_host_flush(server); +} + +void Room::RoomImpl::HandleGameNamePacket(const ENetEvent* event) { + Packet in_packet; + in_packet.Append(event->packet->data, event->packet->dataLength); + + in_packet.IgnoreBytes(sizeof(u8)); // Igonore the message type + std::string game_name; + in_packet >> game_name; + auto member = + std::find_if(members.begin(), members.end(), + [event](const Member& member) -> bool { return member.peer == event->peer; }); + if (member != members.end()) { + member->game_name = game_name; + BroadcastRoomInformation(); + } +} + +void Room::RoomImpl::HandleClientDisconnection(ENetPeer* client) { + // Remove the client from the members list. + members.erase(std::remove_if(members.begin(), members.end(), + [client](const Member& member) { return member.peer == client; }), + members.end()); + + // Announce the change to all clients. + enet_peer_disconnect(client, 0); + BroadcastRoomInformation(); +} + +// Room Room::Room() : room_impl{std::make_unique<RoomImpl>()} {} Room::~Room() = default; @@ -25,7 +414,9 @@ Room::~Room() = default; void Room::Create(const std::string& name, const std::string& server_address, u16 server_port) { ENetAddress address; address.host = ENET_HOST_ANY; - enet_address_set_host(&address, server_address.c_str()); + if (!server_address.empty()) { + enet_address_set_host(&address, server_address.c_str()); + } address.port = server_port; room_impl->server = enet_host_create(&address, MaxConcurrentConnections, NumChannels, 0, 0); @@ -34,8 +425,7 @@ void Room::Create(const std::string& name, const std::string& server_address, u1 room_impl->room_information.name = name; room_impl->room_information.member_slots = MaxConcurrentConnections; - - // TODO(B3N30): Start the receiving thread + room_impl->StartLoop(); } Room::State Room::GetState() const { @@ -48,13 +438,17 @@ const RoomInformation& Room::GetRoomInformation() const { void Room::Destroy() { room_impl->state = State::Closed; - // TODO(B3n30): Join the receiving thread + room_impl->room_thread->join(); + room_impl->room_thread.reset(); if (room_impl->server) { enet_host_destroy(room_impl->server); } room_impl->room_information = {}; room_impl->server = nullptr; + room_impl->members.clear(); + room_impl->room_information.member_slots = 0; + room_impl->room_information.name.clear(); } } // namespace Network diff --git a/src/network/room.h b/src/network/room.h index 70c64d5f1..54cccf0ae 100644 --- a/src/network/room.h +++ b/src/network/room.h @@ -4,13 +4,15 @@ #pragma once -#include <atomic> +#include <array> #include <memory> #include <string> #include "common/common_types.h" namespace Network { +constexpr u32 network_version = 1; ///< The version of this Room and RoomMember + constexpr u16 DefaultRoomPort = 1234; constexpr size_t NumChannels = 1; // Number of channels used for the connection @@ -19,6 +21,28 @@ struct RoomInformation { u32 member_slots; ///< Maximum number of members in this room }; +using MacAddress = std::array<u8, 6>; +/// A special MAC address that tells the room we're joining to assign us a MAC address +/// automatically. +const 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, + IdSetGameName, + IdWifiPacket, + IdChatMessage, + IdNameCollision, + IdMacCollision, + IdVersionMismatch, + IdCloseRoom +}; + /// This is what a server [person creating a server] would use. class Room final { public: diff --git a/src/network/room_member.cpp b/src/network/room_member.cpp index c87f009f4..dac9bacae 100644 --- a/src/network/room_member.cpp +++ b/src/network/room_member.cpp @@ -2,8 +2,13 @@ // Licensed under GPLv2 or any later version // Refer to the license.txt file included. +#include <atomic> +#include <list> +#include <mutex> +#include <thread> #include "common/assert.h" #include "enet/enet.h" +#include "network/packet.h" #include "network/room_member.h" namespace Network { @@ -15,11 +20,263 @@ 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; + std::atomic<State> state{State::Idle}; ///< Current state of the RoomMember. + void SetState(const State new_state); + bool IsConnected() const; + + std::string nickname; ///< The nickname of this member. + 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 + 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 preferred_mac The preferred MAC address to use in the room, the NoPreferredMac tells + * the server to assign one for us. + */ + void SendJoinRequest(const std::string& nickname, + const MacAddress& preferred_mac = NoPreferredMac); + + /** + * 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 RakNet 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); - std::string nickname; ///< The nickname of this member. + /** + * Disconnects the RoomMember from the Room + */ + void Disconnect(); }; +// RoomMemberImpl +void RoomMember::RoomMemberImpl::SetState(const State new_state) { + state = new_state; + // TODO(B3N30): Invoke the callback functions +} + +bool RoomMember::RoomMemberImpl::IsConnected() const { + return state == State::Joining || state == State::Joined; +} + +void RoomMember::RoomMemberImpl::MemberLoop() { + // Receive packets while the connection is open + while (IsConnected()) { + std::lock_guard<std::mutex> 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 IdRoomInformation: + HandleRoomInformationPacket(&event); + break; + case IdJoinSuccess: + // 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 + SetState(State::Joined); + break; + case IdNameCollision: + SetState(State::NameCollision); + break; + case IdMacCollision: + SetState(State::MacCollision); + break; + case IdVersionMismatch: + SetState(State::WrongVersion); + break; + case IdCloseRoom: + SetState(State::LostConnection); + break; + } + enet_packet_destroy(event.packet); + break; + case ENET_EVENT_TYPE_DISCONNECT: + SetState(State::LostConnection); + break; + } + } + { + std::lock_guard<std::mutex> 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<std::mutex> lock(send_list_mutex); + send_list.push_back(std::move(packet)); +} + +void RoomMember::RoomMemberImpl::SendJoinRequest(const std::string& nickname, + const MacAddress& preferred_mac) { + Packet packet; + packet << static_cast<u8>(IdJoinRequest); + packet << nickname; + packet << preferred_mac; + packet << network_version; + 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)); // Igonore the message type + + RoomInformation info{}; + packet >> info.name; + packet >> info.member_slots; + room_information.name = info.name; + room_information.member_slots = info.member_slots; + + 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_name; + } + // TODO(B3N30): Invoke callbacks +} + +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)); // Igonore the message type + + // Parse the MAC Address from the packet + packet >> mac_address; + // TODO(B3N30): Invoke callbacks +} + +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)); // Igonore 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; + + u32 data_length; + packet >> data_length; + + packet >> wifi_packet.data; + + // TODO(B3N30): Invoke callbacks +} + +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.message; + // TODO(B3N30): Invoke callbacks +} + +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; + } + } + // didn't disconnect gracefully force disconnect + enet_peer_reset(server); + server = nullptr; +} + +// RoomMember RoomMember::RoomMember() : room_member_impl{std::make_unique<RoomMemberImpl>()} { room_member_impl->client = enet_host_create(nullptr, 1, NumChannels, 0, 0); ASSERT_MSG(room_member_impl->client != nullptr, "Could not create client"); @@ -34,17 +291,44 @@ 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 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 char* server_addr, u16 server_port, - u16 client_port) { + u16 client_port, const MacAddress& preferred_mac) { + // If the member is connected, kill the connection first + if (room_member_impl->loop_thread && room_member_impl->loop_thread->joinable()) { + room_member_impl->SetState(State::Error); + room_member_impl->loop_thread->join(); + room_member_impl->loop_thread.reset(); + } + // 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(); + } + 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->state = State::Error; + room_member_impl->SetState(State::Error); return; } @@ -52,23 +336,47 @@ void RoomMember::Join(const std::string& nick, const char* server_addr, u16 serv 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->state = State::Joining; - // TODO(B3N30): Send a join request with the nickname to the server - // TODO(B3N30): Start the receive thread + room_member_impl->SetState(State::Joining); + room_member_impl->StartLoop(); + room_member_impl->SendJoinRequest(nick, preferred_mac); } else { - room_member_impl->state = State::CouldNotConnect; + room_member_impl->SetState(State::CouldNotConnect); } } bool RoomMember::IsConnected() const { - return room_member_impl->state == State::Joining || room_member_impl->state == State::Joined; + 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::SendGameName(const std::string& game_name) { + Packet packet; + packet << static_cast<u8>(IdSetGameName); + packet << game_name; + room_member_impl->Send(std::move(packet)); } void RoomMember::Leave() { - enet_peer_disconnect(room_member_impl->server, 0); - room_member_impl->state = State::Idle; - // TODO(B3N30): Close the receive thread - enet_peer_reset(room_member_impl->server); + room_member_impl->SetState(State::Idle); + room_member_impl->loop_thread->join(); + room_member_impl->loop_thread.reset(); } } // namespace Network diff --git a/src/network/room_member.h b/src/network/room_member.h index 177622b69..bc1af3a7e 100644 --- a/src/network/room_member.h +++ b/src/network/room_member.h @@ -4,14 +4,32 @@ #pragma once -#include <atomic> #include <memory> #include <string> +#include <vector> #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 }; + 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. +}; + +/// Represents a chat message. +struct ChatEntry { + std::string nickname; ///< Nickname of the client who sent this message. + std::string message; ///< Body of the message. +}; + /** * 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 @@ -29,9 +47,18 @@ public: // Reasons why connection was rejected NameCollision, ///< Somebody is already using this name MacCollision, ///< Somebody is already using that mac-address + WrongVersion, ///< The room version is not the same as for this RoomMember CouldNotConnect ///< The room is not responding to a connection attempt }; + struct MemberInformation { + std::string nickname; ///< Nickname of the member. + std::string game_name; ///< 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>; + RoomMember(); ~RoomMember(); @@ -41,6 +68,26 @@ public: 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 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; @@ -50,7 +97,26 @@ public: * This may fail if the username is already taken. */ void Join(const std::string& nickname, const char* server_addr = "127.0.0.1", - const u16 serverPort = DefaultRoomPort, const u16 clientPort = 0); + const u16 serverPort = DefaultRoomPort, const u16 clientPort = 0, + const MacAddress& preferred_mac = NoPreferredMac); + + /** + * 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 name to the room. + * @param game_name The game name. + */ + void SendGameName(const std::string& game_name); /** * Leaves the current room. |