OpenTTD Source: src/network/core/tcp.h Source File

OpenTTD Source 15.0-RC2

tcp.h
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
12#ifndef NETWORK_CORE_TCP_H
13#define NETWORK_CORE_TCP_H
14
15#include "address.h"
16#include "packet.h"
17
18#include <atomic>
19#include <chrono>
20#include <thread>
21
23 enum SendPacketsState : uint8_t {
24 SPS_CLOSED,
25 SPS_NONE_SENT,
26 SPS_PARTLY_SENT,
27 SPS_ALL_SENT,
28};
29
31 class NetworkTCPSocketHandler : public NetworkSocketHandler {
32private:
33 std::deque<std::unique_ptr<Packet>> packet_queue{};
34 std::unique_ptr<Packet> packet_recv = nullptr;
35
36 void EmptyPacketQueue();
37public:
38 SOCKET sock = INVALID_SOCKET;
39 bool writable = false;
40
45 bool IsConnected() const { return this->sock != INVALID_SOCKET; }
46
47 virtual NetworkRecvStatus CloseConnection(bool error = true);
48 void CloseSocket();
49
50 virtual void SendPacket(std::unique_ptr<Packet> &&packet);
51 SendPacketsState SendPackets(bool closing_down = false);
52
53 virtual std::unique_ptr<Packet> ReceivePacket();
54
55 bool CanSendReceive();
56
61 bool HasSendQueue() { return !this->packet_queue.empty(); }
62
67 NetworkTCPSocketHandler(SOCKET s = INVALID_SOCKET) : sock(s) {}
68 ~NetworkTCPSocketHandler();
69};
70
74 class TCPConnecter {
75private:
83 enum class Status : uint8_t {
84 Init,
85 Resolving,
86 Failure,
87 Connecting,
88 Connected,
89 };
90
91 std::thread resolve_thread;
92 std::atomic<Status> status = Status::Init;
93 std::atomic<bool> killed = false;
94
95 addrinfo *ai = nullptr;
96 std::vector<addrinfo *> addresses;
97 std::map<SOCKET, NetworkAddress> sock_to_address;
98 size_t current_address = 0;
99
100 std::vector<SOCKET> sockets;
101 std::chrono::steady_clock::time_point last_attempt;
102
103 std::string connection_string;
104 NetworkAddress bind_address;
105 int family = AF_UNSPEC;
106
107 static std::vector<std::shared_ptr<TCPConnecter>> connecters;
108
109 void Resolve();
110 void OnResolved(addrinfo *ai);
111 bool TryNextAddress();
112 void Connect(addrinfo *address);
113 virtual bool CheckActivity();
114
115 /* We do not want any other derived classes from this class being able to
116 * access these private members, but it is okay for TCPServerConnecter. */
117 friend class TCPServerConnecter;
118
119 static void ResolveThunk(TCPConnecter *connecter);
120
121public:
122 TCPConnecter() {};
123 TCPConnecter(std::string_view connection_string, uint16_t default_port, const NetworkAddress &bind_address = {}, int family = AF_UNSPEC);
124 virtual ~TCPConnecter();
125
130 virtual void OnConnect([[maybe_unused]] SOCKET s) {}
131
135 virtual void OnFailure() {}
136
137 void Kill();
138
139 static void CheckCallbacks();
140 static void KillAll();
141
148 template <class T, typename... Args>
149 static std::shared_ptr<TCPConnecter> Create(Args&& ... args)
150 {
151 return TCPConnecter::connecters.emplace_back(std::make_shared<T>(std::forward<Args>(args)...));
152 }
153};
154
155 class TCPServerConnecter : public TCPConnecter {
156private:
157 SOCKET socket = INVALID_SOCKET;
158
159 bool CheckActivity() override;
160
161public:
162 ServerAddress server_address;
163
164 TCPServerConnecter(std::string_view connection_string, uint16_t default_port);
165
166 void SetConnected(SOCKET sock);
167 void SetFailure();
168};
169
170#endif /* NETWORK_CORE_TCP_H */
address.h
Wrapper for network addresses.
NetworkAddress
Wrapper for (un)resolved network addresses; there's no reason to transform a numeric IP to a string a...
Definition address.h:28
NetworkSocketHandler
SocketHandler for all network sockets in OpenTTD.
Definition core.h:43
NetworkTCPSocketHandler
Base socket handler for all TCP sockets.
Definition tcp.h:31
NetworkTCPSocketHandler::packet_queue
std::deque< std::unique_ptr< Packet > > packet_queue
Packets that are awaiting delivery. Cannot be std::queue as that does not have a clear() function.
Definition tcp.h:33
NetworkTCPSocketHandler::CloseConnection
virtual NetworkRecvStatus CloseConnection(bool error=true)
This will put this socket handler in a close state.
Definition tcp.cpp:41
NetworkTCPSocketHandler::ReceivePacket
virtual std::unique_ptr< Packet > ReceivePacket()
Receives a packet for the given client.
Definition tcp.cpp:119
NetworkTCPSocketHandler::IsConnected
bool IsConnected() const
Whether this socket is currently bound to a socket.
Definition tcp.h:45
NetworkTCPSocketHandler::NetworkTCPSocketHandler
NetworkTCPSocketHandler(SOCKET s=INVALID_SOCKET)
Construct a socket handler for a TCP connection.
Definition tcp.h:67
NetworkTCPSocketHandler::sock
SOCKET sock
The socket currently connected to.
Definition tcp.h:38
NetworkTCPSocketHandler::writable
bool writable
Can we write to this socket?
Definition tcp.h:39
NetworkTCPSocketHandler::SendPacket
virtual void SendPacket(std::unique_ptr< Packet > &&packet)
This function puts the packet in the send-queue and it is send as soon as possible.
Definition tcp.cpp:58
NetworkTCPSocketHandler::SendPackets
SendPacketsState SendPackets(bool closing_down=false)
Sends all the buffered packets out for this client.
Definition tcp.cpp:76
NetworkTCPSocketHandler::CloseSocket
void CloseSocket()
Close the actual socket of the connection.
Definition tcp.cpp:29
NetworkTCPSocketHandler::CanSendReceive
bool CanSendReceive()
Check whether this socket can send or receive something.
Definition tcp.cpp:194
NetworkTCPSocketHandler::packet_recv
std::unique_ptr< Packet > packet_recv
Partially received packet.
Definition tcp.h:34
NetworkTCPSocketHandler::HasSendQueue
bool HasSendQueue()
Whether there is something pending in the send queue.
Definition tcp.h:61
ServerAddress
Address to a game server.
Definition address.h:184
TCPConnecter
"Helper" class for creating TCP connections in a non-blocking manner
Definition tcp.h:74
TCPConnecter::bind_address
NetworkAddress bind_address
Address we're binding to, if any.
Definition tcp.h:104
TCPConnecter::Kill
void Kill()
Kill this connecter.
Definition tcp_connect.cpp:78
TCPConnecter::last_attempt
std::chrono::steady_clock::time_point last_attempt
Time we last tried to connect.
Definition tcp.h:101
TCPConnecter::status
std::atomic< Status > status
The current status of the connecter.
Definition tcp.h:92
TCPConnecter::connection_string
std::string connection_string
Current address we are connecting to (before resolving).
Definition tcp.h:103
TCPConnecter::connecters
static std::vector< std::shared_ptr< TCPConnecter > > connecters
List of connections that are currently being created.
Definition tcp.h:107
TCPConnecter::sockets
std::vector< SOCKET > sockets
Pending connect() attempts.
Definition tcp.h:100
TCPConnecter::CheckCallbacks
static void CheckCallbacks()
Check whether we need to call the callback, i.e.
Definition tcp_connect.cpp:462
TCPConnecter::Create
static std::shared_ptr< TCPConnecter > Create(Args &&... args)
Create the connecter, and initiate connecting by putting it in the collection of TCP connections to m...
Definition tcp.h:149
TCPConnecter::current_address
size_t current_address
Current index in addresses we are trying.
Definition tcp.h:98
TCPConnecter::Resolve
void Resolve()
Start resolving the hostname.
Definition tcp_connect.cpp:220
TCPConnecter::OnFailure
virtual void OnFailure()
Callback for when the connection attempt failed.
Definition tcp.h:135
TCPConnecter::OnResolved
void OnResolved(addrinfo *ai)
Callback when resolving is done.
Definition tcp_connect.cpp:148
TCPConnecter::CheckActivity
virtual bool CheckActivity()
Check if there was activity for this connecter.
Definition tcp_connect.cpp:270
TCPConnecter::sock_to_address
std::map< SOCKET, NetworkAddress > sock_to_address
Mapping of a socket to the real address it is connecting to. USed for DEBUG statements.
Definition tcp.h:97
TCPConnecter::ResolveThunk
static void ResolveThunk(TCPConnecter *connecter)
Thunk to start Resolve() on the right instance.
Definition tcp_connect.cpp:261
TCPConnecter::addresses
std::vector< addrinfo * > addresses
Addresses we can connect to.
Definition tcp.h:96
TCPConnecter::resolve_thread
std::thread resolve_thread
Thread used during resolving.
Definition tcp.h:91
TCPConnecter::KillAll
static void KillAll()
Kill all connection attempts.
Definition tcp_connect.cpp:471
TCPConnecter::TryNextAddress
bool TryNextAddress()
Start the connect() for the next address in the list.
Definition tcp_connect.cpp:134
TCPConnecter::killed
std::atomic< bool > killed
Whether this connecter is marked as killed.
Definition tcp.h:93
TCPConnecter::Status
Status
The current status of the connecter.
Definition tcp.h:83
TCPConnecter::Status::Connected
@ Connected
The connection is established.
TCPConnecter::Status::Resolving
@ Resolving
The hostname is being resolved (threaded).
TCPConnecter::Status::Init
@ Init
TCPConnecter is created but resolving hasn't started.
TCPConnecter::Status::Failure
@ Failure
Resolving failed.
TCPConnecter::Status::Connecting
@ Connecting
We are currently connecting.
TCPConnecter::OnConnect
virtual void OnConnect(SOCKET s)
Callback when the connection succeeded.
Definition tcp.h:130
TCPConnecter::Connect
void Connect(addrinfo *address)
Start a connection to the indicated address.
Definition tcp_connect.cpp:88
TCPConnecter::ai
addrinfo * ai
getaddrinfo() allocated linked-list of resolved addresses.
Definition tcp.h:95
TCPConnecter::family
int family
Family we are using to connect with.
Definition tcp.h:105
TCPServerConnecter
Definition tcp.h:155
TCPServerConnecter::SetConnected
void SetConnected(SOCKET sock)
The connection was successfully established.
Definition tcp_connect.cpp:440
TCPServerConnecter::CheckActivity
bool CheckActivity() override
Check if there was activity for this connecter.
Definition tcp_connect.cpp:405
TCPServerConnecter::server_address
ServerAddress server_address
Address we are connecting to.
Definition tcp.h:162
TCPServerConnecter::SetFailure
void SetFailure()
The connection couldn't be established.
Definition tcp_connect.cpp:451
TCPServerConnecter::socket
SOCKET socket
The socket when a connection is established.
Definition tcp.h:157
NetworkRecvStatus
NetworkRecvStatus
Status of a network client; reasons why a client has quit.
Definition core.h:23
packet.h
Basic functions to create, fill and read packets.
SendPacketsState
SendPacketsState
The states of sending the packets.
Definition tcp.h:23
SPS_PARTLY_SENT
@ SPS_PARTLY_SENT
The packets are partly sent; there are more packets to be sent in the queue.
Definition tcp.h:26
SPS_ALL_SENT
@ SPS_ALL_SENT
All packets in the queue are sent.
Definition tcp.h:27
SPS_NONE_SENT
@ SPS_NONE_SENT
The buffer is still full, so no (parts of) packets could be sent.
Definition tcp.h:25
SPS_CLOSED
@ SPS_CLOSED
The connection got closed.
Definition tcp.h:24