Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffered_read_stream_fwd.hpp
// // buffered_read_stream_fwd.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 ASIO_BUFFERED_READ_STREAM_FWD_HPP #define ASIO_BUFFERED_READ_STREAM_FWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) namespace asio { template <typename Stream> class buffered_read_stream; } // namespace asio #endif // ASIO_BUFFERED_READ_STREAM_FWD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/placeholders.hpp
// // placeholders.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 ASIO_PLACEHOLDERS_HPP #define ASIO_PLACEHOLDERS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/functional.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace placeholders { #if defined(GENERATING_DOCUMENTATION) /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the error argument of a handler for any of the asynchronous /// functions. unspecified error; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the bytes_transferred argument of a handler for asynchronous /// functions such as asio::basic_stream_socket::async_write_some or /// asio::async_write. unspecified bytes_transferred; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the iterator argument of a handler for asynchronous functions /// such as asio::async_connect. unspecified iterator; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the results argument of a handler for asynchronous functions /// such as asio::basic_resolver::async_resolve. unspecified results; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the results argument of a handler for asynchronous functions /// such as asio::async_connect. unspecified endpoint; /// An argument placeholder, for use with std::bind() or boost::bind(), that /// corresponds to the signal_number argument of a handler for asynchronous /// functions such as asio::signal_set::async_wait. unspecified signal_number; #else static ASIO_INLINE_VARIABLE constexpr auto& error = std::placeholders::_1; static ASIO_INLINE_VARIABLE constexpr auto& bytes_transferred = std::placeholders::_2; static ASIO_INLINE_VARIABLE constexpr auto& iterator = std::placeholders::_2; static ASIO_INLINE_VARIABLE constexpr auto& results = std::placeholders::_2; static ASIO_INLINE_VARIABLE constexpr auto& endpoint = std::placeholders::_2; static ASIO_INLINE_VARIABLE constexpr auto& signal_number = std::placeholders::_2; #endif } // namespace placeholders } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_PLACEHOLDERS_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/spawn.hpp
// // spawn.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 ASIO_SPAWN_HPP #define ASIO_SPAWN_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/any_io_executor.hpp" #include "asio/cancellation_signal.hpp" #include "asio/cancellation_state.hpp" #include "asio/detail/exception.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/type_traits.hpp" #include "asio/io_context.hpp" #include "asio/is_executor.hpp" #include "asio/strand.hpp" #if defined(ASIO_HAS_BOOST_COROUTINE) # include <boost/coroutine/all.hpp> #endif // defined(ASIO_HAS_BOOST_COROUTINE) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Base class for all spawn()-ed thread implementations. class spawned_thread_base { public: spawned_thread_base() : owner_(0), has_context_switched_(false), throw_if_cancelled_(false), terminal_(false) { } virtual ~spawned_thread_base() {} virtual void resume() = 0; virtual void suspend_with(void (*fn)(void*), void* arg) = 0; virtual void destroy() = 0; void attach(spawned_thread_base** owner) { owner_ = owner; *owner_ = this; } void detach() { if (owner_) *owner_ = 0; owner_ = 0; } void suspend() { suspend_with(0, 0); } template <typename F> void suspend_with(F f) { suspend_with(&spawned_thread_base::call<F>, &f); } cancellation_slot get_cancellation_slot() const noexcept { return cancellation_state_.slot(); } cancellation_state get_cancellation_state() const noexcept { return cancellation_state_; } void reset_cancellation_state() { cancellation_state_ = cancellation_state(parent_cancellation_slot_); } template <typename Filter> void reset_cancellation_state(Filter filter) { cancellation_state_ = cancellation_state( parent_cancellation_slot_, filter, filter); } template <typename InFilter, typename OutFilter> void reset_cancellation_state(InFilter in_filter, OutFilter out_filter) { cancellation_state_ = cancellation_state( parent_cancellation_slot_, in_filter, out_filter); } cancellation_type_t cancelled() const noexcept { return cancellation_state_.cancelled(); } bool has_context_switched() const noexcept { return has_context_switched_; } bool throw_if_cancelled() const noexcept { return throw_if_cancelled_; } void throw_if_cancelled(bool value) noexcept { throw_if_cancelled_ = value; } protected: spawned_thread_base** owner_; // Points to data member in active handler. asio::cancellation_slot parent_cancellation_slot_; asio::cancellation_state cancellation_state_; bool has_context_switched_; bool throw_if_cancelled_; bool terminal_; private: // Disallow copying and assignment. spawned_thread_base(const spawned_thread_base&) = delete; spawned_thread_base& operator=(const spawned_thread_base&) = delete; template <typename F> static void call(void* f) { (*static_cast<F*>(f))(); } }; template <typename T> struct spawn_signature { typedef void type(exception_ptr, T); }; template <> struct spawn_signature<void> { typedef void type(exception_ptr); }; template <typename Executor> class initiate_spawn; } // namespace detail /// A @ref completion_token that represents the currently executing coroutine. /** * The basic_yield_context class is a completion token type that is used to * represent the currently executing stackful coroutine. A basic_yield_context * object may be passed as a completion token to an asynchronous operation. For * example: * * @code template <typename Executor> * void my_coroutine(basic_yield_context<Executor> yield) * { * ... * std::size_t n = my_socket.async_read_some(buffer, yield); * ... * } @endcode * * The initiating function (async_read_some in the above example) suspends the * current coroutine. The coroutine is resumed when the asynchronous operation * completes, and the result of the operation is returned. */ template <typename Executor> class basic_yield_context { public: /// The executor type associated with the yield context. typedef Executor executor_type; /// The cancellation slot type associated with the yield context. typedef cancellation_slot cancellation_slot_type; /// Construct a yield context from another yield context type. /** * Requires that OtherExecutor be convertible to Executor. */ template <typename OtherExecutor> basic_yield_context(const basic_yield_context<OtherExecutor>& other, constraint_t< is_convertible<OtherExecutor, Executor>::value > = 0) : spawned_thread_(other.spawned_thread_), executor_(other.executor_), ec_(other.ec_) { } /// Get the executor associated with the yield context. executor_type get_executor() const noexcept { return executor_; } /// Get the cancellation slot associated with the coroutine. cancellation_slot_type get_cancellation_slot() const noexcept { return spawned_thread_->get_cancellation_slot(); } /// Get the cancellation state associated with the coroutine. cancellation_state get_cancellation_state() const noexcept { return spawned_thread_->get_cancellation_state(); } /// Reset the cancellation state associated with the coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as * <tt>S(P)</tt>, into the current coroutine's cancellation state object. */ void reset_cancellation_state() const { spawned_thread_->reset_cancellation_state(); } /// Reset the cancellation state associated with the coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as <tt>S(P, * std::forward<Filter>(filter))</tt>, into the current coroutine's * cancellation state object. */ template <typename Filter> void reset_cancellation_state(Filter&& filter) const { spawned_thread_->reset_cancellation_state( static_cast<Filter&&>(filter)); } /// Reset the cancellation state associated with the coroutine. /** * Let <tt>P</tt> be the cancellation slot associated with the current * coroutine's @ref spawn completion handler. Assigns a new * asio::cancellation_state object <tt>S</tt>, constructed as <tt>S(P, * std::forward<InFilter>(in_filter), * std::forward<OutFilter>(out_filter))</tt>, into the current coroutine's * cancellation state object. */ template <typename InFilter, typename OutFilter> void reset_cancellation_state(InFilter&& in_filter, OutFilter&& out_filter) const { spawned_thread_->reset_cancellation_state( static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)); } /// Determine whether the current coroutine has been cancelled. cancellation_type_t cancelled() const noexcept { return spawned_thread_->cancelled(); } /// Determine whether the coroutine throws if trying to suspend when it has /// been cancelled. bool throw_if_cancelled() const noexcept { return spawned_thread_->throw_if_cancelled(); } /// Set whether the coroutine throws if trying to suspend when it has been /// cancelled. void throw_if_cancelled(bool value) const noexcept { spawned_thread_->throw_if_cancelled(value); } /// Return a yield context that sets the specified error_code. /** * By default, when a yield context is used with an asynchronous operation, a * non-success error_code is converted to system_error and thrown. This * operator may be used to specify an error_code object that should instead be * set with the asynchronous operation's result. For example: * * @code template <typename Executor> * void my_coroutine(basic_yield_context<Executor> yield) * { * ... * std::size_t n = my_socket.async_read_some(buffer, yield[ec]); * if (ec) * { * // An error occurred. * } * ... * } @endcode */ basic_yield_context operator[](asio::error_code& ec) const { basic_yield_context tmp(*this); tmp.ec_ = &ec; return tmp; } #if !defined(GENERATING_DOCUMENTATION) //private: basic_yield_context(detail::spawned_thread_base* spawned_thread, const Executor& ex) : spawned_thread_(spawned_thread), executor_(ex), ec_(0) { } detail::spawned_thread_base* spawned_thread_; Executor executor_; asio::error_code* ec_; #endif // !defined(GENERATING_DOCUMENTATION) }; /// A @ref completion_token object that represents the currently executing /// coroutine. typedef basic_yield_context<any_io_executor> yield_context; /** * @defgroup spawn asio::spawn * * @brief Start a new stackful coroutine. * * The spawn() function is a high-level wrapper over the Boost.Coroutine * library. This function enables programs to implement asynchronous logic in a * synchronous manner, as illustrated by the following example: * * @code asio::spawn(my_strand, do_echo, asio::detached); * * // ... * * void do_echo(asio::yield_context yield) * { * try * { * char data[128]; * for (;;) * { * std::size_t length = * my_socket.async_read_some( * asio::buffer(data), yield); * * asio::async_write(my_socket, * asio::buffer(data, length), yield); * } * } * catch (std::exception& e) * { * // ... * } * } @endcode */ /*@{*/ /// Start a new stackful coroutine that executes on a given executor. /** * This function is used to launch a new stackful coroutine. * * @param ex Identifies the executor that will run the stackful coroutine. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename Executor, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken = default_completion_token_t<Executor>> auto spawn(const Executor& ex, F&& function, CompletionToken&& token = default_completion_token_t<Executor>(), #if defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< !is_same< decay_t<CompletionToken>, boost::coroutines::attributes >::value > = 0, #endif // defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type>( declval<detail::initiate_spawn<Executor>>(), token, static_cast<F&&>(function))); /// Start a new stackful coroutine that executes on a given execution context. /** * This function is used to launch a new stackful coroutine. * * @param ctx Identifies the execution context that will run the stackful * coroutine. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename ExecutionContext, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context< typename ExecutionContext::executor_type>)>>::type) CompletionToken = default_completion_token_t< typename ExecutionContext::executor_type>> auto spawn(ExecutionContext& ctx, F&& function, CompletionToken&& token = default_completion_token_t<typename ExecutionContext::executor_type>(), #if defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< !is_same< decay_t<CompletionToken>, boost::coroutines::attributes >::value > = 0, #endif // defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context< typename ExecutionContext::executor_type>)>>::type>( declval<detail::initiate_spawn< typename ExecutionContext::executor_type>>(), token, static_cast<F&&>(function))); /// Start a new stackful coroutine, inheriting the executor of another. /** * This function is used to launch a new stackful coroutine. * * @param ctx Identifies the current coroutine as a parent of the new * coroutine. This specifies that the new coroutine should inherit the executor * of the parent. For example, if the parent coroutine is executing in a * particular strand, then the new coroutine will execute in the same strand. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename Executor, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken = default_completion_token_t<Executor>> auto spawn(const basic_yield_context<Executor>& ctx, F&& function, CompletionToken&& token = default_completion_token_t<Executor>(), #if defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< !is_same< decay_t<CompletionToken>, boost::coroutines::attributes >::value > = 0, #endif // defined(ASIO_HAS_BOOST_COROUTINE) constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type>( declval<detail::initiate_spawn<Executor>>(), token, static_cast<F&&>(function))); #if defined(ASIO_HAS_BOOST_CONTEXT_FIBER) \ || defined(GENERATING_DOCUMENTATION) /// Start a new stackful coroutine that executes on a given executor. /** * This function is used to launch a new stackful coroutine using the * specified stack allocator. * * @param ex Identifies the executor that will run the stackful coroutine. * * @param stack_allocator Denotes the allocator to be used to allocate the * underlying coroutine's stack. The type must satisfy the stack-allocator * concept defined by the Boost.Context library. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename Executor, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken = default_completion_token_t<Executor>> auto spawn(const Executor& ex, allocator_arg_t, StackAllocator&& stack_allocator, F&& function, CompletionToken&& token = default_completion_token_t<Executor>(), constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type>( declval<detail::initiate_spawn<Executor>>(), token, allocator_arg_t(), static_cast<StackAllocator&&>(stack_allocator), static_cast<F&&>(function))); /// Start a new stackful coroutine that executes on a given execution context. /** * This function is used to launch a new stackful coroutine. * * @param ctx Identifies the execution context that will run the stackful * coroutine. * * @param stack_allocator Denotes the allocator to be used to allocate the * underlying coroutine's stack. The type must satisfy the stack-allocator * concept defined by the Boost.Context library. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename ExecutionContext, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context< typename ExecutionContext::executor_type>)>>::type) CompletionToken = default_completion_token_t< typename ExecutionContext::executor_type>> auto spawn(ExecutionContext& ctx, allocator_arg_t, StackAllocator&& stack_allocator, F&& function, CompletionToken&& token = default_completion_token_t<typename ExecutionContext::executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context< typename ExecutionContext::executor_type>)>>::type>( declval<detail::initiate_spawn< typename ExecutionContext::executor_type>>(), token, allocator_arg_t(), static_cast<StackAllocator&&>(stack_allocator), static_cast<F&&>(function))); /// Start a new stackful coroutine, inheriting the executor of another. /** * This function is used to launch a new stackful coroutine using the * specified stack allocator. * * @param ctx Identifies the current coroutine as a parent of the new * coroutine. This specifies that the new coroutine should inherit the * executor of the parent. For example, if the parent coroutine is executing * in a particular strand, then the new coroutine will execute in the same * strand. * * @param stack_allocator Denotes the allocator to be used to allocate the * underlying coroutine's stack. The type must satisfy the stack-allocator * concept defined by the Boost.Context library. * * @param function The coroutine function. The function must be callable the * signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param token The @ref completion_token that will handle the notification * that the coroutine has completed. If the return type @c R of @c function is * @c void, the function signature of the completion handler must be: * * @code void handler(std::exception_ptr); @endcode * Otherwise, the function signature of the completion handler must be: * @code void handler(std::exception_ptr, R); @endcode * * @par Completion Signature * @code void(std::exception_ptr, R) @endcode * where @c R is the return type of the function object. * * @par Per-Operation Cancellation * The new thread of execution is created with a cancellation state that * supports @c cancellation_type::terminal values only. To change the * cancellation state, call the basic_yield_context member function * @c reset_cancellation_state. */ template <typename Executor, typename StackAllocator, typename F, ASIO_COMPLETION_TOKEN_FOR(typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type) CompletionToken = default_completion_token_t<Executor>> auto spawn(const basic_yield_context<Executor>& ctx, allocator_arg_t, StackAllocator&& stack_allocator, F&& function, CompletionToken&& token = default_completion_token_t<Executor>(), constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) -> decltype( async_initiate<CompletionToken, typename detail::spawn_signature< result_of_t<F(basic_yield_context<Executor>)>>::type>( declval<detail::initiate_spawn<Executor>>(), token, allocator_arg_t(), static_cast<StackAllocator&&>(stack_allocator), static_cast<F&&>(function))); #endif // defined(ASIO_HAS_BOOST_CONTEXT_FIBER) // || defined(GENERATING_DOCUMENTATION) #if defined(ASIO_HAS_BOOST_COROUTINE) \ || defined(GENERATING_DOCUMENTATION) /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine, calling the specified handler when it completes. /** * This function is used to launch a new coroutine. * * @param function The coroutine function. The function must have the signature: * @code void function(basic_yield_context<Executor> yield); @endcode * where Executor is the associated executor type of @c Function. * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Function> void spawn(Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes()); /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine, calling the specified handler when it completes. /** * This function is used to launch a new coroutine. * * @param handler A handler to be called when the coroutine exits. More * importantly, the handler provides an execution context (via the the handler * invocation hook) for the coroutine. The handler must have the signature: * @code void handler(); @endcode * * @param function The coroutine function. The function must have the signature: * @code void function(basic_yield_context<Executor> yield); @endcode * where Executor is the associated executor type of @c Handler. * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Handler, typename Function> void spawn(Handler&& handler, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes(), constraint_t< !is_executor<decay_t<Handler>>::value && !execution::is_executor<decay_t<Handler>>::value && !is_convertible<Handler&, execution_context&>::value > = 0); /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine, inheriting the execution context of another. /** * This function is used to launch a new coroutine. * * @param ctx Identifies the current coroutine as a parent of the new * coroutine. This specifies that the new coroutine should inherit the * execution context of the parent. For example, if the parent coroutine is * executing in a particular strand, then the new coroutine will execute in the * same strand. * * @param function The coroutine function. The function must have the signature: * @code void function(basic_yield_context<Executor> yield); @endcode * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Executor, typename Function> void spawn(basic_yield_context<Executor> ctx, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes()); /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine that executes on a given executor. /** * This function is used to launch a new coroutine. * * @param ex Identifies the executor that will run the coroutine. The new * coroutine is automatically given its own explicit strand within this * executor. * * @param function The coroutine function. The function must have the signature: * @code void function(yield_context yield); @endcode * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Function, typename Executor> void spawn(const Executor& ex, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes(), constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0); /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine that executes on a given strand. /** * This function is used to launch a new coroutine. * * @param ex Identifies the strand that will run the coroutine. * * @param function The coroutine function. The function must have the signature: * @code void function(yield_context yield); @endcode * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Function, typename Executor> void spawn(const strand<Executor>& ex, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes()); #if !defined(ASIO_NO_TS_EXECUTORS) /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine that executes in the context of a strand. /** * This function is used to launch a new coroutine. * * @param s Identifies a strand. By starting multiple coroutines on the same * strand, the implementation ensures that none of those coroutines can execute * simultaneously. * * @param function The coroutine function. The function must have the signature: * @code void function(yield_context yield); @endcode * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Function> void spawn(const asio::io_context::strand& s, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes()); #endif // !defined(ASIO_NO_TS_EXECUTORS) /// (Deprecated: Use overloads with a completion token.) Start a new stackful /// coroutine that executes on a given execution context. /** * This function is used to launch a new coroutine. * * @param ctx Identifies the execution context that will run the coroutine. The * new coroutine is implicitly given its own strand within this execution * context. * * @param function The coroutine function. The function must have the signature: * @code void function(yield_context yield); @endcode * * @param attributes Boost.Coroutine attributes used to customise the coroutine. */ template <typename Function, typename ExecutionContext> void spawn(ExecutionContext& ctx, Function&& function, const boost::coroutines::attributes& attributes = boost::coroutines::attributes(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0); #endif // defined(ASIO_HAS_BOOST_COROUTINE) // || defined(GENERATING_DOCUMENTATION) /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/spawn.hpp" #endif // ASIO_SPAWN_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_socket_iostream.hpp
// // basic_socket_iostream.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 ASIO_BASIC_SOCKET_IOSTREAM_HPP #define ASIO_BASIC_SOCKET_IOSTREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_IOSTREAM) #include <istream> #include <ostream> #include "asio/basic_socket_streambuf.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // A separate base class is used to ensure that the streambuf is initialised // prior to the basic_socket_iostream's basic_iostream base class. template <typename Protocol, typename Clock, typename WaitTraits> class socket_iostream_base { protected: socket_iostream_base() { } socket_iostream_base(socket_iostream_base&& other) : streambuf_(std::move(other.streambuf_)) { } socket_iostream_base(basic_stream_socket<Protocol> s) : streambuf_(std::move(s)) { } socket_iostream_base& operator=(socket_iostream_base&& other) { streambuf_ = std::move(other.streambuf_); return *this; } basic_socket_streambuf<Protocol, Clock, WaitTraits> streambuf_; }; } // namespace detail #if !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) #define ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) class basic_socket_iostream; #endif // !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) /// Iostream interface for a socket. #if defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #else // defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock, typename WaitTraits> #endif // defined(GENERATING_DOCUMENTATION) class basic_socket_iostream : private detail::socket_iostream_base<Protocol, Clock, WaitTraits>, public std::basic_iostream<char> { private: // These typedefs are intended keep this class's implementation independent // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef WaitTraits traits_helper; #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef detail::chrono_time_traits<Clock, WaitTraits> traits_helper; #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) public: /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// The clock type. typedef Clock clock_type; #if defined(GENERATING_DOCUMENTATION) /// (Deprecated: Use time_point.) The time type. typedef typename WaitTraits::time_type time_type; /// The time type. typedef typename WaitTraits::time_point time_point; /// (Deprecated: Use duration.) The duration type. typedef typename WaitTraits::duration_type duration_type; /// The duration type. typedef typename WaitTraits::duration duration; #else # if !defined(ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_type; typedef typename traits_helper::duration_type duration_type; # endif // !defined(ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_point; typedef typename traits_helper::duration_type duration; #endif /// Construct a basic_socket_iostream without establishing a connection. basic_socket_iostream() : std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); } /// Construct a basic_socket_iostream from the supplied socket. explicit basic_socket_iostream(basic_stream_socket<protocol_type> s) : detail::socket_iostream_base< Protocol, Clock, WaitTraits>(std::move(s)), std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); } /// Move-construct a basic_socket_iostream from another. basic_socket_iostream(basic_socket_iostream&& other) : detail::socket_iostream_base< Protocol, Clock, WaitTraits>(std::move(other)), std::basic_iostream<char>(std::move(other)) { this->set_rdbuf(&this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_); } /// Move-assign a basic_socket_iostream from another. basic_socket_iostream& operator=(basic_socket_iostream&& other) { std::basic_iostream<char>::operator=(std::move(other)); detail::socket_iostream_base< Protocol, Clock, WaitTraits>::operator=(std::move(other)); return *this; } /// Establish a connection to an endpoint corresponding to a resolver query. /** * This constructor automatically establishes a connection based on the * supplied resolver query parameters. The arguments are used to construct * a resolver query object. */ template <typename... T> explicit basic_socket_iostream(T... x) : std::basic_iostream<char>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_) { this->setf(std::ios_base::unitbuf); if (rdbuf()->connect(x...) == 0) this->setstate(std::ios_base::failbit); } /// Establish a connection to an endpoint corresponding to a resolver query. /** * This function automatically establishes a connection based on the supplied * resolver query parameters. The arguments are used to construct a resolver * query object. */ template <typename... T> void connect(T... x) { if (rdbuf()->connect(x...) == 0) this->setstate(std::ios_base::failbit); } /// Close the connection. void close() { if (rdbuf()->close() == 0) this->setstate(std::ios_base::failbit); } /// Return a pointer to the underlying streambuf. basic_socket_streambuf<Protocol, Clock, WaitTraits>* rdbuf() const { return const_cast<basic_socket_streambuf<Protocol, Clock, WaitTraits>*>( &this->detail::socket_iostream_base< Protocol, Clock, WaitTraits>::streambuf_); } /// Get a reference to the underlying socket. basic_socket<Protocol>& socket() { return rdbuf()->socket(); } /// Get the last error associated with the stream. /** * @return An \c error_code corresponding to the last error from the stream. * * @par Example * To print the error associated with a failure to establish a connection: * @code tcp::iostream s("www.boost.org", "http"); * if (!s) * { * std::cout << "Error: " << s.error().message() << std::endl; * } @endcode */ const asio::error_code& error() const { return rdbuf()->error(); } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream's expiry time as an absolute /// time. /** * @return An absolute time value representing the stream's expiry time. */ time_point expires_at() const { return rdbuf()->expires_at(); } #endif // !defined(ASIO_NO_DEPRECATED) /// Get the stream's expiry time as an absolute time. /** * @return An absolute time value representing the stream's expiry time. */ time_point expiry() const { return rdbuf()->expiry(); } /// Set the stream's expiry time as an absolute time. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the stream. */ void expires_at(const time_point& expiry_time) { rdbuf()->expires_at(expiry_time); } /// Set the stream's expiry time relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_after(const duration& expiry_time) { rdbuf()->expires_after(expiry_time); } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream's expiry time relative to now. /** * @return A relative time value representing the stream's expiry time. */ duration expires_from_now() const { return rdbuf()->expires_from_now(); } /// (Deprecated: Use expires_after().) Set the stream's expiry time relative /// to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_from_now(const duration& expiry_time) { rdbuf()->expires_from_now(expiry_time); } #endif // !defined(ASIO_NO_DEPRECATED) private: // Disallow copying and assignment. basic_socket_iostream(const basic_socket_iostream&) = delete; basic_socket_iostream& operator=( const basic_socket_iostream&) = delete; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_NO_IOSTREAM) #endif // ASIO_BASIC_SOCKET_IOSTREAM_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/cancel_at.hpp
// // cancel_at.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 ASIO_CANCEL_AT_HPP #define ASIO_CANCEL_AT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/cancellation_type.hpp" #include "asio/detail/chrono.hpp" #include "asio/detail/type_traits.hpp" #include "asio/wait_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token adapter that cancels an operation at a given time. /** * The cancel_at_t class is used to indicate that an asynchronous operation * should be cancelled if not complete at the specified absolute time. */ template <typename CompletionToken, typename Clock, typename WaitTraits = asio::wait_traits<Clock>> class cancel_at_t { public: /// Constructor. template <typename T> cancel_at_t(T&& completion_token, const typename Clock::time_point& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) : token_(static_cast<T&&>(completion_token)), expiry_(expiry), cancel_type_(cancel_type) { } //private: CompletionToken token_; typename Clock::time_point expiry_; cancellation_type_t cancel_type_; }; /// A @ref completion_token adapter that cancels an operation at a given time. /** * The cancel_at_timer class is used to indicate that an asynchronous operation * should be cancelled if not complete at the specified absolute time. */ template <typename CompletionToken, typename Clock, typename WaitTraits = asio::wait_traits<Clock>, typename Executor = any_io_executor> class cancel_at_timer { public: /// Constructor. template <typename T> cancel_at_timer(T&& completion_token, basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const typename Clock::time_point& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) : token_(static_cast<T&&>(completion_token)), timer_(timer), expiry_(expiry), cancel_type_(cancel_type) { } //private: CompletionToken token_; basic_waitable_timer<Clock, WaitTraits, Executor>& timer_; typename Clock::time_point expiry_; cancellation_type_t cancel_type_; }; /// A function object type that adapts a @ref completion_token to cancel an /// operation at a given time. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Clock, typename WaitTraits = asio::wait_traits<Clock>> class partial_cancel_at { public: /// Constructor that specifies the expiry and cancellation type. explicit partial_cancel_at(const typename Clock::time_point& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) : expiry_(expiry), cancel_type_(cancel_type) { } /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> ASIO_NODISCARD inline constexpr cancel_at_t<decay_t<CompletionToken>, Clock, WaitTraits> operator()(CompletionToken&& completion_token) const { return cancel_at_t<decay_t<CompletionToken>, Clock, WaitTraits>( static_cast<CompletionToken&&>(completion_token), expiry_, cancel_type_); } //private: typename Clock::time_point expiry_; cancellation_type_t cancel_type_; }; /// A function object type that adapts a @ref completion_token to cancel an /// operation at a given time. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Clock, typename WaitTraits = asio::wait_traits<Clock>, typename Executor = any_io_executor> class partial_cancel_at_timer { public: /// Constructor that specifies the expiry and cancellation type. explicit partial_cancel_at_timer( basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const typename Clock::time_point& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) : timer_(timer), expiry_(expiry), cancel_type_(cancel_type) { } /// Adapt a @ref completion_token to specify that the completion handler /// arguments should be combined into a single tuple argument. template <typename CompletionToken> ASIO_NODISCARD inline cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor> operator()(CompletionToken&& completion_token) const { return cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timer_, expiry_, cancel_type_); } //private: basic_waitable_timer<Clock, WaitTraits, Executor>& timer_; typename Clock::time_point expiry_; cancellation_type_t cancel_type_; }; /// Create a partial completion token adapter that cancels an operation if not /// complete by the specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Clock, typename Duration> ASIO_NODISCARD inline partial_cancel_at<Clock> cancel_at(const chrono::time_point<Clock, Duration>& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) { return partial_cancel_at<Clock>(expiry, cancel_type); } /// Create a partial completion token adapter that cancels an operation if not /// complete by the specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename Clock, typename WaitTraits, typename Executor, typename Duration> ASIO_NODISCARD inline partial_cancel_at_timer<Clock, WaitTraits, Executor> cancel_at(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::time_point<Clock, Duration>& expiry, cancellation_type_t cancel_type = cancellation_type::terminal) { return partial_cancel_at_timer<Clock, WaitTraits, Executor>( timer, expiry, cancel_type); } /// Adapt a @ref completion_token to cancel an operation if not complete by the /// specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename CompletionToken, typename Clock, typename Duration> ASIO_NODISCARD inline cancel_at_t<decay_t<CompletionToken>, Clock> cancel_at(const chrono::time_point<Clock, Duration>& expiry, CompletionToken&& completion_token) { return cancel_at_t<decay_t<CompletionToken>, Clock>( static_cast<CompletionToken&&>(completion_token), expiry, cancellation_type::terminal); } /// Adapt a @ref completion_token to cancel an operation if not complete by the /// specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename CompletionToken, typename Clock, typename Duration> ASIO_NODISCARD inline cancel_at_t<decay_t<CompletionToken>, Clock> cancel_at(const chrono::time_point<Clock, Duration>& expiry, cancellation_type_t cancel_type, CompletionToken&& completion_token) { return cancel_at_t<decay_t<CompletionToken>, Clock>( static_cast<CompletionToken&&>(completion_token), expiry, cancel_type); } /// Adapt a @ref completion_token to cancel an operation if not complete by the /// specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename CompletionToken, typename Clock, typename WaitTraits, typename Executor, typename Duration> ASIO_NODISCARD inline cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor> cancel_at(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::time_point<Clock, Duration>& expiry, CompletionToken&& completion_token) { return cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timer, expiry, cancellation_type::terminal); } /// Adapt a @ref completion_token to cancel an operation if not complete by the /// specified absolute time. /** * @par Thread Safety * When an asynchronous operation is used with cancel_at, a timer async_wait * operation is performed in parallel to the main operation. If this parallel * async_wait completes first, a cancellation request is emitted to cancel the * main operation. Consequently, the application must ensure that the * asynchronous operation is performed within an implicit or explicit strand. */ template <typename CompletionToken, typename Clock, typename WaitTraits, typename Executor, typename Duration> ASIO_NODISCARD inline cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor> cancel_at(basic_waitable_timer<Clock, WaitTraits, Executor>& timer, const chrono::time_point<Clock, Duration>& expiry, cancellation_type_t cancel_type, CompletionToken&& completion_token) { return cancel_at_timer<decay_t<CompletionToken>, Clock, WaitTraits, Executor>( static_cast<CompletionToken&&>(completion_token), timer, expiry, cancel_type); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/cancel_at.hpp" #endif // ASIO_CANCEL_AT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/serial_port.hpp
// // serial_port.hpp // ~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected]) // // 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 ASIO_SERIAL_PORT_HPP #define ASIO_SERIAL_PORT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SERIAL_PORT) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_serial_port.hpp" namespace asio { /// Typedef for the typical usage of a serial port. typedef basic_serial_port<> serial_port; } // namespace asio #endif // defined(ASIO_HAS_SERIAL_PORT) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_SERIAL_PORT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/bind_immediate_executor.hpp
// // bind_immediate_executor.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 ASIO_BIND_IMMEDIATE_EXECUTOR_HPP #define ASIO_BIND_IMMEDIATE_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_executor.hpp" #include "asio/associated_immediate_executor.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiation_base.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper to automatically define nested typedef result_type. template <typename T, typename = void> struct immediate_executor_binder_result_type { protected: typedef void result_type_or_void; }; template <typename T> struct immediate_executor_binder_result_type<T, void_t<typename T::result_type>> { typedef typename T::result_type result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct immediate_executor_binder_result_type<R(*)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct immediate_executor_binder_result_type<R(&)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct immediate_executor_binder_result_type<R(*)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct immediate_executor_binder_result_type<R(&)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct immediate_executor_binder_result_type<R(*)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct immediate_executor_binder_result_type<R(&)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; // Helper to automatically define nested typedef argument_type. template <typename T, typename = void> struct immediate_executor_binder_argument_type {}; template <typename T> struct immediate_executor_binder_argument_type<T, void_t<typename T::argument_type>> { typedef typename T::argument_type argument_type; }; template <typename R, typename A1> struct immediate_executor_binder_argument_type<R(*)(A1)> { typedef A1 argument_type; }; template <typename R, typename A1> struct immediate_executor_binder_argument_type<R(&)(A1)> { typedef A1 argument_type; }; // Helper to automatically define nested typedefs first_argument_type and // second_argument_type. template <typename T, typename = void> struct immediate_executor_binder_argument_types {}; template <typename T> struct immediate_executor_binder_argument_types<T, void_t<typename T::first_argument_type>> { typedef typename T::first_argument_type first_argument_type; typedef typename T::second_argument_type second_argument_type; }; template <typename R, typename A1, typename A2> struct immediate_executor_binder_argument_type<R(*)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; template <typename R, typename A1, typename A2> struct immediate_executor_binder_argument_type<R(&)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; } // namespace detail /// A call wrapper type to bind a immediate executor of type @c Executor /// to an object of type @c T. template <typename T, typename Executor> class immediate_executor_binder #if !defined(GENERATING_DOCUMENTATION) : public detail::immediate_executor_binder_result_type<T>, public detail::immediate_executor_binder_argument_type<T>, public detail::immediate_executor_binder_argument_types<T> #endif // !defined(GENERATING_DOCUMENTATION) { public: /// The type of the target object. typedef T target_type; /// The type of the associated immediate executor. typedef Executor immediate_executor_type; #if defined(GENERATING_DOCUMENTATION) /// The return type if a function. /** * The type of @c result_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to function type, @c result_type is a synonym for * the return type of @c T; * * @li if @c T is a class type with a member type @c result_type, then @c * result_type is a synonym for @c T::result_type; * * @li otherwise @c result_type is not defined. */ typedef see_below result_type; /// The type of the function's argument. /** * The type of @c argument_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to a function type accepting a single argument, * @c argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c argument_type, then @c * argument_type is a synonym for @c T::argument_type; * * @li otherwise @c argument_type is not defined. */ typedef see_below argument_type; /// The type of the function's first argument. /** * The type of @c first_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * first_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c first_argument_type is a synonym for @c T::first_argument_type; * * @li otherwise @c first_argument_type is not defined. */ typedef see_below first_argument_type; /// The type of the function's second argument. /** * The type of @c second_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * second_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c second_argument_type is a synonym for @c T::second_argument_type; * * @li otherwise @c second_argument_type is not defined. */ typedef see_below second_argument_type; #endif // defined(GENERATING_DOCUMENTATION) /// Construct a immediate executor wrapper for the specified object. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U> immediate_executor_binder(const immediate_executor_type& e, U&& u) : executor_(e), target_(static_cast<U&&>(u)) { } /// Copy constructor. immediate_executor_binder(const immediate_executor_binder& other) : executor_(other.get_immediate_executor()), target_(other.get()) { } /// Construct a copy, but specify a different immediate executor. immediate_executor_binder(const immediate_executor_type& e, const immediate_executor_binder& other) : executor_(e), target_(other.get()) { } /// Construct a copy of a different immediate executor wrapper type. /** * This constructor is only valid if the @c Executor type is * constructible from type @c OtherExecutor, and the type @c T is * constructible from type @c U. */ template <typename U, typename OtherExecutor> immediate_executor_binder( const immediate_executor_binder<U, OtherExecutor>& other, constraint_t<is_constructible<Executor, OtherExecutor>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : executor_(other.get_immediate_executor()), target_(other.get()) { } /// Construct a copy of a different immediate executor wrapper type, but /// specify a different immediate executor. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U, typename OtherExecutor> immediate_executor_binder(const immediate_executor_type& e, const immediate_executor_binder<U, OtherExecutor>& other, constraint_t<is_constructible<T, U>::value> = 0) : executor_(e), target_(other.get()) { } /// Move constructor. immediate_executor_binder(immediate_executor_binder&& other) : executor_(static_cast<immediate_executor_type&&>( other.get_immediate_executor())), target_(static_cast<T&&>(other.get())) { } /// Move construct the target object, but specify a different immediate /// executor. immediate_executor_binder(const immediate_executor_type& e, immediate_executor_binder&& other) : executor_(e), target_(static_cast<T&&>(other.get())) { } /// Move construct from a different immediate executor wrapper type. template <typename U, typename OtherExecutor> immediate_executor_binder( immediate_executor_binder<U, OtherExecutor>&& other, constraint_t<is_constructible<Executor, OtherExecutor>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : executor_(static_cast<OtherExecutor&&>( other.get_immediate_executor())), target_(static_cast<U&&>(other.get())) { } /// Move construct from a different immediate executor wrapper type, but /// specify a different immediate executor. template <typename U, typename OtherExecutor> immediate_executor_binder(const immediate_executor_type& e, immediate_executor_binder<U, OtherExecutor>&& other, constraint_t<is_constructible<T, U>::value> = 0) : executor_(e), target_(static_cast<U&&>(other.get())) { } /// Destructor. ~immediate_executor_binder() { } /// Obtain a reference to the target object. target_type& get() noexcept { return target_; } /// Obtain a reference to the target object. const target_type& get() const noexcept { return target_; } /// Obtain the associated immediate executor. immediate_executor_type get_immediate_executor() const noexcept { return executor_; } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) { return target_(static_cast<Args&&>(args)...); } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) const { return target_(static_cast<Args&&>(args)...); } private: Executor executor_; T target_; }; /// A function object type that adapts a @ref completion_token to specify that /// the completion handler should have the supplied executor as its associated /// immediate executor. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Executor> struct partial_immediate_executor_binder { /// Constructor that specifies associated executor. explicit partial_immediate_executor_binder(const Executor& ex) : executor_(ex) { } /// Adapt a @ref completion_token to specify that the completion handler /// should have the executor as its associated immediate executor. template <typename CompletionToken> ASIO_NODISCARD inline constexpr immediate_executor_binder<decay_t<CompletionToken>, Executor> operator()(CompletionToken&& completion_token) const { return immediate_executor_binder<decay_t<CompletionToken>, Executor>( static_cast<CompletionToken&&>(completion_token), executor_); } //private: Executor executor_; }; /// Create a partial completion token that associates an executor. template <typename Executor> ASIO_NODISCARD inline partial_immediate_executor_binder<Executor> bind_immediate_executor(const Executor& ex) { return partial_immediate_executor_binder<Executor>(ex); } /// Associate an object of type @c T with a immediate executor of type /// @c Executor. template <typename Executor, typename T> ASIO_NODISCARD inline immediate_executor_binder<decay_t<T>, Executor> bind_immediate_executor(const Executor& e, T&& t) { return immediate_executor_binder< decay_t<T>, Executor>( e, static_cast<T&&>(t)); } #if !defined(GENERATING_DOCUMENTATION) namespace detail { template <typename TargetAsyncResult, typename Executor, typename = void> class immediate_executor_binder_completion_handler_async_result { public: template <typename T> explicit immediate_executor_binder_completion_handler_async_result(T&) { } }; template <typename TargetAsyncResult, typename Executor> class immediate_executor_binder_completion_handler_async_result< TargetAsyncResult, Executor, void_t< typename TargetAsyncResult::completion_handler_type >> { private: TargetAsyncResult target_; public: typedef immediate_executor_binder< typename TargetAsyncResult::completion_handler_type, Executor> completion_handler_type; explicit immediate_executor_binder_completion_handler_async_result( typename TargetAsyncResult::completion_handler_type& handler) : target_(handler) { } auto get() -> decltype(target_.get()) { return target_.get(); } }; template <typename TargetAsyncResult, typename = void> struct immediate_executor_binder_async_result_return_type { }; template <typename TargetAsyncResult> struct immediate_executor_binder_async_result_return_type< TargetAsyncResult, void_t< typename TargetAsyncResult::return_type >> { typedef typename TargetAsyncResult::return_type return_type; }; } // namespace detail template <typename T, typename Executor, typename Signature> class async_result<immediate_executor_binder<T, Executor>, Signature> : public detail::immediate_executor_binder_completion_handler_async_result< async_result<T, Signature>, Executor>, public detail::immediate_executor_binder_async_result_return_type< async_result<T, Signature>> { public: explicit async_result(immediate_executor_binder<T, Executor>& b) : detail::immediate_executor_binder_completion_handler_async_result< async_result<T, Signature>, Executor>(b.get()) { } template <typename Initiation> struct init_wrapper : detail::initiation_base<Initiation> { using detail::initiation_base<Initiation>::initiation_base; template <typename Handler, typename... Args> void operator()(Handler&& handler, const Executor& e, Args&&... args) && { static_cast<Initiation&&>(*this)( immediate_executor_binder< decay_t<Handler>, Executor>( e, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, const Executor& e, Args&&... args) const & { static_cast<const Initiation&>(*this)( immediate_executor_binder< decay_t<Handler>, Executor>( e, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), token.get_immediate_executor(), static_cast<Args&&>(args)...)) { return async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( init_wrapper<decay_t<Initiation>>( static_cast<Initiation&&>(initiation)), token.get(), token.get_immediate_executor(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; async_result<T, Signature> target_; }; template <typename Executor, typename... Signatures> struct async_result<partial_immediate_executor_binder<Executor>, Signatures...> { template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), immediate_executor_binder< default_completion_token_t<associated_executor_t<Initiation>>, Executor>(token.executor_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...)) { return async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), immediate_executor_binder< default_completion_token_t<associated_executor_t<Initiation>>, Executor>(token.executor_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...); } }; template <template <typename, typename> class Associator, typename T, typename Executor, typename DefaultCandidate> struct associator<Associator, immediate_executor_binder<T, Executor>, DefaultCandidate> : Associator<T, DefaultCandidate> { static typename Associator<T, DefaultCandidate>::type get( const immediate_executor_binder<T, Executor>& b) noexcept { return Associator<T, DefaultCandidate>::get(b.get()); } static auto get(const immediate_executor_binder<T, Executor>& b, const DefaultCandidate& c) noexcept -> decltype(Associator<T, DefaultCandidate>::get(b.get(), c)) { return Associator<T, DefaultCandidate>::get(b.get(), c); } }; template <typename T, typename Executor, typename Executor1> struct associated_immediate_executor< immediate_executor_binder<T, Executor>, Executor1> { typedef Executor type; static auto get(const immediate_executor_binder<T, Executor>& b, const Executor1& = Executor1()) noexcept -> decltype(b.get_immediate_executor()) { return b.get_immediate_executor(); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BIND_IMMEDIATE_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_socket_streambuf.hpp
// // basic_socket_streambuf.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 ASIO_BASIC_SOCKET_STREAMBUF_HPP #define ASIO_BASIC_SOCKET_STREAMBUF_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_IOSTREAM) #include <streambuf> #include <vector> #include "asio/basic_socket.hpp" #include "asio/basic_stream_socket.hpp" #include "asio/detail/buffer_sequence_adapter.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/throw_error.hpp" #include "asio/io_context.hpp" #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) # include "asio/detail/deadline_timer_service.hpp" #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) # include "asio/steady_timer.hpp" #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // A separate base class is used to ensure that the io_context member is // initialised prior to the basic_socket_streambuf's basic_socket base class. class socket_streambuf_io_context { protected: socket_streambuf_io_context(io_context* ctx) : default_io_context_(ctx) { } shared_ptr<io_context> default_io_context_; }; // A separate base class is used to ensure that the dynamically allocated // buffers are constructed prior to the basic_socket_streambuf's basic_socket // base class. This makes moving the socket is the last potentially throwing // step in the streambuf's move constructor, giving the constructor a strong // exception safety guarantee. class socket_streambuf_buffers { protected: socket_streambuf_buffers() : get_buffer_(buffer_size), put_buffer_(buffer_size) { } enum { buffer_size = 512 }; std::vector<char> get_buffer_; std::vector<char> put_buffer_; }; } // namespace detail #if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) #define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) class basic_socket_streambuf; #endif // !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) /// Iostream streambuf for a socket. #if defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #else // defined(GENERATING_DOCUMENTATION) template <typename Protocol, typename Clock, typename WaitTraits> #endif // defined(GENERATING_DOCUMENTATION) class basic_socket_streambuf : public std::streambuf, private detail::socket_streambuf_io_context, private detail::socket_streambuf_buffers, #if defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) private basic_socket<Protocol> #else // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) public basic_socket<Protocol> #endif // defined(ASIO_NO_DEPRECATED) || defined(GENERATING_DOCUMENTATION) { private: // These typedefs are intended keep this class's implementation independent // of whether it's using Boost.DateClock, Boost.Chrono or std::chrono. #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef WaitTraits traits_helper; #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) typedef detail::chrono_time_traits<Clock, WaitTraits> traits_helper; #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) public: /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// The clock type. typedef Clock clock_type; #if defined(GENERATING_DOCUMENTATION) /// (Deprecated: Use time_point.) The time type. typedef typename WaitTraits::time_type time_type; /// The time type. typedef typename WaitTraits::time_point time_point; /// (Deprecated: Use duration.) The duration type. typedef typename WaitTraits::duration_type duration_type; /// The duration type. typedef typename WaitTraits::duration duration; #else # if !defined(ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_type; typedef typename traits_helper::duration_type duration_type; # endif // !defined(ASIO_NO_DEPRECATED) typedef typename traits_helper::time_type time_point; typedef typename traits_helper::duration_type duration; #endif /// Construct a basic_socket_streambuf without establishing a connection. basic_socket_streambuf() : detail::socket_streambuf_io_context(new io_context), basic_socket<Protocol>(*default_io_context_), expiry_time_(max_expiry_time()) { init_buffers(); } /// Construct a basic_socket_streambuf from the supplied socket. explicit basic_socket_streambuf(basic_stream_socket<protocol_type> s) : detail::socket_streambuf_io_context(0), basic_socket<Protocol>(std::move(s)), expiry_time_(max_expiry_time()) { init_buffers(); } /// Move-construct a basic_socket_streambuf from another. basic_socket_streambuf(basic_socket_streambuf&& other) : detail::socket_streambuf_io_context(other), basic_socket<Protocol>(std::move(other.socket())), ec_(other.ec_), expiry_time_(other.expiry_time_) { get_buffer_.swap(other.get_buffer_); put_buffer_.swap(other.put_buffer_); setg(other.eback(), other.gptr(), other.egptr()); setp(other.pptr(), other.epptr()); other.ec_ = asio::error_code(); other.expiry_time_ = max_expiry_time(); other.init_buffers(); } /// Move-assign a basic_socket_streambuf from another. basic_socket_streambuf& operator=(basic_socket_streambuf&& other) { this->close(); socket() = std::move(other.socket()); detail::socket_streambuf_io_context::operator=(other); ec_ = other.ec_; expiry_time_ = other.expiry_time_; get_buffer_.swap(other.get_buffer_); put_buffer_.swap(other.put_buffer_); setg(other.eback(), other.gptr(), other.egptr()); setp(other.pptr(), other.epptr()); other.ec_ = asio::error_code(); other.expiry_time_ = max_expiry_time(); other.put_buffer_.resize(buffer_size); other.init_buffers(); return *this; } /// Destructor flushes buffered data. virtual ~basic_socket_streambuf() { if (pptr() != pbase()) overflow(traits_type::eof()); } /// Establish a connection. /** * This function establishes a connection to the specified endpoint. * * @return \c this if a connection was successfully established, a null * pointer otherwise. */ basic_socket_streambuf* connect(const endpoint_type& endpoint) { init_buffers(); ec_ = asio::error_code(); this->connect_to_endpoints(&endpoint, &endpoint + 1); return !ec_ ? this : 0; } /// Establish a connection. /** * This function automatically establishes a connection based on the supplied * resolver query parameters. The arguments are used to construct a resolver * query object. * * @return \c this if a connection was successfully established, a null * pointer otherwise. */ template <typename... T> basic_socket_streambuf* connect(T... x) { init_buffers(); typedef typename Protocol::resolver resolver_type; resolver_type resolver(socket().get_executor()); connect_to_endpoints(resolver.resolve(x..., ec_)); return !ec_ ? this : 0; } /// Close the connection. /** * @return \c this if a connection was successfully established, a null * pointer otherwise. */ basic_socket_streambuf* close() { sync(); socket().close(ec_); if (!ec_) init_buffers(); return !ec_ ? this : 0; } /// Get a reference to the underlying socket. basic_socket<Protocol>& socket() { return *this; } /// Get the last error associated with the stream buffer. /** * @return An \c error_code corresponding to the last error from the stream * buffer. */ const asio::error_code& error() const { return ec_; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use error().) Get the last error associated with the stream /// buffer. /** * @return An \c error_code corresponding to the last error from the stream * buffer. */ const asio::error_code& puberror() const { return error(); } /// (Deprecated: Use expiry().) Get the stream buffer's expiry time as an /// absolute time. /** * @return An absolute time value representing the stream buffer's expiry * time. */ time_point expires_at() const { return expiry_time_; } #endif // !defined(ASIO_NO_DEPRECATED) /// Get the stream buffer's expiry time as an absolute time. /** * @return An absolute time value representing the stream buffer's expiry * time. */ time_point expiry() const { return expiry_time_; } /// Set the stream buffer's expiry time as an absolute time. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the stream. */ void expires_at(const time_point& expiry_time) { expiry_time_ = expiry_time; } /// Set the stream buffer's expiry time relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_after(const duration& expiry_time) { expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use expiry().) Get the stream buffer's expiry time relative /// to now. /** * @return A relative time value representing the stream buffer's expiry time. */ duration expires_from_now() const { return traits_helper::subtract(expires_at(), traits_helper::now()); } /// (Deprecated: Use expires_after().) Set the stream buffer's expiry time /// relative to now. /** * This function sets the expiry time associated with the stream. Stream * operations performed after this time (where the operations cannot be * completed using the internal buffers) will fail with the error * asio::error::operation_aborted. * * @param expiry_time The expiry time to be used for the timer. */ void expires_from_now(const duration& expiry_time) { expiry_time_ = traits_helper::add(traits_helper::now(), expiry_time); } #endif // !defined(ASIO_NO_DEPRECATED) protected: int_type underflow() { #if defined(ASIO_WINDOWS_RUNTIME) ec_ = asio::error::operation_not_supported; return traits_type::eof(); #else // defined(ASIO_WINDOWS_RUNTIME) if (gptr() != egptr()) return traits_type::eof(); for (;;) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = asio::error::timed_out; return traits_type::eof(); } // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::buffer_sequence_adapter<mutable_buffer, mutable_buffer> bufs(asio::buffer(get_buffer_) + putback_max); detail::signed_size_type bytes = detail::socket_ops::recv( socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); // Check if operation succeeded. if (bytes > 0) { setg(&get_buffer_[0], &get_buffer_[0] + putback_max, &get_buffer_[0] + putback_max + bytes); return traits_type::to_int_type(*gptr()); } // Check for EOF. if (bytes == 0) { ec_ = asio::error::eof; return traits_type::eof(); } // Operation failed. if (ec_ != asio::error::would_block && ec_ != asio::error::try_again) return traits_type::eof(); // Wait for socket to become ready. if (detail::socket_ops::poll_read( socket().native_handle(), 0, timeout(), ec_) < 0) return traits_type::eof(); } #endif // defined(ASIO_WINDOWS_RUNTIME) } int_type overflow(int_type c) { #if defined(ASIO_WINDOWS_RUNTIME) ec_ = asio::error::operation_not_supported; return traits_type::eof(); #else // defined(ASIO_WINDOWS_RUNTIME) char_type ch = traits_type::to_char_type(c); // Determine what needs to be sent. const_buffer output_buffer; if (put_buffer_.empty()) { if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::not_eof(c); // Nothing to do. output_buffer = asio::buffer(&ch, sizeof(char_type)); } else { output_buffer = asio::buffer(pbase(), (pptr() - pbase()) * sizeof(char_type)); } while (output_buffer.size() > 0) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = asio::error::timed_out; return traits_type::eof(); } // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::buffer_sequence_adapter< const_buffer, const_buffer> bufs(output_buffer); detail::signed_size_type bytes = detail::socket_ops::send( socket().native_handle(), bufs.buffers(), bufs.count(), 0, ec_); // Check if operation succeeded. if (bytes > 0) { output_buffer += static_cast<std::size_t>(bytes); continue; } // Operation failed. if (ec_ != asio::error::would_block && ec_ != asio::error::try_again) return traits_type::eof(); // Wait for socket to become ready. if (detail::socket_ops::poll_write( socket().native_handle(), 0, timeout(), ec_) < 0) return traits_type::eof(); } if (!put_buffer_.empty()) { setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); // If the new character is eof then our work here is done. if (traits_type::eq_int_type(c, traits_type::eof())) return traits_type::not_eof(c); // Add the new character to the output buffer. *pptr() = ch; pbump(1); } return c; #endif // defined(ASIO_WINDOWS_RUNTIME) } int sync() { return overflow(traits_type::eof()); } std::streambuf* setbuf(char_type* s, std::streamsize n) { if (pptr() == pbase() && s == 0 && n == 0) { put_buffer_.clear(); setp(0, 0); sync(); return this; } return 0; } private: // Disallow copying and assignment. basic_socket_streambuf(const basic_socket_streambuf&) = delete; basic_socket_streambuf& operator=( const basic_socket_streambuf&) = delete; void init_buffers() { setg(&get_buffer_[0], &get_buffer_[0] + putback_max, &get_buffer_[0] + putback_max); if (put_buffer_.empty()) setp(0, 0); else setp(&put_buffer_[0], &put_buffer_[0] + put_buffer_.size()); } int timeout() const { int64_t msec = traits_helper::to_posix_duration( traits_helper::subtract(expiry_time_, traits_helper::now())).total_milliseconds(); if (msec > (std::numeric_limits<int>::max)()) msec = (std::numeric_limits<int>::max)(); else if (msec < 0) msec = 0; return static_cast<int>(msec); } template <typename EndpointSequence> void connect_to_endpoints(const EndpointSequence& endpoints) { this->connect_to_endpoints(endpoints.begin(), endpoints.end()); } template <typename EndpointIterator> void connect_to_endpoints(EndpointIterator begin, EndpointIterator end) { #if defined(ASIO_WINDOWS_RUNTIME) ec_ = asio::error::operation_not_supported; #else // defined(ASIO_WINDOWS_RUNTIME) if (ec_) return; ec_ = asio::error::not_found; for (EndpointIterator i = begin; i != end; ++i) { // Check if we are past the expiry time. if (traits_helper::less_than(expiry_time_, traits_helper::now())) { ec_ = asio::error::timed_out; return; } // Close and reopen the socket. typename Protocol::endpoint ep(*i); socket().close(ec_); socket().open(ep.protocol(), ec_); if (ec_) continue; // Try to complete the operation without blocking. if (!socket().native_non_blocking()) socket().native_non_blocking(true, ec_); detail::socket_ops::connect(socket().native_handle(), ep.data(), ep.size(), ec_); // Check if operation succeeded. if (!ec_) return; // Operation failed. if (ec_ != asio::error::in_progress && ec_ != asio::error::would_block) continue; // Wait for socket to become ready. if (detail::socket_ops::poll_connect( socket().native_handle(), timeout(), ec_) < 0) continue; // Get the error code from the connect operation. int connect_error = 0; size_t connect_error_len = sizeof(connect_error); if (detail::socket_ops::getsockopt(socket().native_handle(), 0, SOL_SOCKET, SO_ERROR, &connect_error, &connect_error_len, ec_) == detail::socket_error_retval) return; // Check the result of the connect operation. ec_ = asio::error_code(connect_error, asio::error::get_system_category()); if (!ec_) return; } #endif // defined(ASIO_WINDOWS_RUNTIME) } // Helper function to get the maximum expiry time. static time_point max_expiry_time() { #if defined(ASIO_HAS_BOOST_DATE_TIME) \ && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) return boost::posix_time::pos_infin; #else // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) return (time_point::max)(); #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // && defined(ASIO_USE_BOOST_DATE_TIME_FOR_SOCKET_IOSTREAM) } enum { putback_max = 8 }; asio::error_code ec_; time_point expiry_time_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_NO_IOSTREAM) #endif // ASIO_BASIC_SOCKET_STREAMBUF_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/cancellation_state.hpp
// // cancellation_state.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 ASIO_CANCELLATION_STATE_HPP #define ASIO_CANCELLATION_STATE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cassert> #include <new> #include <utility> #include "asio/cancellation_signal.hpp" #include "asio/detail/cstddef.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A simple cancellation signal propagation filter. template <cancellation_type_t Mask> struct cancellation_filter { /// Returns <tt>type & Mask</tt>. cancellation_type_t operator()( cancellation_type_t type) const noexcept { return type & Mask; } }; /// A cancellation filter that disables cancellation. typedef cancellation_filter<cancellation_type::none> disable_cancellation; /// A cancellation filter that enables terminal cancellation only. typedef cancellation_filter<cancellation_type::terminal> enable_terminal_cancellation; #if defined(GENERATING_DOCUMENTATION) /// A cancellation filter that enables terminal and partial cancellation. typedef cancellation_filter< cancellation_type::terminal | cancellation_type::partial> enable_partial_cancellation; /// A cancellation filter that enables terminal, partial and total cancellation. typedef cancellation_filter<cancellation_type::terminal | cancellation_type::partial | cancellation_type::total> enable_total_cancellation; #else // defined(GENERATING_DOCUMENTATION) typedef cancellation_filter< static_cast<cancellation_type_t>( static_cast<unsigned int>(cancellation_type::terminal) | static_cast<unsigned int>(cancellation_type::partial))> enable_partial_cancellation; typedef cancellation_filter< static_cast<cancellation_type_t>( static_cast<unsigned int>(cancellation_type::terminal) | static_cast<unsigned int>(cancellation_type::partial) | static_cast<unsigned int>(cancellation_type::total))> enable_total_cancellation; #endif // defined(GENERATING_DOCUMENTATION) /// A cancellation state is used for chaining signals and slots in compositions. class cancellation_state { public: /// Construct a disconnected cancellation state. constexpr cancellation_state() noexcept : impl_(0) { } /// Construct and attach to a parent slot to create a new child slot. /** * Initialises the cancellation state so that it allows terminal cancellation * only. Equivalent to <tt>cancellation_state(slot, * enable_terminal_cancellation())</tt>. * * @param slot The parent cancellation slot to which the state will be * attached. */ template <typename CancellationSlot> constexpr explicit cancellation_state(CancellationSlot slot) : impl_(slot.is_connected() ? &slot.template emplace<impl<>>() : 0) { } /// Construct and attach to a parent slot to create a new child slot. /** * @param slot The parent cancellation slot to which the state will be * attached. * * @param filter A function object that is used to transform incoming * cancellation signals as they are received from the parent slot. This * function object must have the signature: * @code asio::cancellation_type_t filter( * asio::cancellation_type_t); @endcode * * The library provides the following pre-defined cancellation filters: * * @li asio::disable_cancellation * @li asio::enable_terminal_cancellation * @li asio::enable_partial_cancellation * @li asio::enable_total_cancellation */ template <typename CancellationSlot, typename Filter> constexpr cancellation_state(CancellationSlot slot, Filter filter) : impl_(slot.is_connected() ? &slot.template emplace<impl<Filter, Filter>>(filter, filter) : 0) { } /// Construct and attach to a parent slot to create a new child slot. /** * @param slot The parent cancellation slot to which the state will be * attached. * * @param in_filter A function object that is used to transform incoming * cancellation signals as they are received from the parent slot. This * function object must have the signature: * @code asio::cancellation_type_t in_filter( * asio::cancellation_type_t); @endcode * * @param out_filter A function object that is used to transform outcoming * cancellation signals as they are relayed to the child slot. This function * object must have the signature: * @code asio::cancellation_type_t out_filter( * asio::cancellation_type_t); @endcode * * The library provides the following pre-defined cancellation filters: * * @li asio::disable_cancellation * @li asio::enable_terminal_cancellation * @li asio::enable_partial_cancellation * @li asio::enable_total_cancellation */ template <typename CancellationSlot, typename InFilter, typename OutFilter> constexpr cancellation_state(CancellationSlot slot, InFilter in_filter, OutFilter out_filter) : impl_(slot.is_connected() ? &slot.template emplace<impl<InFilter, OutFilter>>( static_cast<InFilter&&>(in_filter), static_cast<OutFilter&&>(out_filter)) : 0) { } /// Returns the single child slot associated with the state. /** * This sub-slot is used with the operations that are being composed. */ constexpr cancellation_slot slot() const noexcept { return impl_ ? impl_->signal_.slot() : cancellation_slot(); } /// Returns the cancellation types that have been triggered. cancellation_type_t cancelled() const noexcept { return impl_ ? impl_->cancelled_ : cancellation_type_t(); } /// Clears the specified cancellation types, if they have been triggered. void clear(cancellation_type_t mask = cancellation_type::all) noexcept { if (impl_) impl_->cancelled_ &= ~mask; } private: struct impl_base { impl_base() : cancelled_() { } cancellation_signal signal_; cancellation_type_t cancelled_; }; template < typename InFilter = enable_terminal_cancellation, typename OutFilter = InFilter> struct impl : impl_base { impl() : in_filter_(), out_filter_() { } impl(InFilter in_filter, OutFilter out_filter) : in_filter_(static_cast<InFilter&&>(in_filter)), out_filter_(static_cast<OutFilter&&>(out_filter)) { } void operator()(cancellation_type_t in) { this->cancelled_ = in_filter_(in); cancellation_type_t out = out_filter_(this->cancelled_); if (out != cancellation_type::none) this->signal_.emit(out); } InFilter in_filter_; OutFilter out_filter_; }; impl_base* impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_CANCELLATION_STATE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/thread.hpp
// // thread.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 ASIO_THREAD_HPP #define ASIO_THREAD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/thread.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A simple abstraction for starting threads. /** * The asio::thread class implements the smallest possible subset of the * functionality of boost::thread. It is intended to be used only for starting * a thread and waiting for it to exit. If more extensive threading * capabilities are required, you are strongly advised to use something else. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Example * A typical use of asio::thread would be to launch a thread to run an * io_context's event processing loop: * * @par * @code asio::io_context io_context; * // ... * asio::thread t(boost::bind(&asio::io_context::run, &io_context)); * // ... * t.join(); @endcode */ class thread : private noncopyable { public: /// Start a new thread that executes the supplied function. /** * This constructor creates a new thread that will execute the given function * or function object. * * @param f The function or function object to be run in the thread. The * function signature must be: @code void f(); @endcode */ template <typename Function> explicit thread(Function f) : impl_(f) { } /// Destructor. ~thread() { } /// Wait for the thread to exit. /** * This function will block until the thread has exited. * * If this function is not called before the thread object is destroyed, the * thread itself will continue to run until completion. You will, however, * no longer have the ability to wait for it to exit. */ void join() { impl_.join(); } private: detail::thread impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_THREAD_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/streambuf.hpp
// // streambuf.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 ASIO_STREAMBUF_HPP #define ASIO_STREAMBUF_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_IOSTREAM) #include "asio/basic_streambuf.hpp" namespace asio { /// Typedef for the typical usage of basic_streambuf. typedef basic_streambuf<> streambuf; } // namespace asio #endif // !defined(ASIO_NO_IOSTREAM) #endif // ASIO_STREAMBUF_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/bind_executor.hpp
// // bind_executor.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 ASIO_BIND_EXECUTOR_HPP #define ASIO_BIND_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/associated_executor.hpp" #include "asio/associator.hpp" #include "asio/async_result.hpp" #include "asio/detail/initiation_base.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/executor.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/uses_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper to automatically define nested typedef result_type. template <typename T, typename = void> struct executor_binder_result_type { protected: typedef void result_type_or_void; }; template <typename T> struct executor_binder_result_type<T, void_t<typename T::result_type>> { typedef typename T::result_type result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct executor_binder_result_type<R(*)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R> struct executor_binder_result_type<R(&)()> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct executor_binder_result_type<R(*)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1> struct executor_binder_result_type<R(&)(A1)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct executor_binder_result_type<R(*)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; template <typename R, typename A1, typename A2> struct executor_binder_result_type<R(&)(A1, A2)> { typedef R result_type; protected: typedef result_type result_type_or_void; }; // Helper to automatically define nested typedef argument_type. template <typename T, typename = void> struct executor_binder_argument_type {}; template <typename T> struct executor_binder_argument_type<T, void_t<typename T::argument_type>> { typedef typename T::argument_type argument_type; }; template <typename R, typename A1> struct executor_binder_argument_type<R(*)(A1)> { typedef A1 argument_type; }; template <typename R, typename A1> struct executor_binder_argument_type<R(&)(A1)> { typedef A1 argument_type; }; // Helper to automatically define nested typedefs first_argument_type and // second_argument_type. template <typename T, typename = void> struct executor_binder_argument_types {}; template <typename T> struct executor_binder_argument_types<T, void_t<typename T::first_argument_type>> { typedef typename T::first_argument_type first_argument_type; typedef typename T::second_argument_type second_argument_type; }; template <typename R, typename A1, typename A2> struct executor_binder_argument_type<R(*)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; template <typename R, typename A1, typename A2> struct executor_binder_argument_type<R(&)(A1, A2)> { typedef A1 first_argument_type; typedef A2 second_argument_type; }; // Helper to perform uses_executor construction of the target type, if // required. template <typename T, typename Executor, bool UsesExecutor> class executor_binder_base; template <typename T, typename Executor> class executor_binder_base<T, Executor, true> { protected: template <typename E, typename U> executor_binder_base(E&& e, U&& u) : executor_(static_cast<E&&>(e)), target_(executor_arg_t(), executor_, static_cast<U&&>(u)) { } Executor executor_; T target_; }; template <typename T, typename Executor> class executor_binder_base<T, Executor, false> { protected: template <typename E, typename U> executor_binder_base(E&& e, U&& u) : executor_(static_cast<E&&>(e)), target_(static_cast<U&&>(u)) { } Executor executor_; T target_; }; } // namespace detail /// A call wrapper type to bind an executor of type @c Executor to an object of /// type @c T. template <typename T, typename Executor> class executor_binder #if !defined(GENERATING_DOCUMENTATION) : public detail::executor_binder_result_type<T>, public detail::executor_binder_argument_type<T>, public detail::executor_binder_argument_types<T>, private detail::executor_binder_base< T, Executor, uses_executor<T, Executor>::value> #endif // !defined(GENERATING_DOCUMENTATION) { public: /// The type of the target object. typedef T target_type; /// The type of the associated executor. typedef Executor executor_type; #if defined(GENERATING_DOCUMENTATION) /// The return type if a function. /** * The type of @c result_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to function type, @c result_type is a synonym for * the return type of @c T; * * @li if @c T is a class type with a member type @c result_type, then @c * result_type is a synonym for @c T::result_type; * * @li otherwise @c result_type is not defined. */ typedef see_below result_type; /// The type of the function's argument. /** * The type of @c argument_type is based on the type @c T of the wrapper's * target object: * * @li if @c T is a pointer to a function type accepting a single argument, * @c argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c argument_type, then @c * argument_type is a synonym for @c T::argument_type; * * @li otherwise @c argument_type is not defined. */ typedef see_below argument_type; /// The type of the function's first argument. /** * The type of @c first_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * first_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c first_argument_type is a synonym for @c T::first_argument_type; * * @li otherwise @c first_argument_type is not defined. */ typedef see_below first_argument_type; /// The type of the function's second argument. /** * The type of @c second_argument_type is based on the type @c T of the * wrapper's target object: * * @li if @c T is a pointer to a function type accepting two arguments, @c * second_argument_type is a synonym for the return type of @c T; * * @li if @c T is a class type with a member type @c first_argument_type, * then @c second_argument_type is a synonym for @c T::second_argument_type; * * @li otherwise @c second_argument_type is not defined. */ typedef see_below second_argument_type; #endif // defined(GENERATING_DOCUMENTATION) /// Construct an executor wrapper for the specified object. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U> executor_binder(executor_arg_t, const executor_type& e, U&& u) : base_type(e, static_cast<U&&>(u)) { } /// Copy constructor. executor_binder(const executor_binder& other) : base_type(other.get_executor(), other.get()) { } /// Construct a copy, but specify a different executor. executor_binder(executor_arg_t, const executor_type& e, const executor_binder& other) : base_type(e, other.get()) { } /// Construct a copy of a different executor wrapper type. /** * This constructor is only valid if the @c Executor type is constructible * from type @c OtherExecutor, and the type @c T is constructible from type * @c U. */ template <typename U, typename OtherExecutor> executor_binder(const executor_binder<U, OtherExecutor>& other, constraint_t<is_constructible<Executor, OtherExecutor>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : base_type(other.get_executor(), other.get()) { } /// Construct a copy of a different executor wrapper type, but specify a /// different executor. /** * This constructor is only valid if the type @c T is constructible from type * @c U. */ template <typename U, typename OtherExecutor> executor_binder(executor_arg_t, const executor_type& e, const executor_binder<U, OtherExecutor>& other, constraint_t<is_constructible<T, U>::value> = 0) : base_type(e, other.get()) { } /// Move constructor. executor_binder(executor_binder&& other) : base_type(static_cast<executor_type&&>(other.get_executor()), static_cast<T&&>(other.get())) { } /// Move construct the target object, but specify a different executor. executor_binder(executor_arg_t, const executor_type& e, executor_binder&& other) : base_type(e, static_cast<T&&>(other.get())) { } /// Move construct from a different executor wrapper type. template <typename U, typename OtherExecutor> executor_binder(executor_binder<U, OtherExecutor>&& other, constraint_t<is_constructible<Executor, OtherExecutor>::value> = 0, constraint_t<is_constructible<T, U>::value> = 0) : base_type(static_cast<OtherExecutor&&>(other.get_executor()), static_cast<U&&>(other.get())) { } /// Move construct from a different executor wrapper type, but specify a /// different executor. template <typename U, typename OtherExecutor> executor_binder(executor_arg_t, const executor_type& e, executor_binder<U, OtherExecutor>&& other, constraint_t<is_constructible<T, U>::value> = 0) : base_type(e, static_cast<U&&>(other.get())) { } /// Destructor. ~executor_binder() { } /// Obtain a reference to the target object. target_type& get() noexcept { return this->target_; } /// Obtain a reference to the target object. const target_type& get() const noexcept { return this->target_; } /// Obtain the associated executor. executor_type get_executor() const noexcept { return this->executor_; } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) { return this->target_(static_cast<Args&&>(args)...); } /// Forwarding function call operator. template <typename... Args> result_of_t<T(Args...)> operator()(Args&&... args) const { return this->target_(static_cast<Args&&>(args)...); } private: typedef detail::executor_binder_base<T, Executor, uses_executor<T, Executor>::value> base_type; }; /// A function object type that adapts a @ref completion_token to specify that /// the completion handler should have the supplied executor as its associated /// executor. /** * May also be used directly as a completion token, in which case it adapts the * asynchronous operation's default completion token (or asio::deferred * if no default is available). */ template <typename Executor> struct partial_executor_binder { /// Constructor that specifies associated executor. explicit partial_executor_binder(const Executor& ex) : executor_(ex) { } /// Adapt a @ref completion_token to specify that the completion handler /// should have the executor as its associated executor. template <typename CompletionToken> ASIO_NODISCARD inline constexpr executor_binder<decay_t<CompletionToken>, Executor> operator()(CompletionToken&& completion_token) const { return executor_binder<decay_t<CompletionToken>, Executor>(executor_arg_t(), static_cast<CompletionToken&&>(completion_token), executor_); } //private: Executor executor_; }; /// Create a partial completion token that associates an executor. template <typename Executor> ASIO_NODISCARD inline partial_executor_binder<Executor> bind_executor(const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return partial_executor_binder<Executor>(ex); } /// Associate an object of type @c T with an executor of type @c Executor. template <typename Executor, typename T> ASIO_NODISCARD inline executor_binder<decay_t<T>, Executor> bind_executor(const Executor& ex, T&& t, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return executor_binder<decay_t<T>, Executor>( executor_arg_t(), ex, static_cast<T&&>(t)); } /// Create a partial completion token that associates an execution context's /// executor. template <typename ExecutionContext> ASIO_NODISCARD inline partial_executor_binder< typename ExecutionContext::executor_type> bind_executor(ExecutionContext& ctx, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return partial_executor_binder<typename ExecutionContext::executor_type>( ctx.get_executor()); } /// Associate an object of type @c T with an execution context's executor. template <typename ExecutionContext, typename T> ASIO_NODISCARD inline executor_binder<decay_t<T>, typename ExecutionContext::executor_type> bind_executor(ExecutionContext& ctx, T&& t, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return executor_binder<decay_t<T>, typename ExecutionContext::executor_type>( executor_arg_t(), ctx.get_executor(), static_cast<T&&>(t)); } #if !defined(GENERATING_DOCUMENTATION) template <typename T, typename Executor> struct uses_executor<executor_binder<T, Executor>, Executor> : true_type {}; namespace detail { template <typename TargetAsyncResult, typename Executor, typename = void> class executor_binder_completion_handler_async_result { public: template <typename T> explicit executor_binder_completion_handler_async_result(T&) { } }; template <typename TargetAsyncResult, typename Executor> class executor_binder_completion_handler_async_result< TargetAsyncResult, Executor, void_t<typename TargetAsyncResult::completion_handler_type >> { private: TargetAsyncResult target_; public: typedef executor_binder< typename TargetAsyncResult::completion_handler_type, Executor> completion_handler_type; explicit executor_binder_completion_handler_async_result( typename TargetAsyncResult::completion_handler_type& handler) : target_(handler) { } auto get() -> decltype(target_.get()) { return target_.get(); } }; template <typename TargetAsyncResult, typename = void> struct executor_binder_async_result_return_type { }; template <typename TargetAsyncResult> struct executor_binder_async_result_return_type<TargetAsyncResult, void_t<typename TargetAsyncResult::return_type>> { typedef typename TargetAsyncResult::return_type return_type; }; } // namespace detail template <typename T, typename Executor, typename Signature> class async_result<executor_binder<T, Executor>, Signature> : public detail::executor_binder_completion_handler_async_result< async_result<T, Signature>, Executor>, public detail::executor_binder_async_result_return_type< async_result<T, Signature>> { public: explicit async_result(executor_binder<T, Executor>& b) : detail::executor_binder_completion_handler_async_result< async_result<T, Signature>, Executor>(b.get()) { } template <typename Initiation> struct init_wrapper : detail::initiation_base<Initiation> { using detail::initiation_base<Initiation>::initiation_base; template <typename Handler, typename... Args> void operator()(Handler&& handler, const Executor& e, Args&&... args) && { static_cast<Initiation&&>(*this)( executor_binder<decay_t<Handler>, Executor>( executor_arg_t(), e, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } template <typename Handler, typename... Args> void operator()(Handler&& handler, const Executor& e, Args&&... args) const & { static_cast<const Initiation&>(*this)( executor_binder<decay_t<Handler>, Executor>( executor_arg_t(), e, static_cast<Handler&&>(handler)), static_cast<Args&&>(args)...); } }; template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( declval<init_wrapper<decay_t<Initiation>>>(), token.get(), token.get_executor(), static_cast<Args&&>(args)...)) { return async_initiate< conditional_t< is_const<remove_reference_t<RawCompletionToken>>::value, const T, T>, Signature>( init_wrapper<decay_t<Initiation>>( static_cast<Initiation&&>(initiation)), token.get(), token.get_executor(), static_cast<Args&&>(args)...); } private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; }; template <typename Executor, typename... Signatures> struct async_result<partial_executor_binder<Executor>, Signatures...> { template <typename Initiation, typename RawCompletionToken, typename... Args> static auto initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) -> decltype( async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), executor_binder< default_completion_token_t<associated_executor_t<Initiation>>, Executor>(executor_arg_t(), token.executor_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...)) { return async_initiate<Signatures...>( static_cast<Initiation&&>(initiation), executor_binder< default_completion_token_t<associated_executor_t<Initiation>>, Executor>(executor_arg_t(), token.executor_, default_completion_token_t<associated_executor_t<Initiation>>{}), static_cast<Args&&>(args)...); } }; template <template <typename, typename> class Associator, typename T, typename Executor, typename DefaultCandidate> struct associator<Associator, executor_binder<T, Executor>, DefaultCandidate> : Associator<T, DefaultCandidate> { static typename Associator<T, DefaultCandidate>::type get( const executor_binder<T, Executor>& b) noexcept { return Associator<T, DefaultCandidate>::get(b.get()); } static auto get(const executor_binder<T, Executor>& b, const DefaultCandidate& c) noexcept -> decltype(Associator<T, DefaultCandidate>::get(b.get(), c)) { return Associator<T, DefaultCandidate>::get(b.get(), c); } }; template <typename T, typename Executor, typename Executor1> struct associated_executor<executor_binder<T, Executor>, Executor1> { typedef Executor type; static auto get(const executor_binder<T, Executor>& b, const Executor1& = Executor1()) noexcept -> decltype(b.get_executor()) { return b.get_executor(); } }; #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BIND_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/registered_buffer.hpp
// // registered_buffer.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 ASIO_REGISTERED_BUFFER_HPP #define ASIO_REGISTERED_BUFFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/buffer.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class buffer_registration_base; } // namespace detail class const_registered_buffer; /// Type used to identify a registered buffer. class registered_buffer_id { public: /// The native buffer identifier type. typedef int native_handle_type; /// Default constructor creates an invalid registered buffer identifier. registered_buffer_id() noexcept : scope_(0), index_(-1) { } /// Get the native buffer identifier type. native_handle_type native_handle() const noexcept { return index_; } /// Compare two IDs for equality. friend bool operator==(const registered_buffer_id& lhs, const registered_buffer_id& rhs) noexcept { return lhs.scope_ == rhs.scope_ && lhs.index_ == rhs.index_; } /// Compare two IDs for equality. friend bool operator!=(const registered_buffer_id& lhs, const registered_buffer_id& rhs) noexcept { return lhs.scope_ != rhs.scope_ || lhs.index_ != rhs.index_; } private: friend class detail::buffer_registration_base; // Hidden constructor used by buffer registration. registered_buffer_id(const void* scope, int index) noexcept : scope_(scope), index_(index) { } const void* scope_; int index_; }; /// Holds a registered buffer over modifiable data. /** * Satisfies the @c MutableBufferSequence type requirements. */ class mutable_registered_buffer { public: /// Default constructor creates an invalid registered buffer. mutable_registered_buffer() noexcept : buffer_(), id_() { } /// Get the underlying mutable buffer. const mutable_buffer& buffer() const noexcept { return buffer_; } /// Get a pointer to the beginning of the memory range. /** * @returns <tt>buffer().data()</tt>. */ void* data() const noexcept { return buffer_.data(); } /// Get the size of the memory range. /** * @returns <tt>buffer().size()</tt>. */ std::size_t size() const noexcept { return buffer_.size(); } /// Get the registered buffer identifier. const registered_buffer_id& id() const noexcept { return id_; } /// Move the start of the buffer by the specified number of bytes. mutable_registered_buffer& operator+=(std::size_t n) noexcept { buffer_ += n; return *this; } private: friend class detail::buffer_registration_base; // Hidden constructor used by buffer registration and operators. mutable_registered_buffer(const mutable_buffer& b, const registered_buffer_id& i) noexcept : buffer_(b), id_(i) { } #if !defined(GENERATING_DOCUMENTATION) friend mutable_registered_buffer buffer( const mutable_registered_buffer& b, std::size_t n) noexcept; #endif // !defined(GENERATING_DOCUMENTATION) mutable_buffer buffer_; registered_buffer_id id_; }; /// Holds a registered buffer over non-modifiable data. /** * Satisfies the @c ConstBufferSequence type requirements. */ class const_registered_buffer { public: /// Default constructor creates an invalid registered buffer. const_registered_buffer() noexcept : buffer_(), id_() { } /// Construct a non-modifiable buffer from a modifiable one. const_registered_buffer( const mutable_registered_buffer& b) noexcept : buffer_(b.buffer()), id_(b.id()) { } /// Get the underlying constant buffer. const const_buffer& buffer() const noexcept { return buffer_; } /// Get a pointer to the beginning of the memory range. /** * @returns <tt>buffer().data()</tt>. */ const void* data() const noexcept { return buffer_.data(); } /// Get the size of the memory range. /** * @returns <tt>buffer().size()</tt>. */ std::size_t size() const noexcept { return buffer_.size(); } /// Get the registered buffer identifier. const registered_buffer_id& id() const noexcept { return id_; } /// Move the start of the buffer by the specified number of bytes. const_registered_buffer& operator+=(std::size_t n) noexcept { buffer_ += n; return *this; } private: // Hidden constructor used by operators. const_registered_buffer(const const_buffer& b, const registered_buffer_id& i) noexcept : buffer_(b), id_(i) { } #if !defined(GENERATING_DOCUMENTATION) friend const_registered_buffer buffer( const const_registered_buffer& b, std::size_t n) noexcept; #endif // !defined(GENERATING_DOCUMENTATION) const_buffer buffer_; registered_buffer_id id_; }; /** @addtogroup buffer_sequence_begin */ /// Get an iterator to the first element in a buffer sequence. inline const mutable_buffer* buffer_sequence_begin( const mutable_registered_buffer& b) noexcept { return &b.buffer(); } /// Get an iterator to the first element in a buffer sequence. inline const const_buffer* buffer_sequence_begin( const const_registered_buffer& b) noexcept { return &b.buffer(); } /** @} */ /** @addtogroup buffer_sequence_end */ /// Get an iterator to one past the end element in a buffer sequence. inline const mutable_buffer* buffer_sequence_end( const mutable_registered_buffer& b) noexcept { return &b.buffer() + 1; } /// Get an iterator to one past the end element in a buffer sequence. inline const const_buffer* buffer_sequence_end( const const_registered_buffer& b) noexcept { return &b.buffer() + 1; } /** @} */ /** @addtogroup buffer */ /// Obtain a buffer representing the entire registered buffer. inline mutable_registered_buffer buffer( const mutable_registered_buffer& b) noexcept { return b; } /// Obtain a buffer representing the entire registered buffer. inline const_registered_buffer buffer( const const_registered_buffer& b) noexcept { return b; } /// Obtain a buffer representing part of a registered buffer. inline mutable_registered_buffer buffer( const mutable_registered_buffer& b, std::size_t n) noexcept { return mutable_registered_buffer(buffer(b.buffer_, n), b.id_); } /// Obtain a buffer representing part of a registered buffer. inline const_registered_buffer buffer( const const_registered_buffer& b, std::size_t n) noexcept { return const_registered_buffer(buffer(b.buffer_, n), b.id_); } /** @} */ /// Create a new modifiable registered buffer that is offset from the start of /// another. /** * @relates mutable_registered_buffer */ inline mutable_registered_buffer operator+( const mutable_registered_buffer& b, std::size_t n) noexcept { mutable_registered_buffer tmp(b); tmp += n; return tmp; } /// Create a new modifiable buffer that is offset from the start of another. /** * @relates mutable_registered_buffer */ inline mutable_registered_buffer operator+(std::size_t n, const mutable_registered_buffer& b) noexcept { return b + n; } /// Create a new non-modifiable registered buffer that is offset from the start /// of another. /** * @relates const_registered_buffer */ inline const_registered_buffer operator+(const const_registered_buffer& b, std::size_t n) noexcept { const_registered_buffer tmp(b); tmp += n; return tmp; } /// Create a new non-modifiable buffer that is offset from the start of another. /** * @relates const_registered_buffer */ inline const_registered_buffer operator+(std::size_t n, const const_registered_buffer& b) noexcept { return b + n; } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_REGISTERED_BUFFER_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/read.hpp
// // read.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 ASIO_READ_HPP #define ASIO_READ_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/buffer.hpp" #include "asio/completion_condition.hpp" #include "asio/error.hpp" #if !defined(ASIO_NO_EXTENSIONS) # include "asio/basic_streambuf_fwd.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename> class initiate_async_read; #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_dynbuf_v1; #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) template <typename> class initiate_async_read_dynbuf_v2; } // namespace detail /** * @defgroup read asio::read * * @brief The @c read function is a composed operation that reads a certain * amount of data from a stream before returning. */ /*@{*/ /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, asio::error_code& ec, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v1> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename DynamicBuffer_v1, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read( * s, b, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read( * s, b, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, asio::error_code& ec); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename DynamicBuffer_v2> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename DynamicBuffer_v2, typename CompletionCondition> std::size_t read(SyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, asio::error_code& ec, constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0); /*@}*/ /** * @defgroup async_read asio::async_read * * @brief The @c async_read function is a composed asynchronous operation that * reads a certain amount of data from a stream before completion. */ /*@{*/ /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * asio::async_read(s, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::async_read( * s, buffers, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0, constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read<AsyncReadStream>>(), token, buffers, transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read<AsyncReadStream>(s), token, buffers, transfer_all()); } /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::async_read(s, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename MutableBufferSequence, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_mutable_buffer_sequence<MutableBufferSequence>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read<AsyncReadStream>>(), token, buffers, static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read<AsyncReadStream>(s), token, buffers, static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code asio::async_read( * s, buffers, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, DynamicBuffer_v1&& buffers, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), transfer_all()); } /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v1, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, DynamicBuffer_v1&& buffers, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v1<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< !is_dynamic_buffer_v2<decay_t<DynamicBuffer_v1>>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v1<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v1&&>(buffers), static_cast<CompletionCondition&&>(completion_condition)); } #if !defined(ASIO_NO_EXTENSIONS) #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code asio::async_read( * s, b, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), transfer_all()); } /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename Allocator, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v1<AsyncReadStream>>(), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v1<AsyncReadStream>(s), token, basic_streambuf_ref<Allocator>(b), static_cast<CompletionCondition&&>(completion_condition)); } #endif // !defined(ASIO_NO_IOSTREAM) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // !defined(ASIO_NO_DYNAMIC_BUFFER_V1) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note This overload is equivalent to calling: * @code asio::async_read( * s, buffers, * asio::transfer_all(), * handler); @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< !is_completion_condition<ReadToken>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), transfer_all())) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), transfer_all()); } /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. The asynchronous * operation will continue until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // Number of bytes copied into the buffers. If an error * // occurred, this will be the number of bytes successfully * // transferred prior to the error. * std::size_t bytes_transferred * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c AsyncReadStream type's * @c async_read_some operation. */ template <typename AsyncReadStream, typename DynamicBuffer_v2, typename CompletionCondition, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t< typename AsyncReadStream::executor_type>> inline auto async_read(AsyncReadStream& s, DynamicBuffer_v2 buffers, CompletionCondition completion_condition, ReadToken&& token = default_completion_token_t< typename AsyncReadStream::executor_type>(), constraint_t< is_dynamic_buffer_v2<DynamicBuffer_v2>::value > = 0, constraint_t< is_completion_condition<CompletionCondition>::value > = 0) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<detail::initiate_async_read_dynbuf_v2<AsyncReadStream>>(), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( detail::initiate_async_read_dynbuf_v2<AsyncReadStream>(s), token, static_cast<DynamicBuffer_v2&&>(buffers), static_cast<CompletionCondition&&>(completion_condition)); } /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/read.hpp" #endif // ASIO_READ_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/buffers_iterator.hpp
// // buffers_iterator.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 ASIO_BUFFERS_ITERATOR_HPP #define ASIO_BUFFERS_ITERATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <iterator> #include "asio/buffer.hpp" #include "asio/detail/assert.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <bool IsMutable> struct buffers_iterator_types_helper; template <> struct buffers_iterator_types_helper<false> { typedef const_buffer buffer_type; template <typename ByteType> struct byte_type { typedef add_const_t<ByteType> type; }; }; template <> struct buffers_iterator_types_helper<true> { typedef mutable_buffer buffer_type; template <typename ByteType> struct byte_type { typedef ByteType type; }; }; template <typename BufferSequence, typename ByteType> struct buffers_iterator_types { enum { is_mutable = is_convertible< typename BufferSequence::value_type, mutable_buffer>::value }; typedef buffers_iterator_types_helper<is_mutable> helper; typedef typename helper::buffer_type buffer_type; typedef typename helper::template byte_type<ByteType>::type byte_type; typedef typename BufferSequence::const_iterator const_iterator; }; template <typename ByteType> struct buffers_iterator_types<mutable_buffer, ByteType> { typedef mutable_buffer buffer_type; typedef ByteType byte_type; typedef const mutable_buffer* const_iterator; }; template <typename ByteType> struct buffers_iterator_types<const_buffer, ByteType> { typedef const_buffer buffer_type; typedef add_const_t<ByteType> byte_type; typedef const const_buffer* const_iterator; }; #if !defined(ASIO_NO_DEPRECATED) template <typename ByteType> struct buffers_iterator_types<mutable_buffers_1, ByteType> { typedef mutable_buffer buffer_type; typedef ByteType byte_type; typedef const mutable_buffer* const_iterator; }; template <typename ByteType> struct buffers_iterator_types<const_buffers_1, ByteType> { typedef const_buffer buffer_type; typedef add_const_t<ByteType> byte_type; typedef const const_buffer* const_iterator; }; #endif // !defined(ASIO_NO_DEPRECATED) } /// A random access iterator over the bytes in a buffer sequence. template <typename BufferSequence, typename ByteType = char> class buffers_iterator { private: typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::buffer_type buffer_type; typedef typename detail::buffers_iterator_types<BufferSequence, ByteType>::const_iterator buffer_sequence_iterator_type; public: /// The type used for the distance between two iterators. typedef std::ptrdiff_t difference_type; /// The type of the value pointed to by the iterator. typedef ByteType value_type; #if defined(GENERATING_DOCUMENTATION) /// The type of the result of applying operator->() to the iterator. /** * If the buffer sequence stores buffer objects that are convertible to * mutable_buffer, this is a pointer to a non-const ByteType. Otherwise, a * pointer to a const ByteType. */ typedef const_or_non_const_ByteType* pointer; #else // defined(GENERATING_DOCUMENTATION) typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::byte_type* pointer; #endif // defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The type of the result of applying operator*() to the iterator. /** * If the buffer sequence stores buffer objects that are convertible to * mutable_buffer, this is a reference to a non-const ByteType. Otherwise, a * reference to a const ByteType. */ typedef const_or_non_const_ByteType& reference; #else // defined(GENERATING_DOCUMENTATION) typedef typename detail::buffers_iterator_types< BufferSequence, ByteType>::byte_type& reference; #endif // defined(GENERATING_DOCUMENTATION) /// The iterator category. typedef std::random_access_iterator_tag iterator_category; /// Default constructor. Creates an iterator in an undefined state. buffers_iterator() : current_buffer_(), current_buffer_position_(0), begin_(), current_(), end_(), position_(0) { } /// Construct an iterator representing the beginning of the buffers' data. static buffers_iterator begin(const BufferSequence& buffers) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) __attribute__ ((__noinline__)) #endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) { buffers_iterator new_iter; new_iter.begin_ = asio::buffer_sequence_begin(buffers); new_iter.current_ = asio::buffer_sequence_begin(buffers); new_iter.end_ = asio::buffer_sequence_end(buffers); while (new_iter.current_ != new_iter.end_) { new_iter.current_buffer_ = *new_iter.current_; if (new_iter.current_buffer_.size() > 0) break; ++new_iter.current_; } return new_iter; } /// Construct an iterator representing the end of the buffers' data. static buffers_iterator end(const BufferSequence& buffers) #if defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) __attribute__ ((__noinline__)) #endif // defined(__GNUC__) && (__GNUC__ == 4) && (__GNUC_MINOR__ == 3) { buffers_iterator new_iter; new_iter.begin_ = asio::buffer_sequence_begin(buffers); new_iter.current_ = asio::buffer_sequence_begin(buffers); new_iter.end_ = asio::buffer_sequence_end(buffers); while (new_iter.current_ != new_iter.end_) { buffer_type buffer = *new_iter.current_; new_iter.position_ += buffer.size(); ++new_iter.current_; } return new_iter; } /// Dereference an iterator. reference operator*() const { return dereference(); } /// Dereference an iterator. pointer operator->() const { return &dereference(); } /// Access an individual element. reference operator[](std::ptrdiff_t difference) const { buffers_iterator tmp(*this); tmp.advance(difference); return *tmp; } /// Increment operator (prefix). buffers_iterator& operator++() { increment(); return *this; } /// Increment operator (postfix). buffers_iterator operator++(int) { buffers_iterator tmp(*this); ++*this; return tmp; } /// Decrement operator (prefix). buffers_iterator& operator--() { decrement(); return *this; } /// Decrement operator (postfix). buffers_iterator operator--(int) { buffers_iterator tmp(*this); --*this; return tmp; } /// Addition operator. buffers_iterator& operator+=(std::ptrdiff_t difference) { advance(difference); return *this; } /// Subtraction operator. buffers_iterator& operator-=(std::ptrdiff_t difference) { advance(-difference); return *this; } /// Addition operator. friend buffers_iterator operator+(const buffers_iterator& iter, std::ptrdiff_t difference) { buffers_iterator tmp(iter); tmp.advance(difference); return tmp; } /// Addition operator. friend buffers_iterator operator+(std::ptrdiff_t difference, const buffers_iterator& iter) { buffers_iterator tmp(iter); tmp.advance(difference); return tmp; } /// Subtraction operator. friend buffers_iterator operator-(const buffers_iterator& iter, std::ptrdiff_t difference) { buffers_iterator tmp(iter); tmp.advance(-difference); return tmp; } /// Subtraction operator. friend std::ptrdiff_t operator-(const buffers_iterator& a, const buffers_iterator& b) { return b.distance_to(a); } /// Test two iterators for equality. friend bool operator==(const buffers_iterator& a, const buffers_iterator& b) { return a.equal(b); } /// Test two iterators for inequality. friend bool operator!=(const buffers_iterator& a, const buffers_iterator& b) { return !a.equal(b); } /// Compare two iterators. friend bool operator<(const buffers_iterator& a, const buffers_iterator& b) { return a.distance_to(b) > 0; } /// Compare two iterators. friend bool operator<=(const buffers_iterator& a, const buffers_iterator& b) { return !(b < a); } /// Compare two iterators. friend bool operator>(const buffers_iterator& a, const buffers_iterator& b) { return b < a; } /// Compare two iterators. friend bool operator>=(const buffers_iterator& a, const buffers_iterator& b) { return !(a < b); } private: // Dereference the iterator. reference dereference() const { return static_cast<pointer>( current_buffer_.data())[current_buffer_position_]; } // Compare two iterators for equality. bool equal(const buffers_iterator& other) const { return position_ == other.position_; } // Increment the iterator. void increment() { ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); ++position_; // Check if the increment can be satisfied by the current buffer. ++current_buffer_position_; if (current_buffer_position_ != current_buffer_.size()) return; // Find the next non-empty buffer. ++current_; current_buffer_position_ = 0; while (current_ != end_) { current_buffer_ = *current_; if (current_buffer_.size() > 0) return; ++current_; } } // Decrement the iterator. void decrement() { ASIO_ASSERT(position_ > 0 && "iterator out of bounds"); --position_; // Check if the decrement can be satisfied by the current buffer. if (current_buffer_position_ != 0) { --current_buffer_position_; return; } // Find the previous non-empty buffer. buffer_sequence_iterator_type iter = current_; while (iter != begin_) { --iter; buffer_type buffer = *iter; std::size_t buffer_size = buffer.size(); if (buffer_size > 0) { current_ = iter; current_buffer_ = buffer; current_buffer_position_ = buffer_size - 1; return; } } } // Advance the iterator by the specified distance. void advance(std::ptrdiff_t n) { if (n > 0) { ASIO_ASSERT(current_ != end_ && "iterator out of bounds"); for (;;) { std::ptrdiff_t current_buffer_balance = current_buffer_.size() - current_buffer_position_; // Check if the advance can be satisfied by the current buffer. if (current_buffer_balance > n) { position_ += n; current_buffer_position_ += n; return; } // Update position. n -= current_buffer_balance; position_ += current_buffer_balance; // Move to next buffer. If it is empty then it will be skipped on the // next iteration of this loop. if (++current_ == end_) { ASIO_ASSERT(n == 0 && "iterator out of bounds"); current_buffer_ = buffer_type(); current_buffer_position_ = 0; return; } current_buffer_ = *current_; current_buffer_position_ = 0; } } else if (n < 0) { std::size_t abs_n = -n; ASIO_ASSERT(position_ >= abs_n && "iterator out of bounds"); for (;;) { // Check if the advance can be satisfied by the current buffer. if (current_buffer_position_ >= abs_n) { position_ -= abs_n; current_buffer_position_ -= abs_n; return; } // Update position. abs_n -= current_buffer_position_; position_ -= current_buffer_position_; // Check if we've reached the beginning of the buffers. if (current_ == begin_) { ASIO_ASSERT(abs_n == 0 && "iterator out of bounds"); current_buffer_position_ = 0; return; } // Find the previous non-empty buffer. buffer_sequence_iterator_type iter = current_; while (iter != begin_) { --iter; buffer_type buffer = *iter; std::size_t buffer_size = buffer.size(); if (buffer_size > 0) { current_ = iter; current_buffer_ = buffer; current_buffer_position_ = buffer_size; break; } } } } } // Determine the distance between two iterators. std::ptrdiff_t distance_to(const buffers_iterator& other) const { return other.position_ - position_; } buffer_type current_buffer_; std::size_t current_buffer_position_; buffer_sequence_iterator_type begin_; buffer_sequence_iterator_type current_; buffer_sequence_iterator_type end_; std::size_t position_; }; /// Construct an iterator representing the beginning of the buffers' data. template <typename BufferSequence> inline buffers_iterator<BufferSequence> buffers_begin( const BufferSequence& buffers) { return buffers_iterator<BufferSequence>::begin(buffers); } /// Construct an iterator representing the end of the buffers' data. template <typename BufferSequence> inline buffers_iterator<BufferSequence> buffers_end( const BufferSequence& buffers) { return buffers_iterator<BufferSequence>::end(buffers); } } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BUFFERS_ITERATOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/system_context.hpp
// // system_context.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 ASIO_SYSTEM_CONTEXT_HPP #define ASIO_SYSTEM_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/scheduler.hpp" #include "asio/detail/thread_group.hpp" #include "asio/execution.hpp" #include "asio/execution_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { template <typename Blocking, typename Relationship, typename Allocator> class basic_system_executor; /// The executor context for the system executor. class system_context : public execution_context { public: /// The executor type associated with the context. typedef basic_system_executor< execution::blocking_t::possibly_t, execution::relationship_t::fork_t, std::allocator<void> > executor_type; /// Destructor shuts down all threads in the system thread pool. ASIO_DECL ~system_context(); /// Obtain an executor for the context. executor_type get_executor() noexcept; /// Signal all threads in the system thread pool to stop. ASIO_DECL void stop(); /// Determine whether the system thread pool has been stopped. ASIO_DECL bool stopped() const noexcept; /// Join all threads in the system thread pool. ASIO_DECL void join(); #if defined(GENERATING_DOCUMENTATION) private: #endif // defined(GENERATING_DOCUMENTATION) // Constructor creates all threads in the system thread pool. ASIO_DECL system_context(); private: template <typename, typename, typename> friend class basic_system_executor; struct thread_function; // Helper function to create the underlying scheduler. ASIO_DECL detail::scheduler& add_scheduler(detail::scheduler* s); // The underlying scheduler. detail::scheduler& scheduler_; // The threads in the system thread pool. detail::thread_group threads_; // The number of threads in the pool. std::size_t num_threads_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/system_context.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/system_context.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SYSTEM_CONTEXT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_socket_acceptor.hpp
// // basic_socket_acceptor.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 ASIO_BASIC_SOCKET_ACCEPTOR_HPP #define ASIO_BASIC_SOCKET_ACCEPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <utility> #include "asio/detail/config.hpp" #include "asio/any_io_executor.hpp" #include "asio/basic_socket.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/socket_base.hpp" #if defined(ASIO_WINDOWS_RUNTIME) # include "asio/detail/null_socket_service.hpp" #elif defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_socket_service.hpp" #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/io_uring_socket_service.hpp" #else # include "asio/detail/reactive_socket_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) #define ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_socket_acceptor; #endif // !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) /// Provides the ability to accept new connections. /** * The basic_socket_acceptor class template is used for accepting new socket * connections. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c accept operations are thread safe, if the underlying * operating system calls are also thread safe. This means that it is permitted * to perform concurrent calls to synchronous @c accept operations on a single * socket object. Other synchronous operations, such as @c open or @c close, are * not thread safe. * * @par Example * Opening a socket acceptor with the SO_REUSEADDR option enabled: * @code * asio::ip::tcp::acceptor acceptor(my_context); * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), port); * acceptor.open(endpoint.protocol()); * acceptor.set_option(asio::ip::tcp::acceptor::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ template <typename Protocol, typename Executor> class basic_socket_acceptor : public socket_base { private: class initiate_async_wait; class initiate_async_accept; class initiate_async_move_accept; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the acceptor type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_socket_acceptor<Protocol, Executor1> other; }; /// The native representation of an acceptor. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_WINDOWS_RUNTIME) typedef typename detail::null_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef typename detail::win_iocp_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef typename detail::io_uring_socket_service< Protocol>::native_handle_type native_handle_type; #else typedef typename detail::reactive_socket_service< Protocol>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct an acceptor without opening it. /** * This constructor creates an acceptor without opening it to listen for new * connections. The open() function must be called before the acceptor can * accept new socket connections. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. */ explicit basic_socket_acceptor(const executor_type& ex) : impl_(0, ex) { } /// Construct an acceptor without opening it. /** * This constructor creates an acceptor without opening it to listen for new * connections. The open() function must be called before the acceptor can * accept new socket connections. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. */ template <typename ExecutionContext> explicit basic_socket_acceptor(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Construct an open acceptor. /** * This constructor creates an acceptor and automatically opens it. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_socket_acceptor(const executor_type& ex, const protocol_type& protocol) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Construct an open acceptor. /** * This constructor creates an acceptor and automatically opens it. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Construct an acceptor opened on the given endpoint. /** * This constructor creates an acceptor and automatically opens it to listen * for new connections on the specified endpoint. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param endpoint An endpoint on the local machine on which the acceptor * will listen for new connections. * * @param reuse_addr Whether the constructor should set the socket option * socket_base::reuse_address. * * @throws asio::system_error Thrown on failure. * * @note This constructor is equivalent to the following code: * @code * basic_socket_acceptor<Protocol> acceptor(my_context); * acceptor.open(endpoint.protocol()); * if (reuse_addr) * acceptor.set_option(socket_base::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ basic_socket_acceptor(const executor_type& ex, const endpoint_type& endpoint, bool reuse_addr = true) : impl_(0, ex) { asio::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); if (reuse_addr) { impl_.get_service().set_option(impl_.get_implementation(), socket_base::reuse_address(true), ec); asio::detail::throw_error(ec, "set_option"); } impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); impl_.get_service().listen(impl_.get_implementation(), socket_base::max_listen_connections, ec); asio::detail::throw_error(ec, "listen"); } /// Construct an acceptor opened on the given endpoint. /** * This constructor creates an acceptor and automatically opens it to listen * for new connections on the specified endpoint. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param endpoint An endpoint on the local machine on which the acceptor * will listen for new connections. * * @param reuse_addr Whether the constructor should set the socket option * socket_base::reuse_address. * * @throws asio::system_error Thrown on failure. * * @note This constructor is equivalent to the following code: * @code * basic_socket_acceptor<Protocol> acceptor(my_context); * acceptor.open(endpoint.protocol()); * if (reuse_addr) * acceptor.set_option(socket_base::reuse_address(true)); * acceptor.bind(endpoint); * acceptor.listen(); * @endcode */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const endpoint_type& endpoint, bool reuse_addr = true, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); if (reuse_addr) { impl_.get_service().set_option(impl_.get_implementation(), socket_base::reuse_address(true), ec); asio::detail::throw_error(ec, "set_option"); } impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); impl_.get_service().listen(impl_.get_implementation(), socket_base::max_listen_connections, ec); asio::detail::throw_error(ec, "listen"); } /// Construct a basic_socket_acceptor on an existing native acceptor. /** * This constructor creates an acceptor object to hold an existing native * acceptor. * * @param ex The I/O executor that the acceptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @param native_acceptor A native acceptor. * * @throws asio::system_error Thrown on failure. */ basic_socket_acceptor(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_acceptor) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_socket_acceptor on an existing native acceptor. /** * This constructor creates an acceptor object to hold an existing native * acceptor. * * @param context An execution context which provides the I/O executor that * the acceptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the acceptor. * * @param protocol An object specifying protocol parameters to be used. * * @param native_acceptor A native acceptor. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket_acceptor(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_acceptor, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_socket_acceptor from another. /** * This constructor moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket_acceptor(const executor_type&) * constructor. */ basic_socket_acceptor(basic_socket_acceptor&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket_acceptor from another. /** * This assignment operator moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket_acceptor(const executor_type&) * constructor. */ basic_socket_acceptor& operator=(basic_socket_acceptor&& other) { impl_ = std::move(other.impl_); return *this; } // All socket acceptors have access to each other's implementations. template <typename Protocol1, typename Executor1> friend class basic_socket_acceptor; /// Move-construct a basic_socket_acceptor from an acceptor of another /// protocol type. /** * This constructor moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket_acceptor(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_socket_acceptor(basic_socket_acceptor<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket_acceptor from an acceptor of another protocol /// type. /** * This assignment operator moves an acceptor from one object to another. * * @param other The other basic_socket_acceptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket_acceptor(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_socket_acceptor& > operator=(basic_socket_acceptor<Protocol1, Executor1>&& other) { basic_socket_acceptor tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the acceptor. /** * This function destroys the acceptor, cancelling any outstanding * asynchronous operations associated with the acceptor as if by calling * @c cancel. */ ~basic_socket_acceptor() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Open the acceptor using the specified protocol. /** * This function opens the socket acceptor so that it will use the specified * protocol. * * @param protocol An object specifying which protocol is to be used. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * acceptor.open(asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Open the acceptor using the specified protocol. /** * This function opens the socket acceptor so that it will use the specified * protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * asio::error_code ec; * acceptor.open(asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID open(const protocol_type& protocol, asio::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), protocol, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assigns an existing native acceptor to the acceptor. /* * This function opens the acceptor to hold an existing native acceptor. * * @param protocol An object specifying which protocol is to be used. * * @param native_acceptor A native acceptor. * * @throws asio::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_acceptor) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); asio::detail::throw_error(ec, "assign"); } /// Assigns an existing native acceptor to the acceptor. /* * This function opens the acceptor to hold an existing native acceptor. * * @param protocol An object specifying which protocol is to be used. * * @param native_acceptor A native acceptor. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, const native_handle_type& native_acceptor, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), protocol, native_acceptor, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the acceptor is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Bind the acceptor to the given local endpoint. /** * This function binds the socket acceptor to the specified endpoint on the * local machine. * * @param endpoint An endpoint on the local machine to which the socket * acceptor will be bound. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), 12345); * acceptor.open(endpoint.protocol()); * acceptor.bind(endpoint); * @endcode */ void bind(const endpoint_type& endpoint) { asio::error_code ec; impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Bind the acceptor to the given local endpoint. /** * This function binds the socket acceptor to the specified endpoint on the * local machine. * * @param endpoint An endpoint on the local machine to which the socket * acceptor will be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * asio::ip::tcp::endpoint endpoint(asio::ip::tcp::v4(), 12345); * acceptor.open(endpoint.protocol()); * asio::error_code ec; * acceptor.bind(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, asio::error_code& ec) { impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Place the acceptor into the state where it will listen for new /// connections. /** * This function puts the socket acceptor into the state where it may accept * new connections. * * @param backlog The maximum length of the queue of pending connections. * * @throws asio::system_error Thrown on failure. */ void listen(int backlog = socket_base::max_listen_connections) { asio::error_code ec; impl_.get_service().listen(impl_.get_implementation(), backlog, ec); asio::detail::throw_error(ec, "listen"); } /// Place the acceptor into the state where it will listen for new /// connections. /** * This function puts the socket acceptor into the state where it may accept * new connections. * * @param backlog The maximum length of the queue of pending connections. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::error_code ec; * acceptor.listen(asio::socket_base::max_listen_connections, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID listen(int backlog, asio::error_code& ec) { impl_.get_service().listen(impl_.get_implementation(), backlog, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Close the acceptor. /** * This function is used to close the acceptor. Any asynchronous accept * operations will be cancelled immediately. * * A subsequent call to open() is required before the acceptor can again be * used to again perform socket accept operations. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the acceptor. /** * This function is used to close the acceptor. Any asynchronous accept * operations will be cancelled immediately. * * A subsequent call to open() is required before the acceptor can again be * used to again perform socket accept operations. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::error_code ec; * acceptor.close(ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native acceptor. /** * This function causes all outstanding asynchronous accept operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native acceptor is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native acceptor. /** * This function causes all outstanding asynchronous accept operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native acceptor is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native acceptor representation. /** * This function may be used to obtain the underlying representation of the * acceptor. This is intended to allow access to native acceptor functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the acceptor. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the acceptor. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Set an option on the acceptor. /** * This function is used to set an option on the acceptor. * * @param option The new option value to be set on the acceptor. * * @throws asio::system_error Thrown on failure. * * @sa SettableSocketOption @n * asio::socket_base::reuse_address * asio::socket_base::enable_connection_aborted * * @par Example * Setting the SOL_SOCKET/SO_REUSEADDR option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::reuse_address option(true); * acceptor.set_option(option); * @endcode */ template <typename SettableSocketOption> void set_option(const SettableSocketOption& option) { asio::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the acceptor. /** * This function is used to set an option on the acceptor. * * @param option The new option value to be set on the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * asio::socket_base::reuse_address * asio::socket_base::enable_connection_aborted * * @par Example * Setting the SOL_SOCKET/SO_REUSEADDR option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::reuse_address option(true); * asio::error_code ec; * acceptor.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename SettableSocketOption> ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, asio::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the acceptor. /** * This function is used to get the current value of an option on the * acceptor. * * @param option The option value to be obtained from the acceptor. * * @throws asio::system_error Thrown on failure. * * @sa GettableSocketOption @n * asio::socket_base::reuse_address * * @par Example * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::reuse_address option; * acceptor.get_option(option); * bool is_set = option.get(); * @endcode */ template <typename GettableSocketOption> void get_option(GettableSocketOption& option) const { asio::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the acceptor. /** * This function is used to get the current value of an option on the * acceptor. * * @param option The option value to be obtained from the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * asio::socket_base::reuse_address * * @par Example * Getting the value of the SOL_SOCKET/SO_REUSEADDR option: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::reuse_address option; * asio::error_code ec; * acceptor.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.get(); * @endcode */ template <typename GettableSocketOption> ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, asio::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the acceptor. /** * This function is used to execute an IO control command on the acceptor. * * @param command The IO control command to be performed on the acceptor. * * @throws asio::system_error Thrown on failure. * * @sa IoControlCommand @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::non_blocking_io command(true); * socket.io_control(command); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { asio::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the acceptor. /** * This function is used to execute an IO control command on the acceptor. * * @param command The IO control command to be performed on the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::acceptor::non_blocking_io command(true); * asio::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename IoControlCommand> ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, asio::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the acceptor. /** * @returns @c true if the acceptor's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the acceptor. /** * @param mode If @c true, the acceptor's synchronous operations will fail * with asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @throws asio::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ void non_blocking(bool mode) { asio::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the acceptor. /** * @param mode If @c true, the acceptor's synchronous operations will fail * with asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ ASIO_SYNC_OP_VOID non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native acceptor implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native acceptor. This mode has no effect on the behaviour of the acceptor * object's synchronous operations. * * @returns @c true if the underlying acceptor is in non-blocking mode and * direct system calls may fail with asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the acceptor object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native acceptor. */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the native acceptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native acceptor. It has no effect on the behaviour of the acceptor object's * synchronous operations. * * @param mode If @c true, the underlying acceptor is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @throws asio::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. */ void native_non_blocking(bool mode) { asio::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native acceptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native acceptor. It has no effect on the behaviour of the acceptor object's * synchronous operations. * * @param mode If @c true, the underlying acceptor is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. */ ASIO_SYNC_OP_VOID native_non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint of the acceptor. /** * This function is used to obtain the locally bound endpoint of the acceptor. * * @returns An object that represents the local endpoint of the acceptor. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { asio::error_code ec; endpoint_type ep = impl_.get_service().local_endpoint( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "local_endpoint"); return ep; } /// Get the local endpoint of the acceptor. /** * This function is used to obtain the locally bound endpoint of the acceptor. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the acceptor. * Returns a default-constructed endpoint object if an error occurred and the * error handler did not throw an exception. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::error_code ec; * asio::ip::tcp::endpoint endpoint = acceptor.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(asio::error_code& ec) const { return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); } /// Wait for the acceptor to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for an acceptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired acceptor state. * * @par Example * Waiting for an acceptor to become readable. * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.wait(asio::ip::tcp::acceptor::wait_read); * @endcode */ void wait(wait_type w) { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); asio::detail::throw_error(ec, "wait"); } /// Wait for the acceptor to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for an acceptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired acceptor state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for an acceptor to become readable. * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::error_code ec; * acceptor.wait(asio::ip::tcp::acceptor::wait_read, ec); * @endcode */ ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the acceptor to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for an acceptor to * enter a ready to read, write or error condition state. It is an initiating * function for an @ref asynchronous_operation, and always returns * immediately. * * @param w Specifies the desired acceptor state. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the wait completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Example * @code * void wait_handler(const asio::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_wait( * asio::ip::tcp::acceptor::wait_read, * wait_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait(wait_type w, WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token, w)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token, w); } #if !defined(ASIO_NO_EXTENSIONS) /// Accept a new connection. /** * This function is used to accept a new connection from a peer into the * given socket. The function call will block until a new connection has been * accepted successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(my_context); * acceptor.accept(socket); * @endcode */ template <typename Protocol1, typename Executor1> void accept(basic_socket<Protocol1, Executor1>& peer, constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) { asio::error_code ec; impl_.get_service().accept(impl_.get_implementation(), peer, static_cast<endpoint_type*>(0), ec); asio::detail::throw_error(ec, "accept"); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer into the * given socket. The function call will block until a new connection has been * accepted successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(my_context); * asio::error_code ec; * acceptor.accept(socket, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Protocol1, typename Executor1> ASIO_SYNC_OP_VOID accept( basic_socket<Protocol1, Executor1>& peer, asio::error_code& ec, constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) { impl_.get_service().accept(impl_.get_implementation(), peer, static_cast<endpoint_type*>(0), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection into a * socket, and additionally obtain the endpoint of the remote peer. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param peer The socket into which the new connection will be accepted. * Ownership of the peer object is retained by the caller, which must * guarantee that it is valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(my_context); * acceptor.async_accept(socket, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Protocol1, typename Executor1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) AcceptToken = default_completion_token_t<executor_type>> auto async_accept(basic_socket<Protocol1, Executor1>& peer, AcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<Protocol, Protocol1>::value > = 0) -> decltype( async_initiate<AcceptToken, void (asio::error_code)>( declval<initiate_async_accept>(), token, &peer, static_cast<endpoint_type*>(0))) { return async_initiate<AcceptToken, void (asio::error_code)>( initiate_async_accept(this), token, &peer, static_cast<endpoint_type*>(0)); } /// Accept a new connection and obtain the endpoint of the peer /** * This function is used to accept a new connection from a peer into the * given socket, and additionally provide the endpoint of the remote peer. * The function call will block until a new connection has been accepted * successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param peer_endpoint An endpoint object which will receive the endpoint of * the remote peer. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(my_context); * asio::ip::tcp::endpoint endpoint; * acceptor.accept(socket, endpoint); * @endcode */ template <typename Executor1> void accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint) { asio::error_code ec; impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); asio::detail::throw_error(ec, "accept"); } /// Accept a new connection and obtain the endpoint of the peer /** * This function is used to accept a new connection from a peer into the * given socket, and additionally provide the endpoint of the remote peer. * The function call will block until a new connection has been accepted * successfully or an error occurs. * * @param peer The socket into which the new connection will be accepted. * * @param peer_endpoint An endpoint object which will receive the endpoint of * the remote peer. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(my_context); * asio::ip::tcp::endpoint endpoint; * asio::error_code ec; * acceptor.accept(socket, endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> ASIO_SYNC_OP_VOID accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint, asio::error_code& ec) { impl_.get_service().accept( impl_.get_implementation(), peer, &peer_endpoint, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection into a * socket, and additionally obtain the endpoint of the remote peer. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param peer The socket into which the new connection will be accepted. * Ownership of the peer object is retained by the caller, which must * guarantee that it is valid until the completion handler is called. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_endpoint object is * retained by the caller, which must guarantee that it is valid until the * handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) AcceptToken = default_completion_token_t<executor_type>> auto async_accept(basic_socket<protocol_type, Executor1>& peer, endpoint_type& peer_endpoint, AcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<AcceptToken, void (asio::error_code)>( declval<initiate_async_accept>(), token, &peer, &peer_endpoint)) { return async_initiate<AcceptToken, void (asio::error_code)>( initiate_async_accept(this), token, &peer, &peer_endpoint); } #endif // !defined(ASIO_NO_EXTENSIONS) /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept() { asio::error_code ec; typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept(ec)); * if (ec) * { * // An error occurred. * } * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(asio::error_code& ec) { typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template * rebind_executor<executor_type>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template * rebind_executor<executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept( MoveAcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( declval<initiate_async_move_accept>(), token, declval<const executor_type&>(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( initiate_async_move_accept(this), token, impl_.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly * accepted socket. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { asio::error_code ec; typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept()); * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { asio::error_code ec; typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, asio::error_code& ec, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::socket socket(acceptor.accept(my_context2, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, asio::error_code& ec, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, 0, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * Executor1>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template rebind_executor< * Executor1>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(my_context2, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< constraint_t<is_executor<Executor1>::value || execution::is_executor<Executor1>::value, Executor1>>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(const Executor1& ex, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( declval<initiate_async_move_accept>(), token, ex, static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( initiate_async_move_accept(this), token, ex, static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0)); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * acceptor.async_accept(my_context2, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(ExecutionContext& context, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( declval<initiate_async_move_accept>(), token, context.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( initiate_async_move_accept(this), token, context.get_executor(), static_cast<endpoint_type*>(0), static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket(acceptor.accept(endpoint)); * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(endpoint_type& peer_endpoint) { asio::error_code ec; typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket(acceptor.accept(endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ typename Protocol::socket::template rebind_executor<executor_type>::other accept(endpoint_type& peer_endpoint, asio::error_code& ec) { typename Protocol::socket::template rebind_executor< executor_type>::other peer(impl_.get_executor()); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_endpoint object is * retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template * rebind_executor<executor_type>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template * rebind_executor<executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( declval<initiate_async_move_accept>(), token, declval<const executor_type&>(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor<executor_type>::other)>( initiate_async_move_accept(this), token, impl_.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<executor_type>::other*>(0)); } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint)); * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const Executor1& ex, endpoint_type& peer_endpoint, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { asio::error_code ec; typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @returns A socket object representing the newly accepted connection. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint)); * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, endpoint_type& peer_endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { asio::error_code ec; typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); asio::detail::throw_error(ec, "accept"); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename Executor1> typename Protocol::socket::template rebind_executor<Executor1>::other accept(const executor_type& ex, endpoint_type& peer_endpoint, asio::error_code& ec, constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) { typename Protocol::socket::template rebind_executor<Executor1>::other peer(ex); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Accept a new connection. /** * This function is used to accept a new connection from a peer. The function * call will block until a new connection has been accepted successfully or * an error occurs. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. * * @param ec Set to indicate what error occurred, if any. * * @returns On success, a socket object representing the newly accepted * connection. On error, a socket object where is_open() is false. * * @par Example * @code * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * asio::ip::tcp::socket socket( * acceptor.accept(my_context2, endpoint, ec)); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename ExecutionContext> typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other accept(ExecutionContext& context, endpoint_type& peer_endpoint, asio::error_code& ec, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other peer(context); impl_.get_service().accept(impl_.get_implementation(), peer, &peer_endpoint, ec); return peer; } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param ex The I/O executor object to be used for the newly accepted * socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_endpoint object is * retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * Executor1>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template rebind_executor< * Executor1>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(my_context2, endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename Executor1, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< constraint_t<is_executor<Executor1>::value || execution::is_executor<Executor1>::value, Executor1>>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(const Executor1& ex, endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_executor<Executor1>::value || execution::is_executor<Executor1>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( declval<initiate_async_move_accept>(), token, ex, &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< Executor1>::other)>( initiate_async_move_accept(this), token, ex, &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor<Executor1>::other*>(0)); } /// Start an asynchronous accept. /** * This function is used to asynchronously accept a new connection. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * This overload requires that the Protocol template parameter satisfy the * AcceptableProtocol type requirements. * * @param context The I/O execution context object to be used for the newly * accepted socket. * * @param peer_endpoint An endpoint object into which the endpoint of the * remote peer will be written. Ownership of the peer_endpoint object is * retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the accept completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * // Result of operation. * const asio::error_code& error, * * // On success, the newly accepted socket. * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other peer * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, * typename Protocol::socket::template rebind_executor< * typename ExecutionContext::executor_type>::other)) @endcode * * @par Example * @code * void accept_handler(const asio::error_code& error, * asio::ip::tcp::socket peer) * { * if (!error) * { * // Accept succeeded. * } * } * * ... * * asio::ip::tcp::acceptor acceptor(my_context); * ... * asio::ip::tcp::endpoint endpoint; * acceptor.async_accept(my_context2, endpoint, accept_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ExecutionContext, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)) MoveAcceptToken = default_completion_token_t<executor_type>> auto async_accept(ExecutionContext& context, endpoint_type& peer_endpoint, MoveAcceptToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) -> decltype( async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( declval<initiate_async_move_accept>(), token, context.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0))) { return async_initiate<MoveAcceptToken, void (asio::error_code, typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other)>( initiate_async_move_accept(this), token, context.get_executor(), &peer_endpoint, static_cast<typename Protocol::socket::template rebind_executor< typename ExecutionContext::executor_type>::other*>(0)); } private: // Disallow copying and assignment. basic_socket_acceptor(const basic_socket_acceptor&) = delete; basic_socket_acceptor& operator=( const basic_socket_acceptor&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler, wait_type w) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), w, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; class initiate_async_accept { public: typedef Executor executor_type; explicit initiate_async_accept(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename AcceptHandler, typename Protocol1, typename Executor1> void operator()(AcceptHandler&& handler, basic_socket<Protocol1, Executor1>* peer, endpoint_type* peer_endpoint) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a AcceptHandler. ASIO_ACCEPT_HANDLER_CHECK(AcceptHandler, handler) type_check; detail::non_const_lvalue<AcceptHandler> handler2(handler); self_->impl_.get_service().async_accept( self_->impl_.get_implementation(), *peer, peer_endpoint, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; class initiate_async_move_accept { public: typedef Executor executor_type; explicit initiate_async_move_accept(basic_socket_acceptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename MoveAcceptHandler, typename Executor1, typename Socket> void operator()(MoveAcceptHandler&& handler, const Executor1& peer_ex, endpoint_type* peer_endpoint, Socket*) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a MoveAcceptHandler. ASIO_MOVE_ACCEPT_HANDLER_CHECK( MoveAcceptHandler, handler, Socket) type_check; detail::non_const_lvalue<MoveAcceptHandler> handler2(handler); self_->impl_.get_service().async_move_accept( self_->impl_.get_implementation(), peer_ex, peer_endpoint, handler2.value, self_->impl_.get_executor()); } private: basic_socket_acceptor* self_; }; #if defined(ASIO_WINDOWS_RUNTIME) detail::io_object_impl< detail::null_socket_service<Protocol>, Executor> impl_; #elif defined(ASIO_HAS_IOCP) detail::io_object_impl< detail::win_iocp_socket_service<Protocol>, Executor> impl_; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl< detail::io_uring_socket_service<Protocol>, Executor> impl_; #else detail::io_object_impl< detail::reactive_socket_service<Protocol>, Executor> impl_; #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_SOCKET_ACCEPTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/io_context_strand.hpp
// // io_context_strand.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 ASIO_IO_CONTEXT_STRAND_HPP #define ASIO_IO_CONTEXT_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_EXTENSIONS) \ && !defined(ASIO_NO_TS_EXECUTORS) #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/strand_service.hpp" #include "asio/detail/wrapped_handler.hpp" #include "asio/io_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides serialised handler execution. /** * The io_context::strand class provides the ability to post and dispatch * handlers with the guarantee that none of those handlers will execute * concurrently. * * @par Order of handler invocation * Given: * * @li a strand object @c s * * @li an object @c a meeting completion handler requirements * * @li an object @c a1 which is an arbitrary copy of @c a made by the * implementation * * @li an object @c b meeting completion handler requirements * * @li an object @c b1 which is an arbitrary copy of @c b made by the * implementation * * if any of the following conditions are true: * * @li @c s.post(a) happens-before @c s.post(b) * * @li @c s.post(a) happens-before @c s.dispatch(b), where the latter is * performed outside the strand * * @li @c s.dispatch(a) happens-before @c s.post(b), where the former is * performed outside the strand * * @li @c s.dispatch(a) happens-before @c s.dispatch(b), where both are * performed outside the strand * * then @c a() happens-before @c b() * * Note that in the following case: * @code async_op_1(..., s.wrap(a)); * async_op_2(..., s.wrap(b)); @endcode * the completion of the first async operation will perform @c s.dispatch(a), * and the second will perform @c s.dispatch(b), but the order in which those * are performed is unspecified. That is, you cannot state whether one * happens-before the other. Therefore none of the above conditions are met and * no ordering guarantee is made. * * @note The implementation makes no guarantee that handlers posted or * dispatched through different @c strand objects will be invoked concurrently. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Safe. * * @par Concepts: * Dispatcher. */ class io_context::strand { private: #if !defined(ASIO_NO_DEPRECATED) struct initiate_dispatch; struct initiate_post; #endif // !defined(ASIO_NO_DEPRECATED) public: /// Constructor. /** * Constructs the strand. * * @param io_context The io_context object that the strand will use to * dispatch handlers that are ready to be run. */ explicit strand(asio::io_context& io_context) : service_(asio::use_service< asio::detail::strand_service>(io_context)) { service_.construct(impl_); } /// Copy constructor. /** * Creates a copy such that both strand objects share the same underlying * state. */ strand(const strand& other) noexcept : service_(other.service_), impl_(other.impl_) { } /// Destructor. /** * Destroys a strand. * * Handlers posted through the strand that have not yet been invoked will * still be dispatched in a way that meets the guarantee of non-concurrency. */ ~strand() { } /// Obtain the underlying execution context. asio::io_context& context() const noexcept { return service_.get_io_context(); } /// Inform the strand that it has some outstanding work to do. /** * The strand delegates this call to its underlying io_context. */ void on_work_started() const noexcept { context().get_executor().on_work_started(); } /// Inform the strand that some work is no longer outstanding. /** * The strand delegates this call to its underlying io_context. */ void on_work_finished() const noexcept { context().get_executor().on_work_finished(); } /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying io_context. The function object will be executed * inside this function if the strand is not otherwise busy and if the * underlying io_context's executor's @c dispatch() function is also able to * execute the function before returning. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void dispatch(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.dispatch(impl_, tmp); (void)a; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use asio::dispatch().) Request the strand to invoke /// the given handler. /** * This function is used to ask the strand to execute the given handler. * * The strand object guarantees that handlers posted or dispatched through * the strand will not be executed concurrently. The handler may be executed * inside this function if the guarantee can be met. If this function is * called from within a handler that was posted or dispatched through the same * strand, then the new handler will be executed immediately. * * The strand's guarantee is in addition to the guarantee provided by the * underlying io_context. The io_context guarantees that the handler will only * be called in a thread in which the io_context's run member function is * currently being invoked. * * @param handler The handler to be called. The strand will make a copy of the * handler object as required. The function signature of the handler must be: * @code void handler(); @endcode */ template <typename LegacyCompletionHandler> auto dispatch(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_dispatch>(), handler, this)) { return async_initiate<LegacyCompletionHandler, void ()>( initiate_dispatch(), handler, this); } #endif // !defined(ASIO_NO_DEPRECATED) /// Request the strand to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run by the underlying io_context. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void post(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.post(impl_, tmp); (void)a; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use asio::post().) Request the strand to invoke the /// given handler and return immediately. /** * This function is used to ask the strand to execute the given handler, but * without allowing the strand to call the handler from inside this function. * * The strand object guarantees that handlers posted or dispatched through * the strand will not be executed concurrently. The strand's guarantee is in * addition to the guarantee provided by the underlying io_context. The * io_context guarantees that the handler will only be called in a thread in * which the io_context's run member function is currently being invoked. * * @param handler The handler to be called. The strand will make a copy of the * handler object as required. The function signature of the handler must be: * @code void handler(); @endcode */ template <typename LegacyCompletionHandler> auto post(LegacyCompletionHandler&& handler) -> decltype( async_initiate<LegacyCompletionHandler, void ()>( declval<initiate_post>(), handler, this)) { return async_initiate<LegacyCompletionHandler, void ()>( initiate_post(), handler, this); } #endif // !defined(ASIO_NO_DEPRECATED) /// Request the strand to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled to run by the underlying io_context. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void defer(Function&& f, const Allocator& a) const { decay_t<Function> tmp(static_cast<Function&&>(f)); service_.post(impl_, tmp); (void)a; } #if !defined(ASIO_NO_DEPRECATED) /// (Deprecated: Use asio::bind_executor().) Create a new handler that /// automatically dispatches the wrapped handler on the strand. /** * This function is used to create a new handler function object that, when * invoked, will automatically pass the wrapped handler to the strand's * dispatch function. * * @param handler The handler to be wrapped. The strand will make a copy of * the handler object as required. The function signature of the handler must * be: @code void handler(A1 a1, ... An an); @endcode * * @return A function object that, when invoked, passes the wrapped handler to * the strand's dispatch function. Given a function object with the signature: * @code R f(A1 a1, ... An an); @endcode * If this function object is passed to the wrap function like so: * @code strand.wrap(f); @endcode * then the return value is a function object with the signature * @code void g(A1 a1, ... An an); @endcode * that, when invoked, executes code equivalent to: * @code strand.dispatch(boost::bind(f, a1, ... an)); @endcode */ template <typename Handler> #if defined(GENERATING_DOCUMENTATION) unspecified #else detail::wrapped_handler<strand, Handler, detail::is_continuation_if_running> #endif wrap(Handler handler) { return detail::wrapped_handler<io_context::strand, Handler, detail::is_continuation_if_running>(*this, handler); } #endif // !defined(ASIO_NO_DEPRECATED) /// Determine whether the strand is running in the current thread. /** * @return @c true if the current thread is executing a handler that was * submitted to the strand using post(), dispatch() or wrap(). Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept { return service_.running_in_this_thread(impl_); } /// Compare two strands for equality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator==(const strand& a, const strand& b) noexcept { return a.impl_ == b.impl_; } /// Compare two strands for inequality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator!=(const strand& a, const strand& b) noexcept { return a.impl_ != b.impl_; } private: #if !defined(ASIO_NO_DEPRECATED) struct initiate_dispatch { template <typename LegacyCompletionHandler> void operator()(LegacyCompletionHandler&& handler, strand* self) const { // If you get an error on the following line it means that your // handler does not meet the documented type requirements for a // LegacyCompletionHandler. ASIO_LEGACY_COMPLETION_HANDLER_CHECK( LegacyCompletionHandler, handler) type_check; detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler); self->service_.dispatch(self->impl_, handler2.value); } }; struct initiate_post { template <typename LegacyCompletionHandler> void operator()(LegacyCompletionHandler&& handler, strand* self) const { // If you get an error on the following line it means that your // handler does not meet the documented type requirements for a // LegacyCompletionHandler. ASIO_LEGACY_COMPLETION_HANDLER_CHECK( LegacyCompletionHandler, handler) type_check; detail::non_const_lvalue<LegacyCompletionHandler> handler2(handler); self->service_.post(self->impl_, handler2.value); } }; #endif // !defined(ASIO_NO_DEPRECATED) asio::detail::strand_service& service_; mutable asio::detail::strand_service::implementation_type impl_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_NO_EXTENSIONS) // && !defined(ASIO_NO_TS_EXECUTORS) #endif // ASIO_IO_CONTEXT_STRAND_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/async_result.hpp
// // async_result.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 ASIO_ASYNC_RESULT_HPP #define ASIO_ASYNC_RESULT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename T> struct is_completion_signature : false_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...)> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) &> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) &&> : true_type { }; # if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_completion_signature<R(Args...) noexcept> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) & noexcept> : true_type { }; template <typename R, typename... Args> struct is_completion_signature<R(Args...) && noexcept> : true_type { }; # endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... T> struct are_completion_signatures : false_type { }; template <> struct are_completion_signatures<> : true_type { }; template <typename T0> struct are_completion_signatures<T0> : is_completion_signature<T0> { }; template <typename T0, typename... TN> struct are_completion_signatures<T0, TN...> : integral_constant<bool, ( is_completion_signature<T0>::value && are_completion_signatures<TN...>::value)> { }; } // namespace detail #if defined(ASIO_HAS_CONCEPTS) namespace detail { template <typename T, typename... Args> ASIO_CONCEPT callable_with = requires(T&& t, Args&&... args) { static_cast<T&&>(t)(static_cast<Args&&>(args)...); }; template <typename T, typename... Signatures> struct is_completion_handler_for : false_type { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...)> : integral_constant<bool, (callable_with<decay_t<T>, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) &> : integral_constant<bool, (callable_with<decay_t<T>&, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) &&> : integral_constant<bool, (callable_with<decay_t<T>&&, Args...>)> { }; # if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) noexcept> : integral_constant<bool, (callable_with<decay_t<T>, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) & noexcept> : integral_constant<bool, (callable_with<decay_t<T>&, Args...>)> { }; template <typename T, typename R, typename... Args> struct is_completion_handler_for<T, R(Args...) && noexcept> : integral_constant<bool, (callable_with<decay_t<T>&&, Args...>)> { }; # endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename T, typename Signature0, typename... SignatureN> struct is_completion_handler_for<T, Signature0, SignatureN...> : integral_constant<bool, ( is_completion_handler_for<T, Signature0>::value && is_completion_handler_for<T, SignatureN...>::value)> { }; } // namespace detail template <typename T> ASIO_CONCEPT completion_signature = detail::is_completion_signature<T>::value; #define ASIO_COMPLETION_SIGNATURE \ ::asio::completion_signature template <typename T, typename... Signatures> ASIO_CONCEPT completion_handler_for = detail::are_completion_signatures<Signatures...>::value && detail::is_completion_handler_for<T, Signatures...>::value; #define ASIO_COMPLETION_HANDLER_FOR(sig) \ ::asio::completion_handler_for<sig> #define ASIO_COMPLETION_HANDLER_FOR2(sig0, sig1) \ ::asio::completion_handler_for<sig0, sig1> #define ASIO_COMPLETION_HANDLER_FOR3(sig0, sig1, sig2) \ ::asio::completion_handler_for<sig0, sig1, sig2> #else // defined(ASIO_HAS_CONCEPTS) #define ASIO_COMPLETION_SIGNATURE typename #define ASIO_COMPLETION_HANDLER_FOR(sig) typename #define ASIO_COMPLETION_HANDLER_FOR2(sig0, sig1) typename #define ASIO_COMPLETION_HANDLER_FOR3(sig0, sig1, sig2) typename #endif // defined(ASIO_HAS_CONCEPTS) namespace detail { template <typename T> struct is_lvalue_completion_signature : false_type { }; template <typename R, typename... Args> struct is_lvalue_completion_signature<R(Args...) &> : true_type { }; # if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_lvalue_completion_signature<R(Args...) & noexcept> : true_type { }; # endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... Signatures> struct are_any_lvalue_completion_signatures : false_type { }; template <typename Sig0> struct are_any_lvalue_completion_signatures<Sig0> : is_lvalue_completion_signature<Sig0> { }; template <typename Sig0, typename... SigN> struct are_any_lvalue_completion_signatures<Sig0, SigN...> : integral_constant<bool, ( is_lvalue_completion_signature<Sig0>::value || are_any_lvalue_completion_signatures<SigN...>::value)> { }; template <typename T> struct is_rvalue_completion_signature : false_type { }; template <typename R, typename... Args> struct is_rvalue_completion_signature<R(Args...) &&> : true_type { }; # if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct is_rvalue_completion_signature<R(Args...) && noexcept> : true_type { }; # endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename... Signatures> struct are_any_rvalue_completion_signatures : false_type { }; template <typename Sig0> struct are_any_rvalue_completion_signatures<Sig0> : is_rvalue_completion_signature<Sig0> { }; template <typename Sig0, typename... SigN> struct are_any_rvalue_completion_signatures<Sig0, SigN...> : integral_constant<bool, ( is_rvalue_completion_signature<Sig0>::value || are_any_rvalue_completion_signatures<SigN...>::value)> { }; template <typename T> struct simple_completion_signature; template <typename R, typename... Args> struct simple_completion_signature<R(Args...)> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) &> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) &&> { typedef R type(Args...); }; # if defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename R, typename... Args> struct simple_completion_signature<R(Args...) noexcept> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) & noexcept> { typedef R type(Args...); }; template <typename R, typename... Args> struct simple_completion_signature<R(Args...) && noexcept> { typedef R type(Args...); }; # endif // defined(ASIO_HAS_NOEXCEPT_FUNCTION_TYPE) template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures> class completion_handler_async_result { public: typedef CompletionToken completion_handler_type; typedef void return_type; explicit completion_handler_async_result(completion_handler_type&) { } return_type get() { } template <typename Initiation, ASIO_COMPLETION_HANDLER_FOR(Signatures...) RawCompletionToken, typename... Args> static return_type initiate(Initiation&& initiation, RawCompletionToken&& token, Args&&... args) { static_cast<Initiation&&>(initiation)( static_cast<RawCompletionToken&&>(token), static_cast<Args&&>(args)...); } private: completion_handler_async_result( const completion_handler_async_result&) = delete; completion_handler_async_result& operator=( const completion_handler_async_result&) = delete; }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) /// An interface for customising the behaviour of an initiating function. /** * The async_result traits class is used for determining: * * @li the concrete completion handler type to be called at the end of the * asynchronous operation; * * @li the initiating function return type; and * * @li how the return value of the initiating function is obtained. * * The trait allows the handler and return types to be determined at the point * where the specific completion handler signature is known. * * This template may be specialised for user-defined completion token types. * The primary template assumes that the CompletionToken is the completion * handler. */ template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures> class async_result { public: /// The concrete completion handler type for the specific signature. typedef CompletionToken completion_handler_type; /// The return type of the initiating function. typedef void return_type; /// Construct an async result from a given handler. /** * When using a specalised async_result, the constructor has an opportunity * to initialise some state associated with the completion handler, which is * then returned from the initiating function. */ explicit async_result(completion_handler_type& h); /// Obtain the value to be returned from the initiating function. return_type get(); /// Initiate the asynchronous operation that will produce the result, and /// obtain the value to be returned from the initiating function. template <typename Initiation, typename RawCompletionToken, typename... Args> static return_type initiate( Initiation&& initiation, RawCompletionToken&& token, Args&&... args); private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; }; #else // defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures> class async_result : public conditional_t< detail::are_any_lvalue_completion_signatures<Signatures...>::value || !detail::are_any_rvalue_completion_signatures<Signatures...>::value, detail::completion_handler_async_result<CompletionToken, Signatures...>, async_result<CompletionToken, typename detail::simple_completion_signature<Signatures>::type...> > { public: typedef conditional_t< detail::are_any_lvalue_completion_signatures<Signatures...>::value || !detail::are_any_rvalue_completion_signatures<Signatures...>::value, detail::completion_handler_async_result<CompletionToken, Signatures...>, async_result<CompletionToken, typename detail::simple_completion_signature<Signatures>::type...> > base_type; using base_type::base_type; private: async_result(const async_result&) = delete; async_result& operator=(const async_result&) = delete; }; template <ASIO_COMPLETION_SIGNATURE... Signatures> class async_result<void, Signatures...> { // Empty. }; #endif // defined(GENERATING_DOCUMENTATION) /// Helper template to deduce the handler type from a CompletionToken, capture /// a local copy of the handler, and then create an async_result for the /// handler. template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures> struct async_completion { /// The real handler type to be used for the asynchronous operation. typedef typename asio::async_result< decay_t<CompletionToken>, Signatures...>::completion_handler_type completion_handler_type; /// Constructor. /** * The constructor creates the concrete completion handler and makes the link * between the handler and the asynchronous result. */ explicit async_completion(CompletionToken& token) : completion_handler(static_cast<conditional_t< is_same<CompletionToken, completion_handler_type>::value, completion_handler_type&, CompletionToken&&>>(token)), result(completion_handler) { } /// A copy of, or reference to, a real handler object. conditional_t< is_same<CompletionToken, completion_handler_type>::value, completion_handler_type&, completion_handler_type> completion_handler; /// The result of the asynchronous operation's initiating function. async_result<decay_t<CompletionToken>, Signatures...> result; }; namespace detail { struct async_result_memfns_base { void initiate(); }; template <typename T> struct async_result_memfns_derived : T, async_result_memfns_base { }; template <typename T, T> struct async_result_memfns_check { }; template <typename> char (&async_result_initiate_memfn_helper(...))[2]; template <typename T> char async_result_initiate_memfn_helper( async_result_memfns_check< void (async_result_memfns_base::*)(), &async_result_memfns_derived<T>::initiate>*); template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures> struct async_result_has_initiate_memfn : integral_constant<bool, sizeof(async_result_initiate_memfn_helper< async_result<decay_t<CompletionToken>, Signatures...> >(0)) != 1> { }; } // namespace detail #if defined(GENERATING_DOCUMENTATION) # define ASIO_INITFN_RESULT_TYPE(ct, sig) \ void_or_deduced # define ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) \ void_or_deduced # define ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) \ void_or_deduced #else # define ASIO_INITFN_RESULT_TYPE(ct, sig) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, sig>::return_type # define ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, sig0, sig1>::return_type # define ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, sig0, sig1, sig2>::return_type #define ASIO_HANDLER_TYPE(ct, sig) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, sig>::completion_handler_type #define ASIO_HANDLER_TYPE2(ct, sig0, sig1) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, \ sig0, sig1>::completion_handler_type #define ASIO_HANDLER_TYPE3(ct, sig0, sig1, sig2) \ typename ::asio::async_result< \ typename ::asio::decay<ct>::type, \ sig0, sig1, sig2>::completion_handler_type #endif #if defined(GENERATING_DOCUMENTATION) # define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ auto #elif defined(ASIO_HAS_RETURN_TYPE_DEDUCTION) # define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ auto #else # define ASIO_INITFN_AUTO_RESULT_TYPE(ct, sig) \ ASIO_INITFN_RESULT_TYPE(ct, sig) # define ASIO_INITFN_AUTO_RESULT_TYPE2(ct, sig0, sig1) \ ASIO_INITFN_RESULT_TYPE2(ct, sig0, sig1) # define ASIO_INITFN_AUTO_RESULT_TYPE3(ct, sig0, sig1, sig2) \ ASIO_INITFN_RESULT_TYPE3(ct, sig0, sig1, sig2) #endif #if defined(GENERATING_DOCUMENTATION) # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) #elif defined(ASIO_HAS_RETURN_TYPE_DEDUCTION) # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) #else # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX(ct, sig) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX2(ct, sig0, sig1) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_PREFIX3(ct, sig0, sig1, sig2) \ auto # define ASIO_INITFN_AUTO_RESULT_TYPE_SUFFIX(expr) -> decltype expr #endif #if defined(GENERATING_DOCUMENTATION) # define ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ void_or_deduced # define ASIO_INITFN_DEDUCED_RESULT_TYPE2(ct, sig0, sig1, expr) \ void_or_deduced # define ASIO_INITFN_DEDUCED_RESULT_TYPE3(ct, sig0, sig1, sig2, expr) \ void_or_deduced #else # define ASIO_INITFN_DEDUCED_RESULT_TYPE(ct, sig, expr) \ decltype expr # define ASIO_INITFN_DEDUCED_RESULT_TYPE2(ct, sig0, sig1, expr) \ decltype expr # define ASIO_INITFN_DEDUCED_RESULT_TYPE3(ct, sig0, sig1, sig2, expr) \ decltype expr #endif #if defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, completion_signature... Signatures, typename Initiation, typename... Args> void_or_deduced async_initiate( Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args); #else // defined(GENERATING_DOCUMENTATION) template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures, typename Initiation, typename... Args> inline auto async_initiate(Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args) -> decltype(enable_if_t< enable_if_t< detail::are_completion_signatures<Signatures...>::value, detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>>::value, async_result<decay_t<CompletionToken>, Signatures...>>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...)) { return async_result<decay_t<CompletionToken>, Signatures...>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...); } template < ASIO_COMPLETION_SIGNATURE... Signatures, typename CompletionToken, typename Initiation, typename... Args> inline auto async_initiate(Initiation&& initiation, CompletionToken&& token, Args&&... args) -> decltype(enable_if_t< enable_if_t< detail::are_completion_signatures<Signatures...>::value, detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>>::value, async_result<decay_t<CompletionToken>, Signatures...>>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...)) { return async_result<decay_t<CompletionToken>, Signatures...>::initiate( static_cast<Initiation&&>(initiation), static_cast<CompletionToken&&>(token), static_cast<Args&&>(args)...); } template <typename CompletionToken, ASIO_COMPLETION_SIGNATURE... Signatures, typename Initiation, typename... Args> inline typename enable_if_t< !enable_if_t< detail::are_completion_signatures<Signatures...>::value, detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>>::value, async_result<decay_t<CompletionToken>, Signatures...> >::return_type async_initiate(Initiation&& initiation, type_identity_t<CompletionToken>& token, Args&&... args) { async_completion<CompletionToken, Signatures...> completion(token); static_cast<Initiation&&>(initiation)( static_cast< typename async_result<decay_t<CompletionToken>, Signatures...>::completion_handler_type&&>( completion.completion_handler), static_cast<Args&&>(args)...); return completion.result.get(); } template <ASIO_COMPLETION_SIGNATURE... Signatures, typename CompletionToken, typename Initiation, typename... Args> inline typename enable_if_t< !enable_if_t< detail::are_completion_signatures<Signatures...>::value, detail::async_result_has_initiate_memfn< CompletionToken, Signatures...>>::value, async_result<decay_t<CompletionToken>, Signatures...> >::return_type async_initiate(Initiation&& initiation, CompletionToken&& token, Args&&... args) { async_completion<CompletionToken, Signatures...> completion(token); static_cast<Initiation&&>(initiation)( static_cast< typename async_result<decay_t<CompletionToken>, Signatures...>::completion_handler_type&&>( completion.completion_handler), static_cast<Args&&>(args)...); return completion.result.get(); } #endif // defined(GENERATING_DOCUMENTATION) #if defined(ASIO_HAS_CONCEPTS) namespace detail { template <typename... Signatures> struct initiation_archetype { template <completion_handler_for<Signatures...> CompletionHandler> void operator()(CompletionHandler&&) const { } }; } // namespace detail template <typename T, typename... Signatures> ASIO_CONCEPT completion_token_for = detail::are_completion_signatures<Signatures...>::value && requires(T&& t) { async_initiate<T, Signatures...>( detail::initiation_archetype<Signatures...>{}, t); }; #define ASIO_COMPLETION_TOKEN_FOR(sig) \ ::asio::completion_token_for<sig> #define ASIO_COMPLETION_TOKEN_FOR2(sig0, sig1) \ ::asio::completion_token_for<sig0, sig1> #define ASIO_COMPLETION_TOKEN_FOR3(sig0, sig1, sig2) \ ::asio::completion_token_for<sig0, sig1, sig2> #else // defined(ASIO_HAS_CONCEPTS) #define ASIO_COMPLETION_TOKEN_FOR(sig) typename #define ASIO_COMPLETION_TOKEN_FOR2(sig0, sig1) typename #define ASIO_COMPLETION_TOKEN_FOR3(sig0, sig1, sig2) typename #endif // defined(ASIO_HAS_CONCEPTS) namespace detail { struct async_operation_probe {}; struct async_operation_probe_result {}; template <typename Call, typename = void> struct is_async_operation_call : false_type { }; template <typename Call> struct is_async_operation_call<Call, void_t< enable_if_t< is_same< result_of_t<Call>, async_operation_probe_result >::value > > > : true_type { }; } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <typename... Signatures> class async_result<detail::async_operation_probe, Signatures...> { public: typedef detail::async_operation_probe_result return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::async_operation_probe, InitArgs&&...) { return return_type(); } }; #endif // !defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The is_async_operation trait detects whether a type @c T and arguments /// @c Args... may be used to initiate an asynchronous operation. /** * Class template @c is_async_operation is a trait is derived from @c true_type * if the expression <tt>T(Args..., token)</tt> initiates an asynchronous * operation, where @c token is an unspecified completion token type. Otherwise, * @c is_async_operation is derived from @c false_type. */ template <typename T, typename... Args> struct is_async_operation : integral_constant<bool, automatically_determined> { }; #else // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> struct is_async_operation : detail::is_async_operation_call< T(Args..., detail::async_operation_probe)> { }; #endif // defined(GENERATING_DOCUMENTATION) #if defined(ASIO_HAS_CONCEPTS) template <typename T, typename... Args> ASIO_CONCEPT async_operation = is_async_operation<T, Args...>::value; #define ASIO_ASYNC_OPERATION(t) \ ::asio::async_operation<t> #define ASIO_ASYNC_OPERATION1(t, a0) \ ::asio::async_operation<t, a0> #define ASIO_ASYNC_OPERATION2(t, a0, a1) \ ::asio::async_operation<t, a0, a1> #define ASIO_ASYNC_OPERATION3(t, a0, a1, a2) \ ::asio::async_operation<t, a0, a1, a2> #else // defined(ASIO_HAS_CONCEPTS) #define ASIO_ASYNC_OPERATION(t) typename #define ASIO_ASYNC_OPERATION1(t, a0) typename #define ASIO_ASYNC_OPERATION2(t, a0, a1) typename #define ASIO_ASYNC_OPERATION3(t, a0, a1, a2) typename #endif // defined(ASIO_HAS_CONCEPTS) namespace detail { struct completion_signature_probe {}; template <typename... T> struct completion_signature_probe_result { template <template <typename...> class Op> struct apply { typedef Op<T...> type; }; }; template <typename T> struct completion_signature_probe_result<T> { typedef T type; template <template <typename...> class Op> struct apply { typedef Op<T> type; }; }; template <> struct completion_signature_probe_result<void> { template <template <typename...> class Op> struct apply { typedef Op<> type; }; }; } // namespace detail #if !defined(GENERATING_DOCUMENTATION) template <typename... Signatures> class async_result<detail::completion_signature_probe, Signatures...> { public: typedef detail::completion_signature_probe_result<Signatures...> return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::completion_signature_probe, InitArgs&&...) { return return_type(); } }; template <typename Signature> class async_result<detail::completion_signature_probe, Signature> { public: typedef detail::completion_signature_probe_result<Signature> return_type; template <typename Initiation, typename... InitArgs> static return_type initiate(Initiation&&, detail::completion_signature_probe, InitArgs&&...) { return return_type(); } }; #endif // !defined(GENERATING_DOCUMENTATION) #if defined(GENERATING_DOCUMENTATION) /// The completion_signature_of trait determines the completion signature /// of an asynchronous operation. /** * Class template @c completion_signature_of is a trait with a member type * alias @c type that denotes the completion signature of the asynchronous * operation initiated by the expression <tt>T(Args..., token)</tt> operation, * where @c token is an unspecified completion token type. If the asynchronous * operation does not have exactly one completion signature, the instantion of * the trait is well-formed but the member type alias @c type is omitted. If * the expression <tt>T(Args..., token)</tt> is not an asynchronous operation * then use of the trait is ill-formed. */ template <typename T, typename... Args> struct completion_signature_of { typedef automatically_determined type; }; #else // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> struct completion_signature_of : result_of_t<T(Args..., detail::completion_signature_probe)> { }; #endif // defined(GENERATING_DOCUMENTATION) template <typename T, typename... Args> using completion_signature_of_t = typename completion_signature_of<T, Args...>::type; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/default_completion_token.hpp" #endif // ASIO_ASYNC_RESULT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/multiple_exceptions.hpp
// // multiple_exceptions.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 ASIO_MULTIPLE_EXCEPTIONS_HPP #define ASIO_MULTIPLE_EXCEPTIONS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <exception> #include "asio/detail/push_options.hpp" namespace asio { /// Exception thrown when there are multiple pending exceptions to rethrow. class multiple_exceptions : public std::exception { public: /// Constructor. ASIO_DECL multiple_exceptions( std::exception_ptr first) noexcept; /// Obtain message associated with exception. ASIO_DECL virtual const char* what() const noexcept; /// Obtain a pointer to the first exception. ASIO_DECL std::exception_ptr first_exception() const; private: std::exception_ptr first_; }; } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/multiple_exceptions.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_MULTIPLE_EXCEPTIONS_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_raw_socket.hpp
// // basic_raw_socket.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 ASIO_BASIC_RAW_SOCKET_HPP #define ASIO_BASIC_RAW_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/basic_socket.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_RAW_SOCKET_FWD_DECL) #define ASIO_BASIC_RAW_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_raw_socket; #endif // !defined(ASIO_BASIC_RAW_SOCKET_FWD_DECL) /// Provides raw-oriented socket functionality. /** * The basic_raw_socket class template provides asynchronous and blocking * raw-oriented socket functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c send, @c send_to, @c receive, @c receive_from, @c connect, * and @c shutdown operations are thread safe with respect to each other, if * the underlying operating system calls are also thread safe. This means that * it is permitted to perform concurrent calls to these synchronous operations * on a single socket object. Other synchronous operations, such as @c open or * @c close, are not thread safe. */ template <typename Protocol, typename Executor> class basic_raw_socket : public basic_socket<Protocol, Executor> { private: class initiate_async_send; class initiate_async_send_to; class initiate_async_receive; class initiate_async_receive_from; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_raw_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef typename basic_socket<Protocol, Executor>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; /// Construct a basic_raw_socket without opening it. /** * This constructor creates a raw socket without opening it. The open() * function must be called before data can be sent or received on the socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_raw_socket(const executor_type& ex) : basic_socket<Protocol, Executor>(ex) { } /// Construct a basic_raw_socket without opening it. /** * This constructor creates a raw socket without opening it. The open() * function must be called before data can be sent or received on the socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template <typename ExecutionContext> explicit basic_raw_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context) { } /// Construct and open a basic_raw_socket. /** * This constructor creates and opens a raw socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_raw_socket(const executor_type& ex, const protocol_type& protocol) : basic_socket<Protocol, Executor>(ex, protocol) { } /// Construct and open a basic_raw_socket. /** * This constructor creates and opens a raw socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_raw_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_socket<Protocol, Executor>(context, protocol) { } /// Construct a basic_raw_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a raw socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the raw * socket will be bound. * * @throws asio::system_error Thrown on failure. */ basic_raw_socket(const executor_type& ex, const endpoint_type& endpoint) : basic_socket<Protocol, Executor>(ex, endpoint) { } /// Construct a basic_raw_socket, opening it and binding it to the given /// local endpoint. /** * This constructor creates a raw socket and automatically opens it bound * to the specified endpoint on the local machine. The protocol used is the * protocol associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the raw * socket will be bound. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_raw_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, endpoint) { } /// Construct a basic_raw_socket on an existing native socket. /** * This constructor creates a raw socket object to hold an existing * native socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ basic_raw_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : basic_socket<Protocol, Executor>(ex, protocol, native_socket) { } /// Construct a basic_raw_socket on an existing native socket. /** * This constructor creates a raw socket object to hold an existing * native socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket The new underlying socket implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_raw_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_socket<Protocol, Executor>(context, protocol, native_socket) { } /// Move-construct a basic_raw_socket from another. /** * This constructor moves a raw socket from one object to another. * * @param other The other basic_raw_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_raw_socket(const executor_type&) * constructor. */ basic_raw_socket(basic_raw_socket&& other) noexcept : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_raw_socket from another. /** * This assignment operator moves a raw socket from one object to another. * * @param other The other basic_raw_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_raw_socket(const executor_type&) * constructor. */ basic_raw_socket& operator=(basic_raw_socket&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_raw_socket from a socket of another protocol /// type. /** * This constructor moves a raw socket from one object to another. * * @param other The other basic_raw_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_raw_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> basic_raw_socket(basic_raw_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : basic_socket<Protocol, Executor>(std::move(other)) { } /// Move-assign a basic_raw_socket from a socket of another protocol type. /** * This assignment operator moves a raw socket from one object to another. * * @param other The other basic_raw_socket object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_raw_socket(const executor_type&) * constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_raw_socket& > operator=(basic_raw_socket<Protocol1, Executor1>&& other) { basic_socket<Protocol, Executor>::operator=(std::move(other)); return *this; } /// Destroys the socket. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_raw_socket() { } /// Send some data on a connected socket. /** * This function is used to send data on the raw socket. The function call * will block until the data has been sent successfully or an error occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected raw socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code socket.send(asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the raw socket. The function call * will block until the data has been sent successfully or an error occurs. * * @param buffers One ore more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected raw socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "send"); return s; } /// Send some data on a connected socket. /** * This function is used to send data on the raw socket. The function call * will block until the data has been sent successfully or an error occurs. * * @param buffers One or more data buffers to be sent on the socket. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. * * @note The send operation can only be used with a connected socket. Use * the send_to function to send data on an unconnected raw socket. */ template <typename ConstBufferSequence> std::size_t send(const ConstBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the raw socket. It is * an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected raw * socket. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * socket.async_send(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous send on a connected socket. /** * This function is used to asynchronously send data on the raw socket. It is * an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be sent on the socket. Although * the buffers object may be copied as necessary, ownership of the underlying * memory blocks is retained by the caller, which must guarantee that they * remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_send operation can only be used with a connected socket. * Use the async_send_to function to send data on an unconnected raw * socket. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send(const ConstBufferSequence& buffers, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send>(), token, buffers, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send(this), token, buffers, flags); } /// Send raw data to the specified endpoint. /** * This function is used to send raw data to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * asio::ip::udp::endpoint destination( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.send_to(asio::buffer(data, size), destination); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination) { asio::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, 0, ec); asio::detail::throw_error(ec, "send_to"); return s; } /// Send raw data to the specified endpoint. /** * This function is used to send raw data to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @returns The number of bytes sent. * * @throws asio::system_error Thrown on failure. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().send_to( this->impl_.get_implementation(), buffers, destination, flags, ec); asio::detail::throw_error(ec, "send_to"); return s; } /// Send raw data to the specified endpoint. /** * This function is used to send raw data to the specified remote endpoint. * The function call will block until the data has been sent successfully or * an error occurs. * * @param buffers One or more data buffers to be sent to the remote endpoint. * * @param destination The remote endpoint to which the data will be sent. * * @param flags Flags specifying how the send call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes sent. */ template <typename ConstBufferSequence> std::size_t send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().send_to(this->impl_.get_implementation(), buffers, destination, flags, ec); } /// Start an asynchronous send. /** * This function is used to asynchronously send raw data to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To send a single data buffer use the @ref buffer function as follows: * @code * asio::ip::udp::endpoint destination( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_send_to( * asio::buffer(data, size), destination, handler); * @endcode * See the @ref buffer documentation for information on sending multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, socket_base::message_flags(0))) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send_to(this), token, buffers, destination, socket_base::message_flags(0)); } /// Start an asynchronous send. /** * This function is used to asynchronously send raw data to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more data buffers to be sent to the remote endpoint. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param flags Flags specifying how the send call is to be made. * * @param destination The remote endpoint to which the data will be sent. * Copies will be made of the endpoint as required. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the send completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes sent. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_send_to(const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_send_to>(), token, buffers, destination, flags)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_send_to(this), token, buffers, destination, flags); } /// Receive some data on a connected socket. /** * This function is used to receive data on the raw socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected raw * socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.receive(asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, 0, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the raw socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected raw * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); asio::detail::throw_error(ec, "receive"); return s; } /// Receive some data on a connected socket. /** * This function is used to receive data on the raw socket. The function * call will block until data has been received successfully or an error * occurs. * * @param buffers One or more buffers into which the data will be received. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. * * @note The receive operation can only be used with a connected socket. Use * the receive_from function to receive data on an unconnected raw * socket. */ template <typename MutableBufferSequence> std::size_t receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().receive( this->impl_.get_implementation(), buffers, flags, ec); } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the raw * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * raw socket. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * socket.async_receive(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, socket_base::message_flags(0)); } /// Start an asynchronous receive on a connected socket. /** * This function is used to asynchronously receive data from the raw * socket. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_receive operation can only be used with a connected socket. * Use the async_receive_from function to receive data on an unconnected * raw socket. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive(const MutableBufferSequence& buffers, socket_base::message_flags flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive>(), token, buffers, flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive(this), token, buffers, flags); } /// Receive raw data with the endpoint of the sender. /** * This function is used to receive raw data. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the data. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code * asio::ip::udp::endpoint sender_endpoint; * socket.receive_from( * asio::buffer(data, size), sender_endpoint); * @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, 0, ec); asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive raw data with the endpoint of the sender. /** * This function is used to receive raw data. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the data. * * @param flags Flags specifying how the receive call is to be made. * * @returns The number of bytes received. * * @throws asio::system_error Thrown on failure. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags) { asio::error_code ec; std::size_t s = this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); asio::detail::throw_error(ec, "receive_from"); return s; } /// Receive raw data with the endpoint of the sender. /** * This function is used to receive raw data. The function call will block * until data has been received successfully or an error occurs. * * @param buffers One or more buffers into which the data will be received. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the data. * * @param flags Flags specifying how the receive call is to be made. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes received. */ template <typename MutableBufferSequence> std::size_t receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, asio::error_code& ec) { return this->impl_.get_service().receive_from( this->impl_.get_implementation(), buffers, sender_endpoint, flags, ec); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive raw data. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the data. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Example * To receive into a single data buffer use the @ref buffer function as * follows: * @code socket.async_receive_from( * asio::buffer(data, size), 0, sender_endpoint, handler); @endcode * See the @ref buffer documentation for information on receiving into * multiple buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, socket_base::message_flags(0))) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_from(this), token, buffers, &sender_endpoint, socket_base::message_flags(0)); } /// Start an asynchronous receive. /** * This function is used to asynchronously receive raw data. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more buffers into which the data will be received. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param sender_endpoint An endpoint object that receives the endpoint of * the remote sender of the data. Ownership of the sender_endpoint object * is retained by the caller, which must guarantee that it is valid until the * completion handler is called. * * @param flags Flags specifying how the receive call is to be made. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the receive completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes received. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_receive_from(const MutableBufferSequence& buffers, endpoint_type& sender_endpoint, socket_base::message_flags flags, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_receive_from>(), token, buffers, &sender_endpoint, flags)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_receive_from(this), token, buffers, &sender_endpoint, flags); } private: // Disallow copying and assignment. basic_raw_socket(const basic_raw_socket&) = delete; basic_raw_socket& operator=(const basic_raw_socket&) = delete; class initiate_async_send { public: typedef Executor executor_type; explicit initiate_async_send(basic_raw_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_raw_socket* self_; }; class initiate_async_send_to { public: typedef Executor executor_type; explicit initiate_async_send_to(basic_raw_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers, const endpoint_type& destination, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_send_to( self_->impl_.get_implementation(), buffers, destination, flags, handler2.value, self_->impl_.get_executor()); } private: basic_raw_socket* self_; }; class initiate_async_receive { public: typedef Executor executor_type; explicit initiate_async_receive(basic_raw_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive( self_->impl_.get_implementation(), buffers, flags, handler2.value, self_->impl_.get_executor()); } private: basic_raw_socket* self_; }; class initiate_async_receive_from { public: typedef Executor executor_type; explicit initiate_async_receive_from(basic_raw_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers, endpoint_type* sender_endpoint, socket_base::message_flags flags) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_receive_from( self_->impl_.get_implementation(), buffers, *sender_endpoint, flags, handler2.value, self_->impl_.get_executor()); } private: basic_raw_socket* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_RAW_SOCKET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/append.hpp
// // append.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 ASIO_APPEND_HPP #define ASIO_APPEND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <tuple> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Completion token type used to specify that the completion handler /// arguments should be passed additional values after the results of the /// operation. template <typename CompletionToken, typename... Values> class append_t { public: /// Constructor. template <typename T, typename... V> constexpr explicit append_t(T&& completion_token, V&&... values) : token_(static_cast<T&&>(completion_token)), values_(static_cast<V&&>(values)...) { } //private: CompletionToken token_; std::tuple<Values...> values_; }; /// Completion token type used to specify that the completion handler /// arguments should be passed additional values after the results of the /// operation. template <typename CompletionToken, typename... Values> ASIO_NODISCARD inline constexpr append_t<decay_t<CompletionToken>, decay_t<Values>...> append(CompletionToken&& completion_token, Values&&... values) { return append_t<decay_t<CompletionToken>, decay_t<Values>...>( static_cast<CompletionToken&&>(completion_token), static_cast<Values&&>(values)...); } } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/append.hpp" #endif // ASIO_APPEND_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/readable_pipe.hpp
// // readable_pipe.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 ASIO_READABLE_PIPE_HPP #define ASIO_READABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/basic_readable_pipe.hpp" namespace asio { /// Typedef for the typical usage of a readable pipe. typedef basic_readable_pipe<> readable_pipe; } // namespace asio #endif // defined(ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_READABLE_PIPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/io_service.hpp
// // io_service.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 ASIO_IO_SERVICE_HPP #define ASIO_IO_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/io_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_NO_DEPRECATED) /// Typedef for backwards compatibility. typedef io_context io_service; #endif // !defined(ASIO_NO_DEPRECATED) } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IO_SERVICE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/yield.hpp
// // yield.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) // #include "coroutine.hpp" #ifndef reenter # define reenter(c) ASIO_CORO_REENTER(c) #endif #ifndef yield # define yield ASIO_CORO_YIELD #endif #ifndef fork # define fork ASIO_CORO_FORK #endif
0
repos/asio/asio/include
repos/asio/asio/include/asio/executor.hpp
// // executor.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 ASIO_EXECUTOR_HPP #define ASIO_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_TS_EXECUTORS) #include <new> #include <typeinfo> #include "asio/detail/cstddef.hpp" #include "asio/detail/executor_function.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/throw_exception.hpp" #include "asio/execution_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Exception thrown when trying to access an empty polymorphic executor. class bad_executor : public std::exception { public: /// Constructor. ASIO_DECL bad_executor() noexcept; /// Obtain message associated with exception. ASIO_DECL virtual const char* what() const noexcept; }; /// Polymorphic wrapper for executors. class executor { public: /// Default constructor. executor() noexcept : impl_(0) { } /// Construct from nullptr. executor(nullptr_t) noexcept : impl_(0) { } /// Copy constructor. executor(const executor& other) noexcept : impl_(other.clone()) { } /// Move constructor. executor(executor&& other) noexcept : impl_(other.impl_) { other.impl_ = 0; } /// Construct a polymorphic wrapper for the specified executor. template <typename Executor> executor(Executor e); /// Construct a polymorphic executor that points to the same target as /// another polymorphic executor. executor(std::nothrow_t, const executor& other) noexcept : impl_(other.clone()) { } /// Construct a polymorphic executor that moves the target from another /// polymorphic executor. executor(std::nothrow_t, executor&& other) noexcept : impl_(other.impl_) { other.impl_ = 0; } /// Construct a polymorphic wrapper for the specified executor. template <typename Executor> executor(std::nothrow_t, Executor e) noexcept; /// Allocator-aware constructor to create a polymorphic wrapper for the /// specified executor. template <typename Executor, typename Allocator> executor(allocator_arg_t, const Allocator& a, Executor e); /// Destructor. ~executor() { destroy(); } /// Assignment operator. executor& operator=(const executor& other) noexcept { destroy(); impl_ = other.clone(); return *this; } // Move assignment operator. executor& operator=(executor&& other) noexcept { destroy(); impl_ = other.impl_; other.impl_ = 0; return *this; } /// Assignment operator for nullptr_t. executor& operator=(nullptr_t) noexcept { destroy(); impl_ = 0; return *this; } /// Assignment operator to create a polymorphic wrapper for the specified /// executor. template <typename Executor> executor& operator=(Executor&& e) noexcept { executor tmp(static_cast<Executor&&>(e)); destroy(); impl_ = tmp.impl_; tmp.impl_ = 0; return *this; } /// Obtain the underlying execution context. execution_context& context() const noexcept { return get_impl()->context(); } /// Inform the executor that it has some outstanding work to do. void on_work_started() const noexcept { get_impl()->on_work_started(); } /// Inform the executor that some work is no longer outstanding. void on_work_finished() const noexcept { get_impl()->on_work_finished(); } /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @param f The function object to be called. The executor will make a copy * of the handler object as required. The function signature of the function * object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void dispatch(Function&& f, const Allocator& a) const; /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void post(Function&& f, const Allocator& a) const; /// Request the executor to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object is executed according to the rules of the * target executor object. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void defer(Function&& f, const Allocator& a) const; struct unspecified_bool_type_t {}; typedef void (*unspecified_bool_type)(unspecified_bool_type_t); static void unspecified_bool_true(unspecified_bool_type_t) {} /// Operator to test if the executor contains a valid target. operator unspecified_bool_type() const noexcept { return impl_ ? &executor::unspecified_bool_true : 0; } /// Obtain type information for the target executor object. /** * @returns If @c *this has a target type of type @c T, <tt>typeid(T)</tt>; * otherwise, <tt>typeid(void)</tt>. */ #if !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) const std::type_info& target_type() const noexcept { return impl_ ? impl_->target_type() : typeid(void); } #else // !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) const void* target_type() const noexcept { return impl_ ? impl_->target_type() : 0; } #endif // !defined(ASIO_NO_TYPEID) || defined(GENERATING_DOCUMENTATION) /// Obtain a pointer to the target executor object. /** * @returns If <tt>target_type() == typeid(T)</tt>, a pointer to the stored * executor target; otherwise, a null pointer. */ template <typename Executor> Executor* target() noexcept; /// Obtain a pointer to the target executor object. /** * @returns If <tt>target_type() == typeid(T)</tt>, a pointer to the stored * executor target; otherwise, a null pointer. */ template <typename Executor> const Executor* target() const noexcept; /// Compare two executors for equality. friend bool operator==(const executor& a, const executor& b) noexcept { if (a.impl_ == b.impl_) return true; if (!a.impl_ || !b.impl_) return false; return a.impl_->equals(b.impl_); } /// Compare two executors for inequality. friend bool operator!=(const executor& a, const executor& b) noexcept { return !(a == b); } private: #if !defined(GENERATING_DOCUMENTATION) typedef detail::executor_function function; template <typename, typename> class impl; #if !defined(ASIO_NO_TYPEID) typedef const std::type_info& type_id_result_type; #else // !defined(ASIO_NO_TYPEID) typedef const void* type_id_result_type; #endif // !defined(ASIO_NO_TYPEID) template <typename T> static type_id_result_type type_id() { #if !defined(ASIO_NO_TYPEID) return typeid(T); #else // !defined(ASIO_NO_TYPEID) static int unique_id; return &unique_id; #endif // !defined(ASIO_NO_TYPEID) } // Base class for all polymorphic executor implementations. class impl_base { public: virtual impl_base* clone() const noexcept = 0; virtual void destroy() noexcept = 0; virtual execution_context& context() noexcept = 0; virtual void on_work_started() noexcept = 0; virtual void on_work_finished() noexcept = 0; virtual void dispatch(function&&) = 0; virtual void post(function&&) = 0; virtual void defer(function&&) = 0; virtual type_id_result_type target_type() const noexcept = 0; virtual void* target() noexcept = 0; virtual const void* target() const noexcept = 0; virtual bool equals(const impl_base* e) const noexcept = 0; protected: impl_base(bool fast_dispatch) : fast_dispatch_(fast_dispatch) {} virtual ~impl_base() {} private: friend class executor; const bool fast_dispatch_; }; // Helper function to check and return the implementation pointer. impl_base* get_impl() const { if (!impl_) { bad_executor ex; asio::detail::throw_exception(ex); } return impl_; } // Helper function to clone another implementation. impl_base* clone() const noexcept { return impl_ ? impl_->clone() : 0; } // Helper function to destroy an implementation. void destroy() noexcept { if (impl_) impl_->destroy(); } impl_base* impl_; #endif // !defined(GENERATING_DOCUMENTATION) }; } // namespace asio ASIO_USES_ALLOCATOR(asio::executor) #include "asio/detail/pop_options.hpp" #include "asio/impl/executor.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/executor.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // !defined(ASIO_NO_TS_EXECUTORS) #endif // ASIO_EXECUTOR_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/detached.hpp
// // detached.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 ASIO_DETACHED_HPP #define ASIO_DETACHED_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <memory> #include "asio/detail/type_traits.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// A @ref completion_token type used to specify that an asynchronous operation /// is detached. /** * The detached_t class is used to indicate that an asynchronous operation is * detached. That is, there is no completion handler waiting for the * operation's result. A detached_t object may be passed as a handler to an * asynchronous operation, typically using the special value * @c asio::detached. For example: * * @code my_socket.async_send(my_buffer, asio::detached); * @endcode */ class detached_t { public: /// Constructor. constexpr detached_t() { } /// Adapts an executor to add the @c detached_t completion token as the /// default. template <typename InnerExecutor> struct executor_with_default : InnerExecutor { /// Specify @c detached_t as the default completion token type. typedef detached_t default_completion_token_type; /// Construct the adapted executor from the inner executor type. executor_with_default(const InnerExecutor& ex) noexcept : InnerExecutor(ex) { } /// Convert the specified executor to the inner executor type, then use /// that to construct the adapted executor. template <typename OtherExecutor> executor_with_default(const OtherExecutor& ex, constraint_t< is_convertible<OtherExecutor, InnerExecutor>::value > = 0) noexcept : InnerExecutor(ex) { } }; /// Type alias to adapt an I/O object to use @c detached_t as its /// default completion token type. template <typename T> using as_default_on_t = typename T::template rebind_executor< executor_with_default<typename T::executor_type>>::other; /// Function helper to adapt an I/O object to use @c detached_t as its /// default completion token type. template <typename T> static typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other as_default_on(T&& object) { return typename decay_t<T>::template rebind_executor< executor_with_default<typename decay_t<T>::executor_type> >::other(static_cast<T&&>(object)); } }; /// A @ref completion_token object used to specify that an asynchronous /// operation is detached. /** * See the documentation for asio::detached_t for a usage example. */ ASIO_INLINE_VARIABLE constexpr detached_t detached; } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/detached.hpp" #endif // ASIO_DETACHED_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_socket.hpp
// // basic_socket.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 ASIO_BASIC_SOCKET_HPP #define ASIO_BASIC_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <utility> #include "asio/any_io_executor.hpp" #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/post.hpp" #include "asio/socket_base.hpp" #if defined(ASIO_WINDOWS_RUNTIME) # include "asio/detail/null_socket_service.hpp" #elif defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_socket_service.hpp" #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/io_uring_socket_service.hpp" #else # include "asio/detail/reactive_socket_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_SOCKET_FWD_DECL) #define ASIO_BASIC_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_socket; #endif // !defined(ASIO_BASIC_SOCKET_FWD_DECL) /// Provides socket functionality. /** * The basic_socket class template provides functionality that is common to both * stream-oriented and datagram-oriented sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Protocol, typename Executor> class basic_socket : public socket_base { private: class initiate_async_connect; class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the socket type to another executor. template <typename Executor1> struct rebind_executor { /// The socket type when rebound to the specified executor. typedef basic_socket<Protocol, Executor1> other; }; /// The native representation of a socket. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_WINDOWS_RUNTIME) typedef typename detail::null_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef typename detail::win_iocp_socket_service< Protocol>::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef typename detail::io_uring_socket_service< Protocol>::native_handle_type native_handle_type; #else typedef typename detail::reactive_socket_service< Protocol>::native_handle_type native_handle_type; #endif /// The protocol type. typedef Protocol protocol_type; /// The endpoint type. typedef typename Protocol::endpoint endpoint_type; #if !defined(ASIO_NO_EXTENSIONS) /// A basic_socket is always the lowest layer. typedef basic_socket<Protocol, Executor> lowest_layer_type; #endif // !defined(ASIO_NO_EXTENSIONS) /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening it. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. */ explicit basic_socket(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_socket without opening it. /** * This constructor creates a socket without opening it. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. */ template <typename ExecutionContext> explicit basic_socket(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { } /// Construct and open a basic_socket. /** * This constructor creates and opens a socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_socket. /** * This constructor creates and opens a socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const protocol_type& protocol, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a socket and automatically opens it bound to the * specified endpoint on the local machine. The protocol used is the protocol * associated with the given endpoint. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws asio::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const endpoint_type& endpoint) : impl_(0, ex) { asio::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Construct a basic_socket, opening it and binding it to the given local /// endpoint. /** * This constructor creates a socket and automatically opens it bound to the * specified endpoint on the local machine. The protocol used is the protocol * associated with the given endpoint. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const endpoint_type& endpoint, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; const protocol_type protocol = endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a socket object to hold an existing native socket. * * @param ex The I/O executor that the socket will use, by default, to * dispatch handlers for any asynchronous operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket A native socket. * * @throws asio::system_error Thrown on failure. */ basic_socket(const executor_type& ex, const protocol_type& protocol, const native_handle_type& native_socket) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_socket on an existing native socket. /** * This constructor creates a socket object to hold an existing native socket. * * @param context An execution context which provides the I/O executor that * the socket will use, by default, to dispatch handlers for any asynchronous * operations performed on the socket. * * @param protocol An object specifying protocol parameters to be used. * * @param native_socket A native socket. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_socket(ExecutionContext& context, const protocol_type& protocol, const native_handle_type& native_socket, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_socket from another. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ basic_socket(basic_socket&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from another. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ basic_socket& operator=(basic_socket&& other) { impl_ = std::move(other.impl_); return *this; } // All sockets have access to each other's implementations. template <typename Protocol1, typename Executor1> friend class basic_socket; /// Move-construct a basic_socket from a socket of another protocol type. /** * This constructor moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ template <typename Protocol1, typename Executor1> basic_socket(basic_socket<Protocol1, Executor1>&& other, constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value > = 0) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_socket from a socket of another protocol type. /** * This assignment operator moves a socket from one object to another. * * @param other The other basic_socket object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_socket(const executor_type&) constructor. */ template <typename Protocol1, typename Executor1> constraint_t< is_convertible<Protocol1, Protocol>::value && is_convertible<Executor1, Executor>::value, basic_socket& > operator=(basic_socket<Protocol1, Executor1>&& other) { basic_socket tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } #if !defined(ASIO_NO_EXTENSIONS) /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_socket cannot contain any further layers, it simply * returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } #endif // !defined(ASIO_NO_EXTENSIONS) /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying protocol parameters to be used. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * socket.open(asio::ip::tcp::v4()); * @endcode */ void open(const protocol_type& protocol = protocol_type()) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), protocol, ec); asio::detail::throw_error(ec, "open"); } /// Open the socket using the specified protocol. /** * This function opens the socket so that it will use the specified protocol. * * @param protocol An object specifying which protocol is to be used. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * asio::error_code ec; * socket.open(asio::ip::tcp::v4(), ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID open(const protocol_type& protocol, asio::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), protocol, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @throws asio::system_error Thrown on failure. */ void assign(const protocol_type& protocol, const native_handle_type& native_socket) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native socket to the socket. /* * This function opens the socket to hold an existing native socket. * * @param protocol An object specifying which protocol is to be used. * * @param native_socket A native socket. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const protocol_type& protocol, const native_handle_type& native_socket, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), protocol, native_socket, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the socket. /** * This function is used to close the socket. Any asynchronous send, receive * or connect operations will be cancelled immediately, and will complete * with the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::error_code ec; * socket.close(ec); * if (ec) * { * // An error occurred. * } * @endcode * * @note For portable behaviour with respect to graceful closure of a * connected socket, call shutdown() before closing the socket. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. Ownership * of the native socket is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. Ownership * of the native socket is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native socket representation. /** * This function may be used to obtain the underlying representation of the * socket. This is intended to allow access to native socket functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the socket. /** * This function causes all outstanding asynchronous connect, send and receive * operations to finish immediately, and the handlers for cancelled operations * will be passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using one of the following * alternatives: * * @li Disable asio's I/O completion port backend by defining * ASIO_DISABLE_IOCP. * * @li Use the close() function to simultaneously cancel the outstanding * operations and close the socket. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @return A bool indicating whether the socket is at the out-of-band data * mark. * * @throws asio::system_error Thrown on failure. */ bool at_mark() const { asio::error_code ec; bool b = impl_.get_service().at_mark(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "at_mark"); return b; } /// Determine whether the socket is at the out-of-band data mark. /** * This function is used to check whether the socket input is currently * positioned at the out-of-band data mark. * * @param ec Set to indicate what error occurred, if any. * * @return A bool indicating whether the socket is at the out-of-band data * mark. */ bool at_mark(asio::error_code& ec) const { return impl_.get_service().at_mark(impl_.get_implementation(), ec); } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. * * @throws asio::system_error Thrown on failure. */ std::size_t available() const { asio::error_code ec; std::size_t s = impl_.get_service().available( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "available"); return s; } /// Determine the number of bytes available for reading. /** * This function is used to determine the number of bytes that may be read * without blocking. * * @param ec Set to indicate what error occurred, if any. * * @return The number of bytes that may be read without blocking, or 0 if an * error occurs. */ std::size_t available(asio::error_code& ec) const { return impl_.get_service().available(impl_.get_implementation(), ec); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * socket.open(asio::ip::tcp::v4()); * socket.bind(asio::ip::tcp::endpoint( * asio::ip::tcp::v4(), 12345)); * @endcode */ void bind(const endpoint_type& endpoint) { asio::error_code ec; impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); asio::detail::throw_error(ec, "bind"); } /// Bind the socket to the given local endpoint. /** * This function binds the socket to the specified endpoint on the local * machine. * * @param endpoint An endpoint on the local machine to which the socket will * be bound. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * socket.open(asio::ip::tcp::v4()); * asio::error_code ec; * socket.bind(asio::ip::tcp::endpoint( * asio::ip::tcp::v4(), 12345), ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID bind(const endpoint_type& endpoint, asio::error_code& ec) { impl_.get_service().bind(impl_.get_implementation(), endpoint, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.connect(endpoint); * @endcode */ void connect(const endpoint_type& peer_endpoint) { asio::error_code ec; if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); asio::detail::throw_error(ec, "connect"); } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); asio::detail::throw_error(ec, "connect"); } /// Connect the socket to the specified endpoint. /** * This function is used to connect a socket to the specified remote endpoint. * The function call will block until the connection is successfully made or * an error occurs. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * asio::error_code ec; * socket.connect(endpoint, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID connect(const endpoint_type& peer_endpoint, asio::error_code& ec) { if (!is_open()) { impl_.get_service().open(impl_.get_implementation(), peer_endpoint.protocol(), ec); if (ec) { ASIO_SYNC_OP_VOID_RETURN(ec); } } impl_.get_service().connect(impl_.get_implementation(), peer_endpoint, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous connect. /** * This function is used to asynchronously connect a socket to the specified * remote endpoint. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * The socket is automatically opened if it is not already open. If the * connect fails, and the socket was automatically opened, the socket is * not returned to the closed state. * * @param peer_endpoint The remote endpoint to which the socket will be * connected. Copies will be made of the endpoint object as required. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the connect completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Example * @code * void connect_handler(const asio::error_code& error) * { * if (!error) * { * // Connect succeeded. * } * } * * ... * * asio::ip::tcp::socket socket(my_context); * asio::ip::tcp::endpoint endpoint( * asio::ip::address::from_string("1.2.3.4"), 12345); * socket.async_connect(endpoint, connect_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) ConnectToken = default_completion_token_t<executor_type>> auto async_connect(const endpoint_type& peer_endpoint, ConnectToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ConnectToken, void (asio::error_code)>( declval<initiate_async_connect>(), token, peer_endpoint, declval<asio::error_code&>())) { asio::error_code open_ec; if (!is_open()) { const protocol_type protocol = peer_endpoint.protocol(); impl_.get_service().open(impl_.get_implementation(), protocol, open_ec); } return async_initiate<ConnectToken, void (asio::error_code)>( initiate_async_connect(this), token, peer_endpoint, open_ec); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @throws asio::system_error Thrown on failure. * * @sa SettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::no_delay option(true); * socket.set_option(option); * @endcode */ template <typename SettableSocketOption> void set_option(const SettableSocketOption& option) { asio::error_code ec; impl_.get_service().set_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "set_option"); } /// Set an option on the socket. /** * This function is used to set an option on the socket. * * @param option The new option value to be set on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa SettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Setting the IPPROTO_TCP/TCP_NODELAY option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::no_delay option(true); * asio::error_code ec; * socket.set_option(option, ec); * if (ec) * { * // An error occurred. * } * @endcode */ template <typename SettableSocketOption> ASIO_SYNC_OP_VOID set_option(const SettableSocketOption& option, asio::error_code& ec) { impl_.get_service().set_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @throws asio::system_error Thrown on failure. * * @sa GettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::socket::keep_alive option; * socket.get_option(option); * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> void get_option(GettableSocketOption& option) const { asio::error_code ec; impl_.get_service().get_option(impl_.get_implementation(), option, ec); asio::detail::throw_error(ec, "get_option"); } /// Get an option from the socket. /** * This function is used to get the current value of an option on the socket. * * @param option The option value to be obtained from the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa GettableSocketOption @n * asio::socket_base::broadcast @n * asio::socket_base::do_not_route @n * asio::socket_base::keep_alive @n * asio::socket_base::linger @n * asio::socket_base::receive_buffer_size @n * asio::socket_base::receive_low_watermark @n * asio::socket_base::reuse_address @n * asio::socket_base::send_buffer_size @n * asio::socket_base::send_low_watermark @n * asio::ip::multicast::join_group @n * asio::ip::multicast::leave_group @n * asio::ip::multicast::enable_loopback @n * asio::ip::multicast::outbound_interface @n * asio::ip::multicast::hops @n * asio::ip::tcp::no_delay * * @par Example * Getting the value of the SOL_SOCKET/SO_KEEPALIVE option: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::socket::keep_alive option; * asio::error_code ec; * socket.get_option(option, ec); * if (ec) * { * // An error occurred. * } * bool is_set = option.value(); * @endcode */ template <typename GettableSocketOption> ASIO_SYNC_OP_VOID get_option(GettableSocketOption& option, asio::error_code& ec) const { impl_.get_service().get_option(impl_.get_implementation(), option, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @throws asio::system_error Thrown on failure. * * @sa IoControlCommand @n * asio::socket_base::bytes_readable @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::socket::bytes_readable command; * socket.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { asio::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the socket. /** * This function is used to execute an IO control command on the socket. * * @param command The IO control command to be performed on the socket. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * asio::socket_base::bytes_readable @n * asio::socket_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::socket::bytes_readable command; * asio::error_code ec; * socket.io_control(command, ec); * if (ec) * { * // An error occurred. * } * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, asio::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the socket. /** * @returns @c true if the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @throws asio::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ void non_blocking(bool mode) { asio::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the socket. /** * @param mode If @c true, the socket's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ ASIO_SYNC_OP_VOID non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native socket implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native socket. This mode has no effect on the behaviour of the socket * object's synchronous operations. * * @returns @c true if the underlying socket is in non-blocking mode and * direct system calls may fail with asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the socket object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native socket. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @throws asio::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ void native_non_blocking(bool mode) { asio::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native socket implementation. /** * This function is used to modify the non-blocking mode of the underlying * native socket. It has no effect on the behaviour of the socket object's * synchronous operations. * * @param mode If @c true, the underlying socket is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. * * @par Example * This function is intended to allow the encapsulation of arbitrary * non-blocking system calls as asynchronous operations, in a way that is * transparent to the user of the socket object. The following example * illustrates how Linux's @c sendfile system call might be encapsulated: * @code template <typename Handler> * struct sendfile_op * { * tcp::socket& sock_; * int fd_; * Handler handler_; * off_t offset_; * std::size_t total_bytes_transferred_; * * // Function call operator meeting WriteHandler requirements. * // Used as the handler for the async_write_some operation. * void operator()(asio::error_code ec, std::size_t) * { * // Put the underlying socket into non-blocking mode. * if (!ec) * if (!sock_.native_non_blocking()) * sock_.native_non_blocking(true, ec); * * if (!ec) * { * for (;;) * { * // Try the system call. * errno = 0; * int n = ::sendfile(sock_.native_handle(), fd_, &offset_, 65536); * ec = asio::error_code(n < 0 ? errno : 0, * asio::error::get_system_category()); * total_bytes_transferred_ += ec ? 0 : n; * * // Retry operation immediately if interrupted by signal. * if (ec == asio::error::interrupted) * continue; * * // Check if we need to run the operation again. * if (ec == asio::error::would_block * || ec == asio::error::try_again) * { * // We have to wait for the socket to become ready again. * sock_.async_wait(tcp::socket::wait_write, *this); * return; * } * * if (ec || n == 0) * { * // An error occurred, or we have reached the end of the file. * // Either way we must exit the loop so we can call the handler. * break; * } * * // Loop around to try calling sendfile again. * } * } * * // Pass result back to user's handler. * handler_(ec, total_bytes_transferred_); * } * }; * * template <typename Handler> * void async_sendfile(tcp::socket& sock, int fd, Handler h) * { * sendfile_op<Handler> op = { sock, fd, h, 0, 0 }; * sock.async_wait(tcp::socket::wait_write, op); * } @endcode */ ASIO_SYNC_OP_VOID native_non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @returns An object that represents the local endpoint of the socket. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(); * @endcode */ endpoint_type local_endpoint() const { asio::error_code ec; endpoint_type ep = impl_.get_service().local_endpoint( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "local_endpoint"); return ep; } /// Get the local endpoint of the socket. /** * This function is used to obtain the locally bound endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the local endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::error_code ec; * asio::ip::tcp::endpoint endpoint = socket.local_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type local_endpoint(asio::error_code& ec) const { return impl_.get_service().local_endpoint(impl_.get_implementation(), ec); } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @returns An object that represents the remote endpoint of the socket. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(); * @endcode */ endpoint_type remote_endpoint() const { asio::error_code ec; endpoint_type ep = impl_.get_service().remote_endpoint( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "remote_endpoint"); return ep; } /// Get the remote endpoint of the socket. /** * This function is used to obtain the remote endpoint of the socket. * * @param ec Set to indicate what error occurred, if any. * * @returns An object that represents the remote endpoint of the socket. * Returns a default-constructed endpoint object if an error occurred. * * @par Example * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::error_code ec; * asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(ec); * if (ec) * { * // An error occurred. * } * @endcode */ endpoint_type remote_endpoint(asio::error_code& ec) const { return impl_.get_service().remote_endpoint(impl_.get_implementation(), ec); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @throws asio::system_error Thrown on failure. * * @par Example * Shutting down the send side of the socket: * @code * asio::ip::tcp::socket socket(my_context); * ... * socket.shutdown(asio::ip::tcp::socket::shutdown_send); * @endcode */ void shutdown(shutdown_type what) { asio::error_code ec; impl_.get_service().shutdown(impl_.get_implementation(), what, ec); asio::detail::throw_error(ec, "shutdown"); } /// Disable sends or receives on the socket. /** * This function is used to disable send operations, receive operations, or * both. * * @param what Determines what types of operation will no longer be allowed. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Shutting down the send side of the socket: * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::error_code ec; * socket.shutdown(asio::ip::tcp::socket::shutdown_send, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID shutdown(shutdown_type what, asio::error_code& ec) { impl_.get_service().shutdown(impl_.get_implementation(), what, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @par Example * Waiting for a socket to become readable. * @code * asio::ip::tcp::socket socket(my_context); * ... * socket.wait(asio::ip::tcp::socket::wait_read); * @endcode */ void wait(wait_type w) { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); asio::detail::throw_error(ec, "wait"); } /// Wait for the socket to become ready to read, ready to write, or to have /// pending error conditions. /** * This function is used to perform a blocking wait for a socket to enter * a ready to read, write or error condition state. * * @param w Specifies the desired socket state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for a socket to become readable. * @code * asio::ip::tcp::socket socket(my_context); * ... * asio::error_code ec; * socket.wait(asio::ip::tcp::socket::wait_read, ec); * @endcode */ ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the socket to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for a socket to enter * a ready to read, write or error condition state. It is an initiating * function for an @ref asynchronous_operation, and always returns * immediately. * * @param w Specifies the desired socket state. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the wait completes. Potential * completion tokens include @ref use_future, @ref use_awaitable, @ref * yield_context, or a function object with the correct completion signature. * The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Example * @code * void wait_handler(const asio::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * asio::ip::tcp::socket socket(my_context); * ... * socket.async_wait(asio::ip::tcp::socket::wait_read, wait_handler); * @endcode * * @par Per-Operation Cancellation * On POSIX or Windows operating systems, this asynchronous operation supports * cancellation for the following asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait(wait_type w, WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token, w)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token, w); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the socket, cancelling any outstanding asynchronous * operations associated with the socket as if by calling @c cancel. */ ~basic_socket() { } #if defined(ASIO_WINDOWS_RUNTIME) detail::io_object_impl< detail::null_socket_service<Protocol>, Executor> impl_; #elif defined(ASIO_HAS_IOCP) detail::io_object_impl< detail::win_iocp_socket_service<Protocol>, Executor> impl_; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl< detail::io_uring_socket_service<Protocol>, Executor> impl_; #else detail::io_object_impl< detail::reactive_socket_service<Protocol>, Executor> impl_; #endif private: // Disallow copying and assignment. basic_socket(const basic_socket&) = delete; basic_socket& operator=(const basic_socket&) = delete; class initiate_async_connect { public: typedef Executor executor_type; explicit initiate_async_connect(basic_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ConnectHandler> void operator()(ConnectHandler&& handler, const endpoint_type& peer_endpoint, const asio::error_code& open_ec) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ConnectHandler. ASIO_CONNECT_HANDLER_CHECK(ConnectHandler, handler) type_check; if (open_ec) { asio::post(self_->impl_.get_executor(), asio::detail::bind_handler( static_cast<ConnectHandler&&>(handler), open_ec)); } else { detail::non_const_lvalue<ConnectHandler> handler2(handler); self_->impl_.get_service().async_connect( self_->impl_.get_implementation(), peer_endpoint, handler2.value, self_->impl_.get_executor()); } } private: basic_socket* self_; }; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_socket* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler, wait_type w) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), w, handler2.value, self_->impl_.get_executor()); } private: basic_socket* self_; }; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_BASIC_SOCKET_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/execution_context.hpp
// // execution_context.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 ASIO_EXECUTION_CONTEXT_HPP #define ASIO_EXECUTION_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <stdexcept> #include <typeinfo> #include "asio/detail/noncopyable.hpp" #include "asio/detail/push_options.hpp" namespace asio { class execution_context; class io_context; #if !defined(GENERATING_DOCUMENTATION) template <typename Service> Service& use_service(execution_context&); template <typename Service> Service& use_service(io_context&); template <typename Service> void add_service(execution_context&, Service*); template <typename Service> bool has_service(execution_context&); #endif // !defined(GENERATING_DOCUMENTATION) namespace detail { class service_registry; } /// A context for function object execution. /** * An execution context represents a place where function objects will be * executed. An @c io_context is an example of an execution context. * * @par The execution_context class and services * * Class execution_context implements an extensible, type-safe, polymorphic set * of services, indexed by service type. * * Services exist to manage the resources that are shared across an execution * context. For example, timers may be implemented in terms of a single timer * queue, and this queue would be stored in a service. * * Access to the services of an execution_context is via three function * templates, use_service(), add_service() and has_service(). * * In a call to @c use_service<Service>(), the type argument chooses a service, * making available all members of the named type. If @c Service is not present * in an execution_context, an object of type @c Service is created and added * to the execution_context. A C++ program can check if an execution_context * implements a particular service with the function template @c * has_service<Service>(). * * Service objects may be explicitly added to an execution_context using the * function template @c add_service<Service>(). If the @c Service is already * present, the service_already_exists exception is thrown. If the owner of the * service is not the same object as the execution_context parameter, the * invalid_service_owner exception is thrown. * * Once a service reference is obtained from an execution_context object by * calling use_service(), that reference remains usable as long as the owning * execution_context object exists. * * All service implementations have execution_context::service as a public base * class. Custom services may be implemented by deriving from this class and * then added to an execution_context using the facilities described above. * * @par The execution_context as a base class * * Class execution_context may be used only as a base class for concrete * execution context types. The @c io_context is an example of such a derived * type. * * On destruction, a class that is derived from execution_context must perform * <tt>execution_context::shutdown()</tt> followed by * <tt>execution_context::destroy()</tt>. * * This destruction sequence permits programs to simplify their resource * management by using @c shared_ptr<>. Where an object's lifetime is tied to * the lifetime of a connection (or some other sequence of asynchronous * operations), a @c shared_ptr to the object would be bound into the handlers * for all asynchronous operations associated with it. This works as follows: * * @li When a single connection ends, all associated asynchronous operations * complete. The corresponding handler objects are destroyed, and all @c * shared_ptr references to the objects are destroyed. * * @li To shut down the whole program, the io_context function stop() is called * to terminate any run() calls as soon as possible. The io_context destructor * calls @c shutdown() and @c destroy() to destroy all pending handlers, * causing all @c shared_ptr references to all connection objects to be * destroyed. */ class execution_context : private noncopyable { public: class id; class service; public: /// Constructor. ASIO_DECL execution_context(); /// Destructor. ASIO_DECL ~execution_context(); protected: /// Shuts down all services in the context. /** * This function is implemented as follows: * * @li For each service object @c svc in the execution_context set, in * reverse order of the beginning of service object lifetime, performs @c * svc->shutdown(). */ ASIO_DECL void shutdown(); /// Destroys all services in the context. /** * This function is implemented as follows: * * @li For each service object @c svc in the execution_context set, in * reverse order * of the beginning of service object lifetime, performs * <tt>delete static_cast<execution_context::service*>(svc)</tt>. */ ASIO_DECL void destroy(); public: /// Fork-related event notifications. enum fork_event { /// Notify the context that the process is about to fork. fork_prepare, /// Notify the context that the process has forked and is the parent. fork_parent, /// Notify the context that the process has forked and is the child. fork_child }; /// Notify the execution_context of a fork-related event. /** * This function is used to inform the execution_context that the process is * about to fork, or has just forked. This allows the execution_context, and * the services it contains, to perform any necessary housekeeping to ensure * correct operation following a fork. * * This function must not be called while any other execution_context * function, or any function associated with the execution_context's derived * class, is being called in another thread. It is, however, safe to call * this function from within a completion handler, provided no other thread * is accessing the execution_context or its derived class. * * @param event A fork-related event. * * @throws asio::system_error Thrown on failure. If the notification * fails the execution_context object should no longer be used and should be * destroyed. * * @par Example * The following code illustrates how to incorporate the notify_fork() * function: * @code my_execution_context.notify_fork(execution_context::fork_prepare); * if (fork() == 0) * { * // This is the child process. * my_execution_context.notify_fork(execution_context::fork_child); * } * else * { * // This is the parent process. * my_execution_context.notify_fork(execution_context::fork_parent); * } @endcode * * @note For each service object @c svc in the execution_context set, * performs <tt>svc->notify_fork();</tt>. When processing the fork_prepare * event, services are visited in reverse order of the beginning of service * object lifetime. Otherwise, services are visited in order of the beginning * of service object lifetime. */ ASIO_DECL void notify_fork(fork_event event); /// Obtain the service object corresponding to the given type. /** * This function is used to locate a service object that corresponds to the * given service type. If there is no existing implementation of the service, * then the execution_context will create a new instance of the service. * * @param e The execution_context object that owns the service. * * @return The service interface implementing the specified service type. * Ownership of the service interface is not transferred to the caller. */ template <typename Service> friend Service& use_service(execution_context& e); /// Obtain the service object corresponding to the given type. /** * This function is used to locate a service object that corresponds to the * given service type. If there is no existing implementation of the service, * then the io_context will create a new instance of the service. * * @param ioc The io_context object that owns the service. * * @return The service interface implementing the specified service type. * Ownership of the service interface is not transferred to the caller. * * @note This overload is preserved for backwards compatibility with services * that inherit from io_context::service. */ template <typename Service> friend Service& use_service(io_context& ioc); /// Creates a service object and adds it to the execution_context. /** * This function is used to add a service to the execution_context. * * @param e The execution_context object that owns the service. * * @param args Zero or more arguments to be passed to the service * constructor. * * @throws asio::service_already_exists Thrown if a service of the * given type is already present in the execution_context. */ template <typename Service, typename... Args> friend Service& make_service(execution_context& e, Args&&... args); /// (Deprecated: Use make_service().) Add a service object to the /// execution_context. /** * This function is used to add a service to the execution_context. * * @param e The execution_context object that owns the service. * * @param svc The service object. On success, ownership of the service object * is transferred to the execution_context. When the execution_context object * is destroyed, it will destroy the service object by performing: @code * delete static_cast<execution_context::service*>(svc) @endcode * * @throws asio::service_already_exists Thrown if a service of the * given type is already present in the execution_context. * * @throws asio::invalid_service_owner Thrown if the service's owning * execution_context is not the execution_context object specified by the * @c e parameter. */ template <typename Service> friend void add_service(execution_context& e, Service* svc); /// Determine if an execution_context contains a specified service type. /** * This function is used to determine whether the execution_context contains a * service object corresponding to the given service type. * * @param e The execution_context object that owns the service. * * @return A boolean indicating whether the execution_context contains the * service. */ template <typename Service> friend bool has_service(execution_context& e); private: // The service registry. asio::detail::service_registry* service_registry_; }; /// Class used to uniquely identify a service. class execution_context::id : private noncopyable { public: /// Constructor. id() {} }; /// Base class for all io_context services. class execution_context::service : private noncopyable { public: /// Get the context object that owns the service. execution_context& context(); protected: /// Constructor. /** * @param owner The execution_context object that owns the service. */ ASIO_DECL service(execution_context& owner); /// Destructor. ASIO_DECL virtual ~service(); private: /// Destroy all user-defined handler objects owned by the service. virtual void shutdown() = 0; /// Handle notification of a fork-related event to perform any necessary /// housekeeping. /** * This function is not a pure virtual so that services only have to * implement it if necessary. The default implementation does nothing. */ ASIO_DECL virtual void notify_fork( execution_context::fork_event event); friend class asio::detail::service_registry; struct key { key() : type_info_(0), id_(0) {} const std::type_info* type_info_; const execution_context::id* id_; } key_; execution_context& owner_; service* next_; }; /// Exception thrown when trying to add a duplicate service to an /// execution_context. class service_already_exists : public std::logic_error { public: ASIO_DECL service_already_exists(); }; /// Exception thrown when trying to add a service object to an /// execution_context where the service has a different owner. class invalid_service_owner : public std::logic_error { public: ASIO_DECL invalid_service_owner(); }; namespace detail { // Special derived service id type to keep classes header-file only. template <typename Type> class service_id : public execution_context::id { }; // Special service base class to keep classes header-file only. template <typename Type> class execution_context_service_base : public execution_context::service { public: static service_id<Type> id; // Constructor. execution_context_service_base(execution_context& e) : execution_context::service(e) { } }; template <typename Type> service_id<Type> execution_context_service_base<Type>::id; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/execution_context.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/impl/execution_context.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_EXECUTION_CONTEXT_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_readable_pipe.hpp
// // basic_readable_pipe.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 ASIO_BASIC_READABLE_PIPE_HPP #define ASIO_BASIC_READABLE_PIPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_PIPE) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_handle_service.hpp" #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/io_uring_descriptor_service.hpp" #else # include "asio/detail/reactive_descriptor_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { /// Provides pipe functionality. /** * The basic_readable_pipe class provides a wrapper over pipe * functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_readable_pipe { private: class initiate_async_read_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the pipe type to another executor. template <typename Executor1> struct rebind_executor { /// The pipe type when rebound to the specified executor. typedef basic_readable_pipe<Executor1> other; }; /// The native representation of a pipe. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef detail::win_iocp_handle_service::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef detail::io_uring_descriptor_service::native_handle_type native_handle_type; #else typedef detail::reactive_descriptor_service::native_handle_type native_handle_type; #endif /// A basic_readable_pipe is always the lowest layer. typedef basic_readable_pipe lowest_layer_type; /// Construct a basic_readable_pipe without opening it. /** * This constructor creates a pipe without opening it. * * @param ex The I/O executor that the pipe will use, by default, to dispatch * handlers for any asynchronous operations performed on the pipe. */ explicit basic_readable_pipe(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_readable_pipe without opening it. /** * This constructor creates a pipe without opening it. * * @param context An execution context which provides the I/O executor that * the pipe will use, by default, to dispatch handlers for any asynchronous * operations performed on the pipe. */ template <typename ExecutionContext> explicit basic_readable_pipe(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct a basic_readable_pipe on an existing native pipe. /** * This constructor creates a pipe object to hold an existing native * pipe. * * @param ex The I/O executor that the pipe will use, by default, to * dispatch handlers for any asynchronous operations performed on the * pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ basic_readable_pipe(const executor_type& ex, const native_handle_type& native_pipe) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_readable_pipe on an existing native pipe. /** * This constructor creates a pipe object to hold an existing native * pipe. * * @param context An execution context which provides the I/O executor that * the pipe will use, by default, to dispatch handlers for any * asynchronous operations performed on the pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_readable_pipe(ExecutionContext& context, const native_handle_type& native_pipe, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_readable_pipe from another. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_readable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_readable_pipe(const executor_type&) * constructor. */ basic_readable_pipe(basic_readable_pipe&& other) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_readable_pipe from another. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_readable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_readable_pipe(const executor_type&) * constructor. */ basic_readable_pipe& operator=(basic_readable_pipe&& other) { impl_ = std::move(other.impl_); return *this; } // All pipes have access to each other's implementations. template <typename Executor1> friend class basic_readable_pipe; /// Move-construct a basic_readable_pipe from a pipe of another executor type. /** * This constructor moves a pipe from one object to another. * * @param other The other basic_readable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_readable_pipe(const executor_type&) * constructor. */ template <typename Executor1> basic_readable_pipe(basic_readable_pipe<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_readable_pipe from a pipe of another executor type. /** * This assignment operator moves a pipe from one object to another. * * @param other The other basic_readable_pipe object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_readable_pipe(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_readable_pipe& > operator=(basic_readable_pipe<Executor1>&& other) { basic_readable_pipe tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Destroys the pipe. /** * This function destroys the pipe, cancelling any outstanding * asynchronous wait operations associated with the pipe as if by * calling @c cancel. */ ~basic_readable_pipe() { } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a basic_readable_pipe cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a basic_readable_pipe cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Assign an existing native pipe to the pipe. /* * This function opens the pipe to hold an existing native pipe. * * @param native_pipe A native pipe. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_pipe) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native pipe to the pipe. /* * This function opens the pipe to hold an existing native pipe. * * @param native_pipe A native pipe. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& native_pipe, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), native_pipe, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the pipe is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the pipe. /** * This function is used to close the pipe. Any asynchronous read operations * will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the pipe. /** * This function is used to close the pipe. Any asynchronous read operations * will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous read operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native pipe is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native pipe. /** * This function causes all outstanding asynchronous read operations to * finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. Ownership of the * native pipe is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native pipe representation. /** * This function may be used to obtain the underlying representation of the * pipe. This is intended to allow access to native pipe * functionality that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the pipe. /** * This function causes all outstanding asynchronous read operations to finish * immediately, and the handlers for cancelled operations will be passed the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the pipe. /** * This function causes all outstanding asynchronous read operations to finish * immediately, and the handlers for cancelled operations will be passed the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Read some data from the pipe. /** * This function is used to read data from the pipe. The function call will * block until one or more bytes of data has been read successfully, or until * an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * basic_readable_pipe.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the pipe. /** * This function is used to read data from the pipe. The function call will * block until one or more bytes of data has been read successfully, or until * an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return impl_.get_service().read_some( impl_.get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the pipe. It is an * initiating function for an @ref asynchronous_operation, and always returns * immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * basic_readable_pipe.async_read_some( * asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: // Disallow copying and assignment. basic_readable_pipe(const basic_readable_pipe&) = delete; basic_readable_pipe& operator=(const basic_readable_pipe&) = delete; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_readable_pipe* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_readable_pipe* self_; }; #if defined(ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_handle_service, Executor> impl_; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl<detail::io_uring_descriptor_service, Executor> impl_; #else detail::io_object_impl<detail::reactive_descriptor_service, Executor> impl_; #endif }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_PIPE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_READABLE_PIPE_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/strand.hpp
// // strand.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 ASIO_STRAND_HPP #define ASIO_STRAND_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/strand_executor_service.hpp" #include "asio/detail/type_traits.hpp" #include "asio/execution/blocking.hpp" #include "asio/execution/executor.hpp" #include "asio/is_executor.hpp" #include "asio/detail/push_options.hpp" namespace asio { /// Provides serialised function invocation for any executor type. template <typename Executor> class strand { public: /// The type of the underlying executor. typedef Executor inner_executor_type; /// Default constructor. /** * This constructor is only valid if the underlying executor type is default * constructible. */ strand() : executor_(), impl_(strand::create_implementation(executor_)) { } /// Construct a strand for the specified executor. template <typename Executor1> explicit strand(const Executor1& e, constraint_t< conditional_t< !is_same<Executor1, strand>::value, is_convertible<Executor1, Executor>, false_type >::value > = 0) : executor_(e), impl_(strand::create_implementation(executor_)) { } /// Copy constructor. strand(const strand& other) noexcept : executor_(other.executor_), impl_(other.impl_) { } /// Converting constructor. /** * This constructor is only valid if the @c OtherExecutor type is convertible * to @c Executor. */ template <class OtherExecutor> strand( const strand<OtherExecutor>& other) noexcept : executor_(other.executor_), impl_(other.impl_) { } /// Assignment operator. strand& operator=(const strand& other) noexcept { executor_ = other.executor_; impl_ = other.impl_; return *this; } /// Converting assignment operator. /** * This assignment operator is only valid if the @c OtherExecutor type is * convertible to @c Executor. */ template <class OtherExecutor> strand& operator=( const strand<OtherExecutor>& other) noexcept { executor_ = other.executor_; impl_ = other.impl_; return *this; } /// Move constructor. strand(strand&& other) noexcept : executor_(static_cast<Executor&&>(other.executor_)), impl_(static_cast<implementation_type&&>(other.impl_)) { } /// Converting move constructor. /** * This constructor is only valid if the @c OtherExecutor type is convertible * to @c Executor. */ template <class OtherExecutor> strand(strand<OtherExecutor>&& other) noexcept : executor_(static_cast<OtherExecutor&&>(other.executor_)), impl_(static_cast<implementation_type&&>(other.impl_)) { } /// Move assignment operator. strand& operator=(strand&& other) noexcept { executor_ = static_cast<Executor&&>(other.executor_); impl_ = static_cast<implementation_type&&>(other.impl_); return *this; } /// Converting move assignment operator. /** * This assignment operator is only valid if the @c OtherExecutor type is * convertible to @c Executor. */ template <class OtherExecutor> strand& operator=(strand<OtherExecutor>&& other) noexcept { executor_ = static_cast<OtherExecutor&&>(other.executor_); impl_ = static_cast<implementation_type&&>(other.impl_); return *this; } /// Destructor. ~strand() noexcept { } /// Obtain the underlying executor. inner_executor_type get_inner_executor() const noexcept { return executor_; } /// Forward a query to the underlying executor. /** * Do not call this function directly. It is intended for use with the * asio::query customisation point. * * For example: * @code asio::strand<my_executor_type> ex = ...; * if (asio::query(ex, asio::execution::blocking) * == asio::execution::blocking.never) * ... @endcode */ template <typename Property> constraint_t< can_query<const Executor&, Property>::value, conditional_t< is_convertible<Property, execution::blocking_t>::value, execution::blocking_t, query_result_t<const Executor&, Property> > > query(const Property& p) const noexcept(is_nothrow_query<const Executor&, Property>::value) { return this->query_helper( is_convertible<Property, execution::blocking_t>(), p); } /// Forward a requirement to the underlying executor. /** * Do not call this function directly. It is intended for use with the * asio::require customisation point. * * For example: * @code asio::strand<my_executor_type> ex1 = ...; * auto ex2 = asio::require(ex1, * asio::execution::blocking.never); @endcode */ template <typename Property> constraint_t< can_require<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value, strand<decay_t<require_result_t<const Executor&, Property>>> > require(const Property& p) const noexcept(is_nothrow_require<const Executor&, Property>::value) { return strand<decay_t<require_result_t<const Executor&, Property>>>( asio::require(executor_, p), impl_); } /// Forward a preference to the underlying executor. /** * Do not call this function directly. It is intended for use with the * asio::prefer customisation point. * * For example: * @code asio::strand<my_executor_type> ex1 = ...; * auto ex2 = asio::prefer(ex1, * asio::execution::blocking.never); @endcode */ template <typename Property> constraint_t< can_prefer<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value, strand<decay_t<prefer_result_t<const Executor&, Property>>> > prefer(const Property& p) const noexcept(is_nothrow_prefer<const Executor&, Property>::value) { return strand<decay_t<prefer_result_t<const Executor&, Property>>>( asio::prefer(executor_, p), impl_); } #if !defined(ASIO_NO_TS_EXECUTORS) /// Obtain the underlying execution context. execution_context& context() const noexcept { return executor_.context(); } /// Inform the strand that it has some outstanding work to do. /** * The strand delegates this call to its underlying executor. */ void on_work_started() const noexcept { executor_.on_work_started(); } /// Inform the strand that some work is no longer outstanding. /** * The strand delegates this call to its underlying executor. */ void on_work_finished() const noexcept { executor_.on_work_finished(); } #endif // !defined(ASIO_NO_TS_EXECUTORS) /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying executor. The function object will be executed * according to the properties of the underlying executor. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode */ template <typename Function> constraint_t< traits::execute_member<const Executor&, Function>::is_valid, void > execute(Function&& f) const { detail::strand_executor_service::execute(impl_, executor_, static_cast<Function&&>(f)); } #if !defined(ASIO_NO_TS_EXECUTORS) /// Request the strand to invoke the given function object. /** * This function is used to ask the strand to execute the given function * object on its underlying executor. The function object will be executed * inside this function if the strand is not otherwise busy and if the * underlying executor's @c dispatch() function is also able to execute the * function before returning. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void dispatch(Function&& f, const Allocator& a) const { detail::strand_executor_service::dispatch(impl_, executor_, static_cast<Function&&>(f), a); } /// Request the strand to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled by the underlying executor's defer function. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void post(Function&& f, const Allocator& a) const { detail::strand_executor_service::post(impl_, executor_, static_cast<Function&&>(f), a); } /// Request the strand to invoke the given function object. /** * This function is used to ask the executor to execute the given function * object. The function object will never be executed inside this function. * Instead, it will be scheduled by the underlying executor's defer function. * * @param f The function object to be called. The executor will make * a copy of the handler object as required. The function signature of the * function object must be: @code void function(); @endcode * * @param a An allocator that may be used by the executor to allocate the * internal storage needed for function invocation. */ template <typename Function, typename Allocator> void defer(Function&& f, const Allocator& a) const { detail::strand_executor_service::defer(impl_, executor_, static_cast<Function&&>(f), a); } #endif // !defined(ASIO_NO_TS_EXECUTORS) /// Determine whether the strand is running in the current thread. /** * @return @c true if the current thread is executing a function that was * submitted to the strand using post(), dispatch() or defer(). Otherwise * returns @c false. */ bool running_in_this_thread() const noexcept { return detail::strand_executor_service::running_in_this_thread(impl_); } /// Compare two strands for equality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator==(const strand& a, const strand& b) noexcept { return a.impl_ == b.impl_; } /// Compare two strands for inequality. /** * Two strands are equal if they refer to the same ordered, non-concurrent * state. */ friend bool operator!=(const strand& a, const strand& b) noexcept { return a.impl_ != b.impl_; } #if defined(GENERATING_DOCUMENTATION) private: #endif // defined(GENERATING_DOCUMENTATION) typedef detail::strand_executor_service::implementation_type implementation_type; template <typename InnerExecutor> static implementation_type create_implementation(const InnerExecutor& ex, constraint_t< can_query<InnerExecutor, execution::context_t>::value > = 0) { return use_service<detail::strand_executor_service>( asio::query(ex, execution::context)).create_implementation(); } template <typename InnerExecutor> static implementation_type create_implementation(const InnerExecutor& ex, constraint_t< !can_query<InnerExecutor, execution::context_t>::value > = 0) { return use_service<detail::strand_executor_service>( ex.context()).create_implementation(); } strand(const Executor& ex, const implementation_type& impl) : executor_(ex), impl_(impl) { } template <typename Property> query_result_t<const Executor&, Property> query_helper( false_type, const Property& property) const { return asio::query(executor_, property); } template <typename Property> execution::blocking_t query_helper(true_type, const Property& property) const { execution::blocking_t result = asio::query(executor_, property); return result == execution::blocking.always ? execution::blocking.possibly : result; } Executor executor_; implementation_type impl_; }; /** @defgroup make_strand asio::make_strand * * @brief The asio::make_strand function creates a @ref strand object for * an executor or execution context. */ /*@{*/ /// Create a @ref strand object for an executor. /** * @param ex An executor. * * @returns A strand constructed with the specified executor. */ template <typename Executor> inline strand<Executor> make_strand(const Executor& ex, constraint_t< is_executor<Executor>::value || execution::is_executor<Executor>::value > = 0) { return strand<Executor>(ex); } /// Create a @ref strand object for an execution context. /** * @param ctx An execution context, from which an executor will be obtained. * * @returns A strand constructed with the execution context's executor, obtained * by performing <tt>ctx.get_executor()</tt>. */ template <typename ExecutionContext> inline strand<typename ExecutionContext::executor_type> make_strand(ExecutionContext& ctx, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { return strand<typename ExecutionContext::executor_type>(ctx.get_executor()); } /*@}*/ #if !defined(GENERATING_DOCUMENTATION) namespace traits { #if !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) template <typename Executor> struct equality_comparable<strand<Executor>> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = true; }; #endif // !defined(ASIO_HAS_DEDUCED_EQUALITY_COMPARABLE_TRAIT) #if !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) template <typename Executor, typename Function> struct execute_member<strand<Executor>, Function, enable_if_t< traits::execute_member<const Executor&, Function>::is_valid >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = false; typedef void result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_EXECUTE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) template <typename Executor, typename Property> struct query_member<strand<Executor>, Property, enable_if_t< can_query<const Executor&, Property>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_query<Executor, Property>::value; typedef conditional_t< is_convertible<Property, execution::blocking_t>::value, execution::blocking_t, query_result_t<Executor, Property>> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_QUERY_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) template <typename Executor, typename Property> struct require_member<strand<Executor>, Property, enable_if_t< can_require<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_require<Executor, Property>::value; typedef strand<decay_t<require_result_t<Executor, Property>>> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_REQUIRE_MEMBER_TRAIT) #if !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) template <typename Executor, typename Property> struct prefer_member<strand<Executor>, Property, enable_if_t< can_prefer<const Executor&, Property>::value && !is_convertible<Property, execution::blocking_t::always_t>::value >> { static constexpr bool is_valid = true; static constexpr bool is_noexcept = is_nothrow_prefer<Executor, Property>::value; typedef strand<decay_t<prefer_result_t<Executor, Property>>> result_type; }; #endif // !defined(ASIO_HAS_DEDUCED_PREFER_MEMBER_TRAIT) } // namespace traits #endif // !defined(GENERATING_DOCUMENTATION) } // namespace asio #include "asio/detail/pop_options.hpp" // If both io_context.hpp and strand.hpp have been included, automatically // include the header file needed for the io_context::strand class. #if !defined(ASIO_NO_EXTENSIONS) # if defined(ASIO_IO_CONTEXT_HPP) # include "asio/io_context_strand.hpp" # endif // defined(ASIO_IO_CONTEXT_HPP) #endif // !defined(ASIO_NO_EXTENSIONS) #endif // ASIO_STRAND_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/static_thread_pool.hpp
// // static_thread_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 ASIO_STATIC_THREAD_POOL_HPP #define ASIO_STATIC_THREAD_POOL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/thread_pool.hpp" #include "asio/detail/push_options.hpp" namespace asio { typedef thread_pool static_thread_pool; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_STATIC_THREAD_POOL_HPP
0
repos/asio/asio/include
repos/asio/asio/include/asio/basic_file.hpp
// // basic_file.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 ASIO_BASIC_FILE_HPP #define ASIO_BASIC_FILE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_FILE) \ || defined(GENERATING_DOCUMENTATION) #include <string> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/cstdint.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/type_traits.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/post.hpp" #include "asio/file_base.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_file_service.hpp" #elif defined(ASIO_HAS_IO_URING) # include "asio/detail/io_uring_file_service.hpp" #endif #include "asio/detail/push_options.hpp" namespace asio { #if !defined(ASIO_BASIC_FILE_FWD_DECL) #define ASIO_BASIC_FILE_FWD_DECL // Forward declaration with defaulted arguments. template <typename Executor = any_io_executor> class basic_file; #endif // !defined(ASIO_BASIC_FILE_FWD_DECL) /// Provides file functionality. /** * The basic_file class template provides functionality that is common to both * stream-oriented and random-access files. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor> class basic_file : public file_base { public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the file type to another executor. template <typename Executor1> struct rebind_executor { /// The file type when rebound to the specified executor. typedef basic_file<Executor1> other; }; /// The native representation of a file. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_HAS_IOCP) typedef detail::win_iocp_file_service::native_handle_type native_handle_type; #elif defined(ASIO_HAS_IO_URING) typedef detail::io_uring_file_service::native_handle_type native_handle_type; #endif /// Construct a basic_file without opening it. /** * This constructor initialises a file without opening it. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. */ explicit basic_file(const executor_type& ex) : impl_(0, ex) { } /// Construct a basic_file without opening it. /** * This constructor initialises a file without opening it. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. */ template <typename ExecutionContext> explicit basic_file(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct and open a basic_file. /** * This constructor initialises a file and opens it. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. */ explicit basic_file(const executor_type& ex, const char* path, file_base::flags open_flags) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_file without opening it. /** * This constructor initialises a file and opens it. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. */ template <typename ExecutionContext> explicit basic_file(ExecutionContext& context, const char* path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct and open a basic_file. /** * This constructor initialises a file and opens it. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. */ explicit basic_file(const executor_type& ex, const std::string& path, file_base::flags open_flags) : impl_(0, ex) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_file without opening it. /** * This constructor initialises a file and opens it. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. */ template <typename ExecutionContext> explicit basic_file(ExecutionContext& context, const std::string& path, file_base::flags open_flags, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Construct a basic_file on an existing native file handle. /** * This constructor initialises a file object to hold an existing native file. * * @param ex The I/O executor that the file will use, by default, to * dispatch handlers for any asynchronous operations performed on the file. * * @param native_file A native file handle. * * @throws asio::system_error Thrown on failure. */ basic_file(const executor_type& ex, const native_handle_type& native_file) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a basic_file on an existing native file. /** * This constructor initialises a file object to hold an existing native file. * * @param context An execution context which provides the I/O executor that * the file will use, by default, to dispatch handlers for any asynchronous * operations performed on the file. * * @param native_file A native file. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_file(ExecutionContext& context, const native_handle_type& native_file, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a basic_file from another. /** * This constructor moves a file from one object to another. * * @param other The other basic_file object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_file(const executor_type&) constructor. */ basic_file(basic_file&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a basic_file from another. /** * This assignment operator moves a file from one object to another. * * @param other The other basic_file object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_file(const executor_type&) constructor. */ basic_file& operator=(basic_file&& other) { impl_ = std::move(other.impl_); return *this; } // All files have access to each other's implementations. template <typename Executor1> friend class basic_file; /// Move-construct a basic_file from a file of another executor type. /** * This constructor moves a file from one object to another. * * @param other The other basic_file object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_file(const executor_type&) constructor. */ template <typename Executor1> basic_file(basic_file<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_file from a file of another executor type. /** * This assignment operator moves a file from one object to another. * * @param other The other basic_file object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_file(const executor_type&) constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_file& > operator=(basic_file<Executor1>&& other) { basic_file tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::stream_file file(my_context); * file.open("/path/to/my/file", asio::stream_file::read_only); * @endcode */ void open(const char* path, file_base::flags open_flags) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::stream_file file(my_context); * asio::error_code ec; * file.open("/path/to/my/file", asio::stream_file::read_only, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID open(const char* path, file_base::flags open_flags, asio::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), path, open_flags, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @throws asio::system_error Thrown on failure. * * @par Example * @code * asio::stream_file file(my_context); * file.open("/path/to/my/file", asio::stream_file::read_only); * @endcode */ void open(const std::string& path, file_base::flags open_flags) { asio::error_code ec; impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); asio::detail::throw_error(ec, "open"); } /// Open the file using the specified path. /** * This function opens the file so that it will use the specified path. * * @param path The path name identifying the file to be opened. * * @param open_flags A set of flags that determine how the file should be * opened. * * @param ec Set to indicate what error occurred, if any. * * @par Example * @code * asio::stream_file file(my_context); * asio::error_code ec; * file.open("/path/to/my/file", asio::stream_file::read_only, ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID open(const std::string& path, file_base::flags open_flags, asio::error_code& ec) { impl_.get_service().open(impl_.get_implementation(), path.c_str(), open_flags, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Assign an existing native file to the file. /* * This function opens the file to hold an existing native file. * * @param native_file A native file. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_file) { asio::error_code ec; impl_.get_service().assign( impl_.get_implementation(), native_file, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native file to the file. /* * This function opens the file to hold an existing native file. * * @param native_file A native file. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& native_file, asio::error_code& ec) { impl_.get_service().assign( impl_.get_implementation(), native_file, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the file is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the file. /** * This function is used to close the file. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the file. /** * This function is used to close the file. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. * * @par Example * @code * asio::stream_file file(my_context); * ... * asio::error_code ec; * file.close(ec); * if (ec) * { * // An error occurred. * } * @endcode */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the asio::error::operation_aborted error. * Ownership of the native file is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the asio::error::operation_aborted error. * Ownership of the native file is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native file representation. /** * This function may be used to obtain the underlying representation of the * file. This is intended to allow access to native file functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using the close() function to * simultaneously cancel the outstanding operations and close the file. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the file. /** * This function causes all outstanding asynchronous read and write * operations to finish immediately, and the handlers for cancelled * operations will be passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. * * @note Calls to cancel() will always fail with * asio::error::operation_not_supported when run on Windows XP, Windows * Server 2003, and earlier versions of Windows, unless * ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has * two issues that should be considered before enabling its use: * * @li It will only cancel asynchronous operations that were initiated in the * current thread. * * @li It can appear to complete without error, but the request to cancel the * unfinished operations may be silently ignored by the operating system. * Whether it works or not seems to depend on the drivers that are installed. * * For portable cancellation, consider using the close() function to * simultaneously cancel the outstanding operations and close the file. * * When running on Windows Vista, Windows Server 2008, and later, the * CancelIoEx function is always used. This function does not have the * problems described above. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0600) \ && !defined(ASIO_ENABLE_CANCELIO) __declspec(deprecated("By default, this function always fails with " "operation_not_supported when used on Windows XP, Windows Server 2003, " "or earlier. Consult documentation for details.")) #endif ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the size of the file. /** * This function determines the size of the file, in bytes. * * @throws asio::system_error Thrown on failure. */ uint64_t size() const { asio::error_code ec; uint64_t s = impl_.get_service().size(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "size"); return s; } /// Get the size of the file. /** * This function determines the size of the file, in bytes. * * @param ec Set to indicate what error occurred, if any. */ uint64_t size(asio::error_code& ec) const { return impl_.get_service().size(impl_.get_implementation(), ec); } /// Alter the size of the file. /** * This function resizes the file to the specified size, in bytes. If the * current file size exceeds @c n then any extra data is discarded. If the * current size is less than @c n then the file is extended and filled with * zeroes. * * @param n The new size for the file. * * @throws asio::system_error Thrown on failure. */ void resize(uint64_t n) { asio::error_code ec; impl_.get_service().resize(impl_.get_implementation(), n, ec); asio::detail::throw_error(ec, "resize"); } /// Alter the size of the file. /** * This function resizes the file to the specified size, in bytes. If the * current file size exceeds @c n then any extra data is discarded. If the * current size is less than @c n then the file is extended and filled with * zeroes. * * @param n The new size for the file. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID resize(uint64_t n, asio::error_code& ec) { impl_.get_service().resize(impl_.get_implementation(), n, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Synchronise the file to disk. /** * This function synchronises the file data and metadata to disk. Note that * the semantics of this synchronisation vary between operation systems. * * @throws asio::system_error Thrown on failure. */ void sync_all() { asio::error_code ec; impl_.get_service().sync_all(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "sync_all"); } /// Synchronise the file to disk. /** * This function synchronises the file data and metadata to disk. Note that * the semantics of this synchronisation vary between operation systems. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID sync_all(asio::error_code& ec) { impl_.get_service().sync_all(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Synchronise the file data to disk. /** * This function synchronises the file data to disk. Note that the semantics * of this synchronisation vary between operation systems. * * @throws asio::system_error Thrown on failure. */ void sync_data() { asio::error_code ec; impl_.get_service().sync_data(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "sync_data"); } /// Synchronise the file data to disk. /** * This function synchronises the file data to disk. Note that the semantics * of this synchronisation vary between operation systems. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID sync_data(asio::error_code& ec) { impl_.get_service().sync_data(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the file, cancelling any outstanding asynchronous * operations associated with the file as if by calling @c cancel. */ ~basic_file() { } #if defined(ASIO_HAS_IOCP) detail::io_object_impl<detail::win_iocp_file_service, Executor> impl_; #elif defined(ASIO_HAS_IO_URING) detail::io_object_impl<detail::io_uring_file_service, Executor> impl_; #endif private: // Disallow copying and assignment. basic_file(const basic_file&) = delete; basic_file& operator=(const basic_file&) = delete; }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_FILE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_BASIC_FILE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/error.hpp
// // ssl/error.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 ASIO_SSL_ERROR_HPP #define ASIO_SSL_ERROR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/error_code.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace error { enum ssl_errors { // Error numbers are those produced by openssl. }; extern ASIO_DECL const asio::error_category& get_ssl_category(); static const asio::error_category& ssl_category ASIO_UNUSED_VARIABLE = asio::error::get_ssl_category(); } // namespace error namespace ssl { namespace error { enum stream_errors { #if defined(GENERATING_DOCUMENTATION) /// The underlying stream closed before the ssl stream gracefully shut down. stream_truncated, /// The underlying SSL library returned a system error without providing /// further information. unspecified_system_error, /// The underlying SSL library generated an unexpected result from a function /// call. unexpected_result #else // defined(GENERATING_DOCUMENTATION) # if (OPENSSL_VERSION_NUMBER < 0x10100000L) \ && !defined(OPENSSL_IS_BORINGSSL) \ && !defined(ASIO_USE_WOLFSSL) stream_truncated = ERR_PACK(ERR_LIB_SSL, 0, SSL_R_SHORT_READ), # else stream_truncated = 1, # endif unspecified_system_error = 2, unexpected_result = 3 #endif // defined(GENERATING_DOCUMENTATION) }; extern ASIO_DECL const asio::error_category& get_stream_category(); static const asio::error_category& stream_category ASIO_UNUSED_VARIABLE = asio::ssl::error::get_stream_category(); } // namespace error } // namespace ssl } // namespace asio namespace std { template<> struct is_error_code_enum<asio::error::ssl_errors> { static const bool value = true; }; template<> struct is_error_code_enum<asio::ssl::error::stream_errors> { static const bool value = true; }; } // namespace std namespace asio { namespace error { inline asio::error_code make_error_code(ssl_errors e) { return asio::error_code( static_cast<int>(e), get_ssl_category()); } } // namespace error namespace ssl { namespace error { inline asio::error_code make_error_code(stream_errors e) { return asio::error_code( static_cast<int>(e), get_stream_category()); } } // namespace error } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/impl/error.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SSL_ERROR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/context_base.hpp
// // ssl/context_base.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 ASIO_SSL_CONTEXT_BASE_HPP #define ASIO_SSL_CONTEXT_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// The context_base class is used as a base for the basic_context class /// template so that we have a common place to define various enums. class context_base { public: /// Different methods supported by a context. enum method { /// Generic SSL version 2. sslv2, /// SSL version 2 client. sslv2_client, /// SSL version 2 server. sslv2_server, /// Generic SSL version 3. sslv3, /// SSL version 3 client. sslv3_client, /// SSL version 3 server. sslv3_server, /// Generic TLS version 1. tlsv1, /// TLS version 1 client. tlsv1_client, /// TLS version 1 server. tlsv1_server, /// Generic SSL/TLS. sslv23, /// SSL/TLS client. sslv23_client, /// SSL/TLS server. sslv23_server, /// Generic TLS version 1.1. tlsv11, /// TLS version 1.1 client. tlsv11_client, /// TLS version 1.1 server. tlsv11_server, /// Generic TLS version 1.2. tlsv12, /// TLS version 1.2 client. tlsv12_client, /// TLS version 1.2 server. tlsv12_server, /// Generic TLS version 1.3. tlsv13, /// TLS version 1.3 client. tlsv13_client, /// TLS version 1.3 server. tlsv13_server, /// Generic TLS. tls, /// TLS client. tls_client, /// TLS server. tls_server }; /// Bitmask type for SSL options. typedef uint64_t options; #if defined(GENERATING_DOCUMENTATION) /// Implement various bug workarounds. static const uint64_t default_workarounds = implementation_defined; /// Always create a new key when using tmp_dh parameters. static const uint64_t single_dh_use = implementation_defined; /// Disable SSL v2. static const uint64_t no_sslv2 = implementation_defined; /// Disable SSL v3. static const uint64_t no_sslv3 = implementation_defined; /// Disable TLS v1. static const uint64_t no_tlsv1 = implementation_defined; /// Disable TLS v1.1. static const uint64_t no_tlsv1_1 = implementation_defined; /// Disable TLS v1.2. static const uint64_t no_tlsv1_2 = implementation_defined; /// Disable TLS v1.3. static const uint64_t no_tlsv1_3 = implementation_defined; /// Disable compression. Compression is disabled by default. static const uint64_t no_compression = implementation_defined; #else ASIO_STATIC_CONSTANT(uint64_t, default_workarounds = SSL_OP_ALL); ASIO_STATIC_CONSTANT(uint64_t, single_dh_use = SSL_OP_SINGLE_DH_USE); ASIO_STATIC_CONSTANT(uint64_t, no_sslv2 = SSL_OP_NO_SSLv2); ASIO_STATIC_CONSTANT(uint64_t, no_sslv3 = SSL_OP_NO_SSLv3); ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1 = SSL_OP_NO_TLSv1); # if defined(SSL_OP_NO_TLSv1_1) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_1 = SSL_OP_NO_TLSv1_1); # else // defined(SSL_OP_NO_TLSv1_1) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_1 = 0x10000000L); # endif // defined(SSL_OP_NO_TLSv1_1) # if defined(SSL_OP_NO_TLSv1_2) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_2 = SSL_OP_NO_TLSv1_2); # else // defined(SSL_OP_NO_TLSv1_2) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_2 = 0x08000000L); # endif // defined(SSL_OP_NO_TLSv1_2) # if defined(SSL_OP_NO_TLSv1_3) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_3 = SSL_OP_NO_TLSv1_3); # else // defined(SSL_OP_NO_TLSv1_3) ASIO_STATIC_CONSTANT(uint64_t, no_tlsv1_3 = 0x20000000L); # endif // defined(SSL_OP_NO_TLSv1_3) # if defined(SSL_OP_NO_COMPRESSION) ASIO_STATIC_CONSTANT(uint64_t, no_compression = SSL_OP_NO_COMPRESSION); # else // defined(SSL_OP_NO_COMPRESSION) ASIO_STATIC_CONSTANT(uint64_t, no_compression = 0x20000L); # endif // defined(SSL_OP_NO_COMPRESSION) #endif /// File format types. enum file_format { /// ASN.1 file. asn1, /// PEM file. pem }; #if !defined(GENERATING_DOCUMENTATION) // The following types and constants are preserved for backward compatibility. // New programs should use the equivalents of the same names that are defined // in the asio::ssl namespace. typedef int verify_mode; ASIO_STATIC_CONSTANT(int, verify_none = SSL_VERIFY_NONE); ASIO_STATIC_CONSTANT(int, verify_peer = SSL_VERIFY_PEER); ASIO_STATIC_CONSTANT(int, verify_fail_if_no_peer_cert = SSL_VERIFY_FAIL_IF_NO_PEER_CERT); ASIO_STATIC_CONSTANT(int, verify_client_once = SSL_VERIFY_CLIENT_ONCE); #endif /// Purpose of PEM password. enum password_purpose { /// The password is needed for reading/decryption. for_reading, /// The password is needed for writing/encryption. for_writing }; protected: /// Protected destructor to prevent deletion through this type. ~context_base() { } }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_CONTEXT_BASE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/rfc2818_verification.hpp
// // ssl/rfc2818_verification.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 ASIO_SSL_RFC2818_VERIFICATION_HPP #define ASIO_SSL_RFC2818_VERIFICATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_DEPRECATED) #include <string> #include "asio/ssl/detail/openssl_types.hpp" #include "asio/ssl/verify_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// (Deprecated. Use ssl::host_name_verification.) Verifies a certificate /// against a hostname according to the rules described in RFC 2818. /** * @par Example * The following example shows how to synchronously open a secure connection to * a given host name: * @code * using asio::ip::tcp; * namespace ssl = asio::ssl; * typedef ssl::stream<tcp::socket> ssl_socket; * * // Create a context that uses the default paths for finding CA certificates. * ssl::context ctx(ssl::context::sslv23); * ctx.set_default_verify_paths(); * * // Open a socket and connect it to the remote host. * asio::io_context io_context; * ssl_socket sock(io_context, ctx); * tcp::resolver resolver(io_context); * tcp::resolver::query query("host.name", "https"); * asio::connect(sock.lowest_layer(), resolver.resolve(query)); * sock.lowest_layer().set_option(tcp::no_delay(true)); * * // Perform SSL handshake and verify the remote host's certificate. * sock.set_verify_mode(ssl::verify_peer); * sock.set_verify_callback(ssl::rfc2818_verification("host.name")); * sock.handshake(ssl_socket::client); * * // ... read and write as normal ... * @endcode */ class rfc2818_verification { public: /// The type of the function object's result. typedef bool result_type; /// Constructor. explicit rfc2818_verification(const std::string& host) : host_(host) { } /// Perform certificate verification. ASIO_DECL bool operator()(bool preverified, verify_context& ctx) const; private: // Helper function to check a host name against a pattern. ASIO_DECL static bool match_pattern(const char* pattern, std::size_t pattern_length, const char* host); // Helper function to check a host name against an IPv4 address // The host name to be checked. std::string host_; }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/impl/rfc2818_verification.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // !defined(ASIO_NO_DEPRECATED) #endif // ASIO_SSL_RFC2818_VERIFICATION_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/verify_mode.hpp
// // ssl/verify_mode.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 ASIO_SSL_VERIFY_MODE_HPP #define ASIO_SSL_VERIFY_MODE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// Bitmask type for peer verification. /** * Possible values are: * * @li @ref verify_none * @li @ref verify_peer * @li @ref verify_fail_if_no_peer_cert * @li @ref verify_client_once */ typedef int verify_mode; #if defined(GENERATING_DOCUMENTATION) /// No verification. const int verify_none = implementation_defined; /// Verify the peer. const int verify_peer = implementation_defined; /// Fail verification if the peer has no certificate. Ignored unless /// @ref verify_peer is set. const int verify_fail_if_no_peer_cert = implementation_defined; /// Do not request client certificate on renegotiation. Ignored unless /// @ref verify_peer is set. const int verify_client_once = implementation_defined; #else const int verify_none = SSL_VERIFY_NONE; const int verify_peer = SSL_VERIFY_PEER; const int verify_fail_if_no_peer_cert = SSL_VERIFY_FAIL_IF_NO_PEER_CERT; const int verify_client_once = SSL_VERIFY_CLIENT_ONCE; #endif } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_VERIFY_MODE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/host_name_verification.hpp
// // ssl/host_name_verification.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 ASIO_SSL_HOST_NAME_VERIFICATION_HPP #define ASIO_SSL_HOST_NAME_VERIFICATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <string> #include "asio/ssl/detail/openssl_types.hpp" #include "asio/ssl/verify_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// Verifies a certificate against a host_name according to the rules described /// in RFC 6125. /** * @par Example * The following example shows how to synchronously open a secure connection to * a given host name: * @code * using asio::ip::tcp; * namespace ssl = asio::ssl; * typedef ssl::stream<tcp::socket> ssl_socket; * * // Create a context that uses the default paths for finding CA certificates. * ssl::context ctx(ssl::context::sslv23); * ctx.set_default_verify_paths(); * * // Open a socket and connect it to the remote host. * asio::io_context io_context; * ssl_socket sock(io_context, ctx); * tcp::resolver resolver(io_context); * tcp::resolver::query query("host.name", "https"); * asio::connect(sock.lowest_layer(), resolver.resolve(query)); * sock.lowest_layer().set_option(tcp::no_delay(true)); * * // Perform SSL handshake and verify the remote host's certificate. * sock.set_verify_mode(ssl::verify_peer); * sock.set_verify_callback(ssl::host_name_verification("host.name")); * sock.handshake(ssl_socket::client); * * // ... read and write as normal ... * @endcode */ class host_name_verification { public: /// The type of the function object's result. typedef bool result_type; /// Constructor. explicit host_name_verification(const std::string& host) : host_(host) { } /// Perform certificate verification. ASIO_DECL bool operator()(bool preverified, verify_context& ctx) const; private: // Helper function to check a host name against an IPv4 address // The host name to be checked. std::string host_; }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/impl/host_name_verification.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SSL_HOST_NAME_VERIFICATION_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/stream.hpp
// // ssl/stream.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 ASIO_SSL_STREAM_HPP #define ASIO_SSL_STREAM_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/async_result.hpp" #include "asio/buffer.hpp" #include "asio/detail/buffer_sequence_adapter.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/type_traits.hpp" #include "asio/ssl/context.hpp" #include "asio/ssl/detail/buffered_handshake_op.hpp" #include "asio/ssl/detail/handshake_op.hpp" #include "asio/ssl/detail/io.hpp" #include "asio/ssl/detail/read_op.hpp" #include "asio/ssl/detail/shutdown_op.hpp" #include "asio/ssl/detail/stream_core.hpp" #include "asio/ssl/detail/write_op.hpp" #include "asio/ssl/stream_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// Provides stream-oriented functionality using SSL. /** * The stream class template provides asynchronous and blocking stream-oriented * functionality using SSL. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. The application must also ensure that all * asynchronous operations are performed within the same implicit or explicit * strand. * * @par Example * To use the SSL stream template with an ip::tcp::socket, you would write: * @code * asio::io_context my_context; * asio::ssl::context ctx(asio::ssl::context::sslv23); * asio::ssl::stream<asio::ip::tcp::socket> sock(my_context, ctx); * @endcode * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Stream> class stream : public stream_base, private noncopyable { private: class initiate_async_handshake; class initiate_async_buffered_handshake; class initiate_async_shutdown; class initiate_async_write_some; class initiate_async_read_some; public: /// The native handle type of the SSL stream. typedef SSL* native_handle_type; /// Structure for use with deprecated impl_type. struct impl_struct { SSL* ssl; }; /// The type of the next layer. typedef remove_reference_t<Stream> next_layer_type; /// The type of the lowest layer. typedef typename next_layer_type::lowest_layer_type lowest_layer_type; /// The type of the executor associated with the object. typedef typename lowest_layer_type::executor_type executor_type; /// Construct a stream. /** * This constructor creates a stream and initialises the underlying stream * object. * * @param arg The argument to be passed to initialise the underlying stream. * * @param ctx The SSL context to be used for the stream. */ template <typename Arg> stream(Arg&& arg, context& ctx) : next_layer_(static_cast<Arg&&>(arg)), core_(ctx.native_handle(), next_layer_.lowest_layer().get_executor()) { } /// Construct a stream from an existing native implementation. /** * This constructor creates a stream and initialises the underlying stream * object. On success, ownership of the native implementation is transferred * to the stream, and it will be cleaned up when the stream is destroyed. * * @param arg The argument to be passed to initialise the underlying stream. * * @param handle An existing native SSL implementation. */ template <typename Arg> stream(Arg&& arg, native_handle_type handle) : next_layer_(static_cast<Arg&&>(arg)), core_(handle, next_layer_.lowest_layer().get_executor()) { } /// Move-construct a stream from another. /** * @param other The other stream object from which the move will occur. Must * have no outstanding asynchronous operations associated with it. Following * the move, @c other has a valid but unspecified state where the only safe * operation is destruction, or use as the target of a move assignment. */ stream(stream&& other) : next_layer_(static_cast<Stream&&>(other.next_layer_)), core_(static_cast<detail::stream_core&&>(other.core_)) { } /// Move-assign a stream from another. /** * @param other The other stream object from which the move will occur. Must * have no outstanding asynchronous operations associated with it. Following * the move, @c other has a valid but unspecified state where the only safe * operation is destruction, or use as the target of a move assignment. */ stream& operator=(stream&& other) { if (this != &other) { next_layer_ = static_cast<Stream&&>(other.next_layer_); core_ = static_cast<detail::stream_core&&>(other.core_); } return *this; } /// Destructor. /** * @note A @c stream object must not be destroyed while there are pending * asynchronous operations associated with it. */ ~stream() { } /// Get the executor associated with the object. /** * This function may be used to obtain the executor object that the stream * uses to dispatch handlers for asynchronous operations. * * @return A copy of the executor that stream will use to dispatch handlers. */ executor_type get_executor() noexcept { return next_layer_.lowest_layer().get_executor(); } /// Get the underlying implementation in the native type. /** * This function may be used to obtain the underlying implementation of the * context. This is intended to allow access to context functionality that is * not otherwise provided. * * @par Example * The native_handle() function returns a pointer of type @c SSL* that is * suitable for passing to functions such as @c SSL_get_verify_result and * @c SSL_get_peer_certificate: * @code * asio::ssl::stream<asio::ip::tcp::socket> sock(io_ctx, ctx); * * // ... establish connection and perform handshake ... * * if (X509* cert = SSL_get_peer_certificate(sock.native_handle())) * { * if (SSL_get_verify_result(sock.native_handle()) == X509_V_OK) * { * // ... * } * } * @endcode */ native_handle_type native_handle() { return core_.engine_.native_handle(); } /// Get a reference to the next layer. /** * This function returns a reference to the next layer in a stack of stream * layers. * * @return A reference to the next layer in the stack of stream layers. * Ownership is not transferred to the caller. */ const next_layer_type& next_layer() const { return next_layer_; } /// Get a reference to the next layer. /** * This function returns a reference to the next layer in a stack of stream * layers. * * @return A reference to the next layer in the stack of stream layers. * Ownership is not transferred to the caller. */ next_layer_type& next_layer() { return next_layer_; } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * stream layers. * * @return A reference to the lowest layer in the stack of stream layers. * Ownership is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return next_layer_.lowest_layer(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * stream layers. * * @return A reference to the lowest layer in the stack of stream layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return next_layer_.lowest_layer(); } /// Set the peer verification mode. /** * This function may be used to configure the peer verification mode used by * the stream. The new mode will override the mode inherited from the context. * * @param v A bitmask of peer verification modes. See @ref verify_mode for * available values. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_set_verify. */ void set_verify_mode(verify_mode v) { asio::error_code ec; set_verify_mode(v, ec); asio::detail::throw_error(ec, "set_verify_mode"); } /// Set the peer verification mode. /** * This function may be used to configure the peer verification mode used by * the stream. The new mode will override the mode inherited from the context. * * @param v A bitmask of peer verification modes. See @ref verify_mode for * available values. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_set_verify. */ ASIO_SYNC_OP_VOID set_verify_mode( verify_mode v, asio::error_code& ec) { core_.engine_.set_verify_mode(v, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Set the peer verification depth. /** * This function may be used to configure the maximum verification depth * allowed by the stream. * * @param depth Maximum depth for the certificate chain verification that * shall be allowed. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_set_verify_depth. */ void set_verify_depth(int depth) { asio::error_code ec; set_verify_depth(depth, ec); asio::detail::throw_error(ec, "set_verify_depth"); } /// Set the peer verification depth. /** * This function may be used to configure the maximum verification depth * allowed by the stream. * * @param depth Maximum depth for the certificate chain verification that * shall be allowed. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_set_verify_depth. */ ASIO_SYNC_OP_VOID set_verify_depth( int depth, asio::error_code& ec) { core_.engine_.set_verify_depth(depth, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Set the callback used to verify peer certificates. /** * This function is used to specify a callback function that will be called * by the implementation when it needs to verify a peer certificate. * * @param callback The function object to be used for verifying a certificate. * The function signature of the handler must be: * @code bool verify_callback( * bool preverified, // True if the certificate passed pre-verification. * verify_context& ctx // The peer certificate and other context. * ); @endcode * The return value of the callback is true if the certificate has passed * verification, false otherwise. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_set_verify. */ template <typename VerifyCallback> void set_verify_callback(VerifyCallback callback) { asio::error_code ec; this->set_verify_callback(callback, ec); asio::detail::throw_error(ec, "set_verify_callback"); } /// Set the callback used to verify peer certificates. /** * This function is used to specify a callback function that will be called * by the implementation when it needs to verify a peer certificate. * * @param callback The function object to be used for verifying a certificate. * The function signature of the handler must be: * @code bool verify_callback( * bool preverified, // True if the certificate passed pre-verification. * verify_context& ctx // The peer certificate and other context. * ); @endcode * The return value of the callback is true if the certificate has passed * verification, false otherwise. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_set_verify. */ template <typename VerifyCallback> ASIO_SYNC_OP_VOID set_verify_callback(VerifyCallback callback, asio::error_code& ec) { core_.engine_.set_verify_callback( new detail::verify_callback<VerifyCallback>(callback), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform SSL handshaking. /** * This function is used to perform SSL handshaking on the stream. The * function call will block until handshaking is complete or an error occurs. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @throws asio::system_error Thrown on failure. */ void handshake(handshake_type type) { asio::error_code ec; handshake(type, ec); asio::detail::throw_error(ec, "handshake"); } /// Perform SSL handshaking. /** * This function is used to perform SSL handshaking on the stream. The * function call will block until handshaking is complete or an error occurs. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID handshake(handshake_type type, asio::error_code& ec) { detail::io(next_layer_, core_, detail::handshake_op(type), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform SSL handshaking. /** * This function is used to perform SSL handshaking on the stream. The * function call will block until handshaking is complete or an error occurs. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @param buffers The buffered data to be reused for the handshake. * * @throws asio::system_error Thrown on failure. */ template <typename ConstBufferSequence> void handshake(handshake_type type, const ConstBufferSequence& buffers) { asio::error_code ec; handshake(type, buffers, ec); asio::detail::throw_error(ec, "handshake"); } /// Perform SSL handshaking. /** * This function is used to perform SSL handshaking on the stream. The * function call will block until handshaking is complete or an error occurs. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @param buffers The buffered data to be reused for the handshake. * * @param ec Set to indicate what error occurred, if any. */ template <typename ConstBufferSequence> ASIO_SYNC_OP_VOID handshake(handshake_type type, const ConstBufferSequence& buffers, asio::error_code& ec) { detail::io(next_layer_, core_, detail::buffered_handshake_op<ConstBufferSequence>(type, buffers), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Start an asynchronous SSL handshake. /** * This function is used to asynchronously perform an SSL handshake on the * stream. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the handshake completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c Stream type's @c async_read_some and * @c async_write_some operations. */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) HandshakeToken = default_completion_token_t<executor_type>> auto async_handshake(handshake_type type, HandshakeToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<HandshakeToken, void (asio::error_code)>( declval<initiate_async_handshake>(), token, type)) { return async_initiate<HandshakeToken, void (asio::error_code)>( initiate_async_handshake(this), token, type); } /// Start an asynchronous SSL handshake. /** * This function is used to asynchronously perform an SSL handshake on the * stream. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param type The type of handshaking to be performed, i.e. as a client or as * a server. * * @param buffers The buffered data to be reused for the handshake. Although * the buffers object may be copied as necessary, ownership of the underlying * buffers is retained by the caller, which must guarantee that they remain * valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the handshake completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Amount of buffers used in handshake. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c Stream type's @c async_read_some and * @c async_write_some operations. */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) BufferedHandshakeToken = default_completion_token_t<executor_type>> auto async_handshake(handshake_type type, const ConstBufferSequence& buffers, BufferedHandshakeToken&& token = default_completion_token_t<executor_type>(), constraint_t< is_const_buffer_sequence<ConstBufferSequence>::value > = 0) -> decltype( async_initiate<BufferedHandshakeToken, void (asio::error_code, std::size_t)>( declval<initiate_async_buffered_handshake>(), token, type, buffers)) { return async_initiate<BufferedHandshakeToken, void (asio::error_code, std::size_t)>( initiate_async_buffered_handshake(this), token, type, buffers); } /// Shut down SSL on the stream. /** * This function is used to shut down SSL on the stream. The function call * will block until SSL has been shut down or an error occurs. * * @throws asio::system_error Thrown on failure. */ void shutdown() { asio::error_code ec; shutdown(ec); asio::detail::throw_error(ec, "shutdown"); } /// Shut down SSL on the stream. /** * This function is used to shut down SSL on the stream. The function call * will block until SSL has been shut down or an error occurs. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID shutdown(asio::error_code& ec) { detail::io(next_layer_, core_, detail::shutdown_op(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously shut down SSL on the stream. /** * This function is used to asynchronously shut down SSL on the stream. It is * an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the shutdown completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c Stream type's @c async_read_some and * @c async_write_some operations. */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) ShutdownToken = default_completion_token_t<executor_type>> auto async_shutdown( ShutdownToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ShutdownToken, void (asio::error_code)>( declval<initiate_async_shutdown>(), token)) { return async_initiate<ShutdownToken, void (asio::error_code)>( initiate_async_shutdown(this), token); } /// Write some data to the stream. /** * This function is used to write data on the stream. The function call will * block until one or more bytes of data has been written successfully, or * until an error occurs. * * @param buffers The data to be written. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that all * data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t n = write_some(buffers, ec); asio::detail::throw_error(ec, "write_some"); return n; } /// Write some data to the stream. /** * This function is used to write data on the stream. The function call will * block until one or more bytes of data has been written successfully, or * until an error occurs. * * @param buffers The data to be written to the stream. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that all * data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return detail::io(next_layer_, core_, detail::write_op<ConstBufferSequence>(buffers), ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write one or more bytes of data to * the stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers The data to be written to the stream. Although the buffers * object may be copied as necessary, ownership of the underlying buffers is * retained by the caller, which must guarantee that they remain valid until * the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_write_some operation may not transmit all of the data to * the peer. Consider using the @ref async_write function if you need to * ensure that all data is written before the asynchronous operation * completes. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c Stream type's @c async_read_some and * @c async_write_some operations. */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } /// Read some data from the stream. /** * This function is used to read data from the stream. The function call will * block until one or more bytes of data has been read successfully, or until * an error occurs. * * @param buffers The buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t n = read_some(buffers, ec); asio::detail::throw_error(ec, "read_some"); return n; } /// Read some data from the stream. /** * This function is used to read data from the stream. The function call will * block until one or more bytes of data has been read successfully, or until * an error occurs. * * @param buffers The buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that the * requested amount of data is read before the blocking operation completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return detail::io(next_layer_, core_, detail::read_op<MutableBufferSequence>(buffers), ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read one or more bytes of data from * the stream. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers The buffers into which the data will be read. Although the * buffers object may be copied as necessary, ownership of the underlying * buffers is retained by the caller, which must guarantee that they remain * valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The async_read_some operation may not read all of the requested * number of bytes. Consider using the @ref async_read function if you need to * ensure that the requested amount of data is read before the asynchronous * operation completes. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * if they are also supported by the @c Stream type's @c async_read_some and * @c async_write_some operations. */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: class initiate_async_handshake { public: typedef typename stream::executor_type executor_type; explicit initiate_async_handshake(stream* self) : self_(self) { } executor_type get_executor() const noexcept { return self_->get_executor(); } template <typename HandshakeHandler> void operator()(HandshakeHandler&& handler, handshake_type type) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a HandshakeHandler. ASIO_HANDSHAKE_HANDLER_CHECK(HandshakeHandler, handler) type_check; asio::detail::non_const_lvalue<HandshakeHandler> handler2(handler); detail::async_io(self_->next_layer_, self_->core_, detail::handshake_op(type), handler2.value); } private: stream* self_; }; class initiate_async_buffered_handshake { public: typedef typename stream::executor_type executor_type; explicit initiate_async_buffered_handshake(stream* self) : self_(self) { } executor_type get_executor() const noexcept { return self_->get_executor(); } template <typename BufferedHandshakeHandler, typename ConstBufferSequence> void operator()(BufferedHandshakeHandler&& handler, handshake_type type, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your // handler does not meet the documented type requirements for a // BufferedHandshakeHandler. ASIO_BUFFERED_HANDSHAKE_HANDLER_CHECK( BufferedHandshakeHandler, handler) type_check; asio::detail::non_const_lvalue< BufferedHandshakeHandler> handler2(handler); detail::async_io(self_->next_layer_, self_->core_, detail::buffered_handshake_op<ConstBufferSequence>(type, buffers), handler2.value); } private: stream* self_; }; class initiate_async_shutdown { public: typedef typename stream::executor_type executor_type; explicit initiate_async_shutdown(stream* self) : self_(self) { } executor_type get_executor() const noexcept { return self_->get_executor(); } template <typename ShutdownHandler> void operator()(ShutdownHandler&& handler) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ShutdownHandler. ASIO_HANDSHAKE_HANDLER_CHECK(ShutdownHandler, handler) type_check; asio::detail::non_const_lvalue<ShutdownHandler> handler2(handler); detail::async_io(self_->next_layer_, self_->core_, detail::shutdown_op(), handler2.value); } private: stream* self_; }; class initiate_async_write_some { public: typedef typename stream::executor_type executor_type; explicit initiate_async_write_some(stream* self) : self_(self) { } executor_type get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; asio::detail::non_const_lvalue<WriteHandler> handler2(handler); detail::async_io(self_->next_layer_, self_->core_, detail::write_op<ConstBufferSequence>(buffers), handler2.value); } private: stream* self_; }; class initiate_async_read_some { public: typedef typename stream::executor_type executor_type; explicit initiate_async_read_some(stream* self) : self_(self) { } executor_type get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; asio::detail::non_const_lvalue<ReadHandler> handler2(handler); detail::async_io(self_->next_layer_, self_->core_, detail::read_op<MutableBufferSequence>(buffers), handler2.value); } private: stream* self_; }; Stream next_layer_; detail::stream_core core_; }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_STREAM_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/verify_context.hpp
// // ssl/verify_context.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 ASIO_SSL_VERIFY_CONTEXT_HPP #define ASIO_SSL_VERIFY_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// A simple wrapper around the X509_STORE_CTX type, used during verification of /// a peer certificate. /** * @note The verify_context does not own the underlying X509_STORE_CTX object. */ class verify_context : private noncopyable { public: /// The native handle type of the verification context. typedef X509_STORE_CTX* native_handle_type; /// Constructor. explicit verify_context(native_handle_type handle) : handle_(handle) { } /// Get the underlying implementation in the native type. /** * This function may be used to obtain the underlying implementation of the * context. This is intended to allow access to context functionality that is * not otherwise provided. */ native_handle_type native_handle() { return handle_; } private: // The underlying native implementation. native_handle_type handle_; }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_VERIFY_CONTEXT_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/stream_base.hpp
// // ssl/stream_base.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 ASIO_SSL_STREAM_BASE_HPP #define ASIO_SSL_STREAM_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { /// The stream_base class is used as a base for the asio::ssl::stream /// class template so that we have a common place to define various enums. class stream_base { public: /// Different handshake types. enum handshake_type { /// Perform handshaking as a client. client, /// Perform handshaking as a server. server }; protected: /// Protected destructor to prevent deletion through this type. ~stream_base() { } }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_STREAM_BASE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ssl/context.hpp
// // ssl/context.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 ASIO_SSL_CONTEXT_HPP #define ASIO_SSL_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <string> #include "asio/buffer.hpp" #include "asio/io_context.hpp" #include "asio/ssl/context_base.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/ssl/detail/openssl_init.hpp" #include "asio/ssl/detail/password_callback.hpp" #include "asio/ssl/detail/verify_callback.hpp" #include "asio/ssl/verify_mode.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { class context : public context_base, private noncopyable { public: /// The native handle type of the SSL context. typedef SSL_CTX* native_handle_type; /// Constructor. ASIO_DECL explicit context(method m); /// Construct to take ownership of a native handle. ASIO_DECL explicit context(native_handle_type native_handle); /// Move-construct a context from another. /** * This constructor moves an SSL context from one object to another. * * @param other The other context object from which the move will occur. * * @note Following the move, the following operations only are valid for the * moved-from object: * @li Destruction. * @li As a target for move-assignment. */ ASIO_DECL context(context&& other); /// Move-assign a context from another. /** * This assignment operator moves an SSL context from one object to another. * * @param other The other context object from which the move will occur. * * @note Following the move, the following operations only are valid for the * moved-from object: * @li Destruction. * @li As a target for move-assignment. */ ASIO_DECL context& operator=(context&& other); /// Destructor. ASIO_DECL ~context(); /// Get the underlying implementation in the native type. /** * This function may be used to obtain the underlying implementation of the * context. This is intended to allow access to context functionality that is * not otherwise provided. */ ASIO_DECL native_handle_type native_handle(); /// Clear options on the context. /** * This function may be used to configure the SSL options used by the context. * * @param o A bitmask of options. The available option values are defined in * the context_base class. The specified options, if currently enabled on the * context, are cleared. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_clear_options. */ ASIO_DECL void clear_options(options o); /// Clear options on the context. /** * This function may be used to configure the SSL options used by the context. * * @param o A bitmask of options. The available option values are defined in * the context_base class. The specified options, if currently enabled on the * context, are cleared. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_clear_options. */ ASIO_DECL ASIO_SYNC_OP_VOID clear_options(options o, asio::error_code& ec); /// Set options on the context. /** * This function may be used to configure the SSL options used by the context. * * @param o A bitmask of options. The available option values are defined in * the context_base class. The options are bitwise-ored with any existing * value for the options. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_options. */ ASIO_DECL void set_options(options o); /// Set options on the context. /** * This function may be used to configure the SSL options used by the context. * * @param o A bitmask of options. The available option values are defined in * the context_base class. The options are bitwise-ored with any existing * value for the options. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_options. */ ASIO_DECL ASIO_SYNC_OP_VOID set_options(options o, asio::error_code& ec); /// Set the peer verification mode. /** * This function may be used to configure the peer verification mode used by * the context. * * @param v A bitmask of peer verification modes. See @ref verify_mode for * available values. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_verify. */ ASIO_DECL void set_verify_mode(verify_mode v); /// Set the peer verification mode. /** * This function may be used to configure the peer verification mode used by * the context. * * @param v A bitmask of peer verification modes. See @ref verify_mode for * available values. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_verify. */ ASIO_DECL ASIO_SYNC_OP_VOID set_verify_mode( verify_mode v, asio::error_code& ec); /// Set the peer verification depth. /** * This function may be used to configure the maximum verification depth * allowed by the context. * * @param depth Maximum depth for the certificate chain verification that * shall be allowed. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_verify_depth. */ ASIO_DECL void set_verify_depth(int depth); /// Set the peer verification depth. /** * This function may be used to configure the maximum verification depth * allowed by the context. * * @param depth Maximum depth for the certificate chain verification that * shall be allowed. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_verify_depth. */ ASIO_DECL ASIO_SYNC_OP_VOID set_verify_depth( int depth, asio::error_code& ec); /// Set the callback used to verify peer certificates. /** * This function is used to specify a callback function that will be called * by the implementation when it needs to verify a peer certificate. * * @param callback The function object to be used for verifying a certificate. * The function signature of the handler must be: * @code bool verify_callback( * bool preverified, // True if the certificate passed pre-verification. * verify_context& ctx // The peer certificate and other context. * ); @endcode * The return value of the callback is true if the certificate has passed * verification, false otherwise. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_verify. */ template <typename VerifyCallback> void set_verify_callback(VerifyCallback callback); /// Set the callback used to verify peer certificates. /** * This function is used to specify a callback function that will be called * by the implementation when it needs to verify a peer certificate. * * @param callback The function object to be used for verifying a certificate. * The function signature of the handler must be: * @code bool verify_callback( * bool preverified, // True if the certificate passed pre-verification. * verify_context& ctx // The peer certificate and other context. * ); @endcode * The return value of the callback is true if the certificate has passed * verification, false otherwise. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_verify. */ template <typename VerifyCallback> ASIO_SYNC_OP_VOID set_verify_callback(VerifyCallback callback, asio::error_code& ec); /// Load a certification authority file for performing verification. /** * This function is used to load one or more trusted certification authorities * from a file. * * @param filename The name of a file containing certification authority * certificates in PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_load_verify_locations. */ ASIO_DECL void load_verify_file(const std::string& filename); /// Load a certification authority file for performing verification. /** * This function is used to load the certificates for one or more trusted * certification authorities from a file. * * @param filename The name of a file containing certification authority * certificates in PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_load_verify_locations. */ ASIO_DECL ASIO_SYNC_OP_VOID load_verify_file( const std::string& filename, asio::error_code& ec); /// Add certification authority for performing verification. /** * This function is used to add one trusted certification authority * from a memory buffer. * * @param ca The buffer containing the certification authority certificate. * The certificate must use the PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_get_cert_store and @c X509_STORE_add_cert. */ ASIO_DECL void add_certificate_authority(const const_buffer& ca); /// Add certification authority for performing verification. /** * This function is used to add one trusted certification authority * from a memory buffer. * * @param ca The buffer containing the certification authority certificate. * The certificate must use the PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_get_cert_store and @c X509_STORE_add_cert. */ ASIO_DECL ASIO_SYNC_OP_VOID add_certificate_authority( const const_buffer& ca, asio::error_code& ec); /// Configures the context to use the default directories for finding /// certification authority certificates. /** * This function specifies that the context should use the default, * system-dependent directories for locating certification authority * certificates. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_default_verify_paths. */ ASIO_DECL void set_default_verify_paths(); /// Configures the context to use the default directories for finding /// certification authority certificates. /** * This function specifies that the context should use the default, * system-dependent directories for locating certification authority * certificates. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_default_verify_paths. */ ASIO_DECL ASIO_SYNC_OP_VOID set_default_verify_paths( asio::error_code& ec); /// Add a directory containing certificate authority files to be used for /// performing verification. /** * This function is used to specify the name of a directory containing * certification authority certificates. Each file in the directory must * contain a single certificate. The files must be named using the subject * name's hash and an extension of ".0". * * @param path The name of a directory containing the certificates. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_load_verify_locations. */ ASIO_DECL void add_verify_path(const std::string& path); /// Add a directory containing certificate authority files to be used for /// performing verification. /** * This function is used to specify the name of a directory containing * certification authority certificates. Each file in the directory must * contain a single certificate. The files must be named using the subject * name's hash and an extension of ".0". * * @param path The name of a directory containing the certificates. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_load_verify_locations. */ ASIO_DECL ASIO_SYNC_OP_VOID add_verify_path( const std::string& path, asio::error_code& ec); /// Use a certificate from a memory buffer. /** * This function is used to load a certificate into the context from a buffer. * * @param certificate The buffer containing the certificate. * * @param format The certificate format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1. */ ASIO_DECL void use_certificate( const const_buffer& certificate, file_format format); /// Use a certificate from a memory buffer. /** * This function is used to load a certificate into the context from a buffer. * * @param certificate The buffer containing the certificate. * * @param format The certificate format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_certificate or SSL_CTX_use_certificate_ASN1. */ ASIO_DECL ASIO_SYNC_OP_VOID use_certificate( const const_buffer& certificate, file_format format, asio::error_code& ec); /// Use a certificate from a file. /** * This function is used to load a certificate into the context from a file. * * @param filename The name of the file containing the certificate. * * @param format The file format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_certificate_file. */ ASIO_DECL void use_certificate_file( const std::string& filename, file_format format); /// Use a certificate from a file. /** * This function is used to load a certificate into the context from a file. * * @param filename The name of the file containing the certificate. * * @param format The file format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_certificate_file. */ ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_file( const std::string& filename, file_format format, asio::error_code& ec); /// Use a certificate chain from a memory buffer. /** * This function is used to load a certificate chain into the context from a * buffer. * * @param chain The buffer containing the certificate chain. The certificate * chain must use the PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert. */ ASIO_DECL void use_certificate_chain(const const_buffer& chain); /// Use a certificate chain from a memory buffer. /** * This function is used to load a certificate chain into the context from a * buffer. * * @param chain The buffer containing the certificate chain. The certificate * chain must use the PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_certificate and SSL_CTX_add_extra_chain_cert. */ ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_chain( const const_buffer& chain, asio::error_code& ec); /// Use a certificate chain from a file. /** * This function is used to load a certificate chain into the context from a * file. * * @param filename The name of the file containing the certificate. The file * must use the PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_certificate_chain_file. */ ASIO_DECL void use_certificate_chain_file(const std::string& filename); /// Use a certificate chain from a file. /** * This function is used to load a certificate chain into the context from a * file. * * @param filename The name of the file containing the certificate. The file * must use the PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_certificate_chain_file. */ ASIO_DECL ASIO_SYNC_OP_VOID use_certificate_chain_file( const std::string& filename, asio::error_code& ec); /// Use a private key from a memory buffer. /** * This function is used to load a private key into the context from a buffer. * * @param private_key The buffer containing the private key. * * @param format The private key format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1. */ ASIO_DECL void use_private_key( const const_buffer& private_key, file_format format); /// Use a private key from a memory buffer. /** * This function is used to load a private key into the context from a buffer. * * @param private_key The buffer containing the private key. * * @param format The private key format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_PrivateKey or SSL_CTX_use_PrivateKey_ASN1. */ ASIO_DECL ASIO_SYNC_OP_VOID use_private_key( const const_buffer& private_key, file_format format, asio::error_code& ec); /// Use a private key from a file. /** * This function is used to load a private key into the context from a file. * * @param filename The name of the file containing the private key. * * @param format The file format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_PrivateKey_file. */ ASIO_DECL void use_private_key_file( const std::string& filename, file_format format); /// Use a private key from a file. /** * This function is used to load a private key into the context from a file. * * @param filename The name of the file containing the private key. * * @param format The file format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_PrivateKey_file. */ ASIO_DECL ASIO_SYNC_OP_VOID use_private_key_file( const std::string& filename, file_format format, asio::error_code& ec); /// Use an RSA private key from a memory buffer. /** * This function is used to load an RSA private key into the context from a * buffer. * * @param private_key The buffer containing the RSA private key. * * @param format The private key format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1. */ ASIO_DECL void use_rsa_private_key( const const_buffer& private_key, file_format format); /// Use an RSA private key from a memory buffer. /** * This function is used to load an RSA private key into the context from a * buffer. * * @param private_key The buffer containing the RSA private key. * * @param format The private key format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_RSAPrivateKey or SSL_CTX_use_RSAPrivateKey_ASN1. */ ASIO_DECL ASIO_SYNC_OP_VOID use_rsa_private_key( const const_buffer& private_key, file_format format, asio::error_code& ec); /// Use an RSA private key from a file. /** * This function is used to load an RSA private key into the context from a * file. * * @param filename The name of the file containing the RSA private key. * * @param format The file format (ASN.1 or PEM). * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_use_RSAPrivateKey_file. */ ASIO_DECL void use_rsa_private_key_file( const std::string& filename, file_format format); /// Use an RSA private key from a file. /** * This function is used to load an RSA private key into the context from a * file. * * @param filename The name of the file containing the RSA private key. * * @param format The file format (ASN.1 or PEM). * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_use_RSAPrivateKey_file. */ ASIO_DECL ASIO_SYNC_OP_VOID use_rsa_private_key_file( const std::string& filename, file_format format, asio::error_code& ec); /// Use the specified memory buffer to obtain the temporary Diffie-Hellman /// parameters. /** * This function is used to load Diffie-Hellman parameters into the context * from a buffer. * * @param dh The memory buffer containing the Diffie-Hellman parameters. The * buffer must use the PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_tmp_dh. */ ASIO_DECL void use_tmp_dh(const const_buffer& dh); /// Use the specified memory buffer to obtain the temporary Diffie-Hellman /// parameters. /** * This function is used to load Diffie-Hellman parameters into the context * from a buffer. * * @param dh The memory buffer containing the Diffie-Hellman parameters. The * buffer must use the PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_tmp_dh. */ ASIO_DECL ASIO_SYNC_OP_VOID use_tmp_dh( const const_buffer& dh, asio::error_code& ec); /// Use the specified file to obtain the temporary Diffie-Hellman parameters. /** * This function is used to load Diffie-Hellman parameters into the context * from a file. * * @param filename The name of the file containing the Diffie-Hellman * parameters. The file must use the PEM format. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_tmp_dh. */ ASIO_DECL void use_tmp_dh_file(const std::string& filename); /// Use the specified file to obtain the temporary Diffie-Hellman parameters. /** * This function is used to load Diffie-Hellman parameters into the context * from a file. * * @param filename The name of the file containing the Diffie-Hellman * parameters. The file must use the PEM format. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_tmp_dh. */ ASIO_DECL ASIO_SYNC_OP_VOID use_tmp_dh_file( const std::string& filename, asio::error_code& ec); /// Set the password callback. /** * This function is used to specify a callback function to obtain password * information about an encrypted key in PEM format. * * @param callback The function object to be used for obtaining the password. * The function signature of the handler must be: * @code std::string password_callback( * std::size_t max_length, // The maximum size for a password. * password_purpose purpose // Whether password is for reading or writing. * ); @endcode * The return value of the callback is a string containing the password. * * @throws asio::system_error Thrown on failure. * * @note Calls @c SSL_CTX_set_default_passwd_cb. */ template <typename PasswordCallback> void set_password_callback(PasswordCallback callback); /// Set the password callback. /** * This function is used to specify a callback function to obtain password * information about an encrypted key in PEM format. * * @param callback The function object to be used for obtaining the password. * The function signature of the handler must be: * @code std::string password_callback( * std::size_t max_length, // The maximum size for a password. * password_purpose purpose // Whether password is for reading or writing. * ); @endcode * The return value of the callback is a string containing the password. * * @param ec Set to indicate what error occurred, if any. * * @note Calls @c SSL_CTX_set_default_passwd_cb. */ template <typename PasswordCallback> ASIO_SYNC_OP_VOID set_password_callback(PasswordCallback callback, asio::error_code& ec); private: struct bio_cleanup; struct x509_cleanup; struct evp_pkey_cleanup; struct rsa_cleanup; struct dh_cleanup; // Helper function used to set a peer certificate verification callback. ASIO_DECL ASIO_SYNC_OP_VOID do_set_verify_callback( detail::verify_callback_base* callback, asio::error_code& ec); // Callback used when the SSL implementation wants to verify a certificate. ASIO_DECL static int verify_callback_function( int preverified, X509_STORE_CTX* ctx); // Helper function used to set a password callback. ASIO_DECL ASIO_SYNC_OP_VOID do_set_password_callback( detail::password_callback_base* callback, asio::error_code& ec); // Callback used when the SSL implementation wants a password. ASIO_DECL static int password_callback_function( char* buf, int size, int purpose, void* data); // Helper function to set the temporary Diffie-Hellman parameters from a BIO. ASIO_DECL ASIO_SYNC_OP_VOID do_use_tmp_dh( BIO* bio, asio::error_code& ec); // Helper function to make a BIO from a memory buffer. ASIO_DECL BIO* make_buffer_bio(const const_buffer& b); // Translate an SSL error into an error code. ASIO_DECL static asio::error_code translate_error(long error); // The underlying native implementation. native_handle_type handle_; // Ensure openssl is initialised. asio::ssl::detail::openssl_init<> init_; }; } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/ssl/impl/context.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/impl/context.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SSL_CONTEXT_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/verify_callback.hpp
// // ssl/detail/verify_callback.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 ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP #define ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/verify_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class verify_callback_base { public: virtual ~verify_callback_base() { } virtual bool call(bool preverified, verify_context& ctx) = 0; }; template <typename VerifyCallback> class verify_callback : public verify_callback_base { public: explicit verify_callback(VerifyCallback callback) : callback_(callback) { } virtual bool call(bool preverified, verify_context& ctx) { return callback_(preverified, ctx); } private: VerifyCallback callback_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_VERIFY_CALLBACK_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/shutdown_op.hpp
// // ssl/detail/shutdown_op.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 ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP #define ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class shutdown_op { public: static constexpr const char* tracking_name() { return "ssl::stream<>::async_shutdown"; } engine::want operator()(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred) const { bytes_transferred = 0; return eng.shutdown(ec); } template <typename Handler> void call_handler(Handler& handler, const asio::error_code& ec, const std::size_t&) const { if (ec == asio::error::eof) { // The engine only generates an eof when the shutdown notification has // been received from the peer. This indicates that the shutdown has // completed successfully, and thus need not be passed on to the handler. static_cast<Handler&&>(handler)(asio::error_code()); } else { static_cast<Handler&&>(handler)(ec); } } }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_SHUTDOWN_OP_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/password_callback.hpp
// // ssl/detail/password_callback.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 ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP #define ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include <string> #include "asio/ssl/context_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class password_callback_base { public: virtual ~password_callback_base() { } virtual std::string call(std::size_t size, context_base::password_purpose purpose) = 0; }; template <typename PasswordCallback> class password_callback : public password_callback_base { public: explicit password_callback(PasswordCallback callback) : callback_(callback) { } virtual std::string call(std::size_t size, context_base::password_purpose purpose) { return callback_(size, purpose); } private: PasswordCallback callback_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_PASSWORD_CALLBACK_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/openssl_init.hpp
// // ssl/detail/openssl_init.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 ASIO_SSL_DETAIL_OPENSSL_INIT_HPP #define ASIO_SSL_DETAIL_OPENSSL_INIT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstring> #include "asio/detail/memory.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class openssl_init_base : private noncopyable { protected: // Class that performs the actual initialisation. class do_init; // Helper function to manage a do_init singleton. The static instance of the // openssl_init object ensures that this function is always called before // main, and therefore before any other threads can get started. The do_init // instance must be static in this function to ensure that it gets // initialised before any other global objects try to use it. ASIO_DECL static asio::detail::shared_ptr<do_init> instance(); #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) // Get an empty stack of compression methods, to be used when disabling // compression. ASIO_DECL static STACK_OF(SSL_COMP)* get_null_compression_methods(); #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) }; template <bool Do_Init = true> class openssl_init : private openssl_init_base { public: // Constructor. openssl_init() : ref_(instance()) { using namespace std; // For memmove. // Ensure openssl_init::instance_ is linked in. openssl_init* tmp = &instance_; memmove(&tmp, &tmp, sizeof(openssl_init*)); } // Destructor. ~openssl_init() { } #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) using openssl_init_base::get_null_compression_methods; #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) private: // Instance to force initialisation of openssl at global scope. static openssl_init instance_; // Reference to singleton do_init object to ensure that openssl does not get // cleaned up until the last user has finished with it. asio::detail::shared_ptr<do_init> ref_; }; template <bool Do_Init> openssl_init<Do_Init> openssl_init<Do_Init>::instance_; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/detail/impl/openssl_init.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SSL_DETAIL_OPENSSL_INIT_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/handshake_op.hpp
// // ssl/detail/handshake_op.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 ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP #define ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class handshake_op { public: static constexpr const char* tracking_name() { return "ssl::stream<>::async_handshake"; } handshake_op(stream_base::handshake_type type) : type_(type) { } engine::want operator()(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred) const { bytes_transferred = 0; return eng.handshake(type_, ec); } template <typename Handler> void call_handler(Handler& handler, const asio::error_code& ec, const std::size_t&) const { static_cast<Handler&&>(handler)(ec); } private: stream_base::handshake_type type_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_HANDSHAKE_OP_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/openssl_types.hpp
// // ssl/detail/openssl_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 ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP #define ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/socket_types.hpp" #if defined(ASIO_USE_WOLFSSL) # include <wolfssl/options.h> #endif // defined(ASIO_USE_WOLFSSL) #include <openssl/conf.h> #include <openssl/ssl.h> #if !defined(OPENSSL_NO_ENGINE) # include <openssl/engine.h> #endif // !defined(OPENSSL_NO_ENGINE) #include <openssl/dh.h> #include <openssl/err.h> #include <openssl/rsa.h> #include <openssl/x509.h> #include <openssl/x509v3.h> #endif // ASIO_SSL_DETAIL_OPENSSL_TYPES_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/stream_core.hpp
// // ssl/detail/stream_core.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 ASIO_SSL_DETAIL_STREAM_CORE_HPP #define ASIO_SSL_DETAIL_STREAM_CORE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_BOOST_DATE_TIME) # include "asio/deadline_timer.hpp" #else // defined(ASIO_HAS_BOOST_DATE_TIME) # include "asio/steady_timer.hpp" #endif // defined(ASIO_HAS_BOOST_DATE_TIME) #include "asio/ssl/detail/engine.hpp" #include "asio/buffer.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { struct stream_core { // According to the OpenSSL documentation, this is the buffer size that is // sufficient to hold the largest possible TLS record. enum { max_tls_record_size = 17 * 1024 }; template <typename Executor> stream_core(SSL_CTX* context, const Executor& ex) : engine_(context), pending_read_(ex), pending_write_(ex), output_buffer_space_(max_tls_record_size), output_buffer_(asio::buffer(output_buffer_space_)), input_buffer_space_(max_tls_record_size), input_buffer_(asio::buffer(input_buffer_space_)) { pending_read_.expires_at(neg_infin()); pending_write_.expires_at(neg_infin()); } template <typename Executor> stream_core(SSL* ssl_impl, const Executor& ex) : engine_(ssl_impl), pending_read_(ex), pending_write_(ex), output_buffer_space_(max_tls_record_size), output_buffer_(asio::buffer(output_buffer_space_)), input_buffer_space_(max_tls_record_size), input_buffer_(asio::buffer(input_buffer_space_)) { pending_read_.expires_at(neg_infin()); pending_write_.expires_at(neg_infin()); } stream_core(stream_core&& other) : engine_(static_cast<engine&&>(other.engine_)), #if defined(ASIO_HAS_BOOST_DATE_TIME) pending_read_( static_cast<asio::deadline_timer&&>( other.pending_read_)), pending_write_( static_cast<asio::deadline_timer&&>( other.pending_write_)), #else // defined(ASIO_HAS_BOOST_DATE_TIME) pending_read_( static_cast<asio::steady_timer&&>( other.pending_read_)), pending_write_( static_cast<asio::steady_timer&&>( other.pending_write_)), #endif // defined(ASIO_HAS_BOOST_DATE_TIME) output_buffer_space_( static_cast<std::vector<unsigned char>&&>( other.output_buffer_space_)), output_buffer_(other.output_buffer_), input_buffer_space_( static_cast<std::vector<unsigned char>&&>( other.input_buffer_space_)), input_buffer_(other.input_buffer_), input_(other.input_) { other.output_buffer_ = asio::mutable_buffer(0, 0); other.input_buffer_ = asio::mutable_buffer(0, 0); other.input_ = asio::const_buffer(0, 0); } ~stream_core() { } stream_core& operator=(stream_core&& other) { if (this != &other) { engine_ = static_cast<engine&&>(other.engine_); #if defined(ASIO_HAS_BOOST_DATE_TIME) pending_read_ = static_cast<asio::deadline_timer&&>( other.pending_read_); pending_write_ = static_cast<asio::deadline_timer&&>( other.pending_write_); #else // defined(ASIO_HAS_BOOST_DATE_TIME) pending_read_ = static_cast<asio::steady_timer&&>( other.pending_read_); pending_write_ = static_cast<asio::steady_timer&&>( other.pending_write_); #endif // defined(ASIO_HAS_BOOST_DATE_TIME) output_buffer_space_ = static_cast<std::vector<unsigned char>&&>( other.output_buffer_space_); output_buffer_ = other.output_buffer_; input_buffer_space_ = static_cast<std::vector<unsigned char>&&>( other.input_buffer_space_); input_buffer_ = other.input_buffer_; input_ = other.input_; other.output_buffer_ = asio::mutable_buffer(0, 0); other.input_buffer_ = asio::mutable_buffer(0, 0); other.input_ = asio::const_buffer(0, 0); } return *this; } // The SSL engine. engine engine_; #if defined(ASIO_HAS_BOOST_DATE_TIME) // Timer used for storing queued read operations. asio::deadline_timer pending_read_; // Timer used for storing queued write operations. asio::deadline_timer pending_write_; // Helper function for obtaining a time value that always fires. static asio::deadline_timer::time_type neg_infin() { return boost::posix_time::neg_infin; } // Helper function for obtaining a time value that never fires. static asio::deadline_timer::time_type pos_infin() { return boost::posix_time::pos_infin; } // Helper function to get a timer's expiry time. static asio::deadline_timer::time_type expiry( const asio::deadline_timer& timer) { return timer.expires_at(); } #else // defined(ASIO_HAS_BOOST_DATE_TIME) // Timer used for storing queued read operations. asio::steady_timer pending_read_; // Timer used for storing queued write operations. asio::steady_timer pending_write_; // Helper function for obtaining a time value that always fires. static asio::steady_timer::time_point neg_infin() { return (asio::steady_timer::time_point::min)(); } // Helper function for obtaining a time value that never fires. static asio::steady_timer::time_point pos_infin() { return (asio::steady_timer::time_point::max)(); } // Helper function to get a timer's expiry time. static asio::steady_timer::time_point expiry( const asio::steady_timer& timer) { return timer.expiry(); } #endif // defined(ASIO_HAS_BOOST_DATE_TIME) // Buffer space used to prepare output intended for the transport. std::vector<unsigned char> output_buffer_space_; // A buffer that may be used to prepare output intended for the transport. asio::mutable_buffer output_buffer_; // Buffer space used to read input intended for the engine. std::vector<unsigned char> input_buffer_space_; // A buffer that may be used to read input intended for the engine. asio::mutable_buffer input_buffer_; // The buffer pointing to the engine's unconsumed input. asio::const_buffer input_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_STREAM_CORE_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/read_op.hpp
// // ssl/detail/read_op.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 ASIO_SSL_DETAIL_READ_OP_HPP #define ASIO_SSL_DETAIL_READ_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/buffer_sequence_adapter.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { template <typename MutableBufferSequence> class read_op { public: static constexpr const char* tracking_name() { return "ssl::stream<>::async_read_some"; } read_op(const MutableBufferSequence& buffers) : buffers_(buffers) { } engine::want operator()(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred) const { asio::mutable_buffer buffer = asio::detail::buffer_sequence_adapter<asio::mutable_buffer, MutableBufferSequence>::first(buffers_); return eng.read(buffer, ec, bytes_transferred); } template <typename Handler> void call_handler(Handler& handler, const asio::error_code& ec, const std::size_t& bytes_transferred) const { static_cast<Handler&&>(handler)(ec, bytes_transferred); } private: MutableBufferSequence buffers_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_READ_OP_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/io.hpp
// // ssl/detail/io.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 ASIO_SSL_DETAIL_IO_HPP #define ASIO_SSL_DETAIL_IO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/base_from_cancellation_state.hpp" #include "asio/detail/handler_tracking.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/ssl/detail/stream_core.hpp" #include "asio/write.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { template <typename Stream, typename Operation> std::size_t io(Stream& next_layer, stream_core& core, const Operation& op, asio::error_code& ec) { asio::error_code io_ec; std::size_t bytes_transferred = 0; do switch (op(core.engine_, ec, bytes_transferred)) { case engine::want_input_and_retry: // If the input buffer is empty then we need to read some more data from // the underlying transport. if (core.input_.size() == 0) { core.input_ = asio::buffer(core.input_buffer_, next_layer.read_some(core.input_buffer_, io_ec)); if (!ec) ec = io_ec; } // Pass the new input data to the engine. core.input_ = core.engine_.put_input(core.input_); // Try the operation again. continue; case engine::want_output_and_retry: // Get output data from the engine and write it to the underlying // transport. asio::write(next_layer, core.engine_.get_output(core.output_buffer_), io_ec); if (!ec) ec = io_ec; // Try the operation again. continue; case engine::want_output: // Get output data from the engine and write it to the underlying // transport. asio::write(next_layer, core.engine_.get_output(core.output_buffer_), io_ec); if (!ec) ec = io_ec; // Operation is complete. Return result to caller. core.engine_.map_error_code(ec); return bytes_transferred; default: // Operation is complete. Return result to caller. core.engine_.map_error_code(ec); return bytes_transferred; } while (!ec); // Operation failed. Return result to caller. core.engine_.map_error_code(ec); return 0; } template <typename Stream, typename Operation, typename Handler> class io_op : public asio::detail::base_from_cancellation_state<Handler> { public: io_op(Stream& next_layer, stream_core& core, const Operation& op, Handler& handler) : asio::detail::base_from_cancellation_state<Handler>(handler), next_layer_(next_layer), core_(core), op_(op), start_(0), want_(engine::want_nothing), bytes_transferred_(0), handler_(static_cast<Handler&&>(handler)) { } io_op(const io_op& other) : asio::detail::base_from_cancellation_state<Handler>(other), next_layer_(other.next_layer_), core_(other.core_), op_(other.op_), start_(other.start_), want_(other.want_), ec_(other.ec_), bytes_transferred_(other.bytes_transferred_), handler_(other.handler_) { } io_op(io_op&& other) : asio::detail::base_from_cancellation_state<Handler>( static_cast< asio::detail::base_from_cancellation_state<Handler>&&>(other)), next_layer_(other.next_layer_), core_(other.core_), op_(static_cast<Operation&&>(other.op_)), start_(other.start_), want_(other.want_), ec_(other.ec_), bytes_transferred_(other.bytes_transferred_), handler_(static_cast<Handler&&>(other.handler_)) { } void operator()(asio::error_code ec, std::size_t bytes_transferred = ~std::size_t(0), int start = 0) { switch (start_ = start) { case 1: // Called after at least one async operation. do { switch (want_ = op_(core_.engine_, ec_, bytes_transferred_)) { case engine::want_input_and_retry: // If the input buffer already has data in it we can pass it to the // engine and then retry the operation immediately. if (core_.input_.size() != 0) { core_.input_ = core_.engine_.put_input(core_.input_); continue; } // The engine wants more data to be read from input. However, we // cannot allow more than one read operation at a time on the // underlying transport. The pending_read_ timer's expiry is set to // pos_infin if a read is in progress, and neg_infin otherwise. if (core_.expiry(core_.pending_read_) == core_.neg_infin()) { // Prevent other read operations from being started. core_.pending_read_.expires_at(core_.pos_infin()); ASIO_HANDLER_LOCATION(( __FILE__, __LINE__, Operation::tracking_name())); // Start reading some data from the underlying transport. next_layer_.async_read_some( asio::buffer(core_.input_buffer_), static_cast<io_op&&>(*this)); } else { ASIO_HANDLER_LOCATION(( __FILE__, __LINE__, Operation::tracking_name())); // Wait until the current read operation completes. core_.pending_read_.async_wait(static_cast<io_op&&>(*this)); } // Yield control until asynchronous operation completes. Control // resumes at the "default:" label below. return; case engine::want_output_and_retry: case engine::want_output: // The engine wants some data to be written to the output. However, we // cannot allow more than one write operation at a time on the // underlying transport. The pending_write_ timer's expiry is set to // pos_infin if a write is in progress, and neg_infin otherwise. if (core_.expiry(core_.pending_write_) == core_.neg_infin()) { // Prevent other write operations from being started. core_.pending_write_.expires_at(core_.pos_infin()); ASIO_HANDLER_LOCATION(( __FILE__, __LINE__, Operation::tracking_name())); // Start writing all the data to the underlying transport. asio::async_write(next_layer_, core_.engine_.get_output(core_.output_buffer_), static_cast<io_op&&>(*this)); } else { ASIO_HANDLER_LOCATION(( __FILE__, __LINE__, Operation::tracking_name())); // Wait until the current write operation completes. core_.pending_write_.async_wait(static_cast<io_op&&>(*this)); } // Yield control until asynchronous operation completes. Control // resumes at the "default:" label below. return; default: // The SSL operation is done and we can invoke the handler, but we // have to keep in mind that this function might be being called from // the async operation's initiating function. In this case we're not // allowed to call the handler directly. Instead, issue a zero-sized // read so the handler runs "as-if" posted using io_context::post(). if (start) { ASIO_HANDLER_LOCATION(( __FILE__, __LINE__, Operation::tracking_name())); next_layer_.async_read_some( asio::buffer(core_.input_buffer_, 0), static_cast<io_op&&>(*this)); // Yield control until asynchronous operation completes. Control // resumes at the "default:" label below. return; } else { // Continue on to run handler directly. break; } } default: if (bytes_transferred == ~std::size_t(0)) bytes_transferred = 0; // Timer cancellation, no data transferred. else if (!ec_) ec_ = ec; switch (want_) { case engine::want_input_and_retry: // Add received data to the engine's input. core_.input_ = asio::buffer( core_.input_buffer_, bytes_transferred); core_.input_ = core_.engine_.put_input(core_.input_); // Release any waiting read operations. core_.pending_read_.expires_at(core_.neg_infin()); // Check for cancellation before continuing. if (this->cancelled() != cancellation_type::none) { ec_ = asio::error::operation_aborted; break; } // Try the operation again. continue; case engine::want_output_and_retry: // Release any waiting write operations. core_.pending_write_.expires_at(core_.neg_infin()); // Check for cancellation before continuing. if (this->cancelled() != cancellation_type::none) { ec_ = asio::error::operation_aborted; break; } // Try the operation again. continue; case engine::want_output: // Release any waiting write operations. core_.pending_write_.expires_at(core_.neg_infin()); // Fall through to call handler. default: // Pass the result to the handler. op_.call_handler(handler_, core_.engine_.map_error_code(ec_), ec_ ? 0 : bytes_transferred_); // Our work here is done. return; } } while (!ec_); // Operation failed. Pass the result to the handler. op_.call_handler(handler_, core_.engine_.map_error_code(ec_), 0); } } //private: Stream& next_layer_; stream_core& core_; Operation op_; int start_; engine::want want_; asio::error_code ec_; std::size_t bytes_transferred_; Handler handler_; }; template <typename Stream, typename Operation, typename Handler> inline bool asio_handler_is_continuation( io_op<Stream, Operation, Handler>* this_handler) { return this_handler->start_ == 0 ? true : asio_handler_cont_helpers::is_continuation(this_handler->handler_); } template <typename Stream, typename Operation, typename Handler> inline void async_io(Stream& next_layer, stream_core& core, const Operation& op, Handler& handler) { io_op<Stream, Operation, Handler>( next_layer, core, op, handler)( asio::error_code(), 0, 1); } } // namespace detail } // namespace ssl template <template <typename, typename> class Associator, typename Stream, typename Operation, typename Handler, typename DefaultCandidate> struct associator<Associator, ssl::detail::io_op<Stream, Operation, Handler>, DefaultCandidate> : Associator<Handler, DefaultCandidate> { static typename Associator<Handler, DefaultCandidate>::type get( const ssl::detail::io_op<Stream, Operation, Handler>& h) noexcept { return Associator<Handler, DefaultCandidate>::get(h.handler_); } static auto get(const ssl::detail::io_op<Stream, Operation, Handler>& h, const DefaultCandidate& c) noexcept -> decltype(Associator<Handler, DefaultCandidate>::get(h.handler_, c)) { return Associator<Handler, DefaultCandidate>::get(h.handler_, c); } }; } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_IO_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/engine.hpp
// // ssl/detail/engine.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 ASIO_SSL_DETAIL_ENGINE_HPP #define ASIO_SSL_DETAIL_ENGINE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/buffer.hpp" #include "asio/detail/static_mutex.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/ssl/detail/verify_callback.hpp" #include "asio/ssl/stream_base.hpp" #include "asio/ssl/verify_mode.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class engine { public: enum want { // Returned by functions to indicate that the engine wants input. The input // buffer should be updated to point to the data. The engine then needs to // be called again to retry the operation. want_input_and_retry = -2, // Returned by functions to indicate that the engine wants to write output. // The output buffer points to the data to be written. The engine then // needs to be called again to retry the operation. want_output_and_retry = -1, // Returned by functions to indicate that the engine doesn't need input or // output. want_nothing = 0, // Returned by functions to indicate that the engine wants to write output. // The output buffer points to the data to be written. After that the // operation is complete, and the engine does not need to be called again. want_output = 1 }; // Construct a new engine for the specified context. ASIO_DECL explicit engine(SSL_CTX* context); // Construct a new engine for an existing native SSL implementation. ASIO_DECL explicit engine(SSL* ssl_impl); // Move construct from another engine. ASIO_DECL engine(engine&& other) noexcept; // Destructor. ASIO_DECL ~engine(); // Move assign from another engine. ASIO_DECL engine& operator=(engine&& other) noexcept; // Get the underlying implementation in the native type. ASIO_DECL SSL* native_handle(); // Set the peer verification mode. ASIO_DECL asio::error_code set_verify_mode( verify_mode v, asio::error_code& ec); // Set the peer verification depth. ASIO_DECL asio::error_code set_verify_depth( int depth, asio::error_code& ec); // Set a peer certificate verification callback. ASIO_DECL asio::error_code set_verify_callback( verify_callback_base* callback, asio::error_code& ec); // Perform an SSL handshake using either SSL_connect (client-side) or // SSL_accept (server-side). ASIO_DECL want handshake( stream_base::handshake_type type, asio::error_code& ec); // Perform a graceful shutdown of the SSL session. ASIO_DECL want shutdown(asio::error_code& ec); // Write bytes to the SSL session. ASIO_DECL want write(const asio::const_buffer& data, asio::error_code& ec, std::size_t& bytes_transferred); // Read bytes from the SSL session. ASIO_DECL want read(const asio::mutable_buffer& data, asio::error_code& ec, std::size_t& bytes_transferred); // Get output data to be written to the transport. ASIO_DECL asio::mutable_buffer get_output( const asio::mutable_buffer& data); // Put input data that was read from the transport. ASIO_DECL asio::const_buffer put_input( const asio::const_buffer& data); // Map an error::eof code returned by the underlying transport according to // the type and state of the SSL session. Returns a const reference to the // error code object, suitable for passing to a completion handler. ASIO_DECL const asio::error_code& map_error_code( asio::error_code& ec) const; private: // Disallow copying and assignment. engine(const engine&); engine& operator=(const engine&); // Callback used when the SSL implementation wants to verify a certificate. ASIO_DECL static int verify_callback_function( int preverified, X509_STORE_CTX* ctx); #if (OPENSSL_VERSION_NUMBER < 0x10000000L) // The SSL_accept function may not be thread safe. This mutex is used to // protect all calls to the SSL_accept function. ASIO_DECL static asio::detail::static_mutex& accept_mutex(); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) // Perform one operation. Returns >= 0 on success or error, want_read if the // operation needs more input, or want_write if it needs to write some output // before the operation can complete. ASIO_DECL want perform(int (engine::* op)(void*, std::size_t), void* data, std::size_t length, asio::error_code& ec, std::size_t* bytes_transferred); // Adapt the SSL_accept function to the signature needed for perform(). ASIO_DECL int do_accept(void*, std::size_t); // Adapt the SSL_connect function to the signature needed for perform(). ASIO_DECL int do_connect(void*, std::size_t); // Adapt the SSL_shutdown function to the signature needed for perform(). ASIO_DECL int do_shutdown(void*, std::size_t); // Adapt the SSL_read function to the signature needed for perform(). ASIO_DECL int do_read(void* data, std::size_t length); // Adapt the SSL_write function to the signature needed for perform(). ASIO_DECL int do_write(void* data, std::size_t length); SSL* ssl_; BIO* ext_bio_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/ssl/detail/impl/engine.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_SSL_DETAIL_ENGINE_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/buffered_handshake_op.hpp
// // ssl/detail/buffered_handshake_op.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 ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP #define ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { template <typename ConstBufferSequence> class buffered_handshake_op { public: static constexpr const char* tracking_name() { return "ssl::stream<>::async_buffered_handshake"; } buffered_handshake_op(stream_base::handshake_type type, const ConstBufferSequence& buffers) : type_(type), buffers_(buffers), total_buffer_size_(asio::buffer_size(buffers_)) { } engine::want operator()(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred) const { return this->process(eng, ec, bytes_transferred, asio::buffer_sequence_begin(buffers_), asio::buffer_sequence_end(buffers_)); } template <typename Handler> void call_handler(Handler& handler, const asio::error_code& ec, const std::size_t& bytes_transferred) const { static_cast<Handler&&>(handler)(ec, bytes_transferred); } private: template <typename Iterator> engine::want process(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred, Iterator begin, Iterator end) const { Iterator iter = begin; std::size_t accumulated_size = 0; for (;;) { engine::want want = eng.handshake(type_, ec); if (want != engine::want_input_and_retry || bytes_transferred == total_buffer_size_) return want; // Find the next buffer piece to be fed to the engine. while (iter != end) { const_buffer buffer(*iter); // Skip over any buffers which have already been consumed by the engine. if (bytes_transferred >= accumulated_size + buffer.size()) { accumulated_size += buffer.size(); ++iter; continue; } // The current buffer may have been partially consumed by the engine on // a previous iteration. If so, adjust the buffer to point to the // unused portion. if (bytes_transferred > accumulated_size) buffer = buffer + (bytes_transferred - accumulated_size); // Pass the buffer to the engine, and update the bytes transferred to // reflect the total number of bytes consumed so far. bytes_transferred += buffer.size(); buffer = eng.put_input(buffer); bytes_transferred -= buffer.size(); break; } } } stream_base::handshake_type type_; ConstBufferSequence buffers_; std::size_t total_buffer_size_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_BUFFERED_HANDSHAKE_OP_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/detail/write_op.hpp
// // ssl/detail/write_op.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 ASIO_SSL_DETAIL_WRITE_OP_HPP #define ASIO_SSL_DETAIL_WRITE_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/buffer_sequence_adapter.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { template <typename ConstBufferSequence> class write_op { public: static constexpr const char* tracking_name() { return "ssl::stream<>::async_write_some"; } write_op(const ConstBufferSequence& buffers) : buffers_(buffers) { } engine::want operator()(engine& eng, asio::error_code& ec, std::size_t& bytes_transferred) const { unsigned char storage[ asio::detail::buffer_sequence_adapter<asio::const_buffer, ConstBufferSequence>::linearisation_storage_size]; asio::const_buffer buffer = asio::detail::buffer_sequence_adapter<asio::const_buffer, ConstBufferSequence>::linearise(buffers_, asio::buffer(storage)); return eng.write(buffer, ec, bytes_transferred); } template <typename Handler> void call_handler(Handler& handler, const asio::error_code& ec, const std::size_t& bytes_transferred) const { static_cast<Handler&&>(handler)(ec, bytes_transferred); } private: ConstBufferSequence buffers_; }; } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_WRITE_OP_HPP
0
repos/asio/asio/include/asio/ssl/detail
repos/asio/asio/include/asio/ssl/detail/impl/engine.ipp
// // ssl/detail/impl/engine.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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 ASIO_SSL_DETAIL_IMPL_ENGINE_IPP #define ASIO_SSL_DETAIL_IMPL_ENGINE_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/ssl/detail/engine.hpp" #include "asio/ssl/error.hpp" #include "asio/ssl/verify_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { engine::engine(SSL_CTX* context) : ssl_(::SSL_new(context)) { if (!ssl_) { asio::error_code ec( static_cast<int>(::ERR_get_error()), asio::error::get_ssl_category()); asio::detail::throw_error(ec, "engine"); } #if (OPENSSL_VERSION_NUMBER < 0x10000000L) accept_mutex().init(); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) ::SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE); ::SSL_set_mode(ssl_, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if defined(SSL_MODE_RELEASE_BUFFERS) ::SSL_set_mode(ssl_, SSL_MODE_RELEASE_BUFFERS); #endif // defined(SSL_MODE_RELEASE_BUFFERS) ::BIO* int_bio = 0; ::BIO_new_bio_pair(&int_bio, 0, &ext_bio_, 0); ::SSL_set_bio(ssl_, int_bio, int_bio); } engine::engine(SSL* ssl_impl) : ssl_(ssl_impl) { #if (OPENSSL_VERSION_NUMBER < 0x10000000L) accept_mutex().init(); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) ::SSL_set_mode(ssl_, SSL_MODE_ENABLE_PARTIAL_WRITE); ::SSL_set_mode(ssl_, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER); #if defined(SSL_MODE_RELEASE_BUFFERS) ::SSL_set_mode(ssl_, SSL_MODE_RELEASE_BUFFERS); #endif // defined(SSL_MODE_RELEASE_BUFFERS) ::BIO* int_bio = 0; ::BIO_new_bio_pair(&int_bio, 0, &ext_bio_, 0); ::SSL_set_bio(ssl_, int_bio, int_bio); } engine::engine(engine&& other) noexcept : ssl_(other.ssl_), ext_bio_(other.ext_bio_) { other.ssl_ = 0; other.ext_bio_ = 0; } engine::~engine() { if (ssl_ && SSL_get_app_data(ssl_)) { delete static_cast<verify_callback_base*>(SSL_get_app_data(ssl_)); SSL_set_app_data(ssl_, 0); } if (ext_bio_) ::BIO_free(ext_bio_); if (ssl_) ::SSL_free(ssl_); } engine& engine::operator=(engine&& other) noexcept { if (this != &other) { ssl_ = other.ssl_; ext_bio_ = other.ext_bio_; other.ssl_ = 0; other.ext_bio_ = 0; } return *this; } SSL* engine::native_handle() { return ssl_; } asio::error_code engine::set_verify_mode( verify_mode v, asio::error_code& ec) { ::SSL_set_verify(ssl_, v, ::SSL_get_verify_callback(ssl_)); ec = asio::error_code(); return ec; } asio::error_code engine::set_verify_depth( int depth, asio::error_code& ec) { ::SSL_set_verify_depth(ssl_, depth); ec = asio::error_code(); return ec; } asio::error_code engine::set_verify_callback( verify_callback_base* callback, asio::error_code& ec) { if (SSL_get_app_data(ssl_)) delete static_cast<verify_callback_base*>(SSL_get_app_data(ssl_)); SSL_set_app_data(ssl_, callback); ::SSL_set_verify(ssl_, ::SSL_get_verify_mode(ssl_), &engine::verify_callback_function); ec = asio::error_code(); return ec; } int engine::verify_callback_function(int preverified, X509_STORE_CTX* ctx) { if (ctx) { if (SSL* ssl = static_cast<SSL*>( ::X509_STORE_CTX_get_ex_data( ctx, ::SSL_get_ex_data_X509_STORE_CTX_idx()))) { if (SSL_get_app_data(ssl)) { verify_callback_base* callback = static_cast<verify_callback_base*>( SSL_get_app_data(ssl)); verify_context verify_ctx(ctx); return callback->call(preverified != 0, verify_ctx) ? 1 : 0; } } } return 0; } engine::want engine::handshake( stream_base::handshake_type type, asio::error_code& ec) { return perform((type == asio::ssl::stream_base::client) ? &engine::do_connect : &engine::do_accept, 0, 0, ec, 0); } engine::want engine::shutdown(asio::error_code& ec) { return perform(&engine::do_shutdown, 0, 0, ec, 0); } engine::want engine::write(const asio::const_buffer& data, asio::error_code& ec, std::size_t& bytes_transferred) { if (data.size() == 0) { ec = asio::error_code(); return engine::want_nothing; } return perform(&engine::do_write, const_cast<void*>(data.data()), data.size(), ec, &bytes_transferred); } engine::want engine::read(const asio::mutable_buffer& data, asio::error_code& ec, std::size_t& bytes_transferred) { if (data.size() == 0) { ec = asio::error_code(); return engine::want_nothing; } return perform(&engine::do_read, data.data(), data.size(), ec, &bytes_transferred); } asio::mutable_buffer engine::get_output( const asio::mutable_buffer& data) { int length = ::BIO_read(ext_bio_, data.data(), static_cast<int>(data.size())); return asio::buffer(data, length > 0 ? static_cast<std::size_t>(length) : 0); } asio::const_buffer engine::put_input( const asio::const_buffer& data) { int length = ::BIO_write(ext_bio_, data.data(), static_cast<int>(data.size())); return asio::buffer(data + (length > 0 ? static_cast<std::size_t>(length) : 0)); } const asio::error_code& engine::map_error_code( asio::error_code& ec) const { // We only want to map the error::eof code. if (ec != asio::error::eof) return ec; // If there's data yet to be read, it's an error. if (BIO_wpending(ext_bio_)) { ec = asio::ssl::error::stream_truncated; return ec; } // SSL v2 doesn't provide a protocol-level shutdown, so an eof on the // underlying transport is passed through. #if (OPENSSL_VERSION_NUMBER < 0x10100000L) if (SSL_version(ssl_) == SSL2_VERSION) return ec; #endif // (OPENSSL_VERSION_NUMBER < 0x10100000L) // Otherwise, the peer should have negotiated a proper shutdown. if ((::SSL_get_shutdown(ssl_) & SSL_RECEIVED_SHUTDOWN) == 0) { ec = asio::ssl::error::stream_truncated; } return ec; } #if (OPENSSL_VERSION_NUMBER < 0x10000000L) asio::detail::static_mutex& engine::accept_mutex() { static asio::detail::static_mutex mutex = ASIO_STATIC_MUTEX_INIT; return mutex; } #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) engine::want engine::perform(int (engine::* op)(void*, std::size_t), void* data, std::size_t length, asio::error_code& ec, std::size_t* bytes_transferred) { std::size_t pending_output_before = ::BIO_ctrl_pending(ext_bio_); ::ERR_clear_error(); int result = (this->*op)(data, length); int ssl_error = ::SSL_get_error(ssl_, result); int sys_error = static_cast<int>(::ERR_get_error()); std::size_t pending_output_after = ::BIO_ctrl_pending(ext_bio_); if (ssl_error == SSL_ERROR_SSL) { ec = asio::error_code(sys_error, asio::error::get_ssl_category()); return pending_output_after > pending_output_before ? want_output : want_nothing; } if (ssl_error == SSL_ERROR_SYSCALL) { if (sys_error == 0) { ec = asio::ssl::error::unspecified_system_error; } else { ec = asio::error_code(sys_error, asio::error::get_ssl_category()); } return pending_output_after > pending_output_before ? want_output : want_nothing; } if (result > 0 && bytes_transferred) *bytes_transferred = static_cast<std::size_t>(result); if (ssl_error == SSL_ERROR_WANT_WRITE) { ec = asio::error_code(); return want_output_and_retry; } else if (pending_output_after > pending_output_before) { ec = asio::error_code(); return result > 0 ? want_output : want_output_and_retry; } else if (ssl_error == SSL_ERROR_WANT_READ) { ec = asio::error_code(); return want_input_and_retry; } else if (ssl_error == SSL_ERROR_ZERO_RETURN) { ec = asio::error::eof; return want_nothing; } else if (ssl_error == SSL_ERROR_NONE) { ec = asio::error_code(); return want_nothing; } else { ec = asio::ssl::error::unexpected_result; return want_nothing; } } int engine::do_accept(void*, std::size_t) { #if (OPENSSL_VERSION_NUMBER < 0x10000000L) asio::detail::static_mutex::scoped_lock lock(accept_mutex()); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) return ::SSL_accept(ssl_); } int engine::do_connect(void*, std::size_t) { return ::SSL_connect(ssl_); } int engine::do_shutdown(void*, std::size_t) { int result = ::SSL_shutdown(ssl_); if (result == 0) result = ::SSL_shutdown(ssl_); return result; } int engine::do_read(void* data, std::size_t length) { return ::SSL_read(ssl_, data, length < INT_MAX ? static_cast<int>(length) : INT_MAX); } int engine::do_write(void* data, std::size_t length) { return ::SSL_write(ssl_, data, length < INT_MAX ? static_cast<int>(length) : INT_MAX); } } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_IMPL_ENGINE_IPP
0
repos/asio/asio/include/asio/ssl/detail
repos/asio/asio/include/asio/ssl/detail/impl/openssl_init.ipp
// // ssl/detail/impl/openssl_init.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com // Copyright (c) 2005-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 ASIO_SSL_DETAIL_IMPL_OPENSSL_INIT_IPP #define ASIO_SSL_DETAIL_IMPL_OPENSSL_INIT_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <vector> #include "asio/detail/assert.hpp" #include "asio/detail/mutex.hpp" #include "asio/detail/tss_ptr.hpp" #include "asio/ssl/detail/openssl_init.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { namespace detail { class openssl_init_base::do_init { public: do_init() { #if (OPENSSL_VERSION_NUMBER < 0x10100000L) ::SSL_library_init(); ::SSL_load_error_strings(); ::OpenSSL_add_all_algorithms(); mutexes_.resize(::CRYPTO_num_locks()); for (size_t i = 0; i < mutexes_.size(); ++i) mutexes_[i].reset(new asio::detail::mutex); ::CRYPTO_set_locking_callback(&do_init::openssl_locking_func); #endif // (OPENSSL_VERSION_NUMBER < 0x10100000L) #if (OPENSSL_VERSION_NUMBER < 0x10000000L) ::CRYPTO_set_id_callback(&do_init::openssl_id_func); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) null_compression_methods_ = sk_SSL_COMP_new_null(); #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) } ~do_init() { #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) sk_SSL_COMP_free(null_compression_methods_); #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) #if (OPENSSL_VERSION_NUMBER < 0x10000000L) ::CRYPTO_set_id_callback(0); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) #if (OPENSSL_VERSION_NUMBER < 0x10100000L) ::CRYPTO_set_locking_callback(0); ::ERR_free_strings(); ::EVP_cleanup(); ::CRYPTO_cleanup_all_ex_data(); #endif // (OPENSSL_VERSION_NUMBER < 0x10100000L) #if (OPENSSL_VERSION_NUMBER < 0x10000000L) ::ERR_remove_state(0); #elif (OPENSSL_VERSION_NUMBER < 0x10100000L) ::ERR_remove_thread_state(NULL); #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) #if (OPENSSL_VERSION_NUMBER >= 0x10002000L) \ && (OPENSSL_VERSION_NUMBER < 0x10100000L) \ && !defined(SSL_OP_NO_COMPRESSION) ::SSL_COMP_free_compression_methods(); #endif // (OPENSSL_VERSION_NUMBER >= 0x10002000L) // && (OPENSSL_VERSION_NUMBER < 0x10100000L) // && !defined(SSL_OP_NO_COMPRESSION) #if !defined(OPENSSL_IS_BORINGSSL) \ && !defined(ASIO_USE_WOLFSSL) \ && (OPENSSL_VERSION_NUMBER < 0x30000000L) ::CONF_modules_unload(1); #endif // !defined(OPENSSL_IS_BORINGSSL) // && !defined(ASIO_USE_WOLFSSL) // && (OPENSSL_VERSION_NUMBER < 0x30000000L) #if !defined(OPENSSL_NO_ENGINE) \ && (OPENSSL_VERSION_NUMBER < 0x10100000L) ::ENGINE_cleanup(); #endif // !defined(OPENSSL_NO_ENGINE) // && (OPENSSL_VERSION_NUMBER < 0x10100000L) } #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) STACK_OF(SSL_COMP)* get_null_compression_methods() const { return null_compression_methods_; } #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) private: #if (OPENSSL_VERSION_NUMBER < 0x10000000L) static unsigned long openssl_id_func() { #if defined(ASIO_WINDOWS) || defined(__CYGWIN__) return ::GetCurrentThreadId(); #else // defined(ASIO_WINDOWS) || defined(__CYGWIN__) void* id = &errno; ASIO_ASSERT(sizeof(unsigned long) >= sizeof(void*)); return reinterpret_cast<unsigned long>(id); #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) } #endif // (OPENSSL_VERSION_NUMBER < 0x10000000L) #if (OPENSSL_VERSION_NUMBER < 0x10100000L) static void openssl_locking_func(int mode, int n, const char* /*file*/, int /*line*/) { if (mode & CRYPTO_LOCK) instance()->mutexes_[n]->lock(); else instance()->mutexes_[n]->unlock(); } // Mutexes to be used in locking callbacks. std::vector<asio::detail::shared_ptr< asio::detail::mutex>> mutexes_; #endif // (OPENSSL_VERSION_NUMBER < 0x10100000L) #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) STACK_OF(SSL_COMP)* null_compression_methods_; #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) }; asio::detail::shared_ptr<openssl_init_base::do_init> openssl_init_base::instance() { static asio::detail::shared_ptr<do_init> init(new do_init); return init; } #if !defined(SSL_OP_NO_COMPRESSION) \ && (OPENSSL_VERSION_NUMBER >= 0x00908000L) STACK_OF(SSL_COMP)* openssl_init_base::get_null_compression_methods() { return instance()->get_null_compression_methods(); } #endif // !defined(SSL_OP_NO_COMPRESSION) // && (OPENSSL_VERSION_NUMBER >= 0x00908000L) } // namespace detail } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_DETAIL_IMPL_OPENSSL_INIT_IPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/rfc2818_verification.ipp
// // ssl/impl/rfc2818_verification.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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 ASIO_SSL_IMPL_RFC2818_VERIFICATION_IPP #define ASIO_SSL_IMPL_RFC2818_VERIFICATION_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_NO_DEPRECATED) #include <cctype> #include <cstring> #include "asio/ip/address.hpp" #include "asio/ssl/rfc2818_verification.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { bool rfc2818_verification::operator()( bool preverified, verify_context& ctx) const { using namespace std; // For memcmp. // Don't bother looking at certificates that have failed pre-verification. if (!preverified) return false; // We're only interested in checking the certificate at the end of the chain. int depth = X509_STORE_CTX_get_error_depth(ctx.native_handle()); if (depth > 0) return true; // Try converting the host name to an address. If it is an address then we // need to look for an IP address in the certificate rather than a host name. asio::error_code ec; ip::address address = ip::make_address(host_, ec); bool is_address = !ec; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); // Go through the alternate names in the certificate looking for matching DNS // or IP address entries. GENERAL_NAMES* gens = static_cast<GENERAL_NAMES*>( X509_get_ext_d2i(cert, NID_subject_alt_name, 0, 0)); for (int i = 0; i < sk_GENERAL_NAME_num(gens); ++i) { GENERAL_NAME* gen = sk_GENERAL_NAME_value(gens, i); if (gen->type == GEN_DNS && !is_address) { ASN1_IA5STRING* domain = gen->d.dNSName; if (domain->type == V_ASN1_IA5STRING && domain->data && domain->length) { const char* pattern = reinterpret_cast<const char*>(domain->data); std::size_t pattern_length = domain->length; if (match_pattern(pattern, pattern_length, host_.c_str())) { GENERAL_NAMES_free(gens); return true; } } } else if (gen->type == GEN_IPADD && is_address) { ASN1_OCTET_STRING* ip_address = gen->d.iPAddress; if (ip_address->type == V_ASN1_OCTET_STRING && ip_address->data) { if (address.is_v4() && ip_address->length == 4) { ip::address_v4::bytes_type bytes = address.to_v4().to_bytes(); if (memcmp(bytes.data(), ip_address->data, 4) == 0) { GENERAL_NAMES_free(gens); return true; } } else if (address.is_v6() && ip_address->length == 16) { ip::address_v6::bytes_type bytes = address.to_v6().to_bytes(); if (memcmp(bytes.data(), ip_address->data, 16) == 0) { GENERAL_NAMES_free(gens); return true; } } } } } GENERAL_NAMES_free(gens); // No match in the alternate names, so try the common names. We should only // use the "most specific" common name, which is the last one in the list. X509_NAME* name = X509_get_subject_name(cert); int i = -1; ASN1_STRING* common_name = 0; while ((i = X509_NAME_get_index_by_NID(name, NID_commonName, i)) >= 0) { X509_NAME_ENTRY* name_entry = X509_NAME_get_entry(name, i); common_name = X509_NAME_ENTRY_get_data(name_entry); } if (common_name && common_name->data && common_name->length) { const char* pattern = reinterpret_cast<const char*>(common_name->data); std::size_t pattern_length = common_name->length; if (match_pattern(pattern, pattern_length, host_.c_str())) return true; } return false; } bool rfc2818_verification::match_pattern(const char* pattern, std::size_t pattern_length, const char* host) { using namespace std; // For tolower. const char* p = pattern; const char* p_end = p + pattern_length; const char* h = host; while (p != p_end && *h) { if (*p == '*') { ++p; while (*h && *h != '.') if (match_pattern(p, p_end - p, h++)) return true; } else if (tolower(*p) == tolower(*h)) { ++p; ++h; } else { return false; } } return p == p_end && !*h; } } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_NO_DEPRECATED) #endif // ASIO_SSL_IMPL_RFC2818_VERIFICATION_IPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/src.hpp
// // impl/ssl/src.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 ASIO_SSL_IMPL_SRC_HPP #define ASIO_SSL_IMPL_SRC_HPP #define ASIO_SOURCE #include "asio/detail/config.hpp" #if defined(ASIO_HEADER_ONLY) # error Do not compile Asio library source with ASIO_HEADER_ONLY defined #endif #include "asio/ssl/impl/context.ipp" #include "asio/ssl/impl/error.ipp" #include "asio/ssl/detail/impl/engine.ipp" #include "asio/ssl/detail/impl/openssl_init.ipp" #include "asio/ssl/impl/host_name_verification.ipp" #include "asio/ssl/impl/rfc2818_verification.ipp" #endif // ASIO_SSL_IMPL_SRC_HPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/error.ipp
// // ssl/impl/error.ipp // ~~~~~~~~~~~~~~~~~~ // // 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 ASIO_SSL_IMPL_ERROR_IPP #define ASIO_SSL_IMPL_ERROR_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/ssl/error.hpp" #include "asio/ssl/detail/openssl_init.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace error { namespace detail { class ssl_category : public asio::error_category { public: const char* name() const noexcept { return "asio.ssl"; } std::string message(int value) const { const char* reason = ::ERR_reason_error_string(value); if (reason) { const char* lib = ::ERR_lib_error_string(value); #if (OPENSSL_VERSION_NUMBER < 0x30000000L) const char* func = ::ERR_func_error_string(value); #else // (OPENSSL_VERSION_NUMBER < 0x30000000L) const char* func = 0; #endif // (OPENSSL_VERSION_NUMBER < 0x30000000L) std::string result(reason); if (lib || func) { result += " ("; if (lib) result += lib; if (lib && func) result += ", "; if (func) result += func; result += ")"; } return result; } return "asio.ssl error"; } }; } // namespace detail const asio::error_category& get_ssl_category() { static detail::ssl_category instance; return instance; } } // namespace error namespace ssl { namespace error { #if (OPENSSL_VERSION_NUMBER < 0x10100000L) && !defined(OPENSSL_IS_BORINGSSL) const asio::error_category& get_stream_category() { return asio::error::get_ssl_category(); } #else namespace detail { class stream_category : public asio::error_category { public: const char* name() const noexcept { return "asio.ssl.stream"; } std::string message(int value) const { switch (value) { case stream_truncated: return "stream truncated"; case unspecified_system_error: return "unspecified system error"; case unexpected_result: return "unexpected result"; default: return "asio.ssl.stream error"; } } }; } // namespace detail const asio::error_category& get_stream_category() { static detail::stream_category instance; return instance; } #endif } // namespace error } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_IMPL_ERROR_IPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/context.ipp
// // ssl/impl/context.ipp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com // Copyright (c) 2005-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 ASIO_SSL_IMPL_CONTEXT_IPP #define ASIO_SSL_IMPL_CONTEXT_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstring> #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/ssl/context.hpp" #include "asio/ssl/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { struct context::bio_cleanup { BIO* p; ~bio_cleanup() { if (p) ::BIO_free(p); } }; struct context::x509_cleanup { X509* p; ~x509_cleanup() { if (p) ::X509_free(p); } }; struct context::evp_pkey_cleanup { EVP_PKEY* p; ~evp_pkey_cleanup() { if (p) ::EVP_PKEY_free(p); } }; #if (OPENSSL_VERSION_NUMBER < 0x30000000L) struct context::rsa_cleanup { RSA* p; ~rsa_cleanup() { if (p) ::RSA_free(p); } }; struct context::dh_cleanup { DH* p; ~dh_cleanup() { if (p) ::DH_free(p); } }; #endif // (OPENSSL_VERSION_NUMBER < 0x30000000L) context::context(context::method m) : handle_(0) { ::ERR_clear_error(); switch (m) { // SSL v2. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) || defined(OPENSSL_NO_SSL2) case context::sslv2: case context::sslv2_client: case context::sslv2_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) || defined(OPENSSL_NO_SSL2) case context::sslv2: handle_ = ::SSL_CTX_new(::SSLv2_method()); break; case context::sslv2_client: handle_ = ::SSL_CTX_new(::SSLv2_client_method()); break; case context::sslv2_server: handle_ = ::SSL_CTX_new(::SSLv2_server_method()); break; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) || defined(OPENSSL_NO_SSL2) // SSL v3. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) case context::sslv3: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, SSL3_VERSION); SSL_CTX_set_max_proto_version(handle_, SSL3_VERSION); } break; case context::sslv3_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, SSL3_VERSION); SSL_CTX_set_max_proto_version(handle_, SSL3_VERSION); } break; case context::sslv3_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, SSL3_VERSION); SSL_CTX_set_max_proto_version(handle_, SSL3_VERSION); } break; #elif defined(OPENSSL_NO_SSL3) case context::sslv3: case context::sslv3_client: case context::sslv3_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #else // defined(OPENSSL_NO_SSL3) case context::sslv3: handle_ = ::SSL_CTX_new(::SSLv3_method()); break; case context::sslv3_client: handle_ = ::SSL_CTX_new(::SSLv3_client_method()); break; case context::sslv3_server: handle_ = ::SSL_CTX_new(::SSLv3_server_method()); break; #endif // defined(OPENSSL_NO_SSL3) // TLS v1.0. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) case context::tlsv1: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_VERSION); } break; case context::tlsv1_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_VERSION); } break; case context::tlsv1_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_VERSION); } break; #elif defined(SSL_TXT_TLSV1) case context::tlsv1: handle_ = ::SSL_CTX_new(::TLSv1_method()); break; case context::tlsv1_client: handle_ = ::SSL_CTX_new(::TLSv1_client_method()); break; case context::tlsv1_server: handle_ = ::SSL_CTX_new(::TLSv1_server_method()); break; #else // defined(SSL_TXT_TLSV1) case context::tlsv1: case context::tlsv1_client: case context::tlsv1_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #endif // defined(SSL_TXT_TLSV1) // TLS v1.1. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) case context::tlsv11: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_1_VERSION); } break; case context::tlsv11_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_1_VERSION); } break; case context::tlsv11_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_1_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_1_VERSION); } break; #elif defined(SSL_TXT_TLSV1_1) case context::tlsv11: handle_ = ::SSL_CTX_new(::TLSv1_1_method()); break; case context::tlsv11_client: handle_ = ::SSL_CTX_new(::TLSv1_1_client_method()); break; case context::tlsv11_server: handle_ = ::SSL_CTX_new(::TLSv1_1_server_method()); break; #else // defined(SSL_TXT_TLSV1_1) case context::tlsv11: case context::tlsv11_client: case context::tlsv11_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #endif // defined(SSL_TXT_TLSV1_1) // TLS v1.2. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) case context::tlsv12: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_2_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_2_VERSION); } break; case context::tlsv12_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_2_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_2_VERSION); } break; case context::tlsv12_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_2_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_2_VERSION); } break; #elif defined(SSL_TXT_TLSV1_2) case context::tlsv12: handle_ = ::SSL_CTX_new(::TLSv1_2_method()); break; case context::tlsv12_client: handle_ = ::SSL_CTX_new(::TLSv1_2_client_method()); break; case context::tlsv12_server: handle_ = ::SSL_CTX_new(::TLSv1_2_server_method()); break; #else // defined(SSL_TXT_TLSV1_2) case context::tlsv12: case context::tlsv12_client: case context::tlsv12_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #endif // defined(SSL_TXT_TLSV1_2) // TLS v1.3. #if ((OPENSSL_VERSION_NUMBER >= 0x10101000L) \ && !defined(LIBRESSL_VERSION_NUMBER)) \ || defined(ASIO_USE_WOLFSSL) case context::tlsv13: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_3_VERSION); } break; case context::tlsv13_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_3_VERSION); } break; case context::tlsv13_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) { SSL_CTX_set_min_proto_version(handle_, TLS1_3_VERSION); SSL_CTX_set_max_proto_version(handle_, TLS1_3_VERSION); } break; #else // ((OPENSSL_VERSION_NUMBER >= 0x10101000L) // && !defined(LIBRESSL_VERSION_NUMBER)) // || defined(ASIO_USE_WOLFSSL) case context::tlsv13: case context::tlsv13_client: case context::tlsv13_server: asio::detail::throw_error( asio::error::invalid_argument, "context"); break; #endif // ((OPENSSL_VERSION_NUMBER >= 0x10101000L) // && !defined(LIBRESSL_VERSION_NUMBER)) // || defined(ASIO_USE_WOLFSSL) // Any supported SSL/TLS version. case context::sslv23: handle_ = ::SSL_CTX_new(::SSLv23_method()); break; case context::sslv23_client: handle_ = ::SSL_CTX_new(::SSLv23_client_method()); break; case context::sslv23_server: handle_ = ::SSL_CTX_new(::SSLv23_server_method()); break; // Any supported TLS version. #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER) case context::tls: handle_ = ::SSL_CTX_new(::TLS_method()); if (handle_) SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); break; case context::tls_client: handle_ = ::SSL_CTX_new(::TLS_client_method()); if (handle_) SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); break; case context::tls_server: handle_ = ::SSL_CTX_new(::TLS_server_method()); if (handle_) SSL_CTX_set_min_proto_version(handle_, TLS1_VERSION); break; #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) case context::tls: handle_ = ::SSL_CTX_new(::SSLv23_method()); if (handle_) SSL_CTX_set_options(handle_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); break; case context::tls_client: handle_ = ::SSL_CTX_new(::SSLv23_client_method()); if (handle_) SSL_CTX_set_options(handle_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); break; case context::tls_server: handle_ = ::SSL_CTX_new(::SSLv23_server_method()); if (handle_) SSL_CTX_set_options(handle_, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3); break; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) default: handle_ = ::SSL_CTX_new(0); break; } if (handle_ == 0) { asio::error_code ec = translate_error(::ERR_get_error()); asio::detail::throw_error(ec, "context"); } set_options(no_compression); } context::context(context::native_handle_type native_handle) : handle_(native_handle) { if (!handle_) { asio::detail::throw_error( asio::error::invalid_argument, "context"); } } context::context(context&& other) { handle_ = other.handle_; other.handle_ = 0; } context& context::operator=(context&& other) { context tmp(static_cast<context&&>(*this)); handle_ = other.handle_; other.handle_ = 0; return *this; } context::~context() { if (handle_) { #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) void* cb_userdata = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) void* cb_userdata = handle_->default_passwd_callback_userdata; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) if (cb_userdata) { detail::password_callback_base* callback = static_cast<detail::password_callback_base*>( cb_userdata); delete callback; #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) ::SSL_CTX_set_default_passwd_cb_userdata(handle_, 0); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) handle_->default_passwd_callback_userdata = 0; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) } if (SSL_CTX_get_app_data(handle_)) { detail::verify_callback_base* callback = static_cast<detail::verify_callback_base*>( SSL_CTX_get_app_data(handle_)); delete callback; SSL_CTX_set_app_data(handle_, 0); } ::SSL_CTX_free(handle_); } } context::native_handle_type context::native_handle() { return handle_; } void context::clear_options(context::options o) { asio::error_code ec; clear_options(o, ec); asio::detail::throw_error(ec, "clear_options"); } ASIO_SYNC_OP_VOID context::clear_options( context::options o, asio::error_code& ec) { #if (OPENSSL_VERSION_NUMBER >= 0x009080DFL) \ && (OPENSSL_VERSION_NUMBER != 0x00909000L) # if !defined(SSL_OP_NO_COMPRESSION) if ((o & context::no_compression) != 0) { # if (OPENSSL_VERSION_NUMBER >= 0x00908000L) handle_->comp_methods = SSL_COMP_get_compression_methods(); # endif // (OPENSSL_VERSION_NUMBER >= 0x00908000L) o ^= context::no_compression; } # endif // !defined(SSL_OP_NO_COMPRESSION) ::SSL_CTX_clear_options(handle_, o); ec = asio::error_code(); #else // (OPENSSL_VERSION_NUMBER >= 0x009080DFL) // && (OPENSSL_VERSION_NUMBER != 0x00909000L) (void)o; ec = asio::error::operation_not_supported; #endif // (OPENSSL_VERSION_NUMBER >= 0x009080DFL) // && (OPENSSL_VERSION_NUMBER != 0x00909000L) ASIO_SYNC_OP_VOID_RETURN(ec); } void context::set_options(context::options o) { asio::error_code ec; set_options(o, ec); asio::detail::throw_error(ec, "set_options"); } ASIO_SYNC_OP_VOID context::set_options( context::options o, asio::error_code& ec) { #if !defined(SSL_OP_NO_COMPRESSION) if ((o & context::no_compression) != 0) { #if (OPENSSL_VERSION_NUMBER >= 0x00908000L) handle_->comp_methods = asio::ssl::detail::openssl_init<>::get_null_compression_methods(); #endif // (OPENSSL_VERSION_NUMBER >= 0x00908000L) o ^= context::no_compression; } #endif // !defined(SSL_OP_NO_COMPRESSION) ::SSL_CTX_set_options(handle_, o); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::set_verify_mode(verify_mode v) { asio::error_code ec; set_verify_mode(v, ec); asio::detail::throw_error(ec, "set_verify_mode"); } ASIO_SYNC_OP_VOID context::set_verify_mode( verify_mode v, asio::error_code& ec) { ::SSL_CTX_set_verify(handle_, v, ::SSL_CTX_get_verify_callback(handle_)); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::set_verify_depth(int depth) { asio::error_code ec; set_verify_depth(depth, ec); asio::detail::throw_error(ec, "set_verify_depth"); } ASIO_SYNC_OP_VOID context::set_verify_depth( int depth, asio::error_code& ec) { ::SSL_CTX_set_verify_depth(handle_, depth); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::load_verify_file(const std::string& filename) { asio::error_code ec; load_verify_file(filename, ec); asio::detail::throw_error(ec, "load_verify_file"); } ASIO_SYNC_OP_VOID context::load_verify_file( const std::string& filename, asio::error_code& ec) { ::ERR_clear_error(); if (::SSL_CTX_load_verify_locations(handle_, filename.c_str(), 0) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::add_certificate_authority(const const_buffer& ca) { asio::error_code ec; add_certificate_authority(ca, ec); asio::detail::throw_error(ec, "add_certificate_authority"); } ASIO_SYNC_OP_VOID context::add_certificate_authority( const const_buffer& ca, asio::error_code& ec) { ::ERR_clear_error(); bio_cleanup bio = { make_buffer_bio(ca) }; if (bio.p) { if (X509_STORE* store = ::SSL_CTX_get_cert_store(handle_)) { for (bool added = false;; added = true) { x509_cleanup cert = { ::PEM_read_bio_X509(bio.p, 0, 0, 0) }; if (!cert.p) { unsigned long err = ::ERR_get_error(); if (added && ERR_GET_LIB(err) == ERR_LIB_PEM && ERR_GET_REASON(err) == PEM_R_NO_START_LINE) break; ec = translate_error(err); ASIO_SYNC_OP_VOID_RETURN(ec); } if (::X509_STORE_add_cert(store, cert.p) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } } } } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::set_default_verify_paths() { asio::error_code ec; set_default_verify_paths(ec); asio::detail::throw_error(ec, "set_default_verify_paths"); } ASIO_SYNC_OP_VOID context::set_default_verify_paths( asio::error_code& ec) { ::ERR_clear_error(); if (::SSL_CTX_set_default_verify_paths(handle_) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::add_verify_path(const std::string& path) { asio::error_code ec; add_verify_path(path, ec); asio::detail::throw_error(ec, "add_verify_path"); } ASIO_SYNC_OP_VOID context::add_verify_path( const std::string& path, asio::error_code& ec) { ::ERR_clear_error(); if (::SSL_CTX_load_verify_locations(handle_, 0, path.c_str()) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_certificate( const const_buffer& certificate, file_format format) { asio::error_code ec; use_certificate(certificate, format, ec); asio::detail::throw_error(ec, "use_certificate"); } ASIO_SYNC_OP_VOID context::use_certificate( const const_buffer& certificate, file_format format, asio::error_code& ec) { ::ERR_clear_error(); if (format == context_base::asn1) { if (::SSL_CTX_use_certificate_ASN1(handle_, static_cast<int>(certificate.size()), static_cast<const unsigned char*>(certificate.data())) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } else if (format == context_base::pem) { bio_cleanup bio = { make_buffer_bio(certificate) }; if (bio.p) { x509_cleanup cert = { ::PEM_read_bio_X509(bio.p, 0, 0, 0) }; if (cert.p) { if (::SSL_CTX_use_certificate(handle_, cert.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } } } else { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_certificate_file( const std::string& filename, file_format format) { asio::error_code ec; use_certificate_file(filename, format, ec); asio::detail::throw_error(ec, "use_certificate_file"); } ASIO_SYNC_OP_VOID context::use_certificate_file( const std::string& filename, file_format format, asio::error_code& ec) { int file_type; switch (format) { case context_base::asn1: file_type = SSL_FILETYPE_ASN1; break; case context_base::pem: file_type = SSL_FILETYPE_PEM; break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } ::ERR_clear_error(); if (::SSL_CTX_use_certificate_file(handle_, filename.c_str(), file_type) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_certificate_chain(const const_buffer& chain) { asio::error_code ec; use_certificate_chain(chain, ec); asio::detail::throw_error(ec, "use_certificate_chain"); } ASIO_SYNC_OP_VOID context::use_certificate_chain( const const_buffer& chain, asio::error_code& ec) { ::ERR_clear_error(); bio_cleanup bio = { make_buffer_bio(chain) }; if (bio.p) { #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) pem_password_cb* callback = ::SSL_CTX_get_default_passwd_cb(handle_); void* cb_userdata = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) pem_password_cb* callback = handle_->default_passwd_callback; void* cb_userdata = handle_->default_passwd_callback_userdata; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) x509_cleanup cert = { ::PEM_read_bio_X509_AUX(bio.p, 0, callback, cb_userdata) }; if (!cert.p) { ec = translate_error(ERR_R_PEM_LIB); ASIO_SYNC_OP_VOID_RETURN(ec); } int result = ::SSL_CTX_use_certificate(handle_, cert.p); if (result == 0 || ::ERR_peek_error() != 0) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } #if ((OPENSSL_VERSION_NUMBER >= 0x10002000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2090100fL)) \ || defined(ASIO_USE_WOLFSSL) ::SSL_CTX_clear_chain_certs(handle_); #else if (handle_->extra_certs) { ::sk_X509_pop_free(handle_->extra_certs, X509_free); handle_->extra_certs = 0; } #endif // (OPENSSL_VERSION_NUMBER >= 0x10002000L) while (X509* cacert = ::PEM_read_bio_X509(bio.p, 0, callback, cb_userdata)) { if (!::SSL_CTX_add_extra_chain_cert(handle_, cacert)) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } } result = ::ERR_peek_last_error(); if ((ERR_GET_LIB(result) == ERR_LIB_PEM) && (ERR_GET_REASON(result) == PEM_R_NO_START_LINE)) { ::ERR_clear_error(); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_certificate_chain_file(const std::string& filename) { asio::error_code ec; use_certificate_chain_file(filename, ec); asio::detail::throw_error(ec, "use_certificate_chain_file"); } ASIO_SYNC_OP_VOID context::use_certificate_chain_file( const std::string& filename, asio::error_code& ec) { ::ERR_clear_error(); if (::SSL_CTX_use_certificate_chain_file(handle_, filename.c_str()) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_private_key( const const_buffer& private_key, context::file_format format) { asio::error_code ec; use_private_key(private_key, format, ec); asio::detail::throw_error(ec, "use_private_key"); } ASIO_SYNC_OP_VOID context::use_private_key( const const_buffer& private_key, context::file_format format, asio::error_code& ec) { ::ERR_clear_error(); #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) pem_password_cb* callback = ::SSL_CTX_get_default_passwd_cb(handle_); void* cb_userdata = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) pem_password_cb* callback = handle_->default_passwd_callback; void* cb_userdata = handle_->default_passwd_callback_userdata; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) bio_cleanup bio = { make_buffer_bio(private_key) }; if (bio.p) { evp_pkey_cleanup evp_private_key = { 0 }; switch (format) { case context_base::asn1: evp_private_key.p = ::d2i_PrivateKey_bio(bio.p, 0); break; case context_base::pem: evp_private_key.p = ::PEM_read_bio_PrivateKey( bio.p, 0, callback, cb_userdata); break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } if (evp_private_key.p) { if (::SSL_CTX_use_PrivateKey(handle_, evp_private_key.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_private_key_file( const std::string& filename, context::file_format format) { asio::error_code ec; use_private_key_file(filename, format, ec); asio::detail::throw_error(ec, "use_private_key_file"); } void context::use_rsa_private_key( const const_buffer& private_key, context::file_format format) { asio::error_code ec; use_rsa_private_key(private_key, format, ec); asio::detail::throw_error(ec, "use_rsa_private_key"); } ASIO_SYNC_OP_VOID context::use_rsa_private_key( const const_buffer& private_key, context::file_format format, asio::error_code& ec) { ::ERR_clear_error(); #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) pem_password_cb* callback = ::SSL_CTX_get_default_passwd_cb(handle_); void* cb_userdata = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) pem_password_cb* callback = handle_->default_passwd_callback; void* cb_userdata = handle_->default_passwd_callback_userdata; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) bio_cleanup bio = { make_buffer_bio(private_key) }; if (bio.p) { #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) evp_pkey_cleanup evp_private_key = { 0 }; switch (format) { case context_base::asn1: evp_private_key.p = ::d2i_PrivateKey_bio(bio.p, 0); break; case context_base::pem: evp_private_key.p = ::PEM_read_bio_PrivateKey( bio.p, 0, callback, cb_userdata); break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } if (evp_private_key.p) { if (::EVP_PKEY_is_a(evp_private_key.p, "RSA") == 0) { ec = translate_error( ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_RSA_KEY)); ASIO_SYNC_OP_VOID_RETURN(ec); } if (::SSL_CTX_use_PrivateKey(handle_, evp_private_key.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } #else // (OPENSSL_VERSION_NUMBER >= 0x30000000L) rsa_cleanup rsa_private_key = { 0 }; switch (format) { case context_base::asn1: rsa_private_key.p = ::d2i_RSAPrivateKey_bio(bio.p, 0); break; case context_base::pem: rsa_private_key.p = ::PEM_read_bio_RSAPrivateKey( bio.p, 0, callback, cb_userdata); break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } if (rsa_private_key.p) { if (::SSL_CTX_use_RSAPrivateKey(handle_, rsa_private_key.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } #endif // (OPENSSL_VERSION_NUMBER >= 0x30000000L) } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ASIO_SYNC_OP_VOID context::use_private_key_file( const std::string& filename, context::file_format format, asio::error_code& ec) { int file_type; switch (format) { case context_base::asn1: file_type = SSL_FILETYPE_ASN1; break; case context_base::pem: file_type = SSL_FILETYPE_PEM; break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } ::ERR_clear_error(); if (::SSL_CTX_use_PrivateKey_file(handle_, filename.c_str(), file_type) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_rsa_private_key_file( const std::string& filename, context::file_format format) { asio::error_code ec; use_rsa_private_key_file(filename, format, ec); asio::detail::throw_error(ec, "use_rsa_private_key_file"); } ASIO_SYNC_OP_VOID context::use_rsa_private_key_file( const std::string& filename, context::file_format format, asio::error_code& ec) { #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) ::ERR_clear_error(); pem_password_cb* callback = ::SSL_CTX_get_default_passwd_cb(handle_); void* cb_userdata = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); bio_cleanup bio = { ::BIO_new_file(filename.c_str(), "r") }; if (bio.p) { evp_pkey_cleanup evp_private_key = { 0 }; switch (format) { case context_base::asn1: evp_private_key.p = ::d2i_PrivateKey_bio(bio.p, 0); break; case context_base::pem: evp_private_key.p = ::PEM_read_bio_PrivateKey( bio.p, 0, callback, cb_userdata); break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } if (evp_private_key.p) { if (::EVP_PKEY_is_a(evp_private_key.p, "RSA") == 0) { ec = translate_error( ERR_PACK(ERR_LIB_EVP, 0, EVP_R_EXPECTING_AN_RSA_KEY)); ASIO_SYNC_OP_VOID_RETURN(ec); } if (::SSL_CTX_use_PrivateKey(handle_, evp_private_key.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); #else // (OPENSSL_VERSION_NUMBER >= 0x30000000L) int file_type; switch (format) { case context_base::asn1: file_type = SSL_FILETYPE_ASN1; break; case context_base::pem: file_type = SSL_FILETYPE_PEM; break; default: { ec = asio::error::invalid_argument; ASIO_SYNC_OP_VOID_RETURN(ec); } } ::ERR_clear_error(); if (::SSL_CTX_use_RSAPrivateKey_file( handle_, filename.c_str(), file_type) != 1) { ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); #endif // (OPENSSL_VERSION_NUMBER >= 0x30000000L) } void context::use_tmp_dh(const const_buffer& dh) { asio::error_code ec; use_tmp_dh(dh, ec); asio::detail::throw_error(ec, "use_tmp_dh"); } ASIO_SYNC_OP_VOID context::use_tmp_dh( const const_buffer& dh, asio::error_code& ec) { ::ERR_clear_error(); bio_cleanup bio = { make_buffer_bio(dh) }; if (bio.p) { return do_use_tmp_dh(bio.p, ec); } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } void context::use_tmp_dh_file(const std::string& filename) { asio::error_code ec; use_tmp_dh_file(filename, ec); asio::detail::throw_error(ec, "use_tmp_dh_file"); } ASIO_SYNC_OP_VOID context::use_tmp_dh_file( const std::string& filename, asio::error_code& ec) { ::ERR_clear_error(); bio_cleanup bio = { ::BIO_new_file(filename.c_str(), "r") }; if (bio.p) { return do_use_tmp_dh(bio.p, ec); } ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ASIO_SYNC_OP_VOID context::do_use_tmp_dh( BIO* bio, asio::error_code& ec) { ::ERR_clear_error(); #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) EVP_PKEY* p = ::PEM_read_bio_Parameters(bio, 0); if (p) { if (::SSL_CTX_set0_tmp_dh_pkey(handle_, p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } else ::EVP_PKEY_free(p); } #else // (OPENSSL_VERSION_NUMBER >= 0x30000000L) dh_cleanup dh = { ::PEM_read_bio_DHparams(bio, 0, 0, 0) }; if (dh.p) { if (::SSL_CTX_set_tmp_dh(handle_, dh.p) == 1) { ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } } #endif // (OPENSSL_VERSION_NUMBER >= 0x30000000L) ec = translate_error(::ERR_get_error()); ASIO_SYNC_OP_VOID_RETURN(ec); } ASIO_SYNC_OP_VOID context::do_set_verify_callback( detail::verify_callback_base* callback, asio::error_code& ec) { if (SSL_CTX_get_app_data(handle_)) { delete static_cast<detail::verify_callback_base*>( SSL_CTX_get_app_data(handle_)); } SSL_CTX_set_app_data(handle_, callback); ::SSL_CTX_set_verify(handle_, ::SSL_CTX_get_verify_mode(handle_), &context::verify_callback_function); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } int context::verify_callback_function(int preverified, X509_STORE_CTX* ctx) { if (ctx) { if (SSL* ssl = static_cast<SSL*>( ::X509_STORE_CTX_get_ex_data( ctx, ::SSL_get_ex_data_X509_STORE_CTX_idx()))) { if (SSL_CTX* handle = ::SSL_get_SSL_CTX(ssl)) { if (SSL_CTX_get_app_data(handle)) { detail::verify_callback_base* callback = static_cast<detail::verify_callback_base*>( SSL_CTX_get_app_data(handle)); verify_context verify_ctx(ctx); return callback->call(preverified != 0, verify_ctx) ? 1 : 0; } } } } return 0; } ASIO_SYNC_OP_VOID context::do_set_password_callback( detail::password_callback_base* callback, asio::error_code& ec) { #if ((OPENSSL_VERSION_NUMBER >= 0x10100000L) \ && (!defined(LIBRESSL_VERSION_NUMBER) \ || LIBRESSL_VERSION_NUMBER >= 0x2070000fL)) \ || defined(ASIO_USE_WOLFSSL) void* old_callback = ::SSL_CTX_get_default_passwd_cb_userdata(handle_); ::SSL_CTX_set_default_passwd_cb_userdata(handle_, callback); #else // (OPENSSL_VERSION_NUMBER >= 0x10100000L) void* old_callback = handle_->default_passwd_callback_userdata; handle_->default_passwd_callback_userdata = callback; #endif // (OPENSSL_VERSION_NUMBER >= 0x10100000L) if (old_callback) delete static_cast<detail::password_callback_base*>( old_callback); SSL_CTX_set_default_passwd_cb(handle_, &context::password_callback_function); ec = asio::error_code(); ASIO_SYNC_OP_VOID_RETURN(ec); } int context::password_callback_function( char* buf, int size, int purpose, void* data) { using namespace std; // For strncat and strlen. if (data) { detail::password_callback_base* callback = static_cast<detail::password_callback_base*>(data); std::string passwd = callback->call(static_cast<std::size_t>(size), purpose ? context_base::for_writing : context_base::for_reading); #if defined(ASIO_HAS_SECURE_RTL) strcpy_s(buf, size, passwd.c_str()); #else // defined(ASIO_HAS_SECURE_RTL) *buf = '\0'; if (size > 0) strncat(buf, passwd.c_str(), size - 1); #endif // defined(ASIO_HAS_SECURE_RTL) return static_cast<int>(strlen(buf)); } return 0; } BIO* context::make_buffer_bio(const const_buffer& b) { return ::BIO_new_mem_buf( const_cast<void*>(b.data()), static_cast<int>(b.size())); } asio::error_code context::translate_error(long error) { #if (OPENSSL_VERSION_NUMBER >= 0x30000000L) if (ERR_SYSTEM_ERROR(error)) { return asio::error_code( static_cast<int>(ERR_GET_REASON(error)), asio::error::get_system_category()); } #endif // (OPENSSL_VERSION_NUMBER >= 0x30000000L) return asio::error_code(static_cast<int>(error), asio::error::get_ssl_category()); } } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_IMPL_CONTEXT_IPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/host_name_verification.ipp
// // ssl/impl/host_name_verification.ipp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // 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 ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP #define ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cctype> #include <cstring> #include "asio/ip/address.hpp" #include "asio/ssl/host_name_verification.hpp" #include "asio/ssl/detail/openssl_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { bool host_name_verification::operator()( bool preverified, verify_context& ctx) const { using namespace std; // For memcmp. // Don't bother looking at certificates that have failed pre-verification. if (!preverified) return false; // We're only interested in checking the certificate at the end of the chain. int depth = X509_STORE_CTX_get_error_depth(ctx.native_handle()); if (depth > 0) return true; // Try converting the host name to an address. If it is an address then we // need to look for an IP address in the certificate rather than a host name. asio::error_code ec; ip::address address = ip::make_address(host_, ec); const bool is_address = !ec; (void)address; X509* cert = X509_STORE_CTX_get_current_cert(ctx.native_handle()); if (is_address) { return X509_check_ip_asc(cert, host_.c_str(), 0) == 1; } else { char* peername = 0; const int result = X509_check_host(cert, host_.c_str(), host_.size(), 0, &peername); OPENSSL_free(peername); return result == 1; } } } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_IMPL_HOST_NAME_VERIFICATION_IPP
0
repos/asio/asio/include/asio/ssl
repos/asio/asio/include/asio/ssl/impl/context.hpp
// // ssl/impl/context.hpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2005 Voipster / Indrek dot Juhani at voipster dot com // Copyright (c) 2005-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 ASIO_SSL_IMPL_CONTEXT_HPP #define ASIO_SSL_IMPL_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ssl { template <typename VerifyCallback> void context::set_verify_callback(VerifyCallback callback) { asio::error_code ec; this->set_verify_callback(callback, ec); asio::detail::throw_error(ec, "set_verify_callback"); } template <typename VerifyCallback> ASIO_SYNC_OP_VOID context::set_verify_callback( VerifyCallback callback, asio::error_code& ec) { do_set_verify_callback( new detail::verify_callback<VerifyCallback>(callback), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } template <typename PasswordCallback> void context::set_password_callback(PasswordCallback callback) { asio::error_code ec; this->set_password_callback(callback, ec); asio::detail::throw_error(ec, "set_password_callback"); } template <typename PasswordCallback> ASIO_SYNC_OP_VOID context::set_password_callback( PasswordCallback callback, asio::error_code& ec) { do_set_password_callback( new detail::password_callback<PasswordCallback>(callback), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } } // namespace ssl } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_SSL_IMPL_CONTEXT_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/posix/stream_descriptor.hpp
// // posix/stream_descriptor.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 ASIO_POSIX_STREAM_DESCRIPTOR_HPP #define ASIO_POSIX_STREAM_DESCRIPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include "asio/posix/basic_stream_descriptor.hpp" namespace asio { namespace posix { /// Typedef for the typical usage of a stream-oriented descriptor. typedef basic_stream_descriptor<> stream_descriptor; } // namespace posix } // namespace asio #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_STREAM_DESCRIPTOR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/posix/basic_stream_descriptor.hpp
// // posix/basic_stream_descriptor.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 ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP #define ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/posix/basic_descriptor.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/push_options.hpp" namespace asio { namespace posix { /// Provides stream-oriented descriptor functionality. /** * The posix::basic_stream_descriptor class template provides asynchronous and * blocking stream-oriented descriptor functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * Synchronous @c read_some and @c write_some operations are thread safe with * respect to each other, if the underlying operating system calls are also * thread safe. This means that it is permitted to perform concurrent calls to * these synchronous operations on a single descriptor object. Other synchronous * operations, such as @c close, are not thread safe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Executor = any_io_executor> class basic_stream_descriptor : public basic_descriptor<Executor> { private: class initiate_async_write_some; class initiate_async_read_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the descriptor type to another executor. template <typename Executor1> struct rebind_executor { /// The descriptor type when rebound to the specified executor. typedef basic_stream_descriptor<Executor1> other; }; /// The native representation of a descriptor. typedef typename basic_descriptor<Executor>::native_handle_type native_handle_type; /// Construct a stream descriptor without opening it. /** * This constructor creates a stream descriptor without opening it. The * descriptor needs to be opened and then connected or accepted before data * can be sent or received on it. * * @param ex The I/O executor that the descriptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * descriptor. */ explicit basic_stream_descriptor(const executor_type& ex) : basic_descriptor<Executor>(ex) { } /// Construct a stream descriptor without opening it. /** * This constructor creates a stream descriptor without opening it. The * descriptor needs to be opened and then connected or accepted before data * can be sent or received on it. * * @param context An execution context which provides the I/O executor that * the descriptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the descriptor. */ template <typename ExecutionContext> explicit basic_stream_descriptor(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_descriptor<Executor>(context) { } /// Construct a stream descriptor on an existing native descriptor. /** * This constructor creates a stream descriptor object to hold an existing * native descriptor. * * @param ex The I/O executor that the descriptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * descriptor. * * @param native_descriptor The new underlying descriptor implementation. * * @throws asio::system_error Thrown on failure. */ basic_stream_descriptor(const executor_type& ex, const native_handle_type& native_descriptor) : basic_descriptor<Executor>(ex, native_descriptor) { } /// Construct a stream descriptor on an existing native descriptor. /** * This constructor creates a stream descriptor object to hold an existing * native descriptor. * * @param context An execution context which provides the I/O executor that * the descriptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the descriptor. * * @param native_descriptor The new underlying descriptor implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_descriptor(ExecutionContext& context, const native_handle_type& native_descriptor, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_descriptor<Executor>(context, native_descriptor) { } /// Move-construct a stream descriptor from another. /** * This constructor moves a stream descriptor from one object to another. * * @param other The other stream descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_descriptor(const executor_type&) * constructor. */ basic_stream_descriptor(basic_stream_descriptor&& other) noexcept : basic_descriptor<Executor>(std::move(other)) { } /// Move-assign a stream descriptor from another. /** * This assignment operator moves a stream descriptor from one object to * another. * * @param other The other stream descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_descriptor(const executor_type&) * constructor. */ basic_stream_descriptor& operator=(basic_stream_descriptor&& other) { basic_descriptor<Executor>::operator=(std::move(other)); return *this; } /// Move-construct a basic_stream_descriptor from a descriptor of another /// executor type. /** * This constructor moves a descriptor from one object to another. * * @param other The other basic_stream_descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_descriptor(const executor_type&) * constructor. */ template <typename Executor1> basic_stream_descriptor(basic_stream_descriptor<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : basic_descriptor<Executor>(std::move(other)) { } /// Move-assign a basic_stream_descriptor from a descriptor of another /// executor type. /** * This assignment operator moves a descriptor from one object to another. * * @param other The other basic_stream_descriptor object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_descriptor(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_stream_descriptor& > operator=(basic_stream_descriptor<Executor1> && other) { basic_descriptor<Executor>::operator=(std::move(other)); return *this; } /// Write some data to the descriptor. /** * This function is used to write data to the stream descriptor. The function * call will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the descriptor. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * descriptor.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the descriptor. /** * This function is used to write data to the stream descriptor. The function * call will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the descriptor. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream * descriptor. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more data buffers to be written to the descriptor. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * descriptor.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } /// Read some data from the descriptor. /** * This function is used to read data from the stream descriptor. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * descriptor.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the descriptor. /** * This function is used to read data from the stream descriptor. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream * descriptor. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * descriptor.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: class initiate_async_write_some { public: typedef Executor executor_type; explicit initiate_async_write_some(basic_stream_descriptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_descriptor* self_; }; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_stream_descriptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_descriptor* self_; }; }; } // namespace posix } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_BASIC_STREAM_DESCRIPTOR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/posix/descriptor_base.hpp
// // posix/descriptor_base.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 ASIO_POSIX_DESCRIPTOR_BASE_HPP #define ASIO_POSIX_DESCRIPTOR_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/io_control.hpp" #include "asio/detail/socket_option.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace posix { /// The descriptor_base class is used as a base for the descriptor class as a /// place to define the associated IO control commands. class descriptor_base { public: /// Wait types. /** * For use with descriptor::wait() and descriptor::async_wait(). */ enum wait_type { /// Wait for a descriptor to become ready to read. wait_read, /// Wait for a descriptor to become ready to write. wait_write, /// Wait for a descriptor to have error conditions pending. wait_error }; /// IO control command to get the amount of data that can be read without /// blocking. /** * Implements the FIONREAD IO control command. * * @par Example * @code * asio::posix::stream_descriptor descriptor(my_context); * ... * asio::descriptor_base::bytes_readable command(true); * descriptor.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode * * @par Concepts: * IoControlCommand. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined bytes_readable; #else typedef asio::detail::io_control::bytes_readable bytes_readable; #endif protected: /// Protected destructor to prevent deletion through this type. ~descriptor_base() { } }; } // namespace posix } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_DESCRIPTOR_BASE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/posix/basic_descriptor.hpp
// // posix/basic_descriptor.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 ASIO_POSIX_BASIC_DESCRIPTOR_HPP #define ASIO_POSIX_BASIC_DESCRIPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/handler_type_requirements.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/non_const_lvalue.hpp" #include "asio/detail/throw_error.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/posix/descriptor_base.hpp" #if defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/io_uring_descriptor_service.hpp" #else // defined(ASIO_HAS_IO_URING_AS_DEFAULT) # include "asio/detail/reactive_descriptor_service.hpp" #endif // defined(ASIO_HAS_IO_URING_AS_DEFAULT) #include "asio/detail/push_options.hpp" namespace asio { namespace posix { /// Provides POSIX descriptor functionality. /** * The posix::basic_descriptor class template provides the ability to wrap a * POSIX descriptor. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_descriptor : public descriptor_base { private: class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the descriptor type to another executor. template <typename Executor1> struct rebind_executor { /// The descriptor type when rebound to the specified executor. typedef basic_descriptor<Executor1> other; }; /// The native representation of a descriptor. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #elif defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef detail::io_uring_descriptor_service::native_handle_type native_handle_type; #else // defined(ASIO_HAS_IO_URING_AS_DEFAULT) typedef detail::reactive_descriptor_service::native_handle_type native_handle_type; #endif // defined(ASIO_HAS_IO_URING_AS_DEFAULT) /// A descriptor is always the lowest layer. typedef basic_descriptor lowest_layer_type; /// Construct a descriptor without opening it. /** * This constructor creates a descriptor without opening it. * * @param ex The I/O executor that the descriptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * descriptor. */ explicit basic_descriptor(const executor_type& ex) : impl_(0, ex) { } /// Construct a descriptor without opening it. /** * This constructor creates a descriptor without opening it. * * @param context An execution context which provides the I/O executor that * the descriptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the descriptor. */ template <typename ExecutionContext> explicit basic_descriptor(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct a descriptor on an existing native descriptor. /** * This constructor creates a descriptor object to hold an existing native * descriptor. * * @param ex The I/O executor that the descriptor will use, by default, to * dispatch handlers for any asynchronous operations performed on the * descriptor. * * @param native_descriptor A native descriptor. * * @throws asio::system_error Thrown on failure. */ basic_descriptor(const executor_type& ex, const native_handle_type& native_descriptor) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_descriptor, ec); asio::detail::throw_error(ec, "assign"); } /// Construct a descriptor on an existing native descriptor. /** * This constructor creates a descriptor object to hold an existing native * descriptor. * * @param context An execution context which provides the I/O executor that * the descriptor will use, by default, to dispatch handlers for any * asynchronous operations performed on the descriptor. * * @param native_descriptor A native descriptor. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_descriptor(ExecutionContext& context, const native_handle_type& native_descriptor, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_descriptor, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct a descriptor from another. /** * This constructor moves a descriptor from one object to another. * * @param other The other descriptor object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_descriptor(const executor_type&) * constructor. */ basic_descriptor(basic_descriptor&& other) noexcept : impl_(std::move(other.impl_)) { } /// Move-assign a descriptor from another. /** * This assignment operator moves a descriptor from one object to another. * * @param other The other descriptor object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_descriptor(const executor_type&) * constructor. */ basic_descriptor& operator=(basic_descriptor&& other) { impl_ = std::move(other.impl_); return *this; } // All descriptors have access to each other's implementations. template <typename Executor1> friend class basic_descriptor; /// Move-construct a basic_descriptor from a descriptor of another executor /// type. /** * This constructor moves a descriptor from one object to another. * * @param other The other basic_descriptor object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_descriptor(const executor_type&) * constructor. */ template <typename Executor1> basic_descriptor(basic_descriptor<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign a basic_descriptor from a descriptor of another executor type. /** * This assignment operator moves a descriptor from one object to another. * * @param other The other basic_descriptor object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_descriptor(const executor_type&) * constructor. */ template <typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_descriptor& > operator=(basic_descriptor<Executor1> && other) { basic_descriptor tmp(std::move(other)); impl_ = std::move(tmp.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since a descriptor cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since a descriptor cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Assign an existing native descriptor to the descriptor. /* * This function opens the descriptor to hold an existing native descriptor. * * @param native_descriptor A native descriptor. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& native_descriptor) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_descriptor, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native descriptor to the descriptor. /* * This function opens the descriptor to hold an existing native descriptor. * * @param native_descriptor A native descriptor. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& native_descriptor, asio::error_code& ec) { impl_.get_service().assign( impl_.get_implementation(), native_descriptor, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the descriptor is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the descriptor. /** * This function is used to close the descriptor. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. Note that, even if * the function indicates an error, the underlying descriptor is closed. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the descriptor. /** * This function is used to close the descriptor. Any asynchronous read or * write operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. Note that, even if * the function indicates an error, the underlying descriptor is closed. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the native descriptor representation. /** * This function may be used to obtain the underlying representation of the * descriptor. This is intended to allow access to native descriptor * functionality that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Release ownership of the native descriptor implementation. /** * This function may be used to obtain the underlying representation of the * descriptor. After calling this function, @c is_open() returns false. The * caller is responsible for closing the descriptor. * * All outstanding asynchronous read or write operations will finish * immediately, and the handlers for cancelled operations will be passed the * asio::error::operation_aborted error. */ native_handle_type release() { return impl_.get_service().release(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the descriptor. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the descriptor. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform an IO control command on the descriptor. /** * This function is used to execute an IO control command on the descriptor. * * @param command The IO control command to be performed on the descriptor. * * @throws asio::system_error Thrown on failure. * * @sa IoControlCommand @n * asio::posix::descriptor_base::bytes_readable @n * asio::posix::descriptor_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::posix::stream_descriptor descriptor(my_context); * ... * asio::posix::stream_descriptor::bytes_readable command; * descriptor.io_control(command); * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> void io_control(IoControlCommand& command) { asio::error_code ec; impl_.get_service().io_control(impl_.get_implementation(), command, ec); asio::detail::throw_error(ec, "io_control"); } /// Perform an IO control command on the descriptor. /** * This function is used to execute an IO control command on the descriptor. * * @param command The IO control command to be performed on the descriptor. * * @param ec Set to indicate what error occurred, if any. * * @sa IoControlCommand @n * asio::posix::descriptor_base::bytes_readable @n * asio::posix::descriptor_base::non_blocking_io * * @par Example * Getting the number of bytes ready to read: * @code * asio::posix::stream_descriptor descriptor(my_context); * ... * asio::posix::stream_descriptor::bytes_readable command; * asio::error_code ec; * descriptor.io_control(command, ec); * if (ec) * { * // An error occurred. * } * std::size_t bytes_readable = command.get(); * @endcode */ template <typename IoControlCommand> ASIO_SYNC_OP_VOID io_control(IoControlCommand& command, asio::error_code& ec) { impl_.get_service().io_control(impl_.get_implementation(), command, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the descriptor. /** * @returns @c true if the descriptor's synchronous operations will fail with * asio::error::would_block if they are unable to perform the requested * operation immediately. If @c false, synchronous operations will block * until complete. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ bool non_blocking() const { return impl_.get_service().non_blocking(impl_.get_implementation()); } /// Sets the non-blocking mode of the descriptor. /** * @param mode If @c true, the descriptor's synchronous operations will fail * with asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @throws asio::system_error Thrown on failure. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ void non_blocking(bool mode) { asio::error_code ec; impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "non_blocking"); } /// Sets the non-blocking mode of the descriptor. /** * @param mode If @c true, the descriptor's synchronous operations will fail * with asio::error::would_block if they are unable to perform the * requested operation immediately. If @c false, synchronous operations will * block until complete. * * @param ec Set to indicate what error occurred, if any. * * @note The non-blocking mode has no effect on the behaviour of asynchronous * operations. Asynchronous operations will never fail with the error * asio::error::would_block. */ ASIO_SYNC_OP_VOID non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().non_blocking(impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Gets the non-blocking mode of the native descriptor implementation. /** * This function is used to retrieve the non-blocking mode of the underlying * native descriptor. This mode has no effect on the behaviour of the * descriptor object's synchronous operations. * * @returns @c true if the underlying descriptor is in non-blocking mode and * direct system calls may fail with asio::error::would_block (or the * equivalent system error). * * @note The current non-blocking mode is cached by the descriptor object. * Consequently, the return value may be incorrect if the non-blocking mode * was set directly on the native descriptor. */ bool native_non_blocking() const { return impl_.get_service().native_non_blocking( impl_.get_implementation()); } /// Sets the non-blocking mode of the native descriptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native descriptor. It has no effect on the behaviour of the descriptor * object's synchronous operations. * * @param mode If @c true, the underlying descriptor is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @throws asio::system_error Thrown on failure. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. */ void native_non_blocking(bool mode) { asio::error_code ec; impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); asio::detail::throw_error(ec, "native_non_blocking"); } /// Sets the non-blocking mode of the native descriptor implementation. /** * This function is used to modify the non-blocking mode of the underlying * native descriptor. It has no effect on the behaviour of the descriptor * object's synchronous operations. * * @param mode If @c true, the underlying descriptor is put into non-blocking * mode and direct system calls may fail with asio::error::would_block * (or the equivalent system error). * * @param ec Set to indicate what error occurred, if any. If the @c mode is * @c false, but the current value of @c non_blocking() is @c true, this * function fails with asio::error::invalid_argument, as the * combination does not make sense. */ ASIO_SYNC_OP_VOID native_non_blocking( bool mode, asio::error_code& ec) { impl_.get_service().native_non_blocking( impl_.get_implementation(), mode, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Wait for the descriptor to become ready to read, ready to write, or to /// have pending error conditions. /** * This function is used to perform a blocking wait for a descriptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired descriptor state. * * @par Example * Waiting for a descriptor to become readable. * @code * asio::posix::stream_descriptor descriptor(my_context); * ... * descriptor.wait(asio::posix::stream_descriptor::wait_read); * @endcode */ void wait(wait_type w) { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), w, ec); asio::detail::throw_error(ec, "wait"); } /// Wait for the descriptor to become ready to read, ready to write, or to /// have pending error conditions. /** * This function is used to perform a blocking wait for a descriptor to enter * a ready to read, write or error condition state. * * @param w Specifies the desired descriptor state. * * @param ec Set to indicate what error occurred, if any. * * @par Example * Waiting for a descriptor to become readable. * @code * asio::posix::stream_descriptor descriptor(my_context); * ... * asio::error_code ec; * descriptor.wait(asio::posix::stream_descriptor::wait_read, ec); * @endcode */ ASIO_SYNC_OP_VOID wait(wait_type w, asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), w, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Asynchronously wait for the descriptor to become ready to read, ready to /// write, or to have pending error conditions. /** * This function is used to perform an asynchronous wait for a descriptor to * enter a ready to read, write or error condition state. It is an initiating * function for an @ref asynchronous_operation, and always returns * immediately. * * @param w Specifies the desired descriptor state. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the wait completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode * * @par Example * @code * void wait_handler(const asio::error_code& error) * { * if (!error) * { * // Wait succeeded. * } * } * * ... * * asio::posix::stream_descriptor descriptor(my_context); * ... * descriptor.async_wait( * asio::posix::stream_descriptor::wait_read, * wait_handler); * @endcode * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait(wait_type w, WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token, w)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token, w); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the descriptor, cancelling any outstanding * asynchronous wait operations associated with the descriptor as if by * calling @c cancel. */ ~basic_descriptor() { } #if defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl<detail::io_uring_descriptor_service, Executor> impl_; #else // defined(ASIO_HAS_IO_URING_AS_DEFAULT) detail::io_object_impl<detail::reactive_descriptor_service, Executor> impl_; #endif // defined(ASIO_HAS_IO_URING_AS_DEFAULT) private: // Disallow copying and assignment. basic_descriptor(const basic_descriptor&) = delete; basic_descriptor& operator=(const basic_descriptor&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_descriptor* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler, wait_type w) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), w, handler2.value, self_->impl_.get_executor()); } private: basic_descriptor* self_; }; }; } // namespace posix } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_BASIC_DESCRIPTOR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/posix/descriptor.hpp
// // posix/descriptor.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 ASIO_POSIX_DESCRIPTOR_HPP #define ASIO_POSIX_DESCRIPTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) \ || defined(GENERATING_DOCUMENTATION) #include "asio/posix/basic_descriptor.hpp" namespace asio { namespace posix { /// Typedef for the typical usage of basic_descriptor. typedef basic_descriptor<> descriptor; } // namespace posix } // namespace asio #endif // defined(ASIO_HAS_POSIX_STREAM_DESCRIPTOR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_POSIX_DESCRIPTOR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/buffer.hpp
// // ts/buffer.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 ASIO_TS_BUFFER_HPP #define ASIO_TS_BUFFER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/buffer.hpp" #include "asio/completion_condition.hpp" #include "asio/read.hpp" #include "asio/write.hpp" #include "asio/read_until.hpp" #endif // ASIO_TS_BUFFER_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/timer.hpp
// // ts/timer.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 ASIO_TS_TIMER_HPP #define ASIO_TS_TIMER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/chrono.hpp" #include "asio/wait_traits.hpp" #include "asio/basic_waitable_timer.hpp" #include "asio/system_timer.hpp" #include "asio/steady_timer.hpp" #include "asio/high_resolution_timer.hpp" #endif // ASIO_TS_TIMER_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/io_context.hpp
// // ts/io_context.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 ASIO_TS_IO_CONTEXT_HPP #define ASIO_TS_IO_CONTEXT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/io_context.hpp" #endif // ASIO_TS_IO_CONTEXT_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/internet.hpp
// // ts/internet.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 ASIO_TS_INTERNET_HPP #define ASIO_TS_INTERNET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/ip/address.hpp" #include "asio/ip/address_v4.hpp" #include "asio/ip/address_v4_iterator.hpp" #include "asio/ip/address_v4_range.hpp" #include "asio/ip/address_v6.hpp" #include "asio/ip/address_v6_iterator.hpp" #include "asio/ip/address_v6_range.hpp" #include "asio/ip/bad_address_cast.hpp" #include "asio/ip/basic_endpoint.hpp" #include "asio/ip/basic_resolver_query.hpp" #include "asio/ip/basic_resolver_entry.hpp" #include "asio/ip/basic_resolver_iterator.hpp" #include "asio/ip/basic_resolver.hpp" #include "asio/ip/host_name.hpp" #include "asio/ip/network_v4.hpp" #include "asio/ip/network_v6.hpp" #include "asio/ip/tcp.hpp" #include "asio/ip/udp.hpp" #include "asio/ip/v6_only.hpp" #include "asio/ip/unicast.hpp" #include "asio/ip/multicast.hpp" #endif // ASIO_TS_INTERNET_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/net.hpp
// // ts/net.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 ASIO_TS_NET_HPP #define ASIO_TS_NET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/ts/netfwd.hpp" #include "asio/ts/executor.hpp" #include "asio/ts/io_context.hpp" #include "asio/ts/timer.hpp" #include "asio/ts/buffer.hpp" #include "asio/ts/socket.hpp" #include "asio/ts/internet.hpp" #endif // ASIO_TS_NET_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/netfwd.hpp
// // ts/netfwd.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 ASIO_TS_NETFWD_HPP #define ASIO_TS_NETFWD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/chrono.hpp" #if defined(ASIO_HAS_BOOST_DATE_TIME) # include "asio/detail/date_time_fwd.hpp" #endif // defined(ASIO_HAS_BOOST_DATE_TIME) #if !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #include "asio/execution/blocking.hpp" #include "asio/execution/outstanding_work.hpp" #include "asio/execution/relationship.hpp" #endif // !defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) #if !defined(GENERATING_DOCUMENTATION) #include "asio/detail/push_options.hpp" namespace asio { class execution_context; template <typename T, typename Executor> class executor_binder; #if !defined(ASIO_EXECUTOR_WORK_GUARD_DECL) #define ASIO_EXECUTOR_WORK_GUARD_DECL template <typename Executor, typename = void, typename = void> class executor_work_guard; #endif // !defined(ASIO_EXECUTOR_WORK_GUARD_DECL) template <typename Blocking, typename Relationship, typename Allocator> class basic_system_executor; #if defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) class executor; typedef executor any_io_executor; #else // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) namespace execution { #if !defined(ASIO_EXECUTION_ANY_EXECUTOR_FWD_DECL) #define ASIO_EXECUTION_ANY_EXECUTOR_FWD_DECL template <typename... SupportableProperties> class any_executor; #endif // !defined(ASIO_EXECUTION_ANY_EXECUTOR_FWD_DECL) template <typename U> struct context_as_t; template <typename Property> struct prefer_only; } // namespace execution class any_io_executor; #endif // defined(ASIO_USE_TS_EXECUTOR_AS_DEFAULT) template <typename Executor> class strand; class io_context; template <typename Clock> struct wait_traits; #if defined(ASIO_HAS_BOOST_DATE_TIME) template <typename Time> struct time_traits; #endif // defined(ASIO_HAS_BOOST_DATE_TIME) #if !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) #define ASIO_BASIC_WAITABLE_TIMER_FWD_DECL template <typename Clock, typename WaitTraits = wait_traits<Clock>, typename Executor = any_io_executor> class basic_waitable_timer; #endif // !defined(ASIO_BASIC_WAITABLE_TIMER_FWD_DECL) typedef basic_waitable_timer<chrono::system_clock> system_timer; typedef basic_waitable_timer<chrono::steady_clock> steady_timer; typedef basic_waitable_timer<chrono::high_resolution_clock> high_resolution_timer; #if !defined(ASIO_BASIC_SOCKET_FWD_DECL) #define ASIO_BASIC_SOCKET_FWD_DECL template <typename Protocol, typename Executor = any_io_executor> class basic_socket; #endif // !defined(ASIO_BASIC_SOCKET_FWD_DECL) #if !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) #define ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL template <typename Protocol, typename Executor = any_io_executor> class basic_datagram_socket; #endif // !defined(ASIO_BASIC_DATAGRAM_SOCKET_FWD_DECL) #if !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) #define ASIO_BASIC_STREAM_SOCKET_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, typename Executor = any_io_executor> class basic_stream_socket; #endif // !defined(ASIO_BASIC_STREAM_SOCKET_FWD_DECL) #if !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) #define ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL template <typename Protocol, typename Executor = any_io_executor> class basic_socket_acceptor; #endif // !defined(ASIO_BASIC_SOCKET_ACCEPTOR_FWD_DECL) #if !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) #define ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif class basic_socket_streambuf; #endif // !defined(ASIO_BASIC_SOCKET_STREAMBUF_FWD_DECL) #if !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) #define ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL // Forward declaration with defaulted arguments. template <typename Protocol, #if defined(ASIO_HAS_BOOST_DATE_TIME) \ || defined(GENERATING_DOCUMENTATION) typename Clock = boost::posix_time::ptime, typename WaitTraits = time_traits<Clock>> #else typename Clock = chrono::steady_clock, typename WaitTraits = wait_traits<Clock>> #endif class basic_socket_iostream; #endif // !defined(ASIO_BASIC_SOCKET_IOSTREAM_FWD_DECL) namespace ip { class address; class address_v4; class address_v6; template <typename Address> class basic_address_iterator; typedef basic_address_iterator<address_v4> address_v4_iterator; typedef basic_address_iterator<address_v6> address_v6_iterator; template <typename Address> class basic_address_range; typedef basic_address_range<address_v4> address_v4_range; typedef basic_address_range<address_v6> address_v6_range; class network_v4; class network_v6; template <typename InternetProtocol> class basic_endpoint; template <typename InternetProtocol> class basic_resolver_entry; template <typename InternetProtocol> class basic_resolver_results; #if !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) #define ASIO_IP_BASIC_RESOLVER_FWD_DECL template <typename InternetProtocol, typename Executor = any_io_executor> class basic_resolver; #endif // !defined(ASIO_IP_BASIC_RESOLVER_FWD_DECL) class tcp; class udp; } // namespace ip } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(GENERATING_DOCUMENTATION) #endif // ASIO_TS_NETFWD_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/executor.hpp
// // ts/executor.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 ASIO_TS_EXECUTOR_HPP #define ASIO_TS_EXECUTOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/async_result.hpp" #include "asio/associated_allocator.hpp" #include "asio/execution_context.hpp" #include "asio/is_executor.hpp" #include "asio/associated_executor.hpp" #include "asio/bind_executor.hpp" #include "asio/executor_work_guard.hpp" #include "asio/system_executor.hpp" #include "asio/executor.hpp" #include "asio/any_io_executor.hpp" #include "asio/dispatch.hpp" #include "asio/post.hpp" #include "asio/defer.hpp" #include "asio/strand.hpp" #include "asio/packaged_task.hpp" #include "asio/use_future.hpp" #endif // ASIO_TS_EXECUTOR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/ts/socket.hpp
// // ts/socket.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 ASIO_TS_SOCKET_HPP #define ASIO_TS_SOCKET_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/socket_base.hpp" #include "asio/basic_socket.hpp" #include "asio/basic_datagram_socket.hpp" #include "asio/basic_stream_socket.hpp" #include "asio/basic_socket_acceptor.hpp" #include "asio/basic_socket_streambuf.hpp" #include "asio/basic_socket_iostream.hpp" #include "asio/connect.hpp" #endif // ASIO_TS_SOCKET_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/basic_overlapped_handle.hpp
// // windows/basic_overlapped_handle.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 ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP #define ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include <cstddef> #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/win_iocp_handle_service.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace windows { /// Provides Windows handle functionality for objects that support /// overlapped I/O. /** * The windows::overlapped_handle class provides the ability to wrap a Windows * handle. The underlying object referred to by the handle must support * overlapped I/O. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_overlapped_handle { public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the handle type to another executor. template <typename Executor1> struct rebind_executor { /// The handle type when rebound to the specified executor. typedef basic_overlapped_handle<Executor1> other; }; /// The native representation of a handle. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef asio::detail::win_iocp_handle_service::native_handle_type native_handle_type; #endif /// An overlapped_handle is always the lowest layer. typedef basic_overlapped_handle lowest_layer_type; /// Construct an overlapped handle without opening it. /** * This constructor creates an overlapped handle without opening it. * * @param ex The I/O executor that the overlapped handle will use, by default, * to dispatch handlers for any asynchronous operations performed on the * overlapped handle. */ explicit basic_overlapped_handle(const executor_type& ex) : impl_(0, ex) { } /// Construct an overlapped handle without opening it. /** * This constructor creates an overlapped handle without opening it. * * @param context An execution context which provides the I/O executor that * the overlapped handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the overlapped handle. */ template <typename ExecutionContext> explicit basic_overlapped_handle(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct an overlapped handle on an existing native handle. /** * This constructor creates an overlapped handle object to hold an existing * native handle. * * @param ex The I/O executor that the overlapped handle will use, by default, * to dispatch handlers for any asynchronous operations performed on the * overlapped handle. * * @param native_handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ basic_overlapped_handle(const executor_type& ex, const native_handle_type& native_handle) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); asio::detail::throw_error(ec, "assign"); } /// Construct an overlapped handle on an existing native handle. /** * This constructor creates an overlapped handle object to hold an existing * native handle. * * @param context An execution context which provides the I/O executor that * the overlapped handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the overlapped handle. * * @param native_handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_overlapped_handle(ExecutionContext& context, const native_handle_type& native_handle, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct an overlapped handle from another. /** * This constructor moves a handle from one object to another. * * @param other The other overlapped handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c overlapped_handle(const executor_type&) * constructor. */ basic_overlapped_handle(basic_overlapped_handle&& other) : impl_(std::move(other.impl_)) { } /// Move-assign an overlapped handle from another. /** * This assignment operator moves a handle from one object to another. * * @param other The other overlapped handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c overlapped_handle(const executor_type&) * constructor. */ basic_overlapped_handle& operator=(basic_overlapped_handle&& other) { impl_ = std::move(other.impl_); return *this; } // All overlapped handles have access to each other's implementations. template <typename Executor1> friend class basic_overlapped_handle; /// Move-construct an overlapped handle from a handle of another executor /// type. /** * This constructor moves a handle from one object to another. * * @param other The other overlapped handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c overlapped_handle(const executor_type&) * constructor. */ template<typename Executor1> basic_overlapped_handle(basic_overlapped_handle<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign an overlapped handle from a handle of another executor type. /** * This assignment operator moves a handle from one object to another. * * @param other The other overlapped handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c overlapped_handle(const executor_type&) * constructor. */ template<typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_overlapped_handle& > operator=(basic_overlapped_handle<Executor1>&& other) { impl_ = std::move(other.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since an overlapped_handle cannot contain any further layers, it * simply returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since an overlapped_handle cannot contain any further layers, it * simply returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Assign an existing native handle to the handle. /* * This function opens the handle to hold an existing native handle. * * @param handle A native handle. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& handle) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), handle, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native handle to the handle. /* * This function opens the handle to hold an existing native handle. * * @param handle A native handle. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& handle, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), handle, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the handle is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the handle. /** * This function is used to close the handle. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the handle. /** * This function is used to close the handle. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Release ownership of the underlying native handle. /** * This function causes all outstanding asynchronous operations to finish * immediately, and the handlers for cancelled operations will be passed the * asio::error::operation_aborted error. Ownership of the native handle * is then transferred to the caller. * * @throws asio::system_error Thrown on failure. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release() { asio::error_code ec; native_handle_type s = impl_.get_service().release( impl_.get_implementation(), ec); asio::detail::throw_error(ec, "release"); return s; } /// Release ownership of the underlying native handle. /** * This function causes all outstanding asynchronous operations to finish * immediately, and the handlers for cancelled operations will be passed the * asio::error::operation_aborted error. Ownership of the native handle * is then transferred to the caller. * * @param ec Set to indicate what error occurred, if any. * * @note This function is unsupported on Windows versions prior to Windows * 8.1, and will fail with asio::error::operation_not_supported on * these platforms. */ #if defined(ASIO_MSVC) && (ASIO_MSVC >= 1400) \ && (!defined(_WIN32_WINNT) || _WIN32_WINNT < 0x0603) __declspec(deprecated("This function always fails with " "operation_not_supported when used on Windows versions " "prior to Windows 8.1.")) #endif native_handle_type release(asio::error_code& ec) { return impl_.get_service().release(impl_.get_implementation(), ec); } /// Get the native handle representation. /** * This function may be used to obtain the underlying representation of the * handle. This is intended to allow access to native handle functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the handle. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the handle. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } protected: /// Protected destructor to prevent deletion through this type. /** * This function destroys the handle, cancelling any outstanding asynchronous * wait operations associated with the handle as if by calling @c cancel. */ ~basic_overlapped_handle() { } asio::detail::io_object_impl< asio::detail::win_iocp_handle_service, Executor> impl_; private: // Disallow copying and assignment. basic_overlapped_handle(const basic_overlapped_handle&) = delete; basic_overlapped_handle& operator=( const basic_overlapped_handle&) = delete; }; } // namespace windows } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) // || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_BASIC_OVERLAPPED_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/overlapped_ptr.hpp
// // windows/overlapped_ptr.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 ASIO_WINDOWS_OVERLAPPED_PTR_HPP #define ASIO_WINDOWS_OVERLAPPED_PTR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/noncopyable.hpp" #include "asio/detail/win_iocp_overlapped_ptr.hpp" #include "asio/io_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace windows { /// Wraps a handler to create an OVERLAPPED object for use with overlapped I/O. /** * A special-purpose smart pointer used to wrap an application handler so that * it can be passed as the LPOVERLAPPED argument to overlapped I/O functions. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ class overlapped_ptr : private noncopyable { public: /// Construct an empty overlapped_ptr. overlapped_ptr() : impl_() { } /// Construct an overlapped_ptr to contain the specified handler. template <typename ExecutionContext, typename Handler> explicit overlapped_ptr(ExecutionContext& context, Handler&& handler, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(context.get_executor(), static_cast<Handler&&>(handler)) { } /// Construct an overlapped_ptr to contain the specified handler. template <typename Executor, typename Handler> explicit overlapped_ptr(const Executor& ex, Handler&& handler, constraint_t< execution::is_executor<Executor>::value || is_executor<Executor>::value > = 0) : impl_(ex, static_cast<Handler&&>(handler)) { } /// Destructor automatically frees the OVERLAPPED object unless released. ~overlapped_ptr() { } /// Reset to empty. void reset() { impl_.reset(); } /// Reset to contain the specified handler, freeing any current OVERLAPPED /// object. template <typename ExecutionContext, typename Handler> void reset(ExecutionContext& context, Handler&& handler, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) { impl_.reset(context.get_executor(), static_cast<Handler&&>(handler)); } /// Reset to contain the specified handler, freeing any current OVERLAPPED /// object. template <typename Executor, typename Handler> void reset(const Executor& ex, Handler&& handler, constraint_t< execution::is_executor<Executor>::value || is_executor<Executor>::value > = 0) { impl_.reset(ex, static_cast<Handler&&>(handler)); } /// Get the contained OVERLAPPED object. OVERLAPPED* get() { return impl_.get(); } /// Get the contained OVERLAPPED object. const OVERLAPPED* get() const { return impl_.get(); } /// Release ownership of the OVERLAPPED object. OVERLAPPED* release() { return impl_.release(); } /// Post completion notification for overlapped operation. Releases ownership. void complete(const asio::error_code& ec, std::size_t bytes_transferred) { impl_.complete(ec, bytes_transferred); } private: detail::win_iocp_overlapped_ptr impl_; }; } // namespace windows } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_WINDOWS_OVERLAPPED_PTR) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_OVERLAPPED_PTR_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/overlapped_handle.hpp
// // windows/overlapped_handle.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 ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP #define ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/windows/basic_overlapped_handle.hpp" namespace asio { namespace windows { /// Typedef for the typical usage of an overlapped handle. typedef basic_overlapped_handle<> overlapped_handle; } // namespace windows } // namespace asio #endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) // || defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_OVERLAPPED_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/object_handle.hpp
// // windows/object_handle.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2011 Boris Schaeling ([email protected]) // // 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 ASIO_WINDOWS_OBJECT_HANDLE_HPP #define ASIO_WINDOWS_OBJECT_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/windows/basic_object_handle.hpp" namespace asio { namespace windows { /// Typedef for the typical usage of an object handle. typedef basic_object_handle<> object_handle; } // namespace windows } // namespace asio #endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_OBJECT_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/basic_stream_handle.hpp
// // windows/basic_stream_handle.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 ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP #define ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/windows/basic_overlapped_handle.hpp" #if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/push_options.hpp" namespace asio { namespace windows { /// Provides stream-oriented handle functionality. /** * The windows::basic_stream_handle class provides asynchronous and blocking * stream-oriented handle functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. * * @par Concepts: * AsyncReadStream, AsyncWriteStream, Stream, SyncReadStream, SyncWriteStream. */ template <typename Executor = any_io_executor> class basic_stream_handle : public basic_overlapped_handle<Executor> { private: class initiate_async_write_some; class initiate_async_read_some; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the handle type to another executor. template <typename Executor1> struct rebind_executor { /// The handle type when rebound to the specified executor. typedef basic_stream_handle<Executor1> other; }; /// The native representation of a handle. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef asio::detail::win_iocp_handle_service::native_handle_type native_handle_type; #endif /// Construct a stream handle without opening it. /** * This constructor creates a stream handle without opening it. * * @param ex The I/O executor that the stream handle will use, by default, to * dispatch handlers for any asynchronous operations performed on the stream * handle. */ explicit basic_stream_handle(const executor_type& ex) : basic_overlapped_handle<Executor>(ex) { } /// Construct a stream handle without opening it. /** * This constructor creates a stream handle without opening it. The handle * needs to be opened or assigned before data can be written to or read from * it. * * @param context An execution context which provides the I/O executor that * the stream handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the stream handle. */ template <typename ExecutionContext> explicit basic_stream_handle(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_overlapped_handle<Executor>(context) { } /// Construct a stream handle on an existing native handle. /** * This constructor creates a stream handle object to hold an existing native * handle. * * @param ex The I/O executor that the stream handle will use, by default, to * dispatch handlers for any asynchronous operations performed on the stream * handle. * * @param handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ basic_stream_handle(const executor_type& ex, const native_handle_type& handle) : basic_overlapped_handle<Executor>(ex, handle) { } /// Construct a stream handle on an existing native handle. /** * This constructor creates a stream handle object to hold an existing native * handle. * * @param context An execution context which provides the I/O executor that * the stream handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the stream handle. * * @param handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_stream_handle(ExecutionContext& context, const native_handle_type& handle, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_overlapped_handle<Executor>(context, handle) { } /// Move-construct a stream handle from another. /** * This constructor moves a stream handle from one object to another. * * @param other The other stream handle object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_handle(const executor_type&) * constructor. */ basic_stream_handle(basic_stream_handle&& other) : basic_overlapped_handle<Executor>(std::move(other)) { } /// Move-assign a stream handle from another. /** * This assignment operator moves a stream handle from one object to * another. * * @param other The other stream handle object from which the move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_handle(const executor_type&) * constructor. */ basic_stream_handle& operator=(basic_stream_handle&& other) { basic_overlapped_handle<Executor>::operator=(std::move(other)); return *this; } /// Move-construct a stream handle from a handle of another executor type. /** * This constructor moves a stream handle from one object to another. * * @param other The other stream handle object from which the move * will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_handle(const executor_type&) * constructor. */ template<typename Executor1> basic_stream_handle(basic_stream_handle<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : basic_overlapped_handle<Executor>(std::move(other)) { } /// Move-assign a stream handle from a handle of another executor type. /** * This assignment operator moves a stream handle from one object to * another. * * @param other The other stream handle object from which the move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_stream_handle(const executor_type&) * constructor. */ template<typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_stream_handle& > operator=(basic_stream_handle<Executor1>&& other) { basic_overlapped_handle<Executor>::operator=(std::move(other)); return *this; } /// Write some data to the handle. /** * This function is used to write data to the stream handle. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the handle. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.write_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "write_some"); return s; } /// Write some data to the handle. /** * This function is used to write data to the stream handle. The function call * will block until one or more bytes of the data has been written * successfully, or until an error occurs. * * @param buffers One or more data buffers to be written to the handle. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some(const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().write_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous write. /** * This function is used to asynchronously write data to the stream handle. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more data buffers to be written to the handle. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write function if you need to ensure that all * data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.async_write_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some(const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some>(), token, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some(this), token, buffers); } /// Read some data from the handle. /** * This function is used to read data from the stream handle. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.read_some(asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); asio::detail::throw_error(ec, "read_some"); return s; } /// Read some data from the handle. /** * This function is used to read data from the stream handle. The function * call will block until one or more bytes of data has been read successfully, * or until an error occurs. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some(const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().read_some( this->impl_.get_implementation(), buffers, ec); } /// Start an asynchronous read. /** * This function is used to asynchronously read data from the stream handle. * It is an initiating function for an @ref asynchronous_operation, and always * returns immediately. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read function if you need to ensure that the * requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.async_read_some(asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some(const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some>(), token, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some(this), token, buffers); } private: class initiate_async_write_some { public: typedef Executor executor_type; explicit initiate_async_write_some(basic_stream_handle* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_handle* self_; }; class initiate_async_read_some { public: typedef Executor executor_type; explicit initiate_async_read_some(basic_stream_handle* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some( self_->impl_.get_implementation(), buffers, handler2.value, self_->impl_.get_executor()); } private: basic_stream_handle* self_; }; }; } // namespace windows } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_BASIC_STREAM_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/basic_random_access_handle.hpp
// // windows/basic_random_access_handle.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 ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP #define ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/windows/basic_overlapped_handle.hpp" #if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/detail/push_options.hpp" namespace asio { namespace windows { /// Provides random-access handle functionality. /** * The windows::basic_random_access_handle class provides asynchronous and * blocking random-access handle functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_random_access_handle : public basic_overlapped_handle<Executor> { private: class initiate_async_write_some_at; class initiate_async_read_some_at; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the handle type to another executor. template <typename Executor1> struct rebind_executor { /// The handle type when rebound to the specified executor. typedef basic_random_access_handle<Executor1> other; }; /// The native representation of a handle. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef asio::detail::win_iocp_handle_service::native_handle_type native_handle_type; #endif /// Construct a random-access handle without opening it. /** * This constructor creates a random-access handle without opening it. * * @param ex The I/O executor that the random-access handle will use, by * default, to dispatch handlers for any asynchronous operations performed on * the random-access handle. */ explicit basic_random_access_handle(const executor_type& ex) : basic_overlapped_handle<Executor>(ex) { } /// Construct a random-access handle without opening it. /** * This constructor creates a random-access handle without opening it. The * handle needs to be opened or assigned before data can be written to or read * from it. * * @param context An execution context which provides the I/O executor that * the random-access handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the random-access handle. */ template <typename ExecutionContext> explicit basic_random_access_handle(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : basic_overlapped_handle<Executor>(context) { } /// Construct a random-access handle on an existing native handle. /** * This constructor creates a random-access handle object to hold an existing * native handle. * * @param ex The I/O executor that the random-access handle will use, by * default, to dispatch handlers for any asynchronous operations performed on * the random-access handle. * * @param handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ basic_random_access_handle(const executor_type& ex, const native_handle_type& handle) : basic_overlapped_handle<Executor>(ex, handle) { } /// Construct a random-access handle on an existing native handle. /** * This constructor creates a random-access handle object to hold an existing * native handle. * * @param context An execution context which provides the I/O executor that * the random-access handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the random-access handle. * * @param handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_random_access_handle(ExecutionContext& context, const native_handle_type& handle, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : basic_overlapped_handle<Executor>(context, handle) { } /// Move-construct a random-access handle from another. /** * This constructor moves a random-access handle from one object to another. * * @param other The other random-access handle object from which the * move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_handle(const executor_type&) * constructor. */ basic_random_access_handle(basic_random_access_handle&& other) : basic_overlapped_handle<Executor>(std::move(other)) { } /// Move-assign a random-access handle from another. /** * This assignment operator moves a random-access handle from one object to * another. * * @param other The other random-access handle object from which the * move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_handle(const executor_type&) * constructor. */ basic_random_access_handle& operator=(basic_random_access_handle&& other) { basic_overlapped_handle<Executor>::operator=(std::move(other)); return *this; } /// Move-construct a random-access handle from a handle of another executor /// type. /** * This constructor moves a random-access handle from one object to another. * * @param other The other random-access handle object from which the * move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_handle(const executor_type&) * constructor. */ template<typename Executor1> basic_random_access_handle(basic_random_access_handle<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : basic_overlapped_handle<Executor>(std::move(other)) { } /// Move-assign a random-access handle from a handle of another executor /// type. /** * This assignment operator moves a random-access handle from one object to * another. * * @param other The other random-access handle object from which the * move will occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_random_access_handle(const executor_type&) * constructor. */ template<typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_random_access_handle& > operator=(basic_random_access_handle<Executor1>&& other) { basic_overlapped_handle<Executor>::operator=(std::move(other)); return *this; } /// Write some data to the handle at the specified offset. /** * This function is used to write data to the random-access handle. The * function call will block until one or more bytes of the data has been * written successfully, or until an error occurs. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * * @returns The number of bytes written. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The write_some_at operation may not write all of the data. Consider * using the @ref write_at function if you need to ensure that all data is * written before the blocking operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.write_some_at(42, asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename ConstBufferSequence> std::size_t write_some_at(uint64_t offset, const ConstBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().write_some_at( this->impl_.get_implementation(), offset, buffers, ec); asio::detail::throw_error(ec, "write_some_at"); return s; } /// Write some data to the handle at the specified offset. /** * This function is used to write data to the random-access handle. The * function call will block until one or more bytes of the data has been * written successfully, or until an error occurs. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes written. Returns 0 if an error occurred. * * @note The write_some operation may not transmit all of the data to the * peer. Consider using the @ref write_at function if you need to ensure that * all data is written before the blocking operation completes. */ template <typename ConstBufferSequence> std::size_t write_some_at(uint64_t offset, const ConstBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().write_some_at( this->impl_.get_implementation(), offset, buffers, ec); } /// Start an asynchronous write at the specified offset. /** * This function is used to asynchronously write data to the random-access * handle. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param offset The offset at which the data will be written. * * @param buffers One or more data buffers to be written to the handle. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the write completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes written. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The write operation may not transmit all of the data to the peer. * Consider using the @ref async_write_at function if you need to ensure that * all data is written before the asynchronous operation completes. * * @par Example * To write a single data buffer use the @ref buffer function as follows: * @code * handle.async_write_some_at(42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on writing multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename ConstBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) WriteToken = default_completion_token_t<executor_type>> auto async_write_some_at(uint64_t offset, const ConstBufferSequence& buffers, WriteToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WriteToken, void (asio::error_code, std::size_t)>( declval<initiate_async_write_some_at>(), token, offset, buffers)) { return async_initiate<WriteToken, void (asio::error_code, std::size_t)>( initiate_async_write_some_at(this), token, offset, buffers); } /// Read some data from the handle at the specified offset. /** * This function is used to read data from the random-access handle. The * function call will block until one or more bytes of data has been read * successfully, or until an error occurs. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * * @returns The number of bytes read. * * @throws asio::system_error Thrown on failure. An error code of * asio::error::eof indicates that the connection was closed by the * peer. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read_at function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.read_some_at(42, asio::buffer(data, size)); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename MutableBufferSequence> std::size_t read_some_at(uint64_t offset, const MutableBufferSequence& buffers) { asio::error_code ec; std::size_t s = this->impl_.get_service().read_some_at( this->impl_.get_implementation(), offset, buffers, ec); asio::detail::throw_error(ec, "read_some_at"); return s; } /// Read some data from the handle at the specified offset. /** * This function is used to read data from the random-access handle. The * function call will block until one or more bytes of data has been read * successfully, or until an error occurs. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. Returns 0 if an error occurred. * * @note The read_some operation may not read all of the requested number of * bytes. Consider using the @ref read_at function if you need to ensure that * the requested amount of data is read before the blocking operation * completes. */ template <typename MutableBufferSequence> std::size_t read_some_at(uint64_t offset, const MutableBufferSequence& buffers, asio::error_code& ec) { return this->impl_.get_service().read_some_at( this->impl_.get_implementation(), offset, buffers, ec); } /// Start an asynchronous read at the specified offset. /** * This function is used to asynchronously read data from the random-access * handle. It is an initiating function for an @ref asynchronous_operation, * and always returns immediately. * * @param offset The offset at which the data will be read. * * @param buffers One or more buffers into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the completion handler is called. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the read completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * std::size_t bytes_transferred // Number of bytes read. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code, std::size_t) @endcode * * @note The read operation may not read all of the requested number of bytes. * Consider using the @ref async_read_at function if you need to ensure that * the requested amount of data is read before the asynchronous operation * completes. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * handle.async_read_some_at(42, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @par Per-Operation Cancellation * This asynchronous operation supports cancellation for the following * asio::cancellation_type values: * * @li @c cancellation_type::terminal * * @li @c cancellation_type::partial * * @li @c cancellation_type::total */ template <typename MutableBufferSequence, ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code, std::size_t)) ReadToken = default_completion_token_t<executor_type>> auto async_read_some_at(uint64_t offset, const MutableBufferSequence& buffers, ReadToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<ReadToken, void (asio::error_code, std::size_t)>( declval<initiate_async_read_some_at>(), token, offset, buffers)) { return async_initiate<ReadToken, void (asio::error_code, std::size_t)>( initiate_async_read_some_at(this), token, offset, buffers); } private: class initiate_async_write_some_at { public: typedef Executor executor_type; explicit initiate_async_write_some_at(basic_random_access_handle* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WriteHandler, typename ConstBufferSequence> void operator()(WriteHandler&& handler, uint64_t offset, const ConstBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WriteHandler. ASIO_WRITE_HANDLER_CHECK(WriteHandler, handler) type_check; detail::non_const_lvalue<WriteHandler> handler2(handler); self_->impl_.get_service().async_write_some_at( self_->impl_.get_implementation(), offset, buffers, handler2.value, self_->impl_.get_executor()); } private: basic_random_access_handle* self_; }; class initiate_async_read_some_at { public: typedef Executor executor_type; explicit initiate_async_read_some_at(basic_random_access_handle* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename ReadHandler, typename MutableBufferSequence> void operator()(ReadHandler&& handler, uint64_t offset, const MutableBufferSequence& buffers) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a ReadHandler. ASIO_READ_HANDLER_CHECK(ReadHandler, handler) type_check; detail::non_const_lvalue<ReadHandler> handler2(handler); self_->impl_.get_service().async_read_some_at( self_->impl_.get_implementation(), offset, buffers, handler2.value, self_->impl_.get_executor()); } private: basic_random_access_handle* self_; }; }; } // namespace windows } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_BASIC_RANDOM_ACCESS_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/basic_object_handle.hpp
// // windows/basic_object_handle.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2011 Boris Schaeling ([email protected]) // // 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 ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP #define ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include <utility> #include "asio/any_io_executor.hpp" #include "asio/async_result.hpp" #include "asio/detail/io_object_impl.hpp" #include "asio/detail/throw_error.hpp" #include "asio/detail/win_object_handle_service.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace windows { /// Provides object-oriented handle functionality. /** * The windows::basic_object_handle class provides asynchronous and blocking * object-oriented handle functionality. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename Executor = any_io_executor> class basic_object_handle { private: class initiate_async_wait; public: /// The type of the executor associated with the object. typedef Executor executor_type; /// Rebinds the handle type to another executor. template <typename Executor1> struct rebind_executor { /// The handle type when rebound to the specified executor. typedef basic_object_handle<Executor1> other; }; /// The native representation of a handle. #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined native_handle_type; #else typedef asio::detail::win_object_handle_service::native_handle_type native_handle_type; #endif /// An object handle is always the lowest layer. typedef basic_object_handle lowest_layer_type; /// Construct an object handle without opening it. /** * This constructor creates an object handle without opening it. * * @param ex The I/O executor that the object handle will use, by default, to * dispatch handlers for any asynchronous operations performed on the * object handle. */ explicit basic_object_handle(const executor_type& ex) : impl_(0, ex) { } /// Construct an object handle without opening it. /** * This constructor creates an object handle without opening it. * * @param context An execution context which provides the I/O executor that * the object handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the object handle. */ template <typename ExecutionContext> explicit basic_object_handle(ExecutionContext& context, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value, defaulted_constraint > = defaulted_constraint()) : impl_(0, 0, context) { } /// Construct an object handle on an existing native handle. /** * This constructor creates an object handle object to hold an existing native * handle. * * @param ex The I/O executor that the object handle will use, by default, to * dispatch handlers for any asynchronous operations performed on the * object handle. * * @param native_handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ basic_object_handle(const executor_type& ex, const native_handle_type& native_handle) : impl_(0, ex) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); asio::detail::throw_error(ec, "assign"); } /// Construct an object handle on an existing native handle. /** * This constructor creates an object handle object to hold an existing native * handle. * * @param context An execution context which provides the I/O executor that * the object handle will use, by default, to dispatch handlers for any * asynchronous operations performed on the object handle. * * @param native_handle The new underlying handle implementation. * * @throws asio::system_error Thrown on failure. */ template <typename ExecutionContext> basic_object_handle(ExecutionContext& context, const native_handle_type& native_handle, constraint_t< is_convertible<ExecutionContext&, execution_context&>::value > = 0) : impl_(0, 0, context) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), native_handle, ec); asio::detail::throw_error(ec, "assign"); } /// Move-construct an object handle from another. /** * This constructor moves an object handle from one object to another. * * @param other The other object handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_object_handle(const executor_type&) * constructor. */ basic_object_handle(basic_object_handle&& other) : impl_(std::move(other.impl_)) { } /// Move-assign an object handle from another. /** * This assignment operator moves an object handle from one object to another. * * @param other The other object handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_object_handle(const executor_type&) * constructor. */ basic_object_handle& operator=(basic_object_handle&& other) { impl_ = std::move(other.impl_); return *this; } // All handles have access to each other's implementations. template <typename Executor1> friend class basic_object_handle; /// Move-construct an object handle from a handle of another executor type. /** * This constructor moves an object handle from one object to another. * * @param other The other object handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_object_handle(const executor_type&) * constructor. */ template<typename Executor1> basic_object_handle(basic_object_handle<Executor1>&& other, constraint_t< is_convertible<Executor1, Executor>::value, defaulted_constraint > = defaulted_constraint()) : impl_(std::move(other.impl_)) { } /// Move-assign an object handle from a handle of another executor type. /** * This assignment operator moves an object handle from one object to another. * * @param other The other object handle object from which the move will * occur. * * @note Following the move, the moved-from object is in the same state as if * constructed using the @c basic_object_handle(const executor_type&) * constructor. */ template<typename Executor1> constraint_t< is_convertible<Executor1, Executor>::value, basic_object_handle& > operator=(basic_object_handle<Executor1>&& other) { impl_ = std::move(other.impl_); return *this; } /// Get the executor associated with the object. const executor_type& get_executor() noexcept { return impl_.get_executor(); } /// Get a reference to the lowest layer. /** * This function returns a reference to the lowest layer in a stack of * layers. Since an object handle cannot contain any further layers, it simply * returns a reference to itself. * * @return A reference to the lowest layer in the stack of layers. Ownership * is not transferred to the caller. */ lowest_layer_type& lowest_layer() { return *this; } /// Get a const reference to the lowest layer. /** * This function returns a const reference to the lowest layer in a stack of * layers. Since an object handle cannot contain any further layers, it simply * returns a reference to itself. * * @return A const reference to the lowest layer in the stack of layers. * Ownership is not transferred to the caller. */ const lowest_layer_type& lowest_layer() const { return *this; } /// Assign an existing native handle to the handle. /* * This function opens the handle to hold an existing native handle. * * @param handle A native handle. * * @throws asio::system_error Thrown on failure. */ void assign(const native_handle_type& handle) { asio::error_code ec; impl_.get_service().assign(impl_.get_implementation(), handle, ec); asio::detail::throw_error(ec, "assign"); } /// Assign an existing native handle to the handle. /* * This function opens the handle to hold an existing native handle. * * @param handle A native handle. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID assign(const native_handle_type& handle, asio::error_code& ec) { impl_.get_service().assign(impl_.get_implementation(), handle, ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Determine whether the handle is open. bool is_open() const { return impl_.get_service().is_open(impl_.get_implementation()); } /// Close the handle. /** * This function is used to close the handle. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void close() { asio::error_code ec; impl_.get_service().close(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "close"); } /// Close the handle. /** * This function is used to close the handle. Any asynchronous read or write * operations will be cancelled immediately, and will complete with the * asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID close(asio::error_code& ec) { impl_.get_service().close(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Get the native handle representation. /** * This function may be used to obtain the underlying representation of the * handle. This is intended to allow access to native handle functionality * that is not otherwise provided. */ native_handle_type native_handle() { return impl_.get_service().native_handle(impl_.get_implementation()); } /// Cancel all asynchronous operations associated with the handle. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @throws asio::system_error Thrown on failure. */ void cancel() { asio::error_code ec; impl_.get_service().cancel(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "cancel"); } /// Cancel all asynchronous operations associated with the handle. /** * This function causes all outstanding asynchronous read or write operations * to finish immediately, and the handlers for cancelled operations will be * passed the asio::error::operation_aborted error. * * @param ec Set to indicate what error occurred, if any. */ ASIO_SYNC_OP_VOID cancel(asio::error_code& ec) { impl_.get_service().cancel(impl_.get_implementation(), ec); ASIO_SYNC_OP_VOID_RETURN(ec); } /// Perform a blocking wait on the object handle. /** * This function is used to wait for the object handle to be set to the * signalled state. This function blocks and does not return until the object * handle has been set to the signalled state. * * @throws asio::system_error Thrown on failure. */ void wait() { asio::error_code ec; impl_.get_service().wait(impl_.get_implementation(), ec); asio::detail::throw_error(ec, "wait"); } /// Perform a blocking wait on the object handle. /** * This function is used to wait for the object handle to be set to the * signalled state. This function blocks and does not return until the object * handle has been set to the signalled state. * * @param ec Set to indicate what error occurred, if any. */ void wait(asio::error_code& ec) { impl_.get_service().wait(impl_.get_implementation(), ec); } /// Start an asynchronous wait on the object handle. /** * This function is be used to initiate an asynchronous wait against the * object handle. It is an initiating function for an @ref * asynchronous_operation, and always returns immediately. * * @param token The @ref completion_token that will be used to produce a * completion handler, which will be called when the wait completes. * Potential completion tokens include @ref use_future, @ref use_awaitable, * @ref yield_context, or a function object with the correct completion * signature. The function signature of the completion handler must be: * @code void handler( * const asio::error_code& error // Result of operation. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the completion handler will not be invoked from within this function. * On immediate completion, invocation of the handler will be performed in a * manner equivalent to using asio::async_immediate(). * * @par Completion Signature * @code void(asio::error_code) @endcode */ template < ASIO_COMPLETION_TOKEN_FOR(void (asio::error_code)) WaitToken = default_completion_token_t<executor_type>> auto async_wait( WaitToken&& token = default_completion_token_t<executor_type>()) -> decltype( async_initiate<WaitToken, void (asio::error_code)>( declval<initiate_async_wait>(), token)) { return async_initiate<WaitToken, void (asio::error_code)>( initiate_async_wait(this), token); } private: // Disallow copying and assignment. basic_object_handle(const basic_object_handle&) = delete; basic_object_handle& operator=(const basic_object_handle&) = delete; class initiate_async_wait { public: typedef Executor executor_type; explicit initiate_async_wait(basic_object_handle* self) : self_(self) { } const executor_type& get_executor() const noexcept { return self_->get_executor(); } template <typename WaitHandler> void operator()(WaitHandler&& handler) const { // If you get an error on the following line it means that your handler // does not meet the documented type requirements for a WaitHandler. ASIO_WAIT_HANDLER_CHECK(WaitHandler, handler) type_check; detail::non_const_lvalue<WaitHandler> handler2(handler); self_->impl_.get_service().async_wait( self_->impl_.get_implementation(), handler2.value, self_->impl_.get_executor()); } private: basic_object_handle* self_; }; asio::detail::io_object_impl< asio::detail::win_object_handle_service, Executor> impl_; }; } // namespace windows } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_BASIC_OBJECT_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/stream_handle.hpp
// // windows/stream_handle.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 ASIO_WINDOWS_STREAM_HANDLE_HPP #define ASIO_WINDOWS_STREAM_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/windows/basic_stream_handle.hpp" namespace asio { namespace windows { /// Typedef for the typical usage of a stream-oriented handle. typedef basic_stream_handle<> stream_handle; } // namespace windows } // namespace asio #endif // defined(ASIO_HAS_WINDOWS_STREAM_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_STREAM_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/windows/random_access_handle.hpp
// // windows/random_access_handle.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 ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP #define ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) \ || defined(GENERATING_DOCUMENTATION) #include "asio/windows/basic_random_access_handle.hpp" namespace asio { namespace windows { /// Typedef for the typical usage of a random-access handle. typedef basic_random_access_handle<> random_access_handle; } // namespace windows } // namespace asio #endif // defined(ASIO_HAS_WINDOWS_RANDOM_ACCESS_HANDLE) // || defined(GENERATING_DOCUMENTATION) #endif // ASIO_WINDOWS_RANDOM_ACCESS_HANDLE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/win_iocp_thread_info.hpp
// // detail/win_iocp_thread_info.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 ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP #define ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/thread_info_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { struct win_iocp_thread_info : public thread_info_base { }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_WIN_IOCP_THREAD_INFO_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/resolver_service.hpp
// // detail/resolver_service.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 ASIO_DETAIL_RESOLVER_SERVICE_HPP #define ASIO_DETAIL_RESOLVER_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_WINDOWS_RUNTIME) #include "asio/ip/basic_resolver_query.hpp" #include "asio/ip/basic_resolver_results.hpp" #include "asio/detail/concurrency_hint.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/resolve_endpoint_op.hpp" #include "asio/detail/resolve_query_op.hpp" #include "asio/detail/resolver_service_base.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Protocol> class resolver_service : public execution_context_service_base<resolver_service<Protocol>>, public resolver_service_base { public: // The implementation type of the resolver. A cancellation token is used to // indicate to the background thread that the operation has been cancelled. typedef socket_ops::shared_cancel_token_type implementation_type; // The endpoint type. typedef typename Protocol::endpoint endpoint_type; // The query type. typedef asio::ip::basic_resolver_query<Protocol> query_type; // The results type. typedef asio::ip::basic_resolver_results<Protocol> results_type; // Constructor. resolver_service(execution_context& context) : execution_context_service_base<resolver_service<Protocol>>(context), resolver_service_base(context) { } // Destroy all user-defined handler objects owned by the service. void shutdown() { this->base_shutdown(); } // Perform any fork-related housekeeping. void notify_fork(execution_context::fork_event fork_ev) { this->base_notify_fork(fork_ev); } // Resolve a query to a list of entries. results_type resolve(implementation_type&, const query_type& qry, asio::error_code& ec) { asio::detail::addrinfo_type* address_info = 0; socket_ops::getaddrinfo(qry.host_name().c_str(), qry.service_name().c_str(), qry.hints(), &address_info, ec); auto_addrinfo auto_address_info(address_info); ASIO_ERROR_LOCATION(ec); return ec ? results_type() : results_type::create( address_info, qry.host_name(), qry.service_name()); } // Asynchronously resolve a query to a list of entries. template <typename Handler, typename IoExecutor> void async_resolve(implementation_type& impl, const query_type& qry, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef resolve_query_op<Protocol, Handler, IoExecutor> op; typename op::ptr p = { asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl, qry, scheduler_, handler, io_ex); ASIO_HANDLER_CREATION((scheduler_.context(), *p.p, "resolver", &impl, 0, "async_resolve")); start_resolve_op(p.p); p.v = p.p = 0; } // Resolve an endpoint to a list of entries. results_type resolve(implementation_type&, const endpoint_type& endpoint, asio::error_code& ec) { char host_name[NI_MAXHOST]; char service_name[NI_MAXSERV]; socket_ops::sync_getnameinfo(endpoint.data(), endpoint.size(), host_name, NI_MAXHOST, service_name, NI_MAXSERV, endpoint.protocol().type(), ec); ASIO_ERROR_LOCATION(ec); return ec ? results_type() : results_type::create( endpoint, host_name, service_name); } // Asynchronously resolve an endpoint to a list of entries. template <typename Handler, typename IoExecutor> void async_resolve(implementation_type& impl, const endpoint_type& endpoint, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef resolve_endpoint_op<Protocol, Handler, IoExecutor> op; typename op::ptr p = { asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(impl, endpoint, scheduler_, handler, io_ex); ASIO_HANDLER_CREATION((scheduler_.context(), *p.p, "resolver", &impl, 0, "async_resolve")); start_resolve_op(p.p); p.v = p.p = 0; } }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // !defined(ASIO_WINDOWS_RUNTIME) #endif // ASIO_DETAIL_RESOLVER_SERVICE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/resolver_service_base.hpp
// // detail/resolver_service_base.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 ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP #define ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/detail/mutex.hpp" #include "asio/detail/noncopyable.hpp" #include "asio/detail/resolve_op.hpp" #include "asio/detail/socket_ops.hpp" #include "asio/detail/socket_types.hpp" #include "asio/detail/scoped_ptr.hpp" #include "asio/detail/thread.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_io_context.hpp" #else // defined(ASIO_HAS_IOCP) # include "asio/detail/scheduler.hpp" #endif // defined(ASIO_HAS_IOCP) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class resolver_service_base { public: // The implementation type of the resolver. A cancellation token is used to // indicate to the background thread that the operation has been cancelled. typedef socket_ops::shared_cancel_token_type implementation_type; // Constructor. ASIO_DECL resolver_service_base(execution_context& context); // Destructor. ASIO_DECL ~resolver_service_base(); // Destroy all user-defined handler objects owned by the service. ASIO_DECL void base_shutdown(); // Perform any fork-related housekeeping. ASIO_DECL void base_notify_fork( execution_context::fork_event fork_ev); // Construct a new resolver implementation. ASIO_DECL void construct(implementation_type& impl); // Destroy a resolver implementation. ASIO_DECL void destroy(implementation_type&); // Move-construct a new resolver implementation. ASIO_DECL void move_construct(implementation_type& impl, implementation_type& other_impl); // Move-assign from another resolver implementation. ASIO_DECL void move_assign(implementation_type& impl, resolver_service_base& other_service, implementation_type& other_impl); // Move-construct a new timer implementation. void converting_move_construct(implementation_type& impl, resolver_service_base&, implementation_type& other_impl) { move_construct(impl, other_impl); } // Move-assign from another timer implementation. void converting_move_assign(implementation_type& impl, resolver_service_base& other_service, implementation_type& other_impl) { move_assign(impl, other_service, other_impl); } // Cancel pending asynchronous operations. ASIO_DECL void cancel(implementation_type& impl); protected: // Helper function to start an asynchronous resolve operation. ASIO_DECL void start_resolve_op(resolve_op* op); #if !defined(ASIO_WINDOWS_RUNTIME) // Helper class to perform exception-safe cleanup of addrinfo objects. class auto_addrinfo : private asio::detail::noncopyable { public: explicit auto_addrinfo(asio::detail::addrinfo_type* ai) : ai_(ai) { } ~auto_addrinfo() { if (ai_) socket_ops::freeaddrinfo(ai_); } operator asio::detail::addrinfo_type*() { return ai_; } private: asio::detail::addrinfo_type* ai_; }; #endif // !defined(ASIO_WINDOWS_RUNTIME) // Helper class to run the work scheduler in a thread. class work_scheduler_runner; // Start the work scheduler if it's not already running. ASIO_DECL void start_work_thread(); // The scheduler implementation used to post completions. #if defined(ASIO_HAS_IOCP) typedef class win_iocp_io_context scheduler_impl; #else typedef class scheduler scheduler_impl; #endif scheduler_impl& scheduler_; private: // Mutex to protect access to internal data. asio::detail::mutex mutex_; // Private scheduler used for performing asynchronous host resolution. asio::detail::scoped_ptr<scheduler_impl> work_scheduler_; // Thread used for running the work io_context's run loop. asio::detail::scoped_ptr<asio::detail::thread> work_thread_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/detail/impl/resolver_service_base.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_DETAIL_RESOLVER_SERVICE_BASE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/dependent_type.hpp
// // detail/dependent_type.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 ASIO_DETAIL_DEPENDENT_TYPE_HPP #define ASIO_DETAIL_DEPENDENT_TYPE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename DependsOn, typename T> struct dependent_type { typedef T type; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_DEPENDENT_TYPE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/source_location.hpp
// // detail/source_location.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 ASIO_DETAIL_SOURCE_LOCATION_HPP #define ASIO_DETAIL_SOURCE_LOCATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_SOURCE_LOCATION) #if defined(ASIO_HAS_STD_SOURCE_LOCATION) # include <source_location> #elif defined(ASIO_HAS_STD_EXPERIMENTAL_SOURCE_LOCATION) # include <experimental/source_location> #else // defined(ASIO_HAS_STD_EXPERIMENTAL_SOURCE_LOCATION) # error ASIO_HAS_SOURCE_LOCATION is set \ but no source_location is available #endif // defined(ASIO_HAS_STD_EXPERIMENTAL_SOURCE_LOCATION) namespace asio { namespace detail { #if defined(ASIO_HAS_STD_SOURCE_LOCATION) using std::source_location; #elif defined(ASIO_HAS_STD_EXPERIMENTAL_SOURCE_LOCATION) using std::experimental::source_location; #endif // defined(ASIO_HAS_STD_EXPERIMENTAL_SOURCE_LOCATION) } // namespace detail } // namespace asio #endif // defined(ASIO_HAS_SOURCE_LOCATION) #endif // ASIO_DETAIL_SOURCE_LOCATION_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/reactive_socket_accept_op.hpp
// // detail/reactive_socket_accept_op.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 ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP #define ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/fenced_block.hpp" #include "asio/detail/handler_alloc_helpers.hpp" #include "asio/detail/handler_work.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/reactor_op.hpp" #include "asio/detail/socket_holder.hpp" #include "asio/detail/socket_ops.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Socket, typename Protocol> class reactive_socket_accept_op_base : public reactor_op { public: reactive_socket_accept_op_base(const asio::error_code& success_ec, socket_type socket, socket_ops::state_type state, Socket& peer, const Protocol& protocol, typename Protocol::endpoint* peer_endpoint, func_type complete_func) : reactor_op(success_ec, &reactive_socket_accept_op_base::do_perform, complete_func), socket_(socket), state_(state), peer_(peer), protocol_(protocol), peer_endpoint_(peer_endpoint), addrlen_(peer_endpoint ? peer_endpoint->capacity() : 0) { } static status do_perform(reactor_op* base) { ASIO_ASSUME(base != 0); reactive_socket_accept_op_base* o( static_cast<reactive_socket_accept_op_base*>(base)); socket_type new_socket = invalid_socket; status result = socket_ops::non_blocking_accept(o->socket_, o->state_, o->peer_endpoint_ ? o->peer_endpoint_->data() : 0, o->peer_endpoint_ ? &o->addrlen_ : 0, o->ec_, new_socket) ? done : not_done; o->new_socket_.reset(new_socket); ASIO_HANDLER_REACTOR_OPERATION((*o, "non_blocking_accept", o->ec_)); return result; } void do_assign() { if (new_socket_.get() != invalid_socket) { if (peer_endpoint_) peer_endpoint_->resize(addrlen_); peer_.assign(protocol_, new_socket_.get(), ec_); if (!ec_) new_socket_.release(); } } private: socket_type socket_; socket_ops::state_type state_; socket_holder new_socket_; Socket& peer_; Protocol protocol_; typename Protocol::endpoint* peer_endpoint_; std::size_t addrlen_; }; template <typename Socket, typename Protocol, typename Handler, typename IoExecutor> class reactive_socket_accept_op : public reactive_socket_accept_op_base<Socket, Protocol> { public: typedef Handler handler_type; typedef IoExecutor io_executor_type; ASIO_DEFINE_HANDLER_PTR(reactive_socket_accept_op); reactive_socket_accept_op(const asio::error_code& success_ec, socket_type socket, socket_ops::state_type state, Socket& peer, const Protocol& protocol, typename Protocol::endpoint* peer_endpoint, Handler& handler, const IoExecutor& io_ex) : reactive_socket_accept_op_base<Socket, Protocol>( success_ec, socket, state, peer, protocol, peer_endpoint, &reactive_socket_accept_op::do_complete), handler_(static_cast<Handler&&>(handler)), work_(handler_, io_ex) { } static void do_complete(void* owner, operation* base, const asio::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_socket_accept_op* o(static_cast<reactive_socket_accept_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; // On success, assign new connection to peer socket object. if (owner) o->do_assign(); ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder1<Handler, asio::error_code> handler(o->handler_, o->ec_); p.h = asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); w.complete(handler, handler.handler_); ASIO_HANDLER_INVOCATION_END; } } static void do_immediate(operation* base, bool, const void* io_ex) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_socket_accept_op* o(static_cast<reactive_socket_accept_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; // On success, assign new connection to peer socket object. o->do_assign(); ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. immediate_handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder1<Handler, asio::error_code> handler(o->handler_, o->ec_); p.h = asio::detail::addressof(handler.handler_); p.reset(); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_)); w.complete(handler, handler.handler_, io_ex); ASIO_HANDLER_INVOCATION_END; } private: Handler handler_; handler_work<Handler, IoExecutor> work_; }; template <typename Protocol, typename PeerIoExecutor, typename Handler, typename IoExecutor> class reactive_socket_move_accept_op : private Protocol::socket::template rebind_executor<PeerIoExecutor>::other, public reactive_socket_accept_op_base< typename Protocol::socket::template rebind_executor<PeerIoExecutor>::other, Protocol> { public: typedef Handler handler_type; typedef IoExecutor io_executor_type; ASIO_DEFINE_HANDLER_PTR(reactive_socket_move_accept_op); reactive_socket_move_accept_op(const asio::error_code& success_ec, const PeerIoExecutor& peer_io_ex, socket_type socket, socket_ops::state_type state, const Protocol& protocol, typename Protocol::endpoint* peer_endpoint, Handler& handler, const IoExecutor& io_ex) : peer_socket_type(peer_io_ex), reactive_socket_accept_op_base<peer_socket_type, Protocol>( success_ec, socket, state, *this, protocol, peer_endpoint, &reactive_socket_move_accept_op::do_complete), handler_(static_cast<Handler&&>(handler)), work_(handler_, io_ex) { } static void do_complete(void* owner, operation* base, const asio::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_socket_move_accept_op* o( static_cast<reactive_socket_move_accept_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; // On success, assign new connection to peer socket object. if (owner) o->do_assign(); ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::move_binder2<Handler, asio::error_code, peer_socket_type> handler(0, static_cast<Handler&&>(o->handler_), o->ec_, static_cast<peer_socket_type&&>(*o)); p.h = asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); w.complete(handler, handler.handler_); ASIO_HANDLER_INVOCATION_END; } } static void do_immediate(operation* base, bool, const void* io_ex) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_socket_move_accept_op* o( static_cast<reactive_socket_move_accept_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; // On success, assign new connection to peer socket object. o->do_assign(); ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. immediate_handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::move_binder2<Handler, asio::error_code, peer_socket_type> handler(0, static_cast<Handler&&>(o->handler_), o->ec_, static_cast<peer_socket_type&&>(*o)); p.h = asio::detail::addressof(handler.handler_); p.reset(); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, "...")); w.complete(handler, handler.handler_, io_ex); ASIO_HANDLER_INVOCATION_END; } private: typedef typename Protocol::socket::template rebind_executor<PeerIoExecutor>::other peer_socket_type; Handler handler_; handler_work<Handler, IoExecutor> work_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_REACTIVE_SOCKET_ACCEPT_OP_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/chrono_time_traits.hpp
// // detail/chrono_time_traits.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 ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP #define ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/cstdint.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Helper template to compute the greatest common divisor. template <int64_t v1, int64_t v2> struct gcd { enum { value = gcd<v2, v1 % v2>::value }; }; template <int64_t v1> struct gcd<v1, 0> { enum { value = v1 }; }; // Adapts std::chrono clocks for use with a deadline timer. template <typename Clock, typename WaitTraits> struct chrono_time_traits { // The clock type. typedef Clock clock_type; // The duration type of the clock. typedef typename clock_type::duration duration_type; // The time point type of the clock. typedef typename clock_type::time_point time_type; // The period of the clock. typedef typename duration_type::period period_type; // Get the current time. static time_type now() { return clock_type::now(); } // Add a duration to a time. static time_type add(const time_type& t, const duration_type& d) { const time_type epoch; if (t >= epoch) { if ((time_type::max)() - t < d) return (time_type::max)(); } else // t < epoch { if (-(t - (time_type::min)()) > d) return (time_type::min)(); } return t + d; } // Subtract one time from another. static duration_type subtract(const time_type& t1, const time_type& t2) { const time_type epoch; if (t1 >= epoch) { if (t2 >= epoch) { return t1 - t2; } else if (t2 == (time_type::min)()) { return (duration_type::max)(); } else if ((time_type::max)() - t1 < epoch - t2) { return (duration_type::max)(); } else { return t1 - t2; } } else // t1 < epoch { if (t2 < epoch) { return t1 - t2; } else if (t1 == (time_type::min)()) { return (duration_type::min)(); } else if ((time_type::max)() - t2 < epoch - t1) { return (duration_type::min)(); } else { return -(t2 - t1); } } } // Test whether one time is less than another. static bool less_than(const time_type& t1, const time_type& t2) { return t1 < t2; } // Implement just enough of the posix_time::time_duration interface to supply // what the timer_queue requires. class posix_time_duration { public: explicit posix_time_duration(const duration_type& d) : d_(d) { } int64_t ticks() const { return d_.count(); } int64_t total_seconds() const { return duration_cast<1, 1>(); } int64_t total_milliseconds() const { return duration_cast<1, 1000>(); } int64_t total_microseconds() const { return duration_cast<1, 1000000>(); } private: template <int64_t Num, int64_t Den> int64_t duration_cast() const { const int64_t num1 = period_type::num / gcd<period_type::num, Num>::value; const int64_t num2 = Num / gcd<period_type::num, Num>::value; const int64_t den1 = period_type::den / gcd<period_type::den, Den>::value; const int64_t den2 = Den / gcd<period_type::den, Den>::value; const int64_t num = num1 * den2; const int64_t den = num2 * den1; if (num == 1 && den == 1) return ticks(); else if (num != 1 && den == 1) return ticks() * num; else if (num == 1 && period_type::den != 1) return ticks() / den; else return ticks() * num / den; } duration_type d_; }; // Convert to POSIX duration type. static posix_time_duration to_posix_duration(const duration_type& d) { return posix_time_duration(WaitTraits::to_wait_duration(d)); } }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_CHRONO_TIME_TRAITS_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/handler_alloc_helpers.hpp
// // detail/handler_alloc_helpers.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 ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP #define ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/recycling_allocator.hpp" #include "asio/associated_allocator.hpp" #include "asio/detail/push_options.hpp" #define ASIO_DEFINE_TAGGED_HANDLER_PTR(purpose, op) \ struct ptr \ { \ Handler* h; \ op* v; \ op* p; \ ~ptr() \ { \ reset(); \ } \ static op* allocate(Handler& handler) \ { \ typedef typename ::asio::associated_allocator< \ Handler>::type associated_allocator_type; \ typedef typename ::asio::detail::get_recycling_allocator< \ associated_allocator_type, purpose>::type default_allocator_type; \ ASIO_REBIND_ALLOC(default_allocator_type, op) a( \ ::asio::detail::get_recycling_allocator< \ associated_allocator_type, purpose>::get( \ ::asio::get_associated_allocator(handler))); \ return a.allocate(1); \ } \ void reset() \ { \ if (p) \ { \ p->~op(); \ p = 0; \ } \ if (v) \ { \ typedef typename ::asio::associated_allocator< \ Handler>::type associated_allocator_type; \ typedef typename ::asio::detail::get_recycling_allocator< \ associated_allocator_type, purpose>::type default_allocator_type; \ ASIO_REBIND_ALLOC(default_allocator_type, op) a( \ ::asio::detail::get_recycling_allocator< \ associated_allocator_type, purpose>::get( \ ::asio::get_associated_allocator(*h))); \ a.deallocate(static_cast<op*>(v), 1); \ v = 0; \ } \ } \ } \ /**/ #define ASIO_DEFINE_HANDLER_PTR(op) \ ASIO_DEFINE_TAGGED_HANDLER_PTR( \ ::asio::detail::thread_info_base::default_tag, op ) \ /**/ #define ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR(purpose, op) \ struct ptr \ { \ const Alloc* a; \ void* v; \ op* p; \ ~ptr() \ { \ reset(); \ } \ static op* allocate(const Alloc& a) \ { \ typedef typename ::asio::detail::get_recycling_allocator< \ Alloc, purpose>::type recycling_allocator_type; \ ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ ::asio::detail::get_recycling_allocator< \ Alloc, purpose>::get(a)); \ return a1.allocate(1); \ } \ void reset() \ { \ if (p) \ { \ p->~op(); \ p = 0; \ } \ if (v) \ { \ typedef typename ::asio::detail::get_recycling_allocator< \ Alloc, purpose>::type recycling_allocator_type; \ ASIO_REBIND_ALLOC(recycling_allocator_type, op) a1( \ ::asio::detail::get_recycling_allocator< \ Alloc, purpose>::get(*a)); \ a1.deallocate(static_cast<op*>(v), 1); \ v = 0; \ } \ } \ } \ /**/ #define ASIO_DEFINE_HANDLER_ALLOCATOR_PTR(op) \ ASIO_DEFINE_TAGGED_HANDLER_ALLOCATOR_PTR( \ ::asio::detail::thread_info_base::default_tag, op ) \ /**/ #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_HANDLER_ALLOC_HELPERS_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/reactive_null_buffers_op.hpp
// // detail/reactive_null_buffers_op.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 ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP #define ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/fenced_block.hpp" #include "asio/detail/handler_alloc_helpers.hpp" #include "asio/detail/handler_work.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/reactor_op.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Handler, typename IoExecutor> class reactive_null_buffers_op : public reactor_op { public: typedef Handler handler_type; typedef IoExecutor io_executor_type; ASIO_DEFINE_HANDLER_PTR(reactive_null_buffers_op); reactive_null_buffers_op(const asio::error_code& success_ec, Handler& handler, const IoExecutor& io_ex) : reactor_op(success_ec, &reactive_null_buffers_op::do_perform, &reactive_null_buffers_op::do_complete), handler_(static_cast<Handler&&>(handler)), work_(handler_, io_ex) { } static status do_perform(reactor_op*) { return done; } static void do_complete(void* owner, operation* base, const asio::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_null_buffers_op* o(static_cast<reactive_null_buffers_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder2<Handler, asio::error_code, std::size_t> handler(o->handler_, o->ec_, o->bytes_transferred_); p.h = asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); w.complete(handler, handler.handler_); ASIO_HANDLER_INVOCATION_END; } } static void do_immediate(operation* base, bool, const void* io_ex) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); reactive_null_buffers_op* o(static_cast<reactive_null_buffers_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. immediate_handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder2<Handler, asio::error_code, std::size_t> handler(o->handler_, o->ec_, o->bytes_transferred_); p.h = asio::detail::addressof(handler.handler_); p.reset(); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); w.complete(handler, handler.handler_, io_ex); ASIO_HANDLER_INVOCATION_END; } private: Handler handler_; handler_work<Handler, IoExecutor> work_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_REACTIVE_NULL_BUFFERS_OP_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/limits.hpp
// // detail/limits.hpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2011 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 ASIO_DETAIL_LIMITS_HPP #define ASIO_DETAIL_LIMITS_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <limits> #endif // ASIO_DETAIL_LIMITS_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/win_object_handle_service.hpp
// // detail/win_object_handle_service.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2011 Boris Schaeling ([email protected]) // // 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 ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP #define ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) #include "asio/detail/memory.hpp" #include "asio/detail/wait_handler.hpp" #include "asio/error.hpp" #include "asio/execution_context.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_io_context.hpp" #else // defined(ASIO_HAS_IOCP) # include "asio/detail/scheduler.hpp" #endif // defined(ASIO_HAS_IOCP) #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class win_object_handle_service : public execution_context_service_base<win_object_handle_service> { public: // The native type of an object handle. typedef HANDLE native_handle_type; // The implementation type of the object handle. class implementation_type { public: // Default constructor. implementation_type() : handle_(INVALID_HANDLE_VALUE), wait_handle_(INVALID_HANDLE_VALUE), owner_(0), next_(0), prev_(0) { } private: // Only this service will have access to the internal values. friend class win_object_handle_service; // The native object handle representation. May be accessed or modified // without locking the mutex. native_handle_type handle_; // The handle used to unregister the wait operation. The mutex must be // locked when accessing or modifying this member. HANDLE wait_handle_; // The operations waiting on the object handle. If there is a registered // wait then the mutex must be locked when accessing or modifying this // member op_queue<wait_op> op_queue_; // The service instance that owns the object handle implementation. win_object_handle_service* owner_; // Pointers to adjacent handle implementations in linked list. The mutex // must be locked when accessing or modifying these members. implementation_type* next_; implementation_type* prev_; }; // Constructor. ASIO_DECL win_object_handle_service(execution_context& context); // Destroy all user-defined handler objects owned by the service. ASIO_DECL void shutdown(); // Construct a new handle implementation. ASIO_DECL void construct(implementation_type& impl); // Move-construct a new handle implementation. ASIO_DECL void move_construct(implementation_type& impl, implementation_type& other_impl); // Move-assign from another handle implementation. ASIO_DECL void move_assign(implementation_type& impl, win_object_handle_service& other_service, implementation_type& other_impl); // Destroy a handle implementation. ASIO_DECL void destroy(implementation_type& impl); // Assign a native handle to a handle implementation. ASIO_DECL asio::error_code assign(implementation_type& impl, const native_handle_type& handle, asio::error_code& ec); // Determine whether the handle is open. bool is_open(const implementation_type& impl) const { return impl.handle_ != INVALID_HANDLE_VALUE && impl.handle_ != 0; } // Destroy a handle implementation. ASIO_DECL asio::error_code close(implementation_type& impl, asio::error_code& ec); // Get the native handle representation. native_handle_type native_handle(const implementation_type& impl) const { return impl.handle_; } // Cancel all operations associated with the handle. ASIO_DECL asio::error_code cancel(implementation_type& impl, asio::error_code& ec); // Perform a synchronous wait for the object to enter a signalled state. ASIO_DECL void wait(implementation_type& impl, asio::error_code& ec); /// Start an asynchronous wait. template <typename Handler, typename IoExecutor> void async_wait(implementation_type& impl, Handler& handler, const IoExecutor& io_ex) { // Allocate and construct an operation to wrap the handler. typedef wait_handler<Handler, IoExecutor> op; typename op::ptr p = { asio::detail::addressof(handler), op::ptr::allocate(handler), 0 }; p.p = new (p.v) op(handler, io_ex); ASIO_HANDLER_CREATION((scheduler_.context(), *p.p, "object_handle", &impl, reinterpret_cast<uintmax_t>(impl.wait_handle_), "async_wait")); start_wait_op(impl, p.p); p.v = p.p = 0; } private: // Helper function to start an asynchronous wait operation. ASIO_DECL void start_wait_op(implementation_type& impl, wait_op* op); // Helper function to register a wait operation. ASIO_DECL void register_wait_callback( implementation_type& impl, mutex::scoped_lock& lock); // Callback function invoked when the registered wait completes. static ASIO_DECL VOID CALLBACK wait_callback( PVOID param, BOOLEAN timeout); // The scheduler used to post completions. #if defined(ASIO_HAS_IOCP) typedef class win_iocp_io_context scheduler_impl; #else typedef class scheduler scheduler_impl; #endif scheduler_impl& scheduler_; // Mutex to protect access to internal state. mutex mutex_; // The head of a linked list of all implementations. implementation_type* impl_list_; // Flag to indicate that the dispatcher has been shut down. bool shutdown_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/detail/impl/win_object_handle_service.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // defined(ASIO_HAS_WINDOWS_OBJECT_HANDLE) #endif // ASIO_DETAIL_WIN_OBJECT_HANDLE_SERVICE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/io_uring_socket_recvmsg_op.hpp
// // detail/io_uring_socket_recvmsg_op.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 ASIO_DETAIL_IO_URING_SOCKET_RECVMSG_OP_HPP #define ASIO_DETAIL_IO_URING_SOCKET_RECVMSG_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_IO_URING) #include "asio/detail/bind_handler.hpp" #include "asio/detail/buffer_sequence_adapter.hpp" #include "asio/detail/socket_ops.hpp" #include "asio/detail/fenced_block.hpp" #include "asio/detail/handler_work.hpp" #include "asio/detail/io_uring_operation.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename MutableBufferSequence> class io_uring_socket_recvmsg_op_base : public io_uring_operation { public: io_uring_socket_recvmsg_op_base(const asio::error_code& success_ec, socket_type socket, socket_ops::state_type state, const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, func_type complete_func) : io_uring_operation(success_ec, &io_uring_socket_recvmsg_op_base::do_prepare, &io_uring_socket_recvmsg_op_base::do_perform, complete_func), socket_(socket), state_(state), buffers_(buffers), in_flags_(in_flags), out_flags_(out_flags), bufs_(buffers), msghdr_() { msghdr_.msg_iov = bufs_.buffers(); msghdr_.msg_iovlen = static_cast<int>(bufs_.count()); } static void do_prepare(io_uring_operation* base, ::io_uring_sqe* sqe) { ASIO_ASSUME(base != 0); io_uring_socket_recvmsg_op_base* o( static_cast<io_uring_socket_recvmsg_op_base*>(base)); if ((o->state_ & socket_ops::internal_non_blocking) != 0) { bool except_op = (o->in_flags_ & socket_base::message_out_of_band) != 0; ::io_uring_prep_poll_add(sqe, o->socket_, except_op ? POLLPRI : POLLIN); } else { ::io_uring_prep_recvmsg(sqe, o->socket_, &o->msghdr_, o->in_flags_); } } static bool do_perform(io_uring_operation* base, bool after_completion) { ASIO_ASSUME(base != 0); io_uring_socket_recvmsg_op_base* o( static_cast<io_uring_socket_recvmsg_op_base*>(base)); if ((o->state_ & socket_ops::internal_non_blocking) != 0) { bool except_op = (o->in_flags_ & socket_base::message_out_of_band) != 0; if (after_completion || !except_op) { return socket_ops::non_blocking_recvmsg(o->socket_, o->bufs_.buffers(), o->bufs_.count(), o->in_flags_, o->out_flags_, o->ec_, o->bytes_transferred_); } } else if (after_completion) { if (!o->ec_) o->out_flags_ = o->msghdr_.msg_flags; else o->out_flags_ = 0; } if (o->ec_ && o->ec_ == asio::error::would_block) { o->state_ |= socket_ops::internal_non_blocking; return false; } return after_completion; } private: socket_type socket_; socket_ops::state_type state_; MutableBufferSequence buffers_; socket_base::message_flags in_flags_; socket_base::message_flags& out_flags_; buffer_sequence_adapter<asio::mutable_buffer, MutableBufferSequence> bufs_; msghdr msghdr_; }; template <typename MutableBufferSequence, typename Handler, typename IoExecutor> class io_uring_socket_recvmsg_op : public io_uring_socket_recvmsg_op_base<MutableBufferSequence> { public: ASIO_DEFINE_HANDLER_PTR(io_uring_socket_recvmsg_op); io_uring_socket_recvmsg_op(const asio::error_code& success_ec, int socket, socket_ops::state_type state, const MutableBufferSequence& buffers, socket_base::message_flags in_flags, socket_base::message_flags& out_flags, Handler& handler, const IoExecutor& io_ex) : io_uring_socket_recvmsg_op_base<MutableBufferSequence>(success_ec, socket, state, buffers, in_flags, out_flags, &io_uring_socket_recvmsg_op::do_complete), handler_(static_cast<Handler&&>(handler)), work_(handler_, io_ex) { } static void do_complete(void* owner, operation* base, const asio::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); io_uring_socket_recvmsg_op* o (static_cast<io_uring_socket_recvmsg_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder2<Handler, asio::error_code, std::size_t> handler(o->handler_, o->ec_, o->bytes_transferred_); p.h = asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); w.complete(handler, handler.handler_); ASIO_HANDLER_INVOCATION_END; } } private: Handler handler_; handler_work<Handler, IoExecutor> work_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // defined(ASIO_HAS_IO_URING) #endif // ASIO_DETAIL_IO_URING_SOCKET_RECVMSG_OP_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/win_iocp_serial_port_service.hpp
// // detail/win_iocp_serial_port_service.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2024 Christopher M. Kohlhoff (chris at kohlhoff dot com) // Copyright (c) 2008 Rep Invariant Systems, Inc. ([email protected]) // // 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 ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP #define ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_IOCP) && defined(ASIO_HAS_SERIAL_PORT) #include <string> #include "asio/error.hpp" #include "asio/execution_context.hpp" #include "asio/detail/win_iocp_handle_service.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { // Extend win_iocp_handle_service to provide serial port support. class win_iocp_serial_port_service : public execution_context_service_base<win_iocp_serial_port_service> { public: // The native type of a serial port. typedef win_iocp_handle_service::native_handle_type native_handle_type; // The implementation type of the serial port. typedef win_iocp_handle_service::implementation_type implementation_type; // Constructor. ASIO_DECL win_iocp_serial_port_service(execution_context& context); // Destroy all user-defined handler objects owned by the service. ASIO_DECL void shutdown(); // Construct a new serial port implementation. void construct(implementation_type& impl) { handle_service_.construct(impl); } // Move-construct a new serial port implementation. void move_construct(implementation_type& impl, implementation_type& other_impl) { handle_service_.move_construct(impl, other_impl); } // Move-assign from another serial port implementation. void move_assign(implementation_type& impl, win_iocp_serial_port_service& other_service, implementation_type& other_impl) { handle_service_.move_assign(impl, other_service.handle_service_, other_impl); } // Destroy a serial port implementation. void destroy(implementation_type& impl) { handle_service_.destroy(impl); } // Open the serial port using the specified device name. ASIO_DECL asio::error_code open(implementation_type& impl, const std::string& device, asio::error_code& ec); // Assign a native handle to a serial port implementation. asio::error_code assign(implementation_type& impl, const native_handle_type& handle, asio::error_code& ec) { return handle_service_.assign(impl, handle, ec); } // Determine whether the serial port is open. bool is_open(const implementation_type& impl) const { return handle_service_.is_open(impl); } // Destroy a serial port implementation. asio::error_code close(implementation_type& impl, asio::error_code& ec) { return handle_service_.close(impl, ec); } // Get the native serial port representation. native_handle_type native_handle(implementation_type& impl) { return handle_service_.native_handle(impl); } // Cancel all operations associated with the handle. asio::error_code cancel(implementation_type& impl, asio::error_code& ec) { return handle_service_.cancel(impl, ec); } // Set an option on the serial port. template <typename SettableSerialPortOption> asio::error_code set_option(implementation_type& impl, const SettableSerialPortOption& option, asio::error_code& ec) { return do_set_option(impl, &win_iocp_serial_port_service::store_option<SettableSerialPortOption>, &option, ec); } // Get an option from the serial port. template <typename GettableSerialPortOption> asio::error_code get_option(const implementation_type& impl, GettableSerialPortOption& option, asio::error_code& ec) const { return do_get_option(impl, &win_iocp_serial_port_service::load_option<GettableSerialPortOption>, &option, ec); } // Send a break sequence to the serial port. asio::error_code send_break(implementation_type&, asio::error_code& ec) { ec = asio::error::operation_not_supported; ASIO_ERROR_LOCATION(ec); return ec; } // Write the given data. Returns the number of bytes sent. template <typename ConstBufferSequence> size_t write_some(implementation_type& impl, const ConstBufferSequence& buffers, asio::error_code& ec) { return handle_service_.write_some(impl, buffers, ec); } // Start an asynchronous write. The data being written must be valid for the // lifetime of the asynchronous operation. template <typename ConstBufferSequence, typename Handler, typename IoExecutor> void async_write_some(implementation_type& impl, const ConstBufferSequence& buffers, Handler& handler, const IoExecutor& io_ex) { handle_service_.async_write_some(impl, buffers, handler, io_ex); } // Read some data. Returns the number of bytes received. template <typename MutableBufferSequence> size_t read_some(implementation_type& impl, const MutableBufferSequence& buffers, asio::error_code& ec) { return handle_service_.read_some(impl, buffers, ec); } // Start an asynchronous read. The buffer for the data being received must be // valid for the lifetime of the asynchronous operation. template <typename MutableBufferSequence, typename Handler, typename IoExecutor> void async_read_some(implementation_type& impl, const MutableBufferSequence& buffers, Handler& handler, const IoExecutor& io_ex) { handle_service_.async_read_some(impl, buffers, handler, io_ex); } private: // Function pointer type for storing a serial port option. typedef asio::error_code (*store_function_type)( const void*, ::DCB&, asio::error_code&); // Helper function template to store a serial port option. template <typename SettableSerialPortOption> static asio::error_code store_option(const void* option, ::DCB& storage, asio::error_code& ec) { static_cast<const SettableSerialPortOption*>(option)->store(storage, ec); return ec; } // Helper function to set a serial port option. ASIO_DECL asio::error_code do_set_option( implementation_type& impl, store_function_type store, const void* option, asio::error_code& ec); // Function pointer type for loading a serial port option. typedef asio::error_code (*load_function_type)( void*, const ::DCB&, asio::error_code&); // Helper function template to load a serial port option. template <typename GettableSerialPortOption> static asio::error_code load_option(void* option, const ::DCB& storage, asio::error_code& ec) { static_cast<GettableSerialPortOption*>(option)->load(storage, ec); return ec; } // Helper function to get a serial port option. ASIO_DECL asio::error_code do_get_option( const implementation_type& impl, load_function_type load, void* option, asio::error_code& ec) const; // The implementation used for initiating asynchronous operations. win_iocp_handle_service handle_service_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/detail/impl/win_iocp_serial_port_service.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // defined(ASIO_HAS_IOCP) && defined(ASIO_HAS_SERIAL_PORT) #endif // ASIO_DETAIL_WIN_IOCP_SERIAL_PORT_SERVICE_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/io_uring_null_buffers_op.hpp
// // detail/io_uring_null_buffers_op.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 ASIO_DETAIL_IO_URING_NULL_BUFFERS_OP_HPP #define ASIO_DETAIL_IO_URING_NULL_BUFFERS_OP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/detail/bind_handler.hpp" #include "asio/detail/fenced_block.hpp" #include "asio/detail/handler_alloc_helpers.hpp" #include "asio/detail/handler_work.hpp" #include "asio/detail/io_uring_operation.hpp" #include "asio/detail/memory.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Handler, typename IoExecutor> class io_uring_null_buffers_op : public io_uring_operation { public: ASIO_DEFINE_HANDLER_PTR(io_uring_null_buffers_op); io_uring_null_buffers_op(const asio::error_code& success_ec, int descriptor, int poll_flags, Handler& handler, const IoExecutor& io_ex) : io_uring_operation(success_ec, &io_uring_null_buffers_op::do_prepare, &io_uring_null_buffers_op::do_perform, &io_uring_null_buffers_op::do_complete), handler_(static_cast<Handler&&>(handler)), work_(handler_, io_ex), descriptor_(descriptor), poll_flags_(poll_flags) { } static void do_prepare(io_uring_operation* base, ::io_uring_sqe* sqe) { ASIO_ASSUME(base != 0); io_uring_null_buffers_op* o(static_cast<io_uring_null_buffers_op*>(base)); ::io_uring_prep_poll_add(sqe, o->descriptor_, o->poll_flags_); } static bool do_perform(io_uring_operation*, bool after_completion) { return after_completion; } static void do_complete(void* owner, operation* base, const asio::error_code& /*ec*/, std::size_t /*bytes_transferred*/) { // Take ownership of the handler object. ASIO_ASSUME(base != 0); io_uring_null_buffers_op* o(static_cast<io_uring_null_buffers_op*>(base)); ptr p = { asio::detail::addressof(o->handler_), o, o }; ASIO_HANDLER_COMPLETION((*o)); // Take ownership of the operation's outstanding work. handler_work<Handler, IoExecutor> w( static_cast<handler_work<Handler, IoExecutor>&&>( o->work_)); ASIO_ERROR_LOCATION(o->ec_); // Make a copy of the handler so that the memory can be deallocated before // the upcall is made. Even if we're not about to make an upcall, a // sub-object of the handler may be the true owner of the memory associated // with the handler. Consequently, a local copy of the handler is required // to ensure that any owning sub-object remains valid until after we have // deallocated the memory here. detail::binder2<Handler, asio::error_code, std::size_t> handler(o->handler_, o->ec_, o->bytes_transferred_); p.h = asio::detail::addressof(handler.handler_); p.reset(); // Make the upcall if required. if (owner) { fenced_block b(fenced_block::half); ASIO_HANDLER_INVOCATION_BEGIN((handler.arg1_, handler.arg2_)); w.complete(handler, handler.handler_); ASIO_HANDLER_INVOCATION_END; } } private: Handler handler_; handler_work<Handler, IoExecutor> work_; int descriptor_; int poll_flags_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_IO_URING_NULL_BUFFERS_OP_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/event.hpp
// // detail/event.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 ASIO_DETAIL_EVENT_HPP #define ASIO_DETAIL_EVENT_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if !defined(ASIO_HAS_THREADS) # include "asio/detail/null_event.hpp" #elif defined(ASIO_WINDOWS) # include "asio/detail/win_event.hpp" #elif defined(ASIO_HAS_PTHREADS) # include "asio/detail/posix_event.hpp" #else # include "asio/detail/std_event.hpp" #endif namespace asio { namespace detail { #if !defined(ASIO_HAS_THREADS) typedef null_event event; #elif defined(ASIO_WINDOWS) typedef win_event event; #elif defined(ASIO_HAS_PTHREADS) typedef posix_event event; #else typedef std_event event; #endif } // namespace detail } // namespace asio #endif // ASIO_DETAIL_EVENT_HPP
0
repos/asio/asio/include/asio
repos/asio/asio/include/asio/detail/object_pool.hpp
// // detail/object_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 ASIO_DETAIL_OBJECT_POOL_HPP #define ASIO_DETAIL_OBJECT_POOL_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/noncopyable.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { template <typename Object> class object_pool; class object_pool_access { public: template <typename Object> static Object* create() { return new Object; } template <typename Object, typename Arg> static Object* create(Arg arg) { return new Object(arg); } template <typename Object> static void destroy(Object* o) { delete o; } template <typename Object> static Object*& next(Object* o) { return o->next_; } template <typename Object> static Object*& prev(Object* o) { return o->prev_; } }; template <typename Object> class object_pool : private noncopyable { public: // Constructor. object_pool() : live_list_(0), free_list_(0) { } // Destructor destroys all objects. ~object_pool() { destroy_list(live_list_); destroy_list(free_list_); } // Get the object at the start of the live list. Object* first() { return live_list_; } // Allocate a new object. Object* alloc() { Object* o = free_list_; if (o) free_list_ = object_pool_access::next(free_list_); else o = object_pool_access::create<Object>(); object_pool_access::next(o) = live_list_; object_pool_access::prev(o) = 0; if (live_list_) object_pool_access::prev(live_list_) = o; live_list_ = o; return o; } // Allocate a new object with an argument. template <typename Arg> Object* alloc(Arg arg) { Object* o = free_list_; if (o) free_list_ = object_pool_access::next(free_list_); else o = object_pool_access::create<Object>(arg); object_pool_access::next(o) = live_list_; object_pool_access::prev(o) = 0; if (live_list_) object_pool_access::prev(live_list_) = o; live_list_ = o; return o; } // Free an object. Moves it to the free list. No destructors are run. void free(Object* o) { if (live_list_ == o) live_list_ = object_pool_access::next(o); if (object_pool_access::prev(o)) { object_pool_access::next(object_pool_access::prev(o)) = object_pool_access::next(o); } if (object_pool_access::next(o)) { object_pool_access::prev(object_pool_access::next(o)) = object_pool_access::prev(o); } object_pool_access::next(o) = free_list_; object_pool_access::prev(o) = 0; free_list_ = o; } private: // Helper function to destroy all elements in a list. void destroy_list(Object* list) { while (list) { Object* o = list; list = object_pool_access::next(o); object_pool_access::destroy(o); } } // The list of live objects. Object* live_list_; // The free list. Object* free_list_; }; } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_DETAIL_OBJECT_POOL_HPP