diff options
Diffstat (limited to 'src/network')
-rw-r--r-- | src/network/CMakeLists.txt | 2 | ||||
-rw-r--r-- | src/network/address.cpp | 273 | ||||
-rw-r--r-- | src/network/address.h | 77 | ||||
-rw-r--r-- | src/network/clientpackethandler.cpp | 3 | ||||
-rw-r--r-- | src/network/connection.cpp | 1 | ||||
-rw-r--r-- | src/network/connection.h | 131 | ||||
-rw-r--r-- | src/network/networkexceptions.h | 106 | ||||
-rw-r--r-- | src/network/networkpacket.cpp | 2 | ||||
-rw-r--r-- | src/network/networkpacket.h | 153 | ||||
-rw-r--r-- | src/network/peerhandler.h | 73 | ||||
-rw-r--r-- | src/network/serverpackethandler.cpp | 39 | ||||
-rw-r--r-- | src/network/socket.cpp | 363 | ||||
-rw-r--r-- | src/network/socket.h | 70 |
13 files changed, 1069 insertions, 224 deletions
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 <celeron55@gmail.com> + +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 <cstdio> +#include <iostream> +#include <cstdlib> +#include <cstring> +#include <cerrno> +#include <sstream> +#include <iomanip> +#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 <windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> +#define LAST_SOCKET_ERR() WSAGetLastError() +typedef SOCKET socket_t; +typedef int socklen_t; +#else +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <fcntl.h> +#include <netdb.h> +#include <unistd.h> +#include <arpa/inet.h> +#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/network/address.h b/src/network/address.h new file mode 100644 index 000000000..79ca21f8c --- /dev/null +++ b/src/network/address.h @@ -0,0 +1,77 @@ +/* +Minetest +Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com> + +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 <windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> +#else +#include <netinet/in.h> +#endif + +#include <ostream> +#include <cstring> +#include "irrlichttypes.h" +#include "networkexceptions.h" + +class IPv6AddressBytes +{ +public: + u8 bytes[16]; + IPv6AddressBytes() { memset(bytes, 0, 16); } +}; + +class Address +{ +public: + Address(); + Address(u32 address, u16 port); + Address(u8 a, u8 b, u8 c, u8 d, u16 port); + Address(const IPv6AddressBytes *ipv6_bytes, u16 port); + bool operator==(const Address &address); + bool operator!=(const Address &address); + // Resolve() may throw ResolveError (address is unchanged in this case) + void Resolve(const char *name); + struct sockaddr_in getAddress() const; + unsigned short getPort() const; + void setAddress(u32 address); + void setAddress(u8 a, u8 b, u8 c, u8 d); + void setAddress(const IPv6AddressBytes *ipv6_bytes); + struct sockaddr_in6 getAddress6() const; + int getFamily() const; + bool isIPv6() const; + bool isZero() const; + 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_in6 ipv6; + } m_address; + u16 m_port = 0; // Port is separate from sockaddr structures +}; 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: @@ -621,15 +503,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, CUR_INC_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 <celeron55@gmail.com> + +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 <sstream> -#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<u8> oldForgePacket(); - // Temp, we remove SharedBuffer when migration finished - Buffer<u8> 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<u8> m_data; - u32 m_datasize = 0; - u32 m_read_offset = 0; - u16 m_command = 0; - u16 m_peer_id = 0; + std::vector<u8> 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 <celeron55@gmail.com> + +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 <celeron55@gmail.com> + +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 <cstdio> +#include <iostream> +#include <cstdlib> +#include <cstring> +#include <cerrno> +#include <sstream> +#include <iomanip> +#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 <windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> +#define LAST_SOCKET_ERR() WSAGetLastError() +typedef SOCKET socket_t; +typedef int socklen_t; +#else +#include <sys/types.h> +#include <sys/socket.h> +#include <netinet/in.h> +#include <fcntl.h> +#include <netdb.h> +#include <unistd.h> +#include <arpa/inet.h> +#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 <celeron55@gmail.com> + +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 <windows.h> +#include <winsock2.h> +#include <ws2tcpip.h> +#else +#include <sys/socket.h> +#include <netinet/in.h> +#endif + +#include <ostream> +#include <cstring> +#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; +}; |