| 1 |
// SPDX-License-Identifier: BSD-2-Clause |
| 2 |
// Copyright CM4all GmbH |
| 3 |
// author: Max Kellermann <[email protected]> |
| 4 |
|
| 5 |
#pragma once |
| 6 |
|
| 7 |
#include "event/SocketEvent.hxx" |
| 8 |
#include "event/CoarseTimerEvent.hxx" |
| 9 |
#include "util/Cancellable.hxx" |
| 10 |
|
| 11 |
#include <exception> |
| 12 |
|
| 13 |
class UniqueSocketDescriptor; |
| 14 |
class SocketAddress; |
| 15 |
class AddressInfo; |
| 16 |
|
| 17 |
class ConnectSocketHandler { |
| 18 |
public: |
| 19 |
virtual void OnSocketConnectSuccess(UniqueSocketDescriptor fd) noexcept = 0; |
| 20 |
virtual void OnSocketConnectTimeout() noexcept; |
| 21 |
virtual void OnSocketConnectError(std::exception_ptr ep) noexcept = 0; |
| 22 |
}; |
| 23 |
|
| 24 |
/** |
| 25 |
* A class that connects to a SocketAddress. |
| 26 |
*/ |
| 27 |
class ConnectSocket final : public Cancellable { |
| 28 |
ConnectSocketHandler &handler; |
| 29 |
|
| 30 |
SocketEvent event; |
| 31 |
CoarseTimerEvent timeout_event; |
| 32 |
|
| 33 |
public: |
| 34 |
ConnectSocket(EventLoop &_event_loop, |
| 35 |
ConnectSocketHandler &_handler) noexcept; |
| 36 |
~ConnectSocket() noexcept; |
| 37 |
|
| 38 |
auto &GetEventLoop() const noexcept { |
| 39 |
return event.GetEventLoop(); |
| 40 |
} |
| 41 |
|
| 42 |
bool IsPending() const noexcept { |
| 43 |
return event.IsDefined(); |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* @param timeout a timeout or a negative value to disable |
| 48 |
* timeouts |
| 49 |
*/ |
| 50 |
bool Connect(const SocketAddress address, |
| 51 |
Event::Duration timeout) noexcept; |
| 52 |
|
| 53 |
bool Connect(const AddressInfo &address, |
| 54 |
Event::Duration timeout) noexcept; |
| 55 |
|
| 56 |
/** |
| 57 |
* Wait until the given socket is connected (this method returns |
| 58 |
* immediately and invokes the #ConnectSocketHandler on completion |
| 59 |
* or error). |
| 60 |
*/ |
| 61 |
void WaitConnected(UniqueSocketDescriptor _fd, |
| 62 |
Event::Duration timeout=Event::Duration(-1)) noexcept; |
| 63 |
|
| 64 |
/* virtual methods from Cancellable */ |
| 65 |
void Cancel() noexcept override; |
| 66 |
|
| 67 |
private: |
| 68 |
void OnEvent(unsigned events) noexcept; |
| 69 |
void OnTimeout() noexcept; |
| 70 |
}; |