2 // detail/win_iocp_socket_service.hpp
3 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5 // Copyright (c) 2003-2022 Christopher M. Kohlhoff (chris at kohlhoff dot com)
7 // Distributed under the Boost Software License, Version 1.0. (See accompanying
8 // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
11 #ifndef BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP
12 #define BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP
14 #if defined(_MSC_VER) && (_MSC_VER >= 1200)
16 #endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
18 #include <boost/asio/detail/config.hpp>
20 #if defined(BOOST_ASIO_HAS_IOCP)
23 #include <boost/asio/error.hpp>
24 #include <boost/asio/execution_context.hpp>
25 #include <boost/asio/socket_base.hpp>
26 #include <boost/asio/detail/bind_handler.hpp>
27 #include <boost/asio/detail/buffer_sequence_adapter.hpp>
28 #include <boost/asio/detail/fenced_block.hpp>
29 #include <boost/asio/detail/handler_alloc_helpers.hpp>
30 #include <boost/asio/detail/handler_invoke_helpers.hpp>
31 #include <boost/asio/detail/memory.hpp>
32 #include <boost/asio/detail/mutex.hpp>
33 #include <boost/asio/detail/operation.hpp>
34 #include <boost/asio/detail/reactor_op.hpp>
35 #include <boost/asio/detail/select_reactor.hpp>
36 #include <boost/asio/detail/socket_holder.hpp>
37 #include <boost/asio/detail/socket_ops.hpp>
38 #include <boost/asio/detail/socket_types.hpp>
39 #include <boost/asio/detail/win_iocp_io_context.hpp>
40 #include <boost/asio/detail/win_iocp_null_buffers_op.hpp>
41 #include <boost/asio/detail/win_iocp_socket_accept_op.hpp>
42 #include <boost/asio/detail/win_iocp_socket_connect_op.hpp>
43 #include <boost/asio/detail/win_iocp_socket_recvfrom_op.hpp>
44 #include <boost/asio/detail/win_iocp_socket_send_op.hpp>
45 #include <boost/asio/detail/win_iocp_socket_service_base.hpp>
47 #include <boost/asio/detail/push_options.hpp>
53 template <typename Protocol>
54 class win_iocp_socket_service :
55 public execution_context_service_base<win_iocp_socket_service<Protocol> >,
56 public win_iocp_socket_service_base
60 typedef Protocol protocol_type;
63 typedef typename Protocol::endpoint endpoint_type;
65 // The native type of a socket.
66 class native_handle_type
69 native_handle_type(socket_type s)
71 have_remote_endpoint_(false)
75 native_handle_type(socket_type s, const endpoint_type& ep)
77 have_remote_endpoint_(true),
82 void operator=(socket_type s)
85 have_remote_endpoint_ = false;
86 remote_endpoint_ = endpoint_type();
89 operator socket_type() const
94 bool have_remote_endpoint() const
96 return have_remote_endpoint_;
99 endpoint_type remote_endpoint() const
101 return remote_endpoint_;
106 bool have_remote_endpoint_;
107 endpoint_type remote_endpoint_;
110 // The implementation type of the socket.
111 struct implementation_type :
112 win_iocp_socket_service_base::base_implementation_type
114 // Default constructor.
115 implementation_type()
116 : protocol_(endpoint_type().protocol()),
117 have_remote_endpoint_(false),
122 // The protocol associated with the socket.
123 protocol_type protocol_;
125 // Whether we have a cached remote endpoint.
126 bool have_remote_endpoint_;
128 // A cached remote endpoint.
129 endpoint_type remote_endpoint_;
133 win_iocp_socket_service(execution_context& context)
134 : execution_context_service_base<
135 win_iocp_socket_service<Protocol> >(context),
136 win_iocp_socket_service_base(context)
140 // Destroy all user-defined handler objects owned by the service.
143 this->base_shutdown();
146 // Move-construct a new socket implementation.
147 void move_construct(implementation_type& impl,
148 implementation_type& other_impl) BOOST_ASIO_NOEXCEPT
150 this->base_move_construct(impl, other_impl);
152 impl.protocol_ = other_impl.protocol_;
153 other_impl.protocol_ = endpoint_type().protocol();
155 impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_;
156 other_impl.have_remote_endpoint_ = false;
158 impl.remote_endpoint_ = other_impl.remote_endpoint_;
159 other_impl.remote_endpoint_ = endpoint_type();
162 // Move-assign from another socket implementation.
163 void move_assign(implementation_type& impl,
164 win_iocp_socket_service_base& other_service,
165 implementation_type& other_impl)
167 this->base_move_assign(impl, other_service, other_impl);
169 impl.protocol_ = other_impl.protocol_;
170 other_impl.protocol_ = endpoint_type().protocol();
172 impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_;
173 other_impl.have_remote_endpoint_ = false;
175 impl.remote_endpoint_ = other_impl.remote_endpoint_;
176 other_impl.remote_endpoint_ = endpoint_type();
179 // Move-construct a new socket implementation from another protocol type.
180 template <typename Protocol1>
181 void converting_move_construct(implementation_type& impl,
182 win_iocp_socket_service<Protocol1>&,
183 typename win_iocp_socket_service<
184 Protocol1>::implementation_type& other_impl)
186 this->base_move_construct(impl, other_impl);
188 impl.protocol_ = protocol_type(other_impl.protocol_);
189 other_impl.protocol_ = typename Protocol1::endpoint().protocol();
191 impl.have_remote_endpoint_ = other_impl.have_remote_endpoint_;
192 other_impl.have_remote_endpoint_ = false;
194 impl.remote_endpoint_ = other_impl.remote_endpoint_;
195 other_impl.remote_endpoint_ = typename Protocol1::endpoint();
198 // Open a new socket implementation.
199 boost::system::error_code open(implementation_type& impl,
200 const protocol_type& protocol, boost::system::error_code& ec)
202 if (!do_open(impl, protocol.family(),
203 protocol.type(), protocol.protocol(), ec))
205 impl.protocol_ = protocol;
206 impl.have_remote_endpoint_ = false;
207 impl.remote_endpoint_ = endpoint_type();
212 // Assign a native socket to a socket implementation.
213 boost::system::error_code assign(implementation_type& impl,
214 const protocol_type& protocol, const native_handle_type& native_socket,
215 boost::system::error_code& ec)
217 if (!do_assign(impl, protocol.type(), native_socket, ec))
219 impl.protocol_ = protocol;
220 impl.have_remote_endpoint_ = native_socket.have_remote_endpoint();
221 impl.remote_endpoint_ = native_socket.remote_endpoint();
226 // Get the native socket representation.
227 native_handle_type native_handle(implementation_type& impl)
229 if (impl.have_remote_endpoint_)
230 return native_handle_type(impl.socket_, impl.remote_endpoint_);
231 return native_handle_type(impl.socket_);
234 // Bind the socket to the specified local endpoint.
235 boost::system::error_code bind(implementation_type& impl,
236 const endpoint_type& endpoint, boost::system::error_code& ec)
238 socket_ops::bind(impl.socket_, endpoint.data(), endpoint.size(), ec);
242 // Set a socket option.
243 template <typename Option>
244 boost::system::error_code set_option(implementation_type& impl,
245 const Option& option, boost::system::error_code& ec)
247 socket_ops::setsockopt(impl.socket_, impl.state_,
248 option.level(impl.protocol_), option.name(impl.protocol_),
249 option.data(impl.protocol_), option.size(impl.protocol_), ec);
253 // Set a socket option.
254 template <typename Option>
255 boost::system::error_code get_option(const implementation_type& impl,
256 Option& option, boost::system::error_code& ec) const
258 std::size_t size = option.size(impl.protocol_);
259 socket_ops::getsockopt(impl.socket_, impl.state_,
260 option.level(impl.protocol_), option.name(impl.protocol_),
261 option.data(impl.protocol_), &size, ec);
263 option.resize(impl.protocol_, size);
267 // Get the local endpoint.
268 endpoint_type local_endpoint(const implementation_type& impl,
269 boost::system::error_code& ec) const
271 endpoint_type endpoint;
272 std::size_t addr_len = endpoint.capacity();
273 if (socket_ops::getsockname(impl.socket_, endpoint.data(), &addr_len, ec))
274 return endpoint_type();
275 endpoint.resize(addr_len);
279 // Get the remote endpoint.
280 endpoint_type remote_endpoint(const implementation_type& impl,
281 boost::system::error_code& ec) const
283 endpoint_type endpoint = impl.remote_endpoint_;
284 std::size_t addr_len = endpoint.capacity();
285 if (socket_ops::getpeername(impl.socket_, endpoint.data(),
286 &addr_len, impl.have_remote_endpoint_, ec))
287 return endpoint_type();
288 endpoint.resize(addr_len);
292 // Disable sends or receives on the socket.
293 boost::system::error_code shutdown(base_implementation_type& impl,
294 socket_base::shutdown_type what, boost::system::error_code& ec)
296 socket_ops::shutdown(impl.socket_, what, ec);
300 // Send a datagram to the specified endpoint. Returns the number of bytes
302 template <typename ConstBufferSequence>
303 size_t send_to(implementation_type& impl, const ConstBufferSequence& buffers,
304 const endpoint_type& destination, socket_base::message_flags flags,
305 boost::system::error_code& ec)
307 buffer_sequence_adapter<boost::asio::const_buffer,
308 ConstBufferSequence> bufs(buffers);
310 return socket_ops::sync_sendto(impl.socket_, impl.state_,
311 bufs.buffers(), bufs.count(), flags,
312 destination.data(), destination.size(), ec);
315 // Wait until data can be sent without blocking.
316 size_t send_to(implementation_type& impl, const null_buffers&,
317 const endpoint_type&, socket_base::message_flags,
318 boost::system::error_code& ec)
320 // Wait for socket to become ready.
321 socket_ops::poll_write(impl.socket_, impl.state_, -1, ec);
326 // Start an asynchronous send. The data being sent must be valid for the
327 // lifetime of the asynchronous operation.
328 template <typename ConstBufferSequence, typename Handler, typename IoExecutor>
329 void async_send_to(implementation_type& impl,
330 const ConstBufferSequence& buffers, const endpoint_type& destination,
331 socket_base::message_flags flags, Handler& handler,
332 const IoExecutor& io_ex)
334 typename associated_cancellation_slot<Handler>::type slot
335 = boost::asio::get_associated_cancellation_slot(handler);
337 // Allocate and construct an operation to wrap the handler.
338 typedef win_iocp_socket_send_op<
339 ConstBufferSequence, Handler, IoExecutor> op;
340 typename op::ptr p = { boost::asio::detail::addressof(handler),
341 op::ptr::allocate(handler), 0 };
342 operation* o = p.p = new (p.v) op(
343 impl.cancel_token_, buffers, handler, io_ex);
345 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
346 &impl, impl.socket_, "async_send_to"));
348 buffer_sequence_adapter<boost::asio::const_buffer,
349 ConstBufferSequence> bufs(buffers);
351 // Optionally register for per-operation cancellation.
352 if (slot.is_connected())
353 o = &slot.template emplace<iocp_op_cancellation>(impl.socket_, o);
355 start_send_to_op(impl, bufs.buffers(), bufs.count(),
356 destination.data(), static_cast<int>(destination.size()),
361 // Start an asynchronous wait until data can be sent without blocking.
362 template <typename Handler, typename IoExecutor>
363 void async_send_to(implementation_type& impl, const null_buffers&,
364 const endpoint_type&, socket_base::message_flags, Handler& handler,
365 const IoExecutor& io_ex)
367 // Allocate and construct an operation to wrap the handler.
368 typedef win_iocp_null_buffers_op<Handler, IoExecutor> op;
369 typename op::ptr p = { boost::asio::detail::addressof(handler),
370 op::ptr::allocate(handler), 0 };
371 reactor_op* o = p.p = new (p.v) op(impl.cancel_token_, handler, io_ex);
373 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
374 &impl, impl.socket_, "async_send_to(null_buffers)"));
376 start_reactor_op(impl, select_reactor::write_op, o);
380 // Receive a datagram with the endpoint of the sender. Returns the number of
382 template <typename MutableBufferSequence>
383 size_t receive_from(implementation_type& impl,
384 const MutableBufferSequence& buffers,
385 endpoint_type& sender_endpoint, socket_base::message_flags flags,
386 boost::system::error_code& ec)
388 buffer_sequence_adapter<boost::asio::mutable_buffer,
389 MutableBufferSequence> bufs(buffers);
391 std::size_t addr_len = sender_endpoint.capacity();
392 std::size_t bytes_recvd = socket_ops::sync_recvfrom(
393 impl.socket_, impl.state_, bufs.buffers(), bufs.count(),
394 flags, sender_endpoint.data(), &addr_len, ec);
397 sender_endpoint.resize(addr_len);
402 // Wait until data can be received without blocking.
403 size_t receive_from(implementation_type& impl,
404 const null_buffers&, endpoint_type& sender_endpoint,
405 socket_base::message_flags, boost::system::error_code& ec)
407 // Wait for socket to become ready.
408 socket_ops::poll_read(impl.socket_, impl.state_, -1, ec);
410 // Reset endpoint since it can be given no sensible value at this time.
411 sender_endpoint = endpoint_type();
416 // Start an asynchronous receive. The buffer for the data being received and
417 // the sender_endpoint object must both be valid for the lifetime of the
418 // asynchronous operation.
419 template <typename MutableBufferSequence,
420 typename Handler, typename IoExecutor>
421 void async_receive_from(implementation_type& impl,
422 const MutableBufferSequence& buffers, endpoint_type& sender_endp,
423 socket_base::message_flags flags, Handler& handler,
424 const IoExecutor& io_ex)
426 typename associated_cancellation_slot<Handler>::type slot
427 = boost::asio::get_associated_cancellation_slot(handler);
429 // Allocate and construct an operation to wrap the handler.
430 typedef win_iocp_socket_recvfrom_op<MutableBufferSequence,
431 endpoint_type, Handler, IoExecutor> op;
432 typename op::ptr p = { boost::asio::detail::addressof(handler),
433 op::ptr::allocate(handler), 0 };
434 operation* o = p.p = new (p.v) op(sender_endp,
435 impl.cancel_token_, buffers, handler, io_ex);
437 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
438 &impl, impl.socket_, "async_receive_from"));
440 buffer_sequence_adapter<boost::asio::mutable_buffer,
441 MutableBufferSequence> bufs(buffers);
443 // Optionally register for per-operation cancellation.
444 if (slot.is_connected())
445 o = &slot.template emplace<iocp_op_cancellation>(impl.socket_, o);
447 start_receive_from_op(impl, bufs.buffers(), bufs.count(),
448 sender_endp.data(), flags, &p.p->endpoint_size(), o);
452 // Wait until data can be received without blocking.
453 template <typename Handler, typename IoExecutor>
454 void async_receive_from(implementation_type& impl, const null_buffers&,
455 endpoint_type& sender_endpoint, socket_base::message_flags flags,
456 Handler& handler, const IoExecutor& io_ex)
458 typename associated_cancellation_slot<Handler>::type slot
459 = boost::asio::get_associated_cancellation_slot(handler);
461 // Allocate and construct an operation to wrap the handler.
462 typedef win_iocp_null_buffers_op<Handler, IoExecutor> op;
463 typename op::ptr p = { boost::asio::detail::addressof(handler),
464 op::ptr::allocate(handler), 0 };
465 p.p = new (p.v) op(impl.cancel_token_, handler, io_ex);
467 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
468 &impl, impl.socket_, "async_receive_from(null_buffers)"));
470 // Reset endpoint since it can be given no sensible value at this time.
471 sender_endpoint = endpoint_type();
473 // Optionally register for per-operation cancellation.
474 operation* iocp_op = p.p;
475 if (slot.is_connected())
477 p.p->cancellation_key_ = iocp_op =
478 &slot.template emplace<reactor_op_cancellation>(
479 impl.socket_, iocp_op);
482 int op_type = start_null_buffers_receive_op(impl, flags, p.p, iocp_op);
485 // Update cancellation method if the reactor was used.
486 if (slot.is_connected() && op_type != -1)
488 static_cast<reactor_op_cancellation*>(iocp_op)->use_reactor(
489 &get_reactor(), &impl.reactor_data_, op_type);
493 // Accept a new connection.
494 template <typename Socket>
495 boost::system::error_code accept(implementation_type& impl, Socket& peer,
496 endpoint_type* peer_endpoint, boost::system::error_code& ec)
498 // We cannot accept a socket that is already open.
501 ec = boost::asio::error::already_open;
505 std::size_t addr_len = peer_endpoint ? peer_endpoint->capacity() : 0;
506 socket_holder new_socket(socket_ops::sync_accept(impl.socket_,
507 impl.state_, peer_endpoint ? peer_endpoint->data() : 0,
508 peer_endpoint ? &addr_len : 0, ec));
510 // On success, assign new connection to peer socket object.
511 if (new_socket.get() != invalid_socket)
514 peer_endpoint->resize(addr_len);
515 peer.assign(impl.protocol_, new_socket.get(), ec);
517 new_socket.release();
523 // Start an asynchronous accept. The peer and peer_endpoint objects
524 // must be valid until the accept's handler is invoked.
525 template <typename Socket, typename Handler, typename IoExecutor>
526 void async_accept(implementation_type& impl, Socket& peer,
527 endpoint_type* peer_endpoint, Handler& handler, const IoExecutor& io_ex)
529 typename associated_cancellation_slot<Handler>::type slot
530 = boost::asio::get_associated_cancellation_slot(handler);
532 // Allocate and construct an operation to wrap the handler.
533 typedef win_iocp_socket_accept_op<Socket,
534 protocol_type, Handler, IoExecutor> op;
535 typename op::ptr p = { boost::asio::detail::addressof(handler),
536 op::ptr::allocate(handler), 0 };
537 bool enable_connection_aborted =
538 (impl.state_ & socket_ops::enable_connection_aborted) != 0;
539 operation* o = p.p = new (p.v) op(*this, impl.socket_, peer, impl.protocol_,
540 peer_endpoint, enable_connection_aborted, handler, io_ex);
542 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
543 &impl, impl.socket_, "async_accept"));
545 // Optionally register for per-operation cancellation.
546 if (slot.is_connected())
548 accept_op_cancellation* c =
549 &slot.template emplace<accept_op_cancellation>(impl.socket_, o);
550 p.p->enable_cancellation(c->get_cancel_requested(), c);
554 start_accept_op(impl, peer.is_open(), p.p->new_socket(),
555 impl.protocol_.family(), impl.protocol_.type(),
556 impl.protocol_.protocol(), p.p->output_buffer(),
557 p.p->address_length(), o);
561 #if defined(BOOST_ASIO_HAS_MOVE)
562 // Start an asynchronous accept. The peer and peer_endpoint objects
563 // must be valid until the accept's handler is invoked.
564 template <typename PeerIoExecutor, typename Handler, typename IoExecutor>
565 void async_move_accept(implementation_type& impl,
566 const PeerIoExecutor& peer_io_ex, endpoint_type* peer_endpoint,
567 Handler& handler, const IoExecutor& io_ex)
569 typename associated_cancellation_slot<Handler>::type slot
570 = boost::asio::get_associated_cancellation_slot(handler);
572 // Allocate and construct an operation to wrap the handler.
573 typedef win_iocp_socket_move_accept_op<
574 protocol_type, PeerIoExecutor, Handler, IoExecutor> op;
575 typename op::ptr p = { boost::asio::detail::addressof(handler),
576 op::ptr::allocate(handler), 0 };
577 bool enable_connection_aborted =
578 (impl.state_ & socket_ops::enable_connection_aborted) != 0;
579 operation* o = p.p = new (p.v) op(*this, impl.socket_, impl.protocol_,
580 peer_io_ex, peer_endpoint, enable_connection_aborted,
583 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
584 &impl, impl.socket_, "async_accept"));
586 // Optionally register for per-operation cancellation.
587 if (slot.is_connected())
589 accept_op_cancellation* c =
590 &slot.template emplace<accept_op_cancellation>(impl.socket_, o);
591 p.p->enable_cancellation(c->get_cancel_requested(), c);
595 start_accept_op(impl, false, p.p->new_socket(),
596 impl.protocol_.family(), impl.protocol_.type(),
597 impl.protocol_.protocol(), p.p->output_buffer(),
598 p.p->address_length(), o);
601 #endif // defined(BOOST_ASIO_HAS_MOVE)
603 // Connect the socket to the specified endpoint.
604 boost::system::error_code connect(implementation_type& impl,
605 const endpoint_type& peer_endpoint, boost::system::error_code& ec)
607 socket_ops::sync_connect(impl.socket_,
608 peer_endpoint.data(), peer_endpoint.size(), ec);
612 // Start an asynchronous connect.
613 template <typename Handler, typename IoExecutor>
614 void async_connect(implementation_type& impl,
615 const endpoint_type& peer_endpoint, Handler& handler,
616 const IoExecutor& io_ex)
618 typename associated_cancellation_slot<Handler>::type slot
619 = boost::asio::get_associated_cancellation_slot(handler);
621 // Allocate and construct an operation to wrap the handler.
622 typedef win_iocp_socket_connect_op<Handler, IoExecutor> op;
623 typename op::ptr p = { boost::asio::detail::addressof(handler),
624 op::ptr::allocate(handler), 0 };
625 p.p = new (p.v) op(impl.socket_, handler, io_ex);
627 BOOST_ASIO_HANDLER_CREATION((context_, *p.p, "socket",
628 &impl, impl.socket_, "async_connect"));
630 // Optionally register for per-operation cancellation.
631 operation* iocp_op = p.p;
632 if (slot.is_connected())
634 p.p->cancellation_key_ = iocp_op =
635 &slot.template emplace<reactor_op_cancellation>(
636 impl.socket_, iocp_op);
639 int op_type = start_connect_op(impl, impl.protocol_.family(),
640 impl.protocol_.type(), peer_endpoint.data(),
641 static_cast<int>(peer_endpoint.size()), p.p, iocp_op);
644 // Update cancellation method if the reactor was used.
645 if (slot.is_connected() && op_type != -1)
647 static_cast<reactor_op_cancellation*>(iocp_op)->use_reactor(
648 &get_reactor(), &impl.reactor_data_, op_type);
653 } // namespace detail
657 #include <boost/asio/detail/pop_options.hpp>
659 #endif // defined(BOOST_ASIO_HAS_IOCP)
661 #endif // BOOST_ASIO_DETAIL_WIN_IOCP_SOCKET_SERVICE_HPP