aboutsummaryrefslogtreecommitdiff
path: root/src/transports/winsock/winsock.cpp
blob: f989847260be8cb43bc57fa6cdfb8353ae2c7eaa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// Copyright Epic Games, Inc. All Rights Reserved.

#include <inttypes.h>
#include <atomic>
#include <charconv>
#include <exception>
#include <future>
#include <memory>
#include <optional>
#include <thread>

#include <zenbase/concepts.h>
#include <zenbase/refcount.h>

#ifndef _WIN32_WINNT
#	define _WIN32_WINNT 0x0A00
#endif

ZEN_THIRD_PARTY_INCLUDES_START
#include <WS2tcpip.h>
#include <WinSock2.h>
#include <windows.h>
ZEN_THIRD_PARTY_INCLUDES_END

#include <transportplugin.h>

//////////////////////////////////////////////////////////////////////////

template<Integral T>
std::optional<T>
ParseInt(const std::string_view& Input)
{
	T							 Out	= 0;
	const std::from_chars_result Result = std::from_chars(Input.data(), Input.data() + Input.size(), Out);
	if (Result.ec == std::errc::invalid_argument || Result.ec == std::errc::result_out_of_range)
	{
		return std::nullopt;
	}
	return Out;
}

//////////////////////////////////////////////////////////////////////////

using namespace zen;

class WinsockTransportPlugin : public TransportPlugin, zen::RefCounted
{
public:
	WinsockTransportPlugin();
	~WinsockTransportPlugin();

	// TransportPlugin implementation

	virtual uint32_t	AddRef() const override;
	virtual uint32_t	Release() const override;
	virtual void		Configure(const char* OptionTag, const char* OptionValue) override;
	virtual void		Initialize(TransportServer* ServerInterface) override;
	virtual void		Shutdown() override;
	virtual const char* GetDebugName() override;
	virtual bool		IsAvailable() override;

private:
	TransportServer* m_ServerInterface = nullptr;
	bool			 m_IsOk			   = true;
	uint16_t		 m_BasePort		   = 0;

	SOCKET						   m_ListenSocket{};
	std::thread					   m_AcceptThread;
	std::atomic_flag			   m_KeepRunning;
	std::vector<std::future<void>> m_Connections;
};

struct WinsockTransportConnection : public TransportConnection
{
public:
	WinsockTransportConnection();
	~WinsockTransportConnection();

	void Initialize(TransportServerConnection* ServerConnection, SOCKET ClientSocket);
	void HandleConnection();

	// TransportConnection implementation

	virtual int64_t		WriteBytes(const void* Buffer, size_t DataSize) override;
	virtual void		Shutdown(bool Receive, bool Transmit) override;
	virtual void		CloseConnection() override;
	virtual const char* GetDebugName() override;

private:
	zen::Ref<TransportServerConnection> m_ConnectionHandler;
	SOCKET								m_ClientSocket{};
	bool								m_IsTerminated = false;
};

//////////////////////////////////////////////////////////////////////////

WinsockTransportConnection::WinsockTransportConnection()
{
}

WinsockTransportConnection::~WinsockTransportConnection()
{
}

void
WinsockTransportConnection::Initialize(TransportServerConnection* ServerConnection, SOCKET ClientSocket)
{
	// ZEN_ASSERT(!m_ConnectionHandler);

	m_ConnectionHandler = ServerConnection;
	m_ClientSocket		= ClientSocket;
}

void
WinsockTransportConnection::HandleConnection()
{
	// ZEN_ASSERT(m_ConnectionHandler);

	const int				   InputBufferSize = 64 * 1024;
	std::unique_ptr<uint8_t[]> InputBuffer{new uint8_t[64 * 1024]};

	do
	{
		const int RecvBytes = recv(m_ClientSocket, (char*)InputBuffer.get(), InputBufferSize, /* flags */ 0);

		if (RecvBytes == 0)
		{
			// Connection closed
			return CloseConnection();
		}
		else if (RecvBytes < 0)
		{
			// Error
			return CloseConnection();
		}

		m_ConnectionHandler->OnBytesRead(InputBuffer.get(), RecvBytes);
	} while (m_ClientSocket);
}

void
WinsockTransportConnection::CloseConnection()
{
	if (m_IsTerminated)
	{
		return;
	}

	// ZEN_ASSERT(m_ClientSocket);
	m_IsTerminated = true;

	shutdown(m_ClientSocket, SD_BOTH);	// We won't be sending or receiving any more data

	closesocket(m_ClientSocket);
	m_ClientSocket = 0;
}

const char*
WinsockTransportConnection::GetDebugName()
{
	return nullptr;
}

int64_t
WinsockTransportConnection::WriteBytes(const void* Buffer, size_t DataSize)
{
	const uint8_t* BufferCursor	  = reinterpret_cast<const uint8_t*>(Buffer);
	int64_t		   TotalBytesSent = 0;

	while (DataSize)
	{
		const int MaxBlockSize	= 128 * 1024;
		const int SendBlockSize = (DataSize > MaxBlockSize) ? MaxBlockSize : (int)DataSize;
		const int SentBytes		= send(m_ClientSocket, (const char*)BufferCursor, SendBlockSize, /* flags */ 0);

		if (SentBytes < 0)
		{
			// Error
			return SentBytes;
		}

		BufferCursor += SentBytes;
		DataSize -= SentBytes;
		TotalBytesSent += SentBytes;
	}

	return TotalBytesSent;
}

