1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
// Copyright (c) 2026 Steve Gerbino
3  
// Copyright (c) 2026 Steve Gerbino
4  
//
4  
//
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7  
//
7  
//
8  
// Official repository: https://github.com/cppalliance/corosio
8  
// Official repository: https://github.com/cppalliance/corosio
9  
//
9  
//
10  

10  

11  
#ifndef BOOST_COROSIO_TCP_SOCKET_HPP
11  
#ifndef BOOST_COROSIO_TCP_SOCKET_HPP
12  
#define BOOST_COROSIO_TCP_SOCKET_HPP
12  
#define BOOST_COROSIO_TCP_SOCKET_HPP
13  

13  

14  
#include <boost/corosio/detail/config.hpp>
14  
#include <boost/corosio/detail/config.hpp>
15  
#include <boost/corosio/detail/platform.hpp>
15  
#include <boost/corosio/detail/platform.hpp>
16  
#include <boost/corosio/detail/except.hpp>
16  
#include <boost/corosio/detail/except.hpp>
17  
#include <boost/corosio/io/io_stream.hpp>
17  
#include <boost/corosio/io/io_stream.hpp>
18  
#include <boost/capy/io_result.hpp>
18  
#include <boost/capy/io_result.hpp>
19  
#include <boost/corosio/detail/buffer_param.hpp>
19  
#include <boost/corosio/detail/buffer_param.hpp>
20  
#include <boost/corosio/endpoint.hpp>
20  
#include <boost/corosio/endpoint.hpp>
21  
#include <boost/corosio/tcp.hpp>
21  
#include <boost/corosio/tcp.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
23  
#include <boost/capy/ex/execution_context.hpp>
23  
#include <boost/capy/ex/execution_context.hpp>
24  
#include <boost/capy/ex/io_env.hpp>
24  
#include <boost/capy/ex/io_env.hpp>
25  
#include <boost/capy/concept/executor.hpp>
25  
#include <boost/capy/concept/executor.hpp>
26  

26  

27  
#include <system_error>
27  
#include <system_error>
28  

28  

29  
#include <concepts>
29  
#include <concepts>
30  
#include <coroutine>
30  
#include <coroutine>
31  
#include <cstddef>
31  
#include <cstddef>
32  
#include <stop_token>
32  
#include <stop_token>
33  
#include <type_traits>
33  
#include <type_traits>
34  

34  

