-
Notifications
You must be signed in to change notification settings - Fork 821
/
api.cpp
3127 lines (2713 loc) · 82.5 KB
/
api.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
/*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2018 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
/*****************************************************************************
Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
nor the names of its contributors may be used to
endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 07/09/2011
modified by
Haivision Systems Inc.
*****************************************************************************/
#include <exception>
#include <stdexcept>
#include <typeinfo>
#include <iterator>
#include <cstring>
#include "platform_sys.h"
#include "api.h"
#include "core.h"
#include "logging.h"
#include "threadname.h"
#include "srt.h"
#ifdef WIN32
#include <win/wintime.h>
#endif
using namespace std;
extern logging::LogConfig srt_logger_config;
extern logging::Logger mglog;
CUDTSocket::CUDTSocket():
m_Status(SRTS_INIT),
m_TimeStamp(0),
m_iIPversion(0),
m_pSelfAddr(NULL),
m_pPeerAddr(NULL),
m_SocketID(0),
m_ListenSocket(0),
m_PeerID(0),
m_iISN(0),
m_pUDT(NULL),
m_pQueuedSockets(NULL),
m_pAcceptSockets(NULL),
m_AcceptCond(),
m_AcceptLock(),
m_uiBackLog(0),
m_iMuxID(-1)
{
pthread_mutex_init(&m_AcceptLock, NULL);
pthread_cond_init(&m_AcceptCond, NULL);
pthread_mutex_init(&m_ControlLock, NULL);
}
CUDTSocket::~CUDTSocket()
{
if (m_iIPversion == AF_INET)
{
delete (sockaddr_in*)m_pSelfAddr;
delete (sockaddr_in*)m_pPeerAddr;
}
else
{
delete (sockaddr_in6*)m_pSelfAddr;
delete (sockaddr_in6*)m_pPeerAddr;
}
delete m_pUDT;
m_pUDT = NULL;
delete m_pQueuedSockets;
delete m_pAcceptSockets;
pthread_mutex_destroy(&m_AcceptLock);
pthread_cond_destroy(&m_AcceptCond);
pthread_mutex_destroy(&m_ControlLock);
}
////////////////////////////////////////////////////////////////////////////////
CUDTUnited::CUDTUnited():
m_Sockets(),
m_ControlLock(),
m_IDLock(),
m_SocketIDGenerator(0),
m_TLSError(),
m_mMultiplexer(),
m_MultiplexerLock(),
m_pCache(NULL),
m_bClosing(false),
m_GCStopLock(),
m_GCStopCond(),
m_InitLock(),
m_iInstanceCount(0),
m_bGCStatus(false),
m_GCThread(),
m_ClosedSockets()
{
// Socket ID MUST start from a random value
srand((unsigned int)CTimer::getTime());
m_SocketIDGenerator = 1 + (int)((1 << 30) * (double(rand()) / RAND_MAX));
pthread_mutex_init(&m_ControlLock, NULL);
pthread_mutex_init(&m_IDLock, NULL);
pthread_mutex_init(&m_InitLock, NULL);
pthread_key_create(&m_TLSError, TLSDestroy);
m_pCache = new CCache<CInfoBlock>;
}
CUDTUnited::~CUDTUnited()
{
// Call it if it wasn't called already.
// This will happen at the end of main() of the application,
// when the user didn't call srt_cleanup().
if (m_bGCStatus)
{
cleanup();
}
pthread_mutex_destroy(&m_ControlLock);
pthread_mutex_destroy(&m_IDLock);
pthread_mutex_destroy(&m_InitLock);
pthread_key_delete(m_TLSError);
delete m_pCache;
}
std::string CUDTUnited::CONID(SRTSOCKET sock) const
{
if ( sock == 0 )
return "";
std::ostringstream os;
os << "%" << sock << ":";
return os.str();
}
int CUDTUnited::startup()
{
CGuard gcinit(m_InitLock);
if (m_iInstanceCount++ > 0)
return 0;
// Global initialization code
#ifdef WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
if (0 != WSAStartup(wVersionRequested, &wsaData))
throw CUDTException(MJ_SETUP, MN_NONE, WSAGetLastError());
#endif
//init CTimer::EventLock
if (m_bGCStatus)
return true;
m_bClosing = false;
pthread_mutex_init(&m_GCStopLock, NULL);
pthread_cond_init(&m_GCStopCond, NULL);
{
ThreadName tn("SRT:GC");
pthread_create(&m_GCThread, NULL, garbageCollect, this);
}
m_bGCStatus = true;
return 0;
}
int CUDTUnited::cleanup()
{
CGuard gcinit(m_InitLock);
if (--m_iInstanceCount > 0)
return 0;
//destroy CTimer::EventLock
if (!m_bGCStatus)
return 0;
m_bClosing = true;
pthread_cond_signal(&m_GCStopCond);
pthread_join(m_GCThread, NULL);
// XXX There's some weird bug here causing this
// to hangup on Windows. This might be either something
// bigger, or some problem in pthread-win32. As this is
// the application cleanup section, this can be temporarily
// tolerated with simply exit the application without cleanup,
// counting on that the system will take care of it anyway.
#ifndef WIN32
pthread_mutex_destroy(&m_GCStopLock);
pthread_cond_destroy(&m_GCStopCond);
#endif
m_bGCStatus = false;
// Global destruction code
#ifdef WIN32
WSACleanup();
#endif
return 0;
}
SRTSOCKET CUDTUnited::newSocket(int af, int)
{
CUDTSocket* ns = NULL;
try
{
// XXX REFACTOR:
// Use sockaddr_any for m_pSelfAddr and just initialize it
// with 'af'.
ns = new CUDTSocket;
ns->m_pUDT = new CUDT;
if (af == AF_INET)
{
ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in);
((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0;
}
else
{
ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6);
((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0;
}
}
catch (...)
{
delete ns;
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
}
CGuard::enterCS(m_IDLock);
ns->m_SocketID = -- m_SocketIDGenerator;
CGuard::leaveCS(m_IDLock);
ns->m_Status = SRTS_INIT;
ns->m_ListenSocket = 0;
ns->m_pUDT->m_SocketID = ns->m_SocketID;
// The "Socket type" is deprecated. For the sake of
// HSv4 there will be only a "socket type" field set
// in the handshake, always to UDT_DGRAM.
//ns->m_pUDT->m_iSockType = (type == SOCK_STREAM) ? UDT_STREAM : UDT_DGRAM;
ns->m_pUDT->m_iSockType = UDT_DGRAM;
ns->m_pUDT->m_iIPversion = ns->m_iIPversion = af;
ns->m_pUDT->m_pCache = m_pCache;
// protect the m_Sockets structure.
CGuard::enterCS(m_ControlLock);
try
{
HLOGC(mglog.Debug, log << CONID(ns->m_SocketID)
<< "newSocket: mapping socket "
<< ns->m_SocketID);
m_Sockets[ns->m_SocketID] = ns;
}
catch (...)
{
//failure and rollback
CGuard::leaveCS(m_ControlLock);
delete ns;
ns = NULL;
}
CGuard::leaveCS(m_ControlLock);
if (!ns)
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
return ns->m_SocketID;
}
int CUDTUnited::newConnection(const SRTSOCKET listen, const sockaddr* peer, CHandShake* hs, const CPacket& hspkt)
{
CUDTSocket* ns = NULL;
// Can't manage this error through an exception because this is
// running in the listener loop.
CUDTSocket* ls = locate(listen);
if (!ls)
{
LOGC(mglog.Error, log << "IPE: newConnection by listener socket id=" << listen << " which DOES NOT EXIST.");
return -1;
}
// if this connection has already been processed
if ((ns = locate(peer, hs->m_iID, hs->m_iISN)) != NULL)
{
if (ns->m_pUDT->m_bBroken)
{
// last connection from the "peer" address has been broken
ns->m_Status = SRTS_CLOSED;
ns->m_TimeStamp = CTimer::getTime();
CGuard::enterCS(ls->m_AcceptLock);
ls->m_pQueuedSockets->erase(ns->m_SocketID);
ls->m_pAcceptSockets->erase(ns->m_SocketID);
CGuard::leaveCS(ls->m_AcceptLock);
}
else
{
// connection already exist, this is a repeated connection request
// respond with existing HS information
hs->m_iISN = ns->m_pUDT->m_iISN;
hs->m_iMSS = ns->m_pUDT->m_iMSS;
hs->m_iFlightFlagSize = ns->m_pUDT->m_iFlightFlagSize;
hs->m_iReqType = URQ_CONCLUSION;
hs->m_iID = ns->m_SocketID;
return 0;
//except for this situation a new connection should be started
}
}
// exceeding backlog, refuse the connection request
if (ls->m_pQueuedSockets->size() >= ls->m_uiBackLog)
{
LOGC(mglog.Error, log << "newConnection: listen backlog=" << ls->m_uiBackLog << " EXCEEDED");
return -1;
}
try
{
ns = new CUDTSocket;
ns->m_pUDT = new CUDT(*(ls->m_pUDT));
if (ls->m_iIPversion == AF_INET)
{
ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in);
((sockaddr_in*)(ns->m_pSelfAddr))->sin_port = 0;
ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in);
memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in));
}
else
{
ns->m_pSelfAddr = (sockaddr*)(new sockaddr_in6);
((sockaddr_in6*)(ns->m_pSelfAddr))->sin6_port = 0;
ns->m_pPeerAddr = (sockaddr*)(new sockaddr_in6);
memcpy(ns->m_pPeerAddr, peer, sizeof(sockaddr_in6));
}
}
catch (...)
{
delete ns;
LOGC(mglog.Error, log << "IPE: newConnection: unexpected exception (probably std::bad_alloc)");
return -1;
}
CGuard::enterCS(m_IDLock);
ns->m_SocketID = -- m_SocketIDGenerator;
HLOGF(mglog.Debug, "newConnection: generated socket id %d", ns->m_SocketID);
CGuard::leaveCS(m_IDLock);
ns->m_ListenSocket = listen;
ns->m_iIPversion = ls->m_iIPversion;
ns->m_pUDT->m_SocketID = ns->m_SocketID;
ns->m_PeerID = hs->m_iID;
ns->m_iISN = hs->m_iISN;
int error = 0;
// These can throw exception only when the memory allocation failed.
// CUDT::connect() translates exception into CUDTException.
// CUDT::open() may only throw original std::bad_alloc from new.
// This is only to make the library extra safe (when your machine lacks
// memory, it will continue to work, but fail to accept connection).
try
{
// This assignment must happen b4 the call to CUDT::connect() because
// this call causes sending the SRT Handshake through this socket.
// Without this mapping the socket cannot be found and therefore
// the SRT Handshake message would fail.
HLOGF(mglog.Debug,
"newConnection: incoming %s, mapping socket %d",
SockaddrToString(peer).c_str(), ns->m_SocketID);
{
CGuard cg(m_ControlLock);
m_Sockets[ns->m_SocketID] = ns;
}
// bind to the same addr of listening socket
ns->m_pUDT->open();
updateListenerMux(ns, ls);
ns->m_pUDT->acceptAndRespond(peer, hs, hspkt);
}
catch (...)
{
// The mapped socket should be now unmapped to preserve the situation that
// was in the original UDT code.
// In SRT additionally the acceptAndRespond() function (it was called probably
// connect() in UDT code) may fail, in which case this socket should not be
// further processed and should be removed.
{
CGuard cg(m_ControlLock);
m_Sockets.erase(ns->m_SocketID);
}
error = 1;
goto ERR_ROLLBACK;
}
ns->m_Status = SRTS_CONNECTED;
// copy address information of local node
ns->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(ns->m_pSelfAddr);
CIPAddress::pton(ns->m_pSelfAddr, ns->m_pUDT->m_piSelfIP, ns->m_iIPversion);
// protect the m_Sockets structure.
CGuard::enterCS(m_ControlLock);
try
{
HLOGF(mglog.Debug,
"newConnection: mapping peer %d to that socket (%d)\n",
ns->m_PeerID, ns->m_SocketID);
m_PeerRec[ns->getPeerSpec()].insert(ns->m_SocketID);
}
catch (...)
{
error = 2;
}
CGuard::leaveCS(m_ControlLock);
CGuard::enterCS(ls->m_AcceptLock);
try
{
ls->m_pQueuedSockets->insert(ns->m_SocketID);
}
catch (...)
{
error = 3;
}
CGuard::leaveCS(ls->m_AcceptLock);
// acknowledge users waiting for new connections on the listening socket
m_EPoll.update_events(listen, ls->m_pUDT->m_sPollID, UDT_EPOLL_IN, true);
CTimer::triggerEvent();
ERR_ROLLBACK:
// XXX the exact value of 'error' is ignored
if (error > 0)
{
#if ENABLE_LOGGING
static const char* why [] = {"?", "ACCEPT ERROR", "IPE when mapping a socket", "IPE when inserting a socket" };
LOGC(mglog.Error, log << CONID(ns->m_SocketID) << "newConnection: connection rejected due to: " << why[error]);
#endif
ns->m_pUDT->close();
ns->m_Status = SRTS_CLOSED;
ns->m_TimeStamp = CTimer::getTime();
return -1;
}
// wake up a waiting accept() call
pthread_mutex_lock(&(ls->m_AcceptLock));
pthread_cond_signal(&(ls->m_AcceptCond));
pthread_mutex_unlock(&(ls->m_AcceptLock));
return 1;
}
CUDT* CUDTUnited::lookup(const SRTSOCKET u)
{
// protects the m_Sockets structure
CGuard cg(m_ControlLock);
map<SRTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u);
if ((i == m_Sockets.end()) || (i->second->m_Status == SRTS_CLOSED))
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
return i->second->m_pUDT;
}
SRT_SOCKSTATUS CUDTUnited::getStatus(const SRTSOCKET u)
{
// protects the m_Sockets structure
CGuard cg(m_ControlLock);
map<SRTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u);
if (i == m_Sockets.end())
{
if (m_ClosedSockets.find(u) != m_ClosedSockets.end())
return SRTS_CLOSED;
return SRTS_NONEXIST;
}
CUDTSocket* s = i->second;
if (s->m_pUDT->m_bBroken)
return SRTS_BROKEN;
// Connecting timed out
if ((s->m_Status == SRTS_CONNECTING) && !s->m_pUDT->m_bConnecting)
return SRTS_BROKEN;
return s->m_Status;
}
int CUDTUnited::bind(const SRTSOCKET u, const sockaddr* name, int namelen)
{
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CGuard cg(s->m_ControlLock);
// cannot bind a socket more than once
if (s->m_Status != SRTS_INIT)
throw CUDTException(MJ_NOTSUP, MN_NONE, 0);
// check the size of SOCKADDR structure
if (s->m_iIPversion == AF_INET)
{
if (namelen != sizeof(sockaddr_in))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
else
{
if (namelen != sizeof(sockaddr_in6))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
s->m_pUDT->open();
updateMux(s, name);
s->m_Status = SRTS_OPENED;
// copy address information of local node
s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr);
return 0;
}
int CUDTUnited::bind(SRTSOCKET u, UDPSOCKET udpsock)
{
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CGuard cg(s->m_ControlLock);
// cannot bind a socket more than once
if (s->m_Status != SRTS_INIT)
throw CUDTException(MJ_NOTSUP, MN_NONE, 0);
sockaddr_in name4;
sockaddr_in6 name6;
sockaddr* name;
socklen_t namelen;
if (s->m_iIPversion == AF_INET)
{
namelen = sizeof(sockaddr_in);
name = (sockaddr*)&name4;
}
else
{
namelen = sizeof(sockaddr_in6);
name = (sockaddr*)&name6;
}
if (::getsockname(udpsock, name, &namelen) == -1)
throw CUDTException(MJ_NOTSUP, MN_INVAL);
s->m_pUDT->open();
updateMux(s, name, &udpsock);
s->m_Status = SRTS_OPENED;
// copy address information of local node
s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr);
return 0;
}
int CUDTUnited::listen(const SRTSOCKET u, int backlog)
{
if (backlog <= 0)
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
// Don't search for the socket if it's already -1;
// this never is a valid socket.
if (u == UDT::INVALID_SOCK)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CGuard cg(s->m_ControlLock);
// NOTE: since now the socket is protected against simultaneous access.
// In the meantime the socket might have been closed, which means that
// it could have changed the state. It could be also set listen in another
// thread, so check it out.
// do nothing if the socket is already listening
if (s->m_Status == SRTS_LISTENING)
return 0;
// a socket can listen only if is in OPENED status
if (s->m_Status != SRTS_OPENED)
throw CUDTException(MJ_NOTSUP, MN_ISUNBOUND, 0);
// [[using assert(s->m_Status == OPENED)]];
// listen is not supported in rendezvous connection setup
if (s->m_pUDT->m_bRendezvous)
throw CUDTException(MJ_NOTSUP, MN_ISRENDEZVOUS, 0);
s->m_uiBackLog = backlog;
try
{
s->m_pQueuedSockets = new set<SRTSOCKET>;
s->m_pAcceptSockets = new set<SRTSOCKET>;
}
catch (...)
{
delete s->m_pQueuedSockets;
delete s->m_pAcceptSockets;
// XXX Translated std::bad_alloc into CUDTException specifying
// memory allocation failure...
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
}
// [[using assert(s->m_Status == OPENED)]]; // (still, unchanged)
s->m_pUDT->setListenState(); // propagates CUDTException,
// if thrown, remains in OPENED state if so.
s->m_Status = SRTS_LISTENING;
return 0;
}
SRTSOCKET CUDTUnited::accept(const SRTSOCKET listen, sockaddr* addr, int* addrlen)
{
if ((addr) && (!addrlen))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
CUDTSocket* ls = locate(listen);
if (ls == NULL)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
// the "listen" socket must be in LISTENING status
if (ls->m_Status != SRTS_LISTENING)
throw CUDTException(MJ_NOTSUP, MN_NOLISTEN, 0);
// no "accept" in rendezvous connection setup
if (ls->m_pUDT->m_bRendezvous)
throw CUDTException(MJ_NOTSUP, MN_ISRENDEZVOUS, 0);
SRTSOCKET u = CUDT::INVALID_SOCK;
bool accepted = false;
// !!only one conection can be set up each time!!
while (!accepted)
{
CGuard cg(ls->m_AcceptLock);
if ((ls->m_Status != SRTS_LISTENING) || ls->m_pUDT->m_bBroken)
{
// This socket has been closed.
accepted = true;
}
else if (ls->m_pQueuedSockets->size() > 0)
{
// XXX REFACTORING REQUIRED HERE!
// Actually this should at best be something like that:
// set<SRTSOCKET>::iterator b = ls->m_pQueuedSockets->begin();
// u = *b;
// ls->m_pQueuedSockets->erase(b);
// ls->m_pAcceptSockets->insert(u);
//
// It is also questionable why m_pQueuedSockets should be of type 'set'.
// There's no quick-searching capabilities of that container used anywhere except
// checkBrokenSockets and garbageCollect, which aren't performance-critical,
// whereas it's mainly used for getting the first element and iterating
// over elements, which is slow in case of std::set. It's also doubtful
// as to whether the sorting capability of std::set is properly used;
// the first is taken here, which is actually the socket with lowest
// possible descriptor value (as default operator< and ascending sorting
// used for std::set<SRTSOCKET> where SRTSOCKET=int).
//
// Consider using std::list or std::vector here.
u = *(ls->m_pQueuedSockets->begin());
ls->m_pAcceptSockets->insert(ls->m_pAcceptSockets->end(), u);
ls->m_pQueuedSockets->erase(ls->m_pQueuedSockets->begin());
accepted = true;
}
else if (!ls->m_pUDT->m_bSynRecving)
{
accepted = true;
}
if (!accepted && (ls->m_Status == SRTS_LISTENING))
pthread_cond_wait(&(ls->m_AcceptCond), &(ls->m_AcceptLock));
if (ls->m_pQueuedSockets->empty())
m_EPoll.update_events(listen, ls->m_pUDT->m_sPollID, UDT_EPOLL_IN, false);
}
if (u == CUDT::INVALID_SOCK)
{
// non-blocking receiving, no connection available
if (!ls->m_pUDT->m_bSynRecving)
throw CUDTException(MJ_AGAIN, MN_RDAVAIL, 0);
// listening socket is closed
throw CUDTException(MJ_NOTSUP, MN_NOLISTEN, 0);
}
if ((addr != NULL) && (addrlen != NULL))
{
CUDTSocket* s = locate(u);
if (s == NULL)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CGuard cg(s->m_ControlLock);
if (AF_INET == s->m_iIPversion)
*addrlen = sizeof(sockaddr_in);
else
*addrlen = sizeof(sockaddr_in6);
// copy address information of peer node
memcpy(addr, s->m_pPeerAddr, *addrlen);
}
return u;
}
int CUDTUnited::connect(const SRTSOCKET u, const sockaddr* name, int namelen, int32_t forced_isn)
{
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
CGuard cg(s->m_ControlLock);
// XXX Consider translating this to using sockaddr_any,
// this should take out all the "IP version check" things.
if (AF_INET == s->m_iIPversion)
{
if (namelen != sizeof(sockaddr_in))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
else
{
if (namelen != sizeof(sockaddr_in6))
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
// a socket can "connect" only if it is in INIT or OPENED status
if (s->m_Status == SRTS_INIT)
{
if (!s->m_pUDT->m_bRendezvous)
{
s->m_pUDT->open(); // XXX here use the AF_* family value from 'name'
updateMux(s); // <<---- updateMux
// -> C(Snd|Rcv)Queue::init
// -> pthread_create(...C(Snd|Rcv)Queue::worker...)
s->m_Status = SRTS_OPENED;
}
else
throw CUDTException(MJ_NOTSUP, MN_ISRENDUNBOUND, 0);
}
else if (s->m_Status != SRTS_OPENED)
throw CUDTException(MJ_NOTSUP, MN_ISCONNECTED, 0);
// connect_complete() may be called before connect() returns.
// So we need to update the status before connect() is called,
// otherwise the status may be overwritten with wrong value
// (CONNECTED vs. CONNECTING).
s->m_Status = SRTS_CONNECTING;
/*
* In blocking mode, connect can block for up to 30 seconds for
* rendez-vous mode. Holding the s->m_ControlLock prevent close
* from cancelling the connect
*/
try
{
// InvertedGuard unlocks in the constructor, then locks in the
// destructor, no matter if an exception has fired.
InvertedGuard l_unlocker( s->m_pUDT->m_bSynRecving ? &s->m_ControlLock : 0 );
s->m_pUDT->startConnect(name, forced_isn);
}
catch (CUDTException& e) // Interceptor, just to change the state.
{
s->m_Status = SRTS_OPENED;
throw e;
}
// record peer address
delete s->m_pPeerAddr;
if (AF_INET == s->m_iIPversion)
{
s->m_pPeerAddr = (sockaddr*)(new sockaddr_in);
memcpy(s->m_pPeerAddr, name, sizeof(sockaddr_in));
}
else
{
s->m_pPeerAddr = (sockaddr*)(new sockaddr_in6);
memcpy(s->m_pPeerAddr, name, sizeof(sockaddr_in6));
}
// CGuard destructor will delete cg and unlock s->m_ControlLock
return 0;
}
void CUDTUnited::connect_complete(const SRTSOCKET u)
{
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
// copy address information of local node
// the local port must be correctly assigned BEFORE CUDT::startConnect(),
// otherwise if startConnect() fails, the multiplexer cannot be located
// by garbage collection and will cause leak
s->m_pUDT->m_pSndQueue->m_pChannel->getSockAddr(s->m_pSelfAddr);
CIPAddress::pton(s->m_pSelfAddr, s->m_pUDT->m_piSelfIP, s->m_iIPversion);
s->m_Status = SRTS_CONNECTED;
}
int CUDTUnited::close(const SRTSOCKET u)
{
CUDTSocket* s = locate(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
HLOGC(mglog.Debug, log << s->m_pUDT->CONID() << " CLOSE. Acquiring control lock");
CGuard socket_cg(s->m_ControlLock);
HLOGC(mglog.Debug, log << s->m_pUDT->CONID() << " CLOSING (removing from listening, closing CUDT)");
bool synch_close_snd = s->m_pUDT->m_bSynSending;
//bool synch_close_rcv = s->m_pUDT->m_bSynRecving;
int id = s->m_SocketID;
if (s->m_Status == SRTS_LISTENING)
{
if (s->m_pUDT->m_bBroken)
return 0;
s->m_TimeStamp = CTimer::getTime();
s->m_pUDT->m_bBroken = true;
// Change towards original UDT:
// Leave all the closing activities for garbageCollect to happen,
// however remove the listener from the RcvQueue IMMEDIATELY.
// Even though garbageCollect would eventually remove the listener
// as well, there would be some time interval between now and the
// moment when it's done, and during this time the application will
// be unable to bind to this port that the about-to-delete listener
// is currently occupying (due to blocked slot in the RcvQueue).
HLOGC(mglog.Debug, log << s->m_pUDT->CONID() << " CLOSING (removing listener immediately)");
{
CGuard cg(s->m_pUDT->m_ConnectionLock);
s->m_pUDT->m_bListening = false;
s->m_pUDT->m_pRcvQueue->removeListener(s->m_pUDT);
}
// broadcast all "accept" waiting
pthread_mutex_lock(&(s->m_AcceptLock));
pthread_cond_broadcast(&(s->m_AcceptCond));
pthread_mutex_unlock(&(s->m_AcceptLock));
}
else
{
s->m_pUDT->close();
// synchronize with garbage collection.
HLOGC(mglog.Debug, log << "%" << id << " CUDT::close done. GLOBAL CLOSE: " << s->m_pUDT->CONID() << ". Acquiring GLOBAL control lock");
CGuard manager_cg(m_ControlLock);
// since "s" is located before m_ControlLock, locate it again in case
// it became invalid
map<SRTSOCKET, CUDTSocket*>::iterator i = m_Sockets.find(u);
if ((i == m_Sockets.end()) || (i->second->m_Status == SRTS_CLOSED))
return 0;
s = i->second;
s->m_Status = SRTS_CLOSED;
// a socket will not be immediately removed when it is closed
// in order to prevent other methods from accessing invalid address
// a timer is started and the socket will be removed after approximately
// 1 second
s->m_TimeStamp = CTimer::getTime();
m_Sockets.erase(s->m_SocketID);
m_ClosedSockets.insert(pair<SRTSOCKET, CUDTSocket*>(s->m_SocketID, s));
CTimer::triggerEvent();
}
HLOGC(mglog.Debug, log << "%" << id << ": GLOBAL: CLOSING DONE");
// Check if the ID is still in closed sockets before you access it
// (the last triggerEvent could have deleted it).
if ( synch_close_snd )
{
#if SRT_ENABLE_CLOSE_SYNCH
HLOGC(mglog.Debug, log << "%" << id << " GLOBAL CLOSING: sync-waiting for releasing sender resources...");
for (;;)
{
CSndBuffer* sb = s->m_pUDT->m_pSndBuffer;
// Disconnected from buffer - nothing more to check.
if (!sb)
{
HLOGC(mglog.Debug, log << "%" << id << " GLOBAL CLOSING: sending buffer disconnected. Allowed to close.");
break;
}
// Sender buffer empty
if (sb->getCurrBufSize() == 0)
{
HLOGC(mglog.Debug, log << "%" << id << " GLOBAL CLOSING: sending buffer depleted. Allowed to close.");
break;
}
// Ok, now you are keeping GC thread hands off the internal data.
// You can check then if it has already deleted the socket or not.
// The socket is either in m_ClosedSockets or is already gone.
// Done the other way, but still done. You can stop waiting.
bool isgone = false;
{
CGuard manager_cg(m_ControlLock);
isgone = m_ClosedSockets.count(id) == 0;
}
if (!isgone)
{
isgone = !s->m_pUDT->m_bOpened;