13#include <system_error>
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"
38constexpr std::size_t kMaxRequest = 8 * 1024;
42constexpr std::chrono::seconds
kIdle(60);
45constexpr std::size_t kMaxQueued = 4 * 1024 * 1024;
48constexpr uint16_t kNormal = 1000;
49constexpr uint16_t kGoingAway = 1001;
50constexpr uint16_t kProtocolError = 1002;
52std::string CloseBody(uint16_t code, std::string_view reason) {
54 std::string{
static_cast<char>(code >> 8),
static_cast<char>(code & 0xFF)},
58int HttpStatus(
const absl::Status& status) {
59 switch (status.code()) {
60 case absl::StatusCode::kNotFound:
62 case absl::StatusCode::kPermissionDenied:
64 case absl::StatusCode::kUnavailable:
73class Session :
public std::enable_shared_from_this<Session> {
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()),
81 std::error_code ignored;
82 const tcp::endpoint peer = page_.remote_endpoint(ignored);
83 peer_ = absl::StrCat(peer.address().to_string(),
":", peer.port());
86 void Start() { ReadHandshake(); }
89 void ReadHandshake() {
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,
96 Close(
"the page went before its handshake");
99 const std::string head = request_.substr(0, size);
101 decoder_.Append(std::string_view(request_).substr(size));
104 if (!handshake.ok()) {
105 TurnDown(handshake.status());
108 path_ = handshake->path;
109 absl::StatusOr<Upstream> upstream = route_(handshake->path);
110 if (!upstream.ok()) {
111 TurnDown(upstream.status());
114 Connect(*upstream, handshake->key);
118 void Connect(
const Upstream& upstream,
const std::string& key) {
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) {
125 TurnDown(absl::UnavailableError(absl::StrCat(
126 "couldn't find ", upstream.host,
": ", error.message())));
130 upstream_.lowest_layer(), found,
131 [
this, self, upstream, key](std::error_code error,
132 const tcp::endpoint&) {
134 TurnDown(absl::UnavailableError(
135 absl::StrCat(
"couldn't connect to ", upstream.host,
":",
136 upstream.port,
": ", error.message())));
139 std::error_code ignored;
140 upstream_.lowest_layer().set_option(tcp::no_delay(
true),
142 ShakeHands(upstream, key);
147 void ShakeHands(
const Upstream& upstream,
const std::string& key) {
149 upstream_.async_handshake(
150 asio::ssl::stream_base::client, [
this, self = shared_from_this(),
151 upstream, key](std::error_code error) {
153 TurnDown(absl::UnavailableError(
154 absl::StrCat(
"couldn't shake hands with ", upstream.name,
": ",
159 opened_ = std::chrono::steady_clock::now();
161 std::cout <<
"nanommo gateway: " << peer_ <<
" opened " << path_
162 <<
", to " << upstream.host <<
":" << upstream.port
173 void TurnDown(
const absl::Status& why) {
174 std::cerr <<
"nanommo gateway: turned " << peer_ <<
" down: " << why
177 ToPage(
Refuse(HttpStatus(why), why.message()));
181 page_.async_read_some(asio::buffer(page_buffer_),
182 [
this, self = shared_from_this()](
183 std::error_code error, std::size_t size) {
185 Close(
"the page went");
189 decoder_.Append({page_buffer_.data(), size});
199 while (std::optional<Message> message = decoder_.Next()) {
200 switch (message->opcode) {
203 ToUpstream(std::move(message->payload));
210 why_ =
"the page closed it";
217 if (!decoder_.status().ok()) {
219 why_ = std::string(decoder_.status().message());
222 CloseBody(kProtocolError, decoder_.status().message())));
228 void ReadUpstream() {
229 upstream_.async_read_some(
230 asio::buffer(upstream_buffer_),
231 [
this, self = shared_from_this()](std::error_code error,
236 why_ =
"the server closed it";
238 CloseBody(kGoingAway,
"the server closed")));
248 void ToPage(std::string bytes) {
252 if (to_page_size_ + bytes.size() > kMaxQueued) {
253 Close(
"the page couldn't keep up");
256 to_page_size_ += bytes.size();
257 to_page_.push_back(std::move(bytes));
258 if (to_page_.size() == 1) {
265 page_, asio::buffer(to_page_.front()),
266 [
this, self = shared_from_this()](std::error_code error, std::size_t) {
268 Close(
"the page went");
271 to_page_size_ -= to_page_.front().size();
272 to_page_.pop_front();
273 if (!to_page_.empty()) {
275 }
else if (closing_) {
281 void ToUpstream(std::string bytes) {
285 to_upstream_.push_back(std::move(bytes));
286 if (to_upstream_.size() == 1) {
291 void WriteUpstream() {
293 upstream_, asio::buffer(to_upstream_.front()),
294 [
this, self = shared_from_this()](std::error_code error, std::size_t) {
296 Close(
"couldn't write to the server");
299 to_upstream_.pop_front();
300 if (!to_upstream_.empty()) {
307 idle_.expires_after(
kIdle);
308 idle_.async_wait([
this, self = shared_from_this()](std::error_code error) {
310 Close(
"the page was silent for a minute");
317 void Close(std::string_view why) {
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;
329 std::error_code ignored;
332 page_.close(ignored);
333 upstream_.lowest_layer().close(ignored);
338 tcp::resolver resolver_;
339 asio::steady_timer idle_;
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_;
350 std::chrono::steady_clock::time_point opened_;
351 bool relaying_ =
false;
353 bool closing_ =
false;
354 bool closed_ =
false;
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") {
366 const std::vector<std::string_view> parts = absl::StrSplit(path,
'/');
367 if (parts.size() == 4 && parts[0].empty() && parts[1] ==
"world") {
369 if (!absl::SimpleAtoi(parts[3], &port) || port == 0 || port > 65535) {
370 return absl::InvalidArgumentError(
371 absl::StrCat(parts[3],
" isn't a port"));
373 absl::StatusOr<std::string> address =
374 world_address(parts[2],
static_cast<uint16_t
>(port));
376 return address.status();
379 return Upstream{.host = *std::move(address),
380 .port =
static_cast<uint16_t
>(port),
381 .name = std::string(parts[2])};
383 return absl::NotFoundError(absl::StrCat(
"nothing at ", path));
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);
395 gateway->acceptor_.set_option(tcp::acceptor::reuse_address(
true), error);
398 gateway->acceptor_.bind(endpoint, error);
401 gateway->acceptor_.listen(asio::socket_base::max_listen_connections, error);
404 return absl::UnavailableError(
405 absl::StrCat(
"couldn't listen on port ",
port,
": ", error.message()));
412 : acceptor_(io), tls_(tls), route_(std::move(route)) {}
414void Gateway::Accept() {
415 acceptor_.async_accept([
this](std::error_code error, tcp::socket socket) {
417 std::make_shared<Session>(std::move(socket), tls_, route_)->Start();
Gateway(const Gateway &)=delete
static constexpr std::size_t kMaxMessage
A page's message larger than this is refused, as the servers would.
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.
Session(asio::ip::tcp::socket socket, asio::ssl::context &tls, OnMessage on_message, OnClose on_close)
void Start()
Shakes hands over TLS, then reads the client's messages.
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.
absl::StatusOr< Handshake > ParseHandshake(std::string_view request)
asio::ssl::stream< asio::ip::tcp::socket > TlsStream
std::string Refuse(int status, std::string_view why)
An HTTP answer that turns the connection down, with why in its body.
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.
std::string ServerFrame(Opcode opcode, std::string_view payload)
A frame as the server sends it: whole, and never masked.
std::function< absl::StatusOr< Upstream >(std::string_view path)> Route
Where a page's path leads, or why nowhere.
void ExpectName(TlsStream &stream, const std::string &host)
std::string Accept(std::string_view key)
The server's answer that switches the connection over to WebSocket.
Route Routes(Upstream login, WorldAddress world_address)