10#include <sys/socket.h>
12#include <netinet/in.h>
43class TSocketBase<void> {
63 int Create(
int domain,
int type);
74 static void SetCloseOnExec(
int s);
102template<
typename TSockOps>
144 struct TAwaitableRead:
public TAwaitable<TAwaitableRead> {
146 this->ret = TSockOps::read(this->fd, this->b, this->s);
149 void await_suspend(std::coroutine_handle<> h) {
151 this->poller->AddRead(this->fd, h);
154 return TAwaitableRead{Poller_,Fd_,buf,size};
168 struct TAwaitableRead:
public TAwaitable<TAwaitableRead> {
170 return (this->ready =
false);
174 this->ret = TSockOps::read(this->fd, this->b, this->s);
177 void await_suspend(std::coroutine_handle<> h) {
179 this->poller->AddRead(this->fd, h);
182 return TAwaitableRead{Poller_,Fd_,buf,size};
196 struct TAwaitableWrite:
public TAwaitable<TAwaitableWrite> {
198 this->ret = TSockOps::write(this->fd, this->b, this->s);
201 void await_suspend(std::coroutine_handle<> h) {
203 this->poller->AddWrite(this->fd, h);
206 return TAwaitableWrite{Poller_,Fd_,
const_cast<void*
>(buf),size};
219 struct TAwaitableWrite:
public TAwaitable<TAwaitableWrite> {
221 return (this->ready =
false);
225 this->ret = TSockOps::write(this->fd, this->b, this->s);
228 void await_suspend(std::coroutine_handle<> h) {
230 this->poller->AddWrite(this->fd, h);
233 return TAwaitableWrite{Poller_,Fd_,
const_cast<void*
>(buf),size};
253 if (!Poller_->SupportsRemoteHup()) {
254 throw std::system_error(std::make_error_code(std::errc::operation_not_supported),
255 "remote hang-up is not reported by this poller");
257 struct TAwaitableClose:
public TAwaitable<TAwaitableClose> {
259 return (this->ready =
false);
266 void await_suspend(std::coroutine_handle<> h) {
268 this->poller->AddRemoteHup(this->fd, h);
271 return TAwaitableClose{Poller_,Fd_};
294 poller->RemoveEvent(fd, handle);
300 return (ready = (ret >= 0));
314 if (ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK ) {
315 throw std::system_error(WSAGetLastError(), std::generic_category());
318 if (ret < 0 && !(errno==EINTR||errno==EAGAIN||errno==EINPROGRESS)) {
319 throw std::system_error(errno, std::generic_category());
326 void* b =
nullptr;
size_t s = 0;
337 static auto read(
int fd,
void* buf,
size_t count) {
338 return ::read(fd, buf, count);
341 static auto write(
int fd,
const void* buf,
size_t count) {
342 return ::write(fd, buf, count);
345 static auto close(
int fd) {
379 static auto read(
int fd,
void* buf,
size_t count) {
380 return ::recv(fd,
static_cast<char*
>(buf), count, 0);
383 static auto write(
int fd,
const void* buf,
size_t count) {
384 return ::send(fd,
static_cast<const char*
>(buf), count, 0);
387 static auto close(
int fd) {
419 TSocket(
TPollerBase& poller,
int domain,
int type = SOCK_STREAM);
429 TSocket(TSocket&& other);
430 TSocket& operator=(TSocket&& other);
447 if (RemoteAddr_.has_value()) {
448 throw std::runtime_error(
"Already connected");
455 if (deadline != TTime::max()) {
462 int ret = connect(fd, addr.first, addr.second);
464 if (ret < 0 && WSAGetLastError() != WSAEWOULDBLOCK) {
465 throw std::system_error(WSAGetLastError(), std::generic_category(),
"connect");
468 if (ret < 0 && !(errno == EINTR||errno==EAGAIN||errno==EINPROGRESS)) {
469 throw std::system_error(errno, std::generic_category(),
"connect");
472 return (ready = (ret >= 0));
475 void await_suspend(std::coroutine_handle<> h) {
478 if (deadline != TTime::max()) {
479 timerId = poller->
AddTimer(deadline, h);
483 void await_resume() {
488 if (deadline != TTime::max() && poller->
RemoveTimer(timerId, deadline)) {
490 throw std::system_error(std::make_error_code(std::errc::timed_out));
494 socklen_t len =
sizeof(err);
495 if (getsockopt(fd, SOL_SOCKET, SO_ERROR,
reinterpret_cast<char*
>(&err), &len) < 0) {
497 err = WSAGetLastError();
503 throw std::system_error(err, std::generic_category(),
"connect");
509 std::pair<const sockaddr*, int> addr;
511 unsigned timerId = 0;
515 return TAwaitable{Poller_, Fd_, RemoteAddr_->RawAddr(), deadline};
539 bool await_ready()
const {
541 throw std::system_error(EBADF, std::generic_category(),
"accept");
545 void await_suspend(std::coroutine_handle<> h) {
549 std::expected<TSocket, int> await_resume() {
551 char clientaddr[
sizeof(sockaddr_in6)];
552 socklen_t len =
static_cast<socklen_t
>(
sizeof(sockaddr_in6));
555 int clientfd = accept4(fd,
reinterpret_cast<sockaddr*
>(&clientaddr[0]), &len, SOCK_CLOEXEC);
557 int clientfd = accept(fd,
reinterpret_cast<sockaddr*
>(&clientaddr[0]), &len);
562 int err = WSAGetLastError();
566 throw std::system_error(err, std::generic_category(),
"accept");
569 return std::unexpected(err);
571 SetCloseOnExec(clientfd);
573 return TSocket{
TAddress{
reinterpret_cast<sockaddr*
>(&clientaddr[0]), len}, clientfd, *poller};
587 void Listen(
int backlog = 128);
593 const std::optional<TAddress>&
RemoteAddr()
const;
599 const std::optional<TAddress>&
LocalAddr()
const;
616 std::optional<TAddress> LocalAddr_;
617 std::optional<TAddress> RemoteAddr_;
623inline int CheckDrivenResult(
int ret) {
627 if (err == WSAEWOULDBLOCK || err == WSAEINTR || err == WSAEINPROGRESS) {
629 if (err == EINTR || err == EAGAIN || err == EINPROGRESS) {
633 throw std::system_error(err, std::generic_category());
679 : TSocket(poller, domain, type)
682 Poller_->Register(Fd_);
692 : TSocket(addr, fd, poller)
695 Poller_->Register(Fd_);
702 Poller_->Register(Fd_);
705 TPollerDrivenSocket() =
default;
724 TSockOps::close(poller->Cancel(op));
728 bool await_ready()
const {
return false; }
729 void await_suspend(std::coroutine_handle<> h) {
731 poller->Accept(fd,
reinterpret_cast<sockaddr*
>(&addr[0]), &len, op);
734 std::expected<TPollerDrivenSocket<T>,
int> await_resume() {
735 int clientfd = op.Result;
736 if (clientfd == -EBADF) {
737 throw std::system_error(EBADF, std::generic_category(),
"accept");
740 return std::unexpected(-clientfd);
749 char addr[2*(
sizeof(sockaddr_in6)+16)] = {0};
750 socklen_t len =
static_cast<socklen_t
>(
sizeof(addr));
751 typename T::TOperation op = {};
772 if (RemoteAddr_.has_value()) {
773 throw std::runtime_error(
"Already connected");
780 if (deadline != TTime::max()) {
786 bool await_ready()
const {
return false; }
788 void await_suspend(std::coroutine_handle<> h) {
790 poller->Connect(fd, addr.first, addr.second, op);
791 if (deadline != TTime::max()) {
792 timerId = poller->
AddTimer(deadline, h);
797 if (deadline != TTime::max() && poller->
RemoveTimer(timerId, deadline)) {
800 throw std::system_error(std::make_error_code(std::errc::timed_out));
807 std::pair<const sockaddr*, int> addr;
809 unsigned timerId = 0;
810 typename T::TOperation op = {};
814 throw std::system_error(-ret, std::generic_category(),
"connect");
836 bool await_ready()
const {
return false; }
837 void await_suspend(std::coroutine_handle<> h) {
839 poller->Recv(fd, buf, size, op);
842 auto await_resume() {
843 return NDetail::CheckDrivenResult(op.Result);
851 typename T::TOperation op = {};
875 bool await_ready()
const {
return false; }
876 void await_suspend(std::coroutine_handle<> h) {
878 poller->Send(fd, buf, size, op);
881 auto await_resume() {
882 return NDetail::CheckDrivenResult(op.Result);
890 typename T::TOperation op = {};
907 void Reassign(T* poller) {
973 bool await_ready()
const {
return false; }
974 void await_suspend(std::coroutine_handle<> h) {
976 poller->Read(fd, buf, size, op);
979 auto await_resume() {
980 return NDetail::CheckDrivenResult(op.Result);
988 typename T::TOperation op = {};
991 return TAwaitable{Poller_, Fd_, buf, size};
1012 bool await_ready()
const {
return false; }
1013 void await_suspend(std::coroutine_handle<> h) {
1015 poller->Write(fd, buf, size, op);
1018 auto await_resume() {
1019 return NDetail::CheckDrivenResult(op.Result);
1027 typename T::TOperation op = {};
1030 return TAwaitable{Poller_, Fd_, buf, size};
A class representing an IPv4 or IPv6 address (with port).
Definition address.hpp:38
Asynchronous file handle that owns its file descriptor.
Definition socket.hpp:357
TFileHandle(int fd, TPollerBase &poller)
Constructs a TFileHandle from an existing file descriptor.
Definition socket.hpp:365
Definition socket.hpp:333
static constexpr int CloseType
Passed to TPollerBase::Close().
Definition socket.hpp:335
Backend-independent base for I/O pollers.
Definition poller.hpp:49
unsigned AddTimer(TTime deadline, THandle h)
Schedules a timer.
Definition poller.hpp:83
void AddWrite(int fd, THandle h)
Registers a write interest on a file descriptor.
Definition poller.hpp:128
bool RemoveTimer(unsigned timerId, TTime deadline)
Removes or cancels a timer.
Definition poller.hpp:98
void RemoveEvent(int fd)
Removes registered events for a specific file descriptor.
Definition poller.hpp:174
void AddRead(int fd, THandle h)
Registers a read interest on a file descriptor.
Definition poller.hpp:115
auto WriteSomeYield(const void *buf, size_t size)
The WriteSomeYield and ReadSomeYield variants behave similarly to WriteSome/ReadSome.
Definition socket.hpp:1034
auto ReadSomeYield(void *buf, size_t size)
The WriteSomeYield and ReadSomeYield variants behave similarly to WriteSome/ReadSome.
Definition socket.hpp:1039
auto WriteSome(const void *buf, size_t size)
Asynchronously writes data from the provided buffer to the file.
Definition socket.hpp:1004
TPollerDrivenFileHandle(int fd, T &poller)
Constructs a TPollerDrivenFileHandle from an existing file descriptor.
Definition socket.hpp:950
auto ReadSome(void *buf, size_t size)
Asynchronously reads data from the file into the provided buffer.
Definition socket.hpp:965
Socket type driven by the poller's implementation.
Definition socket.hpp:665
TFuture< void > Connect(const TAddress &addr, TTime deadline=TTime::max())
Asynchronously connects to the specified address with an optional deadline.
Definition socket.hpp:771
auto ReadSomeYield(void *buf, size_t size)
The WriteSomeYield and ReadSomeYield variants behave similarly to WriteSome/ReadSome.
Definition socket.hpp:902
auto ReadSome(void *buf, size_t size)
Asynchronously reads data from the socket.
Definition socket.hpp:828
auto WriteSome(const void *buf, size_t size)
Asynchronously writes data to the socket.
Definition socket.hpp:867
auto Accept()
Asynchronously accepts an incoming connection.
Definition socket.hpp:719
TPollerDrivenSocket(T &poller, int domain, int type=SOCK_STREAM)
Constructs a TPollerDrivenSocket from a poller, domain, and socket type.
Definition socket.hpp:678
auto WriteSomeYield(const void *buf, size_t size)
The WriteSomeYield and ReadSomeYield variants behave similarly to WriteSome/ReadSome.
Definition socket.hpp:897
TPollerDrivenSocket(const TAddress &addr, int fd, T &poller)
Constructs a TPollerDrivenSocket from an existing file descriptor.
Definition socket.hpp:691
Definition socket.hpp:375
static constexpr int CloseType
Passed to TPollerBase::Close().
Definition socket.hpp:377
TPollerBase * Poller()
Returns the poller associated with this socket.
Definition socket.hpp:49
Template base class implementing asynchronous socket I/O operations.
Definition socket.hpp:103
TSocketBase(TPollerBase &poller, int domain, int type)
Constructs a TSocketBase with a new socket descriptor.
Definition socket.hpp:112
auto Monitor()
Monitors the socket for remote hang-up (closure).
Definition socket.hpp:252
auto WriteSomeYield(const void *buf, size_t size)
Forces a write operation on the next event loop iteration.
Definition socket.hpp:218
auto WriteSome(const void *buf, size_t size)
Asynchronously writes data from the provided buffer to the socket.
Definition socket.hpp:195
auto ReadSome(void *buf, size_t size)
Asynchronously reads data from the socket into the provided buffer.
Definition socket.hpp:143
void Close()
Closes the socket.
Definition socket.hpp:280
TSocketBase(int fd, TPollerBase &poller)
Constructs a TSocketBase from an existing socket descriptor.
Definition socket.hpp:120
auto ReadSomeYield(void *buf, size_t size)
Forces a read operation on the next event loop iteration.
Definition socket.hpp:167
High-level asynchronous socket for network communication.
Definition socket.hpp:406
bool SetNoDelay()
Disables Nagle's algorithm (TCP_NODELAY) on a TCP socket.
Definition socket.cpp:149
const std::optional< TAddress > & RemoteAddr() const
Returns the remote address of the connected peer.
Definition socket.cpp:141
auto Connect(const TAddress &addr, TTime deadline=TTime::max())
Asynchronously connects to the specified address.
Definition socket.hpp:446
int Fd() const
Returns the underlying socket descriptor.
Definition socket.cpp:145
void Bind(const TAddress &addr)
Binds the socket to the specified local address.
Definition socket.cpp:115
auto Accept()
Asynchronously accepts an incoming connection.
Definition socket.hpp:532
const std::optional< TAddress > & LocalAddr() const
Returns the local address to which the socket is bound.
Definition socket.cpp:137
void Listen(int backlog=128)
Puts the socket in a listening state with an optional backlog (default is 128).
Definition socket.cpp:131
Implementation of a promise/future system for coroutines.
Definition corochain.hpp:74
Definition socket.hpp:290