summaryrefslogtreecommitdiffstats
path: root/lib/base/tcpsocket.hpp
blob: e0f502256460aa0fb9168538a3041920dfbf526d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#ifndef TCPSOCKET_H
#define TCPSOCKET_H

#include "base/i2-base.hpp"
#include "base/io-engine.hpp"
#include "base/socket.hpp"
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>

namespace icinga
{

/**
 * A TCP socket. DEPRECATED - Use Boost ASIO instead.
 *
 * @ingroup base
 */
class TcpSocket final : public Socket
{
public:
	DECLARE_PTR_TYPEDEFS(TcpSocket);

	void Bind(const String& service, int family);
	void Bind(const String& node, const String& service, int family);

	void Connect(const String& node, const String& service);
};

/**
 * TCP Connect based on Boost ASIO.
 *
 * @ingroup base
 */
template<class Socket>
void Connect(Socket& socket, const String& node, const String& service)
{
	using boost::asio::ip::tcp;

	tcp::resolver resolver (IoEngine::Get().GetIoContext());
	tcp::resolver::query query (node, service);
	auto result (resolver.resolve(query));
	auto current (result.begin());

	for (;;) {
		try {
			socket.open(current->endpoint().protocol());
			socket.set_option(tcp::socket::keep_alive(true));
			socket.connect(current->endpoint());

			break;
		} catch (const std::exception&) {
			if (++current == result.end()) {
				throw;
			}

			if (socket.is_open()) {
				socket.close();
			}
		}
	}
}

template<class Socket>
void Connect(Socket& socket, const String& node, const String& service, boost::asio::yield_context yc)
{
	using boost::asio::ip::tcp;

	tcp::resolver resolver (IoEngine::Get().GetIoContext());
	tcp::resolver::query query (node, service);
	auto result (resolver.async_resolve(query, yc));
	auto current (result.begin());

	for (;;) {
		try {
			socket.open(current->endpoint().protocol());
			socket.set_option(tcp::socket::keep_alive(true));
			socket.async_connect(current->endpoint(), yc);

			break;
		} catch (const std::exception&) {
			if (++current == result.end()) {
				throw;
			}

			if (socket.is_open()) {
				socket.close();
			}
		}
	}
}

}

#endif /* TCPSOCKET_H */