summaryrefslogtreecommitdiffhomepage
path: root/websocket.cpp
blob: d361ec135a08a258b265b13be0bcb1e1b3dcfd56 (plain)
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
//
// Websocket, implemented via CRTP for both plain and ssl websockets
//
#include "websocket.h"

namespace beast = boost::beast;         // from <boost/beast.hpp>
namespace http = beast::http;           // from <boost/beast/http.hpp>
namespace net = boost::asio;            // from <boost/asio.hpp>
namespace ssl = boost::asio::ssl;       // from <boost/asio/ssl.hpp>
namespace websocket = beast::websocket;
using tcp = boost::asio::ip::tcp;       // from <boost/asio/ip/tcp.hpp>
using namespace std::placeholders;

// Server session, asynchronous, proxying, implemented w/ CRTP for plain+ssl variants
template<class Derived>
class websocket_session
{
private:
 Derived& derived()
 {
  return static_cast<Derived&>(*this);
 }

 boost::asio::io_context& ioc_;
 boost::asio::ip::tcp::resolver resolver_;
 boost::beast::flat_buffer buffer_in_;
 boost::beast::websocket::stream<beast::tcp_stream> ws_app_;
 boost::beast::flat_buffer buffer_out_;
 std::string host_;
 std::string port_;
 std::string subprotocol_;
 std::string relative_target_;

public: 
 explicit websocket_session(boost::asio::io_context& ioc, std::string&& websocket_address):
  ioc_(ioc),
  resolver_(boost::asio::make_strand(ioc_)),
  ws_app_(boost::asio::make_strand(ioc_)),
  host_{},
  port_{},
  subprotocol_{},
  relative_target_{}
 {
  // Parse websocket address host:port :

  auto colon_pos{websocket_address.find_last_of(':')};

  if (colon_pos == std::string::npos) {
   std::cerr << "Warning: Bad websocket address (colon missing): " << websocket_address << std::endl;
   return;
  }
  
  auto slash_pos{websocket_address.find('/')};
  if (slash_pos == std::string::npos) {
   std::cerr << "Warning: Bad websocket address (slash missing): " << websocket_address << std::endl;
   return;
  }
  if (slash_pos <= colon_pos) {
   std::cerr << "Warning: Bad websocket address: " << websocket_address << std::endl;
   return;
  }

  host_ = websocket_address.substr(0, colon_pos);
  port_ = websocket_address.substr(colon_pos + 1, slash_pos - (colon_pos + 1));
  relative_target_ = websocket_address.substr(slash_pos);
 }

 void fail(boost::beast::error_code ec, char const* what)
 {
  if (ec == websocket::error::closed)
   return;

  boost::beast::error_code ec2;
  if (auto& ws_in{derived().ws_in()}; ws_in.is_open())
   ws_in.close(beast::websocket::close_code::going_away, ec2);
  if (auto& ws_app{ws_app_}; ws_app.is_open())
   ws_app.close(beast::websocket::close_code::going_away, ec2);

  std::cerr << what << ": " << ec.message() << "\n";
 }

 //
 // The initial setup path
 //
 
 // Start the asynchronous accept operation
 void do_accept_in(request_type req)
 {
  // Set suggested timeout settings for the websocket
  derived().ws_in().set_option(
      websocket::stream_base::timeout::suggested(
          beast::role_type::server));

  // Set a decorator to change the Server of the handshake
  derived().ws_in().set_option(websocket::stream_base::decorator(
      [](websocket::response_type& res)
      {
          res.set(http::field::server,
              std::string{"Reichwein.IT Webserver"});
      }));

  // Forward subprotocol from request to target websocket
  subprotocol_ = std::string{req[http::field::sec_websocket_protocol]};

  // Accept the websocket handshake
  derived().ws_in().async_accept(
      req,
      beast::bind_front_handler(
          &websocket_session::on_accept_in,
          derived().shared_from_this()));
 }

private:
 void on_accept_in(beast::error_code ec)
 {
  if (ec)
   return fail(ec, "accept in");

  resolver_.async_resolve(host_, port_,
                          beast::bind_front_handler(&websocket_session::on_resolve_app, derived().shared_from_this()));
 }
 
 void on_resolve_app(beast::error_code ec, tcp::resolver::results_type results)
 {
  if (ec)
   return fail(ec, "resolve app");

  beast::get_lowest_layer(ws_app_).async_connect(results,
                          beast::bind_front_handler(&websocket_session::on_connect_app, derived().shared_from_this()));
 }

