aboutsummaryrefslogtreecommitdiff
path: root/src/zenhttp/servers/wsasio.cpp
blob: 5ae48f5b3e9add8f0f4098a05cad35f8d0ad1af0 (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
// Copyright Epic Games, Inc. All Rights Reserved.

#include "wsasio.h"
#include "asio_socket_traits.h"
#include "wsframecodec.h"

#include <zencore/logging.h>
#include <zenhttp/httpserver.h>

namespace zen::asio_http {

static LoggerRef
WsLog()
{
	static LoggerRef g_Logger = logging::Get("ws");
	return g_Logger;
}

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

template<typename SocketType>
WsAsioConnectionT<SocketType>::WsAsioConnectionT(std::unique_ptr<SocketType> Socket, IWebSocketHandler& Handler, HttpServer* Server)
: m_Socket(std::move(Socket))
, m_Handler(Handler)
, m_HttpServer(Server)
{
}

template<typename SocketType>
WsAsioConnectionT<SocketType>::~WsAsioConnectionT()
{
	m_IsOpen.store(false);
	if (m_HttpServer)
	{
		m_HttpServer->OnWebSocketConnectionClosed();
	}
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::Start()
{
	EnqueueRead();
}

template<typename SocketType>
bool
WsAsioConnectionT<SocketType>::IsOpen() const
{
	return m_IsOpen.load(std::memory_order_relaxed);
}

//////////////////////////////////////////////////////////////////////////
//
// Read loop
//

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::EnqueueRead()
{
	if (!m_IsOpen.load(std::memory_order_relaxed))
	{
		return;
	}

	Ref<WsAsioConnectionT> Self(this);

	asio::async_read(*m_Socket, m_ReadBuffer, asio::transfer_at_least(1), [Self](const asio::error_code& Ec, std::size_t ByteCount) {
		Self->OnDataReceived(Ec, ByteCount);
	});
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::OnDataReceived(const asio::error_code& Ec, [[maybe_unused]] std::size_t ByteCount)
{
	if (Ec)
	{
		if (Ec != asio::error::eof && Ec != asio::error::operation_aborted)
		{
			ZEN_LOG_DEBUG(WsLog(), "WebSocket read error: {}", Ec.message());
		}

		if (m_IsOpen.exchange(false))
		{
			m_Handler.OnWebSocketClose(*this, 1006, "connection lost");
		}
		return;
	}

	ProcessReceivedData();

	if (m_IsOpen.load(std::memory_order_relaxed))
	{
		EnqueueRead();
	}
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::ProcessReceivedData()
{
	while (m_ReadBuffer.size() > 0)
	{
		const auto& InputBuffer = m_ReadBuffer.data();
		const auto* Data		= static_cast<const uint8_t*>(InputBuffer.data());
		const auto	Size		= InputBuffer.size();

		WsFrameParseResult Frame = WsFrameCodec::TryParseFrame(Data, Size);
		if (!Frame.IsValid)
		{
			break;	// not enough data yet
		}

		m_ReadBuffer.consume(Frame.BytesConsumed);

		if (m_HttpServer)
		{
			m_HttpServer->OnWebSocketFrameReceived(Frame.BytesConsumed);
		}

		switch (Frame.Opcode)
		{
			case WebSocketOpcode::kText:
			case WebSocketOpcode::kBinary:
				{
					WebSocketMessage Msg;
					Msg.Opcode	= Frame.Opcode;
					Msg.Payload = IoBuffer(IoBuffer::Clone, Frame.Payload.data(), Frame.Payload.size());
					m_Handler.OnWebSocketMessage(*this, Msg);
					break;
				}

			case WebSocketOpcode::kPing:
				{
					// Auto-respond with pong carrying the same payload
					std::vector<uint8_t> PongFrame = WsFrameCodec::BuildFrame(WebSocketOpcode::kPong, Frame.Payload);
					EnqueueWrite(std::move(PongFrame));
					break;
				}

			case WebSocketOpcode::kPong:
				// Unsolicited pong — ignore per RFC 6455
				break;

			case WebSocketOpcode::kClose:
				{
					uint16_t		 Code = 1000;
					std::string_view Reason;

					if (Frame.Payload.size() >= 2)
					{
						Code = (uint16_t(Frame.Payload[0]) << 8) | uint16_t(Frame.Payload[1]);
						if (Frame.Payload.size() > 2)
						{
							Reason = std::string_view(reinterpret_cast<const char*>(Frame.Payload.data() + 2), Frame.Payload.size() - 2);
						}
					}

					// Echo close frame back if we haven't sent one yet
					if (!m_CloseSent.exchange(true))
					{
						std::vector<uint8_t> CloseFrame = WsFrameCodec::BuildCloseFrame(Code);
						EnqueueWrite(std::move(CloseFrame));
					}

					m_IsOpen.store(false);
					m_Handler.OnWebSocketClose(*this, Code, Reason);

					// Shut down the socket
					std::error_code ShutdownEc;
					SocketTraits<SocketType>::ShutdownBoth(*m_Socket, ShutdownEc);
					SocketTraits<SocketType>::Close(*m_Socket, ShutdownEc);
					return;
				}

			default:
				ZEN_LOG_WARN(WsLog(), "Unknown WebSocket opcode: {:#x}", static_cast<uint8_t>(Frame.Opcode));
				break;
		}
	}
}

//////////////////////////////////////////////////////////////////////////
//
// Write queue
//

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::SendText(std::string_view Text)
{
	if (!m_IsOpen.load(std::memory_order_relaxed))
	{
		return;
	}

	std::span<const uint8_t> Payload(reinterpret_cast<const uint8_t*>(Text.data()), Text.size());
	std::vector<uint8_t>	 Frame = WsFrameCodec::BuildFrame(WebSocketOpcode::kText, Payload);
	EnqueueWrite(std::move(Frame));
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::SendBinary(std::span<const uint8_t> Data)
{
	if (!m_IsOpen.load(std::memory_order_relaxed))
	{
		return;
	}

	std::vector<uint8_t> Frame = WsFrameCodec::BuildFrame(WebSocketOpcode::kBinary, Data);
	EnqueueWrite(std::move(Frame));
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::Close(uint16_t Code, std::string_view Reason)
{
	DoClose(Code, Reason);
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::DoClose(uint16_t Code, std::string_view Reason)
{
	if (!m_IsOpen.exchange(false))
	{
		return;
	}

	if (!m_CloseSent.exchange(true))
	{
		std::vector<uint8_t> CloseFrame = WsFrameCodec::BuildCloseFrame(Code, Reason);
		EnqueueWrite(std::move(CloseFrame));
	}

	m_Handler.OnWebSocketClose(*this, Code, Reason);
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::EnqueueWrite(std::vector<uint8_t> Frame)
{
	if (m_HttpServer)
	{
		m_HttpServer->OnWebSocketFrameSent(Frame.size());
	}

	bool ShouldFlush = false;

	m_WriteLock.WithExclusiveLock([&] {
		m_WriteQueue.push_back(std::move(Frame));
		if (!m_IsWriting)
		{
			m_IsWriting = true;
			ShouldFlush = true;
		}
	});

	if (ShouldFlush)
	{
		FlushWriteQueue();
	}
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::FlushWriteQueue()
{
	std::vector<uint8_t> Frame;

	m_WriteLock.WithExclusiveLock([&] {
		if (m_WriteQueue.empty())
		{
			m_IsWriting = false;
			return;
		}
		Frame = std::move(m_WriteQueue.front());
		m_WriteQueue.pop_front();
	});

	if (Frame.empty())
	{
		return;
	}

	Ref<WsAsioConnectionT> Self(this);

	// Move Frame into a shared_ptr so we can create the buffer and capture ownership
	// in the same async_write call without evaluation order issues.
	auto OwnedFrame = std::make_shared<std::vector<uint8_t>>(std::move(Frame));

	asio::async_write(*m_Socket,
					  asio::buffer(OwnedFrame->data(), OwnedFrame->size()),
					  [Self, OwnedFrame](const asio::error_code& Ec, std::size_t ByteCount) { Self->OnWriteComplete(Ec, ByteCount); });
}

template<typename SocketType>
void
WsAsioConnectionT<SocketType>::OnWriteComplete(const asio::error_code& Ec, [[maybe_unused]] std::size_t ByteCount)
{
	if (Ec)
	{
		if (Ec != asio::error::operation_aborted)
		{
			ZEN_LOG_DEBUG(WsLog(), "WebSocket write error: {}", Ec.message());
		}

		m_WriteLock.WithExclusiveLock([&] {
			m_IsWriting = false;
			m_WriteQueue.clear();
		});

		if (m_IsOpen.exchange(false))
		{
			m_Handler.OnWebSocketClose(*this, 1006, "write error");
		}
		return;
	}

	FlushWriteQueue();
}

//////////////////////////////////////////////////////////////////////////
// Explicit template instantiations

template class WsAsioConnectionT<asio::ip::tcp::socket>;

#if defined(ASIO_HAS_LOCAL_SOCKETS)
template class WsAsioConnectionT<asio::local::stream_protocol::socket>;
#endif

#if ZEN_USE_OPENSSL
template class WsAsioConnectionT<asio::ssl::stream<asio::ip::tcp::socket>>;
#endif

}  // namespace zen::asio_http