http_server_flex.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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: HTTP flex server (plain and SSL), asynchronous
  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/version.hpp>
  19. #include <boost/asio/dispatch.hpp>
  20. #include <boost/asio/strand.hpp>
  21. #include <boost/config.hpp>
  22. #include <algorithm>
  23. #include <cstdlib>
  24. #include <functional>
  25. #include <iostream>
  26. #include <memory>
  27. #include <string>
  28. #include <thread>
  29. namespace beast = boost::beast; // from <boost/beast.hpp>
  30. namespace http = beast::http; // from <boost/beast/http.hpp>
  31. namespace net = boost::asio; // from <boost/asio.hpp>
  32. namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
  33. using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
  34. // Return a reasonable mime type based on the extension of a file.
  35. beast::string_view
  36. mime_type(beast::string_view path)
  37. {
  38. using beast::iequals;
  39. auto const ext = [&path]
  40. {
  41. auto const pos = path.rfind(".");
  42. if(pos == beast::string_view::npos)
  43. return beast::string_view{};
  44. return path.substr(pos);
  45. }();
  46. if(iequals(ext, ".htm")) return "text/html";
  47. if(iequals(ext, ".html")) return "text/html";
  48. if(iequals(ext, ".php")) return "text/html";
  49. if(iequals(ext, ".css")) return "text/css";
  50. if(iequals(ext, ".txt")) return "text/plain";
  51. if(iequals(ext, ".js")) return "application/javascript";
  52. if(iequals(ext, ".json")) return "application/json";
  53. if(iequals(ext, ".xml")) return "application/xml";
  54. if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
  55. if(iequals(ext, ".flv")) return "video/x-flv";
  56. if(iequals(ext, ".png")) return "image/png";
  57. if(iequals(ext, ".jpe")) return "image/jpeg";
  58. if(iequals(ext, ".jpeg")) return "image/jpeg";
  59. if(iequals(ext, ".jpg")) return "image/jpeg";
  60. if(iequals(ext, ".gif")) return "image/gif";
  61. if(iequals(ext, ".bmp")) return "image/bmp";
  62. if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
  63. if(iequals(ext, ".tiff")) return "image/tiff";
  64. if(iequals(ext, ".tif")) return "image/tiff";
  65. if(iequals(ext, ".svg")) return "image/svg+xml";
  66. if(iequals(ext, ".svgz")) return "image/svg+xml";
  67. return "application/text";
  68. }
  69. // Append an HTTP rel-path to a local filesystem path.
  70. // The returned path is normalized for the platform.
  71. std::string
  72. path_cat(
  73. beast::string_view base,
  74. beast::string_view path)
  75. {
  76. if(base.empty())
  77. return std::string(path);
  78. std::string result(base);
  79. #ifdef BOOST_MSVC
  80. char constexpr path_separator = '\\';
  81. if(result.back() == path_separator)
  82. result.resize(result.size() - 1);
  83. result.append(path.data(), path.size());
  84. for(auto& c : result)
  85. if(c == '/')
  86. c = path_separator;
  87. #else
  88. char constexpr path_separator = '/';
  89. if(result.back() == path_separator)
  90. result.resize(result.size() - 1);
  91. result.append(path.data(), path.size());
  92. #endif
  93. return result;
  94. }
  95. // This function produces an HTTP response for the given
  96. // request. The type of the response object depends on the
  97. // contents of the request, so the interface requires the
  98. // caller to pass a generic lambda for receiving the response.
  99. template<
  100. class Body, class Allocator,
  101. class Send>
  102. void
  103. handle_request(
  104. beast::string_view doc_root,
  105. http::request<Body, http::basic_fields<Allocator>>&& req,
  106. Send&& send)
  107. {
  108. // Returns a bad request response
  109. auto const bad_request =
  110. [&req](beast::string_view why)
  111. {
  112. http::response<http::string_body> res{http::status::bad_request, req.version()};
  113. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  114. res.set(http::field::content_type, "text/html");
  115. res.keep_alive(req.keep_alive());
  116. res.body() = std::string(why);
  117. res.prepare_payload();
  118. return res;
  119. };
  120. // Returns a not found response
  121. auto const not_found =
  122. [&req](beast::string_view target)
  123. {
  124. http::response<http::string_body> res{http::status::not_found, req.version()};
  125. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  126. res.set(http::field::content_type, "text/html");
  127. res.keep_alive(req.keep_alive());
  128. res.body() = "The resource '" + std::string(target) + "' was not found.";
  129. res.prepare_payload();
  130. return res;
  131. };
  132. // Returns a server error response
  133. auto const server_error =
  134. [&req](beast::string_view what)
  135. {
  136. http::response<http::string_body> res{http::status::internal_server_error, req.version()};
  137. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  138. res.set(http::field::content_type, "text/html");
  139. res.keep_alive(req.keep_alive());
  140. res.body() = "An error occurred: '" + std::string(what) + "'";
  141. res.prepare_payload();
  142. return res;
  143. };
  144. // Make sure we can handle the method
  145. if( req.method() != http::verb::get &&
  146. req.method() != http::verb::head)
  147. return send(bad_request("Unknown HTTP-method"));
  148. // Request path must be absolute and not contain "..".
  149. if( req.target().empty() ||
  150. req.target()[0] != '/' ||
  151. req.target().find("..") != beast::string_view::npos)
  152. return send(bad_request("Illegal request-target"));
  153. // Build the path to the requested file
  154. std::string path = path_cat(doc_root, req.target());
  155. if(req.target().back() == '/')
  156. path.append("index.html");
  157. // Attempt to open the file
  158. beast::error_code ec;
  159. http::file_body::value_type body;
  160. body.open(path.c_str(), beast::file_mode::scan, ec);
  161. // Handle the case where the file doesn't exist
  162. if(ec == beast::errc::no_such_file_or_directory)
  163. return send(not_found(req.target()));
  164. // Handle an unknown error
  165. if(ec)
  166. return send(server_error(ec.message()));
  167. // Cache the size since we need it after the move
  168. auto const size = body.size();
  169. // Respond to HEAD request
  170. if(req.method() == http::verb::head)
  171. {
  172. http::response<http::empty_body> res{http::status::ok, req.version()};
  173. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  174. res.set(http::field::content_type, mime_type(path));
  175. res.content_length(size);
  176. res.keep_alive(req.keep_alive());
  177. return send(std::move(res));
  178. }
  179. // Respond to GET request
  180. http::response<http::file_body> res{
  181. std::piecewise_construct,
  182. std::make_tuple(std::move(body)),
  183. std::make_tuple(http::status::ok, req.version())};
  184. res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
  185. res.set(http::field::content_type, mime_type(path));
  186. res.content_length(size);
  187. res.keep_alive(req.keep_alive());
  188. return send(std::move(res));
  189. }
  190. //------------------------------------------------------------------------------
  191. // Report a failure
  192. void
  193. fail(beast::error_code ec, char const* what)
  194. {
  195. // ssl::error::stream_truncated, also known as an SSL "short read",
  196. // indicates the peer closed the connection without performing the
  197. // required closing handshake (for example, Google does this to
  198. // improve performance). Generally this can be a security issue,
  199. // but if your communication protocol is self-terminated (as
  200. // it is with both HTTP and WebSocket) then you may simply
  201. // ignore the lack of close_notify.
  202. //
  203. // https://github.com/boostorg/beast/issues/38
  204. //
  205. // https://security.stackexchange.com/questions/91435/how-to-handle-a-malicious-ssl-tls-shutdown
  206. //
  207. // When a short read would cut off the end of an HTTP message,
  208. // Beast returns the error beast::http::error::partial_message.
  209. // Therefore, if we see a short read here, it has occurred
  210. // after the message has been completed, so it is safe to ignore it.
  211. if(ec == net::ssl::error::stream_truncated)
  212. return;
  213. std::cerr << what << ": " << ec.message() << "\n";
  214. }
  215. // Handles an HTTP server connection.
  216. // This uses the Curiously Recurring Template Pattern so that
  217. // the same code works with both SSL streams and regular sockets.
  218. template<class Derived>
  219. class session
  220. {
  221. // Access the derived class, this is part of
  222. // the Curiously Recurring Template Pattern idiom.
  223. Derived&
  224. derived()
  225. {
  226. return static_cast<Derived&>(*this);
  227. }
  228. // This is the C++11 equivalent of a generic lambda.
  229. // The function object is used to send an HTTP message.
  230. struct send_lambda
  231. {
  232. session& self_;
  233. explicit
  234. send_lambda(session& self)
  235. : self_(self)
  236. {
  237. }
  238. template<bool isRequest, class Body, class Fields>
  239. void
  240. operator()(http::message<isRequest, Body, Fields>&& msg) const
  241. {
  242. // The lifetime of the message has to extend
  243. // for the duration of the async operation so
  244. // we use a shared_ptr to manage it.
  245. auto sp = std::make_shared<
  246. http::message<isRequest, Body, Fields>>(std::move(msg));
  247. // Store a type-erased version of the shared
  248. // pointer in the class to keep it alive.
  249. self_.res_ = sp;
  250. // Write the response
  251. http::async_write(
  252. self_.derived().stream(),
  253. *sp,
  254. beast::bind_front_handler(
  255. &session::on_write,
  256. self_.derived().shared_from_this(),
  257. sp->need_eof()));
  258. }
  259. };
  260. std::shared_ptr<std::string const> doc_root_;
  261. http::request<http::string_body> req_;
  262. std::shared_ptr<void> res_;
  263. send_lambda lambda_;
  264. protected:
  265. beast::flat_buffer buffer_;
  266. public:
  267. // Take ownership of the buffer
  268. session(
  269. beast::flat_buffer buffer,
  270. std::shared_ptr<std::string const> const& doc_root)
  271. : doc_root_(doc_root)
  272. , lambda_(*this)
  273. , buffer_(std::move(buffer))
  274. {
  275. }
  276. void
  277. do_read()
  278. {
  279. // Set the timeout.
  280. beast::get_lowest_layer(
  281. derived().stream()).expires_after(std::chrono::seconds(30));
  282. // Read a request
  283. http::async_read(
  284. derived().stream(),
  285. buffer_,
  286. req_,
  287. beast::bind_front_handler(
  288. &session::on_read,
  289. derived().shared_from_this()));
  290. }
  291. void
  292. on_read(
  293. beast::error_code ec,
  294. std::size_t bytes_transferred)
  295. {
  296. boost::ignore_unused(bytes_transferred);
  297. // This means they closed the connection
  298. if(ec == http::error::end_of_stream)
  299. return derived().do_eof();
  300. if(ec)
  301. return fail(ec, "read");
  302. // Send the response
  303. handle_request(*doc_root_, std::move(req_), lambda_);
  304. }
  305. void
  306. on_write(
  307. bool close,
  308. beast::error_code ec,
  309. std::size_t bytes_transferred)
  310. {
  311. boost::ignore_unused(bytes_transferred);
  312. if(ec)
  313. return fail(ec, "write");
  314. if(close)
  315. {
  316. // This means we should close the connection, usually because
  317. // the response indicated the "Connection: close" semantic.
  318. return derived().do_eof();
  319. }
  320. // We're done with the response so delete it
  321. res_ = nullptr;
  322. // Read another request
  323. do_read();
  324. }
  325. };
  326. // Handles a plain HTTP connection
  327. class plain_session
  328. : public session<plain_session>
  329. , public std::enable_shared_from_this<plain_session>
  330. {
  331. beast::tcp_stream stream_;
  332. public:
  333. // Create the session
  334. plain_session(
  335. tcp::socket&& socket,
  336. beast::flat_buffer buffer,
  337. std::shared_ptr<std::string const> const& doc_root)
  338. : session<plain_session>(
  339. std::move(buffer),
  340. doc_root)
  341. , stream_(std::move(socket))
  342. {
  343. }
  344. // Called by the base class
  345. beast::tcp_stream&
  346. stream()
  347. {
  348. return stream_;
  349. }
  350. // Start the asynchronous operation
  351. void
  352. run()
  353. {
  354. // We need to be executing within a strand to perform async operations
  355. // on the I/O objects in this session. Although not strictly necessary
  356. // for single-threaded contexts, this example code is written to be
  357. // thread-safe by default.
  358. net::dispatch(stream_.get_executor(),
  359. beast::bind_front_handler(
  360. &session::do_read,
  361. shared_from_this()));
  362. }
  363. void
  364. do_eof()
  365. {
  366. // Send a TCP shutdown
  367. beast::error_code ec;
  368. stream_.socket().shutdown(tcp::socket::shutdown_send, ec);
  369. // At this point the connection is closed gracefully
  370. }
  371. };
  372. // Handles an SSL HTTP connection
  373. class ssl_session
  374. : public session<ssl_session>
  375. , public std::enable_shared_from_this<ssl_session>
  376. {
  377. beast::ssl_stream<beast::tcp_stream> stream_;
  378. public:
  379. // Create the session
  380. ssl_session(
  381. tcp::socket&& socket,
  382. ssl::context& ctx,
  383. beast::flat_buffer buffer,
  384. std::shared_ptr<std::string const> const& doc_root)
  385. : session<ssl_session>(
  386. std::move(buffer),
  387. doc_root)
  388. , stream_(std::move(socket), ctx)
  389. {
  390. }
  391. // Called by the base class
  392. beast::ssl_stream<beast::tcp_stream>&
  393. stream()
  394. {
  395. return stream_;
  396. }
  397. // Start the asynchronous operation
  398. void
  399. run()
  400. {
  401. auto self = shared_from_this();
  402. // We need to be executing within a strand to perform async operations
  403. // on the I/O objects in this session.
  404. net::dispatch(stream_.get_executor(), [self]() {
  405. // Set the timeout.
  406. beast::get_lowest_layer(self->stream_).expires_after(
  407. std::chrono::seconds(30));
  408. // Perform the SSL handshake
  409. // Note, this is the buffered version of the handshake.
  410. self->stream_.async_handshake(
  411. ssl::stream_base::server,
  412. self->buffer_.data(),
  413. beast::bind_front_handler(
  414. &ssl_session::on_handshake,
  415. self));
  416. });
  417. }
  418. void
  419. on_handshake(
  420. beast::error_code ec,
  421. std::size_t bytes_used)
  422. {
  423. if(ec)
  424. return fail(ec, "handshake");
  425. // Consume the portion of the buffer used by the handshake
  426. buffer_.consume(bytes_used);
  427. do_read();
  428. }
  429. void
  430. do_eof()
  431. {
  432. // Set the timeout.
  433. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
  434. // Perform the SSL shutdown
  435. stream_.async_shutdown(
  436. beast::bind_front_handler(
  437. &ssl_session::on_shutdown,
  438. shared_from_this()));
  439. }
  440. void
  441. on_shutdown(beast::error_code ec)
  442. {
  443. if(ec)
  444. return fail(ec, "shutdown");
  445. // At this point the connection is closed gracefully
  446. }
  447. };
  448. //------------------------------------------------------------------------------
  449. // Detects SSL handshakes
  450. class detect_session : public std::enable_shared_from_this<detect_session>
  451. {
  452. beast::tcp_stream stream_;
  453. ssl::context& ctx_;
  454. std::shared_ptr<std::string const> doc_root_;
  455. beast::flat_buffer buffer_;
  456. public:
  457. detect_session(
  458. tcp::socket&& socket,
  459. ssl::context& ctx,
  460. std::shared_ptr<std::string const> const& doc_root)
  461. : stream_(std::move(socket))
  462. , ctx_(ctx)
  463. , doc_root_(doc_root)
  464. {
  465. }
  466. // Launch the detector
  467. void
  468. run()
  469. {
  470. // Set the timeout.
  471. beast::get_lowest_layer(stream_).expires_after(std::chrono::seconds(30));
  472. // Detect a TLS handshake
  473. async_detect_ssl(
  474. stream_,
  475. buffer_,
  476. beast::bind_front_handler(
  477. &detect_session::on_detect,
  478. shared_from_this()));
  479. }
  480. void
  481. on_detect(beast::error_code ec, bool result)
  482. {
  483. if(ec)
  484. return fail(ec, "detect");
  485. if(result)
  486. {
  487. // Launch SSL session
  488. std::make_shared<ssl_session>(
  489. stream_.release_socket(),
  490. ctx_,
  491. std::move(buffer_),
  492. doc_root_)->run();
  493. return;
  494. }
  495. // Launch plain session
  496. std::make_shared<plain_session>(
  497. stream_.release_socket(),
  498. std::move(buffer_),
  499. doc_root_)->run();
  500. }
  501. };
  502. // Accepts incoming connections and launches the sessions
  503. class listener : public std::enable_shared_from_this<listener>
  504. {
  505. net::io_context& ioc_;
  506. ssl::context& ctx_;
  507. tcp::acceptor acceptor_;
  508. std::shared_ptr<std::string const> doc_root_;
  509. public:
  510. listener(
  511. net::io_context& ioc,
  512. ssl::context& ctx,
  513. tcp::endpoint endpoint,
  514. std::shared_ptr<std::string const> const& doc_root)
  515. : ioc_(ioc)
  516. , ctx_(ctx)
  517. , acceptor_(net::make_strand(ioc))
  518. , doc_root_(doc_root)
  519. {
  520. beast::error_code ec;
  521. // Open the acceptor
  522. acceptor_.open(endpoint.protocol(), ec);
  523. if(ec)
  524. {
  525. fail(ec, "open");
  526. return;
  527. }
  528. // Allow address reuse
  529. acceptor_.set_option(net::socket_base::reuse_address(true), ec);
  530. if(ec)
  531. {
  532. fail(ec, "set_option");
  533. return;
  534. }
  535. // Bind to the server address
  536. acceptor_.bind(endpoint, ec);
  537. if(ec)
  538. {
  539. fail(ec, "bind");
  540. return;
  541. }
  542. // Start listening for connections
  543. acceptor_.listen(
  544. net::socket_base::max_listen_connections, ec);
  545. if(ec)
  546. {
  547. fail(ec, "listen");
  548. return;
  549. }
  550. }
  551. // Start accepting incoming connections
  552. void
  553. run()
  554. {
  555. do_accept();
  556. }
  557. private:
  558. void
  559. do_accept()
  560. {
  561. // The new connection gets its own strand
  562. acceptor_.async_accept(
  563. net::make_strand(ioc_),
  564. beast::bind_front_handler(
  565. &listener::on_accept,
  566. shared_from_this()));
  567. }
  568. void
  569. on_accept(beast::error_code ec, tcp::socket socket)
  570. {
  571. if(ec)
  572. {
  573. fail(ec, "accept");
  574. }
  575. else
  576. {
  577. // Create the detector session and run it
  578. std::make_shared<detect_session>(
  579. std::move(socket),
  580. ctx_,
  581. doc_root_)->run();
  582. }
  583. // Accept another connection
  584. do_accept();
  585. }
  586. };
  587. //------------------------------------------------------------------------------
  588. int main(int argc, char* argv[])
  589. {
  590. // Check command line arguments.
  591. if (argc != 5)
  592. {
  593. std::cerr <<
  594. "Usage: http-server-flex <address> <port> <doc_root> <threads>\n" <<
  595. "Example:\n" <<
  596. " http-server-flex 0.0.0.0 8080 .\n";
  597. return EXIT_FAILURE;
  598. }
  599. auto const address = net::ip::make_address(argv[1]);
  600. auto const port = static_cast<unsigned short>(std::atoi(argv[2]));
  601. auto const doc_root = std::make_shared<std::string>(argv[3]);
  602. auto const threads = std::max<int>(1, std::atoi(argv[4]));
  603. // The io_context is required for all I/O
  604. net::io_context ioc{threads};
  605. // The SSL context is required, and holds certificates
  606. ssl::context ctx{ssl::context::tlsv12};
  607. // This holds the self-signed certificate used by the server
  608. load_server_certificate(ctx);
  609. // Create and launch a listening port
  610. std::make_shared<listener>(
  611. ioc,
  612. ctx,
  613. tcp::endpoint{address, port},
  614. doc_root)->run();
  615. // Run the I/O service on the requested number of threads
  616. std::vector<std::thread> v;
  617. v.reserve(threads - 1);
  618. for(auto i = threads - 1; i > 0; --i)
  619. v.emplace_back(
  620. [&ioc]
  621. {
  622. ioc.run();
  623. });
  624. ioc.run();
  625. return EXIT_SUCCESS;
  626. }