 void on_connect_app(beast::error_code ec, tcp::resolver::results_type::endpoint_type endpoint)
 {
  if (ec)
   return fail(ec, "connect app");

  beast::get_lowest_layer(ws_app_).expires_never();

  host_ += ':' + std::to_string(endpoint.port());

  // Set suggested timeout settings for the websocket
  ws_app_.set_option(
      websocket::stream_base::timeout::suggested(
	  beast::role_type::client));

  ws_app_.set_option(boost::beast::websocket::stream_base::decorator(
   [](boost::beast::websocket::request_type& req)
   {
    req.set(boost::beast::http::field::user_agent, "Reichwein.IT Webserver Websocket client");
   }));
 
  ws_app_.set_option(boost::beast::websocket::stream_base::decorator(
   [this](boost::beast::websocket::request_type& req)
   {
    req.set(boost::beast::http::field::sec_websocket_protocol, subprotocol_);
   }));

  ws_app_.async_handshake(host_, relative_target_,
                          beast::bind_front_handler(&websocket_session::on_handshake_app, derived().shared_from_this()));
 }

 void on_handshake_app(beast::error_code ec)
 {
  if (ec)
   return fail(ec, "handshake app");

  // Start reading messages from both sides, asynchronously
  do_read_in();
  do_read_app();
 }

 //
 // The input path (client,ws_in_ -> app,ws_app_) via
 //
 
 void
 do_read_in()
 {
  // Read a message into our buffer
  derived().ws_in().async_read(
      buffer_in_,
      beast::bind_front_handler(
          &websocket_session::on_read_in,
          derived().shared_from_this()));
 }

 void
 on_read_in(
     beast::error_code ec,
     std::size_t bytes_transferred)
 {
  boost::ignore_unused(bytes_transferred);

  // This indicates that the websocket_session was closed
  if (ec == websocket::error::closed)
   return;

  if (ec) {
   // not error::closed as above, but no other strategy known
   return fail(ec, "read in");
  }

  ws_app_.text(derived().ws_in().got_text());
  
  do_write_app();
 }
 
 void do_write_app()
 {
  ws_app_.async_write(buffer_in_.data(),
      beast::bind_front_handler(
          &websocket_session::on_write_app,
          derived().shared_from_this()));
 }

 void on_write_app(beast::error_code ec, std::size_t bytes_transferred)
 {
  boost::ignore_unused(bytes_transferred);

  if (ec)
   return fail(ec, "write app");

  buffer_in_.consume(buffer_in_.size());

  // Do another read
  do_read_in();
 }

 //
 // The output path (app,ws_app_ -> client,ws_in_)
 //
 
 void do_read_app()
 {
  // Read a message into our buffer
  ws_app_.async_read(
      buffer_out_,
      beast::bind_front_handler(
          &websocket_session::on_read_app,
          derived().shared_from_this()));
 }

 void on_read_app(beast::error_code ec, std::size_t bytes_transferred)
 {
  boost::ignore_unused(bytes_transferred);

  if (ec == websocket::error::closed)
   return;

  if (ec) {
   // not error::closed as above, but no other strategy known
   return fail(ec, "read app");
  }

  do_write_out();
 }

 void do_write_out()
 {
  derived().ws_in().async_write(buffer_out_.data(),
      beast::bind_front_handler(
          &websocket_session::on_write_out,
          derived().shared_from_this()));
 }

 void on_write_out(
     beast::error_code ec,
     std::size_t bytes_transferred)
 {
  boost::ignore_unused(bytes_transferred);

  if (ec)
   return fail(ec, "write out");

  // Clear the buffer
  buffer_out_.consume(buffer_out_.size());

  // Do another read
  do_read_app();
 }

}; // class

class plain_websocket_session:
 public websocket_session<plain_websocket_session>,
 public std::enable_shared_from_this<plain_websocket_session>
{
 boost::beast::websocket::stream<beast::tcp_stream> ws_in_;

public:

 explicit plain_websocket_session(boost::asio::io_context& ioc, beast::tcp_stream&& stream, std::string&& websocket_address):
  websocket_session(ioc, std::move(websocket_address)),
  ws_in_(std::move(stream))
 {
 }

 boost::beast::websocket::stream<beast::tcp_stream>& ws_in()
 {
  return ws_in_;
 }
}; // class

class ssl_websocket_session:
 public websocket_session<ssl_websocket_session>,
 public std::enable_shared_from_this<ssl_websocket_session>
{
 boost::beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>> ws_in_;

public:

 explicit ssl_websocket_session(boost::asio::io_context& ioc, beast::ssl_stream<beast::tcp_stream>&& stream, std::string&& websocket_address):
  websocket_session(ioc, std::move(websocket_address)),
  ws_in_(std::move(stream))
 {
 }

 boost::beast::websocket::stream<beast::ssl_stream<beast::tcp_stream>>& ws_in()
 {
  return ws_in_;
 }
}; // class

void make_websocket_session(boost::asio::io_context& ioc, beast::tcp_stream&& stream, std::string websocket_address, request_type&& req)
{
 std::make_shared<plain_websocket_session>(ioc, std::move(stream), std::move(websocket_address))->do_accept_in(std::move(req));
}

void make_websocket_session(boost::asio::io_context& ioc, beast::ssl_stream<beast::tcp_stream>&& stream, std::string websocket_address, request_type&& req)
{
 std::make_shared<ssl_websocket_session>(ioc, std::move(stream), std::move(websocket_address))->do_accept_in(std::move(req));
}