repo_name
stringclasses
10 values
file_path
stringlengths
29
222
content
stringlengths
24
926k
extention
stringclasses
5 values
asio
data/projects/asio/example/cpp11/type_erasure/sleep.cpp
// // sleep.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 "sleep.hpp" #include <boost/asio/consign.hpp> #include <boost/asio/steady_timer.hpp> #include <memory> void async_sleep_impl( boost::asio::any_completion_handler<void(boost::system::error_code)> handler, boost::asio::any_io_executor ex, std::chrono::nanoseconds duration) { auto timer = std::make_shared<boost::asio::steady_timer>(ex, duration); timer->async_wait(boost::asio::consign(std::move(handler), timer)); }
cpp
asio
data/projects/asio/example/cpp11/type_erasure/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 "line_reader.hpp" #include "sleep.hpp" #include "stdin_line_reader.hpp" #include <boost/asio/coroutine.hpp> #include <boost/asio/detached.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/use_awaitable.hpp> #include <iostream> #include <boost/asio/yield.hpp> class read_loop : boost::asio::coroutine { public: read_loop(boost::asio::any_io_executor e, line_reader& r) : executor(std::move(e)), reader(r) { } void operator()(boost::system::error_code ec = {}, std::string line = {}) { reenter (this) { for (i = 0; i < 10; ++i) { yield reader.async_read_line("Enter something: ", *this); if (ec) break; std::cout << line; yield async_sleep(executor, std::chrono::seconds(1), *this); if (ec) break; } } } private: boost::asio::any_io_executor executor; line_reader& reader; int i; }; #include <boost/asio/unyield.hpp> int main() { boost::asio::io_context ctx{1}; stdin_line_reader reader{ctx.get_executor()}; read_loop(ctx.get_executor(), reader)(); ctx.run(); }
cpp
asio
data/projects/asio/example/cpp11/type_erasure/stdin_line_reader.hpp
// // stdin_line_reader.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 STDIN_LINE_READER_HPP #define STDIN_LINE_READER_HPP #include "line_reader.hpp" #include <boost/asio/posix/stream_descriptor.hpp> class stdin_line_reader : public line_reader { public: explicit stdin_line_reader(boost::asio::any_io_executor ex); private: void async_read_line_impl(std::string prompt, boost::asio::any_completion_handler<void(boost::system::error_code, std::string)> handler) override; boost::asio::posix::stream_descriptor stdin_; std::string buffer_; }; #endif
hpp
asio
data/projects/asio/example/cpp11/type_erasure/sleep.hpp
// // sleep.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 SLEEP_HPP #define SLEEP_HPP #include <boost/asio/any_completion_handler.hpp> #include <boost/asio/any_io_executor.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/error.hpp> #include <chrono> void async_sleep_impl( boost::asio::any_completion_handler<void(boost::system::error_code)> handler, boost::asio::any_io_executor ex, std::chrono::nanoseconds duration); template <typename CompletionToken> inline auto async_sleep(boost::asio::any_io_executor ex, std::chrono::nanoseconds duration, CompletionToken&& token) -> decltype( boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>( async_sleep_impl, token, std::move(ex), duration)) { return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code)>( async_sleep_impl, token, std::move(ex), duration); } #endif // SLEEP_HPP
hpp
asio
data/projects/asio/example/cpp11/type_erasure/line_reader.hpp
// // line_reader.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 LINE_READER_HPP #define LINE_READER_HPP #include <boost/asio/any_completion_handler.hpp> #include <boost/asio/async_result.hpp> #include <boost/asio/error.hpp> #include <string> class line_reader { private: virtual void async_read_line_impl(std::string prompt, boost::asio::any_completion_handler<void(boost::system::error_code, std::string)> handler) = 0; struct initiate_read_line { template <typename Handler> void operator()(Handler handler, line_reader* self, std::string prompt) { self->async_read_line_impl(std::move(prompt), std::move(handler)); } }; public: virtual ~line_reader() {} template <typename CompletionToken> auto async_read_line(std::string prompt, CompletionToken&& token) -> decltype( boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::string)>( initiate_read_line(), token, this, prompt)) { return boost::asio::async_initiate<CompletionToken, void(boost::system::error_code, std::string)>( initiate_read_line(), token, this, prompt); } }; #endif // LINE_READER_HPP
hpp
asio
data/projects/asio/example/cpp11/type_erasure/stdin_line_reader.cpp
// // stdin_line_reader.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 "stdin_line_reader.hpp" #include <boost/asio/deferred.hpp> #include <boost/asio/read_until.hpp> #include <iostream> stdin_line_reader::stdin_line_reader(boost::asio::any_io_executor ex) : stdin_(ex, ::dup(STDIN_FILENO)) { } void stdin_line_reader::async_read_line_impl(std::string prompt, boost::asio::any_completion_handler<void(boost::system::error_code, std::string)> handler) { std::cout << prompt; std::cout.flush(); boost::asio::async_read_until(stdin_, boost::asio::dynamic_buffer(buffer_), '\n', boost::asio::deferred( [this](boost::system::error_code ec, std::size_t n) { if (!ec) { std::string result = buffer_.substr(0, n); buffer_.erase(0, n); return boost::asio::deferred.values(ec, std::move(result)); } else { return boost::asio::deferred.values(ec, std::string{}); } } ) )(std::move(handler)); }
cpp
asio
data/projects/asio/example/cpp11/timeouts/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 <algorithm> #include <cstdlib> #include <deque> #include <iostream> #include <memory> #include <set> #include <string> #include <boost/asio/buffer.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/write.hpp> using boost::asio::steady_timer; using boost::asio::ip::tcp; using boost::asio::ip::udp; //---------------------------------------------------------------------- class subscriber { public: virtual ~subscriber() = default; virtual void deliver(const std::string& msg) = 0; }; typedef std::shared_ptr<subscriber> subscriber_ptr; //---------------------------------------------------------------------- class channel { public: void join(subscriber_ptr subscriber) { subscribers_.insert(subscriber); } void leave(subscriber_ptr subscriber) { subscribers_.erase(subscriber); } void deliver(const std::string& msg) { for (const auto& s : subscribers_) { s->deliver(msg); } } private: std::set<subscriber_ptr> subscribers_; }; //---------------------------------------------------------------------- // // This class manages socket timeouts by applying the concept of a deadline. // Some asynchronous operations are given deadlines by which they must complete. // Deadlines are enforced by two "actors" that persist for the lifetime of the // session object, one for input and one for output: // // +----------------+ +----------------+ // | | | | // | check_deadline |<-------+ | check_deadline |<-------+ // | | | | | | // +----------------+ | +----------------+ | // | | | | // async_wait() | +----------------+ async_wait() | +----------------+ // on input | | lambda | on output | | lambda | // deadline +--->| in | deadline +--->| in | // | check_deadline | | check_deadline | // +----------------+ +----------------+ // // If either deadline actor determines that the corresponding deadline has // expired, the socket is closed and any outstanding operations are cancelled. // // The input actor reads messages from the socket, where messages are delimited // by the newline character: // // +-------------+ // | | // | read_line |<----+ // | | | // +-------------+ | // | | // async_- | +-------------+ // read_- | | lambda | // until() +--->| in | // | read_line | // +-------------+ // // The deadline for receiving a complete message is 30 seconds. If a non-empty // message is received, it is delivered to all subscribers. If a heartbeat (a // message that consists of a single newline character) is received, a heartbeat // is enqueued for the client, provided there are no other messages waiting to // be sent. // // The output actor is responsible for sending messages to the client: // // +----------------+ // | |<---------------------+ // | await_output | | // | |<-------+ | // +----------------+ | | // | | | | // | async_- | +----------------+ | // | wait() | | lambda | | // | +->| in | | // | | await_output | | // | +----------------+ | // V | // +--------------+ +--------------+ // | | async_write() | lambda | // | write_line |-------------->| in | // | | | write_line | // +--------------+ +--------------+ // // The output actor first waits for an output message to be enqueued. It does // this by using a steady_timer as an asynchronous condition variable. The // steady_timer will be signalled whenever the output queue is non-empty. // // Once a message is available, it is sent to the client. The deadline for // sending a complete message is 30 seconds. After the message is successfully // sent, the output actor again waits for the output queue to become non-empty. // class tcp_session : public subscriber, public std::enable_shared_from_this<tcp_session> { public: tcp_session(tcp::socket socket, channel& ch) : channel_(ch), socket_(std::move(socket)) { input_deadline_.expires_at(steady_timer::time_point::max()); output_deadline_.expires_at(steady_timer::time_point::max()); // The non_empty_output_queue_ steady_timer is set to the maximum time // point whenever the output queue is empty. This ensures that the output // actor stays asleep until a message is put into the queue. non_empty_output_queue_.expires_at(steady_timer::time_point::max()); } // Called by the server object to initiate the four actors. void start() { channel_.join(shared_from_this()); read_line(); check_deadline(input_deadline_); await_output(); check_deadline(output_deadline_); } private: void stop() { channel_.leave(shared_from_this()); boost::system::error_code ignored_error; socket_.close(ignored_error); input_deadline_.cancel(); non_empty_output_queue_.cancel(); output_deadline_.cancel(); } bool stopped() const { return !socket_.is_open(); } void deliver(const std::string& msg) override { output_queue_.push_back(msg + "\n"); // Signal that the output queue contains messages. Modifying the expiry // will wake the output actor, if it is waiting on the timer. non_empty_output_queue_.expires_at(steady_timer::time_point::min()); } void read_line() { // Set a deadline for the read operation. input_deadline_.expires_after(std::chrono::seconds(30)); // Start an asynchronous operation to read a newline-delimited message. auto self(shared_from_this()); boost::asio::async_read_until(socket_, boost::asio::dynamic_buffer(input_buffer_), '\n', [this, self](const boost::system::error_code& error, std::size_t n) { // Check if the session was stopped while the operation was pending. if (stopped()) return; if (!error) { // Extract the newline-delimited message from the buffer. std::string msg(input_buffer_.substr(0, n - 1)); input_buffer_.erase(0, n); if (!msg.empty()) { channel_.deliver(msg); } else { // We received a heartbeat message from the client. If there's // nothing else being sent or ready to be sent, send a heartbeat // right back. if (output_queue_.empty()) { output_queue_.push_back("\n"); // Signal that the output queue contains messages. Modifying // the expiry will wake the output actor, if it is waiting on // the timer. non_empty_output_queue_.expires_at( steady_timer::time_point::min()); } } read_line(); } else { stop(); } }); } void await_output() { auto self(shared_from_this()); non_empty_output_queue_.async_wait( [this, self](const boost::system::error_code& /*error*/) { // Check if the session was stopped while the operation was pending. if (stopped()) return; if (output_queue_.empty()) { // There are no messages that are ready to be sent. The actor goes // to sleep by waiting on the non_empty_output_queue_ timer. When a // new message is added, the timer will be modified and the actor // will wake. non_empty_output_queue_.expires_at(steady_timer::time_point::max()); await_output(); } else { write_line(); } }); } void write_line() { // Set a deadline for the write operation. output_deadline_.expires_after(std::chrono::seconds(30)); // Start an asynchronous operation to send a message. auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(output_queue_.front()), [this, self](const boost::system::error_code& error, std::size_t /*n*/) { // Check if the session was stopped while the operation was pending. if (stopped()) return; if (!error) { output_queue_.pop_front(); await_output(); } else { stop(); } }); } void check_deadline(steady_timer& deadline) { auto self(shared_from_this()); deadline.async_wait( [this, self, &deadline](const boost::system::error_code& /*error*/) { // Check if the session was stopped while the operation was pending. if (stopped()) return; // Check whether the deadline has passed. We compare the deadline // against the current time since a new asynchronous operation may // have moved the deadline before this actor had a chance to run. if (deadline.expiry() <= steady_timer::clock_type::now()) { // The deadline has passed. Stop the session. The other actors will // terminate as soon as possible. stop(); } else { // Put the actor back to sleep. check_deadline(deadline); } }); } channel& channel_; tcp::socket socket_; std::string input_buffer_; steady_timer input_deadline_{socket_.get_executor()}; std::deque<std::string> output_queue_; steady_timer non_empty_output_queue_{socket_.get_executor()}; steady_timer output_deadline_{socket_.get_executor()}; }; typedef std::shared_ptr<tcp_session> tcp_session_ptr; //---------------------------------------------------------------------- class udp_broadcaster : public subscriber { public: udp_broadcaster(boost::asio::io_context& io_context, const udp::endpoint& broadcast_endpoint) : socket_(io_context) { socket_.connect(broadcast_endpoint); socket_.set_option(udp::socket::broadcast(true)); } private: void deliver(const std::string& msg) { boost::system::error_code ignored_error; socket_.send(boost::asio::buffer(msg), 0, ignored_error); } udp::socket socket_; }; //---------------------------------------------------------------------- class server { public: server(boost::asio::io_context& io_context, const tcp::endpoint& listen_endpoint, const udp::endpoint& broadcast_endpoint) : io_context_(io_context), acceptor_(io_context, listen_endpoint) { channel_.join( std::make_shared<udp_broadcaster>( io_context_, broadcast_endpoint)); accept(); } private: void accept() { acceptor_.async_accept( [this](const boost::system::error_code& error, tcp::socket socket) { if (!error) { std::make_shared<tcp_session>(std::move(socket), channel_)->start(); } accept(); }); } boost::asio::io_context& io_context_; tcp::acceptor acceptor_; channel channel_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { using namespace std; // For atoi. if (argc != 4) { std::cerr << "Usage: server <listen_port> <bcast_address> <bcast_port>\n"; return 1; } boost::asio::io_context io_context; tcp::endpoint listen_endpoint(tcp::v4(), atoi(argv[1])); udp::endpoint broadcast_endpoint( boost::asio::ip::make_address(argv[2]), atoi(argv[3])); server s(io_context, listen_endpoint, broadcast_endpoint); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/timeouts/blocking_tcp_client.cpp
// // blocking_tcp_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 <boost/asio/buffer.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/read_until.hpp> #include <boost/system/system_error.hpp> #include <boost/asio/write.hpp> #include <cstdlib> #include <iostream> #include <string> using boost::asio::ip::tcp; //---------------------------------------------------------------------- // // This class manages socket timeouts by running the io_context using the timed // io_context::run_for() member function. Each asynchronous operation is given // a timeout within which it must complete. The socket operations themselves // use lambdas as completion handlers. For a given socket operation, the client // object runs the io_context to block thread execution until the operation // completes or the timeout is reached. If the io_context::run_for() function // times out, the socket is closed and the outstanding asynchronous operation // is cancelled. // class client { public: void connect(const std::string& host, const std::string& service, std::chrono::steady_clock::duration timeout) { // Resolve the host name and service to a list of endpoints. auto endpoints = tcp::resolver(io_context_).resolve(host, service); // Start the asynchronous operation itself. The lambda that is used as a // callback will update the error variable when the operation completes. // The blocking_udp_client.cpp example shows how you can use std::bind // rather than a lambda. boost::system::error_code error; boost::asio::async_connect(socket_, endpoints, [&](const boost::system::error_code& result_error, const tcp::endpoint& /*result_endpoint*/) { error = result_error; }); // Run the operation until it completes, or until the timeout. run(timeout); // Determine whether a connection was successfully established. if (error) throw boost::system::system_error(error); } std::string read_line(std::chrono::steady_clock::duration timeout) { // Start the asynchronous operation. The lambda that is used as a callback // will update the error and n variables when the operation completes. The // blocking_udp_client.cpp example shows how you can use std::bind rather // than a lambda. boost::system::error_code error; std::size_t n = 0; boost::asio::async_read_until(socket_, boost::asio::dynamic_buffer(input_buffer_), '\n', [&](const boost::system::error_code& result_error, std::size_t result_n) { error = result_error; n = result_n; }); // Run the operation until it completes, or until the timeout. run(timeout); // Determine whether the read completed successfully. if (error) throw boost::system::system_error(error); std::string line(input_buffer_.substr(0, n - 1)); input_buffer_.erase(0, n); return line; } void write_line(const std::string& line, std::chrono::steady_clock::duration timeout) { std::string data = line + "\n"; // Start the asynchronous operation itself. The lambda that is used as a // callback will update the error variable when the operation completes. // The blocking_udp_client.cpp example shows how you can use std::bind // rather than a lambda. boost::system::error_code error; boost::asio::async_write(socket_, boost::asio::buffer(data), [&](const boost::system::error_code& result_error, std::size_t /*result_n*/) { error = result_error; }); // Run the operation until it completes, or until the timeout. run(timeout); // Determine whether the read completed successfully. if (error) throw boost::system::system_error(error); } private: void run(std::chrono::steady_clock::duration timeout) { // Restart the io_context, as it may have been left in the "stopped" state // by a previous operation. io_context_.restart(); // Block until the asynchronous operation has completed, or timed out. If // the pending asynchronous operation is a composed operation, the deadline // applies to the entire operation, rather than individual operations on // the socket. io_context_.run_for(timeout); // If the asynchronous operation completed successfully then the io_context // would have been stopped due to running out of work. If it was not // stopped, then the io_context::run_for call must have timed out. if (!io_context_.stopped()) { // Close the socket to cancel the outstanding asynchronous operation. socket_.close(); // Run the io_context again until the operation completes. io_context_.run(); } } boost::asio::io_context io_context_; tcp::socket socket_{io_context_}; std::string input_buffer_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc != 4) { std::cerr << "Usage: blocking_tcp_client <host> <port> <message>\n"; return 1; } client c; c.connect(argv[1], argv[2], std::chrono::seconds(10)); auto time_sent = std::chrono::steady_clock::now(); c.write_line(argv[3], std::chrono::seconds(10)); for (;;) { std::string line = c.read_line(std::chrono::seconds(10)); // Keep going until we get back the line that was sent. if (line == argv[3]) break; } auto time_received = std::chrono::steady_clock::now(); std::cout << "Round trip time: "; std::cout << std::chrono::duration_cast< std::chrono::microseconds>( time_received - time_sent).count(); std::cout << " microseconds\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/timeouts/blocking_token_tcp_client.cpp
// // blocking_token_tcp_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 <boost/asio/connect.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/streambuf.hpp> #include <boost/system/system_error.hpp> #include <boost/asio/write.hpp> #include <cstdlib> #include <iostream> #include <memory> #include <string> using boost::asio::ip::tcp; // NOTE: This example uses the new form of the boost::asio::async_result trait. // For an example that works with the Networking TS style of completion tokens, // please see an older version of asio. // We will use our sockets only with an io_context. using tcp_socket = boost::asio::basic_stream_socket< tcp, boost::asio::io_context::executor_type>; //---------------------------------------------------------------------- // A custom completion token that makes asynchronous operations behave as // though they are blocking calls with a timeout. struct close_after { close_after(std::chrono::steady_clock::duration t, tcp_socket& s) : timeout_(t), socket_(s) { } // The maximum time to wait for an asynchronous operation to complete. std::chrono::steady_clock::duration timeout_; // The socket to be closed if the operation does not complete in time. tcp_socket& socket_; }; namespace boost { namespace asio { // The async_result template is specialised to allow the close_after token to // be used with asynchronous operations that have a completion signature of // void(error_code, T). Generalising this for all completion signature forms is // left as an exercise for the reader. template <typename T> class async_result<close_after, void(boost::system::error_code, T)> { public: // The initiate() function is used to launch the asynchronous operation by // calling the operation's initiation function object. For the close_after // completion token, we use this function to run the io_context until the // operation is complete. template <typename Init, typename... Args> static T initiate(Init init, close_after token, Args&&... args) { boost::asio::io_context& io_context = boost::asio::query( token.socket_.get_executor(), boost::asio::execution::context); // Call the operation's initiation function object to start the operation. // A lambda is supplied as the completion handler, to be called when the // operation completes. boost::system::error_code error; T result; init([&](boost::system::error_code e, T t) { error = e; result = t; }, std::forward<Args>(args)...); // Restart the io_context, as it may have been left in the "stopped" state // by a previous operation. io_context.restart(); // Block until the asynchronous operation has completed, or timed out. If // the pending asynchronous operation is a composed operation, the deadline // applies to the entire operation, rather than individual operations on // the socket. io_context.run_for(token.timeout_); // If the asynchronous operation completed successfully then the io_context // would have been stopped due to running out of work. If it was not // stopped, then the io_context::run_for call must have timed out and the // operation is still incomplete. if (!io_context.stopped()) { // Close the socket to cancel the outstanding asynchronous operation. token.socket_.close(); // Run the io_context again until the operation completes. io_context.run(); } // If the operation failed, throw an exception. Otherwise return the result. return error ? throw boost::system::system_error(error) : result; } }; } // namespace asio } // namespace boost //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { if (argc != 4) { std::cerr << "Usage: blocking_tcp_client <host> <port> <message>\n"; return 1; } boost::asio::io_context io_context; // Resolve the host name and service to a list of endpoints. auto endpoints = tcp::resolver(io_context).resolve(argv[1], argv[2]); tcp_socket socket(io_context); // Run an asynchronous connect operation with a timeout. boost::asio::async_connect(socket, endpoints, close_after(std::chrono::seconds(10), socket)); auto time_sent = std::chrono::steady_clock::now(); // Run an asynchronous write operation with a timeout. std::string msg = argv[3] + std::string("\n"); boost::asio::async_write(socket, boost::asio::buffer(msg), close_after(std::chrono::seconds(10), socket)); for (std::string input_buffer;;) { // Run an asynchronous read operation with a timeout. std::size_t n = boost::asio::async_read_until(socket, boost::asio::dynamic_buffer(input_buffer), '\n', close_after(std::chrono::seconds(10), socket)); std::string line(input_buffer.substr(0, n - 1)); input_buffer.erase(0, n); // Keep going until we get back the line that was sent. if (line == argv[3]) break; } auto time_received = std::chrono::steady_clock::now(); std::cout << "Round trip time: "; std::cout << std::chrono::duration_cast< std::chrono::microseconds>( time_received - time_sent).count(); std::cout << " microseconds\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/timeouts/async_tcp_client.cpp
// // async_tcp_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 <boost/asio/buffer.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/read_until.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/write.hpp> #include <functional> #include <iostream> #include <string> using boost::asio::steady_timer; using boost::asio::ip::tcp; using std::placeholders::_1; using std::placeholders::_2; // // This class manages socket timeouts by applying the concept of a deadline. // Some asynchronous operations are given deadlines by which they must complete. // Deadlines are enforced by an "actor" that persists for the lifetime of the // client object: // // +----------------+ // | | // | check_deadline |<---+ // | | | // +----------------+ | async_wait() // | | // +---------+ // // If the deadline actor determines that the deadline has expired, the socket // is closed and any outstanding operations are consequently cancelled. // // Connection establishment involves trying each endpoint in turn until a // connection is successful, or the available endpoints are exhausted. If the // deadline actor closes the socket, the connect actor is woken up and moves to // the next endpoint. // // +---------------+ // | | // | start_connect |<---+ // | | | // +---------------+ | // | | // async_- | +----------------+ // connect() | | | // +--->| handle_connect | // | | // +----------------+ // : // Once a connection is : // made, the connect : // actor forks in two - : // : // an actor for reading : and an actor for // inbound messages: : sending heartbeats: // : // +------------+ : +-------------+ // | |<- - - - -+- - - - ->| | // | start_read | | start_write |<---+ // | |<---+ | | | // +------------+ | +-------------+ | async_wait() // | | | | // async_- | +-------------+ async_- | +--------------+ // read_- | | | write() | | | // until() +--->| handle_read | +--->| handle_write | // | | | | // +-------------+ +--------------+ // // The input actor reads messages from the socket, where messages are delimited // by the newline character. The deadline for a complete message is 30 seconds. // // The heartbeat actor sends a heartbeat (a message that consists of a single // newline character) every 10 seconds. In this example, no deadline is applied // to message sending. // class client { public: client(boost::asio::io_context& io_context) : socket_(io_context), deadline_(io_context), heartbeat_timer_(io_context) { } // Called by the user of the client class to initiate the connection process. // The endpoints will have been obtained using a tcp::resolver. void start(tcp::resolver::results_type endpoints) { // Start the connect actor. endpoints_ = endpoints; start_connect(endpoints_.begin()); // Start the deadline actor. You will note that we're not setting any // particular deadline here. Instead, the connect and input actors will // update the deadline prior to each asynchronous operation. deadline_.async_wait(std::bind(&client::check_deadline, this)); } // This function terminates all the actors to shut down the connection. It // may be called by the user of the client class, or by the class itself in // response to graceful termination or an unrecoverable error. void stop() { stopped_ = true; boost::system::error_code ignored_error; socket_.close(ignored_error); deadline_.cancel(); heartbeat_timer_.cancel(); } private: void start_connect(tcp::resolver::results_type::iterator endpoint_iter) { if (endpoint_iter != endpoints_.end()) { std::cout << "Trying " << endpoint_iter->endpoint() << "...\n"; // Set a deadline for the connect operation. deadline_.expires_after(std::chrono::seconds(60)); // Start the asynchronous connect operation. socket_.async_connect(endpoint_iter->endpoint(), std::bind(&client::handle_connect, this, _1, endpoint_iter)); } else { // There are no more endpoints to try. Shut down the client. stop(); } } void handle_connect(const boost::system::error_code& error, tcp::resolver::results_type::iterator endpoint_iter) { if (stopped_) return; // The async_connect() function automatically opens the socket at the start // of the asynchronous operation. If the socket is closed at this time then // the timeout handler must have run first. if (!socket_.is_open()) { std::cout << "Connect timed out\n"; // Try the next available endpoint. start_connect(++endpoint_iter); } // Check if the connect operation failed before the deadline expired. else if (error) { std::cout << "Connect error: " << error.message() << "\n"; // We need to close the socket used in the previous connection attempt // before starting a new one. socket_.close(); // Try the next available endpoint. start_connect(++endpoint_iter); } // Otherwise we have successfully established a connection. else { std::cout << "Connected to " << endpoint_iter->endpoint() << "\n"; // Start the input actor. start_read(); // Start the heartbeat actor. start_write(); } } void start_read() { // Set a deadline for the read operation. deadline_.expires_after(std::chrono::seconds(30)); // Start an asynchronous operation to read a newline-delimited message. boost::asio::async_read_until(socket_, boost::asio::dynamic_buffer(input_buffer_), '\n', std::bind(&client::handle_read, this, _1, _2)); } void handle_read(const boost::system::error_code& error, std::size_t n) { if (stopped_) return; if (!error) { // Extract the newline-delimited message from the buffer. std::string line(input_buffer_.substr(0, n - 1)); input_buffer_.erase(0, n); // Empty messages are heartbeats and so ignored. if (!line.empty()) { std::cout << "Received: " << line << "\n"; } start_read(); } else { std::cout << "Error on receive: " << error.message() << "\n"; stop(); } } void start_write() { if (stopped_) return; // Start an asynchronous operation to send a heartbeat message. boost::asio::async_write(socket_, boost::asio::buffer("\n", 1), std::bind(&client::handle_write, this, _1)); } void handle_write(const boost::system::error_code& error) { if (stopped_) return; if (!error) { // Wait 10 seconds before sending the next heartbeat. heartbeat_timer_.expires_after(std::chrono::seconds(10)); heartbeat_timer_.async_wait(std::bind(&client::start_write, this)); } else { std::cout << "Error on heartbeat: " << error.message() << "\n"; stop(); } } void check_deadline() { if (stopped_) return; // Check whether the deadline has passed. We compare the deadline against // the current time since a new asynchronous operation may have moved the // deadline before this actor had a chance to run. if (deadline_.expiry() <= steady_timer::clock_type::now()) { // The deadline has passed. The socket is closed so that any outstanding // asynchronous operations are cancelled. socket_.close(); // There is no longer an active deadline. The expiry is set to the // maximum time point so that the actor takes no action until a new // deadline is set. deadline_.expires_at(steady_timer::time_point::max()); } // Put the actor back to sleep. deadline_.async_wait(std::bind(&client::check_deadline, this)); } private: bool stopped_ = false; tcp::resolver::results_type endpoints_; tcp::socket socket_; std::string input_buffer_; steady_timer deadline_; steady_timer heartbeat_timer_; }; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: client <host> <port>\n"; return 1; } boost::asio::io_context io_context; tcp::resolver r(io_context); client c(io_context); c.start(r.resolve(argv[1], argv[2])); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/timeouts/blocking_udp_client.cpp
// // blocking_udp_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 <boost/asio/buffer.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/ip/udp.hpp> #include <cstdlib> #include <functional> #include <iostream> using boost::asio::ip::udp; using std::placeholders::_1; using std::placeholders::_2; //---------------------------------------------------------------------- // // This class manages socket timeouts by running the io_context using the timed // io_context::run_for() member function. Each asynchronous operation is given // a timeout within which it must complete. The socket operations themselves // use std::bind to specify the completion handler: // // +---------------+ // | | // | receive | // | | // +---------------+ // | // async_- | +----------------+ // receive() | | | // +--->| handle_receive | // | | // +----------------+ // // For a given socket operation, the client object runs the io_context to block // thread execution until the operation completes or the timeout is reached. If // the io_context::run_for() function times out, the socket is closed and the // outstanding asynchronous operation is cancelled. // class client { public: client(const udp::endpoint& listen_endpoint) : socket_(io_context_, listen_endpoint) { } std::size_t receive(const boost::asio::mutable_buffer& buffer, std::chrono::steady_clock::duration timeout, boost::system::error_code& error) { // Start the asynchronous operation. The handle_receive function used as a // callback will update the error and length variables. std::size_t length = 0; socket_.async_receive(boost::asio::buffer(buffer), std::bind(&client::handle_receive, _1, _2, &error, &length)); // Run the operation until it completes, or until the timeout. run(timeout); return length; } private: void run(std::chrono::steady_clock::duration timeout) { // Restart the io_context, as it may have been left in the "stopped" state // by a previous operation. io_context_.restart(); // Block until the asynchronous operation has completed, or timed out. If // the pending asynchronous operation is a composed operation, the deadline // applies to the entire operation, rather than individual operations on // the socket. io_context_.run_for(timeout); // If the asynchronous operation completed successfully then the io_context // would have been stopped due to running out of work. If it was not // stopped, then the io_context::run_for call must have timed out. if (!io_context_.stopped()) { // Cancel the outstanding asynchronous operation. socket_.cancel(); // Run the io_context again until the operation completes. io_context_.run(); } } static void handle_receive( const boost::system::error_code& error, std::size_t length, boost::system::error_code* out_error, std::size_t* out_length) { *out_error = error; *out_length = length; } private: boost::asio::io_context io_context_; udp::socket socket_; }; //---------------------------------------------------------------------- int main(int argc, char* argv[]) { try { using namespace std; // For atoi. if (argc != 3) { std::cerr << "Usage: blocking_udp_client <listen_addr> <listen_port>\n"; return 1; } udp::endpoint listen_endpoint( boost::asio::ip::make_address(argv[1]), std::atoi(argv[2])); client c(listen_endpoint); for (;;) { char data[1024]; boost::system::error_code error; std::size_t n = c.receive(boost::asio::buffer(data), std::chrono::seconds(10), error); if (error) { std::cout << "Receive error: " << error.message() << "\n"; } else { std::cout << "Received: "; std::cout.write(data, n); std::cout << "\n"; } } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/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 <boost/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; }
cpp
asio
data/projects/asio/example/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). boost::asio::ip::tcp::resolver resolver(acceptor_.get_executor()); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::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](boost::system::error_code ec, boost::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](boost::system::error_code /*ec*/, int /*signo*/) { io_context_pool_.stop(); }); } } // namespace server2 } // namespace http
cpp
asio
data/projects/asio/example/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 <boost/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<boost::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
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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 <boost/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. boost::asio::signal_set signals_; /// Acceptor used to listen for incoming connections. boost::asio::ip::tcp::acceptor acceptor_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server2 } // namespace http #endif // HTTP_SERVER2_SERVER_HPP
hpp
asio
data/projects/asio/example/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 boost::asio::io_context); io_contexts_.push_back(io_context); work_.push_back(boost::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(); } boost::asio::io_context& io_context_pool::get_io_context() { // Use a round-robin scheme to choose the next io_context to use. boost::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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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(boost::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(boost::asio::buffer(buffer_), [this, self](boost::system::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()); boost::asio::async_write(socket_, reply_.to_buffers(), [this, self](boost::system::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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"; boost::asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return boost::asio::buffer(ok); case reply::created: return boost::asio::buffer(created); case reply::accepted: return boost::asio::buffer(accepted); case reply::no_content: return boost::asio::buffer(no_content); case reply::multiple_choices: return boost::asio::buffer(multiple_choices); case reply::moved_permanently: return boost::asio::buffer(moved_permanently); case reply::moved_temporarily: return boost::asio::buffer(moved_temporarily); case reply::not_modified: return boost::asio::buffer(not_modified); case reply::bad_request: return boost::asio::buffer(bad_request); case reply::unauthorized: return boost::asio::buffer(unauthorized); case reply::forbidden: return boost::asio::buffer(forbidden); case reply::not_found: return boost::asio::buffer(not_found); case reply::internal_server_error: return boost::asio::buffer(internal_server_error); case reply::not_implemented: return boost::asio::buffer(not_implemented); case reply::bad_gateway: return boost::asio::buffer(bad_gateway); case reply::service_unavailable: return boost::asio::buffer(service_unavailable); default: return boost::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<boost::asio::const_buffer> reply::to_buffers() { std::vector<boost::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(boost::asio::buffer(h.name)); buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); buffers.push_back(boost::asio::buffer(h.value)); buffers.push_back(boost::asio::buffer(misc_strings::crlf)); } buffers.push_back(boost::asio::buffer(misc_strings::crlf)); buffers.push_back(boost::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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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 <boost/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(boost::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. boost::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
hpp
asio
data/projects/asio/example/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 <boost/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. boost::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<boost::asio::io_context> io_context_ptr; typedef boost::asio::executor_work_guard< boost::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
hpp
asio
data/projects/asio/example/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 <boost/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; }
cpp
asio
data/projects/asio/example/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). boost::asio::ip::tcp::resolver resolver(io_context_); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::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](boost::system::error_code ec, boost::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](boost::system::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
cpp
asio
data/projects/asio/example/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 <boost/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<boost::asio::const_buffer> to_buffers(); /// Get a stock reply. static reply stock_reply(status_type status); }; } // namespace server } // namespace http #endif // HTTP_REPLY_HPP
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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 <boost/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. boost::asio::io_context io_context_; /// The signal_set is used to register for process termination notifications. boost::asio::signal_set signals_; /// Acceptor used to listen for incoming connections. boost::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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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(boost::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(boost::asio::buffer(buffer_), [this, self](boost::system::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 != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } void connection::do_write() { auto self(shared_from_this()); boost::asio::async_write(socket_, reply_.to_buffers(), [this, self](boost::system::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } if (ec != boost::asio::error::operation_aborted) { connection_manager_.stop(shared_from_this()); } }); } } // namespace server } // namespace http
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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"; boost::asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return boost::asio::buffer(ok); case reply::created: return boost::asio::buffer(created); case reply::accepted: return boost::asio::buffer(accepted); case reply::no_content: return boost::asio::buffer(no_content); case reply::multiple_choices: return boost::asio::buffer(multiple_choices); case reply::moved_permanently: return boost::asio::buffer(moved_permanently); case reply::moved_temporarily: return boost::asio::buffer(moved_temporarily); case reply::not_modified: return boost::asio::buffer(not_modified); case reply::bad_request: return boost::asio::buffer(bad_request); case reply::unauthorized: return boost::asio::buffer(unauthorized); case reply::forbidden: return boost::asio::buffer(forbidden); case reply::not_found: return boost::asio::buffer(not_found); case reply::internal_server_error: return boost::asio::buffer(internal_server_error); case reply::not_implemented: return boost::asio::buffer(not_implemented); case reply::bad_gateway: return boost::asio::buffer(bad_gateway); case reply::service_unavailable: return boost::asio::buffer(service_unavailable); default: return boost::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<boost::asio::const_buffer> reply::to_buffers() { std::vector<boost::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(boost::asio::buffer(h.name)); buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); buffers.push_back(boost::asio::buffer(h.value)); buffers.push_back(boost::asio::buffer(misc_strings::crlf)); } buffers.push_back(boost::asio::buffer(misc_strings::crlf)); buffers.push_back(boost::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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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 <boost/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(boost::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. boost::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
hpp
asio
data/projects/asio/example/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 <boost/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; }
cpp
asio
data/projects/asio/example/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). boost::asio::ip::tcp::resolver resolver(io_context_); boost::asio::ip::tcp::endpoint endpoint = *resolver.resolve(address, port).begin(); acceptor_.open(endpoint.protocol()); acceptor_.set_option(boost::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(boost::asio::make_strand(io_context_), [this](boost::system::error_code ec, boost::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](boost::system::error_code /*ec*/, int /*signo*/) { io_context_.stop(); }); } } // namespace server3 } // namespace http
cpp
asio
data/projects/asio/example/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 <boost/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<boost::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
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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 <boost/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. boost::asio::io_context io_context_; /// The signal_set is used to register for process termination notifications. boost::asio::signal_set signals_; /// Acceptor used to listen for incoming connections. boost::asio::ip::tcp::acceptor acceptor_; /// The handler for all incoming requests. request_handler request_handler_; }; } // namespace server3 } // namespace http #endif // HTTP_SERVER3_SERVER_HPP
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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(boost::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(boost::asio::buffer(buffer_), [this, self](boost::system::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()); boost::asio::async_write(socket_, reply_.to_buffers(), [this, self](boost::system::error_code ec, std::size_t) { if (!ec) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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"; boost::asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return boost::asio::buffer(ok); case reply::created: return boost::asio::buffer(created); case reply::accepted: return boost::asio::buffer(accepted); case reply::no_content: return boost::asio::buffer(no_content); case reply::multiple_choices: return boost::asio::buffer(multiple_choices); case reply::moved_permanently: return boost::asio::buffer(moved_permanently); case reply::moved_temporarily: return boost::asio::buffer(moved_temporarily); case reply::not_modified: return boost::asio::buffer(not_modified); case reply::bad_request: return boost::asio::buffer(bad_request); case reply::unauthorized: return boost::asio::buffer(unauthorized); case reply::forbidden: return boost::asio::buffer(forbidden); case reply::not_found: return boost::asio::buffer(not_found); case reply::internal_server_error: return boost::asio::buffer(internal_server_error); case reply::not_implemented: return boost::asio::buffer(not_implemented); case reply::bad_gateway: return boost::asio::buffer(bad_gateway); case reply::service_unavailable: return boost::asio::buffer(service_unavailable); default: return boost::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<boost::asio::const_buffer> reply::to_buffers() { std::vector<boost::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(boost::asio::buffer(h.name)); buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); buffers.push_back(boost::asio::buffer(h.value)); buffers.push_back(boost::asio::buffer(misc_strings::crlf)); } buffers.push_back(boost::asio::buffer(misc_strings::crlf)); buffers.push_back(boost::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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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 <boost/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(boost::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. boost::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
hpp
asio
data/projects/asio/example/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 <boost/asio.hpp> using boost::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; } boost::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); boost::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. boost::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. boost::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. boost::asio::streambuf response; boost::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. boost::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. boost::system::error_code error; while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) std::cout << &response; if (error != boost::asio::error::eof) throw boost::system::system_error(error); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/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 <boost/asio.hpp> using boost::asio::ip::tcp; class client { public: client(boost::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, boost::asio::placeholders::error, boost::asio::placeholders::results)); } private: void handle_resolve(const boost::system::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. boost::asio::async_connect(socket_, endpoints, std::bind(&client::handle_connect, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_connect(const boost::system::error_code& err) { if (!err) { // The connection was successful. Send the request. boost::asio::async_write(socket_, request_, std::bind(&client::handle_write_request, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_write_request(const boost::system::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. boost::asio::async_read_until(socket_, response_, "\r\n", std::bind(&client::handle_read_status_line, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err.message() << "\n"; } } void handle_read_status_line(const boost::system::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. boost::asio::async_read_until(socket_, response_, "\r\n\r\n", std::bind(&client::handle_read_headers, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_headers(const boost::system::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. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), std::bind(&client::handle_read_content, this, boost::asio::placeholders::error)); } else { std::cout << "Error: " << err << "\n"; } } void handle_read_content(const boost::system::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. boost::asio::async_read(socket_, response_, boost::asio::transfer_at_least(1), std::bind(&client::handle_read_content, this, boost::asio::placeholders::error)); } else if (err != boost::asio::error::eof) { std::cout << "Error: " << err << "\n"; } } tcp::resolver resolver_; tcp::socket socket_; boost::asio::streambuf request_; boost::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; } boost::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; }
cpp
asio
data/projects/asio/example/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 <boost/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; } boost::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. boost::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](boost::system::error_code, int) { io_context.stop(); }); // Run the server. io_context.run(); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/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(boost::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); boost::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 <boost/asio/yield.hpp> void server::operator()(boost::system::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(boost::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 boost::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 <boost/asio/unyield.hpp> } // namespace server4 } // namespace http
cpp
asio
data/projects/asio/example/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 <boost/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<boost::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
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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 <boost/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 : boost::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(boost::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()( boost::system::error_code ec = boost::system::error_code(), std::size_t length = 0); private: typedef boost::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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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"; boost::asio::const_buffer to_buffer(reply::status_type status) { switch (status) { case reply::ok: return boost::asio::buffer(ok); case reply::created: return boost::asio::buffer(created); case reply::accepted: return boost::asio::buffer(accepted); case reply::no_content: return boost::asio::buffer(no_content); case reply::multiple_choices: return boost::asio::buffer(multiple_choices); case reply::moved_permanently: return boost::asio::buffer(moved_permanently); case reply::moved_temporarily: return boost::asio::buffer(moved_temporarily); case reply::not_modified: return boost::asio::buffer(not_modified); case reply::bad_request: return boost::asio::buffer(bad_request); case reply::unauthorized: return boost::asio::buffer(unauthorized); case reply::forbidden: return boost::asio::buffer(forbidden); case reply::not_found: return boost::asio::buffer(not_found); case reply::internal_server_error: return boost::asio::buffer(internal_server_error); case reply::not_implemented: return boost::asio::buffer(not_implemented); case reply::bad_gateway: return boost::asio::buffer(bad_gateway); case reply::service_unavailable: return boost::asio::buffer(service_unavailable); default: return boost::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<boost::asio::const_buffer> reply::to_buffers() { std::vector<boost::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(boost::asio::buffer(h.name)); buffers.push_back(boost::asio::buffer(misc_strings::name_value_separator)); buffers.push_back(boost::asio::buffer(h.value)); buffers.push_back(boost::asio::buffer(misc_strings::crlf)); } buffers.push_back(boost::asio::buffer(misc_strings::crlf)); buffers.push_back(boost::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
cpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/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
cpp
asio
data/projects/asio/example/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
hpp
asio
data/projects/asio/example/cpp11/local/stream_client.cpp
// // stream_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 <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using boost::asio::local::stream_protocol; constexpr std::size_t max_length = 1024; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: stream_client <file>\n"; return 1; } boost::asio::io_context io_context; stream_protocol::socket s(io_context); s.connect(stream_protocol::endpoint(argv[1])); std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); boost::asio::write(s, boost::asio::buffer(request, request_length)); char reply[max_length]; size_t reply_length = boost::asio::read(s, boost::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; } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/cpp11/local/fd_passing_stream_client.cpp
// // fd_passing_stream_client.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2021 Heiko Hund (heiko at openvpn dot net) // // 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) // // Demonstrates how to pass file descriptors between processes with Asio. // The client send a file name (destfile) to the server. The server opens // the file and the associated file descriptor back to the client. #include <cstdlib> #include <cstring> #include <iostream> #include <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) #include <sys/types.h> #include <sys/socket.h> using boost::asio::local::stream_protocol; constexpr std::size_t max_length = 1024; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: fd_passing_stream_client <serversocket>\n"; return 1; } boost::asio::io_context io_context; stream_protocol::socket s(io_context); s.connect(stream_protocol::endpoint(argv[1])); std::cout << "Enter path to write to: "; char request[max_length]; std::cin.getline(request, max_length); size_t request_length = std::strlen(request); boost::asio::write(s, boost::asio::buffer(request, request_length)); char reply[max_length]; struct msghdr msg = {}; struct iovec iov = { reply, sizeof(reply) }; msg.msg_iov = &iov; msg.msg_iovlen = 1; union { struct cmsghdr align; char buf[CMSG_SPACE(sizeof(int))]; } cmsgu; msg.msg_control = cmsgu.buf; msg.msg_controllen = sizeof(cmsgu.buf); ::recvmsg(s.native_handle(), &msg, 0); int fd = -1; struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); while (cmsg != NULL) { if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) { std::memcpy(&fd, CMSG_DATA(cmsg), sizeof(fd)); break; } cmsg = CMSG_NXTHDR(&msg, cmsg); } if (fd != -1) { std::cout << "File descriptor received is: " << fd << "\n"; FILE* f(::fdopen(fd, "w+")); if (f) { ::fprintf(f, "stream_client writing to received fd #%d\n", fd); ::fclose(f); } else ::close(fd); } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/cpp11/local/fd_passing_stream_server.cpp
// // fd_passing_stream_server.cpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2021 Heiko Hund (heiko at openvpn dot net) // // 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) // // Demonstrates how to pass file descriptors between processes with Asio. // The client sends a file name to the server. The server opens the file and // passes the associated file descriptor back to the client. #include <array> #include <cstdio> #include <cassert> #include <iostream> #include <memory> #include <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using boost::asio::local::stream_protocol; class session : public std::enable_shared_from_this<session> { public: session(stream_protocol::socket sock) : socket_(std::move(sock)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_), [this, self](boost::system::error_code ec, std::size_t length) { if (ec) return; assert(length < data_.size()); data_[length] = 0; do_write(data_.data()); }); } void do_write(const char* filename) { auto self(shared_from_this()); socket_.async_wait(stream_protocol::socket::wait_write, [this, self, filename](boost::system::error_code ec) { if (ec) return; FILE* f(::fopen(filename, "w+")); if (!f) return; struct msghdr msg = {}; char buf[] = { 0 }; struct iovec iov = { buf, sizeof(buf) }; msg.msg_iov = &iov; msg.msg_iovlen = 1; union { struct cmsghdr align; char buf[CMSG_SPACE(sizeof(int))]; } cmsgu; msg.msg_control = cmsgu.buf; msg.msg_controllen = sizeof(cmsgu.buf); struct cmsghdr* cmsg = CMSG_FIRSTHDR(&msg); cmsg->cmsg_len = CMSG_LEN(sizeof(int)); cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; int fd = ::fileno(f); std::memcpy(CMSG_DATA(cmsg), &fd, sizeof(int)); ssize_t s(::sendmsg(socket_.native_handle(), &msg, 0)); ::fclose(f); if (s != -1) do_read(); }); } // The socket used to communicate with the client. stream_protocol::socket socket_; // Buffer used to store data received from the client. std::array<char, 1024> data_; }; class server { public: server(boost::asio::io_context& io_context, const std::string& file) : acceptor_(io_context, stream_protocol::endpoint(file)) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](boost::system::error_code ec, stream_protocol::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } stream_protocol::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: fd_passing_stream_server <socketfile>\n"; std::cerr << "*** WARNING: existing file is removed ***\n"; return 1; } boost::asio::io_context io_context; std::remove(argv[1]); server s(io_context, argv[1]); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/cpp11/local/stream_server.cpp
// // stream_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 <cstdio> #include <iostream> #include <memory> #include <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using boost::asio::local::stream_protocol; class session : public std::enable_shared_from_this<session> { public: session(stream_protocol::socket sock) : socket_(std::move(sock)) { } void start() { do_read(); } private: void do_read() { auto self(shared_from_this()); socket_.async_read_some(boost::asio::buffer(data_), [this, self](boost::system::error_code ec, std::size_t length) { if (!ec) do_write(length); }); } void do_write(std::size_t length) { auto self(shared_from_this()); boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this, self](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) do_read(); }); } // The socket used to communicate with the client. stream_protocol::socket socket_; // Buffer used to store data received from the client. std::array<char, 1024> data_; }; class server { public: server(boost::asio::io_context& io_context, const std::string& file) : acceptor_(io_context, stream_protocol::endpoint(file)) { do_accept(); } private: void do_accept() { acceptor_.async_accept( [this](boost::system::error_code ec, stream_protocol::socket socket) { if (!ec) { std::make_shared<session>(std::move(socket))->start(); } do_accept(); }); } stream_protocol::acceptor acceptor_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: stream_server <file>\n"; std::cerr << "*** WARNING: existing file is removed ***\n"; return 1; } boost::asio::io_context io_context; std::remove(argv[1]); server s(io_context, argv[1]); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/cpp11/local/iostream_client.cpp
// // stream_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 <cstring> #include <iostream> #include <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using boost::asio::local::stream_protocol; constexpr std::size_t max_length = 1024; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: iostream_client <file>\n"; return 1; } stream_protocol::endpoint ep(argv[1]); stream_protocol::iostream s(ep); if (!s) { std::cerr << "Unable to connect: " << s.error().message() << std::endl; return 1; } std::cout << "Enter message: "; char request[max_length]; std::cin.getline(request, max_length); size_t length = std::strlen(request); s << request; char reply[max_length]; s.read(reply, length); std::cout << "Reply is: "; std::cout.write(reply, length); std::cout << "\n"; } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/cpp11/local/connect_pair.cpp
// // connect_pair.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 <cctype> #include <boost/asio.hpp> #include <boost/thread/thread.hpp> #if defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) using boost::asio::local::stream_protocol; class uppercase_filter { public: uppercase_filter(stream_protocol::socket sock) : socket_(std::move(sock)) { read(); } private: void read() { socket_.async_read_some(boost::asio::buffer(data_), [this](boost::system::error_code ec, std::size_t size) { if (!ec) { // Compute result. for (std::size_t i = 0; i < size; ++i) data_[i] = std::toupper(data_[i]); // Send result. write(size); } else { throw boost::system::system_error(ec); } }); } void write(std::size_t size) { boost::asio::async_write(socket_, boost::asio::buffer(data_, size), [this](boost::system::error_code ec, std::size_t /*size*/) { if (!ec) { // Wait for request. read(); } else { throw boost::system::system_error(ec); } }); } stream_protocol::socket socket_; std::array<char, 512> data_; }; int main() { try { boost::asio::io_context io_context; // Create a connected pair and pass one end to a filter. stream_protocol::socket socket(io_context); stream_protocol::socket filter_socket(io_context); boost::asio::local::connect_pair(socket, filter_socket); uppercase_filter filter(std::move(filter_socket)); // The io_context runs in a background thread to perform filtering. boost::thread thread( [&io_context]() { try { io_context.run(); } catch (std::exception& e) { std::cerr << "Exception in thread: " << e.what() << "\n"; std::exit(1); } }); for (;;) { // Collect request from user. std::cout << "Enter a string: "; std::string request; std::getline(std::cin, request); // Send request to filter. boost::asio::write(socket, boost::asio::buffer(request)); // Wait for reply from filter. std::vector<char> reply(request.size()); boost::asio::read(socket, boost::asio::buffer(reply)); // Show reply to user. std::cout << "Result: "; std::cout.write(&reply[0], request.size()); std::cout << std::endl; } } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << "\n"; std::exit(1); } } #else // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS) # error Local sockets not available on this platform. #endif // defined(BOOST_ASIO_HAS_LOCAL_SOCKETS)
cpp
asio
data/projects/asio/example/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 <boost/asio.hpp> using boost::asio::ip::tcp; // Define a helper macro to invoke BOOST_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 \ BOOST_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(boost::asio::buffer(data_, max_length), [this, self](boost::system::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()); boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this, self](boost::system::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(boost::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](boost::system::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; } boost::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; }
cpp
asio
data/projects/asio/example/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 BOOST_ASIO_INHERIT_TRACKED_HANDLER \ : public ::custom_tracking::tracked_handler # define BOOST_ASIO_ALSO_INHERIT_TRACKED_HANDLER \ , public ::custom_tracking::tracked_handler # define BOOST_ASIO_HANDLER_TRACKING_INIT \ ::custom_tracking::init() # define BOOST_ASIO_HANDLER_LOCATION(args) \ ::custom_tracking::location args # define BOOST_ASIO_HANDLER_CREATION(args) \ ::custom_tracking::creation args # define BOOST_ASIO_HANDLER_COMPLETION(args) \ ::custom_tracking::completion tracked_completion args # define BOOST_ASIO_HANDLER_INVOCATION_BEGIN(args) \ tracked_completion.invocation_begin args # define BOOST_ASIO_HANDLER_INVOCATION_END \ tracked_completion.invocation_end() # define BOOST_ASIO_HANDLER_OPERATION(args) \ ::custom_tracking::operation args # define BOOST_ASIO_HANDLER_REACTOR_REGISTRATION(args) \ ::custom_tracking::reactor_registration args # define BOOST_ASIO_HANDLER_REACTOR_DEREGISTRATION(args) \ ::custom_tracking::reactor_deregistration args # define BOOST_ASIO_HANDLER_REACTOR_READ_EVENT 1 # define BOOST_ASIO_HANDLER_REACTOR_WRITE_EVENT 2 # define BOOST_ASIO_HANDLER_REACTOR_ERROR_EVENT 4 # define BOOST_ASIO_HANDLER_REACTOR_EVENTS(args) \ ::custom_tracking::reactor_events args # define BOOST_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(boost::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 BOOST_ASIO_THREAD_KEYWORD completion* current = nullptr; return &current; } // Record an operation that is not directly associated with a handler. static void operation(boost::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(boost::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(boost::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(boost::asio::execution_context& context, uintmax_t registration, unsigned events) { std::printf( "Reactor readiness for registration = %" PRIuMAX ", events =%s%s%s\n", registration, (events & BOOST_ASIO_HANDLER_REACTOR_READ_EVENT) ? " read" : "", (events & BOOST_ASIO_HANDLER_REACTOR_WRITE_EVENT) ? " write" : "", (events & BOOST_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 boost::system::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 boost::system::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
hpp
asio
data/projects/asio/example/cpp11/buffers/reference_counted.cpp
// // reference_counted.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 <boost/asio.hpp> #include <iostream> #include <memory> #include <utility> #include <vector> #include <ctime> using boost::asio::ip::tcp; // A reference-counted non-modifiable buffer class. class shared_const_buffer { public: // Construct from a std::string. explicit shared_const_buffer(const std::string& data) : data_(new std::vector<char>(data.begin(), data.end())), buffer_(boost::asio::buffer(*data_)) { } // Implement the ConstBufferSequence requirements. typedef boost::asio::const_buffer value_type; typedef const boost::asio::const_buffer* const_iterator; const boost::asio::const_buffer* begin() const { return &buffer_; } const boost::asio::const_buffer* end() const { return &buffer_ + 1; } private: std::shared_ptr<std::vector<char> > data_; boost::asio::const_buffer buffer_; }; class session : public std::enable_shared_from_this<session> { public: session(tcp::socket socket) : socket_(std::move(socket)) { } void start() { do_write(); } private: void do_write() { std::time_t now = std::time(0); shared_const_buffer buffer(std::ctime(&now)); auto self(shared_from_this()); boost::asio::async_write(socket_, buffer, [self](boost::system::error_code /*ec*/, std::size_t /*length*/) { }); } // The socket used to communicate with the client. tcp::socket socket_; }; class server { public: server(boost::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](boost::system::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: reference_counted <port>\n"; return 1; } boost::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; }
cpp
asio
data/projects/asio/example/cpp11/fork/daemon.cpp
// // daemon.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 <boost/asio/io_context.hpp> #include <boost/asio/ip/udp.hpp> #include <boost/asio/signal_set.hpp> #include <array> #include <ctime> #include <iostream> #include <syslog.h> #include <unistd.h> using boost::asio::ip::udp; class udp_daytime_server { public: udp_daytime_server(boost::asio::io_context& io_context) : socket_(io_context, {udp::v4(), 13}) { receive(); } private: void receive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, [this](boost::system::error_code ec, std::size_t /*n*/) { if (!ec) { using namespace std; // For time_t, time and ctime; time_t now = time(0); std::string message = ctime(&now); boost::system::error_code ignored_ec; socket_.send_to(boost::asio::buffer(message), remote_endpoint_, 0, ignored_ec); } receive(); }); } udp::socket socket_; udp::endpoint remote_endpoint_; std::array<char, 1> recv_buffer_; }; int main() { try { boost::asio::io_context io_context; // Initialise the server before becoming a daemon. If the process is // started from a shell, this means any errors will be reported back to the // user. udp_daytime_server server(io_context); // Register signal handlers so that the daemon may be shut down. You may // also want to register for other signals, such as SIGHUP to trigger a // re-read of a configuration file. boost::asio::signal_set signals(io_context, SIGINT, SIGTERM); signals.async_wait( [&](boost::system::error_code /*ec*/, int /*signo*/) { io_context.stop(); }); // Inform the io_context that we are about to become a daemon. The // io_context cleans up any internal resources, such as threads, that may // interfere with forking. io_context.notify_fork(boost::asio::io_context::fork_prepare); // Fork the process and have the parent exit. If the process was started // from a shell, this returns control to the user. Forking a new process is // also a prerequisite for the subsequent call to setsid(). if (pid_t pid = fork()) { if (pid > 0) { // We're in the parent process and need to exit. // // When the exit() function is used, the program terminates without // invoking local variables' destructors. Only global variables are // destroyed. As the io_context object is a local variable, this means // we do not have to call: // // io_context.notify_fork(boost::asio::io_context::fork_parent); // // However, this line should be added before each call to exit() if // using a global io_context object. An additional call: // // io_context.notify_fork(boost::asio::io_context::fork_prepare); // // should also precede the second fork(). exit(0); } else { syslog(LOG_ERR | LOG_USER, "First fork failed: %m"); return 1; } } // Make the process a new session leader. This detaches it from the // terminal. setsid(); // A process inherits its working directory from its parent. This could be // on a mounted filesystem, which means that the running daemon would // prevent this filesystem from being unmounted. Changing to the root // directory avoids this problem. chdir("/"); // The file mode creation mask is also inherited from the parent process. // We don't want to restrict the permissions on files created by the // daemon, so the mask is cleared. umask(0); // A second fork ensures the process cannot acquire a controlling terminal. if (pid_t pid = fork()) { if (pid > 0) { exit(0); } else { syslog(LOG_ERR | LOG_USER, "Second fork failed: %m"); return 1; } } // Close the standard streams. This decouples the daemon from the terminal // that started it. close(0); close(1); close(2); // We don't want the daemon to have any standard input. if (open("/dev/null", O_RDONLY) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m"); return 1; } // Send standard output to a log file. const char* output = "/tmp/asio.daemon.out"; const int flags = O_WRONLY | O_CREAT | O_APPEND; const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; if (open(output, flags, mode) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output); return 1; } // Also send standard error to the same log file. if (dup(1) < 0) { syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m"); return 1; } // Inform the io_context that we have finished becoming a daemon. The // io_context uses this opportunity to create any internal file descriptors // that need to be private to the new process. io_context.notify_fork(boost::asio::io_context::fork_child); // The io_context can now be used normally. syslog(LOG_INFO | LOG_USER, "Daemon started"); io_context.run(); syslog(LOG_INFO | LOG_USER, "Daemon stopped"); } catch (std::exception& e) { syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what()); std::cerr << "Exception: " << e.what() << std::endl; } }
cpp
asio
data/projects/asio/example/cpp11/fork/process_per_connection.cpp
// // process_per_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 <boost/asio/io_context.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/signal_set.hpp> #include <boost/asio/write.hpp> #include <cstdlib> #include <iostream> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> using boost::asio::ip::tcp; class server { public: server(boost::asio::io_context& io_context, unsigned short port) : io_context_(io_context), signal_(io_context, SIGCHLD), acceptor_(io_context, {tcp::v4(), port}), socket_(io_context) { wait_for_signal(); accept(); } private: void wait_for_signal() { signal_.async_wait( [this](boost::system::error_code /*ec*/, int /*signo*/) { // Only the parent process should check for this signal. We can // determine whether we are in the parent by checking if the acceptor // is still open. if (acceptor_.is_open()) { // Reap completed child processes so that we don't end up with // zombies. int status = 0; while (waitpid(-1, &status, WNOHANG) > 0) {} wait_for_signal(); } }); } void accept() { acceptor_.async_accept( [this](boost::system::error_code ec, tcp::socket new_socket) { if (!ec) { // Take ownership of the newly accepted socket. socket_ = std::move(new_socket); // Inform the io_context that we are about to fork. The io_context // cleans up any internal resources, such as threads, that may // interfere with forking. io_context_.notify_fork(boost::asio::io_context::fork_prepare); if (fork() == 0) { // Inform the io_context that the fork is finished and that this // is the child process. The io_context uses this opportunity to // create any internal file descriptors that must be private to // the new process. io_context_.notify_fork(boost::asio::io_context::fork_child); // The child won't be accepting new connections, so we can close // the acceptor. It remains open in the parent. acceptor_.close(); // The child process is not interested in processing the SIGCHLD // signal. signal_.cancel(); read(); } else { // Inform the io_context that the fork is finished (or failed) // and that this is the parent process. The io_context uses this // opportunity to recreate any internal resources that were // cleaned up during preparation for the fork. io_context_.notify_fork(boost::asio::io_context::fork_parent); // The parent process can now close the newly accepted socket. It // remains open in the child. socket_.close(); accept(); } } else { std::cerr << "Accept error: " << ec.message() << std::endl; accept(); } }); } void read() { socket_.async_read_some(boost::asio::buffer(data_), [this](boost::system::error_code ec, std::size_t length) { if (!ec) write(length); }); } void write(std::size_t length) { boost::asio::async_write(socket_, boost::asio::buffer(data_, length), [this](boost::system::error_code ec, std::size_t /*length*/) { if (!ec) read(); }); } boost::asio::io_context& io_context_; boost::asio::signal_set signal_; tcp::acceptor acceptor_; tcp::socket socket_; std::array<char, 1024> data_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: process_per_connection <port>\n"; return 1; } boost::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() << std::endl; } }
cpp
asio
data/projects/asio/example/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 <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_FILE) class file_copier { public: file_copier(boost::asio::io_context& io_context, const char* from, const char* to) : from_file_(io_context, from, boost::asio::stream_file::read_only), to_file_(io_context, to, boost::asio::stream_file::write_only | boost::asio::stream_file::create | boost::asio::stream_file::truncate) { } void start() { do_read(); } private: void do_read() { from_file_.async_read_some(boost::asio::buffer(data_), [this](boost::system::error_code error, std::size_t n) { if (!error) { do_write(n); } else if (error != boost::asio::error::eof) { std::cerr << "Error copying file: " << error.message() << "\n"; } }); } void do_write(std::size_t n) { boost::asio::async_write(to_file_, boost::asio::buffer(data_, n), [this](boost::system::error_code error, std::size_t /*n*/) { if (!error) { do_read(); } else { std::cerr << "Error copying file: " << error.message() << "\n"; } }); } boost::asio::stream_file from_file_; boost::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; } boost::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(BOOST_ASIO_HAS_FILE) int main() {} #endif // defined(BOOST_ASIO_HAS_FILE)
cpp
asio
data/projects/asio/example/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 <boost/asio.hpp> #if defined(BOOST_ASIO_HAS_FILE) int main(int argc, char* argv[]) { try { if (argc != 3) { std::cerr << "Usage: blocking_file_copy <from> <to>\n"; return 1; } boost::asio::io_context io_context; boost::asio::stream_file from_file(io_context, argv[1], boost::asio::stream_file::read_only); boost::asio::stream_file to_file(io_context, argv[2], boost::asio::stream_file::write_only | boost::asio::stream_file::create | boost::asio::stream_file::truncate); char data[4096]; boost::system::error_code error; for (;;) { std::size_t n = from_file.read_some(boost::asio::buffer(data), error); if (error) break; boost::asio::write(to_file, boost::asio::buffer(data, n), error); if (error) break; } if (error && error != boost::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(BOOST_ASIO_HAS_FILE) int main() {} #endif // defined(BOOST_ASIO_HAS_FILE)
cpp
asio
data/projects/asio/example/cpp11/serialization/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 <boost/asio.hpp> #include <functional> #include <iostream> #include <vector> #include "connection.hpp" // Must come before boost/serialization headers. #include <boost/serialization/vector.hpp> #include "stock.hpp" namespace s11n_example { /// Serves stock quote information to any client that connects to it. class server { public: /// Constructor opens the acceptor and starts waiting for the first incoming /// connection. server(boost::asio::io_context& io_context, unsigned short port) : acceptor_(io_context, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)) { // Create the data to be sent to each client. stock s; s.code = "ABC"; s.name = "A Big Company"; s.open_price = 4.56; s.high_price = 5.12; s.low_price = 4.33; s.last_price = 4.98; s.buy_price = 4.96; s.buy_quantity = 1000; s.sell_price = 4.99; s.sell_quantity = 2000; stocks_.push_back(s); s.code = "DEF"; s.name = "Developer Entertainment Firm"; s.open_price = 20.24; s.high_price = 22.88; s.low_price = 19.50; s.last_price = 19.76; s.buy_price = 19.72; s.buy_quantity = 34000; s.sell_price = 19.85; s.sell_quantity = 45000; stocks_.push_back(s); // Start an accept operation for a new connection. connection_ptr new_conn(new connection(acceptor_.get_executor())); acceptor_.async_accept(new_conn->socket(), std::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_conn)); } /// Handle completion of a accept operation. void handle_accept(const boost::system::error_code& e, connection_ptr conn) { if (!e) { // Successfully accepted a new connection. Send the list of stocks to the // client. The connection::async_write() function will automatically // serialize the data structure for us. conn->async_write(stocks_, std::bind(&server::handle_write, this, boost::asio::placeholders::error, conn)); } // Start an accept operation for a new connection. connection_ptr new_conn(new connection(acceptor_.get_executor())); acceptor_.async_accept(new_conn->socket(), std::bind(&server::handle_accept, this, boost::asio::placeholders::error, new_conn)); } /// Handle completion of a write operation. void handle_write(const boost::system::error_code& e, connection_ptr conn) { // Nothing to do. The socket will be closed automatically when the last // reference to the connection object goes away. } private: /// The acceptor object used to accept incoming socket connections. boost::asio::ip::tcp::acceptor acceptor_; /// The data to be sent to each client. std::vector<stock> stocks_; }; } // namespace s11n_example int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 2) { std::cerr << "Usage: server <port>" << std::endl; return 1; } unsigned short port = std::stoi(argv[1]); boost::asio::io_context io_context; s11n_example::server server(io_context, port); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/serialization/stock.hpp
// // stock.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 SERIALIZATION_STOCK_HPP #define SERIALIZATION_STOCK_HPP #include <string> namespace s11n_example { /// Structure to hold information about a single stock. struct stock { std::string code; std::string name; double open_price; double high_price; double low_price; double last_price; double buy_price; int buy_quantity; double sell_price; int sell_quantity; template <typename Archive> void serialize(Archive& ar, const unsigned int version) { ar & code; ar & name; ar & open_price; ar & high_price; ar & low_price; ar & last_price; ar & buy_price; ar & buy_quantity; ar & sell_price; ar & sell_quantity; } }; } // namespace s11n_example #endif // SERIALIZATION_STOCK_HPP
hpp
asio
data/projects/asio/example/cpp11/serialization/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 <boost/asio.hpp> #include <functional> #include <iostream> #include <vector> #include "connection.hpp" // Must come before boost/serialization headers. #include <boost/serialization/vector.hpp> #include "stock.hpp" namespace s11n_example { /// Downloads stock quote information from a server. class client { public: /// Constructor starts the asynchronous connect operation. client(boost::asio::io_context& io_context, const std::string& host, const std::string& service) : connection_(io_context.get_executor()) { // Resolve the host name into an IP address. boost::asio::ip::tcp::resolver resolver(io_context); boost::asio::ip::tcp::resolver::query query(host, service); boost::asio::ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); // Start an asynchronous connect operation. boost::asio::async_connect(connection_.socket(), endpoint_iterator, std::bind(&client::handle_connect, this, boost::asio::placeholders::error)); } /// Handle completion of a connect operation. void handle_connect(const boost::system::error_code& e) { if (!e) { // Successfully established connection. Start operation to read the list // of stocks. The connection::async_read() function will automatically // decode the data that is read from the underlying socket. connection_.async_read(stocks_, std::bind(&client::handle_read, this, boost::asio::placeholders::error)); } else { // An error occurred. Log it and return. Since we are not starting a new // operation the io_context will run out of work to do and the client will // exit. std::cerr << e.message() << std::endl; } } /// Handle completion of a read operation. void handle_read(const boost::system::error_code& e) { if (!e) { // Print out the data that was received. for (std::size_t i = 0; i < stocks_.size(); ++i) { std::cout << "Stock number " << i << "\n"; std::cout << " code: " << stocks_[i].code << "\n"; std::cout << " name: " << stocks_[i].name << "\n"; std::cout << " open_price: " << stocks_[i].open_price << "\n"; std::cout << " high_price: " << stocks_[i].high_price << "\n"; std::cout << " low_price: " << stocks_[i].low_price << "\n"; std::cout << " last_price: " << stocks_[i].last_price << "\n"; std::cout << " buy_price: " << stocks_[i].buy_price << "\n"; std::cout << " buy_quantity: " << stocks_[i].buy_quantity << "\n"; std::cout << " sell_price: " << stocks_[i].sell_price << "\n"; std::cout << " sell_quantity: " << stocks_[i].sell_quantity << "\n"; } } else { // An error occurred. std::cerr << e.message() << std::endl; } // Since we are not starting a new operation the io_context will run out of // work to do and the client will exit. } private: /// The connection to the server. connection connection_; /// The data received from the server. std::vector<stock> stocks_; }; } // namespace s11n_example int main(int argc, char* argv[]) { try { // Check command line arguments. if (argc != 3) { std::cerr << "Usage: client <host> <port>" << std::endl; return 1; } boost::asio::io_context io_context; s11n_example::client client(io_context, argv[1], argv[2]); io_context.run(); } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/serialization/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 SERIALIZATION_CONNECTION_HPP #define SERIALIZATION_CONNECTION_HPP #include <boost/asio.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <functional> #include <iomanip> #include <memory> #include <string> #include <sstream> #include <tuple> #include <vector> namespace s11n_example { /// The connection class provides serialization primitives on top of a socket. /** * Each message sent using this class consists of: * @li An 8-byte header containing the length of the serialized data in * hexadecimal. * @li The serialized data. */ class connection { public: /// Constructor. connection(const boost::asio::any_io_executor& ex) : socket_(ex) { } /// Get the underlying socket. Used for making a connection or for accepting /// an incoming connection. boost::asio::ip::tcp::socket& socket() { return socket_; } /// Asynchronously write a data structure to the socket. template <typename T, typename Handler> void async_write(const T& t, Handler handler) { // Serialize the data first so we know how large it is. std::ostringstream archive_stream; boost::archive::text_oarchive archive(archive_stream); archive << t; outbound_data_ = archive_stream.str(); // Format the header. std::ostringstream header_stream; header_stream << std::setw(header_length) << std::hex << outbound_data_.size(); if (!header_stream || header_stream.str().size() != header_length) { // Something went wrong, inform the caller. boost::system::error_code error(boost::asio::error::invalid_argument); boost::asio::post(socket_.get_executor(), std::bind(handler, error)); return; } outbound_header_ = header_stream.str(); // Write the serialized data to the socket. We use "gather-write" to send // both the header and the data in a single write operation. std::vector<boost::asio::const_buffer> buffers; buffers.push_back(boost::asio::buffer(outbound_header_)); buffers.push_back(boost::asio::buffer(outbound_data_)); boost::asio::async_write(socket_, buffers, handler); } /// Asynchronously read a data structure from the socket. template <typename T, typename Handler> void async_read(T& t, Handler handler) { // Issue a read operation to read exactly the number of bytes in a header. void (connection::*f)(const boost::system::error_code&, T&, std::tuple<Handler>) = &connection::handle_read_header<T, Handler>; boost::asio::async_read(socket_, boost::asio::buffer(inbound_header_), std::bind(f, this, boost::asio::placeholders::error, std::ref(t), std::make_tuple(handler))); } /// Handle a completed read of a message header. template <typename T, typename Handler> void handle_read_header(const boost::system::error_code& e, T& t, std::tuple<Handler> handler) { if (e) { std::get<0>(handler)(e); } else { // Determine the length of the serialized data. std::istringstream is(std::string(inbound_header_, header_length)); std::size_t inbound_data_size = 0; if (!(is >> std::hex >> inbound_data_size)) { // Header doesn't seem to be valid. Inform the caller. boost::system::error_code error(boost::asio::error::invalid_argument); std::get<0>(handler)(error); return; } // Start an asynchronous call to receive the data. inbound_data_.resize(inbound_data_size); void (connection::*f)( const boost::system::error_code&, T&, std::tuple<Handler>) = &connection::handle_read_data<T, Handler>; boost::asio::async_read(socket_, boost::asio::buffer(inbound_data_), std::bind(f, this, boost::asio::placeholders::error, std::ref(t), handler)); } } /// Handle a completed read of message data. template <typename T, typename Handler> void handle_read_data(const boost::system::error_code& e, T& t, std::tuple<Handler> handler) { if (e) { std::get<0>(handler)(e); } else { // Extract the data structure from the data just received. try { std::string archive_data(&inbound_data_[0], inbound_data_.size()); std::istringstream archive_stream(archive_data); boost::archive::text_iarchive archive(archive_stream); archive >> t; } catch (std::exception& e) { // Unable to decode data. boost::system::error_code error(boost::asio::error::invalid_argument); std::get<0>(handler)(error); return; } // Inform caller that data has been received ok. std::get<0>(handler)(e); } } private: /// The underlying socket. boost::asio::ip::tcp::socket socket_; /// The size of a fixed length header. enum { header_length = 8 }; /// Holds an outbound header. std::string outbound_header_; /// Holds the outbound data. std::string outbound_data_; /// Holds an inbound header. char inbound_header_[header_length]; /// Holds the inbound data. std::vector<char> inbound_data_; }; typedef std::shared_ptr<connection> connection_ptr; } // namespace s11n_example #endif // SERIALIZATION_CONNECTION_HPP
hpp
asio
data/projects/asio/example/cpp11/iostreams/http_client.cpp
// // http_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 <boost/asio/ip/tcp.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 3) { std::cout << "Usage: http_client <server> <path>\n"; std::cout << "Example:\n"; std::cout << " http_client www.boost.org /LICENSE_1_0.txt\n"; return 1; } boost::asio::ip::tcp::iostream s; // The entire sequence of I/O operations must complete within 60 seconds. // If an expiry occurs, the socket is automatically closed and the stream // becomes bad. s.expires_after(std::chrono::seconds(60)); // Establish a connection to the server. s.connect(argv[1], "http"); if (!s) { std::cout << "Unable to connect: " << s.error().message() << "\n"; return 1; } // Send 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. s << "GET " << argv[2] << " HTTP/1.0\r\n"; s << "Host: " << argv[1] << "\r\n"; s << "Accept: */*\r\n"; s << "Connection: close\r\n\r\n"; // By default, the stream is tied with itself. This means that the stream // automatically flush the buffered output before attempting a read. It is // not necessary not explicitly flush the stream at this point. // Check that response is OK. std::string http_version; s >> http_version; unsigned int status_code; s >> status_code; std::string status_message; std::getline(s, status_message); if (!s || 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; } // Process the response headers, which are terminated by a blank line. std::string header; while (std::getline(s, header) && header != "\r") std::cout << header << "\n"; std::cout << "\n"; // Write the remaining data to output. std::cout << s.rdbuf(); } catch (std::exception& e) { std::cout << "Exception: " << e.what() << "\n"; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/iostreams/daytime_server.cpp
// // daytime_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 <ctime> #include <iostream> #include <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; std::string make_daytime_string() { using namespace std; // For time_t, time and ctime; time_t now = time(0); return ctime(&now); } int main() { try { boost::asio::io_context io_context; tcp::endpoint endpoint(tcp::v4(), 13); tcp::acceptor acceptor(io_context, endpoint); for (;;) { tcp::iostream stream; boost::system::error_code ec; acceptor.accept(stream.socket(), ec); if (!ec) { stream << make_daytime_string(); } } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/iostreams/daytime_client.cpp
// // daytime_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 <string> #include <boost/asio.hpp> using boost::asio::ip::tcp; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: daytime_client <host>" << std::endl; return 1; } tcp::iostream s(argv[1], "daytime"); if (!s) { std::cout << "Unable to connect: " << s.error().message() << std::endl; return 1; } std::string line; std::getline(s, line); std::cout << line << std::endl; } catch (std::exception& e) { std::cout << "Exception: " << e.what() << std::endl; } return 0; }
cpp
asio
data/projects/asio/example/cpp11/icmp/icmp_header.hpp
// // icmp_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 ICMP_HEADER_HPP #define ICMP_HEADER_HPP #include <istream> #include <ostream> #include <algorithm> // ICMP header for both IPv4 and IPv6. // // The wire format of an ICMP header is: // // 0 8 16 31 // +---------------+---------------+------------------------------+ --- // | | | | ^ // | type | code | checksum | | // | | | | | // +---------------+---------------+------------------------------+ 8 bytes // | | | | // | identifier | sequence number | | // | | | v // +-------------------------------+------------------------------+ --- class icmp_header { public: enum { echo_reply = 0, destination_unreachable = 3, source_quench = 4, redirect = 5, echo_request = 8, time_exceeded = 11, parameter_problem = 12, timestamp_request = 13, timestamp_reply = 14, info_request = 15, info_reply = 16, address_request = 17, address_reply = 18 }; icmp_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); } unsigned char type() const { return rep_[0]; } unsigned char code() const { return rep_[1]; } unsigned short checksum() const { return decode(2, 3); } unsigned short identifier() const { return decode(4, 5); } unsigned short sequence_number() const { return decode(6, 7); } void type(unsigned char n) { rep_[0] = n; } void code(unsigned char n) { rep_[1] = n; } void checksum(unsigned short n) { encode(2, 3, n); } void identifier(unsigned short n) { encode(4, 5, n); } void sequence_number(unsigned short n) { encode(6, 7, n); } friend std::istream& operator>>(std::istream& is, icmp_header& header) { return is.read(reinterpret_cast<char*>(header.rep_), 8); } friend std::ostream& operator<<(std::ostream& os, const icmp_header& header) { return os.write(reinterpret_cast<const char*>(header.rep_), 8); } private: unsigned short decode(int a, int b) const { return (rep_[a] << 8) + rep_[b]; } void encode(int a, int b, unsigned short n) { rep_[a] = static_cast<unsigned char>(n >> 8); rep_[b] = static_cast<unsigned char>(n & 0xFF); } unsigned char rep_[8]; }; template <typename Iterator> void compute_checksum(icmp_header& header, Iterator body_begin, Iterator body_end) { unsigned int sum = (header.type() << 8) + header.code() + header.identifier() + header.sequence_number(); Iterator body_iter = body_begin; while (body_iter != body_end) { sum += (static_cast<unsigned char>(*body_iter++) << 8); if (body_iter != body_end) sum += static_cast<unsigned char>(*body_iter++); } sum = (sum >> 16) + (sum & 0xFFFF); sum += (sum >> 16); header.checksum(static_cast<unsigned short>(~sum)); } #endif // ICMP_HEADER_HPP
hpp
asio
data/projects/asio/example/cpp11/icmp/ping.cpp
// // ping.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 <boost/asio.hpp> #include <istream> #include <iostream> #include <ostream> #include "icmp_header.hpp" #include "ipv4_header.hpp" using boost::asio::ip::icmp; using boost::asio::steady_timer; namespace chrono = boost::asio::chrono; class pinger { public: pinger(boost::asio::io_context& io_context, const char* destination) : resolver_(io_context), socket_(io_context, icmp::v4()), timer_(io_context), sequence_number_(0), num_replies_(0) { destination_ = *resolver_.resolve(icmp::v4(), destination, "").begin(); start_send(); start_receive(); } private: void start_send() { std::string body("\"Hello!\" from Asio ping."); // Create an ICMP header for an echo request. icmp_header echo_request; echo_request.type(icmp_header::echo_request); echo_request.code(0); echo_request.identifier(get_identifier()); echo_request.sequence_number(++sequence_number_); compute_checksum(echo_request, body.begin(), body.end()); // Encode the request packet. boost::asio::streambuf request_buffer; std::ostream os(&request_buffer); os << echo_request << body; // Send the request. time_sent_ = steady_timer::clock_type::now(); socket_.send_to(request_buffer.data(), destination_); // Wait up to five seconds for a reply. num_replies_ = 0; timer_.expires_at(time_sent_ + chrono::seconds(5)); timer_.async_wait(std::bind(&pinger::handle_timeout, this)); } void handle_timeout() { if (num_replies_ == 0) std::cout << "Request timed out" << std::endl; // Requests must be sent no less than one second apart. timer_.expires_at(time_sent_ + chrono::seconds(1)); timer_.async_wait(std::bind(&pinger::start_send, this)); } void start_receive() { // Discard any data already in the buffer. reply_buffer_.consume(reply_buffer_.size()); // Wait for a reply. We prepare the buffer to receive up to 64KB. socket_.async_receive(reply_buffer_.prepare(65536), std::bind(&pinger::handle_receive, this, std::placeholders::_2)); } void handle_receive(std::size_t length) { // The actual number of bytes received is committed to the buffer so that we // can extract it using a std::istream object. reply_buffer_.commit(length); // Decode the reply packet. std::istream is(&reply_buffer_); ipv4_header ipv4_hdr; icmp_header icmp_hdr; is >> ipv4_hdr >> icmp_hdr; // We can receive all ICMP packets received by the host, so we need to // filter out only the echo replies that match the our identifier and // expected sequence number. if (is && icmp_hdr.type() == icmp_header::echo_reply && icmp_hdr.identifier() == get_identifier() && icmp_hdr.sequence_number() == sequence_number_) { // If this is the first reply, interrupt the five second timeout. if (num_replies_++ == 0) timer_.cancel(); // Print out some information about the reply packet. chrono::steady_clock::time_point now = chrono::steady_clock::now(); chrono::steady_clock::duration elapsed = now - time_sent_; std::cout << length - ipv4_hdr.header_length() << " bytes from " << ipv4_hdr.source_address() << ": icmp_seq=" << icmp_hdr.sequence_number() << ", ttl=" << ipv4_hdr.time_to_live() << ", time=" << chrono::duration_cast<chrono::milliseconds>(elapsed).count() << std::endl; } start_receive(); } static unsigned short get_identifier() { #if defined(BOOST_ASIO_WINDOWS) return static_cast<unsigned short>(::GetCurrentProcessId()); #else return static_cast<unsigned short>(::getpid()); #endif } icmp::resolver resolver_; icmp::endpoint destination_; icmp::socket socket_; steady_timer timer_; unsigned short sequence_number_; chrono::steady_clock::time_point time_sent_; boost::asio::streambuf reply_buffer_; std::size_t num_replies_; }; int main(int argc, char* argv[]) { try { if (argc != 2) { std::cerr << "Usage: ping <host>" << std::endl; #if !defined(BOOST_ASIO_WINDOWS) std::cerr << "(You may need to run this program as root.)" << std::endl; #endif return 1; } boost::asio::io_context io_context; pinger p(io_context, argv[1]); io_context.run(); } catch (std::exception& e) { std::cerr << "Exception: " << e.what() << std::endl; } }
cpp
asio
data/projects/asio/example/cpp11/icmp/ipv4_header.hpp
// // ipv4_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 IPV4_HEADER_HPP #define IPV4_HEADER_HPP #include <algorithm> #include <boost/asio/ip/address_v4.hpp> // Packet header for IPv4. // // The wire format of an IPv4 header is: // // 0 8 16 31 // +-------+-------+---------------+------------------------------+ --- // | | | | | ^ // |version|header | type of | total length in bytes | | // | (4) | length| service | | | // +-------+-------+---------------+-+-+-+------------------------+ | // | | | | | | | // | identification |0|D|M| fragment offset | | // | | |F|F| | | // +---------------+---------------+-+-+-+------------------------+ | // | | | | | // | time to live | protocol | header checksum | 20 bytes // | | | | | // +---------------+---------------+------------------------------+ | // | | | // | source IPv4 address | | // | | | // +--------------------------------------------------------------+ | // | | | // | destination IPv4 address | | // | | v // +--------------------------------------------------------------+ --- // | | ^ // | | | // / options (if any) / 0 - 40 // / / bytes // | | | // | | v // +--------------------------------------------------------------+ --- class ipv4_header { public: ipv4_header() { std::fill(rep_, rep_ + sizeof(rep_), 0); } unsigned char version() const { return (rep_[0] >> 4) & 0xF; } unsigned short header_length() const { return (rep_[0] & 0xF) * 4; } unsigned char type_of_service() const { return rep_[1]; } unsigned short total_length() const { return decode(2, 3); } unsigned short identification() const { return decode(4, 5); } bool dont_fragment() const { return (rep_[6] & 0x40) != 0; } bool more_fragments() const { return (rep_[6] & 0x20) != 0; } unsigned short fragment_offset() const { return decode(6, 7) & 0x1FFF; } unsigned int time_to_live() const { return rep_[8]; } unsigned char protocol() const { return rep_[9]; } unsigned short header_checksum() const { return decode(10, 11); } boost::asio::ip::address_v4 source_address() const { boost::asio::ip::address_v4::bytes_type bytes = { { rep_[12], rep_[13], rep_[14], rep_[15] } }; return boost::asio::ip::address_v4(bytes); } boost::asio::ip::address_v4 destination_address() const { boost::asio::ip::address_v4::bytes_type bytes = { { rep_[16], rep_[17], rep_[18], rep_[19] } }; return boost::asio::ip::address_v4(bytes); } friend std::istream& operator>>(std::istream& is, ipv4_header& header) { is.read(reinterpret_cast<char*>(header.rep_), 20); if (header.version() != 4) is.setstate(std::ios::failbit); std::streamsize options_length = header.header_length() - 20; if (options_length < 0 || options_length > 40) is.setstate(std::ios::failbit); else is.read(reinterpret_cast<char*>(header.rep_) + 20, options_length); return is; } private: unsigned short decode(int a, int b) const { return (rep_[a] << 8) + rep_[b]; } unsigned char rep_[60]; }; #endif // IPV4_HEADER_HPP
hpp