1 //
2 // Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
3 //
4 // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 //
7 // Official repository: https://github.com/boostorg/beast
8 //
9
10 //------------------------------------------------------------------------------
11 //
12 // Example: WebSocket SSL server, coroutine
13 //
14 //------------------------------------------------------------------------------
15
16 #include "example/common/server_certificate.hpp"
17
18 #include <boost/beast/core.hpp>
19 #include <boost/beast/ssl.hpp>
20 #include <boost/beast/websocket.hpp>
21 #include <boost/beast/websocket/ssl.hpp>
22 #include <boost/asio/spawn.hpp>
23 #include <algorithm>
24 #include <cstdlib>
25 #include <functional>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <thread>
30 #include <vector>
31
32 namespace beast = boost::beast; // from <boost/beast.hpp>
33 namespace http = beast::http; // from <boost/beast/http.hpp>
34 namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
35 namespace net = boost::asio; // from <boost/asio.hpp>
36 namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
37 using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
38
39 //------------------------------------------------------------------------------
40
41 // Report a failure
42 void
fail(beast::error_code ec,char const * what)43 fail(beast::error_code ec, char const* what)
44 {
45 std::cerr << what << ": " << ec.message() << "\n";
46 }
47
48 // Echoes back all received WebSocket messages
49 void
do_session(websocket::stream<beast::ssl_stream<beast::tcp_stream>> & ws,net::yield_context yield)50 do_session(
51 websocket::stream<
52 beast::ssl_stream<beast::tcp_stream>>& ws,
53 net::yield_context yield)
54 {
55 beast::error_code ec;
56
57 // Set the timeout.
58 beast::get_lowest_layer(ws).expires_after(std::chrono::seconds(30));
59
60 // Perform the SSL handshake
61 ws.next_layer().async_handshake(ssl::stream_base::server, yield[ec]);
62 if(ec)
63 return fail(ec, "handshake");
64
65 // Turn off the timeout on the tcp_stream, because
66 // the websocket stream has its own timeout system.
67 beast::get_lowest_layer(ws).expires_never();
68
69 // Set suggested timeout settings for the websocket
70 ws.set_option(
71 websocket::stream_base::timeout::suggested(
72 beast::role_type::server));
73
74 // Set a decorator to change the Server of the handshake
75 ws.set_option(websocket::stream_base::decorator(
76 [](websocket::response_type& res)
77 {
78 res.set(http::field::server,
79 std::string(BOOST_BEAST_VERSION_STRING) +
80 " websocket-server-coro-ssl");
81 }));
82
83 // Accept the websocket handshake
84 ws.async_accept(yield[ec]);
85 if(ec)
86 return fail(ec, "accept");
87
88 for(;;)
89 {
90 // This buffer will hold the incoming message
91 beast::flat_buffer buffer;
92
93 // Read a message
94 ws.async_read(buffer, yield[ec]);
95
96 // This indicates that the session was closed
97 if(ec == websocket::error::closed)
98 break;
99
100 if(ec)
101 return fail(ec, "read");
102
103 // Echo the message back
104 ws.text(ws.got_text());
105 ws.async_write(buffer.data(), yield[ec]);
106 if(ec)
107 return fail(ec, "write");
108 }
109 }
110
111 //------------------------------------------------------------------------------
112
113 // Accepts incoming connections and launches the sessions
114 void
do_listen(net::io_context & ioc,ssl::context & ctx,tcp::endpoint endpoint,net::yield_context yield)115 do_listen(
116 net::io_context& ioc,
117 ssl::context& ctx,
118 tcp::endpoint endpoint,
119 net::yield_context yield)
120 {
121 beast::error_code ec;
122
123 // Open the acceptor
124 tcp::acceptor acceptor(ioc);
125 acceptor.open(endpoint.protocol(), ec);
126 if(ec)
127 return fail(ec, "open");
128
129 // Allow address reuse
130 acceptor.set_option(net::socket_base::reuse_address(true), ec);
131 if(ec)
132 return fail(ec, "set_option");
133
134 // Bind to the server address
135 acceptor.bind(endpoint, ec);
136 if(ec)
137 return fail(ec, "bind");
138
139 // Start listening for connections
140 acceptor.listen(net::socket_base::max_listen_connections, ec);
141 if(ec)
142 return fail(ec, "listen");
143
144 for(;;)
145 {
146 tcp::socket socket(ioc);
147 acceptor.async_accept(socket, yield[ec]);
148 if(ec)
149 fail(ec, "accept");
150 else
151 boost::asio::spawn(
152 acceptor.get_executor(),
153 std::bind(
154 &do_session,
155 websocket::stream<beast::ssl_stream<
156 beast::tcp_stream>>(std::move(socket), ctx),
157 std::placeholders::_1));
158 }
159 }
160
main(int argc,char * argv[])161 int main(int argc, char* argv[])
162 {
163 // Check command line arguments.
164 if (argc != 4)
165 {
166 std::cerr <<
167 "Usage: websocket-server-coro-ssl <address> <port> <threads>\n" <<
168 "Example:\n" <<
169 " websocket-server-coro-ssl 0.0.0.0 8080 1\n";
170 return EXIT_FAILURE;
171 }
172 auto const address = net::ip::make_address(argv[1]);
173 auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
174 auto const threads = std::max<int>(1, std::atoi(argv[3]));
175
176 // The io_context is required for all I/O
177 net::io_context ioc{threads};
178
179 // The SSL context is required, and holds certificates
180 ssl::context ctx{ssl::context::tlsv12};
181
182 // This holds the self-signed certificate used by the server
183 load_server_certificate(ctx);
184
185 // Spawn a listening port
186 boost::asio::spawn(ioc,
187 std::bind(
188 &do_listen,
189 std::ref(ioc),
190 std::ref(ctx),
191 tcp::endpoint{address, port},
192 std::placeholders::_1));
193
194 // Run the I/O service on the requested number of threads
195 std::vector<std::thread> v;
196 v.reserve(threads - 1);
197 for(auto i = threads - 1; i > 0; --i)
198 v.emplace_back(
199 [&ioc]
200 {
201 ioc.run();
202 });
203 ioc.run();
204
205 return EXIT_SUCCESS;
206 }
207