35  
namespace boost::corosio {
35  
namespace boost::corosio {
36  

36  

 
37 +
/// Represent a platform-specific socket descriptor (`int` on POSIX, `SOCKET` on Windows).
37  
#if BOOST_COROSIO_HAS_IOCP && !defined(BOOST_COROSIO_MRDOCS)
38  
#if BOOST_COROSIO_HAS_IOCP && !defined(BOOST_COROSIO_MRDOCS)
38 -
using native_handle_type = std::uintptr_t; // SOCKET
39 +
using native_handle_type = std::uintptr_t;
39  
#else
40  
#else
40  
using native_handle_type = int;
41  
using native_handle_type = int;
41  
#endif
42  
#endif
42  

43  

43  
/** An asynchronous TCP socket for coroutine I/O.
44  
/** An asynchronous TCP socket for coroutine I/O.
44  

45  

45  
    This class provides asynchronous TCP socket operations that return
46  
    This class provides asynchronous TCP socket operations that return
46  
    awaitable types. Each operation participates in the affine awaitable
47  
    awaitable types. Each operation participates in the affine awaitable
47  
    protocol, ensuring coroutines resume on the correct executor.
48  
    protocol, ensuring coroutines resume on the correct executor.
48  

49  

49  
    The socket must be opened before performing I/O operations. Operations
50  
    The socket must be opened before performing I/O operations. Operations
50  
    support cancellation through `std::stop_token` via the affine protocol,
51  
    support cancellation through `std::stop_token` via the affine protocol,
51  
    or explicitly through the `cancel()` member function.
52  
    or explicitly through the `cancel()` member function.
52  

53  

53  
    @par Thread Safety
54  
    @par Thread Safety
54  
    Distinct objects: Safe.@n
55  
    Distinct objects: Safe.@n
55  
    Shared objects: Unsafe. A socket must not have concurrent operations
56  
    Shared objects: Unsafe. A socket must not have concurrent operations
56  
    of the same type (e.g., two simultaneous reads). One read and one
57  
    of the same type (e.g., two simultaneous reads). One read and one
57  
    write may be in flight simultaneously.
58  
    write may be in flight simultaneously.
58  

59  

59  
    @par Semantics
60  
    @par Semantics
60  
    Wraps the platform TCP/IP stack. Operations dispatch to
61  
    Wraps the platform TCP/IP stack. Operations dispatch to
61  
    OS socket APIs via the io_context reactor (epoll, IOCP,
62  
    OS socket APIs via the io_context reactor (epoll, IOCP,
62  
    kqueue). Satisfies @ref capy::Stream.
63  
    kqueue). Satisfies @ref capy::Stream.
63  

64  

64  
    @par Example
65  
    @par Example
65  
    @code
66  
    @code
66  
    io_context ioc;
67  
    io_context ioc;
67  
    tcp_socket s(ioc);
68  
    tcp_socket s(ioc);
68  
    s.open();
69  
    s.open();
69  

70  

70  
    // Using structured bindings
71  
    // Using structured bindings
71  
    auto [ec] = co_await s.connect(
72  
    auto [ec] = co_await s.connect(
72  
        endpoint(ipv4_address::loopback(), 8080));
73  
        endpoint(ipv4_address::loopback(), 8080));
73  
    if (ec)
74  
    if (ec)
74  
        co_return;
75  
        co_return;
75  

76  

76  
    char buf[1024];
77  
    char buf[1024];
77  
    auto [read_ec, n] = co_await s.read_some(
78  
    auto [read_ec, n] = co_await s.read_some(
78  
        capy::mutable_buffer(buf, sizeof(buf)));
79  
        capy::mutable_buffer(buf, sizeof(buf)));
79  
    @endcode
80  
    @endcode
80  
*/
81  
*/
81  
class BOOST_COROSIO_DECL tcp_socket : public io_stream
82  
class BOOST_COROSIO_DECL tcp_socket : public io_stream
82  
{
83  
{
83  
public:
84  
public:
84  
    /** Different ways a socket may be shutdown. */
85  
    /** Different ways a socket may be shutdown. */
85  
    enum shutdown_type
86  
    enum shutdown_type
86  
    {
87  
    {
87  
        shutdown_receive,
88  
        shutdown_receive,
88  
        shutdown_send,
89  
        shutdown_send,
89  
        shutdown_both
90  
        shutdown_both
90  
    };
91  
    };
91  

92  

 
93 +
    /** Define backend hooks for TCP socket operations.
 
94 +

 
95 +
        Platform backends (epoll, IOCP, kqueue, select) derive from
 
96 +
        this to implement socket I/O, connection, and option management.
 
97 +
    */
92  
    struct implementation : io_stream::implementation
98  
    struct implementation : io_stream::implementation
93  
    {
99  
    {
 
100 +
        /** Initiate an asynchronous connect to the given endpoint.
 
101 +

 
102 +
            @param h Coroutine handle to resume on completion.
 
103 +
            @param ex Executor for dispatching the completion.
 
104 +
            @param ep The remote endpoint to connect to.
 
105 +
            @param token Stop token for cancellation.
 
106 +
            @param ec Output error code.
 
107 +

 
108 +
            @return Coroutine handle to resume immediately.
 
109 +
        */
94  
        virtual std::coroutine_handle<> connect(
110  
        virtual std::coroutine_handle<> connect(
95 -
            std::coroutine_handle<>,
111 +
            std::coroutine_handle<> h,
96 -
            capy::executor_ref,
112 +
            capy::executor_ref ex,
97 -
            endpoint,
113 +
            endpoint ep,
98 -
            std::stop_token,
114 +
            std::stop_token token,
99 -
            std::error_code*) = 0;
115 +
            std::error_code* ec) = 0;
100  

116  

101 -
        virtual std::error_code shutdown(shutdown_type) noexcept = 0;
117 +
        /** Shut down the socket for the given direction(s).
 
118 +

 
119 +
            @param what The shutdown direction.
102  

120  

 
121 +
            @return Error code on failure, empty on success.
 
122 +
        */
 
123 +
        virtual std::error_code shutdown(shutdown_type what) noexcept = 0;
 
124 +

 
125 +
        /// Return the platform socket descriptor.
103  
        virtual native_handle_type native_handle() const noexcept = 0;
126  
        virtual native_handle_type native_handle() const noexcept = 0;
104  

127  

105  
        /** Request cancellation of pending asynchronous operations.
128  
        /** Request cancellation of pending asynchronous operations.
106  

129  

107  
            All outstanding operations complete with operation_canceled error.
130  
            All outstanding operations complete with operation_canceled error.
108  
            Check `ec == cond::canceled` for portable comparison.
131  
            Check `ec == cond::canceled` for portable comparison.
109  
        */
132  
        */
110  
        virtual void cancel() noexcept = 0;
133  
        virtual void cancel() noexcept = 0;
111  

134  

112  
        /** Set a socket option.
135  
        /** Set a socket option.
113  

136  

114  
            @param level The protocol level (e.g. `SOL_SOCKET`).
137  
            @param level The protocol level (e.g. `SOL_SOCKET`).
115  
            @param optname The option name (e.g. `SO_KEEPALIVE`).
138  
            @param optname The option name (e.g. `SO_KEEPALIVE`).
116  
            @param data Pointer to the option value.
139  
            @param data Pointer to the option value.
117  
            @param size Size of the option value in bytes.
140  
            @param size Size of the option value in bytes.
118  
            @return Error code on failure, empty on success.
141  
            @return Error code on failure, empty on success.
119  
        */
142  
        */
120  
        virtual std::error_code set_option(
143  
        virtual std::error_code set_option(
121  
            int level,
144  
            int level,
122  
            int optname,
145  
            int optname,
123  
            void const* data,
146  
            void const* data,
124  
            std::size_t size) noexcept = 0;
147  
            std::size_t size) noexcept = 0;
125  

148  

126  
        /** Get a socket option.
149  
        /** Get a socket option.
127  

150  

128  
            @param level The protocol level (e.g. `SOL_SOCKET`).
151  
            @param level The protocol level (e.g. `SOL_SOCKET`).
129  
            @param optname The option name (e.g. `SO_KEEPALIVE`).
152  
            @param optname The option name (e.g. `SO_KEEPALIVE`).
130  
            @param data Pointer to receive the option value.
153  
            @param data Pointer to receive the option value.
131  
            @param size On entry, the size of the buffer. On exit,
154  
            @param size On entry, the size of the buffer. On exit,
132  
                the size of the option value.
155  
                the size of the option value.
133  
            @return Error code on failure, empty on success.
156  
            @return Error code on failure, empty on success.
134  
        */
157  
        */
135  
        virtual std::error_code
158  
        virtual std::error_code
136  
        get_option(int level, int optname, void* data, std::size_t* size)
159  
        get_option(int level, int optname, void* data, std::size_t* size)
137  
            const noexcept = 0;
160  
            const noexcept = 0;
138  

161  

139 -
        /// Returns the cached local endpoint.
162 +
        /// Return the cached local endpoint.
140  
        virtual endpoint local_endpoint() const noexcept = 0;
163  
        virtual endpoint local_endpoint() const noexcept = 0;
141  

164  

142 -
        /// Returns the cached remote endpoint.
165 +
        /// Return the cached remote endpoint.
143  
        virtual endpoint remote_endpoint() const noexcept = 0;
166  
        virtual endpoint remote_endpoint() const noexcept = 0;
144  
    };
167  
    };
145  

168  

 
169 +
    /// Represent the awaitable returned by @ref connect.
146  
    struct connect_awaitable
170  
    struct connect_awaitable
147  
    {
171  
    {
148  
        tcp_socket& s_;
172  
        tcp_socket& s_;
149  
        endpoint endpoint_;
173  
        endpoint endpoint_;
150  
        std::stop_token token_;
174  
        std::stop_token token_;
151  
        mutable std::error_code ec_;
175  
        mutable std::error_code ec_;
152  

176  

153  
        connect_awaitable(tcp_socket& s, endpoint ep) noexcept
177  
        connect_awaitable(tcp_socket& s, endpoint ep) noexcept
154  
            : s_(s)
178  
            : s_(s)
155  
            , endpoint_(ep)
179  
            , endpoint_(ep)
156  
        {
180  
        {
157  
        }
181  
        }
158  

182  

159  
        bool await_ready() const noexcept
183  
        bool await_ready() const noexcept
160  
        {
184  
        {
161  
            return token_.stop_requested();
185  
            return token_.stop_requested();
162  
        }
186  
        }
163  

187  

164  
        capy::io_result<> await_resume() const noexcept
188  
        capy::io_result<> await_resume() const noexcept
165  
        {
189  
        {
166  
            if (token_.stop_requested())
190  
            if (token_.stop_requested())
167  
                return {make_error_code(std::errc::operation_canceled)};
191  
                return {make_error_code(std::errc::operation_canceled)};
168  
            return {ec_};
192  
            return {ec_};
169  
        }
193  
        }
170  

194  

171  
        auto await_suspend(std::coroutine_handle<> h, capy::io_env const* env)
195  
        auto await_suspend(std::coroutine_handle<> h, capy::io_env const* env)
172  
            -> std::coroutine_handle<>
196  
            -> std::coroutine_handle<>
173  
        {
197  
        {
174  
            token_ = env->stop_token;
198  
            token_ = env->stop_token;
175  
            return s_.get().connect(h, env->executor, endpoint_, token_, &ec_);
199  
            return s_.get().connect(h, env->executor, endpoint_, token_, &ec_);
176  
        }
200  
        }
177  
    };
201  
    };
178  

202  

179  
public:
203  
public:
180  
    /** Destructor.
204  
    /** Destructor.
181  

205  

182  
        Closes the socket if open, cancelling any pending operations.
206  
        Closes the socket if open, cancelling any pending operations.
183  
    */
207  
    */
184  
    ~tcp_socket() override;
208  
    ~tcp_socket() override;
185  

209  

186  
    /** Construct a socket from an execution context.
210  
    /** Construct a socket from an execution context.
187  

211  

188  
        @param ctx The execution context that will own this socket.
212  
        @param ctx The execution context that will own this socket.
189  
    */
213  
    */
190  
    explicit tcp_socket(capy::execution_context& ctx);
214  
    explicit tcp_socket(capy::execution_context& ctx);
191  

215  

192  
    /** Construct a socket from an executor.
216  
    /** Construct a socket from an executor.
193  

217  

194  
        The socket is associated with the executor's context.
218  
        The socket is associated with the executor's context.
195  

219  

196  
        @param ex The executor whose context will own the socket.
220  
        @param ex The executor whose context will own the socket.
197  
    */
221  
    */
198  
    template<class Ex>
222  
    template<class Ex>
199  
        requires(!std::same_as<std::remove_cvref_t<Ex>, tcp_socket>) &&
223  
        requires(!std::same_as<std::remove_cvref_t<Ex>, tcp_socket>) &&
200  
        capy::Executor<Ex>
224  
        capy::Executor<Ex>
201  
    explicit tcp_socket(Ex const& ex) : tcp_socket(ex.context())
225  
    explicit tcp_socket(Ex const& ex) : tcp_socket(ex.context())
202  
    {
226  
    {
203  
    }
227  
    }
204  

228  

205  
    /** Move constructor.
229  
    /** Move constructor.
206  

230  

207  
        Transfers ownership of the socket resources.
231  
        Transfers ownership of the socket resources.
208  

232  

209  
        @param other The socket to move from.
233  
        @param other The socket to move from.
210  

234  

211  
        @pre No awaitables returned by @p other's methods exist.
235  
        @pre No awaitables returned by @p other's methods exist.
212  
        @pre @p other is not referenced as a peer in any outstanding
236  
        @pre @p other is not referenced as a peer in any outstanding
213  
            accept awaitable.
237  
            accept awaitable.
214  
        @pre The execution context associated with @p other must
238  
        @pre The execution context associated with @p other must
215  
            outlive this socket.
239  
            outlive this socket.
216  
    */
240  
    */
217  
    tcp_socket(tcp_socket&& other) noexcept : io_object(std::move(other)) {}
241  
    tcp_socket(tcp_socket&& other) noexcept : io_object(std::move(other)) {}
218  

242  

219  
    /** Move assignment operator.
243  
    /** Move assignment operator.
220  

244  

221  
        Closes any existing socket and transfers ownership.
245  
        Closes any existing socket and transfers ownership.
222  

246  

223  
        @param other The socket to move from.
247  
        @param other The socket to move from.
224  

248  

225  
        @pre No awaitables returned by either `*this` or @p other's
249  
        @pre No awaitables returned by either `*this` or @p other's
226  
            methods exist.
250  
            methods exist.
227  
        @pre Neither `*this` nor @p other is referenced as a peer in
251  
        @pre Neither `*this` nor @p other is referenced as a peer in
228  
            any outstanding accept awaitable.
252  
            any outstanding accept awaitable.
229  
        @pre The execution context associated with @p other must
253  
        @pre The execution context associated with @p other must
230  
            outlive this socket.
254  
            outlive this socket.
231  

255  

232  
        @return Reference to this socket.
256  
        @return Reference to this socket.
233  
    */
257  
    */
234  
    tcp_socket& operator=(tcp_socket&& other) noexcept
258  
    tcp_socket& operator=(tcp_socket&& other) noexcept
235  
    {
259  
    {
236  
        if (this != &other)
260  
        if (this != &other)
237  
        {
261  
        {
238  
            close();
262  
            close();
239  
            h_ = std::move(other.h_);
263  
            h_ = std::move(other.h_);
240  
        }
264  
        }
241  
        return *this;
265  
        return *this;
242  
    }
266  
    }
243  

267  

244  
    tcp_socket(tcp_socket const&)            = delete;
268  
    tcp_socket(tcp_socket const&)            = delete;
245  
    tcp_socket& operator=(tcp_socket const&) = delete;
269  
    tcp_socket& operator=(tcp_socket const&) = delete;
246  

270  

247  
    /** Open the socket.
271  
    /** Open the socket.
248  

272  

249  
        Creates a TCP socket and associates it with the platform
273  
        Creates a TCP socket and associates it with the platform
250  
        reactor (IOCP on Windows). Calling @ref connect on a closed
274  
        reactor (IOCP on Windows). Calling @ref connect on a closed
251  
        socket opens it automatically with the endpoint's address family,
275  
        socket opens it automatically with the endpoint's address family,
252  
        so explicit `open()` is only needed when socket options must be
276  
        so explicit `open()` is only needed when socket options must be
253  
        set before connecting.
277  
        set before connecting.
254  

278  

255  
        @param proto The protocol (IPv4 or IPv6). Defaults to
279  
        @param proto The protocol (IPv4 or IPv6). Defaults to
256  
            `tcp::v4()`.
280  
            `tcp::v4()`.
257  

281  

258  
        @throws std::system_error on failure.
282  
        @throws std::system_error on failure.
259  
    */
283  
    */
260  
    void open(tcp proto = tcp::v4());
284  
    void open(tcp proto = tcp::v4());
261  

285  

262  
    /** Close the socket.
286  
    /** Close the socket.
263  

287  

264  
        Releases socket resources. Any pending operations complete
288  
        Releases socket resources. Any pending operations complete
265  
        with `errc::operation_canceled`.
289  
        with `errc::operation_canceled`.
266  
    */
290  
    */
267  
    void close();
291  
    void close();
268  

292  

269  
    /** Check if the socket is open.
293  
    /** Check if the socket is open.
270  

294  

271  
        @return `true` if the socket is open and ready for operations.
295  
        @return `true` if the socket is open and ready for operations.
272  
    */
296  
    */
273  
    bool is_open() const noexcept
297  
    bool is_open() const noexcept
274  
    {
298  
    {
275  
#if BOOST_COROSIO_HAS_IOCP && !defined(BOOST_COROSIO_MRDOCS)
299  
#if BOOST_COROSIO_HAS_IOCP && !defined(BOOST_COROSIO_MRDOCS)
276  
        return h_ && get().native_handle() != ~native_handle_type(0);
300  
        return h_ && get().native_handle() != ~native_handle_type(0);
277  
#else
301  
#else
278  
        return h_ && get().native_handle() >= 0;
302  
        return h_ && get().native_handle() >= 0;
279  
#endif
303  
#endif
280  
    }
304  
    }
281  

305  

282  
    /** Initiate an asynchronous connect operation.
306  
    /** Initiate an asynchronous connect operation.
283  

307  

284  
        If the socket is not already open, it is opened automatically
308  
        If the socket is not already open, it is opened automatically
285  
        using the address family of @p ep (IPv4 or IPv6). If the socket
309  
        using the address family of @p ep (IPv4 or IPv6). If the socket
286  
        is already open, the existing file descriptor is used as-is.
310  
        is already open, the existing file descriptor is used as-is.
287  

311  

288  
        The operation supports cancellation via `std::stop_token` through
312  
        The operation supports cancellation via `std::stop_token` through
289  
        the affine awaitable protocol. If the associated stop token is
313  
        the affine awaitable protocol. If the associated stop token is
290  
        triggered, the operation completes immediately with
314  
        triggered, the operation completes immediately with
291  
        `errc::operation_canceled`.
315  
        `errc::operation_canceled`.
292  

316  

293  
        @param ep The remote endpoint to connect to.
317  
        @param ep The remote endpoint to connect to.
294  

318  

295  
        @return An awaitable that completes with `io_result<>`.
319  
        @return An awaitable that completes with `io_result<>`.
296  
            Returns success (default error_code) on successful connection,
320  
            Returns success (default error_code) on successful connection,
297  
            or an error code on failure including:
321  
            or an error code on failure including:
298  
            - connection_refused: No server listening at endpoint
322  
            - connection_refused: No server listening at endpoint
299  
            - timed_out: Connection attempt timed out
323  
            - timed_out: Connection attempt timed out
300  
            - network_unreachable: No route to host
324  
            - network_unreachable: No route to host
301  
            - operation_canceled: Cancelled via stop_token or cancel().
325  
            - operation_canceled: Cancelled via stop_token or cancel().
302  
                Check `ec == cond::canceled` for portable comparison.
326  
                Check `ec == cond::canceled` for portable comparison.
303  

327  

304  
        @throws std::system_error if the socket needs to be opened
328  
        @throws std::system_error if the socket needs to be opened
305  
            and the open fails.
329  
            and the open fails.
306  

330  

307  
        @par Preconditions
331  
        @par Preconditions
308  
        This socket must outlive the returned awaitable.
332  
        This socket must outlive the returned awaitable.
309  

333  

310  
        @par Example
334  
        @par Example
311  
        @code
335  
        @code
312  
        // Socket opened automatically with correct address family:
336  
        // Socket opened automatically with correct address family:
313  
        auto [ec] = co_await s.connect(endpoint);
337  
        auto [ec] = co_await s.connect(endpoint);
314  
        if (ec) { ... }
338  
        if (ec) { ... }
315  
        @endcode
339  
        @endcode
316  
    */
340  
    */
317  
    auto connect(endpoint ep)
341  
    auto connect(endpoint ep)
318  
    {
342  
    {
319  
        if (!is_open())
343  
        if (!is_open())
320  
            open(ep.is_v6() ? tcp::v6() : tcp::v4());
344  
            open(ep.is_v6() ? tcp::v6() : tcp::v4());
321  
        return connect_awaitable(*this, ep);
345  
        return connect_awaitable(*this, ep);
322  
    }
346  
    }
323  

347  

324  
    /** Cancel any pending asynchronous operations.
348  
    /** Cancel any pending asynchronous operations.
325  

349  

326  
        All outstanding operations complete with `errc::operation_canceled`.
350  
        All outstanding operations complete with `errc::operation_canceled`.
327  
        Check `ec == cond::canceled` for portable comparison.
351  
        Check `ec == cond::canceled` for portable comparison.
328  
    */
352  
    */
329  
    void cancel();
353  
    void cancel();
330  

354  

331  
    /** Get the native socket handle.
355  
    /** Get the native socket handle.
332  

356  

333  
        Returns the underlying platform-specific socket descriptor.
357  
        Returns the underlying platform-specific socket descriptor.
334  
        On POSIX systems this is an `int` file descriptor.
358  
        On POSIX systems this is an `int` file descriptor.
335  
        On Windows this is a `SOCKET` handle.
359  
        On Windows this is a `SOCKET` handle.
336  

360  

337  
        @return The native socket handle, or -1/INVALID_SOCKET if not open.
361  
        @return The native socket handle, or -1/INVALID_SOCKET if not open.
338  

362  

339  
        @par Preconditions
363  
        @par Preconditions
340  
        None. May be called on closed sockets.
364  
        None. May be called on closed sockets.
341  
    */
365  
    */
342  
    native_handle_type native_handle() const noexcept;
366  
    native_handle_type native_handle() const noexcept;
343  

367  

344  
    /** Disable sends or receives on the socket.
368  
    /** Disable sends or receives on the socket.
345  

369  

346  
        TCP connections are full-duplex: each direction (send and receive)
370  
        TCP connections are full-duplex: each direction (send and receive)
347  
        operates independently. This function allows you to close one or
371  
        operates independently. This function allows you to close one or
348  
        both directions without destroying the socket.
372  
        both directions without destroying the socket.
349  

373  

350  
        @li @ref shutdown_send sends a TCP FIN packet to the peer,
374  
        @li @ref shutdown_send sends a TCP FIN packet to the peer,
351  
            signaling that you have no more data to send. You can still
375  
            signaling that you have no more data to send. You can still
352  
            receive data until the peer also closes their send direction.
376  
            receive data until the peer also closes their send direction.
353  
            This is the most common use case, typically called before
377  
            This is the most common use case, typically called before
354  
            close() to ensure graceful connection termination.
378  
            close() to ensure graceful connection termination.
355  

379  

356  
        @li @ref shutdown_receive disables reading on the socket. This
380  
        @li @ref shutdown_receive disables reading on the socket. This
357  
            does NOT send anything to the peer - they are not informed
381  
            does NOT send anything to the peer - they are not informed
358  
            and may continue sending data. Subsequent reads will fail
382  
            and may continue sending data. Subsequent reads will fail
359  
            or return end-of-file. Incoming data may be discarded or
383  
            or return end-of-file. Incoming data may be discarded or
360  
            buffered depending on the operating system.
384  
            buffered depending on the operating system.
361  

385  

362  
        @li @ref shutdown_both combines both effects: sends a FIN and
386  
        @li @ref shutdown_both combines both effects: sends a FIN and
363  
            disables reading.
387  
            disables reading.
364  

388  

365  
        When the peer shuts down their send direction (sends a FIN),
389  
        When the peer shuts down their send direction (sends a FIN),
366  
        subsequent read operations will complete with `capy::cond::eof`.
390  
        subsequent read operations will complete with `capy::cond::eof`.
367  
        Use the portable condition test rather than comparing error
391  
        Use the portable condition test rather than comparing error
368  
        codes directly:
392  
        codes directly:
369  

393  

370  
        @code
394  
        @code
371  
        auto [ec, n] = co_await sock.read_some(buffer);
395  
        auto [ec, n] = co_await sock.read_some(buffer);
372  
        if (ec == capy::cond::eof)
396  
        if (ec == capy::cond::eof)
373  
        {
397  
        {
374  
            // Peer closed their send direction
398  
            // Peer closed their send direction
375  
        }
399  
        }
376  
        @endcode
400  
        @endcode
377  

401  

378  
        Any error from the underlying system call is silently discarded
402  
        Any error from the underlying system call is silently discarded
379  
        because it is unlikely to be helpful.
403  
        because it is unlikely to be helpful.
380  

404  

381  
        @param what Determines what operations will no longer be allowed.
405  
        @param what Determines what operations will no longer be allowed.
382  
    */
406  
    */
383  
    void shutdown(shutdown_type what);
407  
    void shutdown(shutdown_type what);
384  

408  

385  
    /** Set a socket option.
409  
    /** Set a socket option.
386  

410  

387  
        Applies a type-safe socket option to the underlying socket.
411  
        Applies a type-safe socket option to the underlying socket.
388  
        The option type encodes the protocol level and option name.
412  
        The option type encodes the protocol level and option name.
389  

413  

390  
        @par Example
414  
        @par Example
391  
        @code
415  
        @code
392  
        sock.set_option( socket_option::no_delay( true ) );
416  
        sock.set_option( socket_option::no_delay( true ) );
393  
        sock.set_option( socket_option::receive_buffer_size( 65536 ) );
417  
        sock.set_option( socket_option::receive_buffer_size( 65536 ) );
394  
        @endcode
418  
        @endcode
395  

419  

396  
        @param opt The option to set.
420  
        @param opt The option to set.
397  

421  

398  
        @throws std::logic_error if the socket is not open.
422  
        @throws std::logic_error if the socket is not open.
399  
        @throws std::system_error on failure.
423  
        @throws std::system_error on failure.
400  
    */
424  
    */
401  
    template<class Option>
425  
    template<class Option>
402  
    void set_option(Option const& opt)
426  
    void set_option(Option const& opt)
403  
    {
427  
    {
404  
        if (!is_open())
428  
        if (!is_open())
405  
            detail::throw_logic_error("set_option: socket not open");
429  
            detail::throw_logic_error("set_option: socket not open");
406  
        std::error_code ec = get().set_option(
430  
        std::error_code ec = get().set_option(
407  
            Option::level(), Option::name(), opt.data(), opt.size());
431  
            Option::level(), Option::name(), opt.data(), opt.size());
408  
        if (ec)
432  
        if (ec)
409  
            detail::throw_system_error(ec, "tcp_socket::set_option");
433  
            detail::throw_system_error(ec, "tcp_socket::set_option");
410  
    }
434  
    }
411  

435  

412  
    /** Get a socket option.
436  
    /** Get a socket option.
413  

437  

414  
        Retrieves the current value of a type-safe socket option.
438  
        Retrieves the current value of a type-safe socket option.
415  

439  

416  
        @par Example
440  
        @par Example
417  
        @code
441  
        @code
418  
        auto nd = sock.get_option<socket_option::no_delay>();
442  
        auto nd = sock.get_option<socket_option::no_delay>();
419  
        if ( nd.value() )
443  
        if ( nd.value() )
420  
            // Nagle's algorithm is disabled
444  
            // Nagle's algorithm is disabled
421  
        @endcode
445  
        @endcode
422  

446  

423  
        @return The current option value.
447  
        @return The current option value.
424  

448  

425  
        @throws std::logic_error if the socket is not open.
449  
        @throws std::logic_error if the socket is not open.
426  
        @throws std::system_error on failure.
450  
        @throws std::system_error on failure.
427  
    */
451  
    */
428  
    template<class Option>
452  
    template<class Option>
429  
    Option get_option() const
453  
    Option get_option() const
430  
    {
454  
    {
431  
        if (!is_open())
455  
        if (!is_open())
432  
            detail::throw_logic_error("get_option: socket not open");
456  
            detail::throw_logic_error("get_option: socket not open");
433  
        Option opt{};
457  
        Option opt{};
434  
        std::size_t sz = opt.size();
458  
        std::size_t sz = opt.size();
435  
        std::error_code ec =
459  
        std::error_code ec =
436  
            get().get_option(Option::level(), Option::name(), opt.data(), &sz);
460  
            get().get_option(Option::level(), Option::name(), opt.data(), &sz);
437  
        if (ec)
461  
        if (ec)
438  
            detail::throw_system_error(ec, "tcp_socket::get_option");
462  
            detail::throw_system_error(ec, "tcp_socket::get_option");
439  
        opt.resize(sz);
463  
        opt.resize(sz);
440  
        return opt;
464  
        return opt;
441  
    }
465  
    }
442  

466  

443  
    /** Get the local endpoint of the socket.
467  
    /** Get the local endpoint of the socket.
444  

468  

445  
        Returns the local address and port to which the socket is bound.
469  
        Returns the local address and port to which the socket is bound.
446  
        For a connected socket, this is the local side of the connection.
470  
        For a connected socket, this is the local side of the connection.
447  
        The endpoint is cached when the connection is established.
471  
        The endpoint is cached when the connection is established.
448  

472  

449  
        @return The local endpoint, or a default endpoint (0.0.0.0:0) if
473  
        @return The local endpoint, or a default endpoint (0.0.0.0:0) if
450  
            the socket is not connected.
474  
            the socket is not connected.
451  

475  

452  
        @par Thread Safety
476  
        @par Thread Safety
453  
        The cached endpoint value is set during connect/accept completion
477  
        The cached endpoint value is set during connect/accept completion
454  
        and cleared during close(). This function may be called concurrently
478  
        and cleared during close(). This function may be called concurrently
455  
        with I/O operations, but must not be called concurrently with
479  
        with I/O operations, but must not be called concurrently with
456  
        connect(), accept(), or close().
480  
        connect(), accept(), or close().
457  
    */
481  
    */
458  
    endpoint local_endpoint() const noexcept;
482  
    endpoint local_endpoint() const noexcept;
459  

483  

460  
    /** Get the remote endpoint of the socket.
484  
    /** Get the remote endpoint of the socket.
461  

485  

462  
        Returns the remote address and port to which the socket is connected.
486  
        Returns the remote address and port to which the socket is connected.
463  
        The endpoint is cached when the connection is established.
487  
        The endpoint is cached when the connection is established.
464  

488  

465  
        @return The remote endpoint, or a default endpoint (0.0.0.0:0) if
489  
        @return The remote endpoint, or a default endpoint (0.0.0.0:0) if
466  
            the socket is not connected.
490  
            the socket is not connected.
467  

491  

468  
        @par Thread Safety
492  
        @par Thread Safety
469  
        The cached endpoint value is set during connect/accept completion
493  
        The cached endpoint value is set during connect/accept completion
470  
        and cleared during close(). This function may be called concurrently
494  
        and cleared during close(). This function may be called concurrently
471  
        with I/O operations, but must not be called concurrently with
495  
        with I/O operations, but must not be called concurrently with
472  
        connect(), accept(), or close().
496  
        connect(), accept(), or close().
473  
    */
497  
    */
474  
    endpoint remote_endpoint() const noexcept;
498  
    endpoint remote_endpoint() const noexcept;
475  

499  

476  
protected:
500  
protected:
477  
    tcp_socket() noexcept = default;
501  
    tcp_socket() noexcept = default;
478  

502  

479  
    explicit tcp_socket(handle h) noexcept : io_object(std::move(h)) {}
503  
    explicit tcp_socket(handle h) noexcept : io_object(std::move(h)) {}
480  

504  

481  
private:
505  
private:
482  
    friend class tcp_acceptor;
506  
    friend class tcp_acceptor;
483  

507  

484  
    /// Open the socket for the given protocol triple.
508  
    /// Open the socket for the given protocol triple.
485  
    void open_for_family(int family, int type, int protocol);
509  
    void open_for_family(int family, int type, int protocol);
486  

510  

487  
    inline implementation& get() const noexcept
511  
    inline implementation& get() const noexcept
488  
    {
512  
    {
489  
        return *static_cast<implementation*>(h_.get());
513  
        return *static_cast<implementation*>(h_.get());
490  
    }
514  
    }
491  
};
515  
};
492  

516  

493  
} // namespace boost::corosio
517  
} // namespace boost::corosio
494  

518  

495  
#endif
519  
#endif