channel.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. /*
  2. * SRT - Secure, Reliable, Transport
  3. * Copyright (c) 2018 Haivision Systems Inc.
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. *
  9. */
  10. /*****************************************************************************
  11. Copyright (c) 2001 - 2011, The Board of Trustees of the University of Illinois.
  12. All rights reserved.
  13. Redistribution and use in source and binary forms, with or without
  14. modification, are permitted provided that the following conditions are
  15. met:
  16. * Redistributions of source code must retain the above
  17. copyright notice, this list of conditions and the
  18. following disclaimer.
  19. * Redistributions in binary form must reproduce the
  20. above copyright notice, this list of conditions
  21. and the following disclaimer in the documentation
  22. and/or other materials provided with the distribution.
  23. * Neither the name of the University of Illinois
  24. nor the names of its contributors may be used to
  25. endorse or promote products derived from this
  26. software without specific prior written permission.
  27. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
  28. IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
  29. THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  30. PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  31. CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  32. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  33. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  34. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  35. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  36. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  37. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. ****************************************************************************/
  39. /****************************************************************************
  40. written by
  41. Yunhong Gu, last updated 01/27/2011
  42. modified by
  43. Haivision Systems Inc.
  44. *****************************************************************************/
  45. #include "platform_sys.h"
  46. #include <iostream>
  47. #include <iomanip> // Logging
  48. #include <srt_compat.h>
  49. #include <csignal>
  50. #include "channel.h"
  51. #include "core.h" // srt_logging:kmlog
  52. #include "packet.h"
  53. #include "logging.h"
  54. #include "netinet_any.h"
  55. #include "utilities.h"
  56. #ifdef _WIN32
  57. typedef int socklen_t;
  58. #endif
  59. using namespace std;
  60. using namespace srt_logging;
  61. namespace srt
  62. {
  63. #ifdef _WIN32
  64. // use INVALID_SOCKET, as provided
  65. #else
  66. static const int INVALID_SOCKET = -1;
  67. #endif
  68. #if ENABLE_SOCK_CLOEXEC
  69. #ifndef _WIN32
  70. #if defined(_AIX) || defined(__APPLE__) || defined(__DragonFly__) || defined(__FreeBSD__) || \
  71. defined(__FreeBSD_kernel__) || defined(__linux__) || defined(__OpenBSD__) || defined(__NetBSD__)
  72. // Set the CLOEXEC flag using ioctl() function
  73. static int set_cloexec(int fd, int set)
  74. {
  75. int r;
  76. do
  77. r = ioctl(fd, set ? FIOCLEX : FIONCLEX);
  78. while (r == -1 && errno == EINTR);
  79. if (r)
  80. return errno;
  81. return 0;
  82. }
  83. #else
  84. // Set the CLOEXEC flag using fcntl() function
  85. static int set_cloexec(int fd, int set)
  86. {
  87. int flags;
  88. int r;
  89. do
  90. r = fcntl(fd, F_GETFD);
  91. while (r == -1 && errno == EINTR);
  92. if (r == -1)
  93. return errno;
  94. /* Bail out now if already set/clear. */
  95. if (!!(r & FD_CLOEXEC) == !!set)
  96. return 0;
  97. if (set)
  98. flags = r | FD_CLOEXEC;
  99. else
  100. flags = r & ~FD_CLOEXEC;
  101. do
  102. r = fcntl(fd, F_SETFD, flags);
  103. while (r == -1 && errno == EINTR);
  104. if (r)
  105. return errno;
  106. return 0;
  107. }
  108. #endif // if defined(_AIX) ...
  109. #endif // ifndef _WIN32
  110. #endif // if ENABLE_CLOEXEC
  111. } // namespace srt
  112. srt::CChannel::CChannel()
  113. : m_iSocket(INVALID_SOCKET)
  114. #ifdef SRT_ENABLE_PKTINFO
  115. , m_bBindMasked(true)
  116. #endif
  117. {
  118. #ifdef SRT_ENABLE_PKTINFO
  119. // Do the check for ancillary data buffer size, kinda assertion
  120. static const size_t CMSG_MAX_SPACE = sizeof (CMSGNodeIPv4) + sizeof (CMSGNodeIPv6);
  121. if (CMSG_MAX_SPACE < CMSG_SPACE(sizeof(in_pktinfo)) + CMSG_SPACE(sizeof(in6_pktinfo)))
  122. {
  123. LOGC(kmlog.Fatal, log << "Size of CMSG_MAX_SPACE="
  124. << CMSG_MAX_SPACE << " too short for cmsg "
  125. << CMSG_SPACE(sizeof(in_pktinfo)) << ", "
  126. << CMSG_SPACE(sizeof(in6_pktinfo)) << " - PLEASE FIX");
  127. throw CUDTException(MJ_SETUP, MN_NONE, 0);
  128. }
  129. #endif
  130. }
  131. srt::CChannel::~CChannel() {}
  132. void srt::CChannel::createSocket(int family)
  133. {
  134. #if ENABLE_SOCK_CLOEXEC
  135. bool cloexec_flag = false;
  136. // construct an socket
  137. #if defined(SOCK_CLOEXEC)
  138. m_iSocket = ::socket(family, SOCK_DGRAM | SOCK_CLOEXEC, IPPROTO_UDP);
  139. if (m_iSocket == INVALID_SOCKET)
  140. {
  141. m_iSocket = ::socket(family, SOCK_DGRAM, IPPROTO_UDP);
  142. cloexec_flag = true;
  143. }
  144. #else
  145. m_iSocket = ::socket(family, SOCK_DGRAM, IPPROTO_UDP);
  146. cloexec_flag = true;
  147. #endif
  148. #else // ENABLE_SOCK_CLOEXEC
  149. m_iSocket = ::socket(family, SOCK_DGRAM, IPPROTO_UDP);
  150. #endif // ENABLE_SOCK_CLOEXEC
  151. if (m_iSocket == INVALID_SOCKET)
  152. throw CUDTException(MJ_SETUP, MN_NONE, NET_ERROR);
  153. #if ENABLE_SOCK_CLOEXEC
  154. #ifdef _WIN32
  155. // XXX ::SetHandleInformation(hInputWrite, HANDLE_FLAG_INHERIT, 0)
  156. #else
  157. if (cloexec_flag)
  158. {
  159. if (0 != set_cloexec(m_iSocket, 1))
  160. {
  161. throw CUDTException(MJ_SETUP, MN_NONE, NET_ERROR);
  162. }
  163. }
  164. #endif
  165. #endif // ENABLE_SOCK_CLOEXEC
  166. if ((m_mcfg.iIpV6Only != -1) && (family == AF_INET6)) // (not an error if it fails)
  167. {
  168. const int res SRT_ATR_UNUSED =
  169. ::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&m_mcfg.iIpV6Only, sizeof m_mcfg.iIpV6Only);
  170. #if ENABLE_LOGGING
  171. if (res == -1)
  172. {
  173. int err = errno;
  174. char msg[160];
  175. LOGC(kmlog.Error,
  176. log << "::setsockopt: failed to set IPPROTO_IPV6/IPV6_V6ONLY = " << m_mcfg.iIpV6Only << ": "
  177. << SysStrError(err, msg, 159));
  178. }
  179. #endif // ENABLE_LOGGING
  180. }
  181. }
  182. void srt::CChannel::open(const sockaddr_any& addr)
  183. {
  184. createSocket(addr.family());
  185. socklen_t namelen = addr.size();
  186. if (::bind(m_iSocket, &addr.sa, namelen) == -1)
  187. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  188. m_BindAddr = addr;
  189. #ifdef SRT_ENABLE_PKTINFO
  190. m_bBindMasked = m_BindAddr.isany();
  191. #endif
  192. LOGC(kmlog.Debug, log << "CHANNEL: Bound to local address: " << m_BindAddr.str());
  193. setUDPSockOpt();
  194. }
  195. void srt::CChannel::open(int family)
  196. {
  197. createSocket(family);
  198. // sendto or WSASendTo will also automatically bind the socket
  199. addrinfo hints;
  200. addrinfo* res;
  201. memset(&hints, 0, sizeof(struct addrinfo));
  202. hints.ai_flags = AI_PASSIVE;
  203. hints.ai_family = family;
  204. hints.ai_socktype = SOCK_DGRAM;
  205. const int eai = ::getaddrinfo(NULL, "0", &hints, &res);
  206. if (eai != 0)
  207. {
  208. // Controversial a little bit because this function occasionally
  209. // doesn't use errno (here: NET_ERROR for portability), instead
  210. // it returns 0 if succeeded or an error code. This error code
  211. // is passed here then. A controversy is around the fact that
  212. // the receiver of this error has completely no ability to know
  213. // what this error code's domain is, and it definitely isn't
  214. // the same as for errno.
  215. throw CUDTException(MJ_SETUP, MN_NORES, eai);
  216. }
  217. // On Windows ai_addrlen has type size_t (unsigned), while bind takes int.
  218. if (0 != ::bind(m_iSocket, res->ai_addr, (socklen_t)res->ai_addrlen))
  219. {
  220. ::freeaddrinfo(res);
  221. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  222. }
  223. m_BindAddr = sockaddr_any(res->ai_addr, (sockaddr_any::len_t)res->ai_addrlen);
  224. #ifdef SRT_ENABLE_PKTINFO
  225. // We know that this is intentionally bound now to "any",
  226. // so the requester-destination address must be remembered and passed.
  227. m_bBindMasked = true;
  228. #endif
  229. ::freeaddrinfo(res);
  230. HLOGC(kmlog.Debug, log << "CHANNEL: Bound to local address: " << m_BindAddr.str());
  231. setUDPSockOpt();
  232. }
  233. void srt::CChannel::attach(UDPSOCKET udpsock, const sockaddr_any& udpsocks_addr)
  234. {
  235. // The getsockname() call is done before calling it and the
  236. // result is placed into udpsocks_addr.
  237. m_iSocket = udpsock;
  238. m_BindAddr = udpsocks_addr;
  239. setUDPSockOpt();
  240. }
  241. void srt::CChannel::setUDPSockOpt()
  242. {
  243. #if defined(SUNOS)
  244. {
  245. socklen_t optSize;
  246. // Retrieve starting SND/RCV Buffer sizes.
  247. int startRCVBUF = 0;
  248. optSize = sizeof(startRCVBUF);
  249. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&startRCVBUF, &optSize))
  250. {
  251. startRCVBUF = -1;
  252. }
  253. int startSNDBUF = 0;
  254. optSize = sizeof(startSNDBUF);
  255. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (void*)&startSNDBUF, &optSize))
  256. {
  257. startSNDBUF = -1;
  258. }
  259. // SunOS will fail setsockopt() if the requested buffer size exceeds system
  260. // maximum value.
  261. // However, do not reduce the buffer size.
  262. const int maxsize = 64000;
  263. if (0 !=
  264. ::setsockopt(
  265. m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize))
  266. {
  267. int currentRCVBUF = 0;
  268. optSize = sizeof(currentRCVBUF);
  269. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&currentRCVBUF, &optSize))
  270. {
  271. currentRCVBUF = -1;
  272. }
  273. if (maxsize > currentRCVBUF)
  274. {
  275. ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&maxsize, sizeof maxsize);
  276. }
  277. }
  278. if (0 !=
  279. ::setsockopt(
  280. m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize))
  281. {
  282. int currentSNDBUF = 0;
  283. optSize = sizeof(currentSNDBUF);
  284. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&currentSNDBUF, &optSize))
  285. {
  286. currentSNDBUF = -1;
  287. }
  288. if (maxsize > currentSNDBUF)
  289. {
  290. ::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&maxsize, sizeof maxsize);
  291. }
  292. }
  293. // Retrieve ending SND/RCV Buffer sizes.
  294. int endRCVBUF = 0;
  295. optSize = sizeof(endRCVBUF);
  296. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (void*)&endRCVBUF, &optSize))
  297. {
  298. endRCVBUF = -1;
  299. }
  300. int endSNDBUF = 0;
  301. optSize = sizeof(endSNDBUF);
  302. if (0 != ::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (void*)&endSNDBUF, &optSize))
  303. {
  304. endSNDBUF = -1;
  305. }
  306. LOGC(kmlog.Debug,
  307. log << "SO_RCVBUF:"
  308. << " startRCVBUF=" << startRCVBUF << " m_mcfg.iUDPRcvBufSize=" << m_mcfg.iUDPRcvBufSize
  309. << " endRCVBUF=" << endRCVBUF);
  310. LOGC(kmlog.Debug,
  311. log << "SO_SNDBUF:"
  312. << " startSNDBUF=" << startSNDBUF << " m_mcfg.iUDPSndBufSize=" << m_mcfg.iUDPSndBufSize
  313. << " endSNDBUF=" << endSNDBUF);
  314. }
  315. #elif defined(BSD) || TARGET_OS_MAC
  316. // BSD system will fail setsockopt if the requested buffer size exceeds system maximum value
  317. int maxsize = 64000;
  318. if (0 != ::setsockopt(
  319. m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize))
  320. ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&maxsize, sizeof maxsize);
  321. if (0 != ::setsockopt(
  322. m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize))
  323. ::setsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&maxsize, sizeof maxsize);
  324. #else
  325. // for other systems, if requested is greated than maximum, the maximum value will be automactally used
  326. if ((0 !=
  327. ::setsockopt(
  328. m_iSocket, SOL_SOCKET, SO_RCVBUF, (const char*)&m_mcfg.iUDPRcvBufSize, sizeof m_mcfg.iUDPRcvBufSize)) ||
  329. (0 != ::setsockopt(
  330. m_iSocket, SOL_SOCKET, SO_SNDBUF, (const char*)&m_mcfg.iUDPSndBufSize, sizeof m_mcfg.iUDPSndBufSize)))
  331. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  332. #endif
  333. if (m_mcfg.iIpTTL != -1)
  334. {
  335. if (m_BindAddr.family() == AF_INET)
  336. {
  337. if (0 != ::setsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
  338. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  339. }
  340. else
  341. {
  342. // If IPv6 address is unspecified, set BOTH IP_TTL and IPV6_UNICAST_HOPS.
  343. // For specified IPv6 address, set IPV6_UNICAST_HOPS ONLY UNLESS it's an IPv4-mapped-IPv6
  344. if (IN6_IS_ADDR_UNSPECIFIED(&m_BindAddr.sin6.sin6_addr) ||
  345. !IN6_IS_ADDR_V4MAPPED(&m_BindAddr.sin6.sin6_addr))
  346. {
  347. if (0 !=
  348. ::setsockopt(
  349. m_iSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
  350. {
  351. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  352. }
  353. }
  354. // For specified IPv6 address, set IP_TTL ONLY WHEN it's an IPv4-mapped-IPv6
  355. if (IN6_IS_ADDR_UNSPECIFIED(&m_BindAddr.sin6.sin6_addr) || IN6_IS_ADDR_V4MAPPED(&m_BindAddr.sin6.sin6_addr))
  356. {
  357. if (0 != ::setsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (const char*)&m_mcfg.iIpTTL, sizeof m_mcfg.iIpTTL))
  358. {
  359. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  360. }
  361. }
  362. }
  363. }
  364. if (m_mcfg.iIpToS != -1)
  365. {
  366. if (m_BindAddr.family() == AF_INET)
  367. {
  368. if (0 != ::setsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
  369. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  370. }
  371. else
  372. {
  373. // If IPv6 address is unspecified, set BOTH IP_TOS and IPV6_TCLASS.
  374. #ifdef IPV6_TCLASS
  375. // For specified IPv6 address, set IPV6_TCLASS ONLY UNLESS it's an IPv4-mapped-IPv6
  376. if (IN6_IS_ADDR_UNSPECIFIED(&m_BindAddr.sin6.sin6_addr) ||
  377. !IN6_IS_ADDR_V4MAPPED(&m_BindAddr.sin6.sin6_addr))
  378. {
  379. if (0 != ::setsockopt(
  380. m_iSocket, IPPROTO_IPV6, IPV6_TCLASS, (const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
  381. {
  382. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  383. }
  384. }
  385. #endif
  386. // For specified IPv6 address, set IP_TOS ONLY WHEN it's an IPv4-mapped-IPv6
  387. if (IN6_IS_ADDR_UNSPECIFIED(&m_BindAddr.sin6.sin6_addr) || IN6_IS_ADDR_V4MAPPED(&m_BindAddr.sin6.sin6_addr))
  388. {
  389. if (0 != ::setsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (const char*)&m_mcfg.iIpToS, sizeof m_mcfg.iIpToS))
  390. {
  391. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  392. }
  393. }
  394. }
  395. }
  396. #ifdef SRT_ENABLE_BINDTODEVICE
  397. if (!m_mcfg.sBindToDevice.empty())
  398. {
  399. if (m_BindAddr.family() != AF_INET)
  400. {
  401. LOGC(kmlog.Error, log << "SRTO_BINDTODEVICE can only be set with AF_INET connections");
  402. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  403. }
  404. if (0 != ::setsockopt(
  405. m_iSocket, SOL_SOCKET, SO_BINDTODEVICE, m_mcfg.sBindToDevice.c_str(), m_mcfg.sBindToDevice.size()))
  406. {
  407. #if ENABLE_LOGGING
  408. char buf[255];
  409. const char* err = SysStrError(NET_ERROR, buf, 255);
  410. LOGC(kmlog.Error, log << "setsockopt(SRTO_BINDTODEVICE): " << err);
  411. #endif // ENABLE_LOGGING
  412. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  413. }
  414. }
  415. #endif
  416. #ifdef UNIX
  417. // Set non-blocking I/O
  418. // UNIX does not support SO_RCVTIMEO
  419. int opts = ::fcntl(m_iSocket, F_GETFL);
  420. if (-1 == ::fcntl(m_iSocket, F_SETFL, opts | O_NONBLOCK))
  421. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  422. #elif defined(_WIN32)
  423. u_long nonBlocking = 1;
  424. if (0 != ioctlsocket(m_iSocket, FIONBIO, &nonBlocking))
  425. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  426. #else
  427. timeval tv;
  428. tv.tv_sec = 0;
  429. #if defined(BSD) || TARGET_OS_MAC
  430. // Known BSD bug as the day I wrote this code.
  431. // A small time out value will cause the socket to block forever.
  432. tv.tv_usec = 10000;
  433. #else
  434. tv.tv_usec = 100;
  435. #endif
  436. // Set receiving time-out value
  437. if (0 != ::setsockopt(m_iSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(timeval)))
  438. throw CUDTException(MJ_SETUP, MN_NORES, NET_ERROR);
  439. #endif
  440. #ifdef SRT_ENABLE_PKTINFO
  441. if (m_bBindMasked)
  442. {
  443. HLOGP(kmlog.Debug, "Socket bound to ANY - setting PKTINFO for address retrieval");
  444. const int on = 1, off SRT_ATR_UNUSED = 0;
  445. if (m_BindAddr.family() == AF_INET || m_mcfg.iIpV6Only == 0)
  446. {
  447. ::setsockopt(m_iSocket, IPPROTO_IP, IP_PKTINFO, (char*)&on, sizeof(on));
  448. }
  449. if (m_BindAddr.family() == AF_INET6)
  450. {
  451. ::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof(on));
  452. }
  453. // XXX Unknown why this has to be off. RETEST.
  454. //::setsockopt(m_iSocket, IPPROTO_IPV6, IPV6_V6ONLY, &off, sizeof(off));
  455. }
  456. #endif
  457. }
  458. void srt::CChannel::close() const
  459. {
  460. #ifndef _WIN32
  461. ::close(m_iSocket);
  462. #else
  463. ::closesocket(m_iSocket);
  464. #endif
  465. }
  466. int srt::CChannel::getSndBufSize()
  467. {
  468. socklen_t size = (socklen_t)sizeof m_mcfg.iUDPSndBufSize;
  469. ::getsockopt(m_iSocket, SOL_SOCKET, SO_SNDBUF, (char*)&m_mcfg.iUDPSndBufSize, &size);
  470. return m_mcfg.iUDPSndBufSize;
  471. }
  472. int srt::CChannel::getRcvBufSize()
  473. {
  474. socklen_t size = (socklen_t)sizeof m_mcfg.iUDPRcvBufSize;
  475. ::getsockopt(m_iSocket, SOL_SOCKET, SO_RCVBUF, (char*)&m_mcfg.iUDPRcvBufSize, &size);
  476. return m_mcfg.iUDPRcvBufSize;
  477. }
  478. void srt::CChannel::setConfig(const CSrtMuxerConfig& config)
  479. {
  480. m_mcfg = config;
  481. }
  482. void srt::CChannel::getSocketOption(int level, int option, char* pw_dataptr, socklen_t& w_len, int& w_status)
  483. {
  484. w_status = ::getsockopt(m_iSocket, level, option, (pw_dataptr), (&w_len));
  485. }
  486. int srt::CChannel::getIpTTL() const
  487. {
  488. if (m_iSocket == INVALID_SOCKET)
  489. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  490. socklen_t size = (socklen_t)sizeof m_mcfg.iIpTTL;
  491. if (m_BindAddr.family() == AF_INET)
  492. {
  493. ::getsockopt(m_iSocket, IPPROTO_IP, IP_TTL, (char*)&m_mcfg.iIpTTL, &size);
  494. }
  495. else if (m_BindAddr.family() == AF_INET6)
  496. {
  497. ::getsockopt(m_iSocket, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (char*)&m_mcfg.iIpTTL, &size);
  498. }
  499. else
  500. {
  501. // If family is unspecified, the socket probably doesn't exist.
  502. LOGC(kmlog.Error, log << "IPE: CChannel::getIpTTL called with unset family");
  503. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  504. }
  505. return m_mcfg.iIpTTL;
  506. }
  507. int srt::CChannel::getIpToS() const
  508. {
  509. if (m_iSocket == INVALID_SOCKET)
  510. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  511. socklen_t size = (socklen_t)sizeof m_mcfg.iIpToS;
  512. if (m_BindAddr.family() == AF_INET)
  513. {
  514. ::getsockopt(m_iSocket, IPPROTO_IP, IP_TOS, (char*)&m_mcfg.iIpToS, &size);
  515. }
  516. else if (m_BindAddr.family() == AF_INET6)
  517. {
  518. #ifdef IPV6_TCLASS
  519. ::getsockopt(m_iSocket, IPPROTO_IPV6, IPV6_TCLASS, (char*)&m_mcfg.iIpToS, &size);
  520. #endif
  521. }
  522. else
  523. {
  524. // If family is unspecified, the socket probably doesn't exist.
  525. LOGC(kmlog.Error, log << "IPE: CChannel::getIpToS called with unset family");
  526. throw CUDTException(MJ_NOTSUP, MN_INVAL, 0);
  527. }
  528. return m_mcfg.iIpToS;
  529. }
  530. #ifdef SRT_ENABLE_BINDTODEVICE
  531. bool srt::CChannel::getBind(char* dst, size_t len)
  532. {
  533. if (m_iSocket == INVALID_SOCKET)
  534. return false; // No socket to get data from
  535. // Try to obtain it directly from the function. If not possible,
  536. // then return from internal data.
  537. socklen_t length = len;
  538. int res = ::getsockopt(m_iSocket, SOL_SOCKET, SO_BINDTODEVICE, dst, &length);
  539. if (res == -1)
  540. return false; // Happens on Linux v < 3.8
  541. // For any case
  542. dst[length] = 0;
  543. return true;
  544. }
  545. #endif
  546. int srt::CChannel::ioctlQuery(int type SRT_ATR_UNUSED) const
  547. {
  548. #if defined(unix) || defined(__APPLE__)
  549. int value = 0;
  550. int res = ::ioctl(m_iSocket, type, &value);
  551. if (res != -1)
  552. return value;
  553. #endif
  554. return -1;
  555. }
  556. int srt::CChannel::sockoptQuery(int level SRT_ATR_UNUSED, int option SRT_ATR_UNUSED) const
  557. {
  558. #if defined(unix) || defined(__APPLE__)
  559. int value = 0;
  560. socklen_t len = sizeof(int);
  561. int res = ::getsockopt(m_iSocket, level, option, &value, &len);
  562. if (res != -1)
  563. return value;
  564. #endif
  565. return -1;
  566. }
  567. void srt::CChannel::getSockAddr(sockaddr_any& w_addr) const
  568. {
  569. // The getsockname function requires only to have enough target
  570. // space to copy the socket name, it doesn't have to be correlated
  571. // with the address family. So the maximum space for any name,
  572. // regardless of the family, does the job.
  573. socklen_t namelen = (socklen_t)w_addr.storage_size();
  574. ::getsockname(m_iSocket, (w_addr.get()), (&namelen));
  575. w_addr.len = namelen;
  576. }
  577. void srt::CChannel::getPeerAddr(sockaddr_any& w_addr) const
  578. {
  579. socklen_t namelen = (socklen_t)w_addr.storage_size();
  580. ::getpeername(m_iSocket, (w_addr.get()), (&namelen));
  581. w_addr.len = namelen;
  582. }
  583. int srt::CChannel::sendto(const sockaddr_any& addr, CPacket& packet, const sockaddr_any& source_addr SRT_ATR_UNUSED) const
  584. {
  585. #if ENABLE_HEAVY_LOGGING
  586. ostringstream dsrc;
  587. #ifdef SRT_ENABLE_PKTINFO
  588. dsrc << " sourceIP=" << (m_bBindMasked && !source_addr.isany() ? source_addr.str() : "default");
  589. #endif
  590. LOGC(kslog.Debug,
  591. log << "CChannel::sendto: SENDING NOW DST=" << addr.str() << " target=@" << packet.m_iID
  592. << " size=" << packet.getLength() << " pkt.ts=" << packet.m_iTimeStamp
  593. << dsrc.str() << " " << packet.Info());
  594. #endif
  595. #ifdef SRT_TEST_FAKE_LOSS
  596. #define FAKELOSS_STRING_0(x) #x
  597. #define FAKELOSS_STRING(x) FAKELOSS_STRING_0(x)
  598. const char* fakeloss_text = FAKELOSS_STRING(SRT_TEST_FAKE_LOSS);
  599. #undef FAKELOSS_STRING
  600. #undef FAKELOSS_WRAP
  601. static int dcounter = 0;
  602. static int flwcounter = 0;
  603. struct FakelossConfig
  604. {
  605. pair<int, int> config;
  606. FakelossConfig(const char* f)
  607. {
  608. vector<string> out;
  609. Split(f, '+', back_inserter(out));
  610. config.first = atoi(out[0].c_str());
  611. config.second = out.size() > 1 ? atoi(out[1].c_str()) : 8;
  612. }
  613. };
  614. static FakelossConfig fakeloss = fakeloss_text;
  615. if (!packet.isControl())
  616. {
  617. ++dcounter;
  618. if (flwcounter)
  619. {
  620. // This is a counter of how many packets in a row shall be lost
  621. --flwcounter;
  622. HLOGC(kslog.Debug,
  623. log << "CChannel: TEST: FAKE LOSS OF %" << packet.getSeqNo() << " (" << flwcounter
  624. << " more to drop)");
  625. return packet.getLength(); // fake successful sendinf
  626. }
  627. if (dcounter > 8)
  628. {
  629. // Make a random number in the range between 8 and 24
  630. const int rnd = srt::sync::genRandomInt(8, 24);
  631. if (dcounter > rnd)
  632. {
  633. dcounter = 1;
  634. HLOGC(kslog.Debug,
  635. log << "CChannel: TEST: FAKE LOSS OF %" << packet.getSeqNo() << " (will drop "
  636. << fakeloss.config.first << " more)");
  637. flwcounter = fakeloss.config.first;
  638. return packet.getLength(); // fake successful sendinf
  639. }
  640. }
  641. }
  642. #endif
  643. // convert control information into network order
  644. packet.toNL();
  645. #ifndef _WIN32
  646. msghdr mh;
  647. mh.msg_name = (sockaddr*)&addr;
  648. mh.msg_namelen = addr.size();
  649. mh.msg_iov = (iovec*)packet.m_PacketVector;
  650. mh.msg_iovlen = 2;
  651. bool have_set_src = false;
  652. #ifdef SRT_ENABLE_PKTINFO
  653. // Note that even if PKTINFO is desired, the first caller's packet will be sent
  654. // without ancillary info anyway because there's no "peer" yet to know where to send it.
  655. if (m_bBindMasked && source_addr.family() != AF_UNSPEC && !source_addr.isany())
  656. {
  657. if (!setSourceAddress(mh, source_addr))
  658. {
  659. LOGC(kslog.Error, log << "CChannel::setSourceAddress: source address invalid family #" << source_addr.family() << ", NOT setting.");
  660. }
  661. else
  662. {
  663. HLOGC(kslog.Debug, log << "CChannel::setSourceAddress: setting as " << source_addr.str());
  664. have_set_src = true;
  665. }
  666. }
  667. #endif
  668. if (!have_set_src)
  669. {
  670. mh.msg_control = NULL;
  671. mh.msg_controllen = 0;
  672. }
  673. mh.msg_flags = 0;
  674. const int res = (int)::sendmsg(m_iSocket, &mh, 0);
  675. #else
  676. DWORD size = (DWORD)(CPacket::HDR_SIZE + packet.getLength());
  677. int addrsize = addr.size();
  678. WSAOVERLAPPED overlapped;
  679. SecureZeroMemory((PVOID)&overlapped, sizeof(WSAOVERLAPPED));
  680. int res = ::WSASendTo(m_iSocket, (LPWSABUF)packet.m_PacketVector, 2, &size, 0, addr.get(), addrsize, &overlapped, NULL);
  681. if (res == SOCKET_ERROR && NET_ERROR == WSA_IO_PENDING)
  682. {
  683. DWORD dwFlags = 0;
  684. const bool bCompleted = WSAGetOverlappedResult(m_iSocket, &overlapped, &size, true, &dwFlags);
  685. WSACloseEvent(overlapped.hEvent);
  686. res = bCompleted ? 0 : -1;
  687. }
  688. res = (0 == res) ? size : -1;
  689. #endif
  690. packet.toHL();
  691. return res;
  692. }
  693. srt::EReadStatus srt::CChannel::recvfrom(sockaddr_any& w_addr, CPacket& w_packet) const
  694. {
  695. EReadStatus status = RST_OK;
  696. int msg_flags = 0;
  697. int recv_size = -1;
  698. #if defined(UNIX) || defined(_WIN32)
  699. fd_set set;
  700. timeval tv;
  701. FD_ZERO(&set);
  702. FD_SET(m_iSocket, &set);
  703. tv.tv_sec = 0;
  704. tv.tv_usec = 10000;
  705. const int select_ret = ::select((int)m_iSocket + 1, &set, NULL, &set, &tv);
  706. #else
  707. const int select_ret = 1; // the socket is expected to be in the blocking mode itself
  708. #endif
  709. if (select_ret == 0) // timeout
  710. {
  711. w_packet.setLength(-1);
  712. return RST_AGAIN;
  713. }
  714. #ifndef _WIN32
  715. msghdr mh; // will not be used on failure
  716. if (select_ret > 0)
  717. {
  718. mh.msg_name = (w_addr.get());
  719. mh.msg_namelen = w_addr.size();
  720. mh.msg_iov = (w_packet.m_PacketVector);
  721. mh.msg_iovlen = 2;
  722. // Default
  723. mh.msg_control = NULL;
  724. mh.msg_controllen = 0;
  725. #ifdef SRT_ENABLE_PKTINFO
  726. // Without m_bBindMasked, we don't need ancillary data - the source
  727. // address will always be the bound address.
  728. if (m_bBindMasked)
  729. {
  730. // Extract the destination IP address from the ancillary
  731. // data. This might be interesting for the connection to
  732. // know to which address the packet should be sent back during
  733. // the handshake and then addressed when sending during connection.
  734. mh.msg_control = (m_acCmsgRecvBuffer);
  735. mh.msg_controllen = sizeof m_acCmsgRecvBuffer;
  736. }
  737. #endif
  738. mh.msg_flags = 0;
  739. recv_size = (int)::recvmsg(m_iSocket, (&mh), 0);
  740. msg_flags = mh.msg_flags;
  741. }
  742. // Note that there are exactly four groups of possible errors
  743. // reported by recvmsg():
  744. // 1. Temporary error, can't get the data, but you can try again.
  745. // Codes: EAGAIN/EWOULDBLOCK, EINTR, ECONNREFUSED
  746. // Return: RST_AGAIN.
  747. //
  748. // 2. Problems that should never happen due to unused configurations.
  749. // Codes: ECONNREFUSED, ENOTCONN
  750. // Return: RST_ERROR, just formally treat this as IPE.
  751. //
  752. // 3. Unexpected runtime errors:
  753. // Codes: EINVAL, EFAULT, ENOMEM, ENOTSOCK
  754. // Return: RST_ERROR. Except ENOMEM, this can only be an IPE. ENOMEM
  755. // should make the program stop as lacking memory will kill the program anyway soon.
  756. //
  757. // 4. Expected socket closed in the meantime by another thread.
  758. // Codes: EBADF
  759. // Return: RST_ERROR. This will simply make the worker thread exit, which is
  760. // expected to happen after CChannel::close() is called by another thread.
  761. // We do not handle <= SOCKET_ERROR as they are handled further by checking the recv_size
  762. if (select_ret == -1 || recv_size == -1)
  763. {
  764. const int err = NET_ERROR;
  765. if (err == EAGAIN || err == EINTR ||
  766. err == ECONNREFUSED) // For EAGAIN, this isn't an error, just a useless call.
  767. {
  768. status = RST_AGAIN;
  769. }
  770. else
  771. {
  772. HLOGC(krlog.Debug, log << CONID() << "(sys)recvmsg: " << SysStrError(err) << " [" << err << "]");
  773. status = RST_ERROR;
  774. }
  775. goto Return_error;
  776. }
  777. #ifdef SRT_ENABLE_PKTINFO
  778. if (m_bBindMasked)
  779. {
  780. // Extract the address. Set it explicitly; if this returns address that isany(),
  781. // it will simply set this on the packet so that it behaves as if nothing was
  782. // extracted (it will "fail the old way").
  783. w_packet.m_DestAddr = getTargetAddress(mh);
  784. HLOGC(krlog.Debug, log << CONID() << "(sys)recvmsg: ANY BOUND, retrieved DEST ADDR: " << w_packet.m_DestAddr.str());
  785. }
  786. #endif
  787. #else
  788. // XXX REFACTORING NEEDED!
  789. // This procedure uses the WSARecvFrom function that just reads
  790. // into one buffer. On Windows, the equivalent for recvmsg, WSARecvMsg
  791. // uses the equivalent of msghdr - WSAMSG, which has different field
  792. // names and also uses the equivalet of iovec - WSABUF, which has different
  793. // field names and layout. It is important that this code be translated
  794. // to the "proper" solution, however this requires that CPacket::m_PacketVector
  795. // also uses the "platform independent" (or, better, platform-suitable) type
  796. // which can be appropriate for the appropriate system function, not just iovec
  797. // (see a specifically provided definition for iovec for windows in packet.h).
  798. //
  799. // For the time being, the msg_flags variable is defined in both cases
  800. // so that it can be checked independently, however it won't have any other
  801. // value one Windows than 0, unless this procedure below is rewritten
  802. // to use WSARecvMsg().
  803. int recv_ret = SOCKET_ERROR;
  804. DWORD flag = 0;
  805. if (select_ret > 0) // the total number of socket handles that are ready
  806. {
  807. DWORD size = (DWORD)(CPacket::HDR_SIZE + w_packet.getLength());
  808. int addrsize = w_addr.size();
  809. recv_ret = ::WSARecvFrom(m_iSocket,
  810. ((LPWSABUF)w_packet.m_PacketVector),
  811. 2,
  812. (&size),
  813. (&flag),
  814. (w_addr.get()),
  815. (&addrsize),
  816. NULL,
  817. NULL);
  818. if (recv_ret == 0)
  819. recv_size = size;
  820. }
  821. // We do not handle <= SOCKET_ERROR as they are handled further by checking the recv_size
  822. if (select_ret == SOCKET_ERROR || recv_ret == SOCKET_ERROR) // == SOCKET_ERROR
  823. {
  824. recv_size = -1;
  825. // On Windows this is a little bit more complicated, so simply treat every error
  826. // as an "again" situation. This should still be probably fixed, but it needs more
  827. // thorough research. For example, the problem usually reported from here is
  828. // WSAETIMEDOUT, which isn't mentioned in the documentation of WSARecvFrom at all.
  829. //
  830. // These below errors are treated as "fatal", all others are treated as "again".
  831. static const int fatals[] = {WSAEFAULT, WSAEINVAL, WSAENETDOWN, WSANOTINITIALISED, WSA_OPERATION_ABORTED};
  832. static const int* fatals_end = fatals + Size(fatals);
  833. const int err = NET_ERROR;
  834. if (std::find(fatals, fatals_end, err) != fatals_end)
  835. {
  836. HLOGC(krlog.Debug, log << CONID() << "(sys)WSARecvFrom: " << SysStrError(err) << " [" << err << "]");
  837. status = RST_ERROR;
  838. }
  839. else
  840. {
  841. status = RST_AGAIN;
  842. }
  843. goto Return_error;
  844. }
  845. // Not sure if this problem has ever occurred on Windows, just a sanity check.
  846. if (flag & MSG_PARTIAL)
  847. msg_flags = 1;
  848. #endif
  849. // Sanity check for a case when it didn't fill in even the header
  850. if (size_t(recv_size) < CPacket::HDR_SIZE)
  851. {
  852. status = RST_AGAIN;
  853. HLOGC(krlog.Debug,
  854. log << CONID() << "POSSIBLE ATTACK: received too short packet with " << recv_size << " bytes");
  855. goto Return_error;
  856. }
  857. // Fix for an issue with Linux Kernel found during tests at Tencent.
  858. //
  859. // There was a bug in older Linux Kernel which caused that when the internal
  860. // buffer was depleted during reading from the network, not the whole buffer
  861. // was copied from the packet, EVEN THOUGH THE GIVEN BUFFER WAS OF ENOUGH SIZE.
  862. // It was still very kind of the buggy procedure, though, that at least
  863. // they inform the caller about that this has happened by setting MSG_TRUNC
  864. // flag.
  865. //
  866. // Normally this flag should be set only if there was too small buffer given
  867. // by the caller, so as this code knows that the size is enough, it never
  868. // predicted this to happen. Just for a case then when you run this on a buggy
  869. // system that suffers of this problem, the fix for this case is left here.
  870. //
  871. // When this happens, then you have at best a fragment of the buffer and it's
  872. // useless anyway. This is solved by dropping the packet and fake that no
  873. // packet was received, so the packet will be then retransmitted.
  874. if (msg_flags != 0)
  875. {
  876. #if ENABLE_HEAVY_LOGGING
  877. std::ostringstream flg;
  878. #if !defined(_WIN32)
  879. static const pair<int, const char* const> errmsgflg [] = {
  880. make_pair<int>(MSG_OOB, "OOB"),
  881. make_pair<int>(MSG_EOR, "EOR"),
  882. make_pair<int>(MSG_TRUNC, "TRUNC"),
  883. make_pair<int>(MSG_CTRUNC, "CTRUNC")
  884. };
  885. for (size_t i = 0; i < Size(errmsgflg); ++i)
  886. if ((msg_flags & errmsgflg[i].first) != 0)
  887. flg << " " << errmsgflg[i].second;
  888. // This doesn't work the same way on Windows, so on Windows just skip it.
  889. #endif
  890. HLOGC(krlog.Debug,
  891. log << CONID() << "NET ERROR: packet size=" << recv_size << " msg_flags=0x" << hex << msg_flags
  892. << ", detected flags:" << flg.str());
  893. #endif
  894. status = RST_AGAIN;
  895. goto Return_error;
  896. }
  897. w_packet.setLength(recv_size - CPacket::HDR_SIZE);
  898. // convert back into local host order
  899. // XXX use NtoHLA().
  900. // for (int i = 0; i < 4; ++ i)
  901. // w_packet.m_nHeader[i] = ntohl(w_packet.m_nHeader[i]);
  902. {
  903. uint32_t* p = w_packet.m_nHeader;
  904. for (size_t i = 0; i < SRT_PH_E_SIZE; ++i)
  905. {
  906. *p = ntohl(*p);
  907. ++p;
  908. }
  909. }
  910. if (w_packet.isControl())
  911. {
  912. for (size_t j = 0, n = w_packet.getLength() / sizeof(uint32_t); j < n; ++j)
  913. *((uint32_t*)w_packet.m_pcData + j) = ntohl(*((uint32_t*)w_packet.m_pcData + j));
  914. }
  915. return RST_OK;
  916. Return_error:
  917. w_packet.setLength(-1);
  918. return status;
  919. }