Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_prefer_member_prefer.cpp
// // cpp14/can_prefer_member_prefer.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/prefer.hpp" #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_preferable = true; }; template <int> struct object { template <int N> constexpr object<N> prefer(prop<N>) const { return object<N>(); } }; int main() { static_assert(asio::can_prefer_v<object<1>, prop<2>>, ""); static_assert(asio::can_prefer_v<object<1>, prop<2>, prop<3>>, ""); static_assert(asio::can_prefer_v<object<1>, prop<2>, prop<3>, prop<4>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<2>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<2>, prop<3>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<2>, prop<3>, prop<4>>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_prefer_not_applicable_member_prefer.cpp
// // cpp14/can_prefer_not_applicable_member_prefer.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/prefer.hpp" #include <cassert> template <int> struct prop { static constexpr bool is_preferable = true; }; template <int> struct object { template <int N> constexpr object<N> prefer(prop<N>) const { return object<N>(); } }; int main() { static_assert(!asio::can_prefer_v<object<1>, prop<2>>, ""); static_assert(!asio::can_prefer_v<object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_prefer_v<object<1>, prop<2>, prop<3>, prop<4>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>, prop<3>, prop<4>>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_query_not_applicable_unsupported.cpp
// // cpp14/can_query_not_applicable_unsupported.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/query.hpp" #include <cassert> struct prop { }; struct object { }; int main() { static_assert(!asio::can_query_v<object, prop>, ""); static_assert(!asio::can_query_v<const object, prop>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_query_free.cpp
// // cpp14/can_query_free.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/query.hpp" #include <cassert> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; }; struct object { friend constexpr int query(const object&, prop) { return 123; } }; int main() { static_assert(asio::can_query_v<object, prop>, ""); static_assert(asio::can_query_v<const object, prop>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/require_static.cpp
// // cpp14/require_static.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/require.hpp" #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_requirable = true; template <typename> static constexpr bool static_query_v = true; static constexpr bool value() { return true; } }; template <int> struct object { }; int main() { object<1> o1 = {}; object<1> o2 = asio::require(o1, prop<1>()); object<1> o3 = asio::require(o1, prop<1>(), prop<1>()); object<1> o4 = asio::require(o1, prop<1>(), prop<1>(), prop<1>()); (void)o2; (void)o3; (void)o4; const object<1> o5 = {}; object<1> o6 = asio::require(o5, prop<1>()); object<1> o7 = asio::require(o5, prop<1>(), prop<1>()); object<1> o8 = asio::require(o5, prop<1>(), prop<1>(), prop<1>()); (void)o6; (void)o7; (void)o8; constexpr object<1> o9 = asio::require(object<1>(), prop<1>()); constexpr object<1> o10 = asio::require(object<1>(), prop<1>(), prop<1>()); constexpr object<1> o11 = asio::require(object<1>(), prop<1>(), prop<1>(), prop<1>()); (void)o9; (void)o10; (void)o11; }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/prefer_free_require.cpp
// // cpp14/prefer_free_require.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/prefer.hpp" #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_preferable = true; }; template <int> struct object { template <int N> friend constexpr object<N> require(const object&, prop<N>) { return object<N>(); } }; int main() { object<1> o1 = {}; object<2> o2 = asio::prefer(o1, prop<2>()); object<3> o3 = asio::prefer(o1, prop<2>(), prop<3>()); object<4> o4 = asio::prefer(o1, prop<2>(), prop<3>(), prop<4>()); (void)o2; (void)o3; (void)o4; const object<1> o5 = {}; object<2> o6 = asio::prefer(o5, prop<2>()); object<3> o7 = asio::prefer(o5, prop<2>(), prop<3>()); object<4> o8 = asio::prefer(o5, prop<2>(), prop<3>(), prop<4>()); (void)o6; (void)o7; (void)o8; constexpr object<2> o9 = asio::prefer(object<1>(), prop<2>()); constexpr object<3> o10 = asio::prefer(object<1>(), prop<2>(), prop<3>()); constexpr object<4> o11 = asio::prefer(object<1>(), prop<2>(), prop<3>(), prop<4>()); (void)o9; (void)o10; (void)o11; }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/query_static.cpp
// // cpp14/query_static.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/query.hpp" #include <cassert> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; template <typename> static constexpr int static_query_v = 123; }; struct object { }; int main() { object o1 = {}; int result1 = asio::query(o1, prop()); assert(result1 == 123); (void)result1; const object o2 = {}; int result2 = asio::query(o2, prop()); assert(result2 == 123); (void)result2; constexpr object o3 = {}; constexpr int result3 = asio::query(o3, prop()); assert(result3 == 123); (void)result3; }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_query_not_applicable_member.cpp
// // cpp14/can_query_not_applicable_member.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/query.hpp" #include <cassert> struct prop { }; struct object { constexpr int query(prop) const { return 123; } }; int main() { static_assert(!asio::can_query_v<object, prop>, ""); static_assert(!asio::can_query_v<const object, prop>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_require_concept_static.cpp
// // cpp14/can_require_concept_static.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/require_concept.hpp" #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_requirable_concept = true; template <typename> static constexpr bool static_query_v = true; static constexpr bool value() { return true; } }; template <int> struct object { }; int main() { static_assert(asio::can_require_concept_v<object<1>, prop<1>>, ""); static_assert(asio::can_require_concept_v<const object<1>, prop<1>>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_prefer_static.cpp
// // cpp14/can_prefer_static.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/prefer.hpp" #include <cassert> template <int> struct prop { template <typename> static constexpr bool is_applicable_property_v = true; static constexpr bool is_preferable = true; template <typename> static constexpr bool static_query_v = true; static constexpr bool value() { return true; } }; template <int> struct object { }; int main() { static_assert(asio::can_prefer_v<object<1>, prop<1>>, ""); static_assert(asio::can_prefer_v<object<1>, prop<1>, prop<1>>, ""); static_assert(asio::can_prefer_v<object<1>, prop<1>, prop<1>, prop<1>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<1>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<1>, prop<1>>, ""); static_assert(asio::can_prefer_v<const object<1>, prop<1>, prop<1>, prop<1>>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_prefer_not_applicable_free_require.cpp
// // cpp14/can_prefer_not_applicable_free_require.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/prefer.hpp" #include <cassert> template <int> struct prop { static constexpr bool is_preferable = true; }; template <int> struct object { template <int N> friend constexpr object<N> require(const object&, prop<N>) { return object<N>(); } }; int main() { static_assert(!asio::can_prefer_v<object<1>, prop<2>>, ""); static_assert(!asio::can_prefer_v<object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_prefer_v<object<1>, prop<2>, prop<3>, prop<4>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_prefer_v<const object<1>, prop<2>, prop<3>, prop<4>>, ""); }
0
repos/asio/asio/src/tests/properties
repos/asio/asio/src/tests/properties/cpp14/can_require_not_applicable_member.cpp
// // cpp14/can_require_not_applicable_member.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "asio/require.hpp" #include <cassert> template <int> struct prop { static constexpr bool is_requirable = true; }; template <int> struct object { template <int N> constexpr object<N> require(prop<N>) const { return object<N>(); } }; int main() { static_assert(!asio::can_require_v<object<1>, prop<2>>, ""); static_assert(!asio::can_require_v<object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_require_v<object<1>, prop<2>, prop<3>, prop<4>>, ""); static_assert(!asio::can_require_v<const object<1>, prop<2>>, ""); static_assert(!asio::can_require_v<const object<1>, prop<2>, prop<3>>, ""); static_assert(!asio::can_require_v<const object<1>, prop<2>, prop<3>, prop<4>>, ""); }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/ssl/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <functional> #include <iostream> #include "asio.hpp" #include "asio/ssl.hpp" using asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: session(asio::ssl::stream<tcp::socket> socket) : socket_(std::move(socket)) { } void start() { do_handshake(); } private: void do_handshake() { auto self(shared_from_this()); socket_.async_handshake(asio::ssl::stream_base::server, [this, self](const std::error_code& error) { if (!error) { do_read(); } }); } void do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(data_), [this, self](const std::error_code& ec, std::size_t length) { if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(data_, length), [this, self](const std::error_code& ec, std::size_t /*length*/) { if (!ec) { do_read(); } }); } asio::ssl::stream<tcp::socket> socket_; char data_[1024]; }; class server { public: server(asio::io_context& io_context, unsigned short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)), context_(asio::ssl::context::sslv23) { context_.set_options( asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::single_dh_use); context_.set_password_callback(std::bind(&server::get_password, this)); context_.use_certificate_chain_file("server.pem"); context_.use_private_key_file("server.pem", asio::ssl::context::pem); context_.use_tmp_dh_file("dh4096.pem"); do_accept(); } private: std::string get_password() const { return "test"; } void do_accept() { acceptor_.async_accept( [this](const std::error_code& error, tcp::socket socket) { if (!error) { std::make_shared<session>( asio::ssl::stream<tcp::socket>( std::move(socket), context_))->start(); } do_accept(); }); } tcp::acceptor acceptor_; asio::ssl::context context_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: server <port>\n"; return 1; } asio::io_context io_context; using namespace std; // For atoi. server s(io_context, atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/ssl/client.cpp
// // client.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <functional> #include <iostream> #include "asio.hpp" #include "asio/ssl.hpp" using asio::ip::tcp; using std::placeholders::_1; using std::placeholders::_2; enum { max_length = 1024 }; class client { public: client(asio::io_context& io_context, asio::ssl::context& context, const tcp::resolver::results_type& endpoints) : socket_(io_context, context) { socket_.set_verify_mode(asio::ssl::verify_peer); socket_.set_verify_callback( std::bind(&client::verify_certificate, this, _1, _2)); connect(endpoints); } private: bool verify_certificate(bool preverified, asio::ssl::verify_context& ctx) { // The verify callback can be used to check whether the certificate that is // being presented is valid for the peer. For example, RFC 2818 describes // the steps involved in doing this for HTTPS. Consult the OpenSSL // documentation for more details. Note that the callback is called once // for each certificate in the certificate chain, starting from the root // certificate authority. // In this example we will simply print the certificate's subject name. char subject_name[256]; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); X509_NAME_oneline(X509_get_subject_name(cert), subject_name, 256); std::cout << "Verifying " << subject_name << "\n"; return preverified; } void connect(const tcp::resolver::results_type& endpoints) { asio::async_connect(socket_.lowest_layer(), endpoints, [this](const std::error_code& error, const tcp::endpoint& /*endpoint*/) { if (!error) { handshake(); } else { std::cout << "Connect failed: " << error.message() << "\n"; } }); } void handshake() { socket_.async_handshake(asio::ssl::stream_base::client, [this](const std::error_code& error) { if (!error) { send_request(); } else { std::cout << "Handshake failed: " << error.message() << "\n"; } }); } void send_request() { std::cout << "Enter message: "; std::cin.getline(request_, max_length); size_t request_length = std::strlen(request_); asio::async_write(socket_, asio::buffer(request_, request_length), [this](const std::error_code& error, std::size_t length) { if (!error) { receive_response(length); } else { std::cout << "Write failed: " << error.message() << "\n"; } }); } void receive_response(std::size_t length) { asio::async_read(socket_, asio::buffer(reply_, length), [this](const std::error_code& error, std::size_t length) { if (!error) { std::cout << "Reply: "; std::cout.write(reply_, length); std::cout << "\n"; } else { std::cout << "Read failed: " << error.message() << "\n"; } }); } asio::ssl::stream<tcp::socket> socket_; char request_[max_length]; char reply_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); asio::ssl::context ctx(asio::ssl::context::sslv23); ctx.load_verify_file("ca.pem"); client c(io_context, ctx, endpoints); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/handler_tracking/async_tcp_echo_server.cpp
// // async_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <memory> #include <utility> #include <asio.hpp> using asio::ip::tcp; // Define a helper macro to invoke ASIO_HANDLER_LOCATION with the current // file name, line number, and function name. For the function name, you might // also consider using __PRETTY_FUNCTION__, BOOST_CURRENT_FUNCTION, or a hand- // crafted name. For C++20 or later, you may also use std::source_location. #define HANDLER_LOCATION \ ASIO_HANDLER_LOCATION((__FILE__, __LINE__, __func__)) class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { HANDLER_LOCATION; do_read(); } private: void do_read() { HANDLER_LOCATION; auto self(shared_from_this()); socket_.async_read_some(asio::buffer(data_, max_length), [this, self](std::error_code ec, std::size_t length) { HANDLER_LOCATION; if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { HANDLER_LOCATION; auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(data_, length), [this, self](std::error_code ec, std::size_t /*length*/) { HANDLER_LOCATION; if (!ec) { do_read(); } }); } tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(asio::io_context& io_context, short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: void do_accept() { HANDLER_LOCATION; acceptor_.async_accept( [this](std::error_code ec, tcp::socket socket) { HANDLER_LOCATION; if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/handler_tracking/custom_tracking.hpp
// // custom_tracking.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef CUSTOM_TRACKING_HPP #define CUSTOM_TRACKING_HPP #include <cinttypes> #include <cstdint> #include <cstdio> # define ASIO_INHERIT_TRACKED_HANDLER \ : public ::custom_tracking::tracked_handler # define ASIO_ALSO_INHERIT_TRACKED_HANDLER \ , public ::custom_tracking::tracked_handler # define ASIO_HANDLER_TRACKING_INIT \ ::custom_tracking::init() # define ASIO_HANDLER_LOCATION(args) \ ::custom_tracking::location args # define ASIO_HANDLER_CREATION(args) \ ::custom_tracking::creation args # define ASIO_HANDLER_COMPLETION(args) \ ::custom_tracking::completion tracked_completion args # define ASIO_HANDLER_INVOCATION_BEGIN(args) \ tracked_completion.invocation_begin args # define ASIO_HANDLER_INVOCATION_END \ tracked_completion.invocation_end() # define ASIO_HANDLER_OPERATION(args) \ ::custom_tracking::operation args # define ASIO_HANDLER_REACTOR_REGISTRATION(args) \ ::custom_tracking::reactor_registration args # define ASIO_HANDLER_REACTOR_DEREGISTRATION(args) \ ::custom_tracking::reactor_deregistration args # define ASIO_HANDLER_REACTOR_READ_EVENT 1 # define ASIO_HANDLER_REACTOR_WRITE_EVENT 2 # define ASIO_HANDLER_REACTOR_ERROR_EVENT 4 # define ASIO_HANDLER_REACTOR_EVENTS(args) \ ::custom_tracking::reactor_events args # define ASIO_HANDLER_REACTOR_OPERATION(args) \ ::custom_tracking::reactor_operation args struct custom_tracking { // Base class for objects containing tracked handlers. struct tracked_handler { std::uintmax_t handler_id_ = 0; // To uniquely identify a handler. std::uintmax_t tree_id_ = 0; // To identify related handlers. const char* object_type_; // The object type associated with the handler. std::uintmax_t native_handle_; // Native handle, if any. }; // Initialise the tracking system. static void init() { } // Record a source location. static void location(const char* file_name, int line, const char* function_name) { std::printf("At location %s:%d in %s\n", file_name, line, function_name); } // Record the creation of a tracked handler. static void creation(asio::execution_context& /*ctx*/, tracked_handler& h, const char* object_type, void* /*object*/, std::uintmax_t native_handle, const char* op_name) { // Generate a unique id for the new handler. static std::atomic<std::uintmax_t> next_handler_id{1}; h.handler_id_ = next_handler_id++; // Copy the tree identifier forward from the current handler. if (*current_completion()) h.tree_id_ = (*current_completion())->handler_.tree_id_; // Store various attributes of the operation to use in later output. h.object_type_ = object_type; h.native_handle_ = native_handle; std::printf( "Starting operation %s.%s for native_handle = %" PRIuMAX ", handler = %" PRIuMAX ", tree = %" PRIuMAX "\n", object_type, op_name, h.native_handle_, h.handler_id_, h.tree_id_); } struct completion { explicit completion(const tracked_handler& h) : handler_(h), next_(*current_completion()) { *current_completion() = this; } completion(const completion&) = delete; completion& operator=(const completion&) = delete; // Destructor records only when an exception is thrown from the handler, or // if the memory is being freed without the handler having been invoked. ~completion() { *current_completion() = next_; } // Records that handler is to be invoked with the specified arguments. template <class... Args> void invocation_begin(Args&&... /*args*/) { std::printf("Entering handler %" PRIuMAX " in tree %" PRIuMAX "\n", handler_.handler_id_, handler_.tree_id_); } // Record that handler invocation has ended. void invocation_end() { std::printf("Leaving handler %" PRIuMAX " in tree %" PRIuMAX "\n", handler_.handler_id_, handler_.tree_id_); } tracked_handler handler_; // Completions may nest. Here we stash a pointer to the outer completion. completion* next_; }; static completion** current_completion() { static ASIO_THREAD_KEYWORD completion* current = nullptr; return &current; } // Record an operation that is not directly associated with a handler. static void operation(asio::execution_context& /*ctx*/, const char* /*object_type*/, void* /*object*/, std::uintmax_t /*native_handle*/, const char* /*op_name*/) { } // Record that a descriptor has been registered with the reactor. static void reactor_registration(asio::execution_context& context, uintmax_t native_handle, uintmax_t registration) { std::printf("Adding to reactor native_handle = %" PRIuMAX ", registration = %" PRIuMAX "\n", native_handle, registration); } // Record that a descriptor has been deregistered from the reactor. static void reactor_deregistration(asio::execution_context& context, uintmax_t native_handle, uintmax_t registration) { std::printf("Removing from reactor native_handle = %" PRIuMAX ", registration = %" PRIuMAX "\n", native_handle, registration); } // Record reactor-based readiness events associated with a descriptor. static void reactor_events(asio::execution_context& context, uintmax_t registration, unsigned events) { std::printf( "Reactor readiness for registration = %" PRIuMAX ", events =%s%s%s\n", registration, (events & ASIO_HANDLER_REACTOR_READ_EVENT) ? " read" : "", (events & ASIO_HANDLER_REACTOR_WRITE_EVENT) ? " write" : "", (events & ASIO_HANDLER_REACTOR_ERROR_EVENT) ? " error" : ""); } // Record a reactor-based operation that is associated with a handler. static void reactor_operation(const tracked_handler& h, const char* op_name, const std::error_code& ec) { std::printf( "Performed operation %s.%s for native_handle = %" PRIuMAX ", ec = %s:%d\n", h.object_type_, op_name, h.native_handle_, ec.category().name(), ec.value()); } // Record a reactor-based operation that is associated with a handler. static void reactor_operation(const tracked_handler& h, const char* op_name, const std::error_code& ec, std::size_t bytes_transferred) { std::printf( "Performed operation %s.%s for native_handle = %" PRIuMAX ", ec = %s:%d, n = %" PRIuMAX "\n", h.object_type_, op_name, h.native_handle_, ec.category().name(), ec.value(), static_cast<uintmax_t>(bytes_transferred)); } }; #endif // CUSTOM_TRACKING_HPP
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/blocking_udp_echo_client.cpp
// // blocking_udp_echo_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <iostream> #include "asio.hpp" using asio::ip::udp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_udp_echo_client <host> <port>\n"; return 1; } asio::io_context io_context; udp::socket s(io_context, udp::endpoint(udp::v4(), 0)); udp::resolver resolver(io_context); udp::resolver::results_type endpoints = resolver.resolve(udp::v4(), argv[1], argv[2]); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); s.send_to(asio::buffer(request, request_length), *endpoints.begin()); char reply[max_length]; udp::endpoint sender_endpoint; size_t reply_length = s.receive_from( asio::buffer(reply, max_length), sender_endpoint); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/blocking_tcp_echo_server.cpp
// // blocking_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <thread> #include <utility> #include "asio.hpp" using asio::ip::tcp; const int max_length = 1024; void session(tcp::socket sock) { try { for (;;) { char data[max_length]; std::error_code error; size_t length = sock.read_some(asio::buffer(data), error); if (error == asio::error::eof) break; // Connection closed cleanly by peer. else if (error) throw std::system_error(error); // Some other error. asio::write(sock, asio::buffer(data, length)); } } catch (std::exception& e) { std::cerr << "Exception in thread: " << e.what() << "\n"; } } void server(asio::io_context& io_context, unsigned short port) { tcp::acceptor a(io_context, tcp::endpoint(tcp::v4(), port)); for (;;) { std::thread(session, a.accept()).detach(); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_tcp_echo_server <port>\n"; return 1; } asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/async_udp_echo_server.cpp
// // async_udp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include "asio.hpp" using asio::ip::udp; class server { public: server(asio::io_context& io_context, short port) : socket_(io_context, udp::endpoint(udp::v4(), port)) { do_receive(); } void do_receive() { socket_.async_receive_from( asio::buffer(data_, max_length), sender_endpoint_, [this](std::error_code ec, std::size_t bytes_recvd) { if (!ec && bytes_recvd > 0) { do_send(bytes_recvd); } else { do_receive(); } }); } void do_send(std::size_t length) { socket_.async_send_to( asio::buffer(data_, length), sender_endpoint_, [this](std::error_code /*ec*/, std::size_t /*bytes_sent*/) { do_receive(); }); } private: udp::socket socket_; udp::endpoint sender_endpoint_; enum { max_length = 1024 }; char data_[max_length]; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_udp_echo_server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/blocking_udp_echo_server.cpp
// // blocking_udp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include "asio.hpp" using asio::ip::udp; enum { max_length = 1024 }; void server(asio::io_context& io_context, unsigned short port) { udp::socket sock(io_context, udp::endpoint(udp::v4(), port)); for (;;) { char data[max_length]; udp::endpoint sender_endpoint; size_t length = sock.receive_from( asio::buffer(data, max_length), sender_endpoint); sock.send_to(asio::buffer(data, length), sender_endpoint); } } int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: blocking_udp_echo_server <port>\n"; return 1; } asio::io_context io_context; server(io_context, std::atoi(argv[1])); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/async_tcp_echo_server.cpp
// // async_tcp_echo_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <iostream> #include <memory> #include <utility> #include "asio.hpp" using asio::ip::tcp; class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(data_, max_length), [this, self](std::error_code ec, std::size_t length) { if (!ec) { do_write(length); } }); } void do_write(std::size_t length) { auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(data_, length), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_read(); } }); } tcp::socket socket_; enum { max_length = 1024 }; char data_[max_length]; }; class server { public: server(asio::io_context& io_context, short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](std::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: async_tcp_echo_server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/echo/blocking_tcp_echo_client.cpp
// // blocking_tcp_echo_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <cstring> #include <iostream> #include "asio.hpp" using asio::ip::tcp; enum { max_length = 1024 }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_tcp_echo_client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::socket s(io_context); tcp::resolver resolver(io_context); asio::connect(s, resolver.resolve(argv[1], argv[2])); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); asio::write(s, asio::buffer(request, request_length)); char reply[max_length]; size_t reply_length = asio::read(s, asio::buffer(reply, request_length)); std::cout << "Reply is: "; std::cout.write(reply, reply_length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/allocation/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <cstdlib> #include <iostream> #include <memory> #include <type_traits> #include <utility> #include "asio.hpp" using asio::ip::tcp; // Class to manage the memory to be used for handler-based custom allocation. // It contains a single block of memory which may be returned for allocation // requests. If the memory is in use when an allocation request is made, the // allocator delegates allocation to the global heap. class handler_memory { public: handler_memory() : in_use_(false) { } handler_memory(const handler_memory&) = delete; handler_memory& operator=(const handler_memory&) = delete; void* allocate(std::size_t size) { if (!in_use_ && size < sizeof(storage_)) { in_use_ = true; return &storage_; } else { return ::operator new(size); } } void deallocate(void* pointer) { if (pointer == &storage_) { in_use_ = false; } else { ::operator delete(pointer); } } private: // Storage space used for handler-based custom memory allocation. typename std::aligned_storage<1024>::type storage_; // Whether the handler-based custom allocation storage has been used. bool in_use_; }; // The allocator to be associated with the handler objects. This allocator only // needs to satisfy the C++11 minimal allocator requirements. template <typename T> class handler_allocator { public: using value_type = T; explicit handler_allocator(handler_memory& mem) : memory_(mem) { } template <typename U> handler_allocator(const handler_allocator<U>& other) noexcept : memory_(other.memory_) { } bool operator==(const handler_allocator& other) const noexcept { return &memory_ == &other.memory_; } bool operator!=(const handler_allocator& other) const noexcept { return &memory_ != &other.memory_; } T* allocate(std::size_t n) const { return static_cast<T*>(memory_.allocate(sizeof(T) * n)); } void deallocate(T* p, std::size_t /*n*/) const { return memory_.deallocate(p); } private: template <typename> friend class handler_allocator; // The underlying memory. handler_memory& memory_; }; class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(data_), asio::bind_allocator( handler_allocator<int>(handler_memory_), [this, self](std::error_code ec, std::size_t length) { if (!ec) { do_write(length); } })); } void do_write(std::size_t length) { auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(data_, length), asio::bind_allocator( handler_allocator<int>(handler_memory_), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_read(); } })); } // The socket used to communicate with the client. tcp::socket socket_; // Buffer used to store data received from the client. std::array<char, 1024> data_; // The memory to use for handler-based custom memory allocation. handler_memory handler_memory_; }; class server { public: server(asio::io_context& io_context, short port) : acceptor_(io_context, tcp::endpoint(tcp::v4(), port)) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](std::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } tcp::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: server <port>\n"; return 1; } asio::io_context io_context; server s(io_context, std::atoi(argv[1])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/files/async_file_copy.cpp
// // async_file_copy.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include "asio.hpp" #if defined(ASIO_HAS_FILE) class file_copier { public: file_copier(asio::io_context& io_context, const char* from, const char* to) : from_file_(io_context, from, asio::stream_file::read_only), to_file_(io_context, to, asio::stream_file::write_only | asio::stream_file::create | asio::stream_file::truncate) { } void start() { do_read(); } private: void do_read() { from_file_.async_read_some(asio::buffer(data_), [this](std::error_code error, std::size_t n) { if (!error) { do_write(n); } else if (error != asio::error::eof) { std::cerr << "Error copying file: " << error.message() << "\n"; } }); } void do_write(std::size_t n) { asio::async_write(to_file_, asio::buffer(data_, n), [this](std::error_code error, std::size_t /*n*/) { if (!error) { do_read(); } else { std::cerr << "Error copying file: " << error.message() << "\n"; } }); } asio::stream_file from_file_; asio::stream_file to_file_; char data_[4096]; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: async_file_copy <from> <to>\n"; return 1; } asio::io_context io_context; file_copier copier(io_context, argv[1], argv[2]); copier.start(); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } #else // defined(ASIO_HAS_FILE) int main() {} #endif // defined(ASIO_HAS_FILE)
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/files/blocking_file_copy.cpp
// // blocking_file_copy.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include "asio.hpp" #if defined(ASIO_HAS_FILE) int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_file_copy <from> <to>\n"; return 1; } asio::io_context io_context; asio::stream_file from_file(io_context, argv[1], asio::stream_file::read_only); asio::stream_file to_file(io_context, argv[2], asio::stream_file::write_only | asio::stream_file::create | asio::stream_file::truncate); char data[4096]; std::error_code error; for (;;) { std::size_t n = from_file.read_some(asio::buffer(data), error); if (error) break; asio::write(to_file, asio::buffer(data, n), error); if (error) break; } if (error && error != asio::error::eof) { std::cerr << "Error copying file: " << error.message() << "\n"; return 1; } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; return 1; } return 0; } #else // defined(ASIO_HAS_FILE) int main() {} #endif // defined(ASIO_HAS_FILE)
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/chat/chat_client.cpp
// // chat_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <deque> #include <iostream> #include <thread> #include "asio.hpp" #include "chat_message.hpp" using asio::ip::tcp; typedef std::deque<chat_message> chat_message_queue; class chat_client { public: chat_client(asio::io_context& io_context, const tcp::resolver::results_type& endpoints) : io_context_(io_context), socket_(io_context) { do_connect(endpoints); } void write(const chat_message& msg) { asio::post(io_context_, [this, msg]() { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } }); } void close() { asio::post(io_context_, [this]() { socket_.close(); }); } private: void do_connect(const tcp::resolver::results_type& endpoints) { asio::async_connect(socket_, endpoints, [this](std::error_code ec, tcp::endpoint) { if (!ec) { do_read_header(); } }); } void do_read_header() { asio::async_read(socket_, asio::buffer(read_msg_.data(), chat_message::header_length), [this](std::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { socket_.close(); } }); } void do_read_body() { asio::async_read(socket_, asio::buffer(read_msg_.body(), read_msg_.body_length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { std::cout.write(read_msg_.body(), read_msg_.body_length()); std::cout << "\n"; do_read_header(); } else { socket_.close(); } }); } void do_write() { asio::async_write(socket_, asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { socket_.close(); } }); } private: asio::io_context& io_context_; tcp::socket socket_; chat_message read_msg_; chat_message_queue write_msgs_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: chat_client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::resolver resolver(io_context); auto endpoints = resolver.resolve(argv[1], argv[2]); chat_client c(io_context, endpoints); std::thread t([&io_context](){ io_context.run(); }); char line[chat_message::max_body_length + 1]; while (std::cin.getline(line, chat_message::max_body_length + 1)) { chat_message msg; msg.body_length(std::strlen(line)); std::memcpy(msg.body(), line, msg.body_length()); msg.encode_header(); c.write(msg); } c.close(); t.join(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/chat/chat_message.hpp
// // chat_message.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef CHAT_MESSAGE_HPP #define CHAT_MESSAGE_HPP #include <cstdio> #include <cstdlib> #include <cstring> class chat_message { public: static constexpr std::size_t header_length = 4; static constexpr std::size_t max_body_length = 512; chat_message() : body_length_(0) { } const char* data() const { return data_; } char* data() { return data_; } std::size_t length() const { return header_length + body_length_; } const char* body() const { return data_ + header_length; } char* body() { return data_ + header_length; } std::size_t body_length() const { return body_length_; } void body_length(std::size_t new_length) { body_length_ = new_length; if (body_length_ > max_body_length) body_length_ = max_body_length; } bool decode_header() { char header[header_length + 1] = ""; std::strncat(header, data_, header_length); body_length_ = std::atoi(header); if (body_length_ > max_body_length) { body_length_ = 0; return false; } return true; } void encode_header() { char header[header_length + 1] = ""; std::sprintf(header, "%4d", static_cast<int>(body_length_)); std::memcpy(data_, header, header_length); } private: char data_[header_length + max_body_length]; std::size_t body_length_; }; #endif // CHAT_MESSAGE_HPP
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/chat/posix_chat_client.cpp
// // posix_chat_client.cpp // ~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <cstdlib> #include <cstring> #include <iostream> #include "asio.hpp" #include "chat_message.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) using asio::ip::tcp; namespace posix = asio::posix; class posix_chat_client { public: posix_chat_client(asio::io_context& io_context, const tcp::resolver::results_type& endpoints) : socket_(io_context), input_(io_context, ::dup(STDIN_FILENO)), output_(io_context, ::dup(STDOUT_FILENO)), input_buffer_(chat_message::max_body_length) { do_connect(endpoints); } private: void do_connect(const tcp::resolver::results_type& endpoints) { asio::async_connect(socket_, endpoints, [this](std::error_code ec, tcp::endpoint) { if (!ec) { do_read_header(); do_read_input(); } }); } void do_read_header() { asio::async_read(socket_, asio::buffer(read_msg_.data(), chat_message::header_length), [this](std::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { close(); } }); } void do_read_body() { asio::async_read(socket_, asio::buffer(read_msg_.body(), read_msg_.body_length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_write_output(); } else { close(); } }); } void do_write_output() { // Write out the message we just received, terminated by a newline. static char eol[] = { '\n' }; std::array<asio::const_buffer, 2> buffers = {{ asio::buffer(read_msg_.body(), read_msg_.body_length()), asio::buffer(eol) }}; asio::async_write(output_, buffers, [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_read_header(); } else { close(); } }); } void do_read_input() { // Read a line of input entered by the user. asio::async_read_until(input_, input_buffer_, '\n', [this](std::error_code ec, std::size_t length) { if (!ec) { // Write the message (minus the newline) to the server. write_msg_.body_length(length - 1); input_buffer_.sgetn(write_msg_.body(), length - 1); input_buffer_.consume(1); // Remove newline from input. write_msg_.encode_header(); do_write_message(); } else if (ec == asio::error::not_found) { // Didn't get a newline. Send whatever we have. write_msg_.body_length(input_buffer_.size()); input_buffer_.sgetn(write_msg_.body(), input_buffer_.size()); write_msg_.encode_header(); do_write_message(); } else { close(); } }); } void do_write_message() { asio::async_write(socket_, asio::buffer(write_msg_.data(), write_msg_.length()), [this](std::error_code ec, std::size_t /*length*/) { if (!ec) { do_read_input(); } else { close(); } }); } void close() { // Cancel all outstanding asynchronous operations. socket_.close(); input_.close(); output_.close(); } private: tcp::socket socket_; posix::stream_descriptor input_; posix::stream_descriptor output_; chat_message read_msg_; chat_message write_msg_; asio::streambuf input_buffer_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: posix_chat_client <host> <port>\n"; return 1; } asio::io_context io_context; tcp::resolver resolver(io_context); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], argv[2]); posix_chat_client c(io_context, endpoints); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) int main() {} #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR)
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/chat/chat_server.cpp
// // chat_server.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <cstdlib> #include <deque> #include <iostream> #include <list> #include <memory> #include <set> #include <utility> #include "asio.hpp" #include "chat_message.hpp" using asio::ip::tcp; //---------------------------------------------------------------------- typedef std::deque<chat_message> chat_message_queue; //---------------------------------------------------------------------- class chat_participant { public: virtual ~chat_participant() {} virtual void deliver(const chat_message& msg) = 0; }; typedef std::shared_ptr<chat_participant> chat_participant_ptr; //---------------------------------------------------------------------- class chat_room { public: void join(chat_participant_ptr participant) { participants_.insert(participant); for (auto msg: recent_msgs_) participant->deliver(msg); } void leave(chat_participant_ptr participant) { participants_.erase(participant); } void deliver(const chat_message& msg) { recent_msgs_.push_back(msg); while (recent_msgs_.size() > max_recent_msgs) recent_msgs_.pop_front(); for (auto participant: participants_) participant->deliver(msg); } private: std::set<chat_participant_ptr> participants_; enum { max_recent_msgs = 100 }; chat_message_queue recent_msgs_; }; //---------------------------------------------------------------------- class chat_session : public chat_participant, public std::enable_shared_from_this<chat_session> { public: chat_session(tcp::socket socket, chat_room& room) : socket_(std::move(socket)), room_(room) { } void start() { room_.join(shared_from_this()); do_read_header(); } void deliver(const chat_message& msg) { bool write_in_progress = !write_msgs_.empty(); write_msgs_.push_back(msg); if (!write_in_progress) { do_write(); } } private: void do_read_header() { auto self(shared_from_this()); asio::async_read(socket_, asio::buffer(read_msg_.data(), chat_message::header_length), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec && read_msg_.decode_header()) { do_read_body(); } else { room_.leave(shared_from_this()); } }); } void do_read_body() { auto self(shared_from_this()); asio::async_read(socket_, asio::buffer(read_msg_.body(), read_msg_.body_length()), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec) { room_.deliver(read_msg_); do_read_header(); } else { room_.leave(shared_from_this()); } }); } void do_write() { auto self(shared_from_this()); asio::async_write(socket_, asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()), [this, self](std::error_code ec, std::size_t /*length*/) { if (!ec) { write_msgs_.pop_front(); if (!write_msgs_.empty()) { do_write(); } } else { room_.leave(shared_from_this()); } }); } tcp::socket socket_; chat_room& room_; chat_message read_msg_; chat_message_queue write_msgs_; }; //---------------------------------------------------------------------- class chat_server { public: chat_server(asio::io_context& io_context, const tcp::endpoint& endpoint) : acceptor_(io_context, endpoint) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](std::error_code ec, tcp::socket socket) { if (!ec) { std::make_shared<chat_session>(std::move(socket), room_)->start(); } do_accept(); }); } tcp::acceptor acceptor_; chat_room room_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc < 2) { std::cerr << "Usage: chat_server <port> [<port> ...]\n"; return 1; } asio::io_context io_context; std::list<chat_server> servers; for (int i = 1; i < argc; ++i) { tcp::endpoint endpoint(tcp::v4(), std::atoi(argv[i])); servers.emplace_back(io_context, endpoint); } io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/connection.hpp
// // connection.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_CONNECTION_HPP #define HTTP_SERVER2_CONNECTION_HPP #include <asio.hpp> #include <array> #include <memory> #include "reply.hpp" #include "request.hpp" #include "request_handler.hpp" #include "request_parser.hpp" namespace http { namespace server2 { /// Represents a single connection from a client. class connection : public std::enable_shared_from_this<connection> { public: connection(const connection&) = delete; connection& operator=(const connection&) = delete; /// Construct a connection with the given socket. explicit connection(asio::ip::tcp::socket socket, request_handler& handler); /// Start the first asynchronous operation for the connection. void start(); private: /// Perform an asynchronous read operation. void do_read(); /// Perform an asynchronous write operation. void do_write(); /// Socket for the connection. asio::ip::tcp::socket socket_; /// The handler used to process the incoming request. request_handler& request_handler_; /// Buffer for incoming data. std::array<char, 8192> buffer_; /// The incoming request. request request_; /// The parser for the incoming request. request_parser request_parser_; /// The reply to be sent back to the client. reply reply_; }; typedef std::shared_ptr<connection> connection_ptr; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_CONNECTION_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/request.hpp
// // request.hpp // ~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_REQUEST_HPP #define HTTP_SERVER2_REQUEST_HPP #include <string> #include <vector> #include "header.hpp" namespace http { namespace server2 { /// A request received from a client. struct request { std::string method; std::string uri; int http_version_major; int http_version_minor; std::vector<header> headers; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_REQUEST_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/io_context_pool.cpp
// // io_context_pool.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "server.hpp" #include <stdexcept> #include <thread> namespace http { namespace server2 { io_context_pool::io_context_pool(std::size_t pool_size) : next_io_context_(0) { if (pool_size == 0) throw std::runtime_error("io_context_pool size is 0"); // Give all the io_contexts work to do so that their run() functions will not // exit until they are explicitly stopped. for (std::size_t i = 0; i < pool_size; ++i) { io_context_ptr io_context(new asio::io_context); io_contexts_.push_back(io_context); work_.push_back(asio::make_work_guard(*io_context)); } } void io_context_pool::run() { // Create a pool of threads to run all of the io_contexts. std::vector<std::thread> threads; for (std::size_t i = 0; i < io_contexts_.size(); ++i) threads.emplace_back([this, i]{ io_contexts_[i]->run(); }); // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads.size(); ++i) threads[i].join(); } void io_context_pool::stop() { // Explicitly stop all io_contexts. for (std::size_t i = 0; i < io_contexts_.size(); ++i) io_contexts_[i]->stop(); } asio::io_context& io_context_pool::get_io_context() { // Use a round-robin scheme to choose the next io_context to use. asio::io_context& io_context = *io_contexts_[next_io_context_]; ++next_io_context_; if (next_io_context_ == io_contexts_.size()) next_io_context_ = 0; return io_context; } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/mime_types.cpp
// // mime_types.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "mime_types.hpp" namespace http { namespace server2 { namespace mime_types { struct mapping { const char* extension; const char* mime_type; } mappings[] = { { "gif", "image/gif" }, { "htm", "text/html" }, { "html", "text/html" }, { "jpg", "image/jpeg" }, { "png", "image/png" }, { 0, 0 } // Marks end of list. }; std::string extension_to_type(const std::string& extension) { for (mapping* m = mappings; m->extension; ++m) { if (m->extension == extension) { return m->mime_type; } } return "text/plain"; } } // namespace mime_types } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/connection.cpp
// // connection.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "connection.hpp" #include <utility> #include "request_handler.hpp" namespace http { namespace server2 { connection::connection(asio::ip::tcp::socket socket, request_handler& handler) : socket_(std::move(socket)), request_handler_(handler) { } void connection::start() { do_read(); } void connection::do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(buffer_), [this, self](std::error_code ec, std::size_t bytes_transferred) { if (!ec) { request_parser::result_type result; std::tie(result, std::ignore) = request_parser_.parse( request_, buffer_.data(), buffer_.data() + bytes_transferred); if (result == request_parser::good) { request_handler_.handle_request(request_, reply_); do_write(); } else if (result == request_parser::bad) { reply_ = reply::stock_reply(reply::bad_request); do_write(); } else { do_read(); } } // If an error occurs then no new asynchronous operations are // started. This means that all shared_ptr references to the // connection object will disappear and the object will be // destroyed automatically after this handler returns. The // connection class's destructor closes the socket. }); } void connection::do_write() { auto self(shared_from_this()); asio::async_write(socket_, reply_.to_buffers(), [this, self](std::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. std::error_code ignored_ec; socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec); } // No new asynchronous operations are started. This means that // all shared_ptr references to the connection object will // disappear and the object will be destroyed automatically after // this handler returns. The connection class's destructor closes // the socket. }); } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/request_handler.cpp
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server2 { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/mime_types.hpp
// // mime_types.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_MIME_TYPES_HPP #define HTTP_SERVER2_MIME_TYPES_HPP #include <string> namespace http { namespace server2 { namespace mime_types { /// Convert a file extension into a MIME type. std::string extension_to_type(const std::string& extension); } // namespace mime_types } // namespace server2 } // namespace http #endif // HTTP_SERVER2_MIME_TYPES_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "server.hpp" #include <signal.h> #include <utility> #include "connection.hpp" namespace http { namespace server2 { server::server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t io_context_pool_size) : io_context_pool_(io_context_pool_size), signals_(io_context_pool_.get_io_context()), acceptor_(io_context_pool_.get_io_context()), request_handler_(doc_root) { // Register to handle the signals that indicate when the server should exit. // It is safe to register for the same signal multiple times in a program, // provided all registration for the specified signal is made through Asio. signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // defined(SIGQUIT) do_await_stop(); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). asio::ip::tcp::resolver resolver(acceptor_.get_executor()); asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); do_accept(); } void server::run() { io_context_pool_.run(); } void server::do_accept() { acceptor_.async_accept(io_context_pool_.get_io_context(), [this](std::error_code ec, asio::ip::tcp::socket socket) { // Check whether the server was stopped by a signal before this // completion handler had a chance to run. if (!acceptor_.is_open()) { return; } if (!ec) { std::make_shared<connection>( std::move(socket), request_handler_)->start(); } do_accept(); }); } void server::do_await_stop() { signals_.async_wait( [this](std::error_code /*ec*/, int /*signo*/) { io_context_pool_.stop(); }); } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/reply.cpp
// // reply.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "reply.hpp" #include <string> namespace http { namespace server2 { namespace status_strings { const std::string ok = "HTTP/1.0 200 OK\r\n"; const std::string created = "HTTP/1.0 201 Created\r\n"; const std::string accepted = "HTTP/1.0 202 Accepted\r\n"; const std::string no_content = "HTTP/1.0 204 No Content\r\n"; const std::string multiple_choices = "HTTP/1.0 300 Multiple Choices\r\n"; const std::string moved_permanently = "HTTP/1.0 301 Moved Permanently\r\n"; const std::string moved_temporarily = "HTTP/1.0 302 Moved Temporarily\r\n"; const std::string not_modified = "HTTP/1.0 304 Not Modified\r\n"; const std::string bad_request = "HTTP/1.0 400 Bad Request\r\n"; const std::string unauthorized = "HTTP/1.0 401 Unauthorized\r\n"; const std::string forbidden = "HTTP/1.0 403 Forbidden\r\n"; const std::string not_found = "HTTP/1.0 404 Not Found\r\n"; const std::string internal_server_error = "HTTP/1.0 500 Internal Server Error\r\n"; const std::string not_implemented = "HTTP/1.0 501 Not Implemented\r\n"; const std::string bad_gateway = "HTTP/1.0 502 Bad Gateway\r\n"; const std::string service_unavailable = "HTTP/1.0 503 Service Unavailable\r\n"; asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return asio::buffer(ok); case reply::created: return asio::buffer(created); case reply::accepted: return asio::buffer(accepted); case reply::no_content: return asio::buffer(no_content); case reply::multiple_choices: return asio::buffer(multiple_choices); case reply::moved_permanently: return asio::buffer(moved_permanently); case reply::moved_temporarily: return asio::buffer(moved_temporarily); case reply::not_modified: return asio::buffer(not_modified); case reply::bad_request: return asio::buffer(bad_request); case reply::unauthorized: return asio::buffer(unauthorized); case reply::forbidden: return asio::buffer(forbidden); case reply::not_found: return asio::buffer(not_found); case reply::internal_server_error: return asio::buffer(internal_server_error); case reply::not_implemented: return asio::buffer(not_implemented); case reply::bad_gateway: return asio::buffer(bad_gateway); case reply::service_unavailable: return asio::buffer(service_unavailable); default: return asio::buffer(internal_server_error); } } } // namespace status_strings namespace misc_strings { const char name_value_separator[] = { ':', ' ' }; const char crlf[] = { '\r', '\n' }; } // namespace misc_strings std::vector<asio::const_buffer> reply::to_buffers() { std::vector<asio::const_buffer> buffers; buffers.push_back(status_strings::to_buffer(status)); for (std::size_t i = 0; i < headers.size(); ++i) { header& h = headers[i]; buffers.push_back(asio::buffer(h.name)); buffers.push_back(asio::buffer(misc_strings::name_value_separator)); buffers.push_back(asio::buffer(h.value)); buffers.push_back(asio::buffer(misc_strings::crlf)); } buffers.push_back(asio::buffer(misc_strings::crlf)); buffers.push_back(asio::buffer(content)); return buffers; } namespace stock_replies { const char ok[] = ""; const char created[] = "<html>" "<head><title>Created</title></head>" "<body><h1>201 Created</h1></body>" "</html>"; const char accepted[] = "<html>" "<head><title>Accepted</title></head>" "<body><h1>202 Accepted</h1></body>" "</html>"; const char no_content[] = "<html>" "<head><title>No Content</title></head>" "<body><h1>204 Content</h1></body>" "</html>"; const char multiple_choices[] = "<html>" "<head><title>Multiple Choices</title></head>" "<body><h1>300 Multiple Choices</h1></body>" "</html>"; const char moved_permanently[] = "<html>" "<head><title>Moved Permanently</title></head>" "<body><h1>301 Moved Permanently</h1></body>" "</html>"; const char moved_temporarily[] = "<html>" "<head><title>Moved Temporarily</title></head>" "<body><h1>302 Moved Temporarily</h1></body>" "</html>"; const char not_modified[] = "<html>" "<head><title>Not Modified</title></head>" "<body><h1>304 Not Modified</h1></body>" "</html>"; const char bad_request[] = "<html>" "<head><title>Bad Request</title></head>" "<body><h1>400 Bad Request</h1></body>" "</html>"; const char unauthorized[] = "<html>" "<head><title>Unauthorized</title></head>" "<body><h1>401 Unauthorized</h1></body>" "</html>"; const char forbidden[] = "<html>" "<head><title>Forbidden</title></head>" "<body><h1>403 Forbidden</h1></body>" "</html>"; const char not_found[] = "<html>" "<head><title>Not Found</title></head>" "<body><h1>404 Not Found</h1></body>" "</html>"; const char internal_server_error[] = "<html>" "<head><title>Internal Server Error</title></head>" "<body><h1>500 Internal Server Error</h1></body>" "</html>"; const char not_implemented[] = "<html>" "<head><title>Not Implemented</title></head>" "<body><h1>501 Not Implemented</h1></body>" "</html>"; const char bad_gateway[] = "<html>" "<head><title>Bad Gateway</title></head>" "<body><h1>502 Bad Gateway</h1></body>" "</html>"; const char service_unavailable[] = "<html>" "<head><title>Service Unavailable</title></head>" "<body><h1>503 Service Unavailable</h1></body>" "</html>"; std::string to_string(reply::status_type status) { switch (status) { case reply::ok: return ok; case reply::created: return created; case reply::accepted: return accepted; case reply::no_content: return no_content; case reply::multiple_choices: return multiple_choices; case reply::moved_permanently: return moved_permanently; case reply::moved_temporarily: return moved_temporarily; case reply::not_modified: return not_modified; case reply::bad_request: return bad_request; case reply::unauthorized: return unauthorized; case reply::forbidden: return forbidden; case reply::not_found: return not_found; case reply::internal_server_error: return internal_server_error; case reply::not_implemented: return not_implemented; case reply::bad_gateway: return bad_gateway; case reply::service_unavailable: return service_unavailable; default: return internal_server_error; } } } // namespace stock_replies reply reply::stock_reply(reply::status_type status) { reply rep; rep.status = status; rep.content = stock_replies::to_string(status); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = "text/html"; return rep; } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/request_parser.hpp
// // request_parser.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_REQUEST_PARSER_HPP #define HTTP_SERVER2_REQUEST_PARSER_HPP #include <tuple> namespace http { namespace server2 { struct request; /// Parser for incoming requests. class request_parser { public: /// Construct ready to parse the request method. request_parser(); /// Reset to initial parser state. void reset(); /// Result of parse. enum result_type { good, bad, indeterminate }; /// Parse some data. The enum return value is good when a complete request has /// been parsed, bad if the data is invalid, indeterminate when more data is /// required. The InputIterator return value indicates how much of the input /// has been consumed. template <typename InputIterator> std::tuple<result_type, InputIterator> parse(request& req, InputIterator begin, InputIterator end) { while (begin != end) { result_type result = consume(req, *begin++); if (result == good || result == bad) return std::make_tuple(result, begin); } return std::make_tuple(indeterminate, begin); } private: /// Handle the next character of input. result_type consume(request& req, char input); /// Check if a byte is an HTTP character. static bool is_char(int c); /// Check if a byte is an HTTP control character. static bool is_ctl(int c); /// Check if a byte is defined as an HTTP tspecial character. static bool is_tspecial(int c); /// Check if a byte is a digit. static bool is_digit(int c); /// The current state of the parser. enum state { method_start, method, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3 } state_; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_REQUEST_PARSER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/header.hpp
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_HEADER_HPP #define HTTP_SERVER2_HEADER_HPP #include <string> namespace http { namespace server2 { struct header { std::string name; std::string value; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_HEADER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/request_handler.hpp
// // request_handler.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_REQUEST_HANDLER_HPP #define HTTP_SERVER2_REQUEST_HANDLER_HPP #include <string> namespace http { namespace server2 { struct reply; struct request; /// The common handler for all incoming requests. class request_handler { public: request_handler(const request_handler&) = delete; request_handler& operator=(const request_handler&) = delete; /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root); /// Handle a request and produce a reply. void handle_request(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_REQUEST_HANDLER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/reply.hpp
// // reply.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_REPLY_HPP #define HTTP_SERVER2_REPLY_HPP #include <string> #include <vector> #include <asio.hpp> #include "header.hpp" namespace http { namespace server2 { /// A reply to be sent to a client. struct reply { /// The status of the reply. enum status_type { ok = 200, created = 201, accepted = 202, no_content = 204, multiple_choices = 300, moved_permanently = 301, moved_temporarily = 302, not_modified = 304, bad_request = 400, unauthorized = 401, forbidden = 403, not_found = 404, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503 } status; /// The headers to be included in the reply. std::vector<header> headers; /// The content to be sent in the reply. std::string content; /// Convert the reply into a vector of buffers. The buffers do not own the /// underlying memory blocks, therefore the reply object must remain valid and /// not be changed until the write operation has completed. std::vector<asio::const_buffer> to_buffers(); /// Get a stock reply. static reply stock_reply(status_type status); }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_REPLY_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/io_context_pool.hpp
// // io_context_pool.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_IO_SERVICE_POOL_HPP #define HTTP_SERVER2_IO_SERVICE_POOL_HPP #include <asio.hpp> #include <list> #include <memory> #include <vector> namespace http { namespace server2 { /// A pool of io_context objects. class io_context_pool { public: /// Construct the io_context pool. explicit io_context_pool(std::size_t pool_size); /// Run all io_context objects in the pool. void run(); /// Stop all io_context objects in the pool. void stop(); /// Get an io_context to use. asio::io_context& get_io_context(); private: io_context_pool(const io_context_pool&) = delete; io_context_pool& operator=(const io_context_pool&) = delete; typedef std::shared_ptr<asio::io_context> io_context_ptr; typedef asio::executor_work_guard< asio::io_context::executor_type> io_context_work; /// The pool of io_contexts. std::vector<io_context_ptr> io_contexts_; /// The work that keeps the io_contexts running. std::list<io_context_work> work_; /// The next io_context to use for a connection. std::size_t next_io_context_; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_IO_SERVICE_POOL_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/main.cpp
// // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <string> #include <asio.hpp> #include "server.hpp" int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 5) { std::cerr << "Usage: http_server <address> <port> <threads> <doc_root>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 1 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 1 .\n"; return 1; } // Initialise the server. std::size_t num_threads = std::stoi(argv[3]); http::server2::server s(argv[1], argv[2], argv[4], num_threads); // Run the server until stopped. s.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/server.hpp
// // server.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER2_SERVER_HPP #define HTTP_SERVER2_SERVER_HPP #include <asio.hpp> #include <string> #include "io_context_pool.hpp" #include "request_handler.hpp" namespace http { namespace server2 { /// The top-level class of the HTTP server. class server { public: server(const server&) = delete; server& operator=(const server&) = delete; /// Construct the server to listen on the specified TCP address and port, and /// serve up files from the given directory. explicit server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t io_context_pool_size); /// Run the server's io_context loop. void run(); private: /// Perform an asynchronous accept operation. void do_accept(); /// Wait for a request to stop the server. void do_await_stop(); /// The pool of io_context objects used to perform asynchronous operations. io_context_pool io_context_pool_; /// The signal_set is used to register for process termination notifications. asio::signal_set signals_; /// Acceptor used to listen for incoming connections. asio::ip::tcp::acceptor acceptor_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_SERVER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server2/request_parser.cpp
// // request_parser.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_parser.hpp" #include "request.hpp" namespace http { namespace server2 { request_parser::request_parser() : state_(method_start) { } void request_parser::reset() { state_ = method_start; } request_parser::result_type request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { state_ = method; req.method.push_back(input); return indeterminate; } case method: if (input == ' ') { state_ = uri; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.method.push_back(input); return indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.uri.push_back(input); return indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return indeterminate; } else { return bad; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return indeterminate; } else { return bad; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return indeterminate; } else { return bad; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return indeterminate; } else { return bad; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return indeterminate; } else { return bad; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return indeterminate; } else { return bad; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return indeterminate; } else { return bad; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return indeterminate; } else { return bad; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return indeterminate; } else { return bad; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (input == ' ' || input == '\t') { return indeterminate; } else if (is_ctl(input)) { return bad; } else { state_ = header_value; req.headers.back().value.push_back(input); return indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.back().name.push_back(input); return indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return indeterminate; } else { return bad; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.headers.back().value.push_back(input); return indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case expecting_newline_3: return (input == '\n') ? good : bad; default: return bad; } } bool request_parser::is_char(int c) { return c >= 0 && c <= 127; } bool request_parser::is_ctl(int c) { return (c >= 0 && c <= 31) || (c == 127); } bool request_parser::is_tspecial(int c) { switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } bool request_parser::is_digit(int c) { return c >= '0' && c <= '9'; } } // namespace server2 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/connection.hpp
// // connection.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_CONNECTION_HPP #define HTTP_SERVER3_CONNECTION_HPP #include <asio.hpp> #include <array> #include <memory> #include "reply.hpp" #include "request.hpp" #include "request_handler.hpp" #include "request_parser.hpp" namespace http { namespace server3 { /// Represents a single connection from a client. class connection : public std::enable_shared_from_this<connection> { public: connection(const connection&) = delete; connection& operator=(const connection&) = delete; /// Construct a connection with the given socket. explicit connection(asio::ip::tcp::socket socket, request_handler& handler); /// Start the first asynchronous operation for the connection. void start(); private: /// Perform an asynchronous read operation. void do_read(); /// Perform an asynchronous write operation. void do_write(); /// Socket for the connection. asio::ip::tcp::socket socket_; /// The handler used to process the incoming request. request_handler& request_handler_; /// Buffer for incoming data. std::array<char, 8192> buffer_; /// The incoming request. request request_; /// The parser for the incoming request. request_parser request_parser_; /// The reply to be sent back to the client. reply reply_; }; typedef std::shared_ptr<connection> connection_ptr; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_CONNECTION_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/request.hpp
// // request.hpp // ~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_REQUEST_HPP #define HTTP_SERVER3_REQUEST_HPP #include <string> #include <vector> #include "header.hpp" namespace http { namespace server3 { /// A request received from a client. struct request { std::string method; std::string uri; int http_version_major; int http_version_minor; std::vector<header> headers; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_REQUEST_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/mime_types.cpp
// // mime_types.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "mime_types.hpp" namespace http { namespace server3 { namespace mime_types { struct mapping { const char* extension; const char* mime_type; } mappings[] = { { "gif", "image/gif" }, { "htm", "text/html" }, { "html", "text/html" }, { "jpg", "image/jpeg" }, { "png", "image/png" }, { 0, 0 } // Marks end of list. }; std::string extension_to_type(const std::string& extension) { for (mapping* m = mappings; m->extension; ++m) { if (m->extension == extension) { return m->mime_type; } } return "text/plain"; } } // namespace mime_types } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/connection.cpp
// // connection.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "connection.hpp" #include <utility> #include "request_handler.hpp" namespace http { namespace server3 { connection::connection(asio::ip::tcp::socket socket, request_handler& handler) : socket_(std::move(socket)), request_handler_(handler) { } void connection::start() { do_read(); } void connection::do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(buffer_), [this, self](std::error_code ec, std::size_t bytes_transferred) { if (!ec) { request_parser::result_type result; std::tie(result, std::ignore) = request_parser_.parse( request_, buffer_.data(), buffer_.data() + bytes_transferred); if (result == request_parser::good) { request_handler_.handle_request(request_, reply_); do_write(); } else if (result == request_parser::bad) { reply_ = reply::stock_reply(reply::bad_request); do_write(); } else { do_read(); } } // If an error occurs then no new asynchronous operations are // started. This means that all shared_ptr references to the // connection object will disappear and the object will be // destroyed automatically after this handler returns. The // connection class's destructor closes the socket. }); } void connection::do_write() { auto self(shared_from_this()); asio::async_write(socket_, reply_.to_buffers(), [this, self](std::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. std::error_code ignored_ec; socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec); } // No new asynchronous operations are started. This means that // all shared_ptr references to the connection object will // disappear and the object will be destroyed automatically after // this handler returns. The connection class's destructor closes // the socket. }); } } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/request_handler.cpp
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server3 { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/mime_types.hpp
// // mime_types.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_MIME_TYPES_HPP #define HTTP_SERVER3_MIME_TYPES_HPP #include <string> namespace http { namespace server3 { namespace mime_types { /// Convert a file extension into a MIME type. std::string extension_to_type(const std::string& extension); } // namespace mime_types } // namespace server3 } // namespace http #endif // HTTP_SERVER3_MIME_TYPES_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "server.hpp" #include <signal.h> #include <thread> #include <utility> #include <vector> #include "connection.hpp" namespace http { namespace server3 { server::server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t thread_pool_size) : thread_pool_size_(thread_pool_size), signals_(io_context_), acceptor_(io_context_), request_handler_(doc_root) { // Register to handle the signals that indicate when the server should exit. // It is safe to register for the same signal multiple times in a program, // provided all registration for the specified signal is made through Asio. signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // defined(SIGQUIT) do_await_stop(); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). asio::ip::tcp::resolver resolver(io_context_); asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); do_accept(); } void server::run() { // Create a pool of threads to run the io_context. std::vector<std::thread> threads; for (std::size_t i = 0; i < thread_pool_size_; ++i) threads.emplace_back([this]{ io_context_.run(); }); // Wait for all threads in the pool to exit. for (std::size_t i = 0; i < threads.size(); ++i) threads[i].join(); } void server::do_accept() { // The newly accepted socket is put into its own strand to ensure that all // completion handlers associated with the connection do not run concurrently. acceptor_.async_accept(asio::make_strand(io_context_), [this](std::error_code ec, asio::ip::tcp::socket socket) { // Check whether the server was stopped by a signal before this // completion handler had a chance to run. if (!acceptor_.is_open()) { return; } if (!ec) { std::make_shared<connection>( std::move(socket), request_handler_)->start(); } do_accept(); }); } void server::do_await_stop() { signals_.async_wait( [this](std::error_code /*ec*/, int /*signo*/) { io_context_.stop(); }); } } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/reply.cpp
// // reply.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "reply.hpp" #include <string> namespace http { namespace server3 { namespace status_strings { const std::string ok = "HTTP/1.0 200 OK\r\n"; const std::string created = "HTTP/1.0 201 Created\r\n"; const std::string accepted = "HTTP/1.0 202 Accepted\r\n"; const std::string no_content = "HTTP/1.0 204 No Content\r\n"; const std::string multiple_choices = "HTTP/1.0 300 Multiple Choices\r\n"; const std::string moved_permanently = "HTTP/1.0 301 Moved Permanently\r\n"; const std::string moved_temporarily = "HTTP/1.0 302 Moved Temporarily\r\n"; const std::string not_modified = "HTTP/1.0 304 Not Modified\r\n"; const std::string bad_request = "HTTP/1.0 400 Bad Request\r\n"; const std::string unauthorized = "HTTP/1.0 401 Unauthorized\r\n"; const std::string forbidden = "HTTP/1.0 403 Forbidden\r\n"; const std::string not_found = "HTTP/1.0 404 Not Found\r\n"; const std::string internal_server_error = "HTTP/1.0 500 Internal Server Error\r\n"; const std::string not_implemented = "HTTP/1.0 501 Not Implemented\r\n"; const std::string bad_gateway = "HTTP/1.0 502 Bad Gateway\r\n"; const std::string service_unavailable = "HTTP/1.0 503 Service Unavailable\r\n"; asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return asio::buffer(ok); case reply::created: return asio::buffer(created); case reply::accepted: return asio::buffer(accepted); case reply::no_content: return asio::buffer(no_content); case reply::multiple_choices: return asio::buffer(multiple_choices); case reply::moved_permanently: return asio::buffer(moved_permanently); case reply::moved_temporarily: return asio::buffer(moved_temporarily); case reply::not_modified: return asio::buffer(not_modified); case reply::bad_request: return asio::buffer(bad_request); case reply::unauthorized: return asio::buffer(unauthorized); case reply::forbidden: return asio::buffer(forbidden); case reply::not_found: return asio::buffer(not_found); case reply::internal_server_error: return asio::buffer(internal_server_error); case reply::not_implemented: return asio::buffer(not_implemented); case reply::bad_gateway: return asio::buffer(bad_gateway); case reply::service_unavailable: return asio::buffer(service_unavailable); default: return asio::buffer(internal_server_error); } } } // namespace status_strings namespace misc_strings { const char name_value_separator[] = { ':', ' ' }; const char crlf[] = { '\r', '\n' }; } // namespace misc_strings std::vector<asio::const_buffer> reply::to_buffers() { std::vector<asio::const_buffer> buffers; buffers.push_back(status_strings::to_buffer(status)); for (std::size_t i = 0; i < headers.size(); ++i) { header& h = headers[i]; buffers.push_back(asio::buffer(h.name)); buffers.push_back(asio::buffer(misc_strings::name_value_separator)); buffers.push_back(asio::buffer(h.value)); buffers.push_back(asio::buffer(misc_strings::crlf)); } buffers.push_back(asio::buffer(misc_strings::crlf)); buffers.push_back(asio::buffer(content)); return buffers; } namespace stock_replies { const char ok[] = ""; const char created[] = "<html>" "<head><title>Created</title></head>" "<body><h1>201 Created</h1></body>" "</html>"; const char accepted[] = "<html>" "<head><title>Accepted</title></head>" "<body><h1>202 Accepted</h1></body>" "</html>"; const char no_content[] = "<html>" "<head><title>No Content</title></head>" "<body><h1>204 Content</h1></body>" "</html>"; const char multiple_choices[] = "<html>" "<head><title>Multiple Choices</title></head>" "<body><h1>300 Multiple Choices</h1></body>" "</html>"; const char moved_permanently[] = "<html>" "<head><title>Moved Permanently</title></head>" "<body><h1>301 Moved Permanently</h1></body>" "</html>"; const char moved_temporarily[] = "<html>" "<head><title>Moved Temporarily</title></head>" "<body><h1>302 Moved Temporarily</h1></body>" "</html>"; const char not_modified[] = "<html>" "<head><title>Not Modified</title></head>" "<body><h1>304 Not Modified</h1></body>" "</html>"; const char bad_request[] = "<html>" "<head><title>Bad Request</title></head>" "<body><h1>400 Bad Request</h1></body>" "</html>"; const char unauthorized[] = "<html>" "<head><title>Unauthorized</title></head>" "<body><h1>401 Unauthorized</h1></body>" "</html>"; const char forbidden[] = "<html>" "<head><title>Forbidden</title></head>" "<body><h1>403 Forbidden</h1></body>" "</html>"; const char not_found[] = "<html>" "<head><title>Not Found</title></head>" "<body><h1>404 Not Found</h1></body>" "</html>"; const char internal_server_error[] = "<html>" "<head><title>Internal Server Error</title></head>" "<body><h1>500 Internal Server Error</h1></body>" "</html>"; const char not_implemented[] = "<html>" "<head><title>Not Implemented</title></head>" "<body><h1>501 Not Implemented</h1></body>" "</html>"; const char bad_gateway[] = "<html>" "<head><title>Bad Gateway</title></head>" "<body><h1>502 Bad Gateway</h1></body>" "</html>"; const char service_unavailable[] = "<html>" "<head><title>Service Unavailable</title></head>" "<body><h1>503 Service Unavailable</h1></body>" "</html>"; std::string to_string(reply::status_type status) { switch (status) { case reply::ok: return ok; case reply::created: return created; case reply::accepted: return accepted; case reply::no_content: return no_content; case reply::multiple_choices: return multiple_choices; case reply::moved_permanently: return moved_permanently; case reply::moved_temporarily: return moved_temporarily; case reply::not_modified: return not_modified; case reply::bad_request: return bad_request; case reply::unauthorized: return unauthorized; case reply::forbidden: return forbidden; case reply::not_found: return not_found; case reply::internal_server_error: return internal_server_error; case reply::not_implemented: return not_implemented; case reply::bad_gateway: return bad_gateway; case reply::service_unavailable: return service_unavailable; default: return internal_server_error; } } } // namespace stock_replies reply reply::stock_reply(reply::status_type status) { reply rep; rep.status = status; rep.content = stock_replies::to_string(status); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = "text/html"; return rep; } } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/request_parser.hpp
// // request_parser.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_REQUEST_PARSER_HPP #define HTTP_SERVER3_REQUEST_PARSER_HPP #include <tuple> namespace http { namespace server3 { struct request; /// Parser for incoming requests. class request_parser { public: /// Construct ready to parse the request method. request_parser(); /// Reset to initial parser state. void reset(); /// Result of parse. enum result_type { good, bad, indeterminate }; /// Parse some data. The enum return value is good when a complete request has /// been parsed, bad if the data is invalid, indeterminate when more data is /// required. The InputIterator return value indicates how much of the input /// has been consumed. template <typename InputIterator> std::tuple<result_type, InputIterator> parse(request& req, InputIterator begin, InputIterator end) { while (begin != end) { result_type result = consume(req, *begin++); if (result == good || result == bad) return std::make_tuple(result, begin); } return std::make_tuple(indeterminate, begin); } private: /// Handle the next character of input. result_type consume(request& req, char input); /// Check if a byte is an HTTP character. static bool is_char(int c); /// Check if a byte is an HTTP control character. static bool is_ctl(int c); /// Check if a byte is defined as an HTTP tspecial character. static bool is_tspecial(int c); /// Check if a byte is a digit. static bool is_digit(int c); /// The current state of the parser. enum state { method_start, method, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3 } state_; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_REQUEST_PARSER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/header.hpp
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_HEADER_HPP #define HTTP_SERVER3_HEADER_HPP #include <string> namespace http { namespace server3 { struct header { std::string name; std::string value; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_HEADER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/request_handler.hpp
// // request_handler.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_REQUEST_HANDLER_HPP #define HTTP_SERVER3_REQUEST_HANDLER_HPP #include <string> namespace http { namespace server3 { struct reply; struct request; /// The common handler for all incoming requests. class request_handler { public: request_handler(const request_handler&) = delete; request_handler& operator=(const request_handler&) = delete; /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root); /// Handle a request and produce a reply. void handle_request(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_REQUEST_HANDLER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/reply.hpp
// // reply.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_REPLY_HPP #define HTTP_SERVER3_REPLY_HPP #include <string> #include <vector> #include <asio.hpp> #include "header.hpp" namespace http { namespace server3 { /// A reply to be sent to a client. struct reply { /// The status of the reply. enum status_type { ok = 200, created = 201, accepted = 202, no_content = 204, multiple_choices = 300, moved_permanently = 301, moved_temporarily = 302, not_modified = 304, bad_request = 400, unauthorized = 401, forbidden = 403, not_found = 404, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503 } status; /// The headers to be included in the reply. std::vector<header> headers; /// The content to be sent in the reply. std::string content; /// Convert the reply into a vector of buffers. The buffers do not own the /// underlying memory blocks, therefore the reply object must remain valid and /// not be changed until the write operation has completed. std::vector<asio::const_buffer> to_buffers(); /// Get a stock reply. static reply stock_reply(status_type status); }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_REPLY_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/main.cpp
// // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <string> #include <asio.hpp> #include "server.hpp" int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 5) { std::cerr << "Usage: http_server <address> <port> <threads> <doc_root>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 1 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 1 .\n"; return 1; } // Initialise the server. std::size_t num_threads = std::stoi(argv[3]); http::server3::server s(argv[1], argv[2], argv[4], num_threads); // Run the server until stopped. s.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/server.hpp
// // server.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER3_SERVER_HPP #define HTTP_SERVER3_SERVER_HPP #include <asio.hpp> #include <string> #include "request_handler.hpp" namespace http { namespace server3 { /// The top-level class of the HTTP server. class server { public: server(const server&) = delete; server& operator=(const server&) = delete; /// Construct the server to listen on the specified TCP address and port, and /// serve up files from the given directory. explicit server(const std::string& address, const std::string& port, const std::string& doc_root, std::size_t thread_pool_size); /// Run the server's io_context loop. void run(); private: /// Perform an asynchronous accept operation. void do_accept(); /// Wait for a request to stop the server. void do_await_stop(); /// The number of threads that will call io_context::run(). std::size_t thread_pool_size_; /// The io_context used to perform asynchronous operations. asio::io_context io_context_; /// The signal_set is used to register for process termination notifications. asio::signal_set signals_; /// Acceptor used to listen for incoming connections. asio::ip::tcp::acceptor acceptor_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_SERVER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server3/request_parser.cpp
// // request_parser.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_parser.hpp" #include "request.hpp" namespace http { namespace server3 { request_parser::request_parser() : state_(method_start) { } void request_parser::reset() { state_ = method_start; } request_parser::result_type request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { state_ = method; req.method.push_back(input); return indeterminate; } case method: if (input == ' ') { state_ = uri; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.method.push_back(input); return indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.uri.push_back(input); return indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return indeterminate; } else { return bad; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return indeterminate; } else { return bad; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return indeterminate; } else { return bad; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return indeterminate; } else { return bad; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return indeterminate; } else { return bad; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return indeterminate; } else { return bad; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return indeterminate; } else { return bad; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return indeterminate; } else { return bad; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return indeterminate; } else { return bad; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (input == ' ' || input == '\t') { return indeterminate; } else if (is_ctl(input)) { return bad; } else { state_ = header_value; req.headers.back().value.push_back(input); return indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.back().name.push_back(input); return indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return indeterminate; } else { return bad; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.headers.back().value.push_back(input); return indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case expecting_newline_3: return (input == '\n') ? good : bad; default: return bad; } } bool request_parser::is_char(int c) { return c >= 0 && c <= 127; } bool request_parser::is_ctl(int c) { return (c >= 0 && c <= 31) || (c == 127); } bool request_parser::is_tspecial(int c) { switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } bool request_parser::is_digit(int c) { return c >= '0' && c <= '9'; } } // namespace server3 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/doc_root/data_2K.html
<!-- Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <html> <body> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps ove<br/> </body> </html> <!-- boostinspect:nounlinked -->
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/doc_root/data_1K.html
<!-- Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <html> <body> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the<br/> </body> </html> <!-- boostinspect:nounlinked -->
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/doc_root/data_8K.html
<!-- Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <html> <body> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> .... </body> </html> <!-- boostinspect:nounlinked -->
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/doc_root/data_4K.html
<!-- Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) --> <html> <body> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox jumps over the lazy dog<br/> The quick brown fox<br/> </body> </html> <!-- boostinspect:nounlinked -->
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/client/async_client.cpp
// // async_client.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <functional> #include <iostream> #include <istream> #include <ostream> #include <string> #include <asio.hpp> using asio::ip::tcp; class client { public: client(asio::io_context& io_context, const std::string& server, const std::string& path) : resolver_(io_context), socket_(io_context) { // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. std::ostream request_stream(&request_); request_stream << "GET " << path << " HTTP/1.0\r\n"; request_stream << "Host: " << server << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n\r\n"; // Start an asynchronous resolve to translate the server and service names // into a list of endpoints. resolver_.async_resolve(server, "http", std::bind(&client::handle_resolve, this, asio::placeholders::error, asio::placeholders::results)); } private: void handle_resolve(const std::error_code& err, const tcp::resolver::results_type& endpoints) { if (!err) { // Attempt a connection to each endpoint in the list until we // successfully establish a connection. asio::async_connect(socket_, endpoints, std::bind(&client::handle_connect, this, asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_connect(const std::error_code& err) { if (!err) { // The connection was successful. Send the request. asio::async_write(socket_, request_, std::bind(&client::handle_write_request, this, asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_write_request(const std::error_code& err) { if (!err) { // Read the response status line. The response_ streambuf will // automatically grow to accommodate the entire line. The growth may be // limited by passing a maximum size to the streambuf constructor. asio::async_read_until(socket_, response_, "\r\n", std::bind(&client::handle_read_status_line, this, asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_read_status_line(const std::error_code& err) { if (!err) { // Check that response is OK. std::istream response_stream(&response_); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return; } if (status_code != 200) { std::cout << "Response returned with status code "; std::cout << status_code << "\n"; return; } // Read the response headers, which are terminated by a blank line. asio::async_read_until(socket_, response_, "\r\n\r\n", std::bind(&client::handle_read_headers, this, asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_headers(const std::error_code& err) { if (!err) { // Process the response headers. std::istream response_stream(&response_); std::string header; while (std::getline(response_stream, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write whatever content we already have to output. if (response_.size() > 0) std::cout << &response_; // Start reading remaining data until EOF. asio::async_read(socket_, response_, asio::transfer_at_least(1), std::bind(&client::handle_read_content, this, asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_content(const std::error_code& err) { if (!err) { // Write all of the data that has been read so far. std::cout << &response_; // Continue reading remaining data until EOF. asio::async_read(socket_, response_, asio::transfer_at_least(1), std::bind(&client::handle_read_content, this, asio::placeholders::error)); } else if (err != asio::error::eof) { std::cout << "Error: " << err << "\n"; } } tcp::resolver resolver_; tcp::socket socket_; asio::streambuf request_; asio::streambuf response_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cout << "Usage: async_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " async_client www.boost.org /LICENSE_1_0.txt\n"; return 1; } asio::io_context io_context; client c(io_context, argv[1], argv[2]); io_context.run(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/client/sync_client.cpp
// // sync_client.cpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <istream> #include <ostream> #include <string> #include <asio.hpp> using asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cout << "Usage: sync_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " sync_client www.boost.org /LICENSE_1_0.txt\n"; return 1; } asio::io_context io_context; // Get a list of endpoints corresponding to the server name. tcp::resolver resolver(io_context); tcp::resolver::results_type endpoints = resolver.resolve(argv[1], "http"); // Try each endpoint until we successfully establish a connection. tcp::socket socket(io_context); asio::connect(socket, endpoints); // Form the request. We specify the "Connection: close" header so that the // server will close the socket after transmitting the response. This will // allow us to treat all data up until the EOF as the content. asio::streambuf request; std::ostream request_stream(&request); request_stream << "GET " << argv[2] << " HTTP/1.0\r\n"; request_stream << "Host: " << argv[1] << "\r\n"; request_stream << "Accept: */*\r\n"; request_stream << "Connection: close\r\n\r\n"; // Send the request. asio::write(socket, request); // Read the response status line. The response streambuf will automatically // grow to accommodate the entire line. The growth may be limited by passing // a maximum size to the streambuf constructor. asio::streambuf response; asio::read_until(socket, response, "\r\n"); // Check that response is OK. std::istream response_stream(&response); std::string http_version; response_stream >> http_version; unsigned int status_code; response_stream >> status_code; std::string status_message; std::getline(response_stream, status_message); if (!response_stream || http_version.substr(0, 5) != "HTTP/") { std::cout << "Invalid response\n"; return 1; } if (status_code != 200) { std::cout << "Response returned with status code " << status_code << "\n"; return 1; } // Read the response headers, which are terminated by a blank line. asio::read_until(socket, response, "\r\n\r\n"); // Process the response headers. std::string header; while (std::getline(response_stream, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write whatever content we already have to output. if (response.size() > 0) std::cout << &response; // Read until EOF, writing data to output as we go. std::error_code error; while (asio::read(socket, response, asio::transfer_at_least(1), error)) std::cout << &response; if (error != asio::error::eof) throw std::system_error(error); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/connection.hpp
// // connection.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_CONNECTION_HPP #define HTTP_CONNECTION_HPP #include <asio.hpp> #include <array> #include <memory> #include "reply.hpp" #include "request.hpp" #include "request_handler.hpp" #include "request_parser.hpp" namespace http { namespace server { class connection_manager; /// Represents a single connection from a client. class connection : public std::enable_shared_from_this<connection> { public: connection(const connection&) = delete; connection& operator=(const connection&) = delete; /// Construct a connection with the given socket. explicit connection(asio::ip::tcp::socket socket, connection_manager& manager, request_handler& handler); /// Start the first asynchronous operation for the connection. void start(); /// Stop all asynchronous operations associated with the connection. void stop(); private: /// Perform an asynchronous read operation. void do_read(); /// Perform an asynchronous write operation. void do_write(); /// Socket for the connection. asio::ip::tcp::socket socket_; /// The manager for this connection. connection_manager& connection_manager_; /// The handler used to process the incoming request. request_handler& request_handler_; /// Buffer for incoming data. std::array<char, 8192> buffer_; /// The incoming request. request request_; /// The parser for the incoming request. request_parser request_parser_; /// The reply to be sent back to the client. reply reply_; }; typedef std::shared_ptr<connection> connection_ptr; } // namespace server } // namespace http #endif // HTTP_CONNECTION_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/request.hpp
// // request.hpp // ~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_REQUEST_HPP #define HTTP_REQUEST_HPP #include <string> #include <vector> #include "header.hpp" namespace http { namespace server { /// A request received from a client. struct request { std::string method; std::string uri; int http_version_major; int http_version_minor; std::vector<header> headers; }; } // namespace server } // namespace http #endif // HTTP_REQUEST_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/mime_types.cpp
// // mime_types.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "mime_types.hpp" namespace http { namespace server { namespace mime_types { struct mapping { const char* extension; const char* mime_type; } mappings[] = { { "gif", "image/gif" }, { "htm", "text/html" }, { "html", "text/html" }, { "jpg", "image/jpeg" }, { "png", "image/png" } }; std::string extension_to_type(const std::string& extension) { for (mapping m: mappings) { if (m.extension == extension) { return m.mime_type; } } return "text/plain"; } } // namespace mime_types } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/connection.cpp
// // connection.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "connection.hpp" #include <utility> #include "connection_manager.hpp" #include "request_handler.hpp" namespace http { namespace server { connection::connection(asio::ip::tcp::socket socket, connection_manager& manager, request_handler& handler) : socket_(std::move(socket)), connection_manager_(manager), request_handler_(handler) { } void connection::start() { do_read(); } void connection::stop() { socket_.close(); } void connection::do_read() { auto self(shared_from_this()); socket_.async_read_some(asio::buffer(buffer_), [this, self](std::error_code ec, std::size_t bytes_transferred) { if (!ec) { request_parser::result_type result; std::tie(result, std::ignore) = request_parser_.parse( request_, buffer_.data(), buffer_.data() + bytes_transferred); if (result == request_parser::good) { request_handler_.handle_request(request_, reply_); do_write(); } else if (result == request_parser::bad) { reply_ = reply::stock_reply(reply::bad_request); do_write(); } else { do_read(); } } else if (ec != asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } void connection::do_write() { auto self(shared_from_this()); asio::async_write(socket_, reply_.to_buffers(), [this, self](std::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. std::error_code ignored_ec; socket_.shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec); } if (ec != asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/request_handler.cpp
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/mime_types.hpp
// // mime_types.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_MIME_TYPES_HPP #define HTTP_MIME_TYPES_HPP #include <string> namespace http { namespace server { namespace mime_types { /// Convert a file extension into a MIME type. std::string extension_to_type(const std::string& extension); } // namespace mime_types } // namespace server } // namespace http #endif // HTTP_MIME_TYPES_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "server.hpp" #include <signal.h> #include <utility> namespace http { namespace server { server::server(const std::string& address, const std::string& port, const std::string& doc_root) : io_context_(1), signals_(io_context_), acceptor_(io_context_), connection_manager_(), request_handler_(doc_root) { // Register to handle the signals that indicate when the server should exit. // It is safe to register for the same signal multiple times in a program, // provided all registration for the specified signal is made through Asio. signals_.add(SIGINT); signals_.add(SIGTERM); #if defined(SIGQUIT) signals_.add(SIGQUIT); #endif // defined(SIGQUIT) do_await_stop(); // Open the acceptor with the option to reuse the address (i.e. SO_REUSEADDR). asio::ip::tcp::resolver resolver(io_context_); asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(asio::ip::tcp::acceptor::reuse_address(true)); acceptor_.bind(endpoint); acceptor_.listen(); do_accept(); } void server::run() { // The io_context::run() call will block until all asynchronous operations // have finished. While the server is running, there is always at least one // asynchronous operation outstanding: the asynchronous accept call waiting // for new incoming connections. io_context_.run(); } void server::do_accept() { acceptor_.async_accept( [this](std::error_code ec, asio::ip::tcp::socket socket) { // Check whether the server was stopped by a signal before this // completion handler had a chance to run. if (!acceptor_.is_open()) { return; } if (!ec) { connection_manager_.start(std::make_shared<connection>( std::move(socket), connection_manager_, request_handler_)); } do_accept(); }); } void server::do_await_stop() { signals_.async_wait( [this](std::error_code /*ec*/, int /*signo*/) { // The server is stopped by cancelling all outstanding asynchronous // operations. Once all operations have finished the io_context::run() // call will exit. acceptor_.close(); connection_manager_.stop_all(); }); } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/reply.cpp
// // reply.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "reply.hpp" #include <string> namespace http { namespace server { namespace status_strings { const std::string ok = "HTTP/1.0 200 OK\r\n"; const std::string created = "HTTP/1.0 201 Created\r\n"; const std::string accepted = "HTTP/1.0 202 Accepted\r\n"; const std::string no_content = "HTTP/1.0 204 No Content\r\n"; const std::string multiple_choices = "HTTP/1.0 300 Multiple Choices\r\n"; const std::string moved_permanently = "HTTP/1.0 301 Moved Permanently\r\n"; const std::string moved_temporarily = "HTTP/1.0 302 Moved Temporarily\r\n"; const std::string not_modified = "HTTP/1.0 304 Not Modified\r\n"; const std::string bad_request = "HTTP/1.0 400 Bad Request\r\n"; const std::string unauthorized = "HTTP/1.0 401 Unauthorized\r\n"; const std::string forbidden = "HTTP/1.0 403 Forbidden\r\n"; const std::string not_found = "HTTP/1.0 404 Not Found\r\n"; const std::string internal_server_error = "HTTP/1.0 500 Internal Server Error\r\n"; const std::string not_implemented = "HTTP/1.0 501 Not Implemented\r\n"; const std::string bad_gateway = "HTTP/1.0 502 Bad Gateway\r\n"; const std::string service_unavailable = "HTTP/1.0 503 Service Unavailable\r\n"; asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return asio::buffer(ok); case reply::created: return asio::buffer(created); case reply::accepted: return asio::buffer(accepted); case reply::no_content: return asio::buffer(no_content); case reply::multiple_choices: return asio::buffer(multiple_choices); case reply::moved_permanently: return asio::buffer(moved_permanently); case reply::moved_temporarily: return asio::buffer(moved_temporarily); case reply::not_modified: return asio::buffer(not_modified); case reply::bad_request: return asio::buffer(bad_request); case reply::unauthorized: return asio::buffer(unauthorized); case reply::forbidden: return asio::buffer(forbidden); case reply::not_found: return asio::buffer(not_found); case reply::internal_server_error: return asio::buffer(internal_server_error); case reply::not_implemented: return asio::buffer(not_implemented); case reply::bad_gateway: return asio::buffer(bad_gateway); case reply::service_unavailable: return asio::buffer(service_unavailable); default: return asio::buffer(internal_server_error); } } } // namespace status_strings namespace misc_strings { const char name_value_separator[] = { ':', ' ' }; const char crlf[] = { '\r', '\n' }; } // namespace misc_strings std::vector<asio::const_buffer> reply::to_buffers() { std::vector<asio::const_buffer> buffers; buffers.push_back(status_strings::to_buffer(status)); for (std::size_t i = 0; i < headers.size(); ++i) { header& h = headers[i]; buffers.push_back(asio::buffer(h.name)); buffers.push_back(asio::buffer(misc_strings::name_value_separator)); buffers.push_back(asio::buffer(h.value)); buffers.push_back(asio::buffer(misc_strings::crlf)); } buffers.push_back(asio::buffer(misc_strings::crlf)); buffers.push_back(asio::buffer(content)); return buffers; } namespace stock_replies { const char ok[] = ""; const char created[] = "<html>" "<head><title>Created</title></head>" "<body><h1>201 Created</h1></body>" "</html>"; const char accepted[] = "<html>" "<head><title>Accepted</title></head>" "<body><h1>202 Accepted</h1></body>" "</html>"; const char no_content[] = "<html>" "<head><title>No Content</title></head>" "<body><h1>204 Content</h1></body>" "</html>"; const char multiple_choices[] = "<html>" "<head><title>Multiple Choices</title></head>" "<body><h1>300 Multiple Choices</h1></body>" "</html>"; const char moved_permanently[] = "<html>" "<head><title>Moved Permanently</title></head>" "<body><h1>301 Moved Permanently</h1></body>" "</html>"; const char moved_temporarily[] = "<html>" "<head><title>Moved Temporarily</title></head>" "<body><h1>302 Moved Temporarily</h1></body>" "</html>"; const char not_modified[] = "<html>" "<head><title>Not Modified</title></head>" "<body><h1>304 Not Modified</h1></body>" "</html>"; const char bad_request[] = "<html>" "<head><title>Bad Request</title></head>" "<body><h1>400 Bad Request</h1></body>" "</html>"; const char unauthorized[] = "<html>" "<head><title>Unauthorized</title></head>" "<body><h1>401 Unauthorized</h1></body>" "</html>"; const char forbidden[] = "<html>" "<head><title>Forbidden</title></head>" "<body><h1>403 Forbidden</h1></body>" "</html>"; const char not_found[] = "<html>" "<head><title>Not Found</title></head>" "<body><h1>404 Not Found</h1></body>" "</html>"; const char internal_server_error[] = "<html>" "<head><title>Internal Server Error</title></head>" "<body><h1>500 Internal Server Error</h1></body>" "</html>"; const char not_implemented[] = "<html>" "<head><title>Not Implemented</title></head>" "<body><h1>501 Not Implemented</h1></body>" "</html>"; const char bad_gateway[] = "<html>" "<head><title>Bad Gateway</title></head>" "<body><h1>502 Bad Gateway</h1></body>" "</html>"; const char service_unavailable[] = "<html>" "<head><title>Service Unavailable</title></head>" "<body><h1>503 Service Unavailable</h1></body>" "</html>"; std::string to_string(reply::status_type status) { switch (status) { case reply::ok: return ok; case reply::created: return created; case reply::accepted: return accepted; case reply::no_content: return no_content; case reply::multiple_choices: return multiple_choices; case reply::moved_permanently: return moved_permanently; case reply::moved_temporarily: return moved_temporarily; case reply::not_modified: return not_modified; case reply::bad_request: return bad_request; case reply::unauthorized: return unauthorized; case reply::forbidden: return forbidden; case reply::not_found: return not_found; case reply::internal_server_error: return internal_server_error; case reply::not_implemented: return not_implemented; case reply::bad_gateway: return bad_gateway; case reply::service_unavailable: return service_unavailable; default: return internal_server_error; } } } // namespace stock_replies reply reply::stock_reply(reply::status_type status) { reply rep; rep.status = status; rep.content = stock_replies::to_string(status); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = "text/html"; return rep; } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/request_parser.hpp
// // request_parser.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_REQUEST_PARSER_HPP #define HTTP_REQUEST_PARSER_HPP #include <tuple> namespace http { namespace server { struct request; /// Parser for incoming requests. class request_parser { public: /// Construct ready to parse the request method. request_parser(); /// Reset to initial parser state. void reset(); /// Result of parse. enum result_type { good, bad, indeterminate }; /// Parse some data. The enum return value is good when a complete request has /// been parsed, bad if the data is invalid, indeterminate when more data is /// required. The InputIterator return value indicates how much of the input /// has been consumed. template <typename InputIterator> std::tuple<result_type, InputIterator> parse(request& req, InputIterator begin, InputIterator end) { while (begin != end) { result_type result = consume(req, *begin++); if (result == good || result == bad) return std::make_tuple(result, begin); } return std::make_tuple(indeterminate, begin); } private: /// Handle the next character of input. result_type consume(request& req, char input); /// Check if a byte is an HTTP character. static bool is_char(int c); /// Check if a byte is an HTTP control character. static bool is_ctl(int c); /// Check if a byte is defined as an HTTP tspecial character. static bool is_tspecial(int c); /// Check if a byte is a digit. static bool is_digit(int c); /// The current state of the parser. enum state { method_start, method, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3 } state_; }; } // namespace server } // namespace http #endif // HTTP_REQUEST_PARSER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/header.hpp
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_HEADER_HPP #define HTTP_HEADER_HPP #include <string> namespace http { namespace server { struct header { std::string name; std::string value; }; } // namespace server } // namespace http #endif // HTTP_HEADER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/connection_manager.hpp
// // connection_manager.hpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_CONNECTION_MANAGER_HPP #define HTTP_CONNECTION_MANAGER_HPP #include <set> #include "connection.hpp" namespace http { namespace server { /// Manages open connections so that they may be cleanly stopped when the server /// needs to shut down. class connection_manager { public: connection_manager(const connection_manager&) = delete; connection_manager& operator=(const connection_manager&) = delete; /// Construct a connection manager. connection_manager(); /// Add the specified connection to the manager and start it. void start(connection_ptr c); /// Stop the specified connection. void stop(connection_ptr c); /// Stop all connections. void stop_all(); private: /// The managed connections. std::set<connection_ptr> connections_; }; } // namespace server } // namespace http #endif // HTTP_CONNECTION_MANAGER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/request_handler.hpp
// // request_handler.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_REQUEST_HANDLER_HPP #define HTTP_REQUEST_HANDLER_HPP #include <string> namespace http { namespace server { struct reply; struct request; /// The common handler for all incoming requests. class request_handler { public: request_handler(const request_handler&) = delete; request_handler& operator=(const request_handler&) = delete; /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root); /// Handle a request and produce a reply. void handle_request(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); }; } // namespace server } // namespace http #endif // HTTP_REQUEST_HANDLER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/reply.hpp
// // reply.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_REPLY_HPP #define HTTP_REPLY_HPP #include <string> #include <vector> #include <asio.hpp> #include "header.hpp" namespace http { namespace server { /// A reply to be sent to a client. struct reply { /// The status of the reply. enum status_type { ok = 200, created = 201, accepted = 202, no_content = 204, multiple_choices = 300, moved_permanently = 301, moved_temporarily = 302, not_modified = 304, bad_request = 400, unauthorized = 401, forbidden = 403, not_found = 404, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503 } status; /// The headers to be included in the reply. std::vector<header> headers; /// The content to be sent in the reply. std::string content; /// Convert the reply into a vector of buffers. The buffers do not own the /// underlying memory blocks, therefore the reply object must remain valid and /// not be changed until the write operation has completed. std::vector<asio::const_buffer> to_buffers(); /// Get a stock reply. static reply stock_reply(status_type status); }; } // namespace server } // namespace http #endif // HTTP_REPLY_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/main.cpp
// // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <string> #include <asio.hpp> #include "server.hpp" int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 4) { std::cerr << "Usage: http_server <address> <port> <doc_root>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 .\n"; return 1; } // Initialise the server. http::server::server s(argv[1], argv[2], argv[3]); // Run the server until stopped. s.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/server.hpp
// // server.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER_HPP #define HTTP_SERVER_HPP #include <asio.hpp> #include <string> #include "connection.hpp" #include "connection_manager.hpp" #include "request_handler.hpp" namespace http { namespace server { /// The top-level class of the HTTP server. class server { public: server(const server&) = delete; server& operator=(const server&) = delete; /// Construct the server to listen on the specified TCP address and port, and /// serve up files from the given directory. explicit server(const std::string& address, const std::string& port, const std::string& doc_root); /// Run the server's io_context loop. void run(); private: /// Perform an asynchronous accept operation. void do_accept(); /// Wait for a request to stop the server. void do_await_stop(); /// The io_context used to perform asynchronous operations. asio::io_context io_context_; /// The signal_set is used to register for process termination notifications. asio::signal_set signals_; /// Acceptor used to listen for incoming connections. asio::ip::tcp::acceptor acceptor_; /// The connection manager which owns all live connections. connection_manager connection_manager_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server } // namespace http #endif // HTTP_SERVER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/request_parser.cpp
// // request_parser.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_parser.hpp" #include "request.hpp" namespace http { namespace server { request_parser::request_parser() : state_(method_start) { } void request_parser::reset() { state_ = method_start; } request_parser::result_type request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { state_ = method; req.method.push_back(input); return indeterminate; } case method: if (input == ' ') { state_ = uri; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.method.push_back(input); return indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.uri.push_back(input); return indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return indeterminate; } else { return bad; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return indeterminate; } else { return bad; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return indeterminate; } else { return bad; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return indeterminate; } else { return bad; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return indeterminate; } else { return bad; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return indeterminate; } else { return bad; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return indeterminate; } else { return bad; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return indeterminate; } else { return bad; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return indeterminate; } else { return bad; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (input == ' ' || input == '\t') { return indeterminate; } else if (is_ctl(input)) { return bad; } else { state_ = header_value; req.headers.back().value.push_back(input); return indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.back().name.push_back(input); return indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return indeterminate; } else { return bad; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.headers.back().value.push_back(input); return indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case expecting_newline_3: return (input == '\n') ? good : bad; default: return bad; } } bool request_parser::is_char(int c) { return c >= 0 && c <= 127; } bool request_parser::is_ctl(int c) { return (c >= 0 && c <= 31) || (c == 127); } bool request_parser::is_tspecial(int c) { switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } bool request_parser::is_digit(int c) { return c >= '0' && c <= '9'; } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server/connection_manager.cpp
// // connection_manager.cpp // ~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "connection_manager.hpp" namespace http { namespace server { connection_manager::connection_manager() { } void connection_manager::start(connection_ptr c) { connections_.insert(c); c->start(); } void connection_manager::stop(connection_ptr c) { connections_.erase(c); c->stop(); } void connection_manager::stop_all() { for (auto c: connections_) c->stop(); connections_.clear(); } } // namespace server } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/request.hpp
// // request.hpp // ~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_REQUEST_HPP #define HTTP_SERVER4_REQUEST_HPP #include <string> #include <vector> #include "header.hpp" namespace http { namespace server4 { /// A request received from a client. struct request { std::string method; std::string uri; int http_version_major; int http_version_minor; std::vector<header> headers; }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_REQUEST_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/mime_types.cpp
// // mime_types.cpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "mime_types.hpp" namespace http { namespace server4 { namespace mime_types { struct mapping { const char* extension; const char* mime_type; } mappings[] = { { "gif", "image/gif" }, { "htm", "text/html" }, { "html", "text/html" }, { "jpg", "image/jpeg" }, { "png", "image/png" }, { 0, 0 } // Marks end of list. }; std::string extension_to_type(const std::string& extension) { for (mapping* m = mappings; m->extension; ++m) { if (m->extension == extension) { return m->mime_type; } } return "text/plain"; } } // namespace mime_types } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/file_handler.hpp
// // file_handler.hpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_FILE_HANDLER_HPP #define HTTP_SERVER4_FILE_HANDLER_HPP #include <string> namespace http { namespace server4 { struct reply; struct request; /// The common handler for all incoming requests. class file_handler { public: /// Construct with a directory containing files to be served. explicit file_handler(const std::string& doc_root); /// Handle a request and produce a reply. void operator()(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_FILE_HANDLER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/request_handler.cpp
// // request_handler.cpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server4 { request_handler::request_handler(const std::string& doc_root) : doc_root_(doc_root) { } void request_handler::handle_request(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool request_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/mime_types.hpp
// // mime_types.hpp // ~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_MIME_TYPES_HPP #define HTTP_SERVER4_MIME_TYPES_HPP #include <string> namespace http { namespace server4 { namespace mime_types { /// Convert a file extension into a MIME type. std::string extension_to_type(const std::string& extension); } // namespace mime_types } // namespace server4 } // namespace http #endif // HTTP_SERVER4_MIME_TYPES_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/server.cpp
// // server.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "server.hpp" #include "request.hpp" #include "reply.hpp" namespace http { namespace server4 { server::server(asio::io_context& io_context, const std::string& address, const std::string& port, std::function<void(const request&, reply&)> request_handler) : request_handler_(request_handler) { tcp::resolver resolver(io_context); asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.reset(new tcp::acceptor(io_context, endpoint)); } // Enable the pseudo-keywords reenter, yield and fork. #include <asio/yield.hpp> void server::operator()(std::error_code ec, std::size_t length) { // In this example we keep the error handling code in one place by // hoisting it outside the coroutine. An alternative approach would be to // check the value of ec after each yield for an asynchronous operation. if (!ec) { // On reentering a coroutine, control jumps to the location of the last // yield or fork. The argument to the "reenter" pseudo-keyword can be a // pointer or reference to an object of type coroutine. reenter (this) { // Loop to accept incoming connections. do { // Create a new socket for the next incoming connection. socket_.reset(new tcp::socket(acceptor_->get_executor())); // Accept a new connection. The "yield" pseudo-keyword saves the current // line number and exits the coroutine's "reenter" block. We use the // server coroutine as the completion handler for the async_accept // operation. When the asynchronous operation completes, the io_context // invokes the function call operator, we "reenter" the coroutine, and // then control resumes at the following line. yield acceptor_->async_accept(*socket_, *this); // We "fork" by cloning a new server coroutine to handle the connection. // After forking we have a parent coroutine and a child coroutine. Both // parent and child continue execution at the following line. They can // be distinguished using the functions coroutine::is_parent() and // coroutine::is_child(). fork server(*this)(); // The parent continues looping to accept the next incoming connection. // The child exits the loop and processes the connection. } while (is_parent()); // Create the objects needed to receive a request on the connection. buffer_.reset(new std::array<char, 8192>); request_.reset(new request); // Loop until a complete request (or an invalid one) has been received. do { // Receive some more data. When control resumes at the following line, // the ec and length parameters reflect the result of the asynchronous // operation. yield socket_->async_read_some(asio::buffer(*buffer_), *this); // Parse the data we just received. std::tie(parse_result_, std::ignore) = request_parser_.parse(*request_, buffer_->data(), buffer_->data() + length); // An indeterminate result means we need more data, so keep looping. } while (parse_result_ == request_parser::indeterminate); // Create the reply object that will be sent back to the client. reply_.reset(new reply); if (parse_result_ == request_parser::good) { // A valid request was received. Call the user-supplied function object // to process the request and compose a reply. request_handler_(*request_, *reply_); } else { // The request was invalid. *reply_ = reply::stock_reply(reply::bad_request); } // Send the reply back to the client. yield asio::async_write(*socket_, reply_->to_buffers(), *this); // Initiate graceful connection closure. socket_->shutdown(tcp::socket::shutdown_both, ec); } } // If an error occurs then the coroutine is not reentered. Consequently, no // new asynchronous operations are started. This means that all shared_ptr // references will disappear and the resources associated with the coroutine // will be destroyed automatically after this function call returns. } // Disable the pseudo-keywords reenter, yield and fork. #include <asio/unyield.hpp> } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/reply.cpp
// // reply.cpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "reply.hpp" #include <string> namespace http { namespace server4 { namespace status_strings { const std::string ok = "HTTP/1.0 200 OK\r\n"; const std::string created = "HTTP/1.0 201 Created\r\n"; const std::string accepted = "HTTP/1.0 202 Accepted\r\n"; const std::string no_content = "HTTP/1.0 204 No Content\r\n"; const std::string multiple_choices = "HTTP/1.0 300 Multiple Choices\r\n"; const std::string moved_permanently = "HTTP/1.0 301 Moved Permanently\r\n"; const std::string moved_temporarily = "HTTP/1.0 302 Moved Temporarily\r\n"; const std::string not_modified = "HTTP/1.0 304 Not Modified\r\n"; const std::string bad_request = "HTTP/1.0 400 Bad Request\r\n"; const std::string unauthorized = "HTTP/1.0 401 Unauthorized\r\n"; const std::string forbidden = "HTTP/1.0 403 Forbidden\r\n"; const std::string not_found = "HTTP/1.0 404 Not Found\r\n"; const std::string internal_server_error = "HTTP/1.0 500 Internal Server Error\r\n"; const std::string not_implemented = "HTTP/1.0 501 Not Implemented\r\n"; const std::string bad_gateway = "HTTP/1.0 502 Bad Gateway\r\n"; const std::string service_unavailable = "HTTP/1.0 503 Service Unavailable\r\n"; asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return asio::buffer(ok); case reply::created: return asio::buffer(created); case reply::accepted: return asio::buffer(accepted); case reply::no_content: return asio::buffer(no_content); case reply::multiple_choices: return asio::buffer(multiple_choices); case reply::moved_permanently: return asio::buffer(moved_permanently); case reply::moved_temporarily: return asio::buffer(moved_temporarily); case reply::not_modified: return asio::buffer(not_modified); case reply::bad_request: return asio::buffer(bad_request); case reply::unauthorized: return asio::buffer(unauthorized); case reply::forbidden: return asio::buffer(forbidden); case reply::not_found: return asio::buffer(not_found); case reply::internal_server_error: return asio::buffer(internal_server_error); case reply::not_implemented: return asio::buffer(not_implemented); case reply::bad_gateway: return asio::buffer(bad_gateway); case reply::service_unavailable: return asio::buffer(service_unavailable); default: return asio::buffer(internal_server_error); } } } // namespace status_strings namespace misc_strings { const char name_value_separator[] = { ':', ' ' }; const char crlf[] = { '\r', '\n' }; } // namespace misc_strings std::vector<asio::const_buffer> reply::to_buffers() { std::vector<asio::const_buffer> buffers; buffers.push_back(status_strings::to_buffer(status)); for (std::size_t i = 0; i < headers.size(); ++i) { header& h = headers[i]; buffers.push_back(asio::buffer(h.name)); buffers.push_back(asio::buffer(misc_strings::name_value_separator)); buffers.push_back(asio::buffer(h.value)); buffers.push_back(asio::buffer(misc_strings::crlf)); } buffers.push_back(asio::buffer(misc_strings::crlf)); buffers.push_back(asio::buffer(content)); return buffers; } namespace stock_replies { const char ok[] = ""; const char created[] = "<html>" "<head><title>Created</title></head>" "<body><h1>201 Created</h1></body>" "</html>"; const char accepted[] = "<html>" "<head><title>Accepted</title></head>" "<body><h1>202 Accepted</h1></body>" "</html>"; const char no_content[] = "<html>" "<head><title>No Content</title></head>" "<body><h1>204 Content</h1></body>" "</html>"; const char multiple_choices[] = "<html>" "<head><title>Multiple Choices</title></head>" "<body><h1>300 Multiple Choices</h1></body>" "</html>"; const char moved_permanently[] = "<html>" "<head><title>Moved Permanently</title></head>" "<body><h1>301 Moved Permanently</h1></body>" "</html>"; const char moved_temporarily[] = "<html>" "<head><title>Moved Temporarily</title></head>" "<body><h1>302 Moved Temporarily</h1></body>" "</html>"; const char not_modified[] = "<html>" "<head><title>Not Modified</title></head>" "<body><h1>304 Not Modified</h1></body>" "</html>"; const char bad_request[] = "<html>" "<head><title>Bad Request</title></head>" "<body><h1>400 Bad Request</h1></body>" "</html>"; const char unauthorized[] = "<html>" "<head><title>Unauthorized</title></head>" "<body><h1>401 Unauthorized</h1></body>" "</html>"; const char forbidden[] = "<html>" "<head><title>Forbidden</title></head>" "<body><h1>403 Forbidden</h1></body>" "</html>"; const char not_found[] = "<html>" "<head><title>Not Found</title></head>" "<body><h1>404 Not Found</h1></body>" "</html>"; const char internal_server_error[] = "<html>" "<head><title>Internal Server Error</title></head>" "<body><h1>500 Internal Server Error</h1></body>" "</html>"; const char not_implemented[] = "<html>" "<head><title>Not Implemented</title></head>" "<body><h1>501 Not Implemented</h1></body>" "</html>"; const char bad_gateway[] = "<html>" "<head><title>Bad Gateway</title></head>" "<body><h1>502 Bad Gateway</h1></body>" "</html>"; const char service_unavailable[] = "<html>" "<head><title>Service Unavailable</title></head>" "<body><h1>503 Service Unavailable</h1></body>" "</html>"; std::string to_string(reply::status_type status) { switch (status) { case reply::ok: return ok; case reply::created: return created; case reply::accepted: return accepted; case reply::no_content: return no_content; case reply::multiple_choices: return multiple_choices; case reply::moved_permanently: return moved_permanently; case reply::moved_temporarily: return moved_temporarily; case reply::not_modified: return not_modified; case reply::bad_request: return bad_request; case reply::unauthorized: return unauthorized; case reply::forbidden: return forbidden; case reply::not_found: return not_found; case reply::internal_server_error: return internal_server_error; case reply::not_implemented: return not_implemented; case reply::bad_gateway: return bad_gateway; case reply::service_unavailable: return service_unavailable; default: return internal_server_error; } } } // namespace stock_replies reply reply::stock_reply(reply::status_type status) { reply rep; rep.status = status; rep.content = stock_replies::to_string(status); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = "text/html"; return rep; } } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/request_parser.hpp
// // request_parser.hpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_REQUEST_PARSER_HPP #define HTTP_SERVER4_REQUEST_PARSER_HPP #include <tuple> namespace http { namespace server4 { struct request; /// Parser for incoming requests. class request_parser { public: /// Construct ready to parse the request method. request_parser(); /// Reset to initial parser state. void reset(); /// Result of parse. enum result_type { good, bad, indeterminate }; /// Parse some data. The enum return value is good when a complete request has /// been parsed, bad if the data is invalid, indeterminate when more data is /// required. The InputIterator return value indicates how much of the input /// has been consumed. template <typename InputIterator> std::tuple<result_type, InputIterator> parse(request& req, InputIterator begin, InputIterator end) { while (begin != end) { result_type result = consume(req, *begin++); if (result == good || result == bad) return std::make_tuple(result, begin); } return std::make_tuple(indeterminate, begin); } private: /// Handle the next character of input. result_type consume(request& req, char input); /// Check if a byte is an HTTP character. static bool is_char(int c); /// Check if a byte is an HTTP control character. static bool is_ctl(int c); /// Check if a byte is defined as an HTTP tspecial character. static bool is_tspecial(int c); /// Check if a byte is a digit. static bool is_digit(int c); /// The current state of the parser. enum state { method_start, method, uri, http_version_h, http_version_t_1, http_version_t_2, http_version_p, http_version_slash, http_version_major_start, http_version_major, http_version_minor_start, http_version_minor, expecting_newline_1, header_line_start, header_lws, header_name, space_before_header_value, header_value, expecting_newline_2, expecting_newline_3 } state_; }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_REQUEST_PARSER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/file_handler.cpp
// // file_handler.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "file_handler.hpp" #include <fstream> #include <sstream> #include <string> #include "mime_types.hpp" #include "reply.hpp" #include "request.hpp" namespace http { namespace server4 { file_handler::file_handler(const std::string& doc_root) : doc_root_(doc_root) { } void file_handler::operator()(const request& req, reply& rep) { // Decode url to path. std::string request_path; if (!url_decode(req.uri, request_path)) { rep = reply::stock_reply(reply::bad_request); return; } // Request path must be absolute and not contain "..". if (request_path.empty() || request_path[0] != '/' || request_path.find("..") != std::string::npos) { rep = reply::stock_reply(reply::bad_request); return; } // If path ends in slash (i.e. is a directory) then add "index.html". if (request_path[request_path.size() - 1] == '/') { request_path += "index.html"; } // Determine the file extension. std::size_t last_slash_pos = request_path.find_last_of("/"); std::size_t last_dot_pos = request_path.find_last_of("."); std::string extension; if (last_dot_pos != std::string::npos && last_dot_pos > last_slash_pos) { extension = request_path.substr(last_dot_pos + 1); } // Open the file to send back. std::string full_path = doc_root_ + request_path; std::ifstream is(full_path.c_str(), std::ios::in | std::ios::binary); if (!is) { rep = reply::stock_reply(reply::not_found); return; } // Fill out the reply to be sent to the client. rep.status = reply::ok; char buf[512]; while (is.read(buf, sizeof(buf)).gcount() > 0) rep.content.append(buf, is.gcount()); rep.headers.resize(2); rep.headers[0].name = "Content-Length"; rep.headers[0].value = std::to_string(rep.content.size()); rep.headers[1].name = "Content-Type"; rep.headers[1].value = mime_types::extension_to_type(extension); } bool file_handler::url_decode(const std::string& in, std::string& out) { out.clear(); out.reserve(in.size()); for (std::size_t i = 0; i < in.size(); ++i) { if (in[i] == '%') { if (i + 3 <= in.size()) { int value = 0; std::istringstream is(in.substr(i + 1, 2)); if (is >> std::hex >> value) { out += static_cast<char>(value); i += 2; } else { return false; } } else { return false; } } else if (in[i] == '+') { out += ' '; } else { out += in[i]; } } return true; } } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/header.hpp
// // header.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_HEADER_HPP #define HTTP_SERVER4_HEADER_HPP #include <string> namespace http { namespace server4 { struct header { std::string name; std::string value; }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_HEADER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/request_handler.hpp
// // request_handler.hpp // ~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_REQUEST_HANDLER_HPP #define HTTP_SERVER4_REQUEST_HANDLER_HPP #include <string> namespace http { namespace server4 { struct reply; struct request; /// The common handler for all incoming requests. class request_handler { public: request_handler(const request_handler&) = delete; request_handler& operator=(const request_handler&) = delete; /// Construct with a directory containing files to be served. explicit request_handler(const std::string& doc_root); /// Handle a request and produce a reply. void handle_request(const request& req, reply& rep); private: /// The directory containing the files to be served. std::string doc_root_; /// Perform URL-decoding on a string. Returns false if the encoding was /// invalid. static bool url_decode(const std::string& in, std::string& out); }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_REQUEST_HANDLER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/reply.hpp
// // reply.hpp // ~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_REPLY_HPP #define HTTP_SERVER4_REPLY_HPP #include <string> #include <vector> #include <asio.hpp> #include "header.hpp" namespace http { namespace server4 { /// A reply to be sent to a client. struct reply { /// The status of the reply. enum status_type { ok = 200, created = 201, accepted = 202, no_content = 204, multiple_choices = 300, moved_permanently = 301, moved_temporarily = 302, not_modified = 304, bad_request = 400, unauthorized = 401, forbidden = 403, not_found = 404, internal_server_error = 500, not_implemented = 501, bad_gateway = 502, service_unavailable = 503 } status; /// The headers to be included in the reply. std::vector<header> headers; /// The content to be sent in the reply. std::string content; /// Convert the reply into a vector of buffers. The buffers do not own the /// underlying memory blocks, therefore the reply object must remain valid and /// not be changed until the write operation has completed. std::vector<asio::const_buffer> to_buffers(); /// Get a stock reply. static reply stock_reply(status_type status); }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_REPLY_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/main.cpp
// // main.cpp // ~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <iostream> #include <asio.hpp> #include <signal.h> #include "server.hpp" #include "file_handler.hpp" int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 4) { std::cerr << "Usage: http_server <address> <port> <doc_root>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 80 .\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 80 .\n"; return 1; } asio::io_context io_context; // Launch the initial server coroutine. http::server4::server(io_context, argv[1], argv[2], http::server4::file_handler(argv[3]))(); // Wait for signals indicating time to shut down. asio::signal_set signals(io_context); signals.add(SIGINT); signals.add(SIGTERM); #if defined(SIGQUIT) signals.add(SIGQUIT); #endif // defined(SIGQUIT) signals.async_wait( [&io_context](std::error_code, int) { io_context.stop(); }); // Run the server. io_context.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/server.hpp
// // server.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef HTTP_SERVER4_SERVER_HPP #define HTTP_SERVER4_SERVER_HPP #include <asio.hpp> #include <array> #include <functional> #include <memory> #include <string> #include "request_parser.hpp" namespace http { namespace server4 { struct request; struct reply; /// The top-level coroutine of the HTTP server. class server : asio::coroutine { public: /// Construct the server to listen on the specified TCP address and port, and /// serve up files from the given directory. explicit server(asio::io_context& io_context, const std::string& address, const std::string& port, std::function<void(const request&, reply&)> request_handler); /// Perform work associated with the server. void operator()( std::error_code ec = std::error_code(), std::size_t length = 0); private: typedef asio::ip::tcp tcp; /// The user-supplied handler for all incoming requests. std::function<void(const request&, reply&)> request_handler_; /// Acceptor used to listen for incoming connections. std::shared_ptr<tcp::acceptor> acceptor_; /// The current connection from a client. std::shared_ptr<tcp::socket> socket_; /// Buffer for incoming data. std::shared_ptr<std::array<char, 8192>> buffer_; /// The incoming request. std::shared_ptr<request> request_; /// Whether the request is valid or not. request_parser::result_type parse_result_; /// The parser for the incoming request. request_parser request_parser_; /// The reply to be sent back to the client. std::shared_ptr<reply> reply_; }; } // namespace server4 } // namespace http #endif // HTTP_SERVER4_SERVER_HPP
0
repos/asio/asio/src/examples/cpp11/http
repos/asio/asio/src/examples/cpp11/http/server4/request_parser.cpp
// // request_parser.cpp // ~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include "request_parser.hpp" #include "request.hpp" namespace http { namespace server4 { request_parser::request_parser() : state_(method_start) { } void request_parser::reset() { state_ = method_start; } request_parser::result_type request_parser::consume(request& req, char input) { switch (state_) { case method_start: if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { state_ = method; req.method.push_back(input); return indeterminate; } case method: if (input == ' ') { state_ = uri; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.method.push_back(input); return indeterminate; } case uri: if (input == ' ') { state_ = http_version_h; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.uri.push_back(input); return indeterminate; } case http_version_h: if (input == 'H') { state_ = http_version_t_1; return indeterminate; } else { return bad; } case http_version_t_1: if (input == 'T') { state_ = http_version_t_2; return indeterminate; } else { return bad; } case http_version_t_2: if (input == 'T') { state_ = http_version_p; return indeterminate; } else { return bad; } case http_version_p: if (input == 'P') { state_ = http_version_slash; return indeterminate; } else { return bad; } case http_version_slash: if (input == '/') { req.http_version_major = 0; req.http_version_minor = 0; state_ = http_version_major_start; return indeterminate; } else { return bad; } case http_version_major_start: if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; state_ = http_version_major; return indeterminate; } else { return bad; } case http_version_major: if (input == '.') { state_ = http_version_minor_start; return indeterminate; } else if (is_digit(input)) { req.http_version_major = req.http_version_major * 10 + input - '0'; return indeterminate; } else { return bad; } case http_version_minor_start: if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; state_ = http_version_minor; return indeterminate; } else { return bad; } case http_version_minor: if (input == '\r') { state_ = expecting_newline_1; return indeterminate; } else if (is_digit(input)) { req.http_version_minor = req.http_version_minor * 10 + input - '0'; return indeterminate; } else { return bad; } case expecting_newline_1: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case header_line_start: if (input == '\r') { state_ = expecting_newline_3; return indeterminate; } else if (!req.headers.empty() && (input == ' ' || input == '\t')) { state_ = header_lws; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.push_back(header()); req.headers.back().name.push_back(input); state_ = header_name; return indeterminate; } case header_lws: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (input == ' ' || input == '\t') { return indeterminate; } else if (is_ctl(input)) { return bad; } else { state_ = header_value; req.headers.back().value.push_back(input); return indeterminate; } case header_name: if (input == ':') { state_ = space_before_header_value; return indeterminate; } else if (!is_char(input) || is_ctl(input) || is_tspecial(input)) { return bad; } else { req.headers.back().name.push_back(input); return indeterminate; } case space_before_header_value: if (input == ' ') { state_ = header_value; return indeterminate; } else { return bad; } case header_value: if (input == '\r') { state_ = expecting_newline_2; return indeterminate; } else if (is_ctl(input)) { return bad; } else { req.headers.back().value.push_back(input); return indeterminate; } case expecting_newline_2: if (input == '\n') { state_ = header_line_start; return indeterminate; } else { return bad; } case expecting_newline_3: return (input == '\n') ? good : bad; default: return bad; } } bool request_parser::is_char(int c) { return c >= 0 && c <= 127; } bool request_parser::is_ctl(int c) { return (c >= 0 && c <= 31) || (c == 127); } bool request_parser::is_tspecial(int c) { switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; default: return false; } } bool request_parser::is_digit(int c) { return c >= '0' && c <= '9'; } } // namespace server4 } // namespace http
0
repos/asio/asio/src/examples/cpp11
repos/asio/asio/src/examples/cpp11/multicast/receiver.cpp
// // receiver.cpp // ~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #include <array> #include <iostream> #include <string> #include "asio.hpp" constexpr short multicast_port = 30001; class receiver { public: receiver(asio::io_context& io_context, const asio::ip::address& listen_address, const asio::ip::address& multicast_address) : socket_(io_context) { // Create the socket so that multiple may be bound to the same address. asio::ip::udp::endpoint listen_endpoint( listen_address, multicast_port); socket_.open(listen_endpoint.protocol()); socket_.set_option(asio::ip::udp::socket::reuse_address(true)); socket_.bind(listen_endpoint); // Join the multicast group. socket_.set_option( asio::ip::multicast::join_group(multicast_address)); do_receive(); } private: void do_receive() { socket_.async_receive_from( asio::buffer(data_), sender_endpoint_, [this](std::error_code ec, std::size_t length) { if (!ec) { std::cout.write(data_.data(), length); std::cout << std::endl; do_receive(); } }); } asio::ip::udp::socket socket_; asio::ip::udp::endpoint sender_endpoint_; std::array<char, 1024> data_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: receiver <listen_address> <multicast_address>\n"; std::cerr << " For IPv4, try:\n"; std::cerr << " receiver 0.0.0.0 239.255.0.1\n"; std::cerr << " For IPv6, try:\n"; std::cerr << " receiver 0::0 ff31::8000:1234\n"; return 1; } asio::io_context io_context; receiver r(io_context, asio::ip::make_address(argv[1]), asio::ip::make_address(argv[2])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }