-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathStdSocket.cpp
2122 lines (1817 loc) · 72.6 KB
/
StdSocket.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
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
/* Copyright (C) 2016-2020 Thomas Hauck - All Rights Reserved.
Distributed under MIT license.
See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
The author would be happy if changes and
improvements were reported back to him.
Author: Thomas Hauck
Email: [email protected]
*/
#define _CRTDBG_MAP_ALLOC
#include <sstream>
#include <vector>
#include <algorithm>
#include "StdSocket.h"
#if defined (_WIN32) || defined (_WIN64)
#include <iphlpapi.h>
//https://support.microsoft.com/de-de/kb/257460
//#pragma comment(lib, "wsock32")
#pragma comment(lib, "Ws2_32")
#pragma comment(lib, "IPHLPAPI.lib")
typedef char SOCKOPT;
#else
#include <fcntl.h>
#include <sys/types.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#define INVALID_SOCKET (-1)
#define SOCKET_ERROR (-1)
#define closesocket(x) close(x)
#define WSAGetLastError() errno
#define WSAEWOULDBLOCK EWOULDBLOCK
#define SD_RECEIVE SHUT_RD
#define SD_SEND SHUT_WR
#define SD_BOTH SHUT_RDWR
typedef int SOCKOPT;
#endif
// Initialize the Socket Library
InitSocket& SocketInit = InitSocket::GetInstance();
InitSocket& InitSocket::GetInstance() noexcept
{
static InitSocket iniSocket;
return iniSocket;
}
InitSocket::~InitSocket()
{
#if defined(_WIN32) || defined(_WIN64)
if (m_hIFaceNotify != nullptr)
CancelMibChangeNotify2(m_hIFaceNotify);
::WSACleanup();
#else
m_bStopThread = true;
if (m_thIpChange.joinable() == true)
m_thIpChange.join();
#endif
}
void InitSocket::SetAddrNotifyCallback(const function<void(bool, const string&, int, int)>& fnCbAddrNotify)
{
m_fnCbAddrNotify = fnCbAddrNotify;
if (m_fnCbAddrNotify)
{ // notify on current ip addresses
for (auto iter : m_vCurIPAddr)
m_fnCbAddrNotify(true, get<0>(iter), get<1>(iter), get<2>(iter));
}
#if defined(_WIN32) || defined(_WIN64)
if (m_hIFaceNotify == nullptr)
NotifyIpInterfaceChange(AF_UNSPEC, IpIfaceChanged, this, TRUE, &m_hIFaceNotify);
#else
if (m_thIpChange.joinable() == false)
m_thIpChange = thread(&InitSocket::IpChangeThread, this);
#endif
}
InitSocket::InitSocket() noexcept
{
#if defined(_WIN32) || defined(_WIN64)
WSADATA wsaData;
::WSAStartup(MAKEWORD(2, 2), &wsaData);
m_hIFaceNotify = nullptr;
#else
//signal(SIGPIPE, SIG_IGN);
sigset_t sigset;
sigemptyset(&sigset);
sigaddset(&sigset, SIGPIPE);
sigprocmask(SIG_BLOCK, &sigset, NULL);
BaseSocketImpl::EnumIpAddresses(bind(&InitSocket::CbEnumIpAdressen, this, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4), &m_vCurIPAddr);
m_bStopThread = false;
#endif
}
#if defined (_WIN32) || defined (_WIN64)
VOID __stdcall InitSocket::IpIfaceChanged(PVOID CallerContext, PMIB_IPINTERFACE_ROW /*pRow*/, MIB_NOTIFICATION_TYPE NotificationType)
{
InitSocket* const pThis = static_cast<InitSocket*>(CallerContext);
if (pThis == nullptr)
return;
function<int(int, const string&, int, void*)> fnCb = bind(&InitSocket::CbEnumIpAdressen, pThis, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4);
vector<tuple<string, int, int>> vNewIPAddr;
BaseSocketImpl::EnumIpAddresses(fnCb, &vNewIPAddr);
pThis->NotifyOnAddressChanges(vNewIPAddr);
switch (NotificationType)
{
case MibParameterNotification: // 0
OutputDebugString(L"IP Parameter changed\r\n");
break;
case MibAddInstance: // 1
OutputDebugString(L"IP Interface added\r\n");
break;
case MibDeleteInstance: // 2
OutputDebugString(L"IP Interface removed\r\n");
break;
case MibInitialNotification: // 3
OutputDebugString(L"IP Notification initialized\r\n");
break;
}
}
#else
void InitSocket::IpChangeThread()
{
SOCKET fSock;
if ((fSock = socket(PF_NETLINK, SOCK_RAW, NETLINK_ROUTE)) == -1)
{
return;
}
struct sockaddr_nl addr{};
addr.nl_family = AF_NETLINK;
addr.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR | RTMGRP_IPV6_IFADDR;
if (bind(fSock, reinterpret_cast<struct sockaddr *>(&addr), sizeof(addr)) == -1)
{
::closesocket(fSock);
return;
}
if (fcntl(fSock, F_SETFD, FD_CLOEXEC) == -1 || fcntl(fSock, F_SETFL, fcntl(fSock, F_GETFL) | O_NONBLOCK) == -1)
{
::closesocket(fSock);
return;
}
while (m_bStopThread == false)
{
fd_set readfd, errorfd;
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
FD_ZERO(&readfd);
FD_ZERO(&errorfd);
FD_SET(fSock, &readfd);
FD_SET(fSock, &errorfd);
if (::select(static_cast<int>(fSock + 1), &readfd, nullptr, &errorfd, &timeout) > 0)
{
if (FD_ISSET(fSock, &errorfd))
{
int iError;
socklen_t iLen = sizeof(iError);
getsockopt(fSock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&iError), &iLen);
break;
}
if (FD_ISSET(fSock, &readfd))
{
string buf(4096, 0);
int32_t transferred = ::recv(fSock, &buf[0], buf.size(), 0);
if (transferred > 0)
{
struct nlmsghdr* nlh = reinterpret_cast<struct nlmsghdr*>(&buf[0]);
while ((NLMSG_OK(nlh, static_cast<unsigned int>(transferred))) && (nlh->nlmsg_type != NLMSG_DONE))
{
if (nlh->nlmsg_type == RTM_NEWADDR || nlh->nlmsg_type == RTM_DELADDR || nlh->nlmsg_type == RTM_GETADDR)
{
/*struct ifaddrmsg *ifa = (struct ifaddrmsg *) NLMSG_DATA(nlh);
struct rtattr *rth = IFA_RTA(ifa);
int rtl = IFA_PAYLOAD(nlh);
char name[IFNAMSIZ];
if_indextoname(ifa->ifa_index, name);
*/
vector<tuple<string, int, int>> vNewIPAddr;
BaseSocketImpl::EnumIpAddresses(bind(&InitSocket::CbEnumIpAdressen, this, placeholders::_1, placeholders::_2, placeholders::_3, placeholders::_4), &vNewIPAddr);
NotifyOnAddressChanges(vNewIPAddr);
}
nlh = NLMSG_NEXT(nlh, transferred);
}
}
}
}
}
::closesocket(fSock);
}
#endif
int InitSocket::CbEnumIpAdressen(int iFamily, const string& strIp, int nInterFaceId, void* vpUserParam)
{
if (vpUserParam == nullptr)
return 1; // Stop enumeration, doesn't make sense
vector<tuple<const string, int, int>>* pmaStrIps = static_cast<vector<tuple<const string, int, int>>*>(vpUserParam);
pmaStrIps->push_back(make_tuple(strIp, iFamily, nInterFaceId));
return 0;
}
void InitSocket::NotifyOnAddressChanges(vector<tuple<string, int, int>>& vNewListing)
{
vector<tuple<string, int, int>> vDelIPAddr;
m_mxCurIpAddr.lock();
// remove all IP addr. in the vector that where before available
for (auto iter = begin(m_vCurIPAddr); iter != end(m_vCurIPAddr);)
{
auto itFound = find_if(begin(vNewListing), end(vNewListing), [iter](auto& item) { return get<0>(*iter) == get<0>(item) ? true : false; });
if (itFound != end(vNewListing))
vNewListing.erase(itFound); // address existed before, so remove it from the list with our new addresses
else
{ // the IP does not exist any more
vDelIPAddr.push_back(*iter); // remember witch one was removed
iter = m_vCurIPAddr.erase(iter);
continue;
}
++iter;
}
for (auto iter : vNewListing)
m_vCurIPAddr.push_back(iter); // remember witch one was removed
m_mxCurIpAddr.unlock();
if (m_fnCbAddrNotify)
{
// Notify on all deleted IP addresses
for (auto iter : vDelIPAddr)
m_fnCbAddrNotify(false, get<0>(iter), get<1>(iter), get<2>(iter));
// Notify on all new IP addresses
for (auto iter : vNewListing)
m_fnCbAddrNotify(true, get<0>(iter), get<1>(iter), get<2>(iter));
}
}
function<void(const uint16_t, const char*, size_t, bool)> BaseSocketImpl::s_fTrafficDebug;
deque<unique_ptr<BaseSocket>> BaseSocketImpl::s_lstClientSocket;
mutex BaseSocketImpl::s_mxClientSocket;
BaseSocketImpl::BaseSocketImpl() noexcept : m_fSock(INVALID_SOCKET), m_bStop(false), m_iError(0), m_iErrLoc(0), m_iShutDownState(0), m_fError(bind(&BaseSocketImpl::OnError, this)), m_pvUserData(nullptr), m_pBkRef(nullptr)
{
}
BaseSocketImpl::BaseSocketImpl(BaseSocketImpl* pBaseSocket) : m_fSock(INVALID_SOCKET), m_bStop(pBaseSocket->m_bStop), m_iError(pBaseSocket->m_iError), m_iErrLoc(pBaseSocket->m_iErrLoc), m_iShutDownState(0), m_fError(bind(&BaseSocketImpl::OnError, this)), m_pvUserData(pBaseSocket->m_pvUserData), m_pBkRef(nullptr)
{
lock_guard<mutex> lock(pBaseSocket->m_mxWrite);
swap(m_fSock, pBaseSocket->m_fSock);
swap(m_fError, pBaseSocket->m_fError);
swap(m_fErrorParam, pBaseSocket->m_fErrorParam);
swap(m_fClosing, pBaseSocket->m_fClosing);
swap(m_fClosingParam, pBaseSocket->m_fClosingParam);
m_iShutDownState.exchange(pBaseSocket->m_iShutDownState);
}
BaseSocketImpl::~BaseSocketImpl()
{
if (m_thListen.joinable() == true)
m_thListen.join();
if (m_thWrite.joinable() == true)
m_thWrite.join();
if (m_thClose.joinable() == true)
m_thClose.join();
}
function<void(BaseSocket*)> BaseSocketImpl::BindErrorFunction(function<void(BaseSocket*)> fError) noexcept
{
m_fError.swap(fError);
return fError;
}
function<void(BaseSocket*, void*)> BaseSocketImpl::BindErrorFunction(function<void(BaseSocket*, void*)> fError) noexcept
{
m_fErrorParam.swap(fError);
return fError;
}
function<void(BaseSocket*)> BaseSocketImpl::BindCloseFunction(function<void(BaseSocket*)> fClosing) noexcept
{
m_fClosing.swap(fClosing);
return fClosing;
}
function<void(BaseSocket*, void*)> BaseSocketImpl::BindCloseFunction(function<void(BaseSocket*, void*)> fClosing) noexcept
{
m_fClosingParam.swap(fClosing);
return fClosing;
}
void BaseSocketImpl::SetCallbackUserData(void* pUserData) noexcept
{
m_pvUserData = pUserData;
}
void BaseSocketImpl::SetSocketOption(const SOCKET& fd)
{
constexpr SOCKOPT rc = 1;
if (::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &rc, sizeof(rc)) != 0)
throw WSAGetLastError();
#if defined(_WIN32) || defined(_WIN64)
unsigned long rl = 1;
if (::ioctlsocket(fd, FIONBIO, &rl) == SOCKET_ERROR) /* 1 for non-block, 0 for block */
throw WSAGetLastError();
#else
if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1)
throw errno;
if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK) == -1)
throw errno;
#endif
}
void BaseSocketImpl::OnError()
{
Close();
}
void BaseSocketImpl::StartClosingCB()
{
m_mxFnClosing.lock();
if (m_fClosingParam)
{
function<void(BaseSocket*, void*)> tmpfun;
m_fClosingParam.swap(tmpfun);
m_mxFnClosing.unlock();
tmpfun(m_pBkRef, m_pvUserData);
}
else if (m_fClosing)
{
function<void(BaseSocket*)> tmpfun;
m_fClosing.swap(tmpfun);
m_mxFnClosing.unlock();
tmpfun(m_pBkRef);
}
else
m_mxFnClosing.unlock();
}
uint16_t BaseSocketImpl::GetSocketPort()
{
struct sockaddr_storage addrPe;
socklen_t addLen = sizeof(addrPe);
if (::getsockname(m_fSock, reinterpret_cast<struct sockaddr*>(&addrPe), &addLen) == 0) // Get our IP where the connection was established
{
string caAddrPeer(INET6_ADDRSTRLEN + 1, 0);
string servInfoPeer(NI_MAXSERV, 0);
if (::getnameinfo(reinterpret_cast<struct sockaddr*>(&addrPe), sizeof(struct sockaddr_storage), &caAddrPeer[0], INET6_ADDRSTRLEN, &servInfoPeer[0], NI_MAXSERV, NI_NUMERICHOST | NI_NUMERICSERV) == 0)
{
return static_cast<uint16_t>(stoi(&servInfoPeer[0]));
}
}
return 0;
}
int BaseSocketImpl::EnumIpAddresses(function<int(int, const string&, int, void*)> fnCallBack, void* vpUser)
{
#if defined(_WIN32) || defined(_WIN64)
ULONG outBufLen = sizeof(IP_ADAPTER_ADDRESSES_LH) * 255;
auto pAddressList = make_unique<IP_ADAPTER_ADDRESSES_LH[]>(255);
if (pAddressList == nullptr)
return ERROR_OUTOFMEMORY;
DWORD ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, &pAddressList[0], &outBufLen);
if (ret == ERROR_BUFFER_OVERFLOW)
{
pAddressList = make_unique<IP_ADAPTER_ADDRESSES_LH[]>(outBufLen / sizeof(IP_ADAPTER_ADDRESSES_LH) + 1);
if (pAddressList == nullptr)
return ERROR_OUTOFMEMORY;
ret = GetAdaptersAddresses(AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, nullptr, &pAddressList[0], &outBufLen);
}
if (ret == ERROR_SUCCESS)
{
for (PIP_ADAPTER_ADDRESSES pCurrentAddresses = &pAddressList[0]; pCurrentAddresses != nullptr; pCurrentAddresses = pCurrentAddresses->Next)
{
if (pCurrentAddresses->IfType == IF_TYPE_SOFTWARE_LOOPBACK || pCurrentAddresses->OperStatus != IfOperStatusUp)
continue;
for (PIP_ADAPTER_UNICAST_ADDRESS pUnicast = pCurrentAddresses->FirstUnicastAddress; pUnicast != nullptr; pUnicast = pUnicast->Next)
{
if ((pUnicast->Flags & IP_ADAPTER_ADDRESS_TRANSIENT) == IP_ADAPTER_ADDRESS_TRANSIENT)
continue;
string strTmp(255, 0);
if (pUnicast->Address.lpSockaddr->sa_family == AF_INET6)
strTmp = inet_ntop(AF_INET6, &reinterpret_cast<struct sockaddr_in6*>(pUnicast->Address.lpSockaddr)->sin6_addr, &strTmp[0], strTmp.size());
else
strTmp = inet_ntop(AF_INET, &reinterpret_cast<struct sockaddr_in*>(pUnicast->Address.lpSockaddr)->sin_addr, &strTmp[0], strTmp.size());
if (fnCallBack(pUnicast->Address.lpSockaddr->sa_family, strTmp, pCurrentAddresses->IfIndex, vpUser) != 0)
{
return ERROR_CANCELLED;
}
}
}
}
#else
int ret = 0;
struct ifaddrs* lstAddr;
if (getifaddrs(&lstAddr) == 0)
{
for (struct ifaddrs *ptr = lstAddr; ptr != nullptr; ptr = ptr->ifa_next)
{
if (ptr->ifa_addr == nullptr || (ptr->ifa_addr->sa_family != AF_INET && ptr->ifa_addr->sa_family != AF_INET6))
continue;
if ((ptr->ifa_flags & IFF_UP) == 0 || (ptr->ifa_flags & IFF_LOOPBACK) == IFF_LOOPBACK)
continue;
string strAddrBuf(NI_MAXHOST, 0);
if (/*&& string(ptr->ifa_name).find("eth") != string::npos &&*/ getnameinfo(ptr->ifa_addr, (ptr->ifa_addr->sa_family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), &strAddrBuf[0], strAddrBuf.size(), NULL, 0, NI_NUMERICHOST) == 0)
{
unsigned int iIfIndex = if_nametoindex(ptr->ifa_name);
if (fnCallBack(ptr->ifa_addr->sa_family, strAddrBuf, iIfIndex, vpUser) != 0)
{
freeifaddrs(lstAddr);
return ECANCELED;
}
}
}
freeifaddrs(lstAddr);
}
#endif
return ret;
}
void BaseSocketImpl::SetAddrNotifyCallback(const function<void(bool, const string&, int, int)>& fnCbAddrNotify)
{
InitSocket::GetInstance().SetAddrNotifyCallback(fnCbAddrNotify);
}
//************************************************************************************
TcpSocketImpl::TcpSocketImpl(BaseSocket* pBkRef) : m_pRefServSocket(nullptr), m_bCloseReq(false), m_sClientPort(0), m_sIFacePort(0), m_bSelfDelete(false)
{
atomic_init(&m_atInBytes, static_cast<size_t>(0));
atomic_init(&m_atOutBytes, static_cast<size_t>(0));
m_pBkRef = pBkRef;
}
TcpSocketImpl::TcpSocketImpl(BaseSocket* pBkRef, TcpSocketImpl* pTcpSocketImpl) : BaseSocketImpl(pTcpSocketImpl), m_pRefServSocket(pTcpSocketImpl->m_pRefServSocket), m_bCloseReq(pTcpSocketImpl->m_bCloseReq), m_bSelfDelete(pTcpSocketImpl->m_bSelfDelete)
{
pTcpSocketImpl->m_pRefServSocket = nullptr;
atomic_init(&m_atInBytes, static_cast<size_t>(0));
atomic_init(&m_atOutBytes, static_cast<size_t>(0));
pTcpSocketImpl->m_mxInDeque.lock();
swap(m_quInData, pTcpSocketImpl->m_quInData);
m_atInBytes.exchange(pTcpSocketImpl->m_atInBytes);
swap(m_fBytesReceived, pTcpSocketImpl->m_fBytesReceived);
swap(m_fBytesReceivedParam, pTcpSocketImpl->m_fBytesReceivedParam);
pTcpSocketImpl->m_mxInDeque.unlock();
pTcpSocketImpl->m_mxOutDeque.lock();
swap(m_quOutData, pTcpSocketImpl->m_quOutData);
m_atOutBytes.exchange(pTcpSocketImpl->m_atOutBytes);
pTcpSocketImpl->m_mxOutDeque.unlock();
swap(m_strClientAddr, pTcpSocketImpl->m_strClientAddr);
swap(m_sClientPort, pTcpSocketImpl->m_sClientPort);
swap(m_strIFaceAddr, pTcpSocketImpl->m_strIFaceAddr);
swap(m_sIFacePort, pTcpSocketImpl->m_sIFacePort);
swap(m_fClientConnected, pTcpSocketImpl->m_fClientConnected);
swap(m_fClientConnectedParam, pTcpSocketImpl->m_fClientConnectedParam);
swap(m_fClientConnectedSsl, pTcpSocketImpl->m_fClientConnectedSsl);
m_iShutDownState = 7;
m_thWrite = thread(&TcpSocketImpl::WriteThread, this);
m_pBkRef = pBkRef;
}
TcpSocketImpl::~TcpSocketImpl()
{
//OutputDebugString(L"TcpSocketImpl::~TcpSocketImpl\r\n");
m_bStop = true; // Stops the listening thread
const bool bIsLocked = m_mxWrite.try_lock();
m_bCloseReq = true;
m_atOutBytes = 0;
m_cv.notify_all();
if (bIsLocked == true)
m_mxWrite.unlock();
if (m_thConnect.joinable() == true)
m_thConnect.join();
if (m_fSock != INVALID_SOCKET)
{
::closesocket(m_fSock);
m_fSock = INVALID_SOCKET;
StartClosingCB();
}
}
bool TcpSocketImpl::Connect(const char* const szIpToWhere, const uint16_t sPort, const int AddrHint/* = AF_UNSPEC*/)
{
if (m_fSock != INVALID_SOCKET)
{
::closesocket(m_fSock);
m_fSock = INVALID_SOCKET;
}
struct addrinfo* lstAddr{}, hint{};
hint.ai_family = AddrHint;
hint.ai_socktype = SOCK_STREAM;
if (::getaddrinfo(szIpToWhere, to_string(sPort).c_str(), &hint, &lstAddr) != 0)
return false;
bool bRet = true;
try
{
m_fSock = ::socket(lstAddr->ai_family, lstAddr->ai_socktype, lstAddr->ai_protocol);
if (m_fSock == INVALID_SOCKET)
throw WSAGetLastError();
SetSocketOption(m_fSock);
if (lstAddr->ai_family == AF_INET6)
{
constexpr uint32_t on = 0;
if (::setsockopt(m_fSock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char*>(&on), sizeof(on)) == -1)
throw WSAGetLastError();
}
const int rc = ::connect(m_fSock, lstAddr->ai_addr, static_cast<int>(lstAddr->ai_addrlen));
if (rc == SOCKET_ERROR)
{
m_iError = WSAGetLastError();
#if defined (_WIN32) || defined (_WIN64)
if (m_iError != WSAEWOULDBLOCK)
#else
if (m_iError != EINPROGRESS)
#endif
throw m_iError;
m_iError = 0;
m_thConnect = thread(&TcpSocketImpl::ConnectThread, this);
}
else
{
GetConnectionInfo();
m_thListen = thread(&TcpSocketImpl::SelectThread, this);
m_thWrite = thread(&TcpSocketImpl::WriteThread, this);
TcpSocket* pTcpSocket = dynamic_cast<TcpSocket*>(m_pBkRef);
if (m_fClientConnectedParam && pTcpSocket != nullptr)
m_fClientConnectedParam(pTcpSocket, m_pvUserData);
else if (m_fClientConnected && pTcpSocket != nullptr)
m_fClientConnected(pTcpSocket);
if (m_fClientConnectedSsl)
m_fClientConnectedSsl(nullptr);
}
}
catch (const int iSocketErr)
{
m_iError = iSocketErr;
m_iErrLoc = 1;
if (m_fSock != INVALID_SOCKET)
{
::closesocket(m_fSock);
m_fSock = INVALID_SOCKET;
}
bRet = false;
}
::freeaddrinfo(lstAddr);
return bRet;
}
void TcpSocketImpl::SetSocketOption(const SOCKET& fd)
{
BaseSocketImpl::SetSocketOption(fd);
constexpr SOCKOPT rc = 1;
if (::setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &rc, sizeof(rc)) == -1)
throw WSAGetLastError();
uint32_t nSize = 0x100000;
constexpr int iLen = sizeof(nSize);
if (::setsockopt(m_fSock, SOL_SOCKET, SO_SNDBUF, reinterpret_cast<char*>(&nSize), iLen) == -1)
throw WSAGetLastError();
nSize = 0x100000;
if (::setsockopt(m_fSock, SOL_SOCKET, SO_RCVBUF, reinterpret_cast<char*>(&nSize), iLen) == -1)
throw WSAGetLastError();
}
size_t TcpSocketImpl::Read(void* buf, size_t len)
{
if (m_atInBytes == 0 || buf == nullptr || len == 0)
return 0;
size_t nOffset = 0;
size_t nRet = 0;
NextFromQue:
m_mxInDeque.lock();
DATA data = move(m_quInData.front());
m_quInData.pop_front();
m_mxInDeque.unlock();
// Copy the data into the destination buffer
const size_t nToCopy = min(BUFLEN(data), len);
copy_n(&BUFFER(data)[0], nToCopy, &static_cast<uint8_t*>(buf)[nOffset]);
m_atInBytes -= nToCopy;
nRet += nToCopy;
if (nToCopy < BUFLEN(data))
{ // Put the Rest of the Data back to the Que
size_t nRest = BUFLEN(data) - nToCopy;
auto tmp = make_unique<uint8_t[]>(nRest);
copy_n(&BUFFER(data)[nToCopy], nToCopy + nRest, &tmp[0]);
m_mxInDeque.lock();
m_quInData.emplace_front(move(tmp), nRest);
m_mxInDeque.unlock();
}
else if (m_quInData.size() > 0 && len > nToCopy)
{
len -= nToCopy;
nOffset += nToCopy;
goto NextFromQue;
}
return nRet;
}
size_t TcpSocketImpl::PutBackRead(void* buf, size_t len)
{
if (buf == nullptr || len == 0)
return 0;
auto tmp = make_unique<uint8_t[]>(len);
copy_n(&static_cast<const uint8_t*>(buf)[0], len, &tmp[0]);
m_mxInDeque.lock();
m_quInData.emplace_front(move(tmp), len);
m_atInBytes += len;
m_mxInDeque.unlock();
return len;
}
void TcpSocketImpl::TriggerWriteThread()
{
unique_lock<mutex> lock(m_mxWrite);
m_cv.notify_all();
}
size_t TcpSocketImpl::Write(const void* buf, size_t len)
{
if (m_bStop == true || m_bCloseReq == true || buf == nullptr || len == 0)
return 0;
if (s_fTrafficDebug != nullptr)
s_fTrafficDebug(static_cast<uint16_t>(m_fSock), static_cast<const char*>(buf), len, true);
if (m_fnSslInitDone != nullptr && m_fnSslInitDone() != 1)
{
auto tmp = make_unique<uint8_t[]>(len);
copy_n(&static_cast<const uint8_t*>(buf)[0], len, &tmp[0]);
lock_guard<mutex> lock(m_mxOutDeque);
m_quTmpOutData.emplace_back(move(tmp), len);
return len;
}
int iRet = 0;
if (m_fnSslEncode == nullptr || (iRet = m_fnSslEncode(reinterpret_cast<const uint8_t*>(buf), len), iRet == 0))
{
auto tmp = make_unique<uint8_t[]>(len);
copy_n(&static_cast<const uint8_t*>(buf)[0], len, &tmp[0]);
m_mxOutDeque.lock();
m_atOutBytes += len;
m_quOutData.emplace_back(move(tmp), len);
m_mxOutDeque.unlock();
iRet = 1; // Trigger WriteThread
}
if (iRet > 0)
TriggerWriteThread();
return len;
}
void TcpSocketImpl::WriteThread()
{
m_iShutDownState &= static_cast<uint8_t>(~2);
unique_lock<mutex> lock(m_mxWrite);
while (m_bCloseReq == false || m_atOutBytes != 0)
{
if (m_bCloseReq == false && m_atOutBytes == 0)
m_cv.wait(lock, [&]() noexcept { return m_atOutBytes == 0 ? m_bCloseReq : true; });
if (m_fSock == INVALID_SOCKET)
break;
if (m_atOutBytes != 0)
{
fd_set writefd{}, errorfd{};
struct timeval timeout{};
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&writefd);
FD_ZERO(&errorfd);
FD_SET(m_fSock, &writefd);
FD_SET(m_fSock, &errorfd);
if (::select(static_cast<int>(m_fSock + 1), nullptr, &writefd, &errorfd, &timeout) == 0)
{
if (m_bCloseReq == false) continue;
break;
}
if (FD_ISSET(m_fSock, &errorfd))
{
if (m_iError == 0)
{
socklen_t iLen = sizeof(m_iError);
getsockopt(m_fSock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&m_iError), &iLen);
m_iErrLoc = 2;
lock.unlock();
thread thErrorCb([&]()
{
if (m_fErrorParam && m_bStop == false)
m_fErrorParam(m_pBkRef, m_pvUserData);
else if (m_fError && m_bStop == false)
m_fError(m_pBkRef);
});
thErrorCb.join();
lock.lock();
}
break;
}
m_mxOutDeque.lock();
if (m_quOutData.size() == 0)
{
m_atOutBytes = 0;
m_mxOutDeque.unlock();
continue;
}
DATA data = move(m_quOutData.front());
m_quOutData.pop_front();
m_atOutBytes -= BUFLEN(data);
m_mxOutDeque.unlock();
const uint32_t transferred = ::send(m_fSock, reinterpret_cast<char*>(&BUFFER(data)[0]), static_cast<int>(BUFLEN(data)), 0);
if (static_cast<int32_t>(transferred) <= 0)
{
const int iError = WSAGetLastError();
if (iError != WSAEWOULDBLOCK)
{
m_iError = iError;
m_iErrLoc = 3;
lock.unlock();
thread thErrorCb([&]()
{
if (m_fErrorParam && m_bStop == false)
m_fErrorParam(m_pBkRef, m_pvUserData);
else if (m_fError && m_bStop == false)
m_fError(m_pBkRef);
});
thErrorCb.join();
lock.lock();
break;
}
// Put the not send bytes back into the que if it is not a SSL connection. A SSL connection has the bytes still available
auto tmp = make_unique<uint8_t[]>(BUFLEN(data));
copy_n(&BUFFER(data)[0], BUFLEN(data), &tmp[0]);
m_mxOutDeque.lock();
m_atOutBytes += BUFLEN(data);
m_quOutData.emplace_front(move(tmp), BUFLEN(data));
m_mxOutDeque.unlock();
}
else if (transferred < BUFLEN(data)) // Less bytes send as buffer size, we put the rast back in your que
{
auto tmp = make_unique<uint8_t[]>(BUFLEN(data) - transferred);
copy_n(&BUFFER(data)[transferred], BUFLEN(data) - transferred, &tmp[0]);
m_mxOutDeque.lock();
m_atOutBytes += (BUFLEN(data) - transferred);
m_quOutData.emplace_front(move(tmp), (BUFLEN(data) - transferred));
m_mxOutDeque.unlock();
}
}
if (m_iError != 0)
break;
}
lock.unlock();
// if we get out of the while loop, the stop request was send or we have an error
if (m_iError == 0 && m_fSock != INVALID_SOCKET)
{
if (::shutdown(m_fSock, SD_SEND) != 0)
{
m_iError = WSAGetLastError();// OutputDebugString(L"Error shutdown socket\r\n");
m_iErrLoc = 4;
}
}
m_iShutDownState |= 2;
unsigned char cExpected = 7;
if (m_iShutDownState.compare_exchange_strong(cExpected, 15) == true)
{
if (m_fSock != INVALID_SOCKET)
{
::closesocket(m_fSock);
m_fSock = INVALID_SOCKET;
}
StartClosingCB();
if (m_pRefServSocket != nullptr || m_bSelfDelete == true) // Auto-delete, socket created from server socket
Delete();// thread([&]() { delete this; }).detach();
}
}
void TcpSocketImpl::StartReceiving()
{
m_thListen = thread(&TcpSocketImpl::SelectThread, this);
}
void TcpSocketImpl::Close()
{
//OutputDebugString(L"TcpSocketImpl::Close\r\n");
m_bCloseReq = true; // Stops the write thread after the last byte was send
do
{
const bool bIsLocked = m_mxWrite.try_lock();
m_cv.notify_all();
if (bIsLocked == true)
m_mxWrite.unlock();
} while ((m_iShutDownState & 2) == 0 && m_iError == 0); // Wait until the write thread is finished
m_bStop = true; // Stops the listening thread
if (m_pRefServSocket == nullptr && m_iShutDownState == 15 && (m_fClosing || m_fClosingParam) && m_thClose.joinable() == false)
{
m_thClose = thread([&]() {
StartClosingCB();
});
while (m_fClosingParam != nullptr || m_fClosing != nullptr)
this_thread::sleep_for(chrono::milliseconds(1));
}
}
void TcpSocketImpl::SelfDestroy()
{
m_bSelfDelete = true;
m_pBkRef = nullptr;
Close();
}
void TcpSocketImpl::Delete()
{
thread([&]()
{
if (m_pBkRef == nullptr)
{
delete this;
return;
}
TcpSocket* pSock = dynamic_cast<TcpSocket*>(m_pBkRef);
lock_guard<mutex> lock(s_mxClientSocket);
auto it = find_if(begin(s_lstClientSocket), end(s_lstClientSocket), [&](auto& item) noexcept { return item.get() == pSock; });
if (it != end(s_lstClientSocket))
s_lstClientSocket.erase(it);
else
delete pSock;
}).detach();
}
size_t TcpSocketImpl::GetBytesAvailable() const noexcept
{
return m_atInBytes;
}
size_t TcpSocketImpl::GetOutBytesInQue() const noexcept
{
return m_atOutBytes;
}
function<void(TcpSocket*)> TcpSocketImpl::BindFuncBytesReceived(function<void(TcpSocket*)> fBytesReceived) noexcept
{
m_fBytesReceived.swap(fBytesReceived);
return fBytesReceived;
}
function<void(TcpSocket*, void*)> TcpSocketImpl::BindFuncBytesReceived(function<void(TcpSocket*, void*)> fBytesReceived) noexcept
{
m_fBytesReceivedParam.swap(fBytesReceived);
return fBytesReceived;
}
function<void(TcpSocket*)> TcpSocketImpl::BindFuncConEstablished(function<void(TcpSocket*)> fClientConnected) noexcept
{
m_fClientConnected.swap(fClientConnected);
return fClientConnected;
}
function<void(TcpSocket*, void*)> TcpSocketImpl::BindFuncConEstablished(function<void(TcpSocket*, void*)> fClientConnected) noexcept
{
m_fClientConnectedParam.swap(fClientConnected);
return fClientConnected;
}
void TcpSocketImpl::BindFuncConEstablished(function<void(TcpSocketImpl*)> fClientConnected) noexcept
{
m_fClientConnectedSsl.swap(fClientConnected);
}
void TcpSocketImpl::SelectThread()
{
m_iShutDownState &= static_cast<uint8_t>(~1);
bool bReadCall = false;
mutex mxNotify;
bool bSocketShutDown = false;
auto buf = make_unique<char[]>(0x0000ffff);
while (m_bStop == false)
{
if (m_atInBytes > 0x80000) // More than 512 KB in the receive buffer
{
this_thread::sleep_for(chrono::milliseconds(1));
continue;
}
fd_set readfd{}, errorfd{};
struct timeval timeout{};
timeout.tv_sec = 2;
timeout.tv_usec = 0;
FD_ZERO(&readfd);
FD_ZERO(&errorfd);
FD_SET(m_fSock, &readfd);
FD_SET(m_fSock, &errorfd);
if (::select(static_cast<int>(m_fSock + 1), &readfd, nullptr, &errorfd, &timeout) > 0)
{
if (FD_ISSET(m_fSock, &errorfd))
{
socklen_t iLen = sizeof(m_iError);
getsockopt(m_fSock, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&m_iError), &iLen);
m_iErrLoc = 5;
if (m_fErrorParam && m_bStop == false)
m_fErrorParam(m_pBkRef, m_pvUserData);
else if (m_fError && m_bStop == false)
m_fError(m_pBkRef);
break;
}
if (FD_ISSET(m_fSock, &readfd))
{
do
{
int32_t transferred = ::recv(m_fSock, &buf[0], 0x0000ffff, 0);
if (transferred <= 0)
{