Repository navigation
Expand file tree
/
Copy pathNetworkIF.cpp
More file actions
1426 lines (1220 loc) · 47.4 KB
/
Copy pathNetworkIF.cpp
File metadata and controls
1426 lines (1220 loc) · 47.4 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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// NetworkIF.cpp
// Implementation of cross-platform template-based network interface
#include "NetworkIF.h"
#include <algorithm>
#include <cstring>
#include "NameResolver.h"
#ifdef _WIN32
#define POLL_FUNC WSAPoll
#else
#define POLL_FUNC ::poll
#endif
std::string_view networkErrorToString(NetworkError aError) noexcept {
switch (aError) {
case NetworkError::SUCCESS:
return "Success";
case NetworkError::SOCKET_CREATE_ERROR:
return "Socket creation failed";
case NetworkError::BIND_ERROR:
return "Socket bind failed";
case NetworkError::LISTEN_ERROR:
return "Socket listen failed";
case NetworkError::ACCEPT_ERROR:
return "Connection accept failed";
case NetworkError::CONNECT_ERROR:
return "Connection failed";
case NetworkError::SEND_ERROR:
return "Send failed";
case NetworkError::RECEIVE_ERROR:
return "Receive failed";
case NetworkError::TIMEOUT_ERROR:
return "Operation timed out";
case NetworkError::INVALID_ADDRESS:
return "Invalid network address";
case NetworkError::SOCKET_INVALID:
return "Invalid socket";
case NetworkError::ALREADY_BOUND:
return "Socket is already bound";
case NetworkError::NOT_CONNECTED:
return "Socket is not connected";
case NetworkError::MULTICAST_ERROR:
return "Multicast operation failed";
case NetworkError::OPTION_ERROR:
return "Socket option failed";
case NetworkError::WINSOCK_INIT_ERROR:
return "Winsock initialization failed";
case NetworkError::ADDRESS_IN_USE:
return "Address is already in use";
case NetworkError::CONNECTION_REFUSED:
return "Connection was refused";
case NetworkError::CONNECTION_RESET:
return "Connection was reset";
case NetworkError::WOULD_BLOCK:
return "Operation would block";
case NetworkError::UNKNOWN_ERROR:
return "Unknown network error";
}
return "Unknown network error";
}
// -------------------- Constructor / Destructor --------------------
template <Protocol TProtocol, Role TRole>
NetworkIF<TProtocol, TRole>::NetworkIF()
: mNextIdleCleanup(std::chrono::steady_clock::now())
, mReceiveBuffer(DEFAULT_BUFFER_SIZE) {
#ifdef _WIN32
NetworkIFInternal::getWinsockInitializer();
#endif
}
template <Protocol TProtocol, Role TRole>
NetworkIF<TProtocol, TRole>::~NetworkIF() {
close();
}
template <Protocol TProtocol, Role TRole>
NetworkIF<TProtocol, TRole>::NetworkIF(NetworkIF&& aOther) noexcept
: mSocket(aOther.mSocket)
, mIpVersion(aOther.mIpVersion)
, mBound(aOther.mBound)
, mConnected(aOther.mConnected)
, mListening(aOther.mListening)
, mLocalPort(aOther.mLocalPort)
, mIdleTimeoutMs(aOther.mIdleTimeoutMs)
, mNextIdleCleanup(aOther.mNextIdleCleanup)
, mMaxEventsPerPoll(aOther.mMaxEventsPerPoll)
, mPollModeEnabled(aOther.mPollModeEnabled)
, mClients(std::move(aOther.mClients))
, mOnNewConnection(std::move(aOther.mOnNewConnection))
, mOnDataReceived(std::move(aOther.mOnDataReceived))
, mOnDisconnect(std::move(aOther.mOnDisconnect))
, mReceiveBuffer(std::move(aOther.mReceiveBuffer)) {
aOther.mSocket = INVALID_SOCK;
aOther.mBound = false;
aOther.mConnected = false;
aOther.mListening = false;
aOther.mPollModeEnabled = false;
}
template <Protocol TProtocol, Role TRole>
NetworkIF<TProtocol, TRole>& NetworkIF<TProtocol, TRole>::operator=(NetworkIF&& aOther) noexcept {
if (this != &aOther) {
close();
mSocket = aOther.mSocket;
mIpVersion = aOther.mIpVersion;
mBound = aOther.mBound;
mConnected = aOther.mConnected;
mListening = aOther.mListening;
mLocalPort = aOther.mLocalPort;
mIdleTimeoutMs = aOther.mIdleTimeoutMs;
mNextIdleCleanup = aOther.mNextIdleCleanup;
mMaxEventsPerPoll = aOther.mMaxEventsPerPoll;
mPollModeEnabled = aOther.mPollModeEnabled;
mClients = std::move(aOther.mClients);
mOnNewConnection = std::move(aOther.mOnNewConnection);
mOnDataReceived = std::move(aOther.mOnDataReceived);
mOnDisconnect = std::move(aOther.mOnDisconnect);
mReceiveBuffer = std::move(aOther.mReceiveBuffer);
aOther.mSocket = INVALID_SOCK;
aOther.mBound = false;
aOther.mConnected = false;
aOther.mListening = false;
aOther.mPollModeEnabled = false;
}
return *this;
}
// -------------------- Core Operations --------------------
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::create(IpVersion aIpVersion) {
#ifdef _WIN32
if (!NetworkIFInternal::getWinsockInitializer().isInitialized()) {
return NetworkError::WINSOCK_INIT_ERROR;
}
#endif
if (mSocket != INVALID_SOCK) {
close();
}
mIpVersion = aIpVersion;
auto lFamily = getAddressFamily();
auto lType = (TProtocol == Protocol::TCP) ? SOCK_STREAM : SOCK_DGRAM;
auto lProtocol = (TProtocol == Protocol::TCP) ? IPPROTO_TCP : IPPROTO_UDP;
mSocket = ::socket(lFamily, lType, lProtocol);
if (mSocket == INVALID_SOCK) {
return mapSystemError(GET_LAST_ERROR);
}
// Enable address reuse
int32_t lReuseAddr = 1;
setSocketOption(SOL_SOCKET, SO_REUSEADDR, &lReuseAddr, sizeof(lReuseAddr));
// For dual-stack, disable IPV6_V6ONLY to allow IPv4-mapped addresses
if (aIpVersion == IpVersion::DUAL && lFamily == AF_INET6) {
int32_t lV6Only = 0;
setSocketOption(IPPROTO_IPV6, IPV6_V6ONLY, &lV6Only, sizeof(lV6Only));
}
// For IPv6 only, enable IPV6_V6ONLY
if (aIpVersion == IpVersion::V6 && lFamily == AF_INET6) {
int32_t lV6Only = 1;
setSocketOption(IPPROTO_IPV6, IPV6_V6ONLY, &lV6Only, sizeof(lV6Only));
}
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::bind(uint16_t aPort, const std::string& aBindAddress) {
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
if (mBound) {
return NetworkError::ALREADY_BOUND;
}
sockaddr_storage lAddr;
socklen_t lAddrLen;
std::memset(&lAddr, 0, sizeof(lAddr));
auto lFamily = getAddressFamily();
if (!aBindAddress.empty()) {
const auto lAddress = IpAddress::parse(aBindAddress);
if (!lAddress ||
(lFamily == AF_INET6 && !lAddress->isIPv6()) ||
(lFamily == AF_INET && !lAddress->isIPv4())) {
return NetworkError::INVALID_ADDRESS;
}
NetworkSocklen lNativeLength = 0;
if (!lAddress->toSockaddr(aPort, lAddr, lNativeLength)) {
return NetworkError::INVALID_ADDRESS;
}
lAddrLen = static_cast<socklen_t>(lNativeLength);
} else if (lFamily == AF_INET6) {
auto* lpAddr6 = reinterpret_cast<sockaddr_in6*>(&lAddr);
lpAddr6->sin6_family = AF_INET6;
lpAddr6->sin6_port = htons(aPort);
lpAddr6->sin6_addr = in6addr_any;
lAddrLen = sizeof(sockaddr_in6);
} else {
auto* lpAddr4 = reinterpret_cast<sockaddr_in*>(&lAddr);
lpAddr4->sin_family = AF_INET;
lpAddr4->sin_port = htons(aPort);
lpAddr4->sin_addr.s_addr = INADDR_ANY;
lAddrLen = sizeof(sockaddr_in);
}
if (::bind(mSocket, reinterpret_cast<sockaddr*>(&lAddr), lAddrLen) == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
// Get actual bound port (useful if aPort was 0)
if (getsockname(mSocket, reinterpret_cast<sockaddr*>(&lAddr), &lAddrLen) == 0) {
if (lFamily == AF_INET6) {
mLocalPort = ntohs(reinterpret_cast<sockaddr_in6*>(&lAddr)->sin6_port);
} else {
mLocalPort = ntohs(reinterpret_cast<sockaddr_in*>(&lAddr)->sin_port);
}
}
mBound = true;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::listen(int32_t aBacklog) {
if constexpr (TProtocol != Protocol::TCP || TRole != Role::SERVER) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
if (!mBound) {
return NetworkError::SOCKET_INVALID;
}
if (::listen(mSocket, aBacklog) == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
mListening = true;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::accept(NetworkIF<Protocol::TCP, Role::CLIENT>& rClientSocket, ClientInfo& rClientInfo) {
if constexpr (TProtocol != Protocol::TCP || TRole != Role::SERVER) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK || !mListening) {
return NetworkError::SOCKET_INVALID;
}
sockaddr_storage lClientAddr;
socklen_t lAddrLen = sizeof(lClientAddr);
std::memset(&lClientAddr, 0, sizeof(lClientAddr));
SOCKTYPE lClientSocket = ::accept(mSocket, reinterpret_cast<sockaddr*>(&lClientAddr), &lAddrLen);
if (lClientSocket == INVALID_SOCK) {
return mapSystemError(GET_LAST_ERROR);
}
extractClientInfo(lClientAddr, lAddrLen, rClientInfo);
// Set up the client socket
rClientSocket.close();
rClientSocket.mSocket = lClientSocket;
rClientSocket.mIpVersion = mIpVersion;
rClientSocket.mConnected = true;
rClientSocket.mBound = true;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::connect(const std::string& aHost, uint16_t aPort) {
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
sockaddr_storage lAddr;
socklen_t lAddrLen;
auto lResolveResult = resolveAddress(aHost, aPort, lAddr, lAddrLen);
if (lResolveResult != NetworkError::SUCCESS) {
return lResolveResult;
}
if (::connect(mSocket, reinterpret_cast<sockaddr*>(&lAddr), lAddrLen) == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
mConnected = true;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::close() {
if (mSocket != INVALID_SOCK) {
if constexpr (TRole == Role::SERVER) {
std::vector<std::shared_ptr<NetworkIFInternal::ClientContext>> lClients;
{
std::lock_guard<std::mutex> lLock(mClientsMutex);
lClients.reserve(mClients.size());
for (const auto& lEntry : mClients) {
lClients.push_back(lEntry.second);
}
mClients.clear();
mPollSetDirty = true;
}
for (const auto& lpClient : lClients) {
std::lock_guard<std::recursive_mutex> lClientLock(lpClient->mMutex);
if (!lpClient->mActive) {
continue;
}
lpClient->mActive = false;
if (mOnDisconnect) {
mOnDisconnect(lpClient->mInfo, lpClient->mUserContext);
}
if constexpr (TProtocol == Protocol::TCP) {
if (lpClient->mSocket != INVALID_SOCK) {
CLOSE_SOCKET(lpClient->mSocket);
lpClient->mSocket = INVALID_SOCK;
}
}
}
}
CLOSE_SOCKET(mSocket);
mSocket = INVALID_SOCK;
}
mBound = false;
mConnected = false;
mListening = false;
mLocalPort = 0;
mPollModeEnabled = false;
mPollFds.clear();
mPollClients.clear();
mPollSetDirty = true;
}
// -------------------- Data Transfer --------------------
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::send(std::span<const uint8_t> aData, int64_t& rBytesSent) {
rBytesSent = 0;
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
if constexpr (TProtocol == Protocol::TCP) {
if (!mConnected) {
return NetworkError::NOT_CONNECTED;
}
}
#ifdef _WIN32
auto lResult = ::send(mSocket, reinterpret_cast<const char*>(aData.data()),
static_cast<int>(aData.size()), 0);
#else
auto lResult = ::send(mSocket, aData.data(), aData.size(), 0);
#endif
if (lResult == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
rBytesSent = lResult;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::sendTo(std::span<const uint8_t> aData, const std::string& aHost, uint16_t aPort, int64_t& rBytesSent) {
rBytesSent = 0;
if constexpr (TProtocol != Protocol::UDP) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
sockaddr_storage lAddr;
socklen_t lAddrLen;
auto lResolveResult = resolveAddress(aHost, aPort, lAddr, lAddrLen);
if (lResolveResult != NetworkError::SUCCESS) {
return lResolveResult;
}
#ifdef _WIN32
auto lResult = ::sendto(mSocket, reinterpret_cast<const char*>(aData.data()),
static_cast<int>(aData.size()), 0,
reinterpret_cast<sockaddr*>(&lAddr), lAddrLen);
#else
auto lResult = ::sendto(mSocket, aData.data(), aData.size(), 0,
reinterpret_cast<sockaddr*>(&lAddr), lAddrLen);
#endif
if (lResult == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
rBytesSent = lResult;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::receive(std::span<uint8_t> rBuffer, int64_t& rBytesReceived) {
rBytesReceived = 0;
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
#ifdef _WIN32
auto lResult = ::recv(mSocket, reinterpret_cast<char*>(rBuffer.data()),
static_cast<int>(rBuffer.size()), 0);
#else
auto lResult = ::recv(mSocket, rBuffer.data(), rBuffer.size(), 0);
#endif
if (lResult == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
if (lResult == 0 && TProtocol == Protocol::TCP) {
return NetworkError::CONNECTION_RESET;
}
rBytesReceived = lResult;
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::receiveFrom(std::span<uint8_t> rBuffer, int64_t& rBytesReceived, ClientInfo& rClientInfo) {
rBytesReceived = 0;
if constexpr (TProtocol != Protocol::UDP) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
sockaddr_storage lSenderAddr;
socklen_t lAddrLen = sizeof(lSenderAddr);
std::memset(&lSenderAddr, 0, sizeof(lSenderAddr));
#ifdef _WIN32
auto lResult = ::recvfrom(mSocket, reinterpret_cast<char*>(rBuffer.data()),
static_cast<int>(rBuffer.size()), 0,
reinterpret_cast<sockaddr*>(&lSenderAddr), &lAddrLen);
#else
auto lResult = ::recvfrom(mSocket, rBuffer.data(), rBuffer.size(), 0,
reinterpret_cast<sockaddr*>(&lSenderAddr), &lAddrLen);
#endif
if (lResult == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
extractClientInfo(lSenderAddr, lAddrLen, rClientInfo);
rBytesReceived = lResult;
return NetworkError::SUCCESS;
}
// -------------------- Timeout Configuration --------------------
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::setReceiveTimeout(int64_t aMilliseconds) {
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
#ifdef _WIN32
DWORD lTimeout = static_cast<DWORD>(aMilliseconds);
return setSocketOption(SOL_SOCKET, SO_RCVTIMEO, &lTimeout, sizeof(lTimeout));
#else
struct timeval lTv;
lTv.tv_sec = aMilliseconds / 1000;
lTv.tv_usec = (aMilliseconds % 1000) * 1000;
return setSocketOption(SOL_SOCKET, SO_RCVTIMEO, &lTv, sizeof(lTv));
#endif
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::setSendTimeout(int64_t aMilliseconds) {
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
#ifdef _WIN32
DWORD lTimeout = static_cast<DWORD>(aMilliseconds);
return setSocketOption(SOL_SOCKET, SO_SNDTIMEO, &lTimeout, sizeof(lTimeout));
#else
struct timeval lTv;
lTv.tv_sec = aMilliseconds / 1000;
lTv.tv_usec = (aMilliseconds % 1000) * 1000;
return setSocketOption(SOL_SOCKET, SO_SNDTIMEO, &lTv, sizeof(lTv));
#endif
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::setIdleTimeout(int64_t aMilliseconds) {
mIdleTimeoutMs = aMilliseconds;
mNextIdleCleanup = std::chrono::steady_clock::now();
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::setMaxEventsPerPoll(size_t aMaxEvents) {
mMaxEventsPerPoll = std::max<size_t>(1, aMaxEvents);
}
// -------------------- Server Callbacks --------------------
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::setOnNewConnection(OnNewConnectionCallback aCallback) {
mOnNewConnection = std::move(aCallback);
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::setOnDataReceived(OnDataReceivedCallback aCallback) {
mOnDataReceived = std::move(aCallback);
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::setOnDisconnect(OnDisconnectCallback aCallback) {
mOnDisconnect = std::move(aCallback);
}
// -------------------- Server Event Loop --------------------
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::setNonBlocking(SOCKTYPE aSocket) {
#ifdef _WIN32
u_long lMode = 1;
if (ioctlsocket(aSocket, FIONBIO, &lMode) == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
#else
auto lFlags = fcntl(aSocket, F_GETFL, 0);
if (lFlags == SOCK_ERROR || fcntl(aSocket, F_SETFL, lFlags | O_NONBLOCK) == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
#endif
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::enablePollMode() {
if (mPollModeEnabled) {
return NetworkError::SUCCESS;
}
auto lResult = setNonBlocking(mSocket);
if (lResult == NetworkError::SUCCESS) {
mPollModeEnabled = true;
mPollSetDirty = true;
}
return lResult;
}
template <Protocol TProtocol, Role TRole>
void NetworkIF<TProtocol, TRole>::rebuildPollSet() {
mPollFds.clear();
mPollClients.clear();
NetworkPollFd lServerFd{};
lServerFd.fd = mSocket;
lServerFd.events = POLLIN;
mPollFds.push_back(lServerFd);
if constexpr (TProtocol == Protocol::TCP) {
std::lock_guard<std::mutex> lLock(mClientsMutex);
mPollFds.reserve(mClients.size() + 1);
mPollClients.reserve(mClients.size());
for (const auto& lEntry : mClients) {
const auto& lpClient = lEntry.second;
if (lpClient->mSocket == INVALID_SOCK) {
continue;
}
NetworkPollFd lClientFd{};
lClientFd.fd = lpClient->mSocket;
lClientFd.events = POLLIN;
mPollFds.push_back(lClientFd);
mPollClients.push_back(lpClient);
}
}
mPollSetDirty = false;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::poll(int64_t aTimeoutMs) {
if constexpr (TRole != Role::SERVER) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
auto lModeResult = enablePollMode();
if (lModeResult != NetworkError::SUCCESS) {
return lModeResult;
}
if (mPollSetDirty) {
rebuildPollSet();
}
#ifdef _WIN32
auto lPollResult = POLL_FUNC(mPollFds.data(), static_cast<ULONG>(mPollFds.size()),
static_cast<INT>(aTimeoutMs));
#else
auto lPollResult = POLL_FUNC(mPollFds.data(), mPollFds.size(), static_cast<int>(aTimeoutMs));
#endif
if (lPollResult == SOCK_ERROR) {
return mapSystemError(GET_LAST_ERROR);
}
if (lPollResult == 0) {
cleanupIdleClients();
return NetworkError::TIMEOUT_ERROR;
}
if ((mPollFds[0].revents & POLLIN) != 0) {
if constexpr (TProtocol == Protocol::TCP) {
for (size_t lEvent = 0; lEvent < mMaxEventsPerPoll; ++lEvent) {
sockaddr_storage lClientAddr{};
socklen_t lAddrLen = sizeof(lClientAddr);
auto lClientSocket = ::accept(
mSocket, reinterpret_cast<sockaddr*>(&lClientAddr), &lAddrLen);
if (lClientSocket == INVALID_SOCK) {
auto lError = GET_LAST_ERROR;
if (isWouldBlock(lError)) {
break;
}
return mapSystemError(lError);
}
auto lNonBlockingResult = setNonBlocking(lClientSocket);
if (lNonBlockingResult != NetworkError::SUCCESS) {
CLOSE_SOCKET(lClientSocket);
return lNonBlockingResult;
}
ClientInfo lInfo;
extractClientInfo(lClientAddr, lAddrLen, lInfo);
std::optional<std::any> lUserContext = std::any{};
if (mOnNewConnection) {
lUserContext = mOnNewConnection(lInfo);
}
if (!lUserContext.has_value()) {
CLOSE_SOCKET(lClientSocket);
continue;
}
auto lpClient = std::make_shared<NetworkIFInternal::ClientContext>();
lpClient->mUserContext = std::move(*lUserContext);
lpClient->mLastActivity = std::chrono::steady_clock::now();
lpClient->mInfo = lInfo;
lpClient->mKey = makeEndpointKey(lClientAddr);
lpClient->mSocket = lClientSocket;
std::lock_guard<std::mutex> lLock(mClientsMutex);
auto [lIt, lInserted] = mClients.emplace(lpClient->mKey, lpClient);
static_cast<void>(lIt);
if (lInserted) {
mPollSetDirty = true;
} else {
CLOSE_SOCKET(lClientSocket);
}
}
} else {
for (size_t lEvent = 0; lEvent < mMaxEventsPerPoll; ++lEvent) {
sockaddr_storage lSenderAddr{};
socklen_t lAddrLen = sizeof(lSenderAddr);
#ifdef _WIN32
auto lRecvResult = ::recvfrom(
mSocket, reinterpret_cast<char*>(mReceiveBuffer.data()),
static_cast<int>(mReceiveBuffer.size()), 0,
reinterpret_cast<sockaddr*>(&lSenderAddr), &lAddrLen);
#else
auto lRecvResult = ::recvfrom(
mSocket, mReceiveBuffer.data(), mReceiveBuffer.size(), 0,
reinterpret_cast<sockaddr*>(&lSenderAddr), &lAddrLen);
#endif
if (lRecvResult == SOCK_ERROR) {
auto lError = GET_LAST_ERROR;
if (isWouldBlock(lError)) {
break;
}
return mapSystemError(lError);
}
auto lKey = makeEndpointKey(lSenderAddr);
std::shared_ptr<NetworkIFInternal::ClientContext> lpClient;
{
std::lock_guard<std::mutex> lLock(mClientsMutex);
auto lIt = mClients.find(lKey);
if (lIt != mClients.end()) {
lpClient = lIt->second;
}
}
if (!lpClient) {
ClientInfo lInfo;
extractClientInfo(lSenderAddr, lAddrLen, lInfo);
std::optional<std::any> lUserContext = std::any{};
if (mOnNewConnection) {
lUserContext = mOnNewConnection(lInfo);
}
if (!lUserContext.has_value()) {
continue;
}
lpClient = std::make_shared<NetworkIFInternal::ClientContext>();
lpClient->mUserContext = std::move(*lUserContext);
lpClient->mLastActivity = std::chrono::steady_clock::now();
lpClient->mInfo = lInfo;
lpClient->mKey = lKey;
std::lock_guard<std::mutex> lLock(mClientsMutex);
auto [lIt, lInserted] = mClients.emplace(lKey, lpClient);
if (!lInserted) {
lpClient = lIt->second;
}
}
std::lock_guard<std::recursive_mutex> lClientLock(lpClient->mMutex);
if (!lpClient->mActive) {
continue;
}
lpClient->mLastActivity = std::chrono::steady_clock::now();
if (mOnDataReceived) {
mOnDataReceived(
lpClient->mInfo,
std::span<const uint8_t>(mReceiveBuffer.data(), static_cast<size_t>(lRecvResult)),
lpClient->mUserContext);
}
}
}
}
if constexpr (TProtocol == Protocol::TCP) {
for (size_t lIdx = 1; lIdx < mPollFds.size(); ++lIdx) {
if ((mPollFds[lIdx].revents & (POLLIN | POLLHUP | POLLERR)) == 0) {
continue;
}
const auto& lpClient = mPollClients[lIdx - 1];
std::lock_guard<std::recursive_mutex> lClientLock(lpClient->mMutex);
if (!lpClient->mActive) {
continue;
}
for (size_t lEvent = 0; lEvent < mMaxEventsPerPoll; ++lEvent) {
#ifdef _WIN32
auto lRecvResult = ::recv(
lpClient->mSocket, reinterpret_cast<char*>(mReceiveBuffer.data()),
static_cast<int>(mReceiveBuffer.size()), 0);
#else
auto lRecvResult = ::recv(
lpClient->mSocket, mReceiveBuffer.data(), mReceiveBuffer.size(), 0);
#endif
if (lRecvResult > 0) {
lpClient->mLastActivity = std::chrono::steady_clock::now();
if (mOnDataReceived) {
mOnDataReceived(
lpClient->mInfo,
std::span<const uint8_t>(mReceiveBuffer.data(), static_cast<size_t>(lRecvResult)),
lpClient->mUserContext);
}
if (!lpClient->mActive) {
break;
}
continue;
}
if (lRecvResult == SOCK_ERROR && isWouldBlock(GET_LAST_ERROR)) {
break;
}
removeClient(lpClient->mInfo);
break;
}
}
}
cleanupIdleClients();
return NetworkError::SUCCESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::removeClient(const ClientInfo& aClientInfo) {
if constexpr (TRole != Role::SERVER) {
return NetworkError::SOCKET_INVALID;
}
auto lKey = makeEndpointKey(aClientInfo);
if (!lKey.has_value()) {
return NetworkError::INVALID_ADDRESS;
}
std::shared_ptr<NetworkIFInternal::ClientContext> lpClient;
{
std::lock_guard<std::mutex> lLock(mClientsMutex);
auto lIt = mClients.find(*lKey);
if (lIt == mClients.end()) {
return NetworkError::INVALID_ADDRESS;
}
lpClient = lIt->second;
mClients.erase(lIt);
mPollSetDirty = true;
}
std::lock_guard<std::recursive_mutex> lClientLock(lpClient->mMutex);
if (!lpClient->mActive) {
return NetworkError::SUCCESS;
}
lpClient->mActive = false;
if (mOnDisconnect) {
mOnDisconnect(lpClient->mInfo, lpClient->mUserContext);
}
if constexpr (TProtocol == Protocol::TCP) {
if (lpClient->mSocket != INVALID_SOCK) {
CLOSE_SOCKET(lpClient->mSocket);
lpClient->mSocket = INVALID_SOCK;
}
}
return NetworkError::SUCCESS;
}
// -------------------- UDP Multicast --------------------
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::joinMulticastGroup(const std::string& aGroupAddr, const std::string& aInterface) {
if constexpr (TProtocol != Protocol::UDP) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
// Determine if IPv4 or IPv6 multicast address
struct in_addr lAddr4;
struct in6_addr lAddr6;
if (inet_pton(AF_INET, aGroupAddr.c_str(), &lAddr4) == 1) {
// IPv4 multicast
struct ip_mreq lMreq;
std::memset(&lMreq, 0, sizeof(lMreq));
lMreq.imr_multiaddr = lAddr4;
if (aInterface.empty()) {
lMreq.imr_interface.s_addr = INADDR_ANY;
} else {
if (inet_pton(AF_INET, aInterface.c_str(), &lMreq.imr_interface) != 1) {
// Try as interface index
#ifdef _WIN32
lMreq.imr_interface.s_addr = INADDR_ANY;
#else
auto lIfIndex = if_nametoindex(aInterface.c_str());
if (lIfIndex == 0) {
lMreq.imr_interface.s_addr = INADDR_ANY;
} else {
// For IPv4, we can't directly use interface index, use ANY
lMreq.imr_interface.s_addr = INADDR_ANY;
}
#endif
}
}
return setSocketOption(IPPROTO_IP, IP_ADD_MEMBERSHIP, &lMreq, sizeof(lMreq));
} else if (inet_pton(AF_INET6, aGroupAddr.c_str(), &lAddr6) == 1) {
// IPv6 multicast
struct ipv6_mreq lMreq6;
std::memset(&lMreq6, 0, sizeof(lMreq6));
lMreq6.ipv6mr_multiaddr = lAddr6;
if (aInterface.empty()) {
lMreq6.ipv6mr_interface = 0;
} else {
#ifdef _WIN32
lMreq6.ipv6mr_interface = 0;
#else
lMreq6.ipv6mr_interface = if_nametoindex(aInterface.c_str());
#endif
}
return setSocketOption(IPPROTO_IPV6, IPV6_JOIN_GROUP, &lMreq6, sizeof(lMreq6));
}
return NetworkError::INVALID_ADDRESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::leaveMulticastGroup(const std::string& aGroupAddr, const std::string& aInterface) {
if constexpr (TProtocol != Protocol::UDP) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
struct in_addr lAddr4;
struct in6_addr lAddr6;
if (inet_pton(AF_INET, aGroupAddr.c_str(), &lAddr4) == 1) {
struct ip_mreq lMreq;
std::memset(&lMreq, 0, sizeof(lMreq));
lMreq.imr_multiaddr = lAddr4;
if (aInterface.empty()) {
lMreq.imr_interface.s_addr = INADDR_ANY;
} else {
inet_pton(AF_INET, aInterface.c_str(), &lMreq.imr_interface);
}
return setSocketOption(IPPROTO_IP, IP_DROP_MEMBERSHIP, &lMreq, sizeof(lMreq));
} else if (inet_pton(AF_INET6, aGroupAddr.c_str(), &lAddr6) == 1) {
struct ipv6_mreq lMreq6;
std::memset(&lMreq6, 0, sizeof(lMreq6));
lMreq6.ipv6mr_multiaddr = lAddr6;
if (!aInterface.empty()) {
#ifdef _WIN32
lMreq6.ipv6mr_interface = 0;
#else
lMreq6.ipv6mr_interface = if_nametoindex(aInterface.c_str());
#endif
}
return setSocketOption(IPPROTO_IPV6, IPV6_LEAVE_GROUP, &lMreq6, sizeof(lMreq6));
}
return NetworkError::INVALID_ADDRESS;
}
template <Protocol TProtocol, Role TRole>
NetworkError NetworkIF<TProtocol, TRole>::joinSourceSpecificMulticast(const std::string& aGroupAddr, const std::string& aSourceAddr, const std::string& aInterface) {
if constexpr (TProtocol != Protocol::UDP) {
return NetworkError::SOCKET_INVALID;
}
if (mSocket == INVALID_SOCK) {
return NetworkError::SOCKET_INVALID;
}
struct in_addr lGroupAddr4;
struct in_addr lSourceAddr4;
struct in6_addr lGroupAddr6;
struct in6_addr lSourceAddr6;
if (inet_pton(AF_INET, aGroupAddr.c_str(), &lGroupAddr4) == 1 &&
inet_pton(AF_INET, aSourceAddr.c_str(), &lSourceAddr4) == 1) {
// IPv4 SSM
struct ip_mreq_source lMreq;
std::memset(&lMreq, 0, sizeof(lMreq));
lMreq.imr_multiaddr = lGroupAddr4;
lMreq.imr_sourceaddr = lSourceAddr4;
if (aInterface.empty()) {
lMreq.imr_interface.s_addr = INADDR_ANY;
} else {
inet_pton(AF_INET, aInterface.c_str(), &lMreq.imr_interface);
}
return setSocketOption(IPPROTO_IP, IP_ADD_SOURCE_MEMBERSHIP, &lMreq, sizeof(lMreq));
} else if (inet_pton(AF_INET6, aGroupAddr.c_str(), &lGroupAddr6) == 1 &&
inet_pton(AF_INET6, aSourceAddr.c_str(), &lSourceAddr6) == 1) {
// IPv6 SSM using group_source_req
struct group_source_req lGsr;
std::memset(&lGsr, 0, sizeof(lGsr));
auto* lpGroup = reinterpret_cast<sockaddr_in6*>(&lGsr.gsr_group);