-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathsocket.cpp
489 lines (398 loc) · 13.2 KB
/
socket.cpp
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#include "socket.h"
#include "singleton.h"
#include "../client.h"
#include <assert.h>
#include <stdexcept>
#include <system_error>
#include <unordered_set>
#include <memory.h>
#include <thread>
#if !defined(_win_)
# include <errno.h>
# include <fcntl.h>
# include <netdb.h>
# include <netinet/tcp.h>
# include <signal.h>
# include <unistd.h>
#endif
namespace clickhouse {
#if defined(_win_)
char const* windowsErrorCategory::name() const noexcept {
return "WindowsSocketError";
}
std::string windowsErrorCategory::message(int c) const {
char error[UINT8_MAX];
auto len = FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, static_cast<DWORD>(c), 0, error, sizeof(error), nullptr);
if (len == 0) {
return "unknown";
}
while (len && (error[len - 1] == '\r' || error[len - 1] == '\n')) {
--len;
}
return std::string(error, len);
}
windowsErrorCategory const& windowsErrorCategory::category() {
static windowsErrorCategory c;
return c;
}
#endif
#if defined(_unix_)
char const* getaddrinfoErrorCategory::name() const noexcept {
return "getaddrinfoError";
}
std::string getaddrinfoErrorCategory::message(int c) const {
return gai_strerror(c);
}
getaddrinfoErrorCategory const& getaddrinfoErrorCategory::category() {
static getaddrinfoErrorCategory c;
return c;
}
#endif
namespace {
class LocalNames : public std::unordered_set<std::string> {
public:
LocalNames() {
emplace("localhost");
emplace("localhost.localdomain");
emplace("localhost6");
emplace("localhost6.localdomain6");
emplace("::1");
emplace("127.0.0.1");
}
inline bool IsLocalName(const std::string& name) const noexcept {
return find(name) != end();
}
};
inline int getSocketErrorCode() {
#if defined(_win_)
return WSAGetLastError();
#else
return errno;
#endif
}
const std::error_category& getErrorCategory() noexcept {
#if defined(_win_)
return windowsErrorCategory::category();
#else
return std::system_category();
#endif
}
void SetNonBlock(SOCKET fd, bool value) {
#if defined(_unix_) || defined(__CYGWIN__)
int flags;
int ret;
#if defined(O_NONBLOCK)
if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
flags = 0;
if (value) {
flags |= O_NONBLOCK;
} else {
flags &= ~O_NONBLOCK;
}
ret = fcntl(fd, F_SETFL, flags);
#else
flags = value;
return ioctl(fd, FIOBIO, &flags);
#endif
if (ret == -1) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to set nonblocking mode");
}
#elif defined(_win_)
unsigned long inbuf = value;
unsigned long outbuf = 0;
DWORD written = 0;
if (!inbuf) {
WSAEventSelect(fd, nullptr, 0);
}
if (WSAIoctl(fd, FIONBIO, &inbuf, sizeof(inbuf), &outbuf, sizeof(outbuf), &written, 0, 0) == SOCKET_ERROR) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to set nonblocking mode");
}
#endif
}
void SetTimeout(SOCKET fd, const SocketTimeoutParams& timeout_params) {
#if defined(_unix_)
timeval recv_timeout{ static_cast<time_t>(timeout_params.recv_timeout.count() / 1000), static_cast<suseconds_t>(timeout_params.recv_timeout.count() % 1000 * 1000) };
auto recv_ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &recv_timeout, sizeof(recv_timeout));
timeval send_timeout{ static_cast<time_t>(timeout_params.send_timeout.count() / 1000), static_cast<suseconds_t>(timeout_params.send_timeout.count() % 1000 * 1000) };
auto send_ret = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &send_timeout, sizeof(send_timeout));
if (recv_ret == -1 || send_ret == -1) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to set socket timeout");
}
#else
DWORD recv_timeout = static_cast<DWORD>(timeout_params.recv_timeout.count());
auto recv_ret = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (const char*)&recv_timeout, sizeof(DWORD));
DWORD send_timeout = static_cast<DWORD>(timeout_params.send_timeout.count());
auto send_ret = setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (const char*)&send_timeout, sizeof(DWORD));
if (recv_ret == SOCKET_ERROR || send_ret == SOCKET_ERROR) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to set socket timeout");
}
#endif
};
ssize_t Poll(struct pollfd* fds, int nfds, int timeout) noexcept {
#if defined(_win_)
return WSAPoll(fds, nfds, timeout);
#else
return poll(fds, nfds, timeout);
#endif
}
#ifndef INVALID_SOCKET
const SOCKET INVALID_SOCKET = -1;
#endif
void CloseSocket(SOCKET socket) {
if (socket == INVALID_SOCKET)
return;
#if defined(_win_)
closesocket(socket);
#else
close(socket);
#endif
}
struct SocketRAIIWrapper {
SOCKET socket = INVALID_SOCKET;
~SocketRAIIWrapper() {
CloseSocket(socket);
}
SOCKET operator*() const {
return socket;
}
SOCKET release() {
auto result = socket;
socket = INVALID_SOCKET;
return result;
}
};
SOCKET SocketConnect(const NetworkAddress& addr, const SocketTimeoutParams& timeout_params) {
int last_err = 0;
for (auto res = addr.Info(); res != nullptr; res = res->ai_next) {
SocketRAIIWrapper s{socket(res->ai_family, res->ai_socktype, res->ai_protocol)};
if (*s == INVALID_SOCKET) {
continue;
}
SetNonBlock(*s, true);
SetTimeout(*s, timeout_params);
if (connect(*s, res->ai_addr, (int)res->ai_addrlen) != 0) {
int err = getSocketErrorCode();
if (
err == EINPROGRESS || err == EAGAIN || err == EWOULDBLOCK
#if defined(_win_)
|| err == WSAEWOULDBLOCK || err == WSAEINPROGRESS
#endif
) {
pollfd fd;
fd.fd = *s;
fd.events = POLLOUT;
fd.revents = 0;
ssize_t rval = Poll(&fd, 1, static_cast<int>(timeout_params.connect_timeout.count()));
if (rval == -1) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to connect");
}
if (rval == 0) {
#if defined(_win_)
last_err = WSAETIMEDOUT;
#else
last_err = ETIMEDOUT;
#endif
}
if (rval > 0) {
socklen_t len = sizeof(err);
getsockopt(*s, SOL_SOCKET, SO_ERROR, (char*)&err, &len);
if (!err) {
SetNonBlock(*s, false);
return s.release();
}
last_err = err;
}
}
} else {
SetNonBlock(*s, false);
return s.release();
}
}
if (last_err > 0) {
throw std::system_error(last_err, getErrorCategory(), "fail to connect");
}
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to connect");
}
} // namespace
NetworkAddress::NetworkAddress(const std::string& host, const std::string& port)
: host_(host)
, info_(nullptr)
{
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
// using AI_ADDRCONFIG on windows will cause getaddrinfo to return WSAHOST_NOT_FOUND
// for more information, see https://github.com/ClickHouse/clickhouse-cpp/issues/195
#if defined(_unix_)
if (!Singleton<LocalNames>()->IsLocalName(host)) {
// https://linux.die.net/man/3/getaddrinfo
// If hints.ai_flags includes the AI_ADDRCONFIG flag,
// then IPv4 addresses are returned in the list pointed to by res only
// if the local system has at least one IPv4 address configured,
// and IPv6 addresses are only returned if the local system
// has at least one IPv6 address configured.
// The loopback address is not considered for this case
// as valid as a configured address.
hints.ai_flags |= AI_ADDRCONFIG;
}
#endif
const int error = getaddrinfo(host.c_str(), port.c_str(), &hints, &info_);
#if defined(_unix_)
if (error && error != EAI_SYSTEM) {
throw std::system_error(error, getaddrinfoErrorCategory::category());
}
#endif
if (error) {
throw std::system_error(getSocketErrorCode(), getErrorCategory());
}
}
NetworkAddress::~NetworkAddress() {
if (info_) {
freeaddrinfo(info_);
}
}
const struct addrinfo* NetworkAddress::Info() const {
return info_;
}
const std::string & NetworkAddress::Host() const {
return host_;
}
SocketBase::~SocketBase() = default;
SocketFactory::~SocketFactory() = default;
void SocketFactory::sleepFor(const std::chrono::milliseconds& duration) {
std::this_thread::sleep_for(duration);
}
Socket::Socket(const NetworkAddress& addr, const SocketTimeoutParams& timeout_params)
: handle_(SocketConnect(addr, timeout_params))
{}
Socket::Socket(const NetworkAddress & addr)
: handle_(SocketConnect(addr, SocketTimeoutParams{}))
{}
Socket::Socket(Socket&& other) noexcept
: handle_(other.handle_)
{
other.handle_ = INVALID_SOCKET;
}
Socket& Socket::operator=(Socket&& other) noexcept {
if (this != &other) {
Close();
handle_ = other.handle_;
other.handle_ = INVALID_SOCKET;
}
return *this;
}
Socket::~Socket() {
Close();
}
void Socket::Close() {
CloseSocket(handle_);
handle_ = INVALID_SOCKET;
}
void Socket::SetTcpKeepAlive(int idle, int intvl, int cnt) noexcept {
int val = 1;
#if defined(_unix_)
setsockopt(handle_, SOL_SOCKET, SO_KEEPALIVE, &val, sizeof(val));
# if defined(_linux_)
setsockopt(handle_, IPPROTO_TCP, TCP_KEEPIDLE, &idle, sizeof(idle));
# elif defined(_darwin_)
setsockopt(handle_, IPPROTO_TCP, TCP_KEEPALIVE, &idle, sizeof(idle));
# else
# error "platform is not supported"
# endif
setsockopt(handle_, IPPROTO_TCP, TCP_KEEPINTVL, &intvl, sizeof(intvl));
setsockopt(handle_, IPPROTO_TCP, TCP_KEEPCNT, &cnt, sizeof(cnt));
#else
setsockopt(handle_, SOL_SOCKET, SO_KEEPALIVE, (const char*)&val, sizeof(val));
std::ignore = idle = intvl = cnt;
#endif
}
void Socket::SetTcpNoDelay(bool nodelay) noexcept {
int val = nodelay;
#if defined(_unix_)
setsockopt(handle_, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
#else
setsockopt(handle_, IPPROTO_TCP, TCP_NODELAY, (const char*)&val, sizeof(val));
#endif
}
std::unique_ptr<InputStream> Socket::makeInputStream() const {
return std::make_unique<SocketInput>(handle_);
}
std::unique_ptr<OutputStream> Socket::makeOutputStream() const {
return std::make_unique<SocketOutput>(handle_);
}
NonSecureSocketFactory::~NonSecureSocketFactory() {}
std::unique_ptr<SocketBase> NonSecureSocketFactory::connect(const ClientOptions &opts, const Endpoint& endpoint) {
const auto address = NetworkAddress(endpoint.host, std::to_string(endpoint.port));
auto socket = doConnect(address, opts);
setSocketOptions(*socket, opts);
return socket;
}
std::unique_ptr<Socket> NonSecureSocketFactory::doConnect(const NetworkAddress& address, const ClientOptions& opts) {
SocketTimeoutParams timeout_params { opts.connection_connect_timeout, opts.connection_recv_timeout, opts.connection_send_timeout };
return std::make_unique<Socket>(address, timeout_params);
}
void NonSecureSocketFactory::setSocketOptions(Socket &socket, const ClientOptions &opts) {
if (opts.tcp_keepalive) {
socket.SetTcpKeepAlive(
static_cast<int>(opts.tcp_keepalive_idle.count()),
static_cast<int>(opts.tcp_keepalive_intvl.count()),
static_cast<int>(opts.tcp_keepalive_cnt));
}
if (opts.tcp_nodelay) {
socket.SetTcpNoDelay(opts.tcp_nodelay);
}
}
SocketInput::SocketInput(SOCKET s)
: s_(s)
{
}
SocketInput::~SocketInput() = default;
size_t SocketInput::DoRead(void* buf, size_t len) {
const ssize_t ret = ::recv(s_, (char*)buf, (int)len, 0);
if (ret > 0) {
return (size_t)ret;
}
if (ret == 0) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "closed");
}
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "can't receive string data");
}
bool SocketInput::Skip(size_t /*bytes*/) {
return false;
}
SocketOutput::SocketOutput(SOCKET s)
: s_(s)
{
}
SocketOutput::~SocketOutput() = default;
size_t SocketOutput::DoWrite(const void* data, size_t len) {
#if defined (_linux_)
static const int flags = MSG_NOSIGNAL;
#else
static const int flags = 0;
#endif
const ssize_t ret = ::send(s_, (const char*)data, (int)len, flags);
if (ret < 0) {
throw std::system_error(getSocketErrorCode(), getErrorCategory(), "fail to send " + std::to_string(len) + " bytes of data");
}
return (size_t)ret;
}
NetrworkInitializer::NetrworkInitializer() {
struct NetrworkInitializerImpl {
NetrworkInitializerImpl() {
#if defined (_win_)
WSADATA data;
const int result = WSAStartup(MAKEWORD(2, 2), &data);
if (result) {
assert(false);
exit(-1);
}
#elif defined(_unix_)
signal(SIGPIPE, SIG_IGN);
#endif
}
};
(void)Singleton<NetrworkInitializerImpl>();
}
}