You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1940 lines
57 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright 2004 The WebRTC Project Authors. All rights reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #include "rtc_base/physical_socket_server.h"
  11. #if defined(_MSC_VER) && _MSC_VER < 1300
  12. #pragma warning(disable : 4786)
  13. #endif
  14. #ifdef MEMORY_SANITIZER
  15. #include <sanitizer/msan_interface.h>
  16. #endif
  17. #if defined(WEBRTC_POSIX)
  18. #include <fcntl.h>
  19. #include <string.h>
  20. #if defined(WEBRTC_USE_EPOLL)
  21. // "poll" will be used to wait for the signal dispatcher.
  22. #include <poll.h>
  23. #endif
  24. #include <signal.h>
  25. #include <sys/ioctl.h>
  26. #include <sys/select.h>
  27. #include <sys/time.h>
  28. #include <unistd.h>
  29. #endif
  30. #if defined(WEBRTC_WIN)
  31. #include <windows.h>
  32. #include <winsock2.h>
  33. #include <ws2tcpip.h>
  34. #undef SetPort
  35. #endif
  36. #include <errno.h>
  37. #include <algorithm>
  38. #include <map>
  39. #include "rtc_base/arraysize.h"
  40. #include "rtc_base/byte_order.h"
  41. #include "rtc_base/checks.h"
  42. #include "rtc_base/logging.h"
  43. #include "rtc_base/network_monitor.h"
  44. #include "rtc_base/null_socket_server.h"
  45. #include "rtc_base/time_utils.h"
  46. #if defined(WEBRTC_LINUX)
  47. #include <linux/sockios.h>
  48. #endif
  49. #if defined(WEBRTC_WIN)
  50. #define LAST_SYSTEM_ERROR (::GetLastError())
  51. #elif defined(__native_client__) && __native_client__
  52. #define LAST_SYSTEM_ERROR (0)
  53. #elif defined(WEBRTC_POSIX)
  54. #define LAST_SYSTEM_ERROR (errno)
  55. #endif // WEBRTC_WIN
  56. #if defined(WEBRTC_POSIX)
  57. #include <netinet/tcp.h> // for TCP_NODELAY
  58. #define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
  59. typedef void* SockOptArg;
  60. #endif // WEBRTC_POSIX
  61. #if defined(WEBRTC_POSIX) && !defined(WEBRTC_MAC) && !defined(__native_client__)
  62. int64_t GetSocketRecvTimestamp(int socket) {
  63. struct timeval tv_ioctl;
  64. int ret = ioctl(socket, SIOCGSTAMP, &tv_ioctl);
  65. if (ret != 0)
  66. return -1;
  67. int64_t timestamp =
  68. rtc::kNumMicrosecsPerSec * static_cast<int64_t>(tv_ioctl.tv_sec) +
  69. static_cast<int64_t>(tv_ioctl.tv_usec);
  70. return timestamp;
  71. }
  72. #else
  73. int64_t GetSocketRecvTimestamp(int socket) {
  74. return -1;
  75. }
  76. #endif
  77. #if defined(WEBRTC_WIN)
  78. typedef char* SockOptArg;
  79. #endif
  80. #if defined(WEBRTC_USE_EPOLL)
  81. // POLLRDHUP / EPOLLRDHUP are only defined starting with Linux 2.6.17.
  82. #if !defined(POLLRDHUP)
  83. #define POLLRDHUP 0x2000
  84. #endif
  85. #if !defined(EPOLLRDHUP)
  86. #define EPOLLRDHUP 0x2000
  87. #endif
  88. #endif
  89. namespace rtc {
  90. std::unique_ptr<SocketServer> SocketServer::CreateDefault() {
  91. #if defined(__native_client__)
  92. return std::unique_ptr<SocketServer>(new rtc::NullSocketServer);
  93. #else
  94. return std::unique_ptr<SocketServer>(new rtc::PhysicalSocketServer);
  95. #endif
  96. }
  97. PhysicalSocket::PhysicalSocket(PhysicalSocketServer* ss, SOCKET s)
  98. : ss_(ss),
  99. s_(s),
  100. error_(0),
  101. state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
  102. resolver_(nullptr) {
  103. if (s_ != INVALID_SOCKET) {
  104. SetEnabledEvents(DE_READ | DE_WRITE);
  105. int type = SOCK_STREAM;
  106. socklen_t len = sizeof(type);
  107. const int res =
  108. getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len);
  109. RTC_DCHECK_EQ(0, res);
  110. udp_ = (SOCK_DGRAM == type);
  111. }
  112. }
  113. PhysicalSocket::~PhysicalSocket() {
  114. Close();
  115. }
  116. bool PhysicalSocket::Create(int family, int type) {
  117. Close();
  118. s_ = ::socket(family, type, 0);
  119. udp_ = (SOCK_DGRAM == type);
  120. UpdateLastError();
  121. if (udp_) {
  122. SetEnabledEvents(DE_READ | DE_WRITE);
  123. }
  124. return s_ != INVALID_SOCKET;
  125. }
  126. SocketAddress PhysicalSocket::GetLocalAddress() const {
  127. sockaddr_storage addr_storage = {0};
  128. socklen_t addrlen = sizeof(addr_storage);
  129. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  130. int result = ::getsockname(s_, addr, &addrlen);
  131. SocketAddress address;
  132. if (result >= 0) {
  133. SocketAddressFromSockAddrStorage(addr_storage, &address);
  134. } else {
  135. RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
  136. << s_;
  137. }
  138. return address;
  139. }
  140. SocketAddress PhysicalSocket::GetRemoteAddress() const {
  141. sockaddr_storage addr_storage = {0};
  142. socklen_t addrlen = sizeof(addr_storage);
  143. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  144. int result = ::getpeername(s_, addr, &addrlen);
  145. SocketAddress address;
  146. if (result >= 0) {
  147. SocketAddressFromSockAddrStorage(addr_storage, &address);
  148. } else {
  149. RTC_LOG(LS_WARNING)
  150. << "GetRemoteAddress: unable to get remote addr, socket=" << s_;
  151. }
  152. return address;
  153. }
  154. int PhysicalSocket::Bind(const SocketAddress& bind_addr) {
  155. SocketAddress copied_bind_addr = bind_addr;
  156. // If a network binder is available, use it to bind a socket to an interface
  157. // instead of bind(), since this is more reliable on an OS with a weak host
  158. // model.
  159. if (ss_->network_binder() && !bind_addr.IsAnyIP()) {
  160. NetworkBindingResult result =
  161. ss_->network_binder()->BindSocketToNetwork(s_, bind_addr.ipaddr());
  162. if (result == NetworkBindingResult::SUCCESS) {
  163. // Since the network binder handled binding the socket to the desired
  164. // network interface, we don't need to (and shouldn't) include an IP in
  165. // the bind() call; bind() just needs to assign a port.
  166. copied_bind_addr.SetIP(GetAnyIP(copied_bind_addr.ipaddr().family()));
  167. } else if (result == NetworkBindingResult::NOT_IMPLEMENTED) {
  168. RTC_LOG(LS_INFO) << "Can't bind socket to network because "
  169. "network binding is not implemented for this OS.";
  170. } else {
  171. if (bind_addr.IsLoopbackIP()) {
  172. // If we couldn't bind to a loopback IP (which should only happen in
  173. // test scenarios), continue on. This may be expected behavior.
  174. RTC_LOG(LS_VERBOSE) << "Binding socket to loopback address "
  175. << bind_addr.ipaddr().ToString()
  176. << " failed; result: " << static_cast<int>(result);
  177. } else {
  178. RTC_LOG(LS_WARNING) << "Binding socket to network address "
  179. << bind_addr.ipaddr().ToString()
  180. << " failed; result: " << static_cast<int>(result);
  181. // If a network binding was attempted and failed, we should stop here
  182. // and not try to use the socket. Otherwise, we may end up sending
  183. // packets with an invalid source address.
  184. // See: https://bugs.chromium.org/p/webrtc/issues/detail?id=7026
  185. return -1;
  186. }
  187. }
  188. }
  189. sockaddr_storage addr_storage;
  190. size_t len = copied_bind_addr.ToSockAddrStorage(&addr_storage);
  191. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  192. int err = ::bind(s_, addr, static_cast<int>(len));
  193. UpdateLastError();
  194. #if !defined(NDEBUG)
  195. if (0 == err) {
  196. dbg_addr_ = "Bound @ ";
  197. dbg_addr_.append(GetLocalAddress().ToString());
  198. }
  199. #endif
  200. return err;
  201. }
  202. int PhysicalSocket::Connect(const SocketAddress& addr) {
  203. // TODO(pthatcher): Implicit creation is required to reconnect...
  204. // ...but should we make it more explicit?
  205. if (state_ != CS_CLOSED) {
  206. SetError(EALREADY);
  207. return SOCKET_ERROR;
  208. }
  209. if (addr.IsUnresolvedIP()) {
  210. RTC_LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
  211. resolver_ = new AsyncResolver();
  212. resolver_->SignalDone.connect(this, &PhysicalSocket::OnResolveResult);
  213. resolver_->Start(addr);
  214. state_ = CS_CONNECTING;
  215. return 0;
  216. }
  217. return DoConnect(addr);
  218. }
  219. int PhysicalSocket::DoConnect(const SocketAddress& connect_addr) {
  220. if ((s_ == INVALID_SOCKET) && !Create(connect_addr.family(), SOCK_STREAM)) {
  221. return SOCKET_ERROR;
  222. }
  223. sockaddr_storage addr_storage;
  224. size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
  225. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  226. int err = ::connect(s_, addr, static_cast<int>(len));
  227. UpdateLastError();
  228. uint8_t events = DE_READ | DE_WRITE;
  229. if (err == 0) {
  230. state_ = CS_CONNECTED;
  231. } else if (IsBlockingError(GetError())) {
  232. state_ = CS_CONNECTING;
  233. events |= DE_CONNECT;
  234. } else {
  235. return SOCKET_ERROR;
  236. }
  237. EnableEvents(events);
  238. return 0;
  239. }
  240. int PhysicalSocket::GetError() const {
  241. CritScope cs(&crit_);
  242. return error_;
  243. }
  244. void PhysicalSocket::SetError(int error) {
  245. CritScope cs(&crit_);
  246. error_ = error;
  247. }
  248. AsyncSocket::ConnState PhysicalSocket::GetState() const {
  249. return state_;
  250. }
  251. int PhysicalSocket::GetOption(Option opt, int* value) {
  252. int slevel;
  253. int sopt;
  254. if (TranslateOption(opt, &slevel, &sopt) == -1)
  255. return -1;
  256. socklen_t optlen = sizeof(*value);
  257. int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
  258. if (ret != -1 && opt == OPT_DONTFRAGMENT) {
  259. #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
  260. *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
  261. #endif
  262. }
  263. return ret;
  264. }
  265. int PhysicalSocket::SetOption(Option opt, int value) {
  266. int slevel;
  267. int sopt;
  268. if (TranslateOption(opt, &slevel, &sopt) == -1)
  269. return -1;
  270. if (opt == OPT_DONTFRAGMENT) {
  271. #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
  272. value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
  273. #endif
  274. }
  275. return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
  276. }
  277. int PhysicalSocket::Send(const void* pv, size_t cb) {
  278. int sent = DoSend(
  279. s_, reinterpret_cast<const char*>(pv), static_cast<int>(cb),
  280. #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
  281. // Suppress SIGPIPE. Without this, attempting to send on a socket whose
  282. // other end is closed will result in a SIGPIPE signal being raised to
  283. // our process, which by default will terminate the process, which we
  284. // don't want. By specifying this flag, we'll just get the error EPIPE
  285. // instead and can handle the error gracefully.
  286. MSG_NOSIGNAL
  287. #else
  288. 0
  289. #endif
  290. );
  291. UpdateLastError();
  292. MaybeRemapSendError();
  293. // We have seen minidumps where this may be false.
  294. RTC_DCHECK(sent <= static_cast<int>(cb));
  295. if ((sent > 0 && sent < static_cast<int>(cb)) ||
  296. (sent < 0 && IsBlockingError(GetError()))) {
  297. EnableEvents(DE_WRITE);
  298. }
  299. return sent;
  300. }
  301. int PhysicalSocket::SendTo(const void* buffer,
  302. size_t length,
  303. const SocketAddress& addr) {
  304. sockaddr_storage saddr;
  305. size_t len = addr.ToSockAddrStorage(&saddr);
  306. int sent =
  307. DoSendTo(s_, static_cast<const char*>(buffer), static_cast<int>(length),
  308. #if defined(WEBRTC_LINUX) && !defined(WEBRTC_ANDROID)
  309. // Suppress SIGPIPE. See above for explanation.
  310. MSG_NOSIGNAL,
  311. #else
  312. 0,
  313. #endif
  314. reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
  315. UpdateLastError();
  316. MaybeRemapSendError();
  317. // We have seen minidumps where this may be false.
  318. RTC_DCHECK(sent <= static_cast<int>(length));
  319. if ((sent > 0 && sent < static_cast<int>(length)) ||
  320. (sent < 0 && IsBlockingError(GetError()))) {
  321. EnableEvents(DE_WRITE);
  322. }
  323. return sent;
  324. }
  325. int PhysicalSocket::Recv(void* buffer, size_t length, int64_t* timestamp) {
  326. int received =
  327. ::recv(s_, static_cast<char*>(buffer), static_cast<int>(length), 0);
  328. if ((received == 0) && (length != 0)) {
  329. // Note: on graceful shutdown, recv can return 0. In this case, we
  330. // pretend it is blocking, and then signal close, so that simplifying
  331. // assumptions can be made about Recv.
  332. RTC_LOG(LS_WARNING) << "EOF from socket; deferring close event";
  333. // Must turn this back on so that the select() loop will notice the close
  334. // event.
  335. EnableEvents(DE_READ);
  336. SetError(EWOULDBLOCK);
  337. return SOCKET_ERROR;
  338. }
  339. if (timestamp) {
  340. *timestamp = GetSocketRecvTimestamp(s_);
  341. }
  342. UpdateLastError();
  343. int error = GetError();
  344. bool success = (received >= 0) || IsBlockingError(error);
  345. if (udp_ || success) {
  346. EnableEvents(DE_READ);
  347. }
  348. if (!success) {
  349. RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
  350. }
  351. return received;
  352. }
  353. int PhysicalSocket::RecvFrom(void* buffer,
  354. size_t length,
  355. SocketAddress* out_addr,
  356. int64_t* timestamp) {
  357. sockaddr_storage addr_storage;
  358. socklen_t addr_len = sizeof(addr_storage);
  359. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  360. int received = ::recvfrom(s_, static_cast<char*>(buffer),
  361. static_cast<int>(length), 0, addr, &addr_len);
  362. if (timestamp) {
  363. *timestamp = GetSocketRecvTimestamp(s_);
  364. }
  365. UpdateLastError();
  366. if ((received >= 0) && (out_addr != nullptr))
  367. SocketAddressFromSockAddrStorage(addr_storage, out_addr);
  368. int error = GetError();
  369. bool success = (received >= 0) || IsBlockingError(error);
  370. if (udp_ || success) {
  371. EnableEvents(DE_READ);
  372. }
  373. if (!success) {
  374. RTC_LOG_F(LS_VERBOSE) << "Error = " << error;
  375. }
  376. return received;
  377. }
  378. int PhysicalSocket::Listen(int backlog) {
  379. int err = ::listen(s_, backlog);
  380. UpdateLastError();
  381. if (err == 0) {
  382. state_ = CS_CONNECTING;
  383. EnableEvents(DE_ACCEPT);
  384. #if !defined(NDEBUG)
  385. dbg_addr_ = "Listening @ ";
  386. dbg_addr_.append(GetLocalAddress().ToString());
  387. #endif
  388. }
  389. return err;
  390. }
  391. AsyncSocket* PhysicalSocket::Accept(SocketAddress* out_addr) {
  392. // Always re-subscribe DE_ACCEPT to make sure new incoming connections will
  393. // trigger an event even if DoAccept returns an error here.
  394. EnableEvents(DE_ACCEPT);
  395. sockaddr_storage addr_storage;
  396. socklen_t addr_len = sizeof(addr_storage);
  397. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  398. SOCKET s = DoAccept(s_, addr, &addr_len);
  399. UpdateLastError();
  400. if (s == INVALID_SOCKET)
  401. return nullptr;
  402. if (out_addr != nullptr)
  403. SocketAddressFromSockAddrStorage(addr_storage, out_addr);
  404. return ss_->WrapSocket(s);
  405. }
  406. int PhysicalSocket::Close() {
  407. if (s_ == INVALID_SOCKET)
  408. return 0;
  409. int err = ::closesocket(s_);
  410. UpdateLastError();
  411. s_ = INVALID_SOCKET;
  412. state_ = CS_CLOSED;
  413. SetEnabledEvents(0);
  414. if (resolver_) {
  415. resolver_->Destroy(false);
  416. resolver_ = nullptr;
  417. }
  418. return err;
  419. }
  420. SOCKET PhysicalSocket::DoAccept(SOCKET socket,
  421. sockaddr* addr,
  422. socklen_t* addrlen) {
  423. return ::accept(socket, addr, addrlen);
  424. }
  425. int PhysicalSocket::DoSend(SOCKET socket, const char* buf, int len, int flags) {
  426. return ::send(socket, buf, len, flags);
  427. }
  428. int PhysicalSocket::DoSendTo(SOCKET socket,
  429. const char* buf,
  430. int len,
  431. int flags,
  432. const struct sockaddr* dest_addr,
  433. socklen_t addrlen) {
  434. return ::sendto(socket, buf, len, flags, dest_addr, addrlen);
  435. }
  436. void PhysicalSocket::OnResolveResult(AsyncResolverInterface* resolver) {
  437. if (resolver != resolver_) {
  438. return;
  439. }
  440. int error = resolver_->GetError();
  441. if (error == 0) {
  442. error = DoConnect(resolver_->address());
  443. } else {
  444. Close();
  445. }
  446. if (error) {
  447. SetError(error);
  448. SignalCloseEvent(this, error);
  449. }
  450. }
  451. void PhysicalSocket::UpdateLastError() {
  452. SetError(LAST_SYSTEM_ERROR);
  453. }
  454. void PhysicalSocket::MaybeRemapSendError() {
  455. #if defined(WEBRTC_MAC)
  456. // https://developer.apple.com/library/mac/documentation/Darwin/
  457. // Reference/ManPages/man2/sendto.2.html
  458. // ENOBUFS - The output queue for a network interface is full.
  459. // This generally indicates that the interface has stopped sending,
  460. // but may be caused by transient congestion.
  461. if (GetError() == ENOBUFS) {
  462. SetError(EWOULDBLOCK);
  463. }
  464. #endif
  465. }
  466. void PhysicalSocket::SetEnabledEvents(uint8_t events) {
  467. enabled_events_ = events;
  468. }
  469. void PhysicalSocket::EnableEvents(uint8_t events) {
  470. enabled_events_ |= events;
  471. }
  472. void PhysicalSocket::DisableEvents(uint8_t events) {
  473. enabled_events_ &= ~events;
  474. }
  475. int PhysicalSocket::TranslateOption(Option opt, int* slevel, int* sopt) {
  476. switch (opt) {
  477. case OPT_DONTFRAGMENT:
  478. #if defined(WEBRTC_WIN)
  479. *slevel = IPPROTO_IP;
  480. *sopt = IP_DONTFRAGMENT;
  481. break;
  482. #elif defined(WEBRTC_MAC) || defined(BSD) || defined(__native_client__)
  483. RTC_LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
  484. return -1;
  485. #elif defined(WEBRTC_POSIX)
  486. *slevel = IPPROTO_IP;
  487. *sopt = IP_MTU_DISCOVER;
  488. break;
  489. #endif
  490. case OPT_RCVBUF:
  491. *slevel = SOL_SOCKET;
  492. *sopt = SO_RCVBUF;
  493. break;
  494. case OPT_SNDBUF:
  495. *slevel = SOL_SOCKET;
  496. *sopt = SO_SNDBUF;
  497. break;
  498. case OPT_NODELAY:
  499. *slevel = IPPROTO_TCP;
  500. *sopt = TCP_NODELAY;
  501. break;
  502. case OPT_DSCP:
  503. RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported.";
  504. return -1;
  505. case OPT_RTP_SENDTIME_EXTN_ID:
  506. return -1; // No logging is necessary as this not a OS socket option.
  507. default:
  508. RTC_NOTREACHED();
  509. return -1;
  510. }
  511. return 0;
  512. }
  513. SocketDispatcher::SocketDispatcher(PhysicalSocketServer* ss)
  514. #if defined(WEBRTC_WIN)
  515. : PhysicalSocket(ss),
  516. id_(0),
  517. signal_close_(false)
  518. #else
  519. : PhysicalSocket(ss)
  520. #endif
  521. {
  522. }
  523. SocketDispatcher::SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
  524. #if defined(WEBRTC_WIN)
  525. : PhysicalSocket(ss, s),
  526. id_(0),
  527. signal_close_(false)
  528. #else
  529. : PhysicalSocket(ss, s)
  530. #endif
  531. {
  532. }
  533. SocketDispatcher::~SocketDispatcher() {
  534. Close();
  535. }
  536. bool SocketDispatcher::Initialize() {
  537. RTC_DCHECK(s_ != INVALID_SOCKET);
  538. // Must be a non-blocking
  539. #if defined(WEBRTC_WIN)
  540. u_long argp = 1;
  541. ioctlsocket(s_, FIONBIO, &argp);
  542. #elif defined(WEBRTC_POSIX)
  543. fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
  544. #endif
  545. #if defined(WEBRTC_IOS)
  546. // iOS may kill sockets when the app is moved to the background
  547. // (specifically, if the app doesn't use the "voip" UIBackgroundMode). When
  548. // we attempt to write to such a socket, SIGPIPE will be raised, which by
  549. // default will terminate the process, which we don't want. By specifying
  550. // this socket option, SIGPIPE will be disabled for the socket.
  551. int value = 1;
  552. ::setsockopt(s_, SOL_SOCKET, SO_NOSIGPIPE, &value, sizeof(value));
  553. #endif
  554. ss_->Add(this);
  555. return true;
  556. }
  557. bool SocketDispatcher::Create(int type) {
  558. return Create(AF_INET, type);
  559. }
  560. bool SocketDispatcher::Create(int family, int type) {
  561. // Change the socket to be non-blocking.
  562. if (!PhysicalSocket::Create(family, type))
  563. return false;
  564. if (!Initialize())
  565. return false;
  566. #if defined(WEBRTC_WIN)
  567. do {
  568. id_ = ++next_id_;
  569. } while (id_ == 0);
  570. #endif
  571. return true;
  572. }
  573. #if defined(WEBRTC_WIN)
  574. WSAEVENT SocketDispatcher::GetWSAEvent() {
  575. return WSA_INVALID_EVENT;
  576. }
  577. SOCKET SocketDispatcher::GetSocket() {
  578. return s_;
  579. }
  580. bool SocketDispatcher::CheckSignalClose() {
  581. if (!signal_close_)
  582. return false;
  583. char ch;
  584. if (recv(s_, &ch, 1, MSG_PEEK) > 0)
  585. return false;
  586. state_ = CS_CLOSED;
  587. signal_close_ = false;
  588. SignalCloseEvent(this, signal_err_);
  589. return true;
  590. }
  591. int SocketDispatcher::next_id_ = 0;
  592. #elif defined(WEBRTC_POSIX)
  593. int SocketDispatcher::GetDescriptor() {
  594. return s_;
  595. }
  596. bool SocketDispatcher::IsDescriptorClosed() {
  597. if (udp_) {
  598. // The MSG_PEEK trick doesn't work for UDP, since (at least in some
  599. // circumstances) it requires reading an entire UDP packet, which would be
  600. // bad for performance here. So, just check whether |s_| has been closed,
  601. // which should be sufficient.
  602. return s_ == INVALID_SOCKET;
  603. }
  604. // We don't have a reliable way of distinguishing end-of-stream
  605. // from readability. So test on each readable call. Is this
  606. // inefficient? Probably.
  607. char ch;
  608. ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
  609. if (res > 0) {
  610. // Data available, so not closed.
  611. return false;
  612. } else if (res == 0) {
  613. // EOF, so closed.
  614. return true;
  615. } else { // error
  616. switch (errno) {
  617. // Returned if we've already closed s_.
  618. case EBADF:
  619. // Returned during ungraceful peer shutdown.
  620. case ECONNRESET:
  621. return true;
  622. // The normal blocking error; don't log anything.
  623. case EWOULDBLOCK:
  624. // Interrupted system call.
  625. case EINTR:
  626. return false;
  627. default:
  628. // Assume that all other errors are just blocking errors, meaning the
  629. // connection is still good but we just can't read from it right now.
  630. // This should only happen when connecting (and at most once), because
  631. // in all other cases this function is only called if the file
  632. // descriptor is already known to be in the readable state. However,
  633. // it's not necessary a problem if we spuriously interpret a
  634. // "connection lost"-type error as a blocking error, because typically
  635. // the next recv() will get EOF, so we'll still eventually notice that
  636. // the socket is closed.
  637. RTC_LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
  638. return false;
  639. }
  640. }
  641. }
  642. #endif // WEBRTC_POSIX
  643. uint32_t SocketDispatcher::GetRequestedEvents() {
  644. return enabled_events();
  645. }
  646. void SocketDispatcher::OnPreEvent(uint32_t ff) {
  647. if ((ff & DE_CONNECT) != 0)
  648. state_ = CS_CONNECTED;
  649. #if defined(WEBRTC_WIN)
  650. // We set CS_CLOSED from CheckSignalClose.
  651. #elif defined(WEBRTC_POSIX)
  652. if ((ff & DE_CLOSE) != 0)
  653. state_ = CS_CLOSED;
  654. #endif
  655. }
  656. #if defined(WEBRTC_WIN)
  657. void SocketDispatcher::OnEvent(uint32_t ff, int err) {
  658. int cache_id = id_;
  659. // Make sure we deliver connect/accept first. Otherwise, consumers may see
  660. // something like a READ followed by a CONNECT, which would be odd.
  661. if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
  662. if (ff != DE_CONNECT)
  663. RTC_LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
  664. DisableEvents(DE_CONNECT);
  665. #if !defined(NDEBUG)
  666. dbg_addr_ = "Connected @ ";
  667. dbg_addr_.append(GetRemoteAddress().ToString());
  668. #endif
  669. SignalConnectEvent(this);
  670. }
  671. if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
  672. DisableEvents(DE_ACCEPT);
  673. SignalReadEvent(this);
  674. }
  675. if ((ff & DE_READ) != 0) {
  676. DisableEvents(DE_READ);
  677. SignalReadEvent(this);
  678. }
  679. if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
  680. DisableEvents(DE_WRITE);
  681. SignalWriteEvent(this);
  682. }
  683. if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
  684. signal_close_ = true;
  685. signal_err_ = err;
  686. }
  687. }
  688. #elif defined(WEBRTC_POSIX)
  689. void SocketDispatcher::OnEvent(uint32_t ff, int err) {
  690. #if defined(WEBRTC_USE_EPOLL)
  691. // Remember currently enabled events so we can combine multiple changes
  692. // into one update call later.
  693. // The signal handlers might re-enable events disabled here, so we can't
  694. // keep a list of events to disable at the end of the method. This list
  695. // would not be updated with the events enabled by the signal handlers.
  696. StartBatchedEventUpdates();
  697. #endif
  698. // Make sure we deliver connect/accept first. Otherwise, consumers may see
  699. // something like a READ followed by a CONNECT, which would be odd.
  700. if ((ff & DE_CONNECT) != 0) {
  701. DisableEvents(DE_CONNECT);
  702. SignalConnectEvent(this);
  703. }
  704. if ((ff & DE_ACCEPT) != 0) {
  705. DisableEvents(DE_ACCEPT);
  706. SignalReadEvent(this);
  707. }
  708. if ((ff & DE_READ) != 0) {
  709. DisableEvents(DE_READ);
  710. SignalReadEvent(this);
  711. }
  712. if ((ff & DE_WRITE) != 0) {
  713. DisableEvents(DE_WRITE);
  714. SignalWriteEvent(this);
  715. }
  716. if ((ff & DE_CLOSE) != 0) {
  717. // The socket is now dead to us, so stop checking it.
  718. SetEnabledEvents(0);
  719. SignalCloseEvent(this, err);
  720. }
  721. #if defined(WEBRTC_USE_EPOLL)
  722. FinishBatchedEventUpdates();
  723. #endif
  724. }
  725. #endif // WEBRTC_POSIX
  726. #if defined(WEBRTC_USE_EPOLL)
  727. static int GetEpollEvents(uint32_t ff) {
  728. int events = 0;
  729. if (ff & (DE_READ | DE_ACCEPT)) {
  730. events |= EPOLLIN;
  731. }
  732. if (ff & (DE_WRITE | DE_CONNECT)) {
  733. events |= EPOLLOUT;
  734. }
  735. return events;
  736. }
  737. void SocketDispatcher::StartBatchedEventUpdates() {
  738. RTC_DCHECK_EQ(saved_enabled_events_, -1);
  739. saved_enabled_events_ = enabled_events();
  740. }
  741. void SocketDispatcher::FinishBatchedEventUpdates() {
  742. RTC_DCHECK_NE(saved_enabled_events_, -1);
  743. uint8_t old_events = static_cast<uint8_t>(saved_enabled_events_);
  744. saved_enabled_events_ = -1;
  745. MaybeUpdateDispatcher(old_events);
  746. }
  747. void SocketDispatcher::MaybeUpdateDispatcher(uint8_t old_events) {
  748. if (GetEpollEvents(enabled_events()) != GetEpollEvents(old_events) &&
  749. saved_enabled_events_ == -1) {
  750. ss_->Update(this);
  751. }
  752. }
  753. void SocketDispatcher::SetEnabledEvents(uint8_t events) {
  754. uint8_t old_events = enabled_events();
  755. PhysicalSocket::SetEnabledEvents(events);
  756. MaybeUpdateDispatcher(old_events);
  757. }
  758. void SocketDispatcher::EnableEvents(uint8_t events) {
  759. uint8_t old_events = enabled_events();
  760. PhysicalSocket::EnableEvents(events);
  761. MaybeUpdateDispatcher(old_events);
  762. }
  763. void SocketDispatcher::DisableEvents(uint8_t events) {
  764. uint8_t old_events = enabled_events();
  765. PhysicalSocket::DisableEvents(events);
  766. MaybeUpdateDispatcher(old_events);
  767. }
  768. #endif // WEBRTC_USE_EPOLL
  769. int SocketDispatcher::Close() {
  770. if (s_ == INVALID_SOCKET)
  771. return 0;
  772. #if defined(WEBRTC_WIN)
  773. id_ = 0;
  774. signal_close_ = false;
  775. #endif
  776. ss_->Remove(this);
  777. return PhysicalSocket::Close();
  778. }
  779. #if defined(WEBRTC_POSIX)
  780. class EventDispatcher : public Dispatcher {
  781. public:
  782. EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
  783. if (pipe(afd_) < 0)
  784. RTC_LOG(LERROR) << "pipe failed";
  785. ss_->Add(this);
  786. }
  787. ~EventDispatcher() override {
  788. ss_->Remove(this);
  789. close(afd_[0]);
  790. close(afd_[1]);
  791. }
  792. virtual void Signal() {
  793. CritScope cs(&crit_);
  794. if (!fSignaled_) {
  795. const uint8_t b[1] = {0};
  796. const ssize_t res = write(afd_[1], b, sizeof(b));
  797. RTC_DCHECK_EQ(1, res);
  798. fSignaled_ = true;
  799. }
  800. }
  801. uint32_t GetRequestedEvents() override { return DE_READ; }
  802. void OnPreEvent(uint32_t ff) override {
  803. // It is not possible to perfectly emulate an auto-resetting event with
  804. // pipes. This simulates it by resetting before the event is handled.
  805. CritScope cs(&crit_);
  806. if (fSignaled_) {
  807. uint8_t b[4]; // Allow for reading more than 1 byte, but expect 1.
  808. const ssize_t res = read(afd_[0], b, sizeof(b));
  809. RTC_DCHECK_EQ(1, res);
  810. fSignaled_ = false;
  811. }
  812. }
  813. void OnEvent(uint32_t ff, int err) override { RTC_NOTREACHED(); }
  814. int GetDescriptor() override { return afd_[0]; }
  815. bool IsDescriptorClosed() override { return false; }
  816. private:
  817. PhysicalSocketServer* ss_;
  818. int afd_[2];
  819. bool fSignaled_;
  820. CriticalSection crit_;
  821. };
  822. // These two classes use the self-pipe trick to deliver POSIX signals to our
  823. // select loop. This is the only safe, reliable, cross-platform way to do
  824. // non-trivial things with a POSIX signal in an event-driven program (until
  825. // proper pselect() implementations become ubiquitous).
  826. class PosixSignalHandler {
  827. public:
  828. // POSIX only specifies 32 signals, but in principle the system might have
  829. // more and the programmer might choose to use them, so we size our array
  830. // for 128.
  831. static const int kNumPosixSignals = 128;
  832. // There is just a single global instance. (Signal handlers do not get any
  833. // sort of user-defined void * parameter, so they can't access anything that
  834. // isn't global.)
  835. static PosixSignalHandler* Instance() {
  836. static PosixSignalHandler* const instance = new PosixSignalHandler();
  837. return instance;
  838. }
  839. // Returns true if the given signal number is set.
  840. bool IsSignalSet(int signum) const {
  841. RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
  842. if (signum < static_cast<int>(arraysize(received_signal_))) {
  843. return received_signal_[signum];
  844. } else {
  845. return false;
  846. }
  847. }
  848. // Clears the given signal number.
  849. void ClearSignal(int signum) {
  850. RTC_DCHECK(signum < static_cast<int>(arraysize(received_signal_)));
  851. if (signum < static_cast<int>(arraysize(received_signal_))) {
  852. received_signal_[signum] = false;
  853. }
  854. }
  855. // Returns the file descriptor to monitor for signal events.
  856. int GetDescriptor() const { return afd_[0]; }
  857. // This is called directly from our real signal handler, so it must be
  858. // signal-handler-safe. That means it cannot assume anything about the
  859. // user-level state of the process, since the handler could be executed at any
  860. // time on any thread.
  861. void OnPosixSignalReceived(int signum) {
  862. if (signum >= static_cast<int>(arraysize(received_signal_))) {
  863. // We don't have space in our array for this.
  864. return;
  865. }
  866. // Set a flag saying we've seen this signal.
  867. received_signal_[signum] = true;
  868. // Notify application code that we got a signal.
  869. const uint8_t b[1] = {0};
  870. if (-1 == write(afd_[1], b, sizeof(b))) {
  871. // Nothing we can do here. If there's an error somehow then there's
  872. // nothing we can safely do from a signal handler.
  873. // No, we can't even safely log it.
  874. // But, we still have to check the return value here. Otherwise,
  875. // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
  876. return;
  877. }
  878. }
  879. private:
  880. PosixSignalHandler() {
  881. if (pipe(afd_) < 0) {
  882. RTC_LOG_ERR(LS_ERROR) << "pipe failed";
  883. return;
  884. }
  885. if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
  886. RTC_LOG_ERR(LS_WARNING) << "fcntl #1 failed";
  887. }
  888. if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
  889. RTC_LOG_ERR(LS_WARNING) << "fcntl #2 failed";
  890. }
  891. memset(const_cast<void*>(static_cast<volatile void*>(received_signal_)), 0,
  892. sizeof(received_signal_));
  893. }
  894. ~PosixSignalHandler() {
  895. int fd1 = afd_[0];
  896. int fd2 = afd_[1];
  897. // We clobber the stored file descriptor numbers here or else in principle
  898. // a signal that happens to be delivered during application termination
  899. // could erroneously write a zero byte to an unrelated file handle in
  900. // OnPosixSignalReceived() if some other file happens to be opened later
  901. // during shutdown and happens to be given the same file descriptor number
  902. // as our pipe had. Unfortunately even with this precaution there is still a
  903. // race where that could occur if said signal happens to be handled
  904. // concurrently with this code and happens to have already read the value of
  905. // afd_[1] from memory before we clobber it, but that's unlikely.
  906. afd_[0] = -1;
  907. afd_[1] = -1;
  908. close(fd1);
  909. close(fd2);
  910. }
  911. int afd_[2];
  912. // These are boolean flags that will be set in our signal handler and read
  913. // and cleared from Wait(). There is a race involved in this, but it is
  914. // benign. The signal handler sets the flag before signaling the pipe, so
  915. // we'll never end up blocking in select() while a flag is still true.
  916. // However, if two of the same signal arrive close to each other then it's
  917. // possible that the second time the handler may set the flag while it's still
  918. // true, meaning that signal will be missed. But the first occurrence of it
  919. // will still be handled, so this isn't a problem.
  920. // Volatile is not necessary here for correctness, but this data _is_ volatile
  921. // so I've marked it as such.
  922. volatile uint8_t received_signal_[kNumPosixSignals];
  923. };
  924. class PosixSignalDispatcher : public Dispatcher {
  925. public:
  926. PosixSignalDispatcher(PhysicalSocketServer* owner) : owner_(owner) {
  927. owner_->Add(this);
  928. }
  929. ~PosixSignalDispatcher() override { owner_->Remove(this); }
  930. uint32_t GetRequestedEvents() override { return DE_READ; }
  931. void OnPreEvent(uint32_t ff) override {
  932. // Events might get grouped if signals come very fast, so we read out up to
  933. // 16 bytes to make sure we keep the pipe empty.
  934. uint8_t b[16];
  935. ssize_t ret = read(GetDescriptor(), b, sizeof(b));
  936. if (ret < 0) {
  937. RTC_LOG_ERR(LS_WARNING) << "Error in read()";
  938. } else if (ret == 0) {
  939. RTC_LOG(LS_WARNING) << "Should have read at least one byte";
  940. }
  941. }
  942. void OnEvent(uint32_t ff, int err) override {
  943. for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
  944. ++signum) {
  945. if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
  946. PosixSignalHandler::Instance()->ClearSignal(signum);
  947. HandlerMap::iterator i = handlers_.find(signum);
  948. if (i == handlers_.end()) {
  949. // This can happen if a signal is delivered to our process at around
  950. // the same time as we unset our handler for it. It is not an error
  951. // condition, but it's unusual enough to be worth logging.
  952. RTC_LOG(LS_INFO) << "Received signal with no handler: " << signum;
  953. } else {
  954. // Otherwise, execute our handler.
  955. (*i->second)(signum);
  956. }
  957. }
  958. }
  959. }
  960. int GetDescriptor() override {
  961. return PosixSignalHandler::Instance()->GetDescriptor();
  962. }
  963. bool IsDescriptorClosed() override { return false; }
  964. void SetHandler(int signum, void (*handler)(int)) {
  965. handlers_[signum] = handler;
  966. }
  967. void ClearHandler(int signum) { handlers_.erase(signum); }
  968. bool HasHandlers() { return !handlers_.empty(); }
  969. private:
  970. typedef std::map<int, void (*)(int)> HandlerMap;
  971. HandlerMap handlers_;
  972. // Our owner.
  973. PhysicalSocketServer* owner_;
  974. };
  975. #endif // WEBRTC_POSIX
  976. #if defined(WEBRTC_WIN)
  977. static uint32_t FlagsToEvents(uint32_t events) {
  978. uint32_t ffFD = FD_CLOSE;
  979. if (events & DE_READ)
  980. ffFD |= FD_READ;
  981. if (events & DE_WRITE)
  982. ffFD |= FD_WRITE;
  983. if (events & DE_CONNECT)
  984. ffFD |= FD_CONNECT;
  985. if (events & DE_ACCEPT)
  986. ffFD |= FD_ACCEPT;
  987. return ffFD;
  988. }
  989. class EventDispatcher : public Dispatcher {
  990. public:
  991. EventDispatcher(PhysicalSocketServer* ss) : ss_(ss) {
  992. hev_ = WSACreateEvent();
  993. if (hev_) {
  994. ss_->Add(this);
  995. }
  996. }
  997. ~EventDispatcher() override {
  998. if (hev_ != nullptr) {
  999. ss_->Remove(this);
  1000. WSACloseEvent(hev_);
  1001. hev_ = nullptr;
  1002. }
  1003. }
  1004. virtual void Signal() {
  1005. if (hev_ != nullptr)
  1006. WSASetEvent(hev_);
  1007. }
  1008. uint32_t GetRequestedEvents() override { return 0; }
  1009. void OnPreEvent(uint32_t ff) override { WSAResetEvent(hev_); }
  1010. void OnEvent(uint32_t ff, int err) override {}
  1011. WSAEVENT GetWSAEvent() override { return hev_; }
  1012. SOCKET GetSocket() override { return INVALID_SOCKET; }
  1013. bool CheckSignalClose() override { return false; }
  1014. private:
  1015. PhysicalSocketServer* ss_;
  1016. WSAEVENT hev_;
  1017. };
  1018. #endif // WEBRTC_WIN
  1019. // Sets the value of a boolean value to false when signaled.
  1020. class Signaler : public EventDispatcher {
  1021. public:
  1022. Signaler(PhysicalSocketServer* ss, bool* pf) : EventDispatcher(ss), pf_(pf) {}
  1023. ~Signaler() override {}
  1024. void OnEvent(uint32_t ff, int err) override {
  1025. if (pf_)
  1026. *pf_ = false;
  1027. }
  1028. private:
  1029. bool* pf_;
  1030. };
  1031. PhysicalSocketServer::PhysicalSocketServer() : fWait_(false) {
  1032. #if defined(WEBRTC_USE_EPOLL)
  1033. // Since Linux 2.6.8, the size argument is ignored, but must be greater than
  1034. // zero. Before that the size served as hint to the kernel for the amount of
  1035. // space to initially allocate in internal data structures.
  1036. epoll_fd_ = epoll_create(FD_SETSIZE);
  1037. if (epoll_fd_ == -1) {
  1038. // Not an error, will fall back to "select" below.
  1039. RTC_LOG_E(LS_WARNING, EN, errno) << "epoll_create";
  1040. epoll_fd_ = INVALID_SOCKET;
  1041. }
  1042. #endif
  1043. signal_wakeup_ = new Signaler(this, &fWait_);
  1044. #if defined(WEBRTC_WIN)
  1045. socket_ev_ = WSACreateEvent();
  1046. #endif
  1047. }
  1048. PhysicalSocketServer::~PhysicalSocketServer() {
  1049. #if defined(WEBRTC_WIN)
  1050. WSACloseEvent(socket_ev_);
  1051. #endif
  1052. #if defined(WEBRTC_POSIX)
  1053. signal_dispatcher_.reset();
  1054. #endif
  1055. delete signal_wakeup_;
  1056. #if defined(WEBRTC_USE_EPOLL)
  1057. if (epoll_fd_ != INVALID_SOCKET) {
  1058. close(epoll_fd_);
  1059. }
  1060. #endif
  1061. RTC_DCHECK(dispatchers_.empty());
  1062. }
  1063. void PhysicalSocketServer::WakeUp() {
  1064. signal_wakeup_->Signal();
  1065. }
  1066. Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
  1067. PhysicalSocket* socket = new PhysicalSocket(this);
  1068. if (socket->Create(family, type)) {
  1069. return socket;
  1070. } else {
  1071. delete socket;
  1072. return nullptr;
  1073. }
  1074. }
  1075. AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
  1076. SocketDispatcher* dispatcher = new SocketDispatcher(this);
  1077. if (dispatcher->Create(family, type)) {
  1078. return dispatcher;
  1079. } else {
  1080. delete dispatcher;
  1081. return nullptr;
  1082. }
  1083. }
  1084. AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
  1085. SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
  1086. if (dispatcher->Initialize()) {
  1087. return dispatcher;
  1088. } else {
  1089. delete dispatcher;
  1090. return nullptr;
  1091. }
  1092. }
  1093. void PhysicalSocketServer::Add(Dispatcher* pdispatcher) {
  1094. CritScope cs(&crit_);
  1095. if (processing_dispatchers_) {
  1096. // A dispatcher is being added while a "Wait" call is processing the
  1097. // list of socket events.
  1098. // Defer adding to "dispatchers_" set until processing is done to avoid
  1099. // invalidating the iterator in "Wait".
  1100. pending_remove_dispatchers_.erase(pdispatcher);
  1101. pending_add_dispatchers_.insert(pdispatcher);
  1102. } else {
  1103. dispatchers_.insert(pdispatcher);
  1104. }
  1105. #if defined(WEBRTC_USE_EPOLL)
  1106. if (epoll_fd_ != INVALID_SOCKET) {
  1107. AddEpoll(pdispatcher);
  1108. }
  1109. #endif // WEBRTC_USE_EPOLL
  1110. }
  1111. void PhysicalSocketServer::Remove(Dispatcher* pdispatcher) {
  1112. CritScope cs(&crit_);
  1113. if (processing_dispatchers_) {
  1114. // A dispatcher is being removed while a "Wait" call is processing the
  1115. // list of socket events.
  1116. // Defer removal from "dispatchers_" set until processing is done to avoid
  1117. // invalidating the iterator in "Wait".
  1118. if (!pending_add_dispatchers_.erase(pdispatcher) &&
  1119. dispatchers_.find(pdispatcher) == dispatchers_.end()) {
  1120. RTC_LOG(LS_WARNING) << "PhysicalSocketServer asked to remove a unknown "
  1121. << "dispatcher, potentially from a duplicate call to "
  1122. << "Add.";
  1123. return;
  1124. }
  1125. pending_remove_dispatchers_.insert(pdispatcher);
  1126. } else if (!dispatchers_.erase(pdispatcher)) {
  1127. RTC_LOG(LS_WARNING)
  1128. << "PhysicalSocketServer asked to remove a unknown "
  1129. << "dispatcher, potentially from a duplicate call to Add.";
  1130. return;
  1131. }
  1132. #if defined(WEBRTC_USE_EPOLL)
  1133. if (epoll_fd_ != INVALID_SOCKET) {
  1134. RemoveEpoll(pdispatcher);
  1135. }
  1136. #endif // WEBRTC_USE_EPOLL
  1137. }
  1138. void PhysicalSocketServer::Update(Dispatcher* pdispatcher) {
  1139. #if defined(WEBRTC_USE_EPOLL)
  1140. if (epoll_fd_ == INVALID_SOCKET) {
  1141. return;
  1142. }
  1143. CritScope cs(&crit_);
  1144. if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
  1145. return;
  1146. }
  1147. UpdateEpoll(pdispatcher);
  1148. #endif
  1149. }
  1150. void PhysicalSocketServer::AddRemovePendingDispatchers() {
  1151. if (!pending_add_dispatchers_.empty()) {
  1152. for (Dispatcher* pdispatcher : pending_add_dispatchers_) {
  1153. dispatchers_.insert(pdispatcher);
  1154. }
  1155. pending_add_dispatchers_.clear();
  1156. }
  1157. if (!pending_remove_dispatchers_.empty()) {
  1158. for (Dispatcher* pdispatcher : pending_remove_dispatchers_) {
  1159. dispatchers_.erase(pdispatcher);
  1160. }
  1161. pending_remove_dispatchers_.clear();
  1162. }
  1163. }
  1164. #if defined(WEBRTC_POSIX)
  1165. bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
  1166. #if defined(WEBRTC_USE_EPOLL)
  1167. // We don't keep a dedicated "epoll" descriptor containing only the non-IO
  1168. // (i.e. signaling) dispatcher, so "poll" will be used instead of the default
  1169. // "select" to support sockets larger than FD_SETSIZE.
  1170. if (!process_io) {
  1171. return WaitPoll(cmsWait, signal_wakeup_);
  1172. } else if (epoll_fd_ != INVALID_SOCKET) {
  1173. return WaitEpoll(cmsWait);
  1174. }
  1175. #endif
  1176. return WaitSelect(cmsWait, process_io);
  1177. }
  1178. static void ProcessEvents(Dispatcher* dispatcher,
  1179. bool readable,
  1180. bool writable,
  1181. bool check_error) {
  1182. int errcode = 0;
  1183. // TODO(pthatcher): Should we set errcode if getsockopt fails?
  1184. if (check_error) {
  1185. socklen_t len = sizeof(errcode);
  1186. ::getsockopt(dispatcher->GetDescriptor(), SOL_SOCKET, SO_ERROR, &errcode,
  1187. &len);
  1188. }
  1189. uint32_t ff = 0;
  1190. // Check readable descriptors. If we're waiting on an accept, signal
  1191. // that. Otherwise we're waiting for data, check to see if we're
  1192. // readable or really closed.
  1193. // TODO(pthatcher): Only peek at TCP descriptors.
  1194. if (readable) {
  1195. if (dispatcher->GetRequestedEvents() & DE_ACCEPT) {
  1196. ff |= DE_ACCEPT;
  1197. } else if (errcode || dispatcher->IsDescriptorClosed()) {
  1198. ff |= DE_CLOSE;
  1199. } else {
  1200. ff |= DE_READ;
  1201. }
  1202. }
  1203. // Check writable descriptors. If we're waiting on a connect, detect
  1204. // success versus failure by the reaped error code.
  1205. if (writable) {
  1206. if (dispatcher->GetRequestedEvents() & DE_CONNECT) {
  1207. if (!errcode) {
  1208. ff |= DE_CONNECT;
  1209. } else {
  1210. ff |= DE_CLOSE;
  1211. }
  1212. } else {
  1213. ff |= DE_WRITE;
  1214. }
  1215. }
  1216. // Tell the descriptor about the event.
  1217. if (ff != 0) {
  1218. dispatcher->OnPreEvent(ff);
  1219. dispatcher->OnEvent(ff, errcode);
  1220. }
  1221. }
  1222. bool PhysicalSocketServer::WaitSelect(int cmsWait, bool process_io) {
  1223. // Calculate timing information
  1224. struct timeval* ptvWait = nullptr;
  1225. struct timeval tvWait;
  1226. int64_t stop_us;
  1227. if (cmsWait != kForever) {
  1228. // Calculate wait timeval
  1229. tvWait.tv_sec = cmsWait / 1000;
  1230. tvWait.tv_usec = (cmsWait % 1000) * 1000;
  1231. ptvWait = &tvWait;
  1232. // Calculate when to return
  1233. stop_us = rtc::TimeMicros() + cmsWait * 1000;
  1234. }
  1235. // Zero all fd_sets. Don't need to do this inside the loop since
  1236. // select() zeros the descriptors not signaled
  1237. fd_set fdsRead;
  1238. FD_ZERO(&fdsRead);
  1239. fd_set fdsWrite;
  1240. FD_ZERO(&fdsWrite);
  1241. // Explicitly unpoison these FDs on MemorySanitizer which doesn't handle the
  1242. // inline assembly in FD_ZERO.
  1243. // http://crbug.com/344505
  1244. #ifdef MEMORY_SANITIZER
  1245. __msan_unpoison(&fdsRead, sizeof(fdsRead));
  1246. __msan_unpoison(&fdsWrite, sizeof(fdsWrite));
  1247. #endif
  1248. fWait_ = true;
  1249. while (fWait_) {
  1250. int fdmax = -1;
  1251. {
  1252. CritScope cr(&crit_);
  1253. // TODO(jbauch): Support re-entrant waiting.
  1254. RTC_DCHECK(!processing_dispatchers_);
  1255. for (Dispatcher* pdispatcher : dispatchers_) {
  1256. // Query dispatchers for read and write wait state
  1257. RTC_DCHECK(pdispatcher);
  1258. if (!process_io && (pdispatcher != signal_wakeup_))
  1259. continue;
  1260. int fd = pdispatcher->GetDescriptor();
  1261. // "select"ing a file descriptor that is equal to or larger than
  1262. // FD_SETSIZE will result in undefined behavior.
  1263. RTC_DCHECK_LT(fd, FD_SETSIZE);
  1264. if (fd > fdmax)
  1265. fdmax = fd;
  1266. uint32_t ff = pdispatcher->GetRequestedEvents();
  1267. if (ff & (DE_READ | DE_ACCEPT))
  1268. FD_SET(fd, &fdsRead);
  1269. if (ff & (DE_WRITE | DE_CONNECT))
  1270. FD_SET(fd, &fdsWrite);
  1271. }
  1272. }
  1273. // Wait then call handlers as appropriate
  1274. // < 0 means error
  1275. // 0 means timeout
  1276. // > 0 means count of descriptors ready
  1277. int n = select(fdmax + 1, &fdsRead, &fdsWrite, nullptr, ptvWait);
  1278. // If error, return error.
  1279. if (n < 0) {
  1280. if (errno != EINTR) {
  1281. RTC_LOG_E(LS_ERROR, EN, errno) << "select";
  1282. return false;
  1283. }
  1284. // Else ignore the error and keep going. If this EINTR was for one of the
  1285. // signals managed by this PhysicalSocketServer, the
  1286. // PosixSignalDeliveryDispatcher will be in the signaled state in the next
  1287. // iteration.
  1288. } else if (n == 0) {
  1289. // If timeout, return success
  1290. return true;
  1291. } else {
  1292. // We have signaled descriptors
  1293. CritScope cr(&crit_);
  1294. processing_dispatchers_ = true;
  1295. for (Dispatcher* pdispatcher : dispatchers_) {
  1296. int fd = pdispatcher->GetDescriptor();
  1297. bool readable = FD_ISSET(fd, &fdsRead);
  1298. if (readable) {
  1299. FD_CLR(fd, &fdsRead);
  1300. }
  1301. bool writable = FD_ISSET(fd, &fdsWrite);
  1302. if (writable) {
  1303. FD_CLR(fd, &fdsWrite);
  1304. }
  1305. // The error code can be signaled through reads or writes.
  1306. ProcessEvents(pdispatcher, readable, writable, readable || writable);
  1307. }
  1308. processing_dispatchers_ = false;
  1309. // Process deferred dispatchers that have been added/removed while the
  1310. // events were handled above.
  1311. AddRemovePendingDispatchers();
  1312. }
  1313. // Recalc the time remaining to wait. Doing it here means it doesn't get
  1314. // calced twice the first time through the loop
  1315. if (ptvWait) {
  1316. ptvWait->tv_sec = 0;
  1317. ptvWait->tv_usec = 0;
  1318. int64_t time_left_us = stop_us - rtc::TimeMicros();
  1319. if (time_left_us > 0) {
  1320. ptvWait->tv_sec = time_left_us / rtc::kNumMicrosecsPerSec;
  1321. ptvWait->tv_usec = time_left_us % rtc::kNumMicrosecsPerSec;
  1322. }
  1323. }
  1324. }
  1325. return true;
  1326. }
  1327. #if defined(WEBRTC_USE_EPOLL)
  1328. // Initial number of events to process with one call to "epoll_wait".
  1329. static const size_t kInitialEpollEvents = 128;
  1330. // Maximum number of events to process with one call to "epoll_wait".
  1331. static const size_t kMaxEpollEvents = 8192;
  1332. void PhysicalSocketServer::AddEpoll(Dispatcher* pdispatcher) {
  1333. RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
  1334. int fd = pdispatcher->GetDescriptor();
  1335. RTC_DCHECK(fd != INVALID_SOCKET);
  1336. if (fd == INVALID_SOCKET) {
  1337. return;
  1338. }
  1339. struct epoll_event event = {0};
  1340. event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
  1341. event.data.ptr = pdispatcher;
  1342. int err = epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &event);
  1343. RTC_DCHECK_EQ(err, 0);
  1344. if (err == -1) {
  1345. RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_ADD";
  1346. }
  1347. }
  1348. void PhysicalSocketServer::RemoveEpoll(Dispatcher* pdispatcher) {
  1349. RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
  1350. int fd = pdispatcher->GetDescriptor();
  1351. RTC_DCHECK(fd != INVALID_SOCKET);
  1352. if (fd == INVALID_SOCKET) {
  1353. return;
  1354. }
  1355. struct epoll_event event = {0};
  1356. int err = epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &event);
  1357. RTC_DCHECK(err == 0 || errno == ENOENT);
  1358. if (err == -1) {
  1359. if (errno == ENOENT) {
  1360. // Socket has already been closed.
  1361. RTC_LOG_E(LS_VERBOSE, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
  1362. } else {
  1363. RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_DEL";
  1364. }
  1365. }
  1366. }
  1367. void PhysicalSocketServer::UpdateEpoll(Dispatcher* pdispatcher) {
  1368. RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
  1369. int fd = pdispatcher->GetDescriptor();
  1370. RTC_DCHECK(fd != INVALID_SOCKET);
  1371. if (fd == INVALID_SOCKET) {
  1372. return;
  1373. }
  1374. struct epoll_event event = {0};
  1375. event.events = GetEpollEvents(pdispatcher->GetRequestedEvents());
  1376. event.data.ptr = pdispatcher;
  1377. int err = epoll_ctl(epoll_fd_, EPOLL_CTL_MOD, fd, &event);
  1378. RTC_DCHECK_EQ(err, 0);
  1379. if (err == -1) {
  1380. RTC_LOG_E(LS_ERROR, EN, errno) << "epoll_ctl EPOLL_CTL_MOD";
  1381. }
  1382. }
  1383. bool PhysicalSocketServer::WaitEpoll(int cmsWait) {
  1384. RTC_DCHECK(epoll_fd_ != INVALID_SOCKET);
  1385. int64_t tvWait = -1;
  1386. int64_t tvStop = -1;
  1387. if (cmsWait != kForever) {
  1388. tvWait = cmsWait;
  1389. tvStop = TimeAfter(cmsWait);
  1390. }
  1391. if (epoll_events_.empty()) {
  1392. // The initial space to receive events is created only if epoll is used.
  1393. epoll_events_.resize(kInitialEpollEvents);
  1394. }
  1395. fWait_ = true;
  1396. while (fWait_) {
  1397. // Wait then call handlers as appropriate
  1398. // < 0 means error
  1399. // 0 means timeout
  1400. // > 0 means count of descriptors ready
  1401. int n = epoll_wait(epoll_fd_, &epoll_events_[0],
  1402. static_cast<int>(epoll_events_.size()),
  1403. static_cast<int>(tvWait));
  1404. if (n < 0) {
  1405. if (errno != EINTR) {
  1406. RTC_LOG_E(LS_ERROR, EN, errno) << "epoll";
  1407. return false;
  1408. }
  1409. // Else ignore the error and keep going. If this EINTR was for one of the
  1410. // signals managed by this PhysicalSocketServer, the
  1411. // PosixSignalDeliveryDispatcher will be in the signaled state in the next
  1412. // iteration.
  1413. } else if (n == 0) {
  1414. // If timeout, return success
  1415. return true;
  1416. } else {
  1417. // We have signaled descriptors
  1418. CritScope cr(&crit_);
  1419. for (int i = 0; i < n; ++i) {
  1420. const epoll_event& event = epoll_events_[i];
  1421. Dispatcher* pdispatcher = static_cast<Dispatcher*>(event.data.ptr);
  1422. if (dispatchers_.find(pdispatcher) == dispatchers_.end()) {
  1423. // The dispatcher for this socket no longer exists.
  1424. continue;
  1425. }
  1426. bool readable = (event.events & (EPOLLIN | EPOLLPRI));
  1427. bool writable = (event.events & EPOLLOUT);
  1428. bool check_error = (event.events & (EPOLLRDHUP | EPOLLERR | EPOLLHUP));
  1429. ProcessEvents(pdispatcher, readable, writable, check_error);
  1430. }
  1431. }
  1432. if (static_cast<size_t>(n) == epoll_events_.size() &&
  1433. epoll_events_.size() < kMaxEpollEvents) {
  1434. // We used the complete space to receive events, increase size for future
  1435. // iterations.
  1436. epoll_events_.resize(std::max(epoll_events_.size() * 2, kMaxEpollEvents));
  1437. }
  1438. if (cmsWait != kForever) {
  1439. tvWait = TimeDiff(tvStop, TimeMillis());
  1440. if (tvWait < 0) {
  1441. // Return success on timeout.
  1442. return true;
  1443. }
  1444. }
  1445. }
  1446. return true;
  1447. }
  1448. bool PhysicalSocketServer::WaitPoll(int cmsWait, Dispatcher* dispatcher) {
  1449. RTC_DCHECK(dispatcher);
  1450. int64_t tvWait = -1;
  1451. int64_t tvStop = -1;
  1452. if (cmsWait != kForever) {
  1453. tvWait = cmsWait;
  1454. tvStop = TimeAfter(cmsWait);
  1455. }
  1456. fWait_ = true;
  1457. struct pollfd fds = {0};
  1458. int fd = dispatcher->GetDescriptor();
  1459. fds.fd = fd;
  1460. while (fWait_) {
  1461. uint32_t ff = dispatcher->GetRequestedEvents();
  1462. fds.events = 0;
  1463. if (ff & (DE_READ | DE_ACCEPT)) {
  1464. fds.events |= POLLIN;
  1465. }
  1466. if (ff & (DE_WRITE | DE_CONNECT)) {
  1467. fds.events |= POLLOUT;
  1468. }
  1469. fds.revents = 0;
  1470. // Wait then call handlers as appropriate
  1471. // < 0 means error
  1472. // 0 means timeout
  1473. // > 0 means count of descriptors ready
  1474. int n = poll(&fds, 1, static_cast<int>(tvWait));
  1475. if (n < 0) {
  1476. if (errno != EINTR) {
  1477. RTC_LOG_E(LS_ERROR, EN, errno) << "poll";
  1478. return false;
  1479. }
  1480. // Else ignore the error and keep going. If this EINTR was for one of the
  1481. // signals managed by this PhysicalSocketServer, the
  1482. // PosixSignalDeliveryDispatcher will be in the signaled state in the next
  1483. // iteration.
  1484. } else if (n == 0) {
  1485. // If timeout, return success
  1486. return true;
  1487. } else {
  1488. // We have signaled descriptors (should only be the passed dispatcher).
  1489. RTC_DCHECK_EQ(n, 1);
  1490. RTC_DCHECK_EQ(fds.fd, fd);
  1491. bool readable = (fds.revents & (POLLIN | POLLPRI));
  1492. bool writable = (fds.revents & POLLOUT);
  1493. bool check_error = (fds.revents & (POLLRDHUP | POLLERR | POLLHUP));
  1494. ProcessEvents(dispatcher, readable, writable, check_error);
  1495. }
  1496. if (cmsWait != kForever) {
  1497. tvWait = TimeDiff(tvStop, TimeMillis());
  1498. if (tvWait < 0) {
  1499. // Return success on timeout.
  1500. return true;
  1501. }
  1502. }
  1503. }
  1504. return true;
  1505. }
  1506. #endif // WEBRTC_USE_EPOLL
  1507. static void GlobalSignalHandler(int signum) {
  1508. PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
  1509. }
  1510. bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
  1511. void (*handler)(int)) {
  1512. // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
  1513. // otherwise set one.
  1514. if (handler == SIG_IGN || handler == SIG_DFL) {
  1515. if (!InstallSignal(signum, handler)) {
  1516. return false;
  1517. }
  1518. if (signal_dispatcher_) {
  1519. signal_dispatcher_->ClearHandler(signum);
  1520. if (!signal_dispatcher_->HasHandlers()) {
  1521. signal_dispatcher_.reset();
  1522. }
  1523. }
  1524. } else {
  1525. if (!signal_dispatcher_) {
  1526. signal_dispatcher_.reset(new PosixSignalDispatcher(this));
  1527. }
  1528. signal_dispatcher_->SetHandler(signum, handler);
  1529. if (!InstallSignal(signum, &GlobalSignalHandler)) {
  1530. return false;
  1531. }
  1532. }
  1533. return true;
  1534. }
  1535. Dispatcher* PhysicalSocketServer::signal_dispatcher() {
  1536. return signal_dispatcher_.get();
  1537. }
  1538. bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
  1539. struct sigaction act;
  1540. // It doesn't really matter what we set this mask to.
  1541. if (sigemptyset(&act.sa_mask) != 0) {
  1542. RTC_LOG_ERR(LS_ERROR) << "Couldn't set mask";
  1543. return false;
  1544. }
  1545. act.sa_handler = handler;
  1546. #if !defined(__native_client__)
  1547. // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
  1548. // and it's a nuisance. Though some syscalls still return EINTR and there's no
  1549. // real standard for which ones. :(
  1550. act.sa_flags = SA_RESTART;
  1551. #else
  1552. act.sa_flags = 0;
  1553. #endif
  1554. if (sigaction(signum, &act, nullptr) != 0) {
  1555. RTC_LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
  1556. return false;
  1557. }
  1558. return true;
  1559. }
  1560. #endif // WEBRTC_POSIX
  1561. #if defined(WEBRTC_WIN)
  1562. bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
  1563. int64_t cmsTotal = cmsWait;
  1564. int64_t cmsElapsed = 0;
  1565. int64_t msStart = Time();
  1566. fWait_ = true;
  1567. while (fWait_) {
  1568. std::vector<WSAEVENT> events;
  1569. std::vector<Dispatcher*> event_owners;
  1570. events.push_back(socket_ev_);
  1571. {
  1572. CritScope cr(&crit_);
  1573. // TODO(jbauch): Support re-entrant waiting.
  1574. RTC_DCHECK(!processing_dispatchers_);
  1575. // Calling "CheckSignalClose" might remove a closed dispatcher from the
  1576. // set. This must be deferred to prevent invalidating the iterator.
  1577. processing_dispatchers_ = true;
  1578. for (Dispatcher* disp : dispatchers_) {
  1579. if (!process_io && (disp != signal_wakeup_))
  1580. continue;
  1581. SOCKET s = disp->GetSocket();
  1582. if (disp->CheckSignalClose()) {
  1583. // We just signalled close, don't poll this socket
  1584. } else if (s != INVALID_SOCKET) {
  1585. WSAEventSelect(s, events[0],
  1586. FlagsToEvents(disp->GetRequestedEvents()));
  1587. } else {
  1588. events.push_back(disp->GetWSAEvent());
  1589. event_owners.push_back(disp);
  1590. }
  1591. }
  1592. processing_dispatchers_ = false;
  1593. // Process deferred dispatchers that have been added/removed while the
  1594. // events were handled above.
  1595. AddRemovePendingDispatchers();
  1596. }
  1597. // Which is shorter, the delay wait or the asked wait?
  1598. int64_t cmsNext;
  1599. if (cmsWait == kForever) {
  1600. cmsNext = cmsWait;
  1601. } else {
  1602. cmsNext = std::max<int64_t>(0, cmsTotal - cmsElapsed);
  1603. }
  1604. // Wait for one of the events to signal
  1605. DWORD dw =
  1606. WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()), &events[0],
  1607. false, static_cast<DWORD>(cmsNext), false);
  1608. if (dw == WSA_WAIT_FAILED) {
  1609. // Failed?
  1610. // TODO(pthatcher): need a better strategy than this!
  1611. WSAGetLastError();
  1612. RTC_NOTREACHED();
  1613. return false;
  1614. } else if (dw == WSA_WAIT_TIMEOUT) {
  1615. // Timeout?
  1616. return true;
  1617. } else {
  1618. // Figure out which one it is and call it
  1619. CritScope cr(&crit_);
  1620. int index = dw - WSA_WAIT_EVENT_0;
  1621. if (index > 0) {
  1622. --index; // The first event is the socket event
  1623. Dispatcher* disp = event_owners[index];
  1624. // The dispatcher could have been removed while waiting for events.
  1625. if (dispatchers_.find(disp) != dispatchers_.end()) {
  1626. disp->OnPreEvent(0);
  1627. disp->OnEvent(0, 0);
  1628. }
  1629. } else if (process_io) {
  1630. processing_dispatchers_ = true;
  1631. for (Dispatcher* disp : dispatchers_) {
  1632. SOCKET s = disp->GetSocket();
  1633. if (s == INVALID_SOCKET)
  1634. continue;
  1635. WSANETWORKEVENTS wsaEvents;
  1636. int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
  1637. if (err == 0) {
  1638. {
  1639. if ((wsaEvents.lNetworkEvents & FD_READ) &&
  1640. wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
  1641. RTC_LOG(WARNING)
  1642. << "PhysicalSocketServer got FD_READ_BIT error "
  1643. << wsaEvents.iErrorCode[FD_READ_BIT];
  1644. }
  1645. if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
  1646. wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
  1647. RTC_LOG(WARNING)
  1648. << "PhysicalSocketServer got FD_WRITE_BIT error "
  1649. << wsaEvents.iErrorCode[FD_WRITE_BIT];
  1650. }
  1651. if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
  1652. wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
  1653. RTC_LOG(WARNING)
  1654. << "PhysicalSocketServer got FD_CONNECT_BIT error "
  1655. << wsaEvents.iErrorCode[FD_CONNECT_BIT];
  1656. }
  1657. if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
  1658. wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
  1659. RTC_LOG(WARNING)
  1660. << "PhysicalSocketServer got FD_ACCEPT_BIT error "
  1661. << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
  1662. }
  1663. if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
  1664. wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
  1665. RTC_LOG(WARNING)
  1666. << "PhysicalSocketServer got FD_CLOSE_BIT error "
  1667. << wsaEvents.iErrorCode[FD_CLOSE_BIT];
  1668. }
  1669. }
  1670. uint32_t ff = 0;
  1671. int errcode = 0;
  1672. if (wsaEvents.lNetworkEvents & FD_READ)
  1673. ff |= DE_READ;
  1674. if (wsaEvents.lNetworkEvents & FD_WRITE)
  1675. ff |= DE_WRITE;
  1676. if (wsaEvents.lNetworkEvents & FD_CONNECT) {
  1677. if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
  1678. ff |= DE_CONNECT;
  1679. } else {
  1680. ff |= DE_CLOSE;
  1681. errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
  1682. }
  1683. }
  1684. if (wsaEvents.lNetworkEvents & FD_ACCEPT)
  1685. ff |= DE_ACCEPT;
  1686. if (wsaEvents.lNetworkEvents & FD_CLOSE) {
  1687. ff |= DE_CLOSE;
  1688. errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
  1689. }
  1690. if (ff != 0) {
  1691. disp->OnPreEvent(ff);
  1692. disp->OnEvent(ff, errcode);
  1693. }
  1694. }
  1695. }
  1696. processing_dispatchers_ = false;
  1697. // Process deferred dispatchers that have been added/removed while the
  1698. // events were handled above.
  1699. AddRemovePendingDispatchers();
  1700. }
  1701. // Reset the network event until new activity occurs
  1702. WSAResetEvent(socket_ev_);
  1703. }
  1704. // Break?
  1705. if (!fWait_)
  1706. break;
  1707. cmsElapsed = TimeSince(msStart);
  1708. if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
  1709. break;
  1710. }
  1711. }
  1712. // Done
  1713. return true;
  1714. }
  1715. #endif // WEBRTC_WIN
  1716. } // namespace rtc