forked from Haivision/srt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchannel.cpp
More file actions
1230 lines (1075 loc) · 40.2 KB
/
channel.cpp
File metadata and controls
1230 lines (1075 loc) · 40.2 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
/*
* 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 01/27/2011
modified by
Haivision Systems Inc.
*****************************************************************************/
#include "platform_sys.h"
#include <iostream>
#include <iomanip> // Logging
#include <hvu_compat.h>
#include <csignal>
#include "channel.h"
#include "core.h" // srt::logging::kmlog
#include "packet.h"
#include "logging.h"
#include "netinet_any.h"
#include "utilities.h"
#ifdef _WIN32
typedef int socklen_t;
#endif
using namespace std;
using namespace srt::logging;
using namespace hvu; // ofmt
namespace srt
{
#ifdef _WIN32
// use INVALID_SOCKET, as provided
#else
static const int INVALID_SOCKET = -1;
#endif
// CREATING A SOCKET, possibly with CLOEXEC flag
// (portability solution)
// MAIN INTERFACE:
//
// SYSSOCKET createUDPSocket_asneeded(int family);
//
// Creates a UDP/DGRAM socket. The CLOEXEC flag should be set
// on it, if configured so. On error, throws CUDTException.
//
// Depending on platform and runtime conditions, it can do:
//
// 1. Create a socket without CLOEXEC (if not needed)
// 2. Create a socket with CLOEXEC flag set
// 3. Create a socket without CLOEXEC set and this flag will be
// set later using the set_cloexec() function, defined below.
// SIGNATURE:
//
// int set_cloexec(SYSSOCKET fd, int set)
//
// RETURNS: int error_code, as defined in
// - POSIX, as int errno
// - Windows, as return value of WSAGetLastError
// It is considered that 0 is the value of "no error"
// or "success" otherwise.
//
// SYSSOCKET is defined in srt.h as
// - SOCKET on Windows
// - int on POSIX
#ifndef _WIN32
#if defined(_AIX) || defined(__APPLE__) || defined(__DragonFly__) || defined(__FreeBSD__) || \
defined(__FreeBSD_kernel__) || defined(__linux__) || defined(__OpenBSD__) || defined(__NetBSD__)
// Set the CLOEXEC flag using ioctl() function
static int set_cloexec(SYSSOCKET fd, int set)
{
int r;
do
r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
while (r == -1 && errno == EINTR);
if (r)
return errno;
return 0;
}
#else
// Set the CLOEXEC flag using fcntl() function
static int set_cloexec(SYSSOCKET fd, int set)
{
int flags;
int r;
do
r = fcntl(fd, F_GETFD);
while (r == -1 && errno == EINTR);
if (r == -1)
return errno;
/* Bail out now if already set/clear. */
if (!!(r & FD_CLOEXEC) == !!set)
return 0;
if (set)
flags = r | FD_CLOEXEC;
else
flags = r & ~FD_CLOEXEC;
do
r = fcntl(fd, F_SETFD, flags);
while (r == -1 && errno == EINTR);
if (r)
return errno;
return 0;
}
#endif // if defined(_AIX) ...
#else // _WIN32
static int set_cloexec(SYSSOCKET fd, int set)
{
if (!::SetHandleInformation((HANDLE)fd, HANDLE_FLAG_INHERIT, set))
return NET_ERROR;
return 0;
}
#endif // ifndef _WIN32
// Creates a socket without requesting the CLOEXEC flag.
static inline SYSSOCKET createUDPSocket(int family)
{
SYSSOCKET s = ::socket(family, SOCK_DGRAM, IPPROTO_UDP);
if (s == INVALID_SOCKET)
throw CUDTException(MJ_SETUP, MN_NONE, NET_ERROR);
return s;
}
// Creates a socket with or without CLOEXEC flag, depending on
// what is possible. Returns:
// .first: created socket
// .second: true, if the set_cloexec needs to be still called on it
static inline pair<SYSSOCKET, bool> createUDPSocket_try_cloexec(int family)
{
// Try with SOCK_CLOEXEC, if this flag is available at compile time
#if defined(SOCK_CLOEXEC)
SYSSOCKET s = ::socket(family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
if (s != INVALID_SOCKET)
{
return make_pair(s, false);
}
// If this failed, fallback HERE.
#endif
// If failed or not available, just create socket and report
// the need to set it later.
return make_pair(createUDPSocket(family), true);
}
// Creates a socket that will have the CLOEXEC flag set if needed.
// If CLOEXEC flag was needed, this fill return the socket with
// this flag set - one way or another.
static inline SYSSOCKET createUDPSocket_asneeded(int family)
{
#if SRT_ENABLE_CLOEXEC
// Create a socket, preferably with CLOEXEC flag.
// 'setafter' means that socket is there, but the CLOEXEC
// flag must be set separately.
SYSSOCKET s;
bool setafter;
Tie(s, setafter) = createUDPSocket_try_cloexec(family);
if (setafter)
{
int ret_err = set_cloexec(s, 1);
if (ret_err != 0)
{
throw CUDTException(MJ_SETUP, MN_NONE, ret_err);
}
}
return s;
#else
return createUDPSocket(family);
#endif
}
//-----------------------------------
CChannel::CChannel()
: m_iSocket(INVALID_SOCKET)
#ifdef SRT_ENABLE_PKTINFO
, m_bBindMasked(true)
#endif
{
#ifdef SRT_ENABLE_PKTINFO
// Do the check for ancillary data buffer size, kinda assertion
static const size_t CMSG_MAX_SPACE = sizeof (CMSGNodeIPv4) + sizeof (CMSGNodeIPv6);
if (CMSG_MAX_SPACE < CMSG_SPACE(sizeof(in_pktinfo)) + CMSG_SPACE(sizeof(in6_pktinfo)))
{
LOGC(kmlog.Fatal, log << "Size of CMSG_MAX_SPACE="
<< CMSG_MAX_SPACE << " too short for cmsg "
<< CMSG_SPACE(sizeof(in_pktinfo)) << ", "
<< CMSG_SPACE(sizeof(in6_pktinfo)) << " - PLEASE FIX");
throw CUDTException(MJ_SETUP, MN_NONE, 0);
}
#endif
}
CChannel::~CChannel() {}
void CChannel::createSocket(int family)
{
// Creates the socket, regarding any required default flags
m_iSocket = createUDPSocket_asneeded(family);
if (m_mcfg.iIpV6Only != -1 && family == AF_INET6) // (not an error if it fails)
{
const int res SRT_ATR_UNUSED = ::setsockopt(m_iSocket,
IPPROTO_IPV6, IPV6_V6ONLY,
(const char*)&m_mcfg.iIpV6Only, sizeof m_mcfg.iIpV6Only);
if (res == -1)
{
LOGC(kmlog.Error,
log << "::setsockopt: failed to set IPPROTO_IPV6/IPV6_V6ONLY = " << m_mcfg.iIpV6Only << ": "
<< SysStrError(NET_ERROR));
}
}
}
void CChannel::open(const sockaddr_any& addr)
{
createSocket(addr.family());
socklen_t namelen = addr.size();
if (::bind(m_iSocket, &addr.sa, namelen) == -1)
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
m_BindAddr = addr;
#ifdef SRT_ENABLE_PKTINFO
m_bBindMasked = m_BindAddr.isany();
#endif
LOGC(kmlog.Debug, log << "CHANNEL: Bound to local address: " << m_BindAddr.str());
setUDPSockOpt();
}
void CChannel::open(int family)
{
createSocket(family);
// sendto or WSASendTo will also automatically bind the socket
addrinfo hints;
addrinfo* res;
memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_flags = AI_PASSIVE;
hints.ai_family = family;
hints.ai_socktype = SOCK_DGRAM;
const int eai = ::getaddrinfo(NULL, "0", &hints, &res);
if (eai != 0)
{
// Controversial a little bit because this function occasionally
// doesn't use errno (here: NET_ERROR for portability), instead
// it returns 0 if succeeded or an error code. This error code
// is passed here then. A controversy is around the fact that
// the receiver of this error has completely no ability to know
// what this error code's domain is, and it definitely isn't
// the same as for errno.
throw CUDTException(MJ_SETUP, MN_NORES, eai);
}
// On Windows ai_addrlen has type size_t (unsigned), while bind takes int.
if (0 != ::bind(m_iSocket, res->ai_addr, (socklen_t)res->ai_addrlen))
{
::freeaddrinfo(res);
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
m_BindAddr = sockaddr_any(res->ai_addr, (sockaddr_any::len_t)res->ai_addrlen);
#ifdef SRT_ENABLE_PKTINFO
// We know that this is intentionally bound now to "any",
// so the requester-destination address must be remembered and passed.
m_bBindMasked = true;
#endif
::freeaddrinfo(res);
HLOGC(kmlog.Debug, log << "CHANNEL: Bound to local address: " << m_BindAddr.str());
setUDPSockOpt();
}
void CChannel::attach(UDPSOCKET udpsock, const sockaddr_any& udpsocks_addr)
{
// The getsockname() call is done before calling it and the
// result is placed into udpsocks_addr.
m_iSocket = udpsock;
m_BindAddr = udpsocks_addr;
setUDPSockOpt();
}
static inline string fmt_opt(bool value, const string& label)
{
string out;
out.reserve(label.size() + 2);
out = value ? "+" : "-";
out += label;
return out;
}
static inline string fmt_alt(bool value, const string& label, const string& unlabel)
{
return value ? label : unlabel;
}
void CChannel::setUDPSockOpt()
{
#if defined(SUNOS)
{
socklen_t optSize;
// Retrieve starting SND/RCV Buffer sizes.
int startRCVBUF = 0;
optSize = sizeof(startRCVBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&startRCVBUF, &optSize))
{
startRCVBUF = -1;
}
int startSNDBUF = 0;
optSize = sizeof(startSNDBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (void*)&startSNDBUF, &optSize))
{
startSNDBUF = -1;
}
// SunOS will fail setsockopt() if the requested buffer size exceeds system
// maximum value.
// However, do not reduce the buffer size.
const int maxsize = 64000;
if (-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF,
(const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize))
{
int currentRCVBUF = 0;
optSize = sizeof(currentRCVBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)¤tRCVBUF, &optSize))
{
currentRCVBUF = -1;
}
if (maxsize > currentRCVBUF)
{
::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&maxsize, sizeof maxsize);
}
}
if (-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF,
(const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize))
{
int currentSNDBUF = 0;
optSize = sizeof(currentSNDBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)¤tSNDBUF, &optSize))
{
currentSNDBUF = -1;
}
if (maxsize > currentSNDBUF)
{
::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&maxsize, sizeof maxsize);
}
}
// Retrieve ending SND/RCV Buffer sizes.
int endRCVBUF = 0;
optSize = sizeof(endRCVBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&endRCVBUF, &optSize))
{
endRCVBUF = -1;
}
int endSNDBUF = 0;
optSize = sizeof(endSNDBUF);
if (-1 == ::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (void*)&endSNDBUF, &optSize))
{
endSNDBUF = -1;
}
LOGC(kmlog.Debug,
log << "SO_RCVBUF:"
<< " startRCVBUF=" << startRCVBUF << " m_mcfg.iUDPRcvBufSize=" << m_mcfg.iUDPRcvBufSize
<< " endRCVBUF=" << endRCVBUF);
LOGC(kmlog.Debug,
log << "SO_SNDBUF:"
<< " startSNDBUF=" << startSNDBUF << " m_mcfg.iUDPSndBufSize=" << m_mcfg.iUDPSndBufSize
<< " endSNDBUF=" << endSNDBUF);
}
#elif defined(BSD) || TARGET_OS_MAC
// BSD system will fail setsockopt if the requested buffer size exceeds system maximum value
int maxsize = 64000;
if (-1 == ::setsockopt(
m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize))
::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&maxsize, sizeof maxsize);
if (-1 == ::setsockopt(
m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize))
::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&maxsize, sizeof maxsize);
#else
// for other systems, if requested is greater than maximum, the maximum value will be automatically used
if ((-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF,
(const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize))
||
(-1 == ::setsockopt( m_iSocket, SOL_SOCKET, SO_SNDBUF,
(const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize)))
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
#endif
bool is_set = false;
bool adr_unspec = false, adr_mapped = false, adr_v6 = false;
if (m_BindAddr.family() == AF_INET)
{
adr_unspec = m_BindAddr.isany();
}
else
{
adr_unspec = IN6_IS_ADDR_UNSPECIFIED(&m_BindAddr.sin6.sin6_addr);
adr_mapped = IN6_IS_ADDR_V4MAPPED(&m_BindAddr.sin6.sin6_addr);
adr_v6 = true;
}
if (m_mcfg.iIpTTL != -1)
{
if (!adr_v6)
{
if (-1 == ::setsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
{
LOGC(kmlog.Error, log << "setsockopt(IP_TTL): " << SysStrError(NET_ERROR));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
else
{
// If IPv6 address is unspecified, set BOTH IP_TTL and IPV6_UNICAST_HOPS.
// For specified IPv6 address, set IPV6_UNICAST_HOPS ONLY UNLESS it's an IPv4-mapped-IPv6
if (adr_unspec || !adr_mapped)
{
if (-1 == ::setsockopt( m_iSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS,
(const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
{
LOGC(kmlog.Error, log << "setsockopt(IPV6_UNICAST_HOPS): " << SysStrError(NET_ERROR));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
// For specified IPv6 address, set IP_TTL ONLY WHEN it's an IPv4-mapped-IPv6
if (!is_set) // adr_mapped (because adr_unspec was handled above)
{
if (-1 == ::setsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
{
LOGC(kmlog.Error, log << "setsockopt(IP_TTL): " << SysStrError(NET_ERROR)
<< fmt_alt(adr_unspec, " (v6 unspec)", " (v6 mapped v4)"));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
}
if (!is_set)
{
LOGC(kmlog.Error, log << "srt_setsockflag(SRTO_IPTTL): No suitable condition for adr=" << m_BindAddr.str()
<< " : " << fmt_opt(adr_v6, "v6 ") << fmt_opt(adr_unspec, "unspec ") << fmt_opt(adr_mapped, "mapped"));
throw CUDTException(MJ_SETUP, MN_INVAL, 0);
}
}
is_set = false;
if (m_mcfg.iIpToS != -1)
{
if (m_BindAddr.family() == AF_INET)
{
if (-1 == ::setsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
{
LOGC(kmlog.Error, log << "setsockopt(IP_TOS): " << SysStrError(NET_ERROR));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
else
{
// If IPv6 address is unspecified, set BOTH IP_TOS and IPV6_TCLASS.
SRT_ATR_UNUSED bool using_tclass = false;
#ifdef IPV6_TCLASS
using_tclass = true;
// For specified IPv6 address, set IPV6_TCLASS ONLY UNLESS it's an IPv4-mapped-IPv6
if (adr_unspec || !adr_mapped)
{
if (-1 == ::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_TCLASS,
(const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
{
LOGC(kmlog.Error, log << "setsockopt(IPV6_TCLASS): " << SysStrError(NET_ERROR));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
#endif
// For specified IPv6 address, set IP_TOS ONLY WHEN it's an IPv4-mapped-IPv6
if (!is_set && (adr_unspec || adr_mapped))
{
if (-1 == ::setsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
{
LOGC(kmlog.Error, log << "setsockopt(IP_TOS): " << SysStrError(NET_ERROR)
<< (adr_unspec ? " (v6 unspecified)" : " (v6 mapped v4)")
<< (using_tclass ? "(fallback to IP_TOS)" : ""));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
is_set = true;
}
}
if (!is_set)
{
LOGC(kmlog.Error, log << "srt_setsockflag(SRTO_IPTOS): No suitable condition for adr=" << m_BindAddr.str()
<< " : " << fmt_opt(adr_v6, "v6 ") << fmt_opt(adr_unspec, "unspec ") << fmt_opt(adr_mapped, "mapped"));
throw CUDTException(MJ_SETUP, MN_INVAL, 0);
}
}
#ifdef SRT_ENABLE_BINDTODEVICE
if (!m_mcfg.sBindToDevice.empty())
{
if (m_BindAddr.family() != AF_INET)
{
LOGC(kmlog.Error, log << "SRTO_BINDTODEVICE can only be set with AF_INET connections");
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
if (-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_BINDTODEVICE,
m_mcfg.sBindToDevice.c_str(), m_mcfg.sBindToDevice.size()))
{
LOGC(kmlog.Error, log << "setsockopt(SRTO_BINDTODEVICE): " << SysStrError(NET_ERROR));
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
}
}
#endif
#ifdef UNIX
// Set non-blocking I/O
// UNIX does not support SO_RCVTIMEO
int opts = ::fcntl(m_iSocket, F_GETFL);
if (-1 == ::fcntl(m_iSocket, F_SETFL, opts | O_NONBLOCK))
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
#elif defined(_WIN32)
u_long nonBlocking = 1;
if (-1 == ioctlsocket(m_iSocket, FIONBIO, &nonBlocking))
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
#else
timeval tv;
tv.tv_sec = 0;
#if defined(BSD) || TARGET_OS_MAC
// Known BSD bug as the day I wrote this code.
// A small time out value will cause the socket to block forever.
tv.tv_usec = 10000;
#else
tv.tv_usec = 100;
#endif
// Set receiving time-out value
if (-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(timeval)))
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
// Set sending time-out, too; O_NONBLOCK sets it in both directions,
// so both should be also set here for consistency.
if (-1 == ::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(timeval)))
throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
#endif
#ifdef SRT_ENABLE_PKTINFO
if (m_bBindMasked)
{
HLOGP(kmlog.Debug, "Socket bound to ANY - setting PKTINFO for address retrieval");
const int on = 1, off SRT_ATR_UNUSED = 0;
if (m_BindAddr.family() == AF_INET || m_mcfg.iIpV6Only == 0)
{
::setsockopt(m_iSocket, IPPROTO_IP, IP_PKTINFO, (char*)&on, sizeof(on));
}
if (m_BindAddr.family() == AF_INET6)
{
::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
}
// XXX Unknown why this has to be off. RETEST.
//::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off));
}
#endif
}
void CChannel::close()
{
UDPSOCKET oldsocket = m_iSocket.load();
if (oldsocket == INVALID_SOCKET)
return;
m_iSocket = INVALID_SOCKET;
#ifndef _WIN32
::close(oldsocket);
#else
::closesocket(oldsocket);
#endif
}
int CChannel::getSndBufSize()
{
socklen_t size = (socklen_t)sizeof m_mcfg.iUDPSndBufSize;
::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (char*)&m_mcfg.iUDPSndBufSize, &size);
return m_mcfg.iUDPSndBufSize;
}
int CChannel::getRcvBufSize()
{
socklen_t size = (socklen_t)sizeof m_mcfg.iUDPRcvBufSize;
::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (char*)&m_mcfg.iUDPRcvBufSize, &size);
return m_mcfg.iUDPRcvBufSize;
}
void CChannel::setConfig(const CSrtMuxerConfig& config)
{
m_mcfg = config;
}
void CChannel::getSocketOption(int level, int option, char* pw_dataptr, socklen_t& w_len, int& w_status)
{
w_status = ::getsockopt(m_iSocket, level, option, (pw_dataptr), (&w_len));
}
int CChannel::getIpTTL() const
{
if (m_iSocket == INVALID_SOCKET)
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
socklen_t size = (socklen_t)sizeof m_mcfg.iIpTTL;
if (m_BindAddr.family() == AF_INET)
{
::getsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (char*)&m_mcfg.iIpTTL, &size);
}
else if (m_BindAddr.family() == AF_INET6)
{
::getsockopt(m_iSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (char*)&m_mcfg.iIpTTL, &size);
}
else
{
// If family is unspecified, the socket probably doesn't exist.
LOGC(kmlog.Error, log << "IPE: CChannel::getIpTTL called with unset family");
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
return m_mcfg.iIpTTL;
}
int CChannel::getIpToS() const
{
if (m_iSocket == INVALID_SOCKET)
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
socklen_t size = (socklen_t)sizeof m_mcfg.iIpToS;
if (m_BindAddr.family() == AF_INET)
{
::getsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (char*)&m_mcfg.iIpToS, &size);
}
else if (m_BindAddr.family() == AF_INET6)
{
#ifdef IPV6_TCLASS
::getsockopt(m_iSocket, IPPROTO_IPV6, IPV6_TCLASS, (char*)&m_mcfg.iIpToS, &size);
#endif
}
else
{
// If family is unspecified, the socket probably doesn't exist.
LOGC(kmlog.Error, log << "IPE: CChannel::getIpToS called with unset family");
throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
}
return m_mcfg.iIpToS;
}
#ifdef SRT_ENABLE_BINDTODEVICE
bool CChannel::getBind(char* dst, size_t len) const
{
if (m_iSocket == INVALID_SOCKET)
return false; // No socket to get data from
// Try to obtain it directly from the function. If not possible,
// then return from internal data.
socklen_t length = len;
int res = ::getsockopt(m_iSocket, SOL_SOCKET, SO_BINDTODEVICE, dst, &length);
if (res == -1)
return false; // Happens on Linux v < 3.8
// For any case
dst[length] = 0;
return true;
}
#endif
int CChannel::ioctlQuery(int type SRT_ATR_UNUSED) const
{
#if defined(unix) || defined(__APPLE__)
int value = 0;
int res = ::ioctl(m_iSocket, type, &value);
if (res != -1)
return value;
#endif
return -1;
}
int CChannel::sockoptQuery(int level SRT_ATR_UNUSED, int option SRT_ATR_UNUSED) const
{
#if defined(unix) || defined(__APPLE__)
int value = 0;
socklen_t len = sizeof(int);
int res = ::getsockopt(m_iSocket, level, option, &value, &len);
if (res != -1)
return value;
#endif
return -1;
}
sockaddr_any CChannel::getSockAddr() const
{
sockaddr_any addr;
// The getsockname function requires only to have enough target
// space to copy the socket name, it doesn't have to be correlated
// with the address family. So the maximum space for any name,
// regardless of the family, does the job.
::getsockname(m_iSocket, (addr.get()), (&addr.syslen()));
return addr;
}
sockaddr_any CChannel::getPeerAddr() const
{
sockaddr_any addr;
::getpeername(m_iSocket, (addr.get()), (&addr.syslen()));
return addr;
}
int CChannel::sendto(const sockaddr_any& addr, CPacket& packet, const CNetworkInterface& source_ni SRT_ATR_UNUSED) const
{
#if HVU_ENABLE_HEAVY_LOGGING
ostringstream dsrc;
#ifdef SRT_ENABLE_PKTINFO
if (m_bBindMasked && !source_ni.address.isany())
{
dsrc << " sourceNI=" << source_ni.str();
}
else
{
dsrc << " sourceNI=default";
}
#endif
LOGC(kslog.Debug,
log << "CChannel::sendto: SENDING NOW DST=" << addr.str() << " target=@" << packet.id()
<< " size=" << packet.getLength() << " pkt.ts=" << packet.timestamp()
<< dsrc.str() << " " << packet.Info());
#endif
#ifdef SRT_TEST_FAKE_LOSS
#define FAKELOSS_STRING_0(x) #x
#define FAKELOSS_STRING(x) FAKELOSS_STRING_0(x)
const char* fakeloss_text = FAKELOSS_STRING(SRT_TEST_FAKE_LOSS);
#undef FAKELOSS_STRING
#undef FAKELOSS_WRAP
static int dcounter = 0;
static int flwcounter = 0;
struct FakelossConfig
{
pair<int, int> config;
FakelossConfig(const char* f)
{
vector<string> out;
Split(f, '+', back_inserter(out));
config.first = atoi(out[0].c_str());
config.second = out.size() > 1 ? atoi(out[1].c_str()) : 8;
}
};
static FakelossConfig fakeloss = fakeloss_text;
if (!packet.isControl())
{
++dcounter;
if (flwcounter)
{
// This is a counter of how many packets in a row shall be lost
--flwcounter;
HLOGC(kslog.Debug,
log << "CChannel: TEST: FAKE LOSS OF %" << packet.getSeqNo() << " (" << flwcounter
<< " more to drop)");
return packet.getLength(); // fake successful sendinf
}
if (dcounter > 8)
{
// Make a random number in the range between 8 and 24
const int rnd = sync::genRandomInt(8, 24);
if (dcounter > rnd)
{
dcounter = 1;
HLOGC(kslog.Debug,
log << "CChannel: TEST: FAKE LOSS OF %" << packet.getSeqNo() << " (will drop "
<< fakeloss.config.first << " more)");
flwcounter = fakeloss.config.first;
return packet.getLength(); // fake successful sendinf
}
}
}
#endif
// convert control information into network order
packet.toNetworkByteOrder();
#ifndef _WIN32
msghdr mh;
mh.msg_name = (sockaddr*)&addr;
mh.msg_namelen = addr.size();
mh.msg_iov = (iovec*)packet.m_PacketVector;
mh.msg_iovlen = 2;
bool have_set_src = false;
#ifdef SRT_ENABLE_PKTINFO
// Note that even if PKTINFO is desired, the first caller's packet will be sent
// without ancillary info anyway because there's no "peer" yet to know where to send it.
char mh_crtl_buf[sizeof(CMSGNodeIPv4) + sizeof(CMSGNodeIPv6)];
if (m_bBindMasked && source_ni.address.family() != AF_UNSPEC && !source_ni.address.isany())
{
if (!setSourceAddress(mh, mh_crtl_buf, source_ni))
{
LOGC(kslog.Error, log << "CChannel::setSourceAddress: source address invalid family #" << source_ni.address.family() << ", NOT setting.");
}
else
{
HLOGC(kslog.Debug, log << "CChannel::setSourceAddress: setting as " << source_ni.str());
have_set_src = true;
}
}
#endif
if (!have_set_src)
{
mh.msg_control = NULL;
mh.msg_controllen = 0;
}
mh.msg_flags = 0;
const int res = (int)::sendmsg(m_iSocket.load(), &mh, 0);
#else
class WSAEventRef
{
public:
WSAEventRef()
: e(::WSACreateEvent())
{
}
~WSAEventRef()
{
::WSACloseEvent(e);
e = NULL;
}
void reset()
{
::WSAResetEvent(e);
}
WSAEVENT Handle()
{
return e;
}
private:
WSAEVENT e;
};
#if !defined(__MINGW32__) && defined(ENABLE_CXX11)
thread_local WSAEventRef lEvent;
#else
WSAEventRef lEvent;
#endif
WSAOVERLAPPED overlapped;
::SecureZeroMemory(&overlapped, sizeof(overlapped));
overlapped.hEvent = lEvent.Handle();
DWORD size = (DWORD)(packet.m_PacketVector[0].size() + packet.m_PacketVector[1].size());
int addrsize = addr.size();
int res = ::WSASendTo(m_iSocket.load(), (LPWSABUF)packet.m_PacketVector, 2, &size, 0, addr.get(), addrsize, &overlapped, NULL);
if (res == SOCKET_ERROR)
{
if (NET_ERROR == WSA_IO_PENDING)
{
DWORD dwFlags = 0;
const bool bCompleted = WSAGetOverlappedResult(m_iSocket.load(), &overlapped, &size, TRUE, &dwFlags);
if (bCompleted)
res = 0;
else
LOGC(kslog.Warn, log << "CChannel::sendto call on ::WSAGetOverlappedResult failed with error: " << NET_ERROR);
lEvent.reset();
}
else
{
LOGC(kmlog.Error, log << CONID() << "WSASendTo failed with error: " << NET_ERROR);
}
}
res = (0 == res) ? size : -1;
#endif
packet.toHostByteOrder();
return res;
}
EReadStatus CChannel::recvfrom(sockaddr_any& w_addr, CPacket& w_packet) const
{
EReadStatus status = RST_OK;
int msg_flags = 0;
int recv_size = -1;
#if defined(UNIX) || defined(_WIN32)
fd_set set;
timeval tv;
FD_ZERO(&set);
FD_SET(m_iSocket.load(), &set);
tv.tv_sec = 0;
tv.tv_usec = 10000;
const int select_ret = ::select(int(m_iSocket) + 1, &set, NULL, &set, &tv);
#else
const int select_ret = 1; // the socket is expected to be in the blocking mode itself
#endif
if (select_ret == 0) // timeout
{
w_packet.setLength(-1);
return RST_AGAIN;
}
#ifndef _WIN32
msghdr mh; // will not be used on failure
#ifdef SRT_ENABLE_PKTINFO