summaryrefslogtreecommitdiff
path: root/src/components/transport_manager/test/include/transport_manager/cloud/sample_websocket_server.h
blob: 421462d4d5a8c9cbfe16dc8d86116a784d24c9ff (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
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

/*
 * Copyright (c) 2019, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_CLOUD_SAMPLE_WEBSOCKET_SERVER_H_
#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_CLOUD_SAMPLE_WEBSOCKET_SERVER_H_

#include <unistd.h>
#include <algorithm>
#include <boost/asio/bind_executor.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/placeholders.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <boost/asio/strand.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <boost/make_shared.hpp>
#include <boost/thread/thread.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
#include <vector>

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

//------------------------------------------------------------------------------

// Report a failure
void fail(beast::error_code ec, char const* what) {
  std::cerr << what << ": " << ec.message() << "\n";
}

// Accepts incoming connections and launches the WSServer
class WSSession : public std::enable_shared_from_this<WSSession> {
 private:
  // Echoes back all received WebSocket messages
  class WSServer : public std::enable_shared_from_this<WSServer> {
   public:
    // Take ownership of the socket
    explicit WSServer(tcp::socket&& socket)
        : ws_(std::move(socket)), strand_(ws_.get_executor()) {}

    // Start the asynchronous operation
    void run() {
      // Accept the websocket handshake
      ws_.async_accept(
          boost::asio::bind_executor(strand_,
                                     std::bind(&WSServer::on_accept,
                                               shared_from_this(),
                                               std::placeholders::_1)));
    }

    void on_accept(beast::error_code ec) {
      std::cout << "SERVER: Accepting connection" << std::endl;
      if (ec) {
        std::cout << "SERVER: Connection accept FAILED" << std::endl;
        return fail(ec, "accept");
      }
      // Read a message
      // do_read();
    }

    // void do_read() {
    //   // Read a message into our buffer
    //   ws_.async_read(
    //       buffer_,
    //       boost::asio::bind_executor(strand_,
    //                                  std::bind(&WSServer::on_read,
    //                                            shared_from_this(),
    //                                            std::placeholders::_1,
    //                                            std::placeholders::_2)));
    // }

    // void do_write() {
    //   ws_.text(ws_.got_text());
    //   ws_.async_write(buffer_.data(),
    //                   std::bind(&WSServer::on_write,
    //                             shared_from_this(),
    //                             std::placeholders::_1,
    //                             std::placeholders::_2));
    // }

    // void on_read(beast::error_code ec, std::size_t bytes_transferred) {
    //   std::cout << "SERVER: receiving data" << std::endl;

    //   boost::ignore_unused(bytes_transferred);

    //   // This indicates that the WSServer was closed
    //   if (ec == websocket::error::closed) {
    //     std::cout << "SERVER: Websocket closed" << std::endl;
    //     return;
    //   }

    //   if (ec) {
    //     std::cout << "SERVER: Read failed" << std::endl;
    //     fail(ec, "read");
    //   }

    //   // Echo the message
    //   do_write();
    // }

    // void on_write(beast::error_code ec, std::size_t bytes_transferred) {
    //   std::cout << "SERVER: Sending data" << std::endl;

    //   boost::ignore_unused(bytes_transferred);

    //   if (ec) {
    //     std::cout << "SERVER: Write failed" << std::endl;
    //     return fail(ec, "write");
    //   }

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

    //   // Do another read
    //   do_read();
    // }

   private:
    websocket::stream<tcp::socket> ws_;
    beast::flat_buffer buffer_;
    boost::asio::strand<boost::asio::io_context::executor_type> strand_;
  };

 public:
  WSSession(const std::string& address, uint16_t port)
      : address_(address), port_(port), acceptor_(ioc_), socket_(ioc_) {
    endpoint_ = {boost::asio::ip::make_address(address), port};

    boost::system::error_code error;

    acceptor_.open(endpoint_.protocol(), error);
    if (error) {
      std::cerr << "ErrorOpen: " << error.message() << std::endl;
      return;
    }
    acceptor_.set_option(boost::asio::socket_base::reuse_address(true), error);
    if (error) {
      std::cerr << "ErrorSetOption: " << error.message() << std::endl;
      return;
    }
    acceptor_.bind(endpoint_, error);
    if (error) {
      std::cerr << "ErrorBind: " << error.message() << std::endl;
      return;
    }
    acceptor_.listen(boost::asio::socket_base::max_listen_connections, error);
    if (error) {
      std::cerr << "ErrorListen: " << error.message() << std::endl;
      return;
    }
  }

  void run() {
    if (acceptor_.is_open()) {
      acceptor_.async_accept(
          socket_,
          std::bind(&WSSession::StartSession, this, std::placeholders::_1));
      ioc_.run();
    }
  }

  void stop() {
    std::cout << "SERVER: Closing connection" << std::endl;

    try {
      ioc_.stop();
      acceptor_.close();
    } catch (...) {
      std::cout << "SERVER: Failed to close connection" << std::endl;
    }
  }

 private:
  void StartSession(boost::system::error_code ec) {
    if (ec) {
      std::cerr << "ErrorMessage: " << ec.message() << std::endl;
      ioc_.stop();
      return;
    }

    // Make websocket object and start
    ws_ = std::make_shared<WSServer>(std::move(socket_));
    ws_->run();
  }

  boost::asio::io_context ioc_;
  const std::string& address_;
  uint16_t port_;
  tcp::acceptor acceptor_;
  tcp::socket socket_;
  beast::flat_buffer buffer_;
  boost::asio::ip::tcp::endpoint endpoint_;
  std::shared_ptr<WSServer> ws_;
};

// Accepts incoming connections and launches the sessions
class WSSSession : public std::enable_shared_from_this<WSSSession> {
 private:
  // Echoes back all received WebSocket messages
  class WSSServer : public std::enable_shared_from_this<WSSServer> {
   public:
    // Take ownership of the socket
    WSSServer(tcp::socket&& socket, ssl::context& ctx)
        : wss_(std::move(socket), ctx) {}

    // Start the asynchronous operation
    void run() {
      // Perform the SSL handshake
      wss_.next_layer().async_handshake(ssl::stream_base::server,
                                        std::bind(&WSSServer::on_handshake,
                                                  shared_from_this(),
                                                  std::placeholders::_1));
    }

    void on_handshake(beast::error_code ec) {
      std::cout << "DEBUG: SSL Handshake" << std::endl;
      if (ec)
        return fail(ec, "handshake");

      // Accept the websocket handshake
      wss_.async_accept(std::bind(
          &WSSServer::on_accept, shared_from_this(), std::placeholders::_1));
    }

    void on_accept(beast::error_code ec) {
      std::cout << "DEBUG: Server accepted connection" << std::endl;
      if (ec)
        return fail(ec, "accept");

      // Read a message
      // do_read();
    }

    // void
    // do_read()
    // {
    //     // Read a message into our buffer
    //     wss_.async_read(
    //         buffer_,
    //         std::bind(
    //             &WSSServer::on_read,
    //             shared_from_this(),
    //             std::placeholders::_1,
    //             std::placeholders::_2));
    // }

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

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

    //     if(ec)
    //         fail(ec, "read");

    //     // Echo the message
    //     wss_.text(wss_.got_text());
    //     wss_.async_write(
    //         buffer_.data(),
    //         std::bind(
    //             &WSSServer::on_write,
    //             shared_from_this(),
    //             std::placeholders::_1,
    //             std::placeholders::_2));
    // }

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

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

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

    //     // Do another read
    //     do_read();
    // }
   private:
    websocket::stream<ssl::stream<tcp::socket> > wss_;
    beast::flat_buffer buffer_;
  };

 public:
  WSSSession(const std::string& address,
             uint16_t port,
             const std::string& certificate,
             const std::string& private_key)
      : acceptor_(ioc_), socket_(ioc_), ctx_(ssl::context::sslv23_server) {
    beast::error_code ec;
    endpoint_ = {boost::asio::ip::make_address(address), port};

    std::cout << "DEBUG: Adding certificate" << std::endl;
    // Load the certificate
    ctx_.use_certificate(
        boost::asio::buffer(certificate.c_str(), certificate.size()),
        ssl::context::file_format::pem,
        ec);
    if (ec) {
      fail(ec, "Load certficate");
      return;
    }

    std::cout << "DEBUG: Adding private key" << std::endl;
    // Load the private key
    ctx_.use_rsa_private_key(
        boost::asio::buffer(private_key.c_str(), private_key.size()),
        ssl::context::file_format::pem,
        ec);
    if (ec) {
      fail(ec, "Load private key");
      return;
    }

    // Open the acceptor
    acceptor_.open(endpoint_.protocol(), ec);
    if (ec) {
      fail(ec, "open");
      return;
    }

    // Allow address reuse
    acceptor_.set_option(net::socket_base::reuse_address(true), ec);
    if (ec) {
      fail(ec, "set_option");
      return;
    }

    std::cout << "DEBUG: Binding to host:" << address << ", port:" << port
              << std::endl;
    // Bind to the server address
    acceptor_.bind(endpoint_, ec);
    if (ec) {
      fail(ec, "bind");
      return;
    }

    std::cout << "DEBUG: Start listening for connections" << std::endl;
    // Start listening for connections
    acceptor_.listen(net::socket_base::max_listen_connections, ec);
    if (ec) {
      fail(ec, "listen");
      return;
    }
  }

  // Start accepting incoming connections
  void run() {
    do_accept();
  }

  void stop() {
    std::cout << "SERVER: Closing connection" << std::endl;

    try {
      ioc_.stop();
      acceptor_.close();
    } catch (...) {
      std::cout << "SERVER: Failed to close connection" << std::endl;
    }
  }

 private:
  void do_accept() {
    if (acceptor_.is_open()) {
      std::cout << "DEBUG: Waiting to accept incoming connections" << std::endl;
      // The new connection gets its own strand
      acceptor_.async_accept(socket_,
                             std::bind(&WSSSession::on_accept,
                                       shared_from_this(),
                                       std::placeholders::_1));
      ioc_.run();
    }
  }

  void on_accept(boost::system::error_code ec) {
    std::cout << "DEBUG: Accepted incoming connection" << std::endl;
    if (ec) {
      fail(ec, "accept");
      ioc_.stop();
      return;
    } else {
      std::cout << "DEBUG: Creating secure websocket server" << std::endl;
      // Create the session and run it
      wss_ = std::make_shared<WSSServer>(std::move(socket_), ctx_);
      wss_->run();
    }
  }

 private:
  boost::asio::io_context ioc_;
  tcp::acceptor acceptor_;
  tcp::socket socket_;
  ssl::context ctx_;
  tcp::endpoint endpoint_;
  std::shared_ptr<WSSServer> wss_;
};

#endif  // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_CLOUD_SAMPLE_WEBSOCKET_SERVER_H_