-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcTCPSyncClient_V2.h
More file actions
687 lines (566 loc) · 15.6 KB
/
cTCPSyncClient_V2.h
File metadata and controls
687 lines (566 loc) · 15.6 KB
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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
#pragma once
/**
cTCPSyncClient_V2
Synchronous RAII TCP client for request/response style communication.
Design goals:
- no background worker threads
- no raw ownership / no new / delete
- explicit connect / send / receive / close flow
- convenient one-shot exchange helper for short-lived requests
Notes:
- This class is intentionally not thread-safe.
- TCP is a byte stream, so the caller still needs a framing strategy.
Use `receiveExact`, `receiveUntilDelimiter`, or `receiveUntilClosed`
depending on the protocol.
*/
#include <algorithm>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include <arpa/inet.h>
#include <cerrno>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include "scope_exit.h"
class cTCPSyncClient_V2
{
public:
using Buffer = std::vector<std::uint8_t>;
using duration_type = std::chrono::milliseconds;
enum class enm_IOResult : std::uint8_t
{
Success = 0,
Closed,
Timeout,
NotConnected,
InvalidArgument,
Failed
};
static constexpr std::size_t kDefaultReceiveChunkSize = 4096U;
static constexpr std::size_t kDefaultMaxPayloadSize = 64U * 1024U;
cTCPSyncClient_V2() = delete;
cTCPSyncClient_V2(const cTCPSyncClient_V2 &) = delete;
cTCPSyncClient_V2 &operator=(const cTCPSyncClient_V2 &) = delete;
cTCPSyncClient_V2(cTCPSyncClient_V2 &&) = delete;
cTCPSyncClient_V2 &operator=(cTCPSyncClient_V2 &&) = delete;
cTCPSyncClient_V2(std::string serverAddress, std::uint16_t port)
: m_serverAddress(std::move(serverAddress)),
m_port(port)
{
}
~cTCPSyncClient_V2() noexcept
{
close();
}
[[nodiscard]] const std::string &serverAddress() const noexcept
{
return m_serverAddress;
}
[[nodiscard]] std::uint16_t port() const noexcept
{
return m_port;
}
[[nodiscard]] bool isConnected() const noexcept
{
return m_socket >= 0;
}
[[nodiscard]] duration_type sendTimeout() const noexcept
{
return m_sendTimeout;
}
[[nodiscard]] duration_type receiveTimeout() const noexcept
{
return m_receiveTimeout;
}
[[nodiscard]] bool setSendTimeout(duration_type timeout) noexcept
{
m_sendTimeout = sanitizeTimeout(timeout);
return applyConfiguredTimeout(m_sendTimeout, SO_SNDTIMEO);
}
[[nodiscard]] bool setReceiveTimeout(duration_type timeout) noexcept
{
m_receiveTimeout = sanitizeTimeout(timeout);
return applyConfiguredTimeout(m_receiveTimeout, SO_RCVTIMEO);
}
[[nodiscard]] bool connect() noexcept
{
close();
clearLastError();
addrinfo hints{};
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo *rawResults = nullptr;
const auto portText = std::to_string(m_port);
const int addressInfoResult =
::getaddrinfo(m_serverAddress.c_str(), portText.c_str(), &hints, &rawResults);
if (addressInfoResult != 0)
{
setLastAddressInfoError(addressInfoResult);
return false;
}
using AddrInfoPtr = std::unique_ptr<addrinfo, void (*)(addrinfo *)>;
AddrInfoPtr addressResults(rawResults, ::freeaddrinfo);
for (addrinfo *current = addressResults.get(); current != nullptr; current = current->ai_next)
{
const int socketFd = ::socket(current->ai_family, current->ai_socktype, current->ai_protocol);
if (socketFd < 0)
{
setLastPlatformError(errno);
continue;
}
if (!configureSocket(socketFd))
{
closeSocketValue(socketFd);
continue;
}
if (::connect(socketFd, current->ai_addr, current->ai_addrlen) == 0)
{
m_socket = socketFd;
clearLastError();
return true;
}
setLastPlatformError(errno);
closeSocketValue(socketFd);
}
return false;
}
[[nodiscard]] bool reconnect() noexcept
{
close();
return connect();
}
void close() noexcept
{
if (m_socket >= 0)
{
closeSocketValue(m_socket);
m_socket = -1;
}
}
[[nodiscard]] bool shutdownWrite() noexcept
{
if (!isConnected())
{
return false;
}
clearLastError();
if (::shutdown(m_socket, SHUT_WR) < 0)
{
setLastPlatformError(errno);
return false;
}
return true;
}
[[nodiscard]] enm_IOResult sendAll(const Buffer &payload) noexcept
{
return sendAll(payload.data(), payload.size());
}
[[nodiscard]] enm_IOResult sendAll(std::string_view payload) noexcept
{
return sendAll(payload.data(), payload.size());
}
[[nodiscard]] enm_IOResult sendAll(const void *data, std::size_t size) noexcept
{
if (size == 0U)
{
clearLastError();
return enm_IOResult::Success;
}
if (data == nullptr)
{
clearLastError();
return enm_IOResult::InvalidArgument;
}
if (!isConnected())
{
clearLastError();
return enm_IOResult::NotConnected;
}
clearLastError();
const auto *bytes = static_cast<const std::uint8_t *>(data);
std::size_t totalSent = 0U;
while (totalSent < size)
{
const auto bytesSent = ::send(
m_socket,
bytes + totalSent,
size - totalSent,
platformSendFlags());
if (bytesSent > 0)
{
totalSent += static_cast<std::size_t>(bytesSent);
continue;
}
if ((bytesSent < 0) && (errno == EINTR))
{
continue;
}
return classifySocketError(errno);
}
return enm_IOResult::Success;
}
[[nodiscard]] enm_IOResult receiveSome(
Buffer &out,
std::size_t maxBytes = kDefaultReceiveChunkSize) noexcept
{
out.clear();
if (maxBytes == 0U)
{
clearLastError();
return enm_IOResult::InvalidArgument;
}
if (!isConnected())
{
clearLastError();
return enm_IOResult::NotConnected;
}
clearLastError();
Buffer buffer(maxBytes);
while (true)
{
const auto bytesRead = ::recv(m_socket, buffer.data(), buffer.size(), 0);
if (bytesRead > 0)
{
buffer.resize(static_cast<std::size_t>(bytesRead));
out = std::move(buffer);
return enm_IOResult::Success;
}
if (bytesRead == 0)
{
return enm_IOResult::Closed;
}
if (errno == EINTR)
{
continue;
}
return classifySocketError(errno);
}
}
[[nodiscard]] enm_IOResult receiveExact(std::size_t bytesToRead, Buffer &out) noexcept
{
out.clear();
if (bytesToRead == 0U)
{
clearLastError();
return enm_IOResult::Success;
}
if (!isConnected())
{
clearLastError();
return enm_IOResult::NotConnected;
}
clearLastError();
out.resize(bytesToRead);
std::size_t totalRead = 0U;
while (totalRead < bytesToRead)
{
const auto bytesRead = ::recv(m_socket, out.data() + totalRead, bytesToRead - totalRead, 0);
if (bytesRead > 0)
{
totalRead += static_cast<std::size_t>(bytesRead);
continue;
}
if (bytesRead == 0)
{
out.resize(totalRead);
return enm_IOResult::Closed;
}
if (errno == EINTR)
{
continue;
}
out.resize(totalRead);
return classifySocketError(errno);
}
return enm_IOResult::Success;
}
[[nodiscard]] enm_IOResult receiveUntilDelimiter(
std::string_view delimiter,
Buffer &out,
std::size_t maxBytes = kDefaultMaxPayloadSize) noexcept
{
if (delimiter.empty() || (maxBytes == 0U))
{
out.clear();
clearLastError();
return enm_IOResult::InvalidArgument;
}
Buffer delimiterBuffer(delimiter.begin(), delimiter.end());
return receiveUntilDelimiter(delimiterBuffer, out, maxBytes);
}
[[nodiscard]] enm_IOResult receiveUntilDelimiter(
const Buffer &delimiter,
Buffer &out,
std::size_t maxBytes = kDefaultMaxPayloadSize) noexcept
{
out.clear();
if (delimiter.empty() || (maxBytes == 0U))
{
clearLastError();
return enm_IOResult::InvalidArgument;
}
if (!isConnected())
{
clearLastError();
return enm_IOResult::NotConnected;
}
clearLastError();
Buffer chunk;
while (out.size() < maxBytes)
{
const auto nextChunkSize = std::min(kDefaultReceiveChunkSize, maxBytes - out.size());
const auto readResult = receiveSome(chunk, nextChunkSize);
if (readResult == enm_IOResult::Success)
{
out.insert(out.end(), chunk.begin(), chunk.end());
if (std::search(out.begin(), out.end(), delimiter.begin(), delimiter.end()) != out.end())
{
return enm_IOResult::Success;
}
continue;
}
return readResult;
}
setLastPlatformError(EMSGSIZE);
return enm_IOResult::Failed;
}
[[nodiscard]] enm_IOResult receiveUntilClosed(
Buffer &out,
std::size_t maxBytes = kDefaultMaxPayloadSize) noexcept
{
out.clear();
if (maxBytes == 0U)
{
clearLastError();
return enm_IOResult::InvalidArgument;
}
if (!isConnected())
{
clearLastError();
return enm_IOResult::NotConnected;
}
clearLastError();
Buffer chunk;
while (out.size() < maxBytes)
{
const auto nextChunkSize = std::min(kDefaultReceiveChunkSize, maxBytes - out.size());
const auto readResult = receiveSome(chunk, nextChunkSize);
if (readResult == enm_IOResult::Success)
{
out.insert(out.end(), chunk.begin(), chunk.end());
continue;
}
if (readResult == enm_IOResult::Closed)
{
clearLastError();
return enm_IOResult::Success;
}
return readResult;
}
setLastPlatformError(EMSGSIZE);
return enm_IOResult::Failed;
}
[[nodiscard]] enm_IOResult exchangeOnce(
std::string_view request,
Buffer &response,
std::size_t maxResponseBytes = kDefaultReceiveChunkSize) noexcept
{
return exchangeOnce(request.data(), request.size(), response, maxResponseBytes);
}
[[nodiscard]] enm_IOResult exchangeOnce(
const Buffer &request,
Buffer &response,
std::size_t maxResponseBytes = kDefaultReceiveChunkSize) noexcept
{
return exchangeOnce(request.data(), request.size(), response, maxResponseBytes);
}
[[nodiscard]] enm_IOResult exchangeOnce(
const void *requestData,
std::size_t requestSize,
Buffer &response,
std::size_t maxResponseBytes = kDefaultReceiveChunkSize) noexcept
{
if (!connect())
{
response.clear();
return enm_IOResult::Failed;
}
auto closeOnExit = hotbits::MakeScopeExit([this]() noexcept
{ close(); });
const auto sendResult = sendAll(requestData, requestSize);
if (sendResult != enm_IOResult::Success)
{
response.clear();
return sendResult;
}
return receiveSome(response, maxResponseBytes);
}
[[nodiscard]] enm_IOResult exchangeOnceUntilClosed(
std::string_view request,
Buffer &response,
std::size_t maxResponseBytes = kDefaultMaxPayloadSize) noexcept
{
return exchangeOnceUntilClosed(request.data(), request.size(), response, maxResponseBytes);
}
[[nodiscard]] enm_IOResult exchangeOnceUntilClosed(
const Buffer &request,
Buffer &response,
std::size_t maxResponseBytes = kDefaultMaxPayloadSize) noexcept
{
return exchangeOnceUntilClosed(request.data(), request.size(), response, maxResponseBytes);
}
[[nodiscard]] enm_IOResult exchangeOnceUntilClosed(
const void *requestData,
std::size_t requestSize,
Buffer &response,
std::size_t maxResponseBytes = kDefaultMaxPayloadSize) noexcept
{
if (!connect())
{
response.clear();
return enm_IOResult::Failed;
}
auto closeOnExit = hotbits::MakeScopeExit([this]() noexcept
{ close(); });
const auto sendResult = sendAll(requestData, requestSize);
if (sendResult != enm_IOResult::Success)
{
response.clear();
return sendResult;
}
if (!shutdownWrite())
{
response.clear();
return enm_IOResult::Failed;
}
return receiveUntilClosed(response, maxResponseBytes);
}
[[nodiscard]] int lastPlatformError() const noexcept
{
return m_lastPlatformError;
}
[[nodiscard]] int lastAddressInfoError() const noexcept
{
return m_lastAddressInfoError;
}
[[nodiscard]] std::string lastErrorMessage() const
{
if (m_lastAddressInfoError != 0)
{
return ::gai_strerror(m_lastAddressInfoError);
}
if (m_lastPlatformError != 0)
{
return std::strerror(m_lastPlatformError);
}
return {};
}
private:
[[nodiscard]] static duration_type sanitizeTimeout(duration_type timeout) noexcept
{
return (timeout < duration_type::zero()) ? duration_type::zero() : timeout;
}
[[nodiscard]] static timeval toTimeval(duration_type timeout) noexcept
{
const auto clamped = sanitizeTimeout(timeout);
timeval value{};
value.tv_sec = static_cast<decltype(value.tv_sec)>(clamped.count() / 1000);
value.tv_usec = static_cast<decltype(value.tv_usec)>((clamped.count() % 1000) * 1000);
return value;
}
[[nodiscard]] bool applyConfiguredTimeout(duration_type timeout, int optionName) noexcept
{
clearLastError();
if (!isConnected())
{
return true;
}
const auto timeoutValue = toTimeval(timeout);
if (::setsockopt(m_socket, SOL_SOCKET, optionName, &timeoutValue, sizeof(timeoutValue)) < 0)
{
setLastPlatformError(errno);
return false;
}
return true;
}
[[nodiscard]] bool configureSocket(int socketFd) noexcept
{
#ifdef SO_NOSIGPIPE
const int disableSigPipe = 1;
if (::setsockopt(socketFd, SOL_SOCKET, SO_NOSIGPIPE, &disableSigPipe, sizeof(disableSigPipe)) < 0)
{
setLastPlatformError(errno);
return false;
}
#endif
const auto sendTimeoutValue = toTimeval(m_sendTimeout);
if (::setsockopt(socketFd, SOL_SOCKET, SO_SNDTIMEO, &sendTimeoutValue, sizeof(sendTimeoutValue)) < 0)
{
setLastPlatformError(errno);
return false;
}
const auto receiveTimeoutValue = toTimeval(m_receiveTimeout);
if (::setsockopt(socketFd, SOL_SOCKET, SO_RCVTIMEO, &receiveTimeoutValue, sizeof(receiveTimeoutValue)) < 0)
{
setLastPlatformError(errno);
return false;
}
return true;
}
[[nodiscard]] static int platformSendFlags() noexcept
{
#ifdef MSG_NOSIGNAL
return MSG_NOSIGNAL;
#else
return 0;
#endif
}
[[nodiscard]] static bool isTimeoutError(int errorCode) noexcept
{
return (errorCode == EAGAIN) || (errorCode == EWOULDBLOCK) || (errorCode == ETIMEDOUT);
}
[[nodiscard]] enm_IOResult classifySocketError(int errorCode) noexcept
{
setLastPlatformError(errorCode);
return isTimeoutError(errorCode) ? enm_IOResult::Timeout : enm_IOResult::Failed;
}
void clearLastError() noexcept
{
m_lastPlatformError = 0;
m_lastAddressInfoError = 0;
}
void setLastPlatformError(int errorCode) noexcept
{
m_lastPlatformError = errorCode;
m_lastAddressInfoError = 0;
}
void setLastAddressInfoError(int errorCode) noexcept
{
m_lastPlatformError = 0;
m_lastAddressInfoError = errorCode;
}
static void closeSocketValue(int socketFd) noexcept
{
if (socketFd >= 0)
{
::shutdown(socketFd, SHUT_RDWR);
::close(socketFd);
}
}
std::string m_serverAddress;
std::uint16_t m_port{0U};
int m_socket{-1};
duration_type m_sendTimeout{duration_type::zero()};
duration_type m_receiveTimeout{duration_type::zero()};
int m_lastPlatformError{0};
int m_lastAddressInfoError{0};
};