nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
gateway.cc
Go to the documentation of this file.
1#include "gateway/gateway.h"
2
3#include <array>
4#include <chrono>
5#include <cstddef>
6#include <cstdint>
7#include <deque>
8#include <iostream>
9#include <memory>
10#include <optional>
11#include <string>
12#include <string_view>
13#include <system_error>
14#include <utility>
15#include <vector>
16
17#include "absl/memory/memory.h"
18#include "absl/status/status.h"
19#include "absl/strings/numbers.h"
20#include "absl/strings/str_cat.h"
21#include "absl/strings/str_format.h"
22#include "absl/strings/str_split.h"
23#include "asio/buffer.hpp"
24#include "asio/connect.hpp"
25#include "asio/read_until.hpp"
26#include "asio/ssl/stream_base.hpp"
27#include "asio/steady_timer.hpp"
28#include "asio/write.hpp"
29#include "gateway/websocket.h"
30#include "protocol/tls.h"
31
32namespace nanommo {
33namespace {
34
35using asio::ip::tcp;
36
37// An opening handshake is a few hundred bytes; one this long is something else.
38constexpr std::size_t kMaxRequest = 8 * 1024;
39
40// A page that's silent this long has gone: the client sends its keys each
41// tick in a world, and a login waits a moment for its answer.
42constexpr std::chrono::seconds kIdle(60);
43
44// What's waiting to go to a page that reads too slowly, before it's dropped.
45constexpr std::size_t kMaxQueued = 4 * 1024 * 1024;
46
47// RFC 6455's close codes: done, gone away, and the protocol broken.
48constexpr uint16_t kNormal = 1000;
49constexpr uint16_t kGoingAway = 1001;
50constexpr uint16_t kProtocolError = 1002;
51
52std::string CloseBody(uint16_t code, std::string_view reason) {
53 return absl::StrCat(
54 std::string{static_cast<char>(code >> 8), static_cast<char>(code & 0xFF)},
55 reason);
56}
57
58int HttpStatus(const absl::Status& status) {
59 switch (status.code()) {
60 case absl::StatusCode::kNotFound:
61 return 404;
62 case absl::StatusCode::kPermissionDenied:
63 return 403;
64 case absl::StatusCode::kUnavailable:
65 return 502;
66 default:
67 return 400;
68 }
69}
70
71// One page's connection: its handshake, then its messages to the server it
72// asked for, and that server's bytes back, until either side goes.
73class Session : public std::enable_shared_from_this<Session> {
74 public:
75 Session(tcp::socket page, asio::ssl::context& tls, const Route& route)
76 : page_(std::move(page)),
77 upstream_(page_.get_executor(), tls),
78 resolver_(page_.get_executor()),
79 idle_(page_.get_executor()),
80 route_(route) {
81 std::error_code ignored;
82 const tcp::endpoint peer = page_.remote_endpoint(ignored);
83 peer_ = absl::StrCat(peer.address().to_string(), ":", peer.port());
84 }
85
86 void Start() { ReadHandshake(); }
87
88 private:
89 void ReadHandshake() {
90 Idle();
91 asio::async_read_until(
92 page_, asio::dynamic_buffer(request_, kMaxRequest), "\r\n\r\n",
93 [this, self = shared_from_this()](std::error_code error,
94 std::size_t size) {
95 if (error) {
96 Close("the page went before its handshake");
97 return;
98 }
99 const std::string head = request_.substr(0, size);
100 // Anything after the handshake is the page's first frames.
101 decoder_.Append(std::string_view(request_).substr(size));
102 request_.clear();
103 absl::StatusOr<Handshake> handshake = ParseHandshake(head);
104 if (!handshake.ok()) {
105 TurnDown(handshake.status());
106 return;
107 }
108 path_ = handshake->path;
109 absl::StatusOr<Upstream> upstream = route_(handshake->path);
110 if (!upstream.ok()) {
111 TurnDown(upstream.status());
112 return;
113 }
114 Connect(*upstream, handshake->key);
115 });
116 }
117
118 void Connect(const Upstream& upstream, const std::string& key) {
119 // IPv4, which the servers listen on, as LogIn looks up.
120 resolver_.async_resolve(
121 tcp::v4(), upstream.host, std::to_string(upstream.port),
122 [this, self = shared_from_this(), upstream, key](
123 std::error_code error, const tcp::resolver::results_type& found) {
124 if (error) {
125 TurnDown(absl::UnavailableError(absl::StrCat(
126 "couldn't find ", upstream.host, ": ", error.message())));
127 return;
128 }
129 asio::async_connect(
130 upstream_.lowest_layer(), found,
131 [this, self, upstream, key](std::error_code error,
132 const tcp::endpoint&) {
133 if (error) {
134 TurnDown(absl::UnavailableError(
135 absl::StrCat("couldn't connect to ", upstream.host, ":",
136 upstream.port, ": ", error.message())));
137 return;
138 }
139 std::error_code ignored;
140 upstream_.lowest_layer().set_option(tcp::no_delay(true),
141 ignored);
142 ShakeHands(upstream, key);
143 });
144 });
145 }
146
147 void ShakeHands(const Upstream& upstream, const std::string& key) {
148 ExpectName(upstream_, upstream.name);
149 upstream_.async_handshake(
150 asio::ssl::stream_base::client, [this, self = shared_from_this(),
151 upstream, key](std::error_code error) {
152 if (error) {
153 TurnDown(absl::UnavailableError(
154 absl::StrCat("couldn't shake hands with ", upstream.name, ": ",
155 HandshakeError(upstream_, upstream.name, error))));
156 return;
157 }
158 ToPage(Accept(key));
159 opened_ = std::chrono::steady_clock::now();
160 relaying_ = true;
161 std::cout << "nanommo gateway: " << peer_ << " opened " << path_
162 << ", to " << upstream.host << ":" << upstream.port
163 << std::endl;
164 // The page's first frames may have come with its handshake.
165 Relay();
166 ReadPage();
167 ReadUpstream();
168 });
169 }
170
171 // An HTTP answer instead of the switch to WebSocket, then the connection
172 // closes.
173 void TurnDown(const absl::Status& why) {
174 std::cerr << "nanommo gateway: turned " << peer_ << " down: " << why
175 << "\n";
176 closing_ = true;
177 ToPage(Refuse(HttpStatus(why), why.message()));
178 }
179
180 void ReadPage() {
181 page_.async_read_some(asio::buffer(page_buffer_),
182 [this, self = shared_from_this()](
183 std::error_code error, std::size_t size) {
184 if (error) {
185 Close("the page went");
186 return;
187 }
188 Idle();
189 decoder_.Append({page_buffer_.data(), size});
190 if (Relay()) {
191 ReadPage();
192 }
193 });
194 }
195
196 // Hands the page's messages on to the server, and answers its pings. False
197 // once the page or the protocol has ended the connection.
198 bool Relay() {
199 while (std::optional<Message> message = decoder_.Next()) {
200 switch (message->opcode) {
201 case Opcode::kBinary:
202 case Opcode::kText:
203 ToUpstream(std::move(message->payload));
204 break;
205 case Opcode::kPing:
206 ToPage(ServerFrame(Opcode::kPong, message->payload));
207 break;
208 case Opcode::kClose:
209 closing_ = true;
210 why_ = "the page closed it";
211 ToPage(ServerFrame(Opcode::kClose, CloseBody(kNormal, "")));
212 return false;
213 default:
214 break;
215 }
216 }
217 if (!decoder_.status().ok()) {
218 closing_ = true;
219 why_ = std::string(decoder_.status().message());
220 ToPage(
222 CloseBody(kProtocolError, decoder_.status().message())));
223 return false;
224 }
225 return true;
226 }
227
228 void ReadUpstream() {
229 upstream_.async_read_some(
230 asio::buffer(upstream_buffer_),
231 [this, self = shared_from_this()](std::error_code error,
232 std::size_t size) {
233 if (error) {
234 // The server went, so the page goes too.
235 closing_ = true;
236 why_ = "the server closed it";
238 CloseBody(kGoingAway, "the server closed")));
239 return;
240 }
241 // The server's bytes as they come, which the page puts back
242 // together into the game's messages, as it would from TCP.
243 ToPage(ServerFrame(Opcode::kBinary, {upstream_buffer_.data(), size}));
244 ReadUpstream();
245 });
246 }
247
248 void ToPage(std::string bytes) {
249 if (closed_) {
250 return;
251 }
252 if (to_page_size_ + bytes.size() > kMaxQueued) {
253 Close("the page couldn't keep up");
254 return;
255 }
256 to_page_size_ += bytes.size();
257 to_page_.push_back(std::move(bytes));
258 if (to_page_.size() == 1) {
259 WritePage();
260 }
261 }
262
263 void WritePage() {
264 asio::async_write(
265 page_, asio::buffer(to_page_.front()),
266 [this, self = shared_from_this()](std::error_code error, std::size_t) {
267 if (error) {
268 Close("the page went");
269 return;
270 }
271 to_page_size_ -= to_page_.front().size();
272 to_page_.pop_front();
273 if (!to_page_.empty()) {
274 WritePage();
275 } else if (closing_) {
276 Close(why_);
277 }
278 });
279 }
280
281 void ToUpstream(std::string bytes) {
282 if (closed_) {
283 return;
284 }
285 to_upstream_.push_back(std::move(bytes));
286 if (to_upstream_.size() == 1) {
287 WriteUpstream();
288 }
289 }
290
291 void WriteUpstream() {
292 asio::async_write(
293 upstream_, asio::buffer(to_upstream_.front()),
294 [this, self = shared_from_this()](std::error_code error, std::size_t) {
295 if (error) {
296 Close("couldn't write to the server");
297 return;
298 }
299 to_upstream_.pop_front();
300 if (!to_upstream_.empty()) {
301 WriteUpstream();
302 }
303 });
304 }
305
306 void Idle() {
307 idle_.expires_after(kIdle);
308 idle_.async_wait([this, self = shared_from_this()](std::error_code error) {
309 if (!error) {
310 Close("the page was silent for a minute");
311 }
312 });
313 }
314
315 // Closes both sides, and says why, for a page that got as far as the
316 // server; a page turned down was said already.
317 void Close(std::string_view why) {
318 if (closed_) {
319 return;
320 }
321 closed_ = true;
322 if (relaying_) {
323 const std::chrono::duration<double> lasted =
324 std::chrono::steady_clock::now() - opened_;
325 std::cout << "nanommo gateway: " << peer_ << " closed " << path_
326 << " after " << absl::StrFormat("%.1f", lasted.count())
327 << " s: " << why << std::endl;
328 }
329 std::error_code ignored;
330 idle_.cancel();
331 resolver_.cancel();
332 page_.close(ignored);
333 upstream_.lowest_layer().close(ignored);
334 }
335
336 tcp::socket page_;
337 TlsStream upstream_;
338 tcp::resolver resolver_;
339 asio::steady_timer idle_;
340 const Route& route_;
341 std::string request_;
343 std::array<char, 8192> page_buffer_{};
344 std::array<char, 8192> upstream_buffer_{};
345 std::deque<std::string> to_page_;
346 std::size_t to_page_size_ = 0;
347 std::deque<std::string> to_upstream_;
348 std::string peer_;
349 std::string path_;
350 std::chrono::steady_clock::time_point opened_;
351 bool relaying_ = false;
352 std::string why_;
353 bool closing_ = false;
354 bool closed_ = false;
355};
356
357} // namespace
358
359Route Routes(Upstream login, WorldAddress world_address) {
360 return [login = std::move(login), world_address = std::move(world_address)](
361 std::string_view path) -> absl::StatusOr<Upstream> {
362 path = path.substr(0, path.find('?'));
363 if (path == "/login") {
364 return login;
365 }
366 const std::vector<std::string_view> parts = absl::StrSplit(path, '/');
367 if (parts.size() == 4 && parts[0].empty() && parts[1] == "world") {
368 uint32_t port = 0;
369 if (!absl::SimpleAtoi(parts[3], &port) || port == 0 || port > 65535) {
370 return absl::InvalidArgumentError(
371 absl::StrCat(parts[3], " isn't a port"));
372 }
373 absl::StatusOr<std::string> address =
374 world_address(parts[2], static_cast<uint16_t>(port));
375 if (!address.ok()) {
376 return address.status();
377 }
378 // Connected at its own address, it's checked by the name players use.
379 return Upstream{.host = *std::move(address),
380 .port = static_cast<uint16_t>(port),
381 .name = std::string(parts[2])};
382 }
383 return absl::NotFoundError(absl::StrCat("nothing at ", path));
384 };
385}
386
387absl::StatusOr<std::unique_ptr<Gateway>> Gateway::Create(
388 asio::io_context& io, uint16_t port, asio::ssl::context& tls, Route route) {
389 std::unique_ptr<Gateway> gateway =
390 absl::WrapUnique(new Gateway(io, tls, std::move(route)));
391 std::error_code error;
392 const tcp::endpoint endpoint(tcp::v4(), port);
393 gateway->acceptor_.open(endpoint.protocol(), error);
394 if (!error) {
395 gateway->acceptor_.set_option(tcp::acceptor::reuse_address(true), error);
396 }
397 if (!error) {
398 gateway->acceptor_.bind(endpoint, error);
399 }
400 if (!error) {
401 gateway->acceptor_.listen(asio::socket_base::max_listen_connections, error);
402 }
403 if (error) {
404 return absl::UnavailableError(
405 absl::StrCat("couldn't listen on port ", port, ": ", error.message()));
406 }
407 gateway->Accept();
408 return gateway;
409}
410
411Gateway::Gateway(asio::io_context& io, asio::ssl::context& tls, Route route)
412 : acceptor_(io), tls_(tls), route_(std::move(route)) {}
413
414void Gateway::Accept() {
415 acceptor_.async_accept([this](std::error_code error, tcp::socket socket) {
416 if (!error) {
417 std::make_shared<Session>(std::move(socket), tls_, route_)->Start();
418 }
419 Accept();
420 });
421}
422
423} // namespace nanommo
uint16_t port() const
Definition gateway.h:53
Gateway(const Gateway &)=delete
static constexpr std::size_t kMaxMessage
A page's message larger than this is refused, as the servers would.
Definition gateway.h:43
static absl::StatusOr< std::unique_ptr< Gateway > > Create(asio::io_context &io, uint16_t port, asio::ssl::context &tls, Route route)
Listens on the port (0 for any), or returns why it can't.
Definition gateway.cc:387
Session(asio::ip::tcp::socket socket, asio::ssl::context &tls, OnMessage on_message, OnClose on_close)
Definition session.cc:14
void Start()
Shakes hands over TLS, then reads the client's messages.
Definition session.cc:24
Definition chat.cc:9
std::string HandshakeError(TlsStream &stream, const std::string &host, const std::error_code &error)
Why a client's handshake with host failed, and what to do about it.
Definition tls.cc:64
absl::StatusOr< Handshake > ParseHandshake(std::string_view request)
Definition websocket.cc:77
asio::ssl::stream< asio::ip::tcp::socket > TlsStream
Definition tls.h:14
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
Definition websocket.cc:139
std::function< absl::StatusOr< std::string >( std::string_view public_host, uint16_t port)> WorldAddress
Finds a world's own address by the host and port players reach it at.
Definition gateway.h:29
std::string ServerFrame(Opcode opcode, std::string_view payload)
A frame as the server sends it: whole, and never masked.
Definition websocket.cc:145
std::function< absl::StatusOr< Upstream >(std::string_view path)> Route
Where a page's path leads, or why nowhere.
Definition gateway.h:26
void ExpectName(TlsStream &stream, const std::string &host)
Definition tls.cc:52
std::string Accept(std::string_view key)
The server's answer that switches the connection over to WebSocket.
Definition websocket.cc:132
Route Routes(Upstream login, WorldAddress world_address)
Definition gateway.cc:359