From c7160cb629086df2a32c7dcf4faed4761ec4393e Mon Sep 17 00:00:00 2001 From: =?utf8?q?Lo=C3=AFc=20Blot?= Date: Thu, 24 Aug 2017 08:28:54 +0200 Subject: [PATCH] Network cleanup (#6302) * Cleanup network headers * Move peerhandler to a specific header to reduce compilation times * Move socket.cpp/h to network folder * More work * Network code cleanups * Move socket.{cpp,h} to network folder * Move Address object to network/address.{cpp,h} * Move network exceptions to network/networkexceptions.h * Client: use unique_ptr for Connection * Server/ClientIface: use shared_ptr for Connection * Format fixes * Remove socket.cpp socket.h from clang-format whitelist * Also fix NetworkPacket code style & make it under clang-format --- src/CMakeLists.txt | 1 - src/client.cpp | 33 +- src/client.h | 16 +- src/client/clientlauncher.cpp | 1 + src/clientiface.cpp | 2 +- src/clientiface.h | 4 +- src/httpfetch.cpp | 4 +- src/main.cpp | 1 + src/network/CMakeLists.txt | 2 + src/network/address.cpp | 273 ++++++++++++ src/{socket.h => network/address.h} | 74 +--- src/network/clientpackethandler.cpp | 3 +- src/network/connection.cpp | 1 + src/network/connection.h | 131 +----- src/network/networkexceptions.h | 106 +++++ src/network/networkpacket.cpp | 2 +- src/network/networkpacket.h | 153 +++---- src/network/peerhandler.h | 73 +++ src/network/serverpackethandler.cpp | 39 +- src/network/socket.cpp | 363 +++++++++++++++ src/network/socket.h | 70 +++ src/server.cpp | 26 +- src/server.h | 10 +- src/socket.cpp | 590 ------------------------- src/unittest/test_connection.cpp | 2 +- src/unittest/test_socket.cpp | 2 +- util/travis/clang-format-whitelist.txt | 3 - 27 files changed, 1060 insertions(+), 925 deletions(-) create mode 100644 src/network/address.cpp rename src/{socket.h => network/address.h} (60%) create mode 100644 src/network/networkexceptions.h create mode 100644 src/network/peerhandler.h create mode 100644 src/network/socket.cpp create mode 100644 src/network/socket.h delete mode 100644 src/socket.cpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2e624dd7f..4e76f3b00 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -442,7 +442,6 @@ set(common_SRCS serverlist.cpp serverobject.cpp settings.cpp - socket.cpp sound.cpp staticobject.cpp subgame.cpp diff --git a/src/client.cpp b/src/client.cpp index ab0eddcdc..30c1ab4d5 100644 --- a/src/client.cpp +++ b/src/client.cpp @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include "client.h" #include "network/clientopcodes.h" +#include "network/connection.h" #include "network/networkpacket.h" #include "threading/mutex_auto_lock.h" #include "client/renderingengine.h" @@ -83,7 +84,7 @@ Client::Client( tsrc, this ), m_particle_manager(&m_env), - m_con(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this), + m_con(new con::Connection(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, this)), m_address_name(address_name), m_server_ser_ver(SER_FMT_VER_INVALID), m_last_chat_message_sent(time(NULL)), @@ -219,7 +220,7 @@ bool Client::isShutdown() Client::~Client() { m_shutdown = true; - m_con.Disconnect(); + m_con->Disconnect(); m_mesh_update_thread.stop(); m_mesh_update_thread.wait(); @@ -253,8 +254,8 @@ void Client::connect(Address address, bool is_local_server) initLocalMapSaving(address, m_address_name, is_local_server); - m_con.SetTimeoutMs(0); - m_con.Connect(address); + m_con->SetTimeoutMs(0); + m_con->Connect(address); } void Client::step(float dtime) @@ -787,7 +788,7 @@ void Client::Receive() { DSTACK(FUNCTION_NAME); NetworkPacket pkt; - m_con.Receive(&pkt); + m_con->Receive(&pkt); ProcessData(&pkt); } @@ -854,7 +855,7 @@ void Client::ProcessData(NetworkPacket *pkt) void Client::Send(NetworkPacket* pkt) { - m_con.Send(PEER_ID_SERVER, + m_con->Send(PEER_ID_SERVER, serverCommandFactoryTable[pkt->getCommand()].channel, pkt, serverCommandFactoryTable[pkt->getCommand()].reliable); @@ -1297,7 +1298,7 @@ void Client::sendPlayerPos() u16 our_peer_id; { //MutexAutoLock lock(m_con_mutex); //bulk comment-out - our_peer_id = m_con.GetPeerID(); + our_peer_id = m_con->GetPeerID(); } // Set peer id if not set already @@ -1319,7 +1320,7 @@ void Client::sendPlayerItem(u16 item) if(myplayer == NULL) return; - u16 our_peer_id = m_con.GetPeerID(); + u16 our_peer_id = m_con->GetPeerID(); // Set peer id if not set already if(myplayer->peer_id == PEER_ID_INEXISTENT) @@ -1658,6 +1659,16 @@ ClientEvent Client::getClientEvent() return event; } +bool Client::connectedToServer() +{ + return m_con->Connected(); +} + +const Address Client::getServerAddress() +{ + return m_con->GetPeerAddress(PEER_ID_SERVER); +} + float Client::mediaReceiveProgress() { if (m_media_downloader) @@ -1768,13 +1779,13 @@ void Client::afterContentReceived() float Client::getRTT() { - return m_con.getPeerStat(PEER_ID_SERVER,con::AVG_RTT); + return m_con->getPeerStat(PEER_ID_SERVER,con::AVG_RTT); } float Client::getCurRate() { - return (m_con.getLocalStat(con::CUR_INC_RATE) + - m_con.getLocalStat(con::CUR_DL_RATE)); + return (m_con->getLocalStat(con::CUR_INC_RATE) + + m_con->getLocalStat(con::CUR_DL_RATE)); } void Client::makeScreenshot() diff --git a/src/client.h b/src/client.h index 80f4cee40..2ee81ea09 100644 --- a/src/client.h +++ b/src/client.h @@ -19,7 +19,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -#include "network/connection.h" #include "clientenvironment.h" #include "irrlichttypes_extrabloated.h" #include @@ -36,6 +35,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mapnode.h" #include "tileanimation.h" #include "mesh_generator_thread.h" +#include "network/address.h" +#include "network/peerhandler.h" #include #define CLIENT_CHAT_MESSAGE_LIMIT_PER_10S 10.0f @@ -57,6 +58,9 @@ class Minimap; struct MinimapMapblock; class Camera; class NetworkPacket; +namespace con { +class Connection; +} enum LocalClientState { LC_Created, @@ -472,8 +476,7 @@ public: u8 getProtoVersion() { return m_proto_ver; } - bool connectedToServer() - { return m_con.Connected(); } + bool connectedToServer(); float mediaReceiveProgress(); @@ -539,10 +542,7 @@ public: void showGameFog(bool show = true); void showGameDebug(bool show = true); - const Address getServerAddress() - { - return m_con.GetPeerAddress(PEER_ID_SERVER); - } + const Address getServerAddress(); const std::string &getAddressName() const { @@ -611,7 +611,7 @@ private: MeshUpdateThread m_mesh_update_thread; ClientEnvironment m_env; ParticleManager m_particle_manager; - con::Connection m_con; + std::unique_ptr m_con; std::string m_address_name; Camera *m_camera = nullptr; Minimap *m_minimap = nullptr; diff --git a/src/client/clientlauncher.cpp b/src/client/clientlauncher.cpp index 3d5d14ae7..dbaba8040 100644 --- a/src/client/clientlauncher.cpp +++ b/src/client/clientlauncher.cpp @@ -33,6 +33,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "clientlauncher.h" #include "version.h" #include "renderingengine.h" +#include "network/networkexceptions.h" /* mainmenumanager.h */ diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 1402ee5c2..585c1cdc6 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -587,7 +587,7 @@ u64 RemoteClient::uptime() const return porting::getTimeS() - m_connection_time; } -ClientInterface::ClientInterface(con::Connection* con) +ClientInterface::ClientInterface(const std::shared_ptr & con) : m_con(con), m_env(NULL), diff --git a/src/clientiface.h b/src/clientiface.h index 3ee09317d..4d61ae74e 100644 --- a/src/clientiface.h +++ b/src/clientiface.h @@ -418,7 +418,7 @@ public: friend class Server; - ClientInterface(con::Connection* con); + ClientInterface(const std::shared_ptr &con); ~ClientInterface(); /* run sync step */ @@ -487,7 +487,7 @@ private: void UpdatePlayerList(); // Connection - con::Connection* m_con; + std::shared_ptr m_con; std::mutex m_clients_mutex; // Connected clients (behind the con mutex) RemoteClientMap m_clients; diff --git a/src/httpfetch.cpp b/src/httpfetch.cpp index c6419a5d6..6a9a5e235 100644 --- a/src/httpfetch.cpp +++ b/src/httpfetch.cpp @@ -17,15 +17,15 @@ with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ -#include "socket.h" // for select() -#include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf() #include "httpfetch.h" +#include "porting.h" // for sleep_ms(), get_sysinfo(), secure_rand_fill_buf() #include #include #include #include #include #include +#include "network/socket.h" // for select() #include "threading/event.h" #include "config.h" #include "exceptions.h" diff --git a/src/main.cpp b/src/main.cpp index c75c6a328..02a85136a 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -39,6 +39,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "config.h" #include "player.h" #include "porting.h" +#include "network/socket.h" #if USE_CURSES #include "terminal_chat_console.h" #endif diff --git a/src/network/CMakeLists.txt b/src/network/CMakeLists.txt index 3805c323d..44969105b 100644 --- a/src/network/CMakeLists.txt +++ b/src/network/CMakeLists.txt @@ -1,8 +1,10 @@ set(common_network_SRCS + ${CMAKE_CURRENT_SOURCE_DIR}/address.cpp ${CMAKE_CURRENT_SOURCE_DIR}/connection.cpp ${CMAKE_CURRENT_SOURCE_DIR}/networkpacket.cpp ${CMAKE_CURRENT_SOURCE_DIR}/serverpackethandler.cpp ${CMAKE_CURRENT_SOURCE_DIR}/serveropcodes.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/socket.cpp PARENT_SCOPE ) diff --git a/src/network/address.cpp b/src/network/address.cpp new file mode 100644 index 000000000..f698a2e91 --- /dev/null +++ b/src/network/address.cpp @@ -0,0 +1,273 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "address.h" + +#include +#include +#include +#include +#include +#include +#include +#include "network/networkexceptions.h" +#include "util/string.h" +#include "util/numeric.h" +#include "constants.h" +#include "debug.h" +#include "settings.h" +#include "log.h" + +#ifdef _WIN32 +// Without this some of the network functions are not found on mingw +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 +#endif +#include +#include +#include +#define LAST_SOCKET_ERR() WSAGetLastError() +typedef SOCKET socket_t; +typedef int socklen_t; +#else +#include +#include +#include +#include +#include +#include +#include +#define LAST_SOCKET_ERR() (errno) +typedef int socket_t; +#endif + +/* + Address +*/ + +Address::Address() +{ + memset(&m_address, 0, sizeof(m_address)); +} + +Address::Address(u32 address, u16 port) +{ + memset(&m_address, 0, sizeof(m_address)); + setAddress(address); + setPort(port); +} + +Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port) +{ + memset(&m_address, 0, sizeof(m_address)); + setAddress(a, b, c, d); + setPort(port); +} + +Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port) +{ + memset(&m_address, 0, sizeof(m_address)); + setAddress(ipv6_bytes); + setPort(port); +} + +// Equality (address family, address and port must be equal) +bool Address::operator==(const Address &address) +{ + if (address.m_addr_family != m_addr_family || address.m_port != m_port) + return false; + + if (m_addr_family == AF_INET) { + return m_address.ipv4.sin_addr.s_addr == + address.m_address.ipv4.sin_addr.s_addr; + } + + if (m_addr_family == AF_INET6) { + return memcmp(m_address.ipv6.sin6_addr.s6_addr, + address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0; + } + + return false; +} + +bool Address::operator!=(const Address &address) +{ + return !(*this == address); +} + +void Address::Resolve(const char *name) +{ + if (!name || name[0] == 0) { + if (m_addr_family == AF_INET) { + setAddress((u32)0); + } else if (m_addr_family == AF_INET6) { + setAddress((IPv6AddressBytes *)0); + } + return; + } + + struct addrinfo *resolved, hints; + memset(&hints, 0, sizeof(hints)); + + // Setup hints + hints.ai_socktype = 0; + hints.ai_protocol = 0; + hints.ai_flags = 0; + if (g_settings->getBool("enable_ipv6")) { + // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned + hints.ai_family = AF_UNSPEC; + } else { + hints.ai_family = AF_INET; + } + + // Do getaddrinfo() + int e = getaddrinfo(name, NULL, &hints, &resolved); + if (e != 0) + throw ResolveError(gai_strerror(e)); + + // Copy data + if (resolved->ai_family == AF_INET) { + struct sockaddr_in *t = (struct sockaddr_in *)resolved->ai_addr; + m_addr_family = AF_INET; + m_address.ipv4 = *t; + } else if (resolved->ai_family == AF_INET6) { + struct sockaddr_in6 *t = (struct sockaddr_in6 *)resolved->ai_addr; + m_addr_family = AF_INET6; + m_address.ipv6 = *t; + } else { + freeaddrinfo(resolved); + throw ResolveError(""); + } + freeaddrinfo(resolved); +} + +// IP address -> textual representation +std::string Address::serializeString() const +{ +// windows XP doesnt have inet_ntop, maybe use better func +#ifdef _WIN32 + if (m_addr_family == AF_INET) { + u8 a, b, c, d; + u32 addr; + addr = ntohl(m_address.ipv4.sin_addr.s_addr); + a = (addr & 0xFF000000) >> 24; + b = (addr & 0x00FF0000) >> 16; + c = (addr & 0x0000FF00) >> 8; + d = (addr & 0x000000FF); + return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d); + } else if (m_addr_family == AF_INET6) { + std::ostringstream os; + for (int i = 0; i < 16; i += 2) { + u16 section = (m_address.ipv6.sin6_addr.s6_addr[i] << 8) | + (m_address.ipv6.sin6_addr.s6_addr[i + 1]); + os << std::hex << section; + if (i < 14) + os << ":"; + } + return os.str(); + } else + return std::string(""); +#else + char str[INET6_ADDRSTRLEN]; + if (inet_ntop(m_addr_family, + (m_addr_family == AF_INET) + ? (void *)&(m_address.ipv4.sin_addr) + : (void *)&(m_address.ipv6.sin6_addr), + str, INET6_ADDRSTRLEN) == NULL) { + return std::string(""); + } + return std::string(str); +#endif +} + +struct sockaddr_in Address::getAddress() const +{ + return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort() +} + +struct sockaddr_in6 Address::getAddress6() const +{ + return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort() +} + +u16 Address::getPort() const +{ + return m_port; +} + +int Address::getFamily() const +{ + return m_addr_family; +} + +bool Address::isIPv6() const +{ + return m_addr_family == AF_INET6; +} + +bool Address::isZero() const +{ + if (m_addr_family == AF_INET) { + return m_address.ipv4.sin_addr.s_addr == 0; + } + + if (m_addr_family == AF_INET6) { + static const char zero[16] = {0}; + return memcmp(m_address.ipv6.sin6_addr.s6_addr, zero, 16) == 0; + } + return false; +} + +void Address::setAddress(u32 address) +{ + m_addr_family = AF_INET; + m_address.ipv4.sin_family = AF_INET; + m_address.ipv4.sin_addr.s_addr = htonl(address); +} + +void Address::setAddress(u8 a, u8 b, u8 c, u8 d) +{ + m_addr_family = AF_INET; + m_address.ipv4.sin_family = AF_INET; + u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d); + m_address.ipv4.sin_addr.s_addr = addr; +} + +void Address::setAddress(const IPv6AddressBytes *ipv6_bytes) +{ + m_addr_family = AF_INET6; + m_address.ipv6.sin6_family = AF_INET6; + if (ipv6_bytes) + memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16); + else + memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16); +} + +void Address::setPort(u16 port) +{ + m_port = port; +} + +void Address::print(std::ostream *s) const +{ + if (m_addr_family == AF_INET6) + *s << "[" << serializeString() << "]:" << m_port; + else + *s << serializeString() << ":" << m_port; +} diff --git a/src/socket.h b/src/network/address.h similarity index 60% rename from src/socket.h rename to src/network/address.h index 2264679ed..79ca21f8c 100644 --- a/src/socket.h +++ b/src/network/address.h @@ -21,52 +21,19 @@ with this program; if not, write to the Free Software Foundation, Inc., #ifdef _WIN32 #ifndef _WIN32_WINNT - #define _WIN32_WINNT 0x0501 +#define _WIN32_WINNT 0x0501 #endif - #include - #include - #include +#include +#include +#include #else - #include - #include +#include #endif #include #include #include "irrlichttypes.h" -#include "exceptions.h" - -extern bool socket_enable_debug_output; - -class SocketException : public BaseException -{ -public: - SocketException(const std::string &s): - BaseException(s) - { - } -}; - -class ResolveError : public BaseException -{ -public: - ResolveError(const std::string &s): - BaseException(s) - { - } -}; - -class SendFailedException : public BaseException -{ -public: - SendFailedException(const std::string &s): - BaseException(s) - { - } -}; - -void sockets_init(); -void sockets_cleanup(); +#include "networkexceptions.h" class IPv6AddressBytes { @@ -98,38 +65,13 @@ public: void setPort(unsigned short port); void print(std::ostream *s) const; std::string serializeString() const; + private: unsigned int m_addr_family = 0; union { - struct sockaddr_in ipv4; + struct sockaddr_in ipv4; struct sockaddr_in6 ipv6; } m_address; u16 m_port = 0; // Port is separate from sockaddr structures }; - -class UDPSocket -{ -public: - UDPSocket() = default; - - UDPSocket(bool ipv6); - ~UDPSocket(); - void Bind(Address addr); - - bool init(bool ipv6, bool noExceptions = false); - - //void Close(); - //bool IsOpen(); - void Send(const Address & destination, const void * data, int size); - // Returns -1 if there is no data - int Receive(Address & sender, void * data, int size); - int GetHandle(); // For debugging purposes only - void setTimeoutMs(int timeout_ms); - // Returns true if there is data, false if timeout occurred - bool WaitData(int timeout_ms); -private: - int m_handle; - int m_timeout_ms; - int m_addr_family; -}; diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 86bb88f61..4800ea87c 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -31,6 +31,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "server.h" #include "util/strfnd.h" #include "network/clientopcodes.h" +#include "network/connection.h" #include "script/scripting_client.h" #include "util/serialize.h" #include "util/srp.h" @@ -97,7 +98,7 @@ void Client::handleCommand_Hello(NetworkPacket* pkt) m_chosen_auth_mech = AUTH_MECHANISM_NONE; m_access_denied = true; m_access_denied_reason = "Unknown"; - m_con.Disconnect(); + m_con->Disconnect(); } } diff --git a/src/network/connection.cpp b/src/network/connection.cpp index 77ce34bfd..44e403611 100644 --- a/src/network/connection.cpp +++ b/src/network/connection.cpp @@ -24,6 +24,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "log.h" #include "porting.h" #include "network/networkpacket.h" +#include "network/peerhandler.h" #include "util/serialize.h" #include "util/numeric.h" #include "util/string.h" diff --git a/src/network/connection.h b/src/network/connection.h index c0a39f313..3d3a502aa 100644 --- a/src/network/connection.h +++ b/src/network/connection.h @@ -20,8 +20,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once #include "irrlichttypes_bloated.h" +#include "peerhandler.h" #include "socket.h" -#include "exceptions.h" #include "constants.h" #include "util/pointer.h" #include "util/container.h" @@ -37,89 +37,6 @@ class NetworkPacket; namespace con { -/* - Exceptions -*/ -class NotFoundException : public BaseException -{ -public: - NotFoundException(const char *s): - BaseException(s) - {} -}; - -class PeerNotFoundException : public BaseException -{ -public: - PeerNotFoundException(const char *s): - BaseException(s) - {} -}; - -class ConnectionException : public BaseException -{ -public: - ConnectionException(const char *s): - BaseException(s) - {} -}; - -class ConnectionBindFailed : public BaseException -{ -public: - ConnectionBindFailed(const char *s): - BaseException(s) - {} -}; - -class InvalidIncomingDataException : public BaseException -{ -public: - InvalidIncomingDataException(const char *s): - BaseException(s) - {} -}; - -class InvalidOutgoingDataException : public BaseException -{ -public: - InvalidOutgoingDataException(const char *s): - BaseException(s) - {} -}; - -class NoIncomingDataException : public BaseException -{ -public: - NoIncomingDataException(const char *s): - BaseException(s) - {} -}; - -class ProcessedSilentlyException : public BaseException -{ -public: - ProcessedSilentlyException(const char *s): - BaseException(s) - {} -}; - -class ProcessedQueued : public BaseException -{ -public: - ProcessedQueued(const char *s): - BaseException(s) - {} -}; - -class IncomingDataCorruption : public BaseException -{ -public: - IncomingDataCorruption(const char *s): - BaseException(s) - {} -}; - typedef enum MTProtocols { MTP_PRIMARY, MTP_UDP, @@ -566,41 +483,6 @@ private: class Peer; -enum PeerChangeType -{ - PEER_ADDED, - PEER_REMOVED -}; -struct PeerChange -{ - PeerChange(PeerChangeType t, u16 _peer_id, bool _timeout): - type(t), peer_id(_peer_id), timeout(_timeout) {} - PeerChange() = delete; - - PeerChangeType type; - u16 peer_id; - bool timeout; -}; - -class PeerHandler -{ -public: - - PeerHandler() = default; - virtual ~PeerHandler() = default; - - /* - This is called after the Peer has been inserted into the - Connection's peer container. - */ - virtual void peerAdded(Peer *peer) = 0; - /* - This is called before the Peer has been removed from the - Connection's peer container. - */ - virtual void deletingPeer(Peer *peer, bool timeout) = 0; -}; - class PeerHelper { public: @@ -620,15 +502,6 @@ private: class Connection; -typedef enum { - MIN_RTT, - MAX_RTT, - AVG_RTT, - MIN_JITTER, - MAX_JITTER, - AVG_JITTER -} rtt_stat_type; - typedef enum { CUR_DL_RATE, AVG_DL_RATE, @@ -974,6 +847,8 @@ private: Connection *m_connection = nullptr; }; +class PeerHandler; + class Connection { public: diff --git a/src/network/networkexceptions.h b/src/network/networkexceptions.h new file mode 100644 index 000000000..f4913928c --- /dev/null +++ b/src/network/networkexceptions.h @@ -0,0 +1,106 @@ +/* +Minetest +Copyright (C) 2013-2017 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#pragma once + +#include "exceptions.h" + +namespace con +{ +/* + Exceptions +*/ +class NotFoundException : public BaseException +{ +public: + NotFoundException(const char *s) : BaseException(s) {} +}; + +class PeerNotFoundException : public BaseException +{ +public: + PeerNotFoundException(const char *s) : BaseException(s) {} +}; + +class ConnectionException : public BaseException +{ +public: + ConnectionException(const char *s) : BaseException(s) {} +}; + +class ConnectionBindFailed : public BaseException +{ +public: + ConnectionBindFailed(const char *s) : BaseException(s) {} +}; + +class InvalidIncomingDataException : public BaseException +{ +public: + InvalidIncomingDataException(const char *s) : BaseException(s) {} +}; + +class InvalidOutgoingDataException : public BaseException +{ +public: + InvalidOutgoingDataException(const char *s) : BaseException(s) {} +}; + +class NoIncomingDataException : public BaseException +{ +public: + NoIncomingDataException(const char *s) : BaseException(s) {} +}; + +class ProcessedSilentlyException : public BaseException +{ +public: + ProcessedSilentlyException(const char *s) : BaseException(s) {} +}; + +class ProcessedQueued : public BaseException +{ +public: + ProcessedQueued(const char *s) : BaseException(s) {} +}; + +class IncomingDataCorruption : public BaseException +{ +public: + IncomingDataCorruption(const char *s) : BaseException(s) {} +}; +} + +class SocketException : public BaseException +{ +public: + SocketException(const std::string &s) : BaseException(s) {} +}; + +class ResolveError : public BaseException +{ +public: + ResolveError(const std::string &s) : BaseException(s) {} +}; + +class SendFailedException : public BaseException +{ +public: + SendFailedException(const std::string &s) : BaseException(s) {} +}; \ No newline at end of file diff --git a/src/network/networkpacket.cpp b/src/network/networkpacket.cpp index ab7ddfb57..d9dc51695 100644 --- a/src/network/networkpacket.cpp +++ b/src/network/networkpacket.cpp @@ -19,7 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "networkpacket.h" #include -#include "exceptions.h" +#include "networkexceptions.h" #include "util/serialize.h" NetworkPacket::NetworkPacket(u16 command, u32 datasize, u16 peer_id): diff --git a/src/network/networkpacket.h b/src/network/networkpacket.h index a4899d656..e3c52aab9 100644 --- a/src/network/networkpacket.h +++ b/src/network/networkpacket.h @@ -28,109 +28,112 @@ class NetworkPacket { public: - NetworkPacket(u16 command, u32 datasize, u16 peer_id); - NetworkPacket(u16 command, u32 datasize); - NetworkPacket() = default; + NetworkPacket(u16 command, u32 datasize, u16 peer_id); + NetworkPacket(u16 command, u32 datasize); + NetworkPacket() = default; - ~NetworkPacket(); + ~NetworkPacket(); - void putRawPacket(u8 *data, u32 datasize, u16 peer_id); + void putRawPacket(u8 *data, u32 datasize, u16 peer_id); - // Getters - u32 getSize() { return m_datasize; } - u16 getPeerId() { return m_peer_id; } - u16 getCommand() { return m_command; } - const u32 getRemainingBytes() const { return m_datasize - m_read_offset; } - const char* getRemainingString() { return getString(m_read_offset); } + // Getters + u32 getSize() { return m_datasize; } + u16 getPeerId() { return m_peer_id; } + u16 getCommand() { return m_command; } + const u32 getRemainingBytes() const { return m_datasize - m_read_offset; } + const char *getRemainingString() { return getString(m_read_offset); } - // Returns a c-string without copying. - // A better name for this would be getRawString() - const char* getString(u32 from_offset); - // major difference to putCString(): doesn't write len into the buffer - void putRawString(const char* src, u32 len); - void putRawString(const std::string &src) - { putRawString(src.c_str(), src.size()); } + // Returns a c-string without copying. + // A better name for this would be getRawString() + const char *getString(u32 from_offset); + // major difference to putCString(): doesn't write len into the buffer + void putRawString(const char *src, u32 len); + void putRawString(const std::string &src) + { + putRawString(src.c_str(), src.size()); + } - NetworkPacket& operator>>(std::string& dst); - NetworkPacket& operator<<(const std::string &src); + NetworkPacket &operator>>(std::string &dst); + NetworkPacket &operator<<(const std::string &src); - void putLongString(const std::string &src); + void putLongString(const std::string &src); - NetworkPacket& operator>>(std::wstring& dst); - NetworkPacket& operator<<(const std::wstring &src); + NetworkPacket &operator>>(std::wstring &dst); + NetworkPacket &operator<<(const std::wstring &src); - std::string readLongString(); + std::string readLongString(); - char getChar(u32 offset); - NetworkPacket& operator>>(char& dst); - NetworkPacket& operator<<(char src); + char getChar(u32 offset); + NetworkPacket &operator>>(char &dst); + NetworkPacket &operator<<(char src); - NetworkPacket& operator>>(bool& dst); - NetworkPacket& operator<<(bool src); + NetworkPacket &operator>>(bool &dst); + NetworkPacket &operator<<(bool src); - u8 getU8(u32 offset); + u8 getU8(u32 offset); - NetworkPacket& operator>>(u8& dst); - NetworkPacket& operator<<(u8 src); + NetworkPacket &operator>>(u8 &dst); + NetworkPacket &operator<<(u8 src); - u8* getU8Ptr(u32 offset); + u8 *getU8Ptr(u32 offset); - u16 getU16(u32 from_offset); - NetworkPacket& operator>>(u16& dst); - NetworkPacket& operator<<(u16 src); + u16 getU16(u32 from_offset); + NetworkPacket &operator>>(u16 &dst); + NetworkPacket &operator<<(u16 src); - NetworkPacket& operator>>(u32& dst); - NetworkPacket& operator<<(u32 src); + NetworkPacket &operator>>(u32 &dst); + NetworkPacket &operator<<(u32 src); - NetworkPacket& operator>>(u64& dst); - NetworkPacket& operator<<(u64 src); + NetworkPacket &operator>>(u64 &dst); + NetworkPacket &operator<<(u64 src); - NetworkPacket& operator>>(std::time_t& dst); - NetworkPacket& operator<<(std::time_t src); + NetworkPacket &operator>>(std::time_t &dst); + NetworkPacket &operator<<(std::time_t src); - NetworkPacket& operator>>(float& dst); - NetworkPacket& operator<<(float src); + NetworkPacket &operator>>(float &dst); + NetworkPacket &operator<<(float src); - NetworkPacket& operator>>(v2f& dst); - NetworkPacket& operator<<(v2f src); + NetworkPacket &operator>>(v2f &dst); + NetworkPacket &operator<<(v2f src); - NetworkPacket& operator>>(v3f& dst); - NetworkPacket& operator<<(v3f src); + NetworkPacket &operator>>(v3f &dst); + NetworkPacket &operator<<(v3f src); - NetworkPacket& operator>>(s16& dst); - NetworkPacket& operator<<(s16 src); + NetworkPacket &operator>>(s16 &dst); + NetworkPacket &operator<<(s16 src); - NetworkPacket& operator>>(s32& dst); - NetworkPacket& operator<<(s32 src); + NetworkPacket &operator>>(s32 &dst); + NetworkPacket &operator<<(s32 src); - NetworkPacket& operator>>(v2s32& dst); - NetworkPacket& operator<<(v2s32 src); + NetworkPacket &operator>>(v2s32 &dst); + NetworkPacket &operator<<(v2s32 src); - NetworkPacket& operator>>(v3s16& dst); - NetworkPacket& operator<<(v3s16 src); + NetworkPacket &operator>>(v3s16 &dst); + NetworkPacket &operator<<(v3s16 src); - NetworkPacket& operator>>(v3s32& dst); - NetworkPacket& operator<<(v3s32 src); + NetworkPacket &operator>>(v3s32 &dst); + NetworkPacket &operator<<(v3s32 src); - NetworkPacket& operator>>(video::SColor& dst); - NetworkPacket& operator<<(video::SColor src); + NetworkPacket &operator>>(video::SColor &dst); + NetworkPacket &operator<<(video::SColor src); + + // Temp, we remove SharedBuffer when migration finished + Buffer oldForgePacket(); - // Temp, we remove SharedBuffer when migration finished - Buffer oldForgePacket(); private: - void checkReadOffset(u32 from_offset, u32 field_size); - - inline void checkDataSize(u32 field_size) - { - if (m_read_offset + field_size > m_datasize) { - m_datasize = m_read_offset + field_size; - m_data.resize(m_datasize); - } + void checkReadOffset(u32 from_offset, u32 field_size); + + inline void checkDataSize(u32 field_size) + { + if (m_read_offset + field_size > m_datasize) { + m_datasize = m_read_offset + field_size; + m_data.resize(m_datasize); } + } - std::vector m_data; - u32 m_datasize = 0; - u32 m_read_offset = 0; - u16 m_command = 0; - u16 m_peer_id = 0; + std::vector m_data; + u32 m_datasize = 0; + u32 m_read_offset = 0; + u16 m_command = 0; + u16 m_peer_id = 0; }; diff --git a/src/network/peerhandler.h b/src/network/peerhandler.h new file mode 100644 index 000000000..b7ac9d64d --- /dev/null +++ b/src/network/peerhandler.h @@ -0,0 +1,73 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#pragma once + +namespace con +{ + +typedef enum { + MIN_RTT, + MAX_RTT, + AVG_RTT, + MIN_JITTER, + MAX_JITTER, + AVG_JITTER +} rtt_stat_type; + +class Peer; + +class PeerHandler +{ +public: + PeerHandler() = default; + + virtual ~PeerHandler() = default; + + /* + This is called after the Peer has been inserted into the + Connection's peer container. + */ + virtual void peerAdded(Peer *peer) = 0; + + /* + This is called before the Peer has been removed from the + Connection's peer container. + */ + virtual void deletingPeer(Peer *peer, bool timeout) = 0; +}; + +enum PeerChangeType +{ + PEER_ADDED, + PEER_REMOVED +}; +struct PeerChange +{ + PeerChange(PeerChangeType t, u16 _peer_id, bool _timeout) + : type(t), peer_id(_peer_id), timeout(_timeout) + { + } + PeerChange() = delete; + + PeerChangeType type; + u16 peer_id; + bool timeout; +}; +} diff --git a/src/network/serverpackethandler.cpp b/src/network/serverpackethandler.cpp index ecc166d1e..09e04674c 100644 --- a/src/network/serverpackethandler.cpp +++ b/src/network/serverpackethandler.cpp @@ -30,6 +30,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "settings.h" #include "tool.h" #include "version.h" +#include "network/connection.h" #include "network/networkprotocol.h" #include "network/serveropcodes.h" #include "util/auth.h" @@ -686,7 +687,7 @@ void Server::handleCommand_ClientReady(NetworkPacket* pkt) actionstream << "TOSERVER_CLIENT_READY stage 2 client init failed for peer_id: " << peer_id << std::endl; - m_con.DisconnectPeer(peer_id); + m_con->DisconnectPeer(peer_id); return; } @@ -695,7 +696,7 @@ void Server::handleCommand_ClientReady(NetworkPacket* pkt) errorstream << "TOSERVER_CLIENT_READY client sent inconsistent data, disconnecting peer_id: " << peer_id << std::endl; - m_con.DisconnectPeer(peer_id); + m_con->DisconnectPeer(peer_id); return; } @@ -830,7 +831,7 @@ void Server::handleCommand_PlayerPos(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -839,7 +840,7 @@ void Server::handleCommand_PlayerPos(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -891,7 +892,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -900,7 +901,7 @@ void Server::handleCommand_InventoryAction(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1072,7 +1073,7 @@ void Server::handleCommand_ChatMessage(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1100,7 +1101,7 @@ void Server::handleCommand_Damage(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1109,7 +1110,7 @@ void Server::handleCommand_Damage(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1166,7 +1167,7 @@ void Server::handleCommand_Password(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1219,7 +1220,7 @@ void Server::handleCommand_PlayerItem(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1228,7 +1229,7 @@ void Server::handleCommand_PlayerItem(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1246,7 +1247,7 @@ void Server::handleCommand_Respawn(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1299,7 +1300,7 @@ void Server::handleCommand_Interact(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1308,7 +1309,7 @@ void Server::handleCommand_Interact(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1738,7 +1739,7 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1747,7 +1748,7 @@ void Server::handleCommand_NodeMetaFields(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1789,7 +1790,7 @@ void Server::handleCommand_InventoryFields(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } @@ -1798,7 +1799,7 @@ void Server::handleCommand_InventoryFields(NetworkPacket* pkt) errorstream << "Server::ProcessData(): Canceling: " "No player object for peer_id=" << pkt->getPeerId() << " disconnecting peer!" << std::endl; - m_con.DisconnectPeer(pkt->getPeerId()); + m_con->DisconnectPeer(pkt->getPeerId()); return; } diff --git a/src/network/socket.cpp b/src/network/socket.cpp new file mode 100644 index 000000000..053013606 --- /dev/null +++ b/src/network/socket.cpp @@ -0,0 +1,363 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#include "socket.h" + +#include +#include +#include +#include +#include +#include +#include +#include "util/string.h" +#include "util/numeric.h" +#include "constants.h" +#include "debug.h" +#include "settings.h" +#include "log.h" + +#ifdef _WIN32 +// Without this some of the network functions are not found on mingw +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 +#endif +#include +#include +#include +#define LAST_SOCKET_ERR() WSAGetLastError() +typedef SOCKET socket_t; +typedef int socklen_t; +#else +#include +#include +#include +#include +#include +#include +#include +#define LAST_SOCKET_ERR() (errno) +typedef int socket_t; +#endif + +// Set to true to enable verbose debug output +bool socket_enable_debug_output = false; // yuck + +static bool g_sockets_initialized = false; + +// Initialize sockets +void sockets_init() +{ +#ifdef _WIN32 + // Windows needs sockets to be initialized before use + WSADATA WsaData; + if (WSAStartup(MAKEWORD(2, 2), &WsaData) != NO_ERROR) + throw SocketException("WSAStartup failed"); +#endif + g_sockets_initialized = true; +} + +void sockets_cleanup() +{ +#ifdef _WIN32 + // On Windows, cleanup sockets after use + WSACleanup(); +#endif +} + +/* + UDPSocket +*/ + +UDPSocket::UDPSocket(bool ipv6) +{ + init(ipv6, false); +} + +bool UDPSocket::init(bool ipv6, bool noExceptions) +{ + if (!g_sockets_initialized) { + dstream << "Sockets not initialized" << std::endl; + return false; + } + + // Use IPv6 if specified + m_addr_family = ipv6 ? AF_INET6 : AF_INET; + m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP); + + if (socket_enable_debug_output) { + dstream << "UDPSocket(" << (int)m_handle + << ")::UDPSocket(): ipv6 = " << (ipv6 ? "true" : "false") + << std::endl; + } + + if (m_handle <= 0) { + if (noExceptions) { + return false; + } + + throw SocketException(std::string("Failed to create socket: error ") + + itos(LAST_SOCKET_ERR())); + } + + setTimeoutMs(0); + + return true; +} + +UDPSocket::~UDPSocket() +{ + if (socket_enable_debug_output) { + dstream << "UDPSocket( " << (int)m_handle << ")::~UDPSocket()" + << std::endl; + } + +#ifdef _WIN32 + closesocket(m_handle); +#else + close(m_handle); +#endif +} + +void UDPSocket::Bind(Address addr) +{ + if (socket_enable_debug_output) { + dstream << "UDPSocket(" << (int)m_handle + << ")::Bind(): " << addr.serializeString() << ":" + << addr.getPort() << std::endl; + } + + if (addr.getFamily() != m_addr_family) { + static const char *errmsg = + "Socket and bind address families do not match"; + errorstream << "Bind failed: " << errmsg << std::endl; + throw SocketException(errmsg); + } + + if (m_addr_family == AF_INET6) { + struct sockaddr_in6 address; + memset(&address, 0, sizeof(address)); + + address = addr.getAddress6(); + address.sin6_family = AF_INET6; + address.sin6_port = htons(addr.getPort()); + + if (bind(m_handle, (const struct sockaddr *)&address, + sizeof(struct sockaddr_in6)) < 0) { + dstream << (int)m_handle << ": Bind failed: " << strerror(errno) + << std::endl; + throw SocketException("Failed to bind socket"); + } + } else { + struct sockaddr_in address; + memset(&address, 0, sizeof(address)); + + address = addr.getAddress(); + address.sin_family = AF_INET; + address.sin_port = htons(addr.getPort()); + + if (bind(m_handle, (const struct sockaddr *)&address, + sizeof(struct sockaddr_in)) < 0) { + dstream << (int)m_handle << ": Bind failed: " << strerror(errno) + << std::endl; + throw SocketException("Failed to bind socket"); + } + } +} + +void UDPSocket::Send(const Address &destination, const void *data, int size) +{ + bool dumping_packet = false; // for INTERNET_SIMULATOR + + if (INTERNET_SIMULATOR) + dumping_packet = myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0; + + if (socket_enable_debug_output) { + // Print packet destination and size + dstream << (int)m_handle << " -> "; + destination.print(&dstream); + dstream << ", size=" << size; + + // Print packet contents + dstream << ", data="; + for (int i = 0; i < size && i < 20; i++) { + if (i % 2 == 0) + dstream << " "; + unsigned int a = ((const unsigned char *)data)[i]; + dstream << std::hex << std::setw(2) << std::setfill('0') << a; + } + + if (size > 20) + dstream << "..."; + + if (dumping_packet) + dstream << " (DUMPED BY INTERNET_SIMULATOR)"; + + dstream << std::endl; + } + + if (dumping_packet) { + // Lol let's forget it + dstream << "UDPSocket::Send(): INTERNET_SIMULATOR: dumping packet." + << std::endl; + return; + } + + if (destination.getFamily() != m_addr_family) + throw SendFailedException("Address family mismatch"); + + int sent; + if (m_addr_family == AF_INET6) { + struct sockaddr_in6 address = destination.getAddress6(); + address.sin6_port = htons(destination.getPort()); + sent = sendto(m_handle, (const char *)data, size, 0, + (struct sockaddr *)&address, sizeof(struct sockaddr_in6)); + } else { + struct sockaddr_in address = destination.getAddress(); + address.sin_port = htons(destination.getPort()); + sent = sendto(m_handle, (const char *)data, size, 0, + (struct sockaddr *)&address, sizeof(struct sockaddr_in)); + } + + if (sent != size) + throw SendFailedException("Failed to send packet"); +} + +int UDPSocket::Receive(Address &sender, void *data, int size) +{ + // Return on timeout + if (!WaitData(m_timeout_ms)) + return -1; + + int received; + if (m_addr_family == AF_INET6) { + struct sockaddr_in6 address; + memset(&address, 0, sizeof(address)); + socklen_t address_len = sizeof(address); + + received = recvfrom(m_handle, (char *)data, size, 0, + (struct sockaddr *)&address, &address_len); + + if (received < 0) + return -1; + + u16 address_port = ntohs(address.sin6_port); + IPv6AddressBytes bytes; + memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16); + sender = Address(&bytes, address_port); + } else { + struct sockaddr_in address; + memset(&address, 0, sizeof(address)); + + socklen_t address_len = sizeof(address); + + received = recvfrom(m_handle, (char *)data, size, 0, + (struct sockaddr *)&address, &address_len); + + if (received < 0) + return -1; + + u32 address_ip = ntohl(address.sin_addr.s_addr); + u16 address_port = ntohs(address.sin_port); + + sender = Address(address_ip, address_port); + } + + if (socket_enable_debug_output) { + // Print packet sender and size + dstream << (int)m_handle << " <- "; + sender.print(&dstream); + dstream << ", size=" << received; + + // Print packet contents + dstream << ", data="; + for (int i = 0; i < received && i < 20; i++) { + if (i % 2 == 0) + dstream << " "; + unsigned int a = ((const unsigned char *)data)[i]; + dstream << std::hex << std::setw(2) << std::setfill('0') << a; + } + if (received > 20) + dstream << "..."; + + dstream << std::endl; + } + + return received; +} + +int UDPSocket::GetHandle() +{ + return m_handle; +} + +void UDPSocket::setTimeoutMs(int timeout_ms) +{ + m_timeout_ms = timeout_ms; +} + +bool UDPSocket::WaitData(int timeout_ms) +{ + fd_set readset; + int result; + + // Initialize the set + FD_ZERO(&readset); + FD_SET(m_handle, &readset); + + // Initialize time out struct + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = timeout_ms * 1000; + + // select() + result = select(m_handle + 1, &readset, NULL, NULL, &tv); + + if (result == 0) + return false; + + if (result < 0 && (errno == EINTR || errno == EBADF)) { + // N.B. select() fails when sockets are destroyed on Connection's dtor + // with EBADF. Instead of doing tricky synchronization, allow this + // thread to exit but don't throw an exception. + return false; + } + + if (result < 0) { + dstream << m_handle << ": Select failed: " << strerror(errno) + << std::endl; + +#ifdef _WIN32 + int e = WSAGetLastError(); + dstream << (int)m_handle << ": WSAGetLastError()=" << e << std::endl; + if (e == 10004 /* WSAEINTR */ || e == 10009 /* WSAEBADF */) { + infostream << "Ignoring WSAEINTR/WSAEBADF." << std::endl; + return false; + } +#endif + + throw SocketException("Select failed"); + } else if (!FD_ISSET(m_handle, &readset)) { + // No data + return false; + } + + // There is data + return true; +} diff --git a/src/network/socket.h b/src/network/socket.h new file mode 100644 index 000000000..e0e76f4c2 --- /dev/null +++ b/src/network/socket.h @@ -0,0 +1,70 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +*/ + +#pragma once + +#ifdef _WIN32 +#ifndef _WIN32_WINNT +#define _WIN32_WINNT 0x0501 +#endif +#include +#include +#include +#else +#include +#include +#endif + +#include +#include +#include "address.h" +#include "irrlichttypes.h" +#include "networkexceptions.h" + +extern bool socket_enable_debug_output; + +void sockets_init(); +void sockets_cleanup(); + +class UDPSocket +{ +public: + UDPSocket() = default; + + UDPSocket(bool ipv6); + ~UDPSocket(); + void Bind(Address addr); + + bool init(bool ipv6, bool noExceptions = false); + + // void Close(); + // bool IsOpen(); + void Send(const Address &destination, const void *data, int size); + // Returns -1 if there is no data + int Receive(Address &sender, void *data, int size); + int GetHandle(); // For debugging purposes only + void setTimeoutMs(int timeout_ms); + // Returns true if there is data, false if timeout occurred + bool WaitData(int timeout_ms); + +private: + int m_handle; + int m_timeout_ms; + int m_addr_family; +}; diff --git a/src/server.cpp b/src/server.cpp index 7d9cfbf59..5c09aee4d 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include "network/connection.h" #include "network/networkprotocol.h" #include "network/serveropcodes.h" #include "ban.h" @@ -157,17 +158,17 @@ Server::Server( m_simple_singleplayer_mode(simple_singleplayer_mode), m_dedicated(dedicated), m_async_fatal_error(""), - m_con(PROTOCOL_ID, + m_con(std::make_shared(PROTOCOL_ID, 512, CONNECTION_TIMEOUT, ipv6, - this), + this)), m_itemdef(createItemDefManager()), m_nodedef(createNodeDefManager()), m_craftdef(createCraftDefManager()), m_event(new EventManager()), m_uptime(0), - m_clients(&m_con), + m_clients(m_con), m_admin_chat(iface) { m_lag = g_settings->getFloat("dedicated_server_step"); @@ -377,8 +378,8 @@ void Server::start(Address bind_addr) m_thread->stop(); // Initialize connection - m_con.SetTimeoutMs(30); - m_con.Serve(bind_addr); + m_con->SetTimeoutMs(30); + m_con->Serve(bind_addr); // Start thread m_thread->start(); @@ -983,7 +984,7 @@ void Server::Receive() u16 peer_id; try { NetworkPacket pkt; - m_con.Receive(&pkt); + m_con->Receive(&pkt); peer_id = pkt.getPeerId(); ProcessData(&pkt); } catch (const con::InvalidIncomingDataException &e) { @@ -1308,7 +1309,7 @@ void Server::deletingPeer(con::Peer *peer, bool timeout) bool Server::getClientConInfo(u16 peer_id, con::rtt_stat_type type, float* retval) { - *retval = m_con.getPeerStat(peer_id,type); + *retval = m_con->getPeerStat(peer_id,type); return *retval != -1; } @@ -2623,7 +2624,7 @@ void Server::DenyAccessVerCompliant(u16 peer_id, u16 proto_ver, AccessDeniedCode } m_clients.event(peer_id, CSE_SetDenied); - m_con.DisconnectPeer(peer_id); + m_con->DisconnectPeer(peer_id); } @@ -2633,7 +2634,7 @@ void Server::DenyAccess(u16 peer_id, AccessDeniedCode reason, const std::string SendAccessDenied(peer_id, reason, custom_reason); m_clients.event(peer_id, CSE_SetDenied); - m_con.DisconnectPeer(peer_id); + m_con->DisconnectPeer(peer_id); } // 13/03/15: remove this function when protocol version 25 will become @@ -2644,7 +2645,7 @@ void Server::DenyAccess_Legacy(u16 peer_id, const std::wstring &reason) SendAccessDenied_Legacy(peer_id, reason); m_clients.event(peer_id, CSE_SetDenied); - m_con.DisconnectPeer(peer_id); + m_con->DisconnectPeer(peer_id); } void Server::acceptAuth(u16 peer_id, bool forSudoMode) @@ -3156,6 +3157,11 @@ const std::string& Server::hudGetHotbarSelectedImage(RemotePlayer *player) const return player->getHotbarSelectedImage(); } +Address Server::getPeerAddress(u16 peer_id) +{ + return m_con->GetPeerAddress(peer_id); +} + bool Server::setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed) { diff --git a/src/server.h b/src/server.h index eeb134a5c..ab1660bf2 100644 --- a/src/server.h +++ b/src/server.h @@ -19,7 +19,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once -#include "network/connection.h" #include "irr_v3d.h" #include "map.h" #include "hud.h" @@ -29,6 +28,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "inventorymanager.h" #include "subgame.h" #include "tileanimation.h" // struct TileAnimationParams +#include "network/peerhandler.h" +#include "network/address.h" #include "util/numeric.h" #include "util/thread.h" #include "util/basic_macros.h" @@ -291,8 +292,7 @@ public: void hudSetHotbarSelectedImage(RemotePlayer *player, std::string name); const std::string &hudGetHotbarSelectedImage(RemotePlayer *player) const; - inline Address getPeerAddress(u16 peer_id) - { return m_con.GetPeerAddress(peer_id); } + Address getPeerAddress(u16 peer_id); bool setLocalPlayerAnimations(RemotePlayer *player, v2s32 animation_frames[4], f32 frame_speed); @@ -320,7 +320,7 @@ public: void DenyAccess(u16 peer_id, AccessDeniedCode reason, const std::string &custom_reason=""); void acceptAuth(u16 peer_id, bool forSudoMode); void DenyAccess_Legacy(u16 peer_id, const std::wstring &reason); - bool getClientConInfo(u16 peer_id, con::rtt_stat_type type,float* retval); + bool getClientConInfo(u16 peer_id, con::rtt_stat_type type, float* retval); bool getClientInfo(u16 peer_id,ClientState* state, u32* uptime, u8* ser_vers, u16* prot_vers, u8* major, u8* minor, u8* patch, std::string* vers_string); @@ -506,7 +506,7 @@ private: ServerEnvironment *m_env = nullptr; // server connection - con::Connection m_con; + std::shared_ptr m_con; // Ban checking BanManager *m_banmanager = nullptr; diff --git a/src/socket.cpp b/src/socket.cpp deleted file mode 100644 index 205c7e8f8..000000000 --- a/src/socket.cpp +++ /dev/null @@ -1,590 +0,0 @@ -/* -Minetest -Copyright (C) 2013 celeron55, Perttu Ahola - -This program is free software; you can redistribute it and/or modify -it under the terms of the GNU Lesser General Public License as published by -the Free Software Foundation; either version 2.1 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public License along -with this program; if not, write to the Free Software Foundation, Inc., -51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -*/ - -#include "socket.h" - -#include -#include -#include -#include -#include -#include -#include -#include "util/string.h" -#include "util/numeric.h" -#include "constants.h" -#include "debug.h" -#include "settings.h" -#include "log.h" - -#ifdef _WIN32 - // Without this some of the network functions are not found on mingw - #ifndef _WIN32_WINNT - #define _WIN32_WINNT 0x0501 - #endif - #include - #include - #include - #define LAST_SOCKET_ERR() WSAGetLastError() - typedef SOCKET socket_t; - typedef int socklen_t; -#else - #include - #include - #include - #include - #include - #include - #include - #define LAST_SOCKET_ERR() (errno) - typedef int socket_t; -#endif - -// Set to true to enable verbose debug output -bool socket_enable_debug_output = false; // yuck - -static bool g_sockets_initialized = false; - -// Initialize sockets -void sockets_init() -{ -#ifdef _WIN32 - // Windows needs sockets to be initialized before use - WSADATA WsaData; - if(WSAStartup( MAKEWORD(2,2), &WsaData ) != NO_ERROR) - throw SocketException("WSAStartup failed"); -#endif - g_sockets_initialized = true; -} - -void sockets_cleanup() -{ -#ifdef _WIN32 - // On Windows, cleanup sockets after use - WSACleanup(); -#endif -} - -/* - Address -*/ - -Address::Address() -{ - memset(&m_address, 0, sizeof(m_address)); -} - -Address::Address(u32 address, u16 port) -{ - memset(&m_address, 0, sizeof(m_address)); - setAddress(address); - setPort(port); -} - -Address::Address(u8 a, u8 b, u8 c, u8 d, u16 port) -{ - memset(&m_address, 0, sizeof(m_address)); - setAddress(a, b, c, d); - setPort(port); -} - -Address::Address(const IPv6AddressBytes *ipv6_bytes, u16 port) -{ - memset(&m_address, 0, sizeof(m_address)); - setAddress(ipv6_bytes); - setPort(port); -} - -// Equality (address family, address and port must be equal) -bool Address::operator==(const Address &address) -{ - if (address.m_addr_family != m_addr_family || address.m_port != m_port) - return false; - - if (m_addr_family == AF_INET) { - return m_address.ipv4.sin_addr.s_addr == - address.m_address.ipv4.sin_addr.s_addr; - } - - if (m_addr_family == AF_INET6) { - return memcmp(m_address.ipv6.sin6_addr.s6_addr, - address.m_address.ipv6.sin6_addr.s6_addr, 16) == 0; - } - - return false; -} - -bool Address::operator!=(const Address &address) -{ - return !(*this == address); -} - -void Address::Resolve(const char *name) -{ - if (!name || name[0] == 0) { - if (m_addr_family == AF_INET) { - setAddress((u32) 0); - } else if (m_addr_family == AF_INET6) { - setAddress((IPv6AddressBytes*) 0); - } - return; - } - - struct addrinfo *resolved, hints; - memset(&hints, 0, sizeof(hints)); - - // Setup hints - hints.ai_socktype = 0; - hints.ai_protocol = 0; - hints.ai_flags = 0; - if(g_settings->getBool("enable_ipv6")) - { - // AF_UNSPEC allows both IPv6 and IPv4 addresses to be returned - hints.ai_family = AF_UNSPEC; - } - else - { - hints.ai_family = AF_INET; - } - - // Do getaddrinfo() - int e = getaddrinfo(name, NULL, &hints, &resolved); - if(e != 0) - throw ResolveError(gai_strerror(e)); - - // Copy data - if(resolved->ai_family == AF_INET) - { - struct sockaddr_in *t = (struct sockaddr_in *) resolved->ai_addr; - m_addr_family = AF_INET; - m_address.ipv4 = *t; - } - else if(resolved->ai_family == AF_INET6) - { - struct sockaddr_in6 *t = (struct sockaddr_in6 *) resolved->ai_addr; - m_addr_family = AF_INET6; - m_address.ipv6 = *t; - } - else - { - freeaddrinfo(resolved); - throw ResolveError(""); - } - freeaddrinfo(resolved); -} - -// IP address -> textual representation -std::string Address::serializeString() const -{ -// windows XP doesnt have inet_ntop, maybe use better func -#ifdef _WIN32 - if(m_addr_family == AF_INET) - { - u8 a, b, c, d; - u32 addr; - addr = ntohl(m_address.ipv4.sin_addr.s_addr); - a = (addr & 0xFF000000) >> 24; - b = (addr & 0x00FF0000) >> 16; - c = (addr & 0x0000FF00) >> 8; - d = (addr & 0x000000FF); - return itos(a) + "." + itos(b) + "." + itos(c) + "." + itos(d); - } - else if(m_addr_family == AF_INET6) - { - std::ostringstream os; - for(int i = 0; i < 16; i += 2) - { - u16 section = - (m_address.ipv6.sin6_addr.s6_addr[i] << 8) | - (m_address.ipv6.sin6_addr.s6_addr[i + 1]); - os << std::hex << section; - if(i < 14) - os << ":"; - } - return os.str(); - } - else - return std::string(""); -#else - char str[INET6_ADDRSTRLEN]; - if (inet_ntop(m_addr_family, (m_addr_family == AF_INET) ? (void*)&(m_address.ipv4.sin_addr) : (void*)&(m_address.ipv6.sin6_addr), str, INET6_ADDRSTRLEN) == NULL) { - return std::string(""); - } - return std::string(str); -#endif -} - -struct sockaddr_in Address::getAddress() const -{ - return m_address.ipv4; // NOTE: NO PORT INCLUDED, use getPort() -} - -struct sockaddr_in6 Address::getAddress6() const -{ - return m_address.ipv6; // NOTE: NO PORT INCLUDED, use getPort() -} - -u16 Address::getPort() const -{ - return m_port; -} - -int Address::getFamily() const -{ - return m_addr_family; -} - -bool Address::isIPv6() const -{ - return m_addr_family == AF_INET6; -} - -bool Address::isZero() const -{ - if (m_addr_family == AF_INET) { - return m_address.ipv4.sin_addr.s_addr == 0; - } - - if (m_addr_family == AF_INET6) { - static const char zero[16] = {0}; - return memcmp(m_address.ipv6.sin6_addr.s6_addr, - zero, 16) == 0; - } - return false; -} - -void Address::setAddress(u32 address) -{ - m_addr_family = AF_INET; - m_address.ipv4.sin_family = AF_INET; - m_address.ipv4.sin_addr.s_addr = htonl(address); -} - -void Address::setAddress(u8 a, u8 b, u8 c, u8 d) -{ - m_addr_family = AF_INET; - m_address.ipv4.sin_family = AF_INET; - u32 addr = htonl((a << 24) | (b << 16) | (c << 8) | d); - m_address.ipv4.sin_addr.s_addr = addr; -} - -void Address::setAddress(const IPv6AddressBytes *ipv6_bytes) -{ - m_addr_family = AF_INET6; - m_address.ipv6.sin6_family = AF_INET6; - if (ipv6_bytes) - memcpy(m_address.ipv6.sin6_addr.s6_addr, ipv6_bytes->bytes, 16); - else - memset(m_address.ipv6.sin6_addr.s6_addr, 0, 16); -} - -void Address::setPort(u16 port) -{ - m_port = port; -} - -void Address::print(std::ostream *s) const -{ - if(m_addr_family == AF_INET6) - *s << "[" << serializeString() << "]:" << m_port; - else - *s << serializeString() << ":" << m_port; -} - -/* - UDPSocket -*/ - -UDPSocket::UDPSocket(bool ipv6) -{ - init(ipv6, false); -} - -bool UDPSocket::init(bool ipv6, bool noExceptions) -{ - if (!g_sockets_initialized) { - dstream << "Sockets not initialized" << std::endl; - return false; - } - - // Use IPv6 if specified - m_addr_family = ipv6 ? AF_INET6 : AF_INET; - m_handle = socket(m_addr_family, SOCK_DGRAM, IPPROTO_UDP); - - if (socket_enable_debug_output) { - dstream << "UDPSocket(" << (int) m_handle - << ")::UDPSocket(): ipv6 = " - << (ipv6 ? "true" : "false") - << std::endl; - } - - if (m_handle <= 0) { - if (noExceptions) { - return false; - } - - throw SocketException(std::string("Failed to create socket: error ") - + itos(LAST_SOCKET_ERR())); - } - - setTimeoutMs(0); - - return true; -} - - -UDPSocket::~UDPSocket() -{ - if (socket_enable_debug_output) { - dstream << "UDPSocket( " << (int) m_handle << ")::~UDPSocket()" - << std::endl; - } - -#ifdef _WIN32 - closesocket(m_handle); -#else - close(m_handle); -#endif -} - -void UDPSocket::Bind(Address addr) -{ - if(socket_enable_debug_output) { - dstream << "UDPSocket(" << (int) m_handle << ")::Bind(): " - << addr.serializeString() << ":" - << addr.getPort() << std::endl; - } - - if (addr.getFamily() != m_addr_family) { - static const char *errmsg = "Socket and bind address families do not match"; - errorstream << "Bind failed: " << errmsg << std::endl; - throw SocketException(errmsg); - } - - if(m_addr_family == AF_INET6) { - struct sockaddr_in6 address; - memset(&address, 0, sizeof(address)); - - address = addr.getAddress6(); - address.sin6_family = AF_INET6; - address.sin6_port = htons(addr.getPort()); - - if(bind(m_handle, (const struct sockaddr *) &address, - sizeof(struct sockaddr_in6)) < 0) { - dstream << (int) m_handle << ": Bind failed: " - << strerror(errno) << std::endl; - throw SocketException("Failed to bind socket"); - } - } else { - struct sockaddr_in address; - memset(&address, 0, sizeof(address)); - - address = addr.getAddress(); - address.sin_family = AF_INET; - address.sin_port = htons(addr.getPort()); - - if (bind(m_handle, (const struct sockaddr *) &address, - sizeof(struct sockaddr_in)) < 0) { - dstream << (int)m_handle << ": Bind failed: " - << strerror(errno) << std::endl; - throw SocketException("Failed to bind socket"); - } - } -} - -void UDPSocket::Send(const Address & destination, const void * data, int size) -{ - bool dumping_packet = false; // for INTERNET_SIMULATOR - - if(INTERNET_SIMULATOR) - dumping_packet = myrand() % INTERNET_SIMULATOR_PACKET_LOSS == 0; - - if(socket_enable_debug_output) { - // Print packet destination and size - dstream << (int)m_handle << " -> "; - destination.print(&dstream); - dstream << ", size=" << size; - - // Print packet contents - dstream << ", data="; - for(int i = 0; i < size && i < 20; i++) { - if(i % 2 == 0) - dstream << " "; - unsigned int a = ((const unsigned char *)data)[i]; - dstream << std::hex << std::setw(2) << std::setfill('0') << a; - } - - if(size > 20) - dstream << "..."; - - if(dumping_packet) - dstream << " (DUMPED BY INTERNET_SIMULATOR)"; - - dstream << std::endl; - } - - if(dumping_packet) { - // Lol let's forget it - dstream << "UDPSocket::Send(): INTERNET_SIMULATOR: dumping packet." - << std::endl; - return; - } - - if(destination.getFamily() != m_addr_family) - throw SendFailedException("Address family mismatch"); - - int sent; - if(m_addr_family == AF_INET6) { - struct sockaddr_in6 address = destination.getAddress6(); - address.sin6_port = htons(destination.getPort()); - sent = sendto(m_handle, (const char *)data, size, - 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in6)); - } else { - struct sockaddr_in address = destination.getAddress(); - address.sin_port = htons(destination.getPort()); - sent = sendto(m_handle, (const char *)data, size, - 0, (struct sockaddr *)&address, sizeof(struct sockaddr_in)); - } - - if(sent != size) - throw SendFailedException("Failed to send packet"); -} - -int UDPSocket::Receive(Address & sender, void *data, int size) -{ - // Return on timeout - if (!WaitData(m_timeout_ms)) - return -1; - - int received; - if (m_addr_family == AF_INET6) { - struct sockaddr_in6 address; - memset(&address, 0, sizeof(address)); - socklen_t address_len = sizeof(address); - - received = recvfrom(m_handle, (char *) data, - size, 0, (struct sockaddr *) &address, &address_len); - - if(received < 0) - return -1; - - u16 address_port = ntohs(address.sin6_port); - IPv6AddressBytes bytes; - memcpy(bytes.bytes, address.sin6_addr.s6_addr, 16); - sender = Address(&bytes, address_port); - } else { - struct sockaddr_in address; - memset(&address, 0, sizeof(address)); - - socklen_t address_len = sizeof(address); - - received = recvfrom(m_handle, (char *)data, - size, 0, (struct sockaddr *)&address, &address_len); - - if(received < 0) - return -1; - - u32 address_ip = ntohl(address.sin_addr.s_addr); - u16 address_port = ntohs(address.sin_port); - - sender = Address(address_ip, address_port); - } - - if (socket_enable_debug_output) { - // Print packet sender and size - dstream << (int) m_handle << " <- "; - sender.print(&dstream); - dstream << ", size=" << received; - - // Print packet contents - dstream << ", data="; - for(int i = 0; i < received && i < 20; i++) { - if(i % 2 == 0) - dstream << " "; - unsigned int a = ((const unsigned char *) data)[i]; - dstream << std::hex << std::setw(2) << std::setfill('0') << a; - } - if(received > 20) - dstream << "..."; - - dstream << std::endl; - } - - return received; -} - -int UDPSocket::GetHandle() -{ - return m_handle; -} - -void UDPSocket::setTimeoutMs(int timeout_ms) -{ - m_timeout_ms = timeout_ms; -} - -bool UDPSocket::WaitData(int timeout_ms) -{ - fd_set readset; - int result; - - // Initialize the set - FD_ZERO(&readset); - FD_SET(m_handle, &readset); - - // Initialize time out struct - struct timeval tv; - tv.tv_sec = 0; - tv.tv_usec = timeout_ms * 1000; - - // select() - result = select(m_handle+1, &readset, NULL, NULL, &tv); - - if (result == 0) - return false; - - if (result < 0 && (errno == EINTR || errno == EBADF)) { - // N.B. select() fails when sockets are destroyed on Connection's dtor - // with EBADF. Instead of doing tricky synchronization, allow this - // thread to exit but don't throw an exception. - return false; - } - - if (result < 0) { - dstream << m_handle << ": Select failed: " << strerror(errno) << std::endl; - -#ifdef _WIN32 - int e = WSAGetLastError(); - dstream << (int) m_handle << ": WSAGetLastError()=" - << e << std::endl; - if (e == 10004 /* WSAEINTR */ || e == 10009 /* WSAEBADF */) { - infostream << "Ignoring WSAEINTR/WSAEBADF." << std::endl; - return false; - } -#endif - - throw SocketException("Select failed"); - } else if (!FD_ISSET(m_handle, &readset)) { - // No data - return false; - } - - // There is data - return true; -} diff --git a/src/unittest/test_connection.cpp b/src/unittest/test_connection.cpp index c23d2a068..5a2e32ca8 100644 --- a/src/unittest/test_connection.cpp +++ b/src/unittest/test_connection.cpp @@ -20,11 +20,11 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "test.h" #include "log.h" -#include "socket.h" #include "settings.h" #include "util/serialize.h" #include "network/connection.h" #include "network/networkpacket.h" +#include "network/socket.h" class TestConnection : public TestBase { public: diff --git a/src/unittest/test_socket.cpp b/src/unittest/test_socket.cpp index 33e568e79..6d5cf334d 100644 --- a/src/unittest/test_socket.cpp +++ b/src/unittest/test_socket.cpp @@ -20,8 +20,8 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "test.h" #include "log.h" -#include "socket.h" #include "settings.h" +#include "network/socket.h" class TestSocket : public TestBase { public: diff --git a/util/travis/clang-format-whitelist.txt b/util/travis/clang-format-whitelist.txt index 9883134d1..f55835656 100644 --- a/util/travis/clang-format-whitelist.txt +++ b/util/travis/clang-format-whitelist.txt @@ -172,7 +172,6 @@ src/network/clientpackethandler.cpp src/network/connection.cpp src/network/connection.h src/network/networkpacket.cpp -src/network/networkpacket.h src/network/networkprotocol.h src/network/serveropcodes.cpp src/network/serveropcodes.h @@ -304,8 +303,6 @@ src/settings_translation_file.cpp src/shader.cpp src/shader.h src/sky.cpp -src/socket.cpp -src/socket.h src/sound.cpp src/sound_openal.cpp src/sound_openal.h -- 2.25.1