advanced_server_flex.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015
  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. // Example: Advanced server, flex (plain + SSL)
  12. //
  13. //------------------------------------------------------------------------------
  14. #include "example/common/server_certificate.hpp"
  15. #include <boost/beast/core.hpp>
  16. #include <boost/beast/http.hpp>
  17. #include <boost/beast/ssl.hpp>
  18. #include <boost/beast/websocket.hpp>
  19. #include <boost/beast/version.hpp>
  20. #include <boost/asio/bind_executor.hpp>
  21. #include <boost/asio/signal_set.hpp>
  22. #include <boost/asio/steady_timer.hpp>
  23. #include <boost/asio/strand.hpp>
  24. #include <boost/make_unique.hpp>
  25. #include <boost/optional.hpp>
  26. #include <algorithm>
  27. #include <cstdlib>
  28. #include <functional>
  29. #include <iostream>
  30. #include <memory>
  31. #include <string>
  32. #include <thread>
  33. #include <vector>
  34. namespace beast = boost::beast; // from <boost/beast.hpp>
  35. namespace http = beast::http; // from <boost/beast/http.hpp>
  36. namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
  37. namespace net = boost::asio; // from <boost/asio.hpp>
  38. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
  39. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  40. // Return a reasonable mime type based on the extension of a file.
  41. beast::string_view
  42. mime_type(beast::string_view path)
  43. {
  44. using beast::iequals;
  45. auto const ext = [&path]
  46. {
  47. auto const pos = path.rfind(".");
  48. if(pos == beast::string_view::npos)
  49. return beast::string_view{};
  50. return path.substr(pos);
  51. }();
  52. if(iequals(ext, ".htm")) return "text/html";
  53. if(iequals(ext, ".html")) return "text/html";
  54. if(iequals(ext, ".php")) return "text/html";
  55. if(iequals(ext, ".css")) return "text/css";
  56. if(iequals(ext, ".txt")) return "text/plain";
  57. if(iequals(ext, ".js")) return "application/javascript";
  58. if(iequals(ext, ".json")) return "application/json";
  59. if(iequals(ext, ".xml")) return "application/xml";
  60. if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
  61. if(iequals(ext, ".flv")) return "video/x-flv";
  62. if(iequals(ext, ".png")) return "image/png";
  63. if(iequals(ext, ".jpe")) return "image/jpeg";
  64. if(iequals(ext, ".jpeg")) return "image/jpeg";
  65. if(iequals(ext, ".jpg")) return "image/jpeg";
  66. if(iequals(ext, ".gif")) return "image/gif";
  67. if(iequals(ext, ".bmp")) return "image/bmp";
  68. if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
  69. if(iequals(ext, ".tiff")) return "image/tiff";
  70. if(iequals(ext, ".tif")) return "image/tiff";
  71. if(iequals(ext, ".svg")) return "image/svg+xml";
  72. if(iequals(ext, ".svgz")) return "image/svg+xml";
  73. return "application/text";
  74. }
  75. // Append an HTTP rel-path to a local filesystem path.
  76. // The returned path is normalized for the platform.
  77. std::string
  78. path_cat(
  79. beast::string_view base,
  80. beast::string_view path)
  81. {
  82. if(base.empty())
  83. return std::string(path);
  84. std::string result(base);
  85. #ifdef BOOST_MSVC
  86. char constexpr path_separator = '\\';
  87. if(result.back() == path_separator)
  88. result.resize(result.size() - 1);
  89. result.append(path.data(), path.size());
  90. for(auto& c : result)
  91. if(c == '/')
  92. c = path_separator;
  93. #else
  94. char constexpr path_separator = '/';
  95. if(result.back() == path_separator)
  96. result.resize(result.size() - 1);
  97. result.append(path.data(), path.size());
  98. #endif
  99. return result;
  100. }
  101. // This function produces an HTTP response for the given
  102. // request. The type of the response object depends on the
  103. // contents of the request, so the interface requires the
  104. // caller to pass a generic lambda for receiving the response.
  105. template<
  106. class Body, class Allocator,
  107. class Send>
  108. void
  109. handle_request(
  110. beast::string_view doc_root,
  111. http::request<Body, http::basic_fields<Allocator>>&& req,
  112. Send&& send)
  113. {
  114. // Returns a bad request response
  115. auto const bad_request =
  116. [&req](beast::string_view why)
  117. {
  118. http::response<http::string_body> res{http::status::bad_request, req.version()};
  119. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  120. res.set(http::field::content_type, "text/html");
  121. res.keep_alive(req.keep_alive());
  122. res.body() = std::string(why);
  123. res.prepare_payload();
  124. return res;
  125. };
  126. // Returns a not found response
  127. auto const not_found =
  128. [&req](beast::string_view target)
  129. {
  130. http::response<http::string_body> res{http::status::not_found, req.version()};
  131. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  132. res.set(http::field::content_type, "text/html");
  133. res.keep_alive(req.keep_alive());
  134. res.body() = "The resource '" + std::string(target) + "' was not found.";
  135. res.prepare_payload();
  136. return res;
  137. };
  138. // Returns a server error response
  139. auto const server_error =
  140. [&req](beast::string_view what)
  141. {
  142. http::response<http::string_body> res{http::status::internal_server_error, req.version()};
  143. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  144. res.set(http::field::content_type, "text/html");
  145. res.keep_alive(req.keep_alive());
  146. res.body() = "An error occurred: '" + std::string(what) + "'";
  147. res.prepare_payload();
  148. return res;
  149. };
  150. // Make sure we can handle the method
  151. if( req.method() != http::verb::get &&
  152. req.method() != http::verb::head)
  153. return send(bad_request("Unknown HTTP-method"));
  154. // Request path must be absolute and not contain "..".
  155. if( req.target().empty() ||
  156. req.target()[0] != '/' ||
  157. req.target().find("..") != beast::string_view::npos)
  158. return send(bad_request("Illegal request-target"));
  159. // Build the path to the requested file
  160. std::string path = path_cat(doc_root, req.target());
  161. if(req.target().back() == '/')
  162. path.append("index.html");
  163. // Attempt to open the file
  164. beast::error_code ec;
  165. http::file_body::value_type body;
  166. body.open(path.c_str(), beast::file_mode::scan, ec);
  167. // Handle the case where the file doesn't exist
  168. if(ec == beast::errc::no_such_file_or_directory)
  169. return send(not_found(req.target()));
  170. // Handle an unknown error
  171. if(ec)
  172. return send(server_error(ec.message()));
  173. // Cache the size since we need it after the move
  174. auto const size = body.size();
  175. // Respond to HEAD request
  176. if(req.method() == http::verb::head)
  177. {
  178. http::response<http::empty_body> res{http::status::ok, req.version()};
  179. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  180. res.set(http::field::content_type, mime_type(path));
  181. res.content_length(size);
  182. res.keep_alive(req.keep_alive());
  183. return send(std::move(res));
  184. }
  185. // Respond to GET request
  186. http::response<http::file_body> res{
  187. std::piecewise_construct,
  188. std::make_tuple(std::move(body)),
  189. std::make_tuple(http::status::ok, req.version())};
  190. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  191. res.set(http::field::content_type, mime_type(path));
  192. res.content_length(size);
  193. res.keep_alive(req.keep_alive());
  194. return send(std::move(res));
  195. }
  196. //------------------------------------------------------------------------------
  197. // Report a failure
  198. void
  199. fail(beast::error_code ec, char const* what)
  200. {
  201. // ssl::error::stream_truncated, also known as an SSL "short read",
  202. // indicates the peer closed the connection without performing the
  203. // required closing handshake (for example, Google does this to
  204. // improve performance). Generally this can be a security issue,
  205. // but if your communication protocol is self-terminated (as
  206. // it is with both HTTP and WebSocket) then you may simply
  207. // ignore the lack of close_notify.
  208. //
  209. // https://github.com/boostorg/beast/issues/38
  210. //
  211. // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
  212. //
  213. // When a short read would cut off the end of an HTTP message,
  214. // Beast returns the error beast::http::error::partial_message.
  215. // Therefore, if we see a short read here, it has occurred
  216. // after the message has been completed, so it is safe to ignore it.
  217. if(ec == net::ssl::error::stream_truncated)
  218. return;
  219. std::cerr << what << ": " << ec.message() << "\n";
  220. }
  221. //------------------------------------------------------------------------------
  222. // Echoes back all received WebSocket messages.
  223. // This uses the Curiously Recurring Template Pattern so that
  224. // the same code works with both SSL streams and regular sockets.
  225. template<class Derived>
  226. class websocket_session
  227. {
  228. // Access the derived class, this is part of
  229. // the Curiously Recurring Template Pattern idiom.
  230. Derived&
  231. derived()
  232. {
  233. return static_cast<Derived&>(*this);
  234. }
  235. beast::flat_buffer buffer_;
  236. // Start the asynchronous operation
  237. template<class Body, class Allocator>
  238. void
  239. do_accept(http::request<Body, http::basic_fields<Allocator>> req)
  240. {
  241. // Set suggested timeout settings for the websocket
  242. derived().ws().set_option(
  243. websocket::stream_base::timeout::suggested(
  244. beast::role_type::server));
  245. // Set a decorator to change the Server of the handshake
  246. derived().ws().set_option(
  247. websocket::stream_base::decorator(
  248. [](websocket::response_type& res)
  249. {
  250. res.set(http::field::server,
  251. std::string(BOOST_BEAST_VERSION_STRING) +
  252. " advanced-server-flex");
  253. }));
  254. // Accept the websocket handshake
  255. derived().ws().async_accept(
  256. req,
  257. beast::bind_front_handler(
  258. &websocket_session::on_accept,
  259. derived().shared_from_this()));
  260. }
  261. void
  262. on_accept(beast::error_code ec)
  263. {
  264. if(ec)
  265. return fail(ec, "accept");
  266. // Read a message
  267. do_read();
  268. }
  269. void
  270. do_read()
  271. {
  272. // Read a message into our buffer
  273. derived().ws().async_read(
  274. buffer_,
  275. beast::bind_front_handler(
  276. &websocket_session::on_read,
  277. derived().shared_from_this()));
  278. }
  279. void
  280. on_read(
  281. beast::error_code ec,
  282. std::size_t bytes_transferred)
  283. {
  284. boost::ignore_unused(bytes_transferred);
  285. // This indicates that the websocket_session was closed
  286. if(ec == websocket::error::closed)
  287. return;
  288. if(ec)
  289. fail(ec, "read");
  290. // Echo the message
  291. derived().ws().text(derived().ws().got_text());
  292. derived().ws().async_write(
  293. buffer_.data(),
  294. beast::bind_front_handler(
  295. &websocket_session::on_write,
  296. derived().shared_from_this()));
  297. }
  298. void
  299. on_write(
  300. beast::error_code ec,
  301. std::size_t bytes_transferred)
  302. {
  303. boost::ignore_unused(bytes_transferred);
  304. if(ec)
  305. return fail(ec, "write");
  306. // Clear the buffer
  307. buffer_.consume(buffer_.size());
  308. // Do another read
  309. do_read();
  310. }
  311. public:
  312. // Start the asynchronous operation
  313. template<class Body, class Allocator>
  314. void
  315. run(http::request<Body, http::basic_fields<Allocator>> req)
  316. {
  317. // Accept the WebSocket upgrade request
  318. do_accept(std::move(req));
  319. }
  320. };
  321. //------------------------------------------------------------------------------
  322. // Handles a plain WebSocket connection
  323. class plain_websocket_session
  324. : public websocket_session<plain_websocket_session>
  325. , public std::enable_shared_from_this<plain_websocket_session>
  326. {
  327. websocket::stream<beast::tcp_stream> ws_;
  328. public:
  329. // Create the session
  330. explicit
  331. plain_websocket_session(
  332. beast::tcp_stream&& stream)
  333. : ws_(std::move(stream))
  334. {
  335. }
  336. // Called by the base class
  337. websocket::stream<beast::tcp_stream>&
  338. ws()
  339. {
  340. return ws_;
  341. }
  342. };
  343. //------------------------------------------------------------------------------
  344. // Handles an SSL WebSocket connection
  345. class ssl_websocket_session
  346. : public websocket_session<ssl_websocket_session>
  347. , public std::enable_shared_from_this<ssl_websocket_session>
  348. {
  349. websocket::stream<
  350. beast::ssl_stream<beast::tcp_stream>> ws_;
  351. public:
  352. // Create the ssl_websocket_session
  353. explicit
  354. ssl_websocket_session(
  355. beast::ssl_stream<beast::tcp_stream>&& stream)
  356. : ws_(std::move(stream))
  357. {
  358. }
  359. // Called by the base class
  360. websocket::stream<
  361. beast::ssl_stream<beast::tcp_stream>>&
  362. ws()
  363. {
  364. return ws_;
  365. }
  366. };
  367. //------------------------------------------------------------------------------
  368. template<class Body, class Allocator>
  369. void
  370. make_websocket_session(
  371. beast::tcp_stream stream,
  372. http::request<Body, http::basic_fields<Allocator>> req)
  373. {
  374. std::make_shared<plain_websocket_session>(
  375. std::move(stream))->run(std::move(req));
  376. }
  377. template<class Body, class Allocator>
  378. void
  379. make_websocket_session(
  380. beast::ssl_stream<beast::tcp_stream> stream,
  381. http::request<Body, http::basic_fields<Allocator>> req)
  382. {
  383. std::make_shared<ssl_websocket_session>(
  384. std::move(stream))->run(std::move(req));
  385. }
  386. //------------------------------------------------------------------------------
  387. // Handles an HTTP server connection.
  388. // This uses the Curiously Recurring Template Pattern so that
  389. // the same code works with both SSL streams and regular sockets.
  390. template<class Derived>
  391. class http_session
  392. {
  393. // Access the derived class, this is part of
  394. // the Curiously Recurring Template Pattern idiom.
  395. Derived&
  396. derived()
  397. {
  398. return static_cast<Derived&>(*this);
  399. }
  400. // This queue is used for HTTP pipelining.
  401. class queue
  402. {
  403. enum
  404. {
  405. // Maximum number of responses we will queue
  406. limit = 8
  407. };
  408. // The type-erased, saved work item
  409. struct work
  410. {
  411. virtual ~work() = default;
  412. virtual void operator()() = 0;
  413. };
  414. http_session& self_;
  415. std::vector<std::unique_ptr<work>> items_;
  416. public:
  417. explicit
  418. queue(http_session& self)
  419. : self_(self)
  420. {
  421. static_assert(limit > 0, "queue limit must be positive");
  422. items_.reserve(limit);
  423. }
  424. // Returns `true` if we have reached the queue limit
  425. bool
  426. is_full() const
  427. {
  428. return items_.size() >= limit;
  429. }
  430. // Called when a message finishes sending
  431. // Returns `true` if the caller should initiate a read
  432. bool
  433. on_write()
  434. {
  435. BOOST_ASSERT(! items_.empty());
  436. auto const was_full = is_full();
  437. items_.erase(items_.begin());
  438. if(! items_.empty())
  439. (*items_.front())();
  440. return was_full;
  441. }
  442. // Called by the HTTP handler to send a response.
  443. template<bool isRequest, class Body, class Fields>
  444. void
  445. operator()(http::message<isRequest, Body, Fields>&& msg)
  446. {
  447. // This holds a work item
  448. struct work_impl : work
  449. {
  450. http_session& self_;
  451. http::message<isRequest, Body, Fields> msg_;
  452. work_impl(
  453. http_session& self,
  454. http::message<isRequest, Body, Fields>&& msg)
  455. : self_(self)
  456. , msg_(std::move(msg))
  457. {
  458. }
  459. void
  460. operator()()
  461. {
  462. http::async_write(
  463. self_.derived().stream(),
  464. msg_,
  465. beast::bind_front_handler(
  466. &http_session::on_write,
  467. self_.derived().shared_from_this(),
  468. msg_.need_eof()));
  469. }
  470. };
  471. // Allocate and store the work
  472. items_.push_back(
  473. boost::make_unique<work_impl>(self_, std::move(msg)));
  474. // If there was no previous work, start this one
  475. if(items_.size() == 1)
  476. (*items_.front())();
  477. }
  478. };
  479. std::shared_ptr<std::string const> doc_root_;
  480. queue queue_;
  481. // The parser is stored in an optional container so we can
  482. // construct it from scratch it at the beginning of each new message.
  483. boost::optional<http::request_parser<http::string_body>> parser_;
  484. protected:
  485. beast::flat_buffer buffer_;
  486. public:
  487. // Construct the session
  488. http_session(
  489. beast::flat_buffer buffer,
  490. std::shared_ptr<std::string const> const& doc_root)
  491. : doc_root_(doc_root)
  492. , queue_(*this)
  493. , buffer_(std::move(buffer))
  494. {
  495. }
  496. void
  497. do_read()
  498. {
  499. // Construct a new parser for each message
  500. parser_.emplace();
  501. // Apply a reasonable limit to the allowed size
  502. // of the body in bytes to prevent abuse.
  503. parser_->body_limit(10000);
  504. // Set the timeout.
  505. beast::get_lowest_layer(
  506. derived().stream()).expires_after(std::chrono::seconds(30));
  507. // Read a request using the parser-oriented interface
  508. http::async_read(
  509. derived().stream(),
  510. buffer_,
  511. *parser_,
  512. beast::bind_front_handler(
  513. &http_session::on_read,
  514. derived().shared_from_this()));
  515. }
  516. void
  517. on_read(beast::error_code ec, std::size_t bytes_transferred)
  518. {
  519. boost::ignore_unused(bytes_transferred);
  520. // This means they closed the connection
  521. if(ec == http::error::end_of_stream)
  522. return derived().do_eof();
  523. if(ec)
  524. return fail(ec, "read");
  525. // See if it is a WebSocket Upgrade
  526. if(websocket::is_upgrade(parser_->get()))
  527. {
  528. // Disable the timeout.
  529. // The websocket::stream uses its own timeout settings.
  530. beast::get_lowest_layer(derived().stream()).expires_never();
  531. // Create a websocket session, transferring ownership
  532. // of both the socket and the HTTP request.
  533. return make_websocket_session(
  534. derived().release_stream(),
  535. parser_->release());
  536. }
  537. // Send the response
  538. handle_request(*doc_root_, parser_->release(), queue_);
  539. // If we aren't at the queue limit, try to pipeline another request
  540. if(! queue_.is_full())
  541. do_read();
  542. }
  543. void
  544. on_write(bool close, beast::error_code ec, std::size_t bytes_transferred)
  545. {
  546. boost::ignore_unused(bytes_transferred);
  547. if(ec)
  548. return fail(ec, "write");
  549. if(close)
  550. {
  551. // This means we should close the connection, usually because
  552. // the response indicated the "Connection: close" semantic.
  553. return derived().do_eof();
  554. }
  555. // Inform the queue that a write completed
  556. if(queue_.on_write())
  557. {
  558. // Read another request
  559. do_read();
  560. }
  561. }
  562. };
  563. //------------------------------------------------------------------------------
  564. // Handles a plain HTTP connection
  565. class plain_http_session
  566. : public http_session<plain_http_session>
  567. , public std::enable_shared_from_this<plain_http_session>
  568. {
  569. beast::tcp_stream stream_;
  570. public:
  571. // Create the session
  572. plain_http_session(
  573. beast::tcp_stream&& stream,
  574. beast::flat_buffer&& buffer,
  575. std::shared_ptr<std::string const> const& doc_root)
  576. : http_session<plain_http_session>(
  577. std::move(buffer),
  578. doc_root)
  579. , stream_(std::move(stream))
  580. {
  581. }
  582. // Start the session
  583. void
  584. run()
  585. {
  586. this->do_read();
  587. }
  588. // Called by the base class
  589. beast::tcp_stream&
  590. stream()
  591. {
  592. return stream_;
  593. }
  594. // Called by the base class
  595. beast::tcp_stream
  596. release_stream()
  597. {
  598. return std::move(stream_);
  599. }
  600. // Called by the base class
  601. void
  602. do_eof()
  603. {
  604. // Send a TCP shutdown
  605. beast::error_code ec;
  606. stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
  607. // At this point the connection is closed gracefully
  608. }
  609. };
  610. //------------------------------------------------------------------------------
  611. // Handles an SSL HTTP connection
  612. class ssl_http_session
  613. : public http_session<ssl_http_session>
  614. , public std::enable_shared_from_this<ssl_http_session>
  615. {
  616. beast::ssl_stream<beast::tcp_stream> stream_;
  617. public:
  618. // Create the http_session
  619. ssl_http_session(
  620. beast::tcp_stream&& stream,
  621. ssl::context& ctx,
  622. beast::flat_buffer&& buffer,
  623. std::shared_ptr<std::string const> const& doc_root)
  624. : http_session<ssl_http_session>(
  625. std::move(buffer),
  626. doc_root)
  627. , stream_(std::move(stream), ctx)
  628. {
  629. }
  630. // Start the session
  631. void
  632. run()
  633. {
  634. // Set the timeout.
  635. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
  636. // Perform the SSL handshake
  637. // Note, this is the buffered version of the handshake.
  638. stream_.async_handshake(
  639. ssl::stream_base::server,
  640. buffer_.data(),
  641. beast::bind_front_handler(
  642. &ssl_http_session::on_handshake,
  643. shared_from_this()));
  644. }
  645. // Called by the base class
  646. beast::ssl_stream<beast::tcp_stream>&
  647. stream()
  648. {
  649. return stream_;
  650. }
  651. // Called by the base class
  652. beast::ssl_stream<beast::tcp_stream>
  653. release_stream()
  654. {
  655. return std::move(stream_);
  656. }
  657. // Called by the base class
  658. void
  659. do_eof()
  660. {
  661. // Set the timeout.
  662. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
  663. // Perform the SSL shutdown
  664. stream_.async_shutdown(
  665. beast::bind_front_handler(
  666. &ssl_http_session::on_shutdown,
  667. shared_from_this()));
  668. }
  669. private:
  670. void
  671. on_handshake(
  672. beast::error_code ec,
  673. std::size_t bytes_used)
  674. {
  675. if(ec)
  676. return fail(ec, "handshake");
  677. // Consume the portion of the buffer used by the handshake
  678. buffer_.consume(bytes_used);
  679. do_read();
  680. }
  681. void
  682. on_shutdown(beast::error_code ec)
  683. {
  684. if(ec)
  685. return fail(ec, "shutdown");
  686. // At this point the connection is closed gracefully
  687. }
  688. };
  689. //------------------------------------------------------------------------------
  690. // Detects SSL handshakes
  691. class detect_session : public std::enable_shared_from_this<detect_session>
  692. {
  693. beast::tcp_stream stream_;
  694. ssl::context& ctx_;
  695. std::shared_ptr<std::string const> doc_root_;
  696. beast::flat_buffer buffer_;
  697. public:
  698. explicit
  699. detect_session(
  700. tcp::socket&& socket,
  701. ssl::context& ctx,
  702. std::shared_ptr<std::string const> const& doc_root)
  703. : stream_(std::move(socket))
  704. , ctx_(ctx)
  705. , doc_root_(doc_root)
  706. {
  707. }
  708. // Launch the detector
  709. void
  710. run()
  711. {
  712. // Set the timeout.
  713. stream_.expires_after(std::chrono::seconds(30));
  714. beast::async_detect_ssl(
  715. stream_,
  716. buffer_,
  717. beast::bind_front_handler(
  718. &detect_session::on_detect,
  719. this->shared_from_this()));
  720. }
  721. void
  722. on_detect(beast::error_code ec, bool result)
  723. {
  724. if(ec)
  725. return fail(ec, "detect");
  726. if(result)
  727. {
  728. // Launch SSL session
  729. std::make_shared<ssl_http_session>(
  730. std::move(stream_),
  731. ctx_,
  732. std::move(buffer_),
  733. doc_root_)->run();
  734. return;
  735. }
  736. // Launch plain session
  737. std::make_shared<plain_http_session>(
  738. std::move(stream_),
  739. std::move(buffer_),
  740. doc_root_)->run();
  741. }
  742. };
  743. // Accepts incoming connections and launches the sessions
  744. class listener : public std::enable_shared_from_this<listener>
  745. {
  746. net::io_context& ioc_;
  747. ssl::context& ctx_;
  748. tcp::acceptor acceptor_;
  749. std::shared_ptr<std::string const> doc_root_;
  750. public:
  751. listener(
  752. net::io_context& ioc,
  753. ssl::context& ctx,
  754. tcp::endpoint endpoint,
  755. std::shared_ptr<std::string const> const& doc_root)
  756. : ioc_(ioc)
  757. , ctx_(ctx)
  758. , acceptor_(net::make_strand(ioc))
  759. , doc_root_(doc_root)
  760. {
  761. beast::error_code ec;
  762. // Open the acceptor
  763. acceptor_.open(endpoint.protocol(), ec);
  764. if(ec)
  765. {
  766. fail(ec, "open");
  767. return;
  768. }
  769. // Allow address reuse
  770. acceptor_.set_option(net::socket_base::reuse_address(true), ec);
  771. if(ec)
  772. {
  773. fail(ec, "set_option");
  774. return;
  775. }
  776. // Bind to the server address
  777. acceptor_.bind(endpoint, ec);
  778. if(ec)
  779. {
  780. fail(ec, "bind");
  781. return;
  782. }
  783. // Start listening for connections
  784. acceptor_.listen(
  785. net::socket_base::max_listen_connections, ec);
  786. if(ec)
  787. {
  788. fail(ec, "listen");
  789. return;
  790. }
  791. }
  792. // Start accepting incoming connections
  793. void
  794. run()
  795. {
  796. do_accept();
  797. }
  798. private:
  799. void
  800. do_accept()
  801. {
  802. // The new connection gets its own strand
  803. acceptor_.async_accept(
  804. net::make_strand(ioc_),
  805. beast::bind_front_handler(
  806. &listener::on_accept,
  807. shared_from_this()));
  808. }
  809. void
  810. on_accept(beast::error_code ec, tcp::socket socket)
  811. {
  812. if(ec)
  813. {
  814. fail(ec, "accept");
  815. }
  816. else
  817. {
  818. // Create the detector http_session and run it
  819. std::make_shared<detect_session>(
  820. std::move(socket),
  821. ctx_,
  822. doc_root_)->run();
  823. }
  824. // Accept another connection
  825. do_accept();
  826. }
  827. };
  828. //------------------------------------------------------------------------------
  829. int main(int argc, char* argv[])
  830. {
  831. // Check command line arguments.
  832. if (argc != 5)
  833. {
  834. std::cerr <<
  835. "Usage: advanced-server-flex <address> <port> <doc_root> <threads>\n" <<
  836. "Example:\n" <<
  837. " advanced-server-flex 0.0.0.0 8080 . 1\n";
  838. return EXIT_FAILURE;
  839. }
  840. auto const address = net::ip::make_address(argv[1]);
  841. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  842. auto const doc_root = std::make_shared<std::string>(argv[3]);
  843. auto const threads = std::max<int>(1, std::atoi(argv[4]));
  844. // The io_context is required for all I/O
  845. net::io_context ioc{threads};
  846. // The SSL context is required, and holds certificates
  847. ssl::context ctx{ssl::context::tlsv12};
  848. // This holds the self-signed certificate used by the server
  849. load_server_certificate(ctx);
  850. // Create and launch a listening port
  851. std::make_shared<listener>(
  852. ioc,
  853. ctx,
  854. tcp::endpoint{address, port},
  855. doc_root)->run();
  856. // Capture SIGINT and SIGTERM to perform a clean shutdown
  857. net::signal_set signals(ioc, SIGINT, SIGTERM);
  858. signals.async_wait(
  859. [&](beast::error_code const&, int)
  860. {
  861. // Stop the `io_context`. This will cause `run()`
  862. // to return immediately, eventually destroying the
  863. // `io_context` and all of the sockets in it.
  864. ioc.stop();
  865. });
  866. // Run the I/O service on the requested number of threads
  867. std::vector<std::thread> v;
  868. v.reserve(threads - 1);
  869. for(auto i = threads - 1; i > 0; --i)
  870. v.emplace_back(
  871. [&ioc]
  872. {
  873. ioc.run();
  874. });
  875. ioc.run();
  876. // (If we get here, it means we got a SIGINT or SIGTERM)
  877. // Block until all the threads exit
  878. for(auto& t : v)
  879. t.join();
  880. return EXIT_SUCCESS;
  881. }