void
WinsockTransportConnection::Shutdown(bool Receive, bool Transmit)
{
	if (Receive)
	{
		if (Transmit)
		{
			shutdown(m_ClientSocket, SD_BOTH);
		}
		else
		{
			shutdown(m_ClientSocket, SD_RECEIVE);
		}
	}
	else if (Transmit)
	{
		shutdown(m_ClientSocket, SD_SEND);
	}
}

//////////////////////////////////////////////////////////////////////////

WinsockTransportPlugin::WinsockTransportPlugin()
{
#if ZEN_PLATFORM_WINDOWS
	WSADATA wsaData;
	if (int Result = WSAStartup(0x202, &wsaData); Result != 0)
	{
		m_IsOk = false;
		WSACleanup();
	}
#endif
}

WinsockTransportPlugin::~WinsockTransportPlugin()
{
	Shutdown();

#if ZEN_PLATFORM_WINDOWS
	if (m_IsOk)
	{
		WSACleanup();
	}
#endif
}

uint32_t
WinsockTransportPlugin::AddRef() const
{
	return RefCounted::AddRef();
}

uint32_t
WinsockTransportPlugin::Release() const
{
	return RefCounted::Release();
}

void
WinsockTransportPlugin::Configure(const char* OptionTag, const char* OptionValue)
{
	using namespace std::literals;

	if (OptionTag == "port"sv)
	{
		if (auto PortNum = ParseInt<uint16_t>(OptionValue))
		{
			m_BasePort = *PortNum;
		}
	}
	else
	{
		// Unknown configuration option
	}
}

void
WinsockTransportPlugin::Initialize(TransportServer* ServerInterface)
{
	uint16_t Port = m_BasePort;

	m_ServerInterface = ServerInterface;
	m_ListenSocket	  = socket(AF_INET6, SOCK_STREAM, 0);

	if (m_ListenSocket == SOCKET_ERROR || m_ListenSocket == INVALID_SOCKET)
	{
		throw std::system_error(std::error_code(WSAGetLastError(), std::system_category()),
								"socket creation failed in HTTP plugin server init");
	}

	sockaddr_in6 Server{};
	Server.sin6_family = AF_INET6;
	Server.sin6_port   = htons(Port);
	Server.sin6_addr   = in6addr_any;

	if (int Result = bind(m_ListenSocket, (sockaddr*)&Server, sizeof(Server)); Result == SOCKET_ERROR)
	{
		throw std::system_error(std::error_code(WSAGetLastError(), std::system_category()), "bind call failed in HTTP plugin server init");
	}

	if (int Result = listen(m_ListenSocket, AF_INET6); Result == SOCKET_ERROR)
	{
		throw std::system_error(std::error_code(WSAGetLastError(), std::system_category()),
								"listen call failed in HTTP plugin server init");
	}

	m_KeepRunning.test_and_set();

	m_AcceptThread = std::thread([&] {
		// SetCurrentThreadName("http_plugin_acceptor");

		// ZEN_INFO("HTTP plugin server waiting for connections");

		do
		{
			if (SOCKET ClientSocket = accept(m_ListenSocket, NULL, NULL); ClientSocket != SOCKET_ERROR)
			{
				int Flag = 1;
				setsockopt(ClientSocket, IPPROTO_TCP, TCP_NODELAY, (char*)&Flag, sizeof(Flag));

				// Handle new connection
				WinsockTransportConnection* Connection = new WinsockTransportConnection();
				TransportServerConnection*	ConnectionInterface{m_ServerInterface->CreateConnectionHandler(Connection)};
				Connection->Initialize(ConnectionInterface, ClientSocket);

				m_Connections.push_back(std::async(std::launch::async, [Connection] {
					try
					{
						Connection->HandleConnection();
					}
					catch (const std::exception&)
					{
						// ZEN_WARN("exception caught in connection loop: {}", Ex.what());
					}

					delete Connection;
				}));
			}
			else
			{
			}
		} while (m_KeepRunning.test());

		// ZEN_INFO("HTTP plugin server accept thread exit");
	});
}

void
WinsockTransportPlugin::Shutdown()
{
	// TODO: all pending/ongoing work should be drained here as well

	m_KeepRunning.clear();

	closesocket(m_ListenSocket);
	m_ListenSocket = 0;

	if (m_AcceptThread.joinable())
	{
		m_AcceptThread.join();
	}
}

const char*
WinsockTransportPlugin::GetDebugName()
{
	return nullptr;
}

bool
WinsockTransportPlugin::IsAvailable()
{
	return true;
}

//////////////////////////////////////////////////////////////////////////

void
GetTransportPluginVersion(uint32_t* OutApiVersion, uint32_t* OutPluginVersion)
{
	if (OutApiVersion != nullptr)
	{
		*OutApiVersion = kTransportApiVersion;
	}

	if (OutPluginVersion != nullptr)
	{
		*OutPluginVersion = 1;
	}
}

TransportPlugin*
CreateTransportPlugin([[maybe_unused]] TransportLogger* Logger)
{
	return new WinsockTransportPlugin;
}

BOOL WINAPI
DllMain([[maybe_unused]] HINSTANCE hinstDLL,   // handle to DLL module
		DWORD					   fdwReason,  // reason for calling function
		LPVOID					   lpvReserved)					   // reserved
{
	// Perform actions based on the reason for calling.
	switch (fdwReason)
	{
		case DLL_PROCESS_ATTACH:
			break;

		case DLL_THREAD_ATTACH:
			break;

		case DLL_THREAD_DETACH:
			break;

		case DLL_PROCESS_DETACH:
			if (lpvReserved != nullptr)
			{
				break;	// do not do cleanup if process termination scenario
			}
			break;
	}

	return TRUE;
}