-
Notifications
You must be signed in to change notification settings - Fork 851
/
api.cpp
4812 lines (4159 loc) · 155 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 "platform_sys.h"
#include <exception>
#include <stdexcept>
#include <typeinfo>
#include <iterator>
#include <vector>
#include <cstring>
#include "utilities.h"
#include "netinet_any.h"
#include "api.h"
#include "core.h"
#include "epoll.h"
#include "logging.h"
#include "threadname.h"
#include "srt.h"
#include "udt.h"
#ifdef _WIN32
#include <win/wintime.h>
#endif
#ifdef _MSC_VER
#pragma warning(error : 4530)
#endif
using namespace std;
using namespace srt_logging;
using namespace srt::sync;
void srt::CUDTSocket::construct()
{
#if ENABLE_BONDING
m_GroupOf = NULL;
m_GroupMemberData = NULL;
#endif
setupMutex(m_AcceptLock, "Accept");
setupCond(m_AcceptCond, "Accept");
setupMutex(m_ControlLock, "Control");
}
srt::CUDTSocket::~CUDTSocket()
{
releaseMutex(m_AcceptLock);
releaseCond(m_AcceptCond);
releaseMutex(m_ControlLock);
}
SRT_SOCKSTATUS srt::CUDTSocket::getStatus()
{
// TTL in CRendezvousQueue::updateConnStatus() will set m_bConnecting to false.
// Although m_Status is still SRTS_CONNECTING, the connection is in fact to be closed due to TTL expiry.
// In this case m_bConnected is also false. Both checks are required to avoid hitting
// a regular state transition from CONNECTING to CONNECTED.
if (m_UDT.m_bBroken)
return SRTS_BROKEN;
// Connecting timed out
if ((m_Status == SRTS_CONNECTING) && !m_UDT.m_bConnecting && !m_UDT.m_bConnected)
return SRTS_BROKEN;
return m_Status;
}
// [[using locked(m_GlobControlLock)]]
void srt::CUDTSocket::breakSocket_LOCKED()
{
// This function is intended to be called from GC,
// under a lock of m_GlobControlLock.
m_UDT.m_bBroken = true;
m_UDT.m_iBrokenCounter = 0;
HLOGC(smlog.Debug, log << "@" << m_SocketID << " CLOSING AS SOCKET");
m_UDT.closeInternal();
setClosed();
}
void srt::CUDTSocket::setClosed()
{
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
m_tsClosureTimeStamp = steady_clock::now();
}
void srt::CUDTSocket::setBrokenClosed()
{
m_UDT.m_iBrokenCounter = 60;
m_UDT.m_bBroken = true;
setClosed();
}
bool srt::CUDTSocket::readReady()
{
if (m_UDT.m_bConnected && m_UDT.isRcvBufferReady())
return true;
if (m_UDT.m_bListening)
return !m_QueuedSockets.empty();
return broken();
}
bool srt::CUDTSocket::writeReady() const
{
return (m_UDT.m_bConnected && (m_UDT.m_pSndBuffer->getCurrBufSize() < m_UDT.m_config.iSndBufSize)) || broken();
}
bool srt::CUDTSocket::broken() const
{
return m_UDT.m_bBroken || !m_UDT.m_bConnected;
}
////////////////////////////////////////////////////////////////////////////////
srt::CUDTUnited::CUDTUnited()
: m_Sockets()
, m_GlobControlLock()
, m_IDLock()
, m_mMultiplexer()
, m_pCache(new CCache<CInfoBlock>)
, m_bClosing(false)
, m_GCStopCond()
, m_InitLock()
, m_iInstanceCount(0)
, m_bGCStatus(false)
, m_ClosedSockets()
{
// Socket ID MUST start from a random value
m_SocketIDGenerator = genRandomInt(1, MAX_SOCKET_VAL);
m_SocketIDGenerator_init = m_SocketIDGenerator;
// XXX An unlikely exception thrown from the below calls
// might destroy the application before `main`. This shouldn't
// be a problem in general.
setupMutex(m_GCStopLock, "GCStop");
setupCond(m_GCStopCond, "GCStop");
setupMutex(m_GlobControlLock, "GlobControl");
setupMutex(m_IDLock, "ID");
setupMutex(m_InitLock, "Init");
}
srt::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();
}
releaseMutex(m_GlobControlLock);
releaseMutex(m_IDLock);
releaseMutex(m_InitLock);
// 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
releaseCond(m_GCStopCond);
#endif
releaseMutex(m_GCStopLock);
delete m_pCache;
}
string srt::CUDTUnited::CONID(SRTSOCKET sock)
{
if (sock == 0)
return "";
std::ostringstream os;
os << "@" << sock << ":";
return os.str();
}
int srt::CUDTUnited::startup()
{
ScopedLock gcinit(m_InitLock);
if (m_bGCStatus)
return 1;
if (m_iInstanceCount++ > 0)
return 1;
// 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
CCryptoControl::globalInit();
PacketFilter::globalInit();
m_bClosing = false;
if (!StartThread(m_GCThread, garbageCollect, this, "SRT:GC"))
return -1;
m_bGCStatus = true;
HLOGC(inlog.Debug, log << "SRT Clock Type: " << SRT_SYNC_CLOCK_STR);
return 0;
}
int srt::CUDTUnited::cleanup()
{
// IMPORTANT!!!
// In this function there must be NO LOGGING AT ALL. This function may
// potentially be called from within the global program destructor, and
// therefore some of the facilities used by the logging system - including
// the default std::cerr object bound to it by default, but also a different
// stream that the user's app has bound to it, and which got destroyed
// together with already exited main() - may be already deleted when
// executing this procedure.
ScopedLock gcinit(m_InitLock);
if (--m_iInstanceCount > 0)
return 0;
if (!m_bGCStatus)
return 0;
{
UniqueLock gclock(m_GCStopLock);
m_bClosing = true;
}
// NOTE: we can do relaxed signaling here because
// waiting on m_GCStopCond has a 1-second timeout,
// after which the m_bClosing flag is cheched, which
// is set here above. Worst case secenario, this
// pthread_join() call will block for 1 second.
CSync::notify_one_relaxed(m_GCStopCond);
m_GCThread.join();
m_bGCStatus = false;
// Global destruction code
#ifdef _WIN32
WSACleanup();
#endif
return 0;
}
SRTSOCKET srt::CUDTUnited::generateSocketID(bool for_group)
{
ScopedLock guard(m_IDLock);
int sockval = m_SocketIDGenerator - 1;
// First problem: zero-value should be avoided by various reasons.
if (sockval <= 0)
{
// We have a rollover on the socket value, so
// definitely we haven't made the Columbus mistake yet.
m_SocketIDGenerator = MAX_SOCKET_VAL;
sockval = MAX_SOCKET_VAL;
}
// Check all sockets if any of them has this value.
// Socket IDs are begin created this way:
//
// Initial random
// |
// |
// |
// |
// ...
// The only problem might be if the number rolls over
// and reaches the same value from the opposite side.
// This is still a valid socket value, but this time
// we have to check, which sockets have been used already.
if (sockval == m_SocketIDGenerator_init)
{
// Mark that since this point on the checks for
// whether the socket ID is in use must be done.
m_SocketIDGenerator_init = 0;
}
// This is when all socket numbers have been already used once.
// This may happen after many years of running an application
// constantly when the connection breaks and gets restored often.
if (m_SocketIDGenerator_init == 0)
{
int startval = sockval;
for (;;) // Roll until an unused value is found
{
enterCS(m_GlobControlLock);
const bool exists =
#if ENABLE_BONDING
for_group
? m_Groups.count(sockval | SRTGROUP_MASK)
:
#endif
m_Sockets.count(sockval);
leaveCS(m_GlobControlLock);
if (exists)
{
// The socket value is in use.
--sockval;
if (sockval <= 0)
sockval = MAX_SOCKET_VAL;
// Before continuing, check if we haven't rolled back to start again
// This is virtually impossible, so just make an RTI error.
if (sockval == startval)
{
// Of course, we don't lack memory, but actually this is so impossible
// that a complete memory extinction is much more possible than this.
// So treat this rather as a formal fallback for something that "should
// never happen". This should make the socket creation functions, from
// socket_create and accept, return this error.
m_SocketIDGenerator = sockval + 1; // so that any next call will cause the same error
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
}
// try again, if this is a free socket
continue;
}
// No socket found, this ID is free to use
m_SocketIDGenerator = sockval;
break;
}
}
else
{
m_SocketIDGenerator = sockval;
}
// The socket value counter remains with the value rolled
// without the group bit set; only the returned value may have
// the group bit set.
if (for_group)
sockval = m_SocketIDGenerator | SRTGROUP_MASK;
else
sockval = m_SocketIDGenerator;
LOGC(smlog.Debug, log << "generateSocketID: " << (for_group ? "(group)" : "") << ": @" << sockval);
return sockval;
}
SRTSOCKET srt::CUDTUnited::newSocket(CUDTSocket** pps)
{
// XXX consider using some replacement of std::unique_ptr
// so that exceptions will clean up the object without the
// need for a dedicated code.
CUDTSocket* ns = NULL;
try
{
ns = new CUDTSocket;
}
catch (...)
{
delete ns;
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
}
try
{
ns->m_SocketID = generateSocketID();
}
catch (...)
{
delete ns;
throw;
}
ns->m_Status = SRTS_INIT;
ns->m_ListenSocket = 0;
ns->core().m_SocketID = ns->m_SocketID;
ns->core().m_pCache = m_pCache;
try
{
HLOGC(smlog.Debug, log << CONID(ns->m_SocketID) << "newSocket: mapping socket " << ns->m_SocketID);
// protect the m_Sockets structure.
ScopedLock cs(m_GlobControlLock);
m_Sockets[ns->m_SocketID] = ns;
}
catch (...)
{
// failure and rollback
delete ns;
ns = NULL;
throw CUDTException(MJ_SYSTEMRES, MN_MEMORY, 0);
}
if (pps)
*pps = ns;
return ns->m_SocketID;
}
int srt::CUDTUnited::newConnection(const SRTSOCKET listen,
const sockaddr_any& peer,
const CPacket& hspkt,
CHandShake& w_hs,
int& w_error,
CUDT*& w_acpu)
{
CUDTSocket* ns = NULL;
w_acpu = NULL;
w_error = SRT_REJ_IPE;
// Can't manage this error through an exception because this is
// running in the listener loop.
CUDTSocket* ls = locateSocket(listen);
if (!ls)
{
LOGC(cnlog.Error, log << "IPE: newConnection by listener socket id=" << listen << " which DOES NOT EXIST.");
return -1;
}
HLOGC(cnlog.Debug,
log << "newConnection: creating new socket after listener @" << listen
<< " contacted with backlog=" << ls->m_uiBackLog);
// if this connection has already been processed
if ((ns = locatePeer(peer, w_hs.m_iID, w_hs.m_iISN)) != NULL)
{
if (ns->core().m_bBroken)
{
// last connection from the "peer" address has been broken
ns->setClosed();
ScopedLock acceptcg(ls->m_AcceptLock);
ls->m_QueuedSockets.erase(ns->m_SocketID);
}
else
{
// connection already exist, this is a repeated connection request
// respond with existing HS information
HLOGC(cnlog.Debug, log << "newConnection: located a WORKING peer @" << w_hs.m_iID << " - ADAPTING.");
w_hs.m_iISN = ns->core().m_iISN;
w_hs.m_iMSS = ns->core().MSS();
w_hs.m_iFlightFlagSize = ns->core().m_config.iFlightFlagSize;
w_hs.m_iReqType = URQ_CONCLUSION;
w_hs.m_iID = ns->m_SocketID;
// Report the original UDT because it will be
// required to complete the HS data for conclusion response.
w_acpu = &ns->core();
return 0;
// except for this situation a new connection should be started
}
}
else
{
HLOGC(cnlog.Debug,
log << "newConnection: NOT located any peer @" << w_hs.m_iID << " - resuming with initial connection.");
}
// exceeding backlog, refuse the connection request
if (ls->m_QueuedSockets.size() >= ls->m_uiBackLog)
{
w_error = SRT_REJ_BACKLOG;
LOGC(cnlog.Note, log << "newConnection: listen backlog=" << ls->m_uiBackLog << " EXCEEDED");
return -1;
}
try
{
// Protect the config of the listener socket from a data race.
ScopedLock lck(ls->core().m_ConnectionLock);
ns = new CUDTSocket(*ls);
// No need to check the peer, this is the address from which the request has come.
ns->m_PeerAddr = peer;
}
catch (...)
{
w_error = SRT_REJ_RESOURCE;
delete ns;
LOGC(cnlog.Error, log << "IPE: newConnection: unexpected exception (probably std::bad_alloc)");
return -1;
}
ns->core().m_RejectReason = SRT_REJ_UNKNOWN; // pre-set a universal value
try
{
ns->m_SocketID = generateSocketID();
}
catch (const CUDTException&)
{
LOGC(cnlog.Fatal, log << "newConnection: IPE: all sockets occupied? Last gen=" << m_SocketIDGenerator);
// generateSocketID throws exception, which can be naturally handled
// when the call is derived from the API call, but here it's called
// internally in response to receiving a handshake. It must be handled
// here and turned into an erroneous return value.
delete ns;
return -1;
}
ns->m_ListenSocket = listen;
ns->core().m_SocketID = ns->m_SocketID;
ns->m_PeerID = w_hs.m_iID;
ns->m_iISN = w_hs.m_iISN;
HLOGC(cnlog.Debug,
log << "newConnection: DATA: lsnid=" << listen << " id=" << ns->core().m_SocketID
<< " peerid=" << ns->core().m_PeerID << " ISN=" << ns->m_iISN);
int error = 0;
bool should_submit_to_accept = true;
// Set the error code for all prospective problems below.
// It won't be interpreted when result was successful.
w_error = SRT_REJ_RESOURCE;
// 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.
HLOGC(cnlog.Debug, log <<
"newConnection: incoming " << peer.str() << ", mapping socket " << ns->m_SocketID);
{
ScopedLock cg(m_GlobControlLock);
m_Sockets[ns->m_SocketID] = ns;
}
if (ls->core().m_cbAcceptHook)
{
if (!ls->core().runAcceptHook(&ns->core(), peer.get(), w_hs, hspkt))
{
w_error = ns->core().m_RejectReason;
error = 1;
goto ERR_ROLLBACK;
}
}
// bind to the same addr of listening socket
ns->core().open();
if (!updateListenerMux(ns, ls))
{
// This is highly unlikely if not impossible, but there's
// a theoretical runtime chance of failure so it should be
// handled
ns->core().m_RejectReason = SRT_REJ_IPE;
throw false; // let it jump directly into the omni exception handler
}
ns->core().acceptAndRespond(ls->m_SelfAddr, peer, hspkt, (w_hs));
}
catch (...)
{
// Extract the error that was set in this new failed entity.
w_error = ns->core().m_RejectReason;
error = 1;
goto ERR_ROLLBACK;
}
ns->m_Status = SRTS_CONNECTED;
// copy address information of local node
// Precisely, what happens here is:
// - Get the IP address and port from the system database
ns->core().m_pSndQueue->m_pChannel->getSockAddr((ns->m_SelfAddr));
// - OVERWRITE just the IP address itself by a value taken from piSelfIP
// (the family is used exactly as the one taken from what has been returned
// by getsockaddr)
CIPAddress::pton((ns->m_SelfAddr), ns->core().m_piSelfIP, peer);
{
// protect the m_PeerRec structure (and group existence)
ScopedLock glock(m_GlobControlLock);
try
{
HLOGC(cnlog.Debug, log << "newConnection: mapping peer " << ns->m_PeerID
<< " to that socket (" << ns->m_SocketID << ")");
m_PeerRec[ns->getPeerSpec()].insert(ns->m_SocketID);
LOGC(cnlog.Note, log << "@" << ns->m_SocketID << " connection on listener @" << listen
<< " (" << ns->m_SelfAddr.str() << ") from peer @" << ns->m_PeerID << " (" << peer.str() << ")");
}
catch (...)
{
LOGC(cnlog.Error, log << "newConnection: error when mapping peer!");
error = 2;
}
// The access to m_GroupOf should be also protected, as the group
// could be requested deletion in the meantime. This will hold any possible
// removal from group and resetting m_GroupOf field.
#if ENABLE_BONDING
if (ns->m_GroupOf)
{
// XXX this might require another check of group type.
// For redundancy group, at least, update the status in the group
CUDTGroup* g = ns->m_GroupOf;
ScopedLock grlock(g->m_GroupLock);
if (g->m_bClosing)
{
error = 1; // "INTERNAL REJECTION"
goto ERR_ROLLBACK;
}
// Check if this is the first socket in the group.
// If so, give it up to accept, otherwise just do nothing
// The client will be informed about the newly added connection at the
// first moment when attempting to get the group status.
for (CUDTGroup::gli_t gi = g->m_Group.begin(); gi != g->m_Group.end(); ++gi)
{
if (gi->laststatus == SRTS_CONNECTED)
{
HLOGC(cnlog.Debug,
log << "Found another connected socket in the group: $" << gi->id
<< " - socket will be NOT given up for accepting");
should_submit_to_accept = false;
break;
}
}
// Update the status in the group so that the next
// operation can include the socket in the group operation.
CUDTGroup::SocketData* gm = ns->m_GroupMemberData;
HLOGC(cnlog.Debug,
log << "newConnection(GROUP): Socket @" << ns->m_SocketID << " BELONGS TO $" << g->id() << " - will "
<< (should_submit_to_accept ? "" : "NOT ") << "report in accept");
gm->sndstate = SRT_GST_IDLE;
gm->rcvstate = SRT_GST_IDLE;
gm->laststatus = SRTS_CONNECTED;
if (!g->m_bConnected)
{
HLOGC(cnlog.Debug, log << "newConnection(GROUP): First socket connected, SETTING GROUP CONNECTED");
g->m_bConnected = true;
}
// XXX PROLBEM!!! These events are subscribed here so that this is done once, lazily,
// but groupwise connections could be accepted from multiple listeners for the same group!
// m_listener MUST BE A CONTAINER, NOT POINTER!!!
// ALSO: Maybe checking "the same listener" is not necessary as subscruption may be done
// multiple times anyway?
if (!g->m_listener)
{
// Newly created group from the listener, which hasn't yet
// the listener set.
g->m_listener = ls;
// Listen on both first connected socket and continued sockets.
// This might help with jump-over situations, and in regular continued
// sockets the IN event won't be reported anyway.
int listener_modes = SRT_EPOLL_ACCEPT | SRT_EPOLL_UPDATE;
epoll_add_usock_INTERNAL(g->m_RcvEID, ls, &listener_modes);
// This listening should be done always when a first connected socket
// appears as accepted off the listener. This is for the sake of swait() calls
// inside the group receiving and sending functions so that they get
// interrupted when a new socket is connected.
}
// Add also per-direction subscription for the about-to-be-accepted socket.
// Both first accepted socket that makes the group-accept and every next
// socket that adds a new link.
int read_modes = SRT_EPOLL_IN | SRT_EPOLL_ERR;
int write_modes = SRT_EPOLL_OUT | SRT_EPOLL_ERR;
epoll_add_usock_INTERNAL(g->m_RcvEID, ns, &read_modes);
epoll_add_usock_INTERNAL(g->m_SndEID, ns, &write_modes);
// With app reader, do not set groupPacketArrival (block the
// provider array feature completely for now).
/* SETUP HERE IF NEEDED
ns->core().m_cbPacketArrival.set(ns->m_pUDT, &CUDT::groupPacketArrival);
*/
}
else
{
HLOGC(cnlog.Debug, log << "newConnection: Socket @" << ns->m_SocketID << " is not in a group");
}
#endif
}
if (should_submit_to_accept)
{
enterCS(ls->m_AcceptLock);
try
{
ls->m_QueuedSockets[ns->m_SocketID] = ns->m_PeerAddr;
}
catch (...)
{
LOGC(cnlog.Error, log << "newConnection: error when queuing socket!");
error = 3;
}
leaveCS(ls->m_AcceptLock);
HLOGC(cnlog.Debug, log << "ACCEPT: new socket @" << ns->m_SocketID << " submitted for acceptance");
// acknowledge users waiting for new connections on the listening socket
m_EPoll.update_events(listen, ls->core().m_sPollID, SRT_EPOLL_ACCEPT, true);
CGlobEvent::triggerEvent();
// XXX the exact value of 'error' is ignored
if (error > 0)
{
goto ERR_ROLLBACK;
}
// wake up a waiting accept() call
CSync::lock_notify_one(ls->m_AcceptCond, ls->m_AcceptLock);
}
else
{
HLOGC(cnlog.Debug,
log << "ACCEPT: new socket @" << ns->m_SocketID
<< " NOT submitted to acceptance, another socket in the group is already connected");
// acknowledge INTERNAL users waiting for new connections on the listening socket
// that are reported when a new socket is connected within an already connected group.
m_EPoll.update_events(listen, ls->core().m_sPollID, SRT_EPOLL_UPDATE, true);
CGlobEvent::triggerEvent();
}
ERR_ROLLBACK:
// XXX the exact value of 'error' is ignored
if (error > 0)
{
#if ENABLE_LOGGING
static const char* why[] = {
"UNKNOWN ERROR", "INTERNAL REJECTION", "IPE when mapping a socket", "IPE when inserting a socket"};
LOGC(cnlog.Warn,
log << CONID(ns->m_SocketID) << "newConnection: connection rejected due to: " << why[error] << " - "
<< RequestTypeStr(URQFailure(w_error)));
#endif
SRTSOCKET id = ns->m_SocketID;
ns->core().closeInternal();
ns->setClosed();
// 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.
{
ScopedLock cg(m_GlobControlLock);
#if ENABLE_BONDING
if (ns->m_GroupOf)
{
HLOGC(smlog.Debug,
log << "@" << ns->m_SocketID << " IS MEMBER OF $" << ns->m_GroupOf->id()
<< " - REMOVING FROM GROUP");
ns->removeFromGroup(true);
}
#endif
m_Sockets.erase(id);
m_ClosedSockets[id] = ns;
}
return -1;
}
return 1;
}
// static forwarder
int srt::CUDT::installAcceptHook(SRTSOCKET lsn, srt_listen_callback_fn* hook, void* opaq)
{
return uglobal().installAcceptHook(lsn, hook, opaq);
}
int srt::CUDTUnited::installAcceptHook(const SRTSOCKET lsn, srt_listen_callback_fn* hook, void* opaq)
{
try
{
CUDTSocket* s = locateSocket(lsn, ERH_THROW);
s->core().installAcceptHook(hook, opaq);
}
catch (CUDTException& e)
{
SetThreadLocalError(e);
return SRT_ERROR;
}
return 0;
}
int srt::CUDT::installConnectHook(SRTSOCKET lsn, srt_connect_callback_fn* hook, void* opaq)
{
return uglobal().installConnectHook(lsn, hook, opaq);
}
int srt::CUDTUnited::installConnectHook(const SRTSOCKET u, srt_connect_callback_fn* hook, void* opaq)
{
try
{
#if ENABLE_BONDING
if (u & SRTGROUP_MASK)
{
GroupKeeper k(*this, u, ERH_THROW);
k.group->installConnectHook(hook, opaq);
return 0;
}
#endif
CUDTSocket* s = locateSocket(u, ERH_THROW);
s->core().installConnectHook(hook, opaq);
}
catch (CUDTException& e)
{
SetThreadLocalError(e);
return SRT_ERROR;
}
return 0;
}
SRT_SOCKSTATUS srt::CUDTUnited::getStatus(const SRTSOCKET u)
{
// protects the m_Sockets structure
ScopedLock cg(m_GlobControlLock);
sockets_t::const_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;
}
return i->second->getStatus();
}
int srt::CUDTUnited::bind(CUDTSocket* s, const sockaddr_any& name)
{
ScopedLock cg(s->m_ControlLock);
// cannot bind a socket more than once
if (s->m_Status != SRTS_INIT)
throw CUDTException(MJ_NOTSUP, MN_NONE, 0);
if (s->core().m_config.iIpV6Only == -1 && name.family() == AF_INET6 && name.isany())
{
// V6ONLY option must be set explicitly if you want to bind to a wildcard address in IPv6
HLOGP(smlog.Error,
"bind: when binding to :: (IPv6 wildcard), SRTO_IPV6ONLY option must be set explicitly to 0 or 1");
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
s->core().open();
updateMux(s, name);
s->m_Status = SRTS_OPENED;
// copy address information of local node
s->core().m_pSndQueue->m_pChannel->getSockAddr((s->m_SelfAddr));
return 0;
}
int srt::CUDTUnited::bind(CUDTSocket* s, UDPSOCKET udpsock)
{
ScopedLock 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_any name;
socklen_t namelen = sizeof name; // max of inet and inet6
// This will preset the sa_family as well; the namelen is given simply large
// enough for any family here.
if (::getsockname(udpsock, &name.sa, &namelen) == -1)
throw CUDTException(MJ_NOTSUP, MN_INVAL);
// Successfully extracted, so update the size
name.len = namelen;
s->core().open();
updateMux(s, name, &udpsock);
s->m_Status = SRTS_OPENED;
// copy address information of local node
s->core().m_pSndQueue->m_pChannel->getSockAddr(s->m_SelfAddr);
return 0;
}
int srt::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 = locateSocket(u);
if (!s)
throw CUDTException(MJ_NOTSUP, MN_SIDINVAL, 0);
ScopedLock 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)]];