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.

1658 lines
47 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2005, Google Inc.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. * 2. Redistributions in binary form must reproduce the above copyright notice,
  11. * this list of conditions and the following disclaimer in the documentation
  12. * and/or other materials provided with the distribution.
  13. * 3. The name of the author may not be used to endorse or promote products
  14. * derived from this software without specific prior written permission.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
  17. * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  18. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
  19. * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  20. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  21. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
  22. * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  23. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
  24. * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
  25. * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #if defined(_MSC_VER) && _MSC_VER < 1300
  28. #pragma warning(disable:4786)
  29. #endif
  30. #include <cassert>
  31. #ifdef POSIX
  32. #include <string.h>
  33. #include <errno.h>
  34. #include <fcntl.h>
  35. #include <sys/time.h>
  36. #include <unistd.h>
  37. #include <signal.h>
  38. #endif
  39. #ifdef WIN32
  40. #define WIN32_LEAN_AND_MEAN
  41. #include <windows.h>
  42. #include <winsock2.h>
  43. #include <ws2tcpip.h>
  44. #undef SetPort
  45. #endif
  46. #include <algorithm>
  47. #include <map>
  48. #include "talk/base/basictypes.h"
  49. #include "talk/base/byteorder.h"
  50. #include "talk/base/common.h"
  51. #include "talk/base/logging.h"
  52. #include "talk/base/nethelpers.h"
  53. #include "talk/base/physicalsocketserver.h"
  54. #include "talk/base/timeutils.h"
  55. #include "talk/base/winping.h"
  56. #include "talk/base/win32socketinit.h"
  57. // stm: this will tell us if we are on OSX
  58. #ifdef HAVE_CONFIG_H
  59. #include "config.h"
  60. #endif
  61. #ifdef POSIX
  62. #include <netinet/tcp.h> // for TCP_NODELAY
  63. #define IP_MTU 14 // Until this is integrated from linux/in.h to netinet/in.h
  64. typedef void* SockOptArg;
  65. #endif // POSIX
  66. #ifdef WIN32
  67. typedef char* SockOptArg;
  68. #endif
  69. namespace talk_base {
  70. // Standard MTUs, from RFC 1191
  71. const uint16 PACKET_MAXIMUMS[] = {
  72. 65535, // Theoretical maximum, Hyperchannel
  73. 32000, // Nothing
  74. 17914, // 16Mb IBM Token Ring
  75. 8166, // IEEE 802.4
  76. //4464, // IEEE 802.5 (4Mb max)
  77. 4352, // FDDI
  78. //2048, // Wideband Network
  79. 2002, // IEEE 802.5 (4Mb recommended)
  80. //1536, // Expermental Ethernet Networks
  81. //1500, // Ethernet, Point-to-Point (default)
  82. 1492, // IEEE 802.3
  83. 1006, // SLIP, ARPANET
  84. //576, // X.25 Networks
  85. //544, // DEC IP Portal
  86. //512, // NETBIOS
  87. 508, // IEEE 802/Source-Rt Bridge, ARCNET
  88. 296, // Point-to-Point (low delay)
  89. 68, // Official minimum
  90. 0, // End of list marker
  91. };
  92. static const int IP_HEADER_SIZE = 20u;
  93. static const int IPV6_HEADER_SIZE = 40u;
  94. static const int ICMP_HEADER_SIZE = 8u;
  95. static const int ICMP_PING_TIMEOUT_MILLIS = 10000u;
  96. class PhysicalSocket : public AsyncSocket, public sigslot::has_slots<> {
  97. public:
  98. PhysicalSocket(PhysicalSocketServer* ss, SOCKET s = INVALID_SOCKET)
  99. : ss_(ss), s_(s), enabled_events_(0), error_(0),
  100. state_((s == INVALID_SOCKET) ? CS_CLOSED : CS_CONNECTED),
  101. resolver_(NULL) {
  102. #ifdef WIN32
  103. // EnsureWinsockInit() ensures that winsock is initialized. The default
  104. // version of this function doesn't do anything because winsock is
  105. // initialized by constructor of a static object. If neccessary libjingle
  106. // users can link it with a different version of this function by replacing
  107. // win32socketinit.cc. See win32socketinit.cc for more details.
  108. EnsureWinsockInit();
  109. #endif
  110. if (s_ != INVALID_SOCKET) {
  111. enabled_events_ = DE_READ | DE_WRITE;
  112. int type = SOCK_STREAM;
  113. socklen_t len = sizeof(type);
  114. VERIFY(0 == getsockopt(s_, SOL_SOCKET, SO_TYPE, (SockOptArg)&type, &len));
  115. udp_ = (SOCK_DGRAM == type);
  116. }
  117. }
  118. virtual ~PhysicalSocket() {
  119. Close();
  120. }
  121. // Creates the underlying OS socket (same as the "socket" function).
  122. virtual bool Create(int family, int type) {
  123. Close();
  124. s_ = ::socket(family, type, 0);
  125. udp_ = (SOCK_DGRAM == type);
  126. UpdateLastError();
  127. if (udp_)
  128. enabled_events_ = DE_READ | DE_WRITE;
  129. return s_ != INVALID_SOCKET;
  130. }
  131. SocketAddress GetLocalAddress() const {
  132. sockaddr_storage addr_storage = {0};
  133. socklen_t addrlen = sizeof(addr_storage);
  134. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  135. int result = ::getsockname(s_, addr, &addrlen);
  136. SocketAddress address;
  137. if (result >= 0) {
  138. SocketAddressFromSockAddrStorage(addr_storage, &address);
  139. } else {
  140. LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket="
  141. << s_;
  142. }
  143. return address;
  144. }
  145. SocketAddress GetRemoteAddress() const {
  146. sockaddr_storage addr_storage = {0};
  147. socklen_t addrlen = sizeof(addr_storage);
  148. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  149. int result = ::getpeername(s_, addr, &addrlen);
  150. SocketAddress address;
  151. if (result >= 0) {
  152. SocketAddressFromSockAddrStorage(addr_storage, &address);
  153. } else {
  154. LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket="
  155. << s_;
  156. }
  157. return address;
  158. }
  159. int Bind(const SocketAddress& bind_addr) {
  160. sockaddr_storage addr_storage;
  161. size_t len = bind_addr.ToSockAddrStorage(&addr_storage);
  162. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  163. int err = ::bind(s_, addr, static_cast<int>(len));
  164. UpdateLastError();
  165. #ifdef _DEBUG
  166. if (0 == err) {
  167. dbg_addr_ = "Bound @ ";
  168. dbg_addr_.append(GetLocalAddress().ToString());
  169. }
  170. #endif // _DEBUG
  171. return err;
  172. }
  173. int Connect(const SocketAddress& addr) {
  174. // TODO: Implicit creation is required to reconnect...
  175. // ...but should we make it more explicit?
  176. if (state_ != CS_CLOSED) {
  177. SetError(EALREADY);
  178. return SOCKET_ERROR;
  179. }
  180. if (addr.IsUnresolved()) {
  181. LOG(LS_VERBOSE) << "Resolving addr in PhysicalSocket::Connect";
  182. resolver_ = new AsyncResolver();
  183. resolver_->set_address(addr);
  184. resolver_->SignalWorkDone.connect(this, &PhysicalSocket::OnResolveResult);
  185. resolver_->Start();
  186. state_ = CS_CONNECTING;
  187. return 0;
  188. }
  189. return DoConnect(addr);
  190. }
  191. int DoConnect(const SocketAddress& connect_addr) {
  192. if ((s_ == INVALID_SOCKET) &&
  193. !Create(connect_addr.family(), SOCK_STREAM)) {
  194. return SOCKET_ERROR;
  195. }
  196. sockaddr_storage addr_storage;
  197. size_t len = connect_addr.ToSockAddrStorage(&addr_storage);
  198. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  199. int err = ::connect(s_, addr, static_cast<int>(len));
  200. UpdateLastError();
  201. if (err == 0) {
  202. state_ = CS_CONNECTED;
  203. } else if (IsBlockingError(error_)) {
  204. state_ = CS_CONNECTING;
  205. enabled_events_ |= DE_CONNECT;
  206. } else {
  207. return SOCKET_ERROR;
  208. }
  209. enabled_events_ |= DE_READ | DE_WRITE;
  210. return 0;
  211. }
  212. int GetError() const {
  213. return error_;
  214. }
  215. void SetError(int error) {
  216. error_ = error;
  217. }
  218. ConnState GetState() const {
  219. return state_;
  220. }
  221. int GetOption(Option opt, int* value) {
  222. int slevel;
  223. int sopt;
  224. if (TranslateOption(opt, &slevel, &sopt) == -1)
  225. return -1;
  226. socklen_t optlen = sizeof(*value);
  227. int ret = ::getsockopt(s_, slevel, sopt, (SockOptArg)value, &optlen);
  228. if (ret != -1 && opt == OPT_DONTFRAGMENT) {
  229. #ifdef LINUX
  230. *value = (*value != IP_PMTUDISC_DONT) ? 1 : 0;
  231. #endif
  232. }
  233. return ret;
  234. }
  235. int SetOption(Option opt, int value) {
  236. int slevel;
  237. int sopt;
  238. if (TranslateOption(opt, &slevel, &sopt) == -1)
  239. return -1;
  240. if (opt == OPT_DONTFRAGMENT) {
  241. #ifdef LINUX
  242. value = (value) ? IP_PMTUDISC_DO : IP_PMTUDISC_DONT;
  243. #endif
  244. }
  245. return ::setsockopt(s_, slevel, sopt, (SockOptArg)&value, sizeof(value));
  246. }
  247. int Send(const void *pv, size_t cb) {
  248. int sent = ::send(s_, reinterpret_cast<const char *>(pv), (int)cb,
  249. #ifdef LINUX
  250. // Suppress SIGPIPE. Without this, attempting to send on a socket whose
  251. // other end is closed will result in a SIGPIPE signal being raised to
  252. // our process, which by default will terminate the process, which we
  253. // don't want. By specifying this flag, we'll just get the error EPIPE
  254. // instead and can handle the error gracefully.
  255. MSG_NOSIGNAL
  256. #else
  257. 0
  258. #endif
  259. );
  260. UpdateLastError();
  261. // We have seen minidumps where this may be false.
  262. ASSERT(sent <= static_cast<int>(cb));
  263. if ((sent < 0) && IsBlockingError(error_)) {
  264. enabled_events_ |= DE_WRITE;
  265. }
  266. return sent;
  267. }
  268. int SendTo(const void* buffer, size_t length, const SocketAddress& addr) {
  269. sockaddr_storage saddr;
  270. size_t len = addr.ToSockAddrStorage(&saddr);
  271. int sent = ::sendto(
  272. s_, static_cast<const char *>(buffer), static_cast<int>(length),
  273. #ifdef LINUX
  274. // Suppress SIGPIPE. See above for explanation.
  275. MSG_NOSIGNAL,
  276. #else
  277. 0,
  278. #endif
  279. reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len));
  280. UpdateLastError();
  281. // We have seen minidumps where this may be false.
  282. ASSERT(sent <= static_cast<int>(length));
  283. if ((sent < 0) && IsBlockingError(error_)) {
  284. enabled_events_ |= DE_WRITE;
  285. }
  286. return sent;
  287. }
  288. int Recv(void* buffer, size_t length) {
  289. int received = ::recv(s_, static_cast<char*>(buffer),
  290. static_cast<int>(length), 0);
  291. if ((received == 0) && (length != 0)) {
  292. // Note: on graceful shutdown, recv can return 0. In this case, we
  293. // pretend it is blocking, and then signal close, so that simplifying
  294. // assumptions can be made about Recv.
  295. LOG(LS_WARNING) << "EOF from socket; deferring close event";
  296. // Must turn this back on so that the select() loop will notice the close
  297. // event.
  298. enabled_events_ |= DE_READ;
  299. error_ = EWOULDBLOCK;
  300. return SOCKET_ERROR;
  301. }
  302. UpdateLastError();
  303. bool success = (received >= 0) || IsBlockingError(error_);
  304. if (udp_ || success) {
  305. enabled_events_ |= DE_READ;
  306. }
  307. if (!success) {
  308. LOG_F(LS_VERBOSE) << "Error = " << error_;
  309. }
  310. return received;
  311. }
  312. int RecvFrom(void* buffer, size_t length, SocketAddress *out_addr) {
  313. sockaddr_storage addr_storage;
  314. socklen_t addr_len = sizeof(addr_storage);
  315. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  316. int received = ::recvfrom(s_, static_cast<char*>(buffer),
  317. static_cast<int>(length), 0, addr, &addr_len);
  318. UpdateLastError();
  319. if ((received >= 0) && (out_addr != NULL))
  320. SocketAddressFromSockAddrStorage(addr_storage, out_addr);
  321. bool success = (received >= 0) || IsBlockingError(error_);
  322. if (udp_ || success) {
  323. enabled_events_ |= DE_READ;
  324. }
  325. if (!success) {
  326. LOG_F(LS_VERBOSE) << "Error = " << error_;
  327. }
  328. return received;
  329. }
  330. int Listen(int backlog) {
  331. int err = ::listen(s_, backlog);
  332. UpdateLastError();
  333. if (err == 0) {
  334. state_ = CS_CONNECTING;
  335. enabled_events_ |= DE_ACCEPT;
  336. #ifdef _DEBUG
  337. dbg_addr_ = "Listening @ ";
  338. dbg_addr_.append(GetLocalAddress().ToString());
  339. #endif // _DEBUG
  340. }
  341. return err;
  342. }
  343. AsyncSocket* Accept(SocketAddress *out_addr) {
  344. sockaddr_storage addr_storage;
  345. socklen_t addr_len = sizeof(addr_storage);
  346. sockaddr* addr = reinterpret_cast<sockaddr*>(&addr_storage);
  347. SOCKET s = ::accept(s_, addr, &addr_len);
  348. UpdateLastError();
  349. if (s == INVALID_SOCKET)
  350. return NULL;
  351. enabled_events_ |= DE_ACCEPT;
  352. if (out_addr != NULL)
  353. SocketAddressFromSockAddrStorage(addr_storage, out_addr);
  354. return ss_->WrapSocket(s);
  355. }
  356. int Close() {
  357. if (s_ == INVALID_SOCKET)
  358. return 0;
  359. int err = ::closesocket(s_);
  360. UpdateLastError();
  361. s_ = INVALID_SOCKET;
  362. state_ = CS_CLOSED;
  363. enabled_events_ = 0;
  364. if (resolver_) {
  365. resolver_->Destroy(false);
  366. resolver_ = NULL;
  367. }
  368. return err;
  369. }
  370. int EstimateMTU(uint16* mtu) {
  371. SocketAddress addr = GetRemoteAddress();
  372. if (addr.IsAny()) {
  373. error_ = ENOTCONN;
  374. return -1;
  375. }
  376. #if defined(WIN32)
  377. // Gets the interface MTU (TTL=1) for the interface used to reach |addr|.
  378. WinPing ping;
  379. if (!ping.IsValid()) {
  380. error_ = EINVAL; // can't think of a better error ID
  381. return -1;
  382. }
  383. int header_size = ICMP_HEADER_SIZE;
  384. if (addr.family() == AF_INET6) {
  385. header_size += IPV6_HEADER_SIZE;
  386. } else if (addr.family() == AF_INET) {
  387. header_size += IP_HEADER_SIZE;
  388. }
  389. for (int level = 0; PACKET_MAXIMUMS[level + 1] > 0; ++level) {
  390. int32 size = PACKET_MAXIMUMS[level] - header_size;
  391. WinPing::PingResult result = ping.Ping(addr.ipaddr(), size,
  392. ICMP_PING_TIMEOUT_MILLIS,
  393. 1, false);
  394. if (result == WinPing::PING_FAIL) {
  395. error_ = EINVAL; // can't think of a better error ID
  396. return -1;
  397. } else if (result != WinPing::PING_TOO_LARGE) {
  398. *mtu = PACKET_MAXIMUMS[level];
  399. return 0;
  400. }
  401. }
  402. ASSERT(false);
  403. return -1;
  404. #elif defined(IOS) || defined(OSX)
  405. // No simple way to do this on Mac OS X.
  406. // SIOCGIFMTU would work if we knew which interface would be used, but
  407. // figuring that out is pretty complicated. For now we'll return an error
  408. // and let the caller pick a default MTU.
  409. error_ = EINVAL;
  410. return -1;
  411. #elif defined(LINUX) || defined(ANDROID)
  412. // Gets the path MTU.
  413. int value;
  414. socklen_t vlen = sizeof(value);
  415. int err = getsockopt(s_, IPPROTO_IP, IP_MTU, &value, &vlen);
  416. if (err < 0) {
  417. UpdateLastError();
  418. return err;
  419. }
  420. ASSERT((0 <= value) && (value <= 65536));
  421. *mtu = value;
  422. return 0;
  423. #endif
  424. }
  425. SocketServer* socketserver() { return ss_; }
  426. protected:
  427. void OnResolveResult(SignalThread* thread) {
  428. if (thread != resolver_) {
  429. return;
  430. }
  431. int error = resolver_->error();
  432. if (error == 0) {
  433. error = DoConnect(resolver_->address());
  434. } else {
  435. Close();
  436. }
  437. if (error) {
  438. error_ = error;
  439. SignalCloseEvent(this, error_);
  440. }
  441. }
  442. void UpdateLastError() {
  443. error_ = LAST_SYSTEM_ERROR;
  444. }
  445. static int TranslateOption(Option opt, int* slevel, int* sopt) {
  446. switch (opt) {
  447. case OPT_DONTFRAGMENT:
  448. #ifdef WIN32
  449. *slevel = IPPROTO_IP;
  450. *sopt = IP_DONTFRAGMENT;
  451. break;
  452. #elif defined(IOS) || defined(OSX) || defined(BSD)
  453. LOG(LS_WARNING) << "Socket::OPT_DONTFRAGMENT not supported.";
  454. return -1;
  455. #elif defined(POSIX)
  456. *slevel = IPPROTO_IP;
  457. *sopt = IP_MTU_DISCOVER;
  458. break;
  459. #endif
  460. case OPT_RCVBUF:
  461. *slevel = SOL_SOCKET;
  462. *sopt = SO_RCVBUF;
  463. break;
  464. case OPT_SNDBUF:
  465. *slevel = SOL_SOCKET;
  466. *sopt = SO_SNDBUF;
  467. break;
  468. case OPT_NODELAY:
  469. *slevel = IPPROTO_TCP;
  470. *sopt = TCP_NODELAY;
  471. break;
  472. default:
  473. ASSERT(false);
  474. return -1;
  475. }
  476. return 0;
  477. }
  478. PhysicalSocketServer* ss_;
  479. SOCKET s_;
  480. uint8 enabled_events_;
  481. bool udp_;
  482. int error_;
  483. ConnState state_;
  484. AsyncResolver* resolver_;
  485. #ifdef _DEBUG
  486. std::string dbg_addr_;
  487. #endif // _DEBUG;
  488. };
  489. #ifdef POSIX
  490. class EventDispatcher : public Dispatcher {
  491. public:
  492. EventDispatcher(PhysicalSocketServer* ss) : ss_(ss), fSignaled_(false) {
  493. if (pipe(afd_) < 0)
  494. LOG(LERROR) << "pipe failed";
  495. ss_->Add(this);
  496. }
  497. virtual ~EventDispatcher() {
  498. ss_->Remove(this);
  499. close(afd_[0]);
  500. close(afd_[1]);
  501. }
  502. virtual void Signal() {
  503. CritScope cs(&crit_);
  504. if (!fSignaled_) {
  505. const uint8 b[1] = { 0 };
  506. if (VERIFY(1 == write(afd_[1], b, sizeof(b)))) {
  507. fSignaled_ = true;
  508. }
  509. }
  510. }
  511. virtual uint32 GetRequestedEvents() {
  512. return DE_READ;
  513. }
  514. virtual void OnPreEvent(uint32 ff) {
  515. // It is not possible to perfectly emulate an auto-resetting event with
  516. // pipes. This simulates it by resetting before the event is handled.
  517. CritScope cs(&crit_);
  518. if (fSignaled_) {
  519. uint8 b[4]; // Allow for reading more than 1 byte, but expect 1.
  520. VERIFY(1 == read(afd_[0], b, sizeof(b)));
  521. fSignaled_ = false;
  522. }
  523. }
  524. virtual void OnEvent(uint32 ff, int err) {
  525. ASSERT(false);
  526. }
  527. virtual int GetDescriptor() {
  528. return afd_[0];
  529. }
  530. virtual bool IsDescriptorClosed() {
  531. return false;
  532. }
  533. private:
  534. PhysicalSocketServer *ss_;
  535. int afd_[2];
  536. bool fSignaled_;
  537. CriticalSection crit_;
  538. };
  539. // These two classes use the self-pipe trick to deliver POSIX signals to our
  540. // select loop. This is the only safe, reliable, cross-platform way to do
  541. // non-trivial things with a POSIX signal in an event-driven program (until
  542. // proper pselect() implementations become ubiquitous).
  543. class PosixSignalHandler {
  544. public:
  545. // POSIX only specifies 32 signals, but in principle the system might have
  546. // more and the programmer might choose to use them, so we size our array
  547. // for 128.
  548. static const int kNumPosixSignals = 128;
  549. // There is just a single global instance. (Signal handlers do not get any
  550. // sort of user-defined void * parameter, so they can't access anything that
  551. // isn't global.)
  552. static PosixSignalHandler* Instance() {
  553. LIBJINGLE_DEFINE_STATIC_LOCAL(PosixSignalHandler, instance, ());
  554. return &instance;
  555. }
  556. // Returns true if the given signal number is set.
  557. bool IsSignalSet(int signum) const {
  558. ASSERT(signum < ARRAY_SIZE(received_signal_));
  559. if (signum < ARRAY_SIZE(received_signal_)) {
  560. return received_signal_[signum];
  561. } else {
  562. return false;
  563. }
  564. }
  565. // Clears the given signal number.
  566. void ClearSignal(int signum) {
  567. ASSERT(signum < ARRAY_SIZE(received_signal_));
  568. if (signum < ARRAY_SIZE(received_signal_)) {
  569. received_signal_[signum] = false;
  570. }
  571. }
  572. // Returns the file descriptor to monitor for signal events.
  573. int GetDescriptor() const {
  574. return afd_[0];
  575. }
  576. // This is called directly from our real signal handler, so it must be
  577. // signal-handler-safe. That means it cannot assume anything about the
  578. // user-level state of the process, since the handler could be executed at any
  579. // time on any thread.
  580. void OnPosixSignalReceived(int signum) {
  581. if (signum >= ARRAY_SIZE(received_signal_)) {
  582. // We don't have space in our array for this.
  583. return;
  584. }
  585. // Set a flag saying we've seen this signal.
  586. received_signal_[signum] = true;
  587. // Notify application code that we got a signal.
  588. const uint8 b[1] = { 0 };
  589. if (-1 == write(afd_[1], b, sizeof(b))) {
  590. // Nothing we can do here. If there's an error somehow then there's
  591. // nothing we can safely do from a signal handler.
  592. // No, we can't even safely log it.
  593. // But, we still have to check the return value here. Otherwise,
  594. // GCC 4.4.1 complains ignoring return value. Even (void) doesn't help.
  595. return;
  596. }
  597. }
  598. private:
  599. PosixSignalHandler() {
  600. if (pipe(afd_) < 0) {
  601. LOG_ERR(LS_ERROR) << "pipe failed";
  602. return;
  603. }
  604. if (fcntl(afd_[0], F_SETFL, O_NONBLOCK) < 0) {
  605. LOG_ERR(LS_WARNING) << "fcntl #1 failed";
  606. }
  607. if (fcntl(afd_[1], F_SETFL, O_NONBLOCK) < 0) {
  608. LOG_ERR(LS_WARNING) << "fcntl #2 failed";
  609. }
  610. memset(const_cast<void *>(static_cast<volatile void *>(received_signal_)),
  611. 0,
  612. sizeof(received_signal_));
  613. }
  614. ~PosixSignalHandler() {
  615. int fd1 = afd_[0];
  616. int fd2 = afd_[1];
  617. // We clobber the stored file descriptor numbers here or else in principle
  618. // a signal that happens to be delivered during application termination
  619. // could erroneously write a zero byte to an unrelated file handle in
  620. // OnPosixSignalReceived() if some other file happens to be opened later
  621. // during shutdown and happens to be given the same file descriptor number
  622. // as our pipe had. Unfortunately even with this precaution there is still a
  623. // race where that could occur if said signal happens to be handled
  624. // concurrently with this code and happens to have already read the value of
  625. // afd_[1] from memory before we clobber it, but that's unlikely.
  626. afd_[0] = -1;
  627. afd_[1] = -1;
  628. close(fd1);
  629. close(fd2);
  630. }
  631. int afd_[2];
  632. // These are boolean flags that will be set in our signal handler and read
  633. // and cleared from Wait(). There is a race involved in this, but it is
  634. // benign. The signal handler sets the flag before signaling the pipe, so
  635. // we'll never end up blocking in select() while a flag is still true.
  636. // However, if two of the same signal arrive close to each other then it's
  637. // possible that the second time the handler may set the flag while it's still
  638. // true, meaning that signal will be missed. But the first occurrence of it
  639. // will still be handled, so this isn't a problem.
  640. // Volatile is not necessary here for correctness, but this data _is_ volatile
  641. // so I've marked it as such.
  642. volatile uint8 received_signal_[kNumPosixSignals];
  643. };
  644. class PosixSignalDispatcher : public Dispatcher {
  645. public:
  646. PosixSignalDispatcher(PhysicalSocketServer *owner) : owner_(owner) {
  647. owner_->Add(this);
  648. }
  649. virtual ~PosixSignalDispatcher() {
  650. owner_->Remove(this);
  651. }
  652. virtual uint32 GetRequestedEvents() {
  653. return DE_READ;
  654. }
  655. virtual void OnPreEvent(uint32 ff) {
  656. // Events might get grouped if signals come very fast, so we read out up to
  657. // 16 bytes to make sure we keep the pipe empty.
  658. uint8 b[16];
  659. ssize_t ret = read(GetDescriptor(), b, sizeof(b));
  660. if (ret < 0) {
  661. LOG_ERR(LS_WARNING) << "Error in read()";
  662. } else if (ret == 0) {
  663. LOG(LS_WARNING) << "Should have read at least one byte";
  664. }
  665. }
  666. virtual void OnEvent(uint32 ff, int err) {
  667. for (int signum = 0; signum < PosixSignalHandler::kNumPosixSignals;
  668. ++signum) {
  669. if (PosixSignalHandler::Instance()->IsSignalSet(signum)) {
  670. PosixSignalHandler::Instance()->ClearSignal(signum);
  671. HandlerMap::iterator i = handlers_.find(signum);
  672. if (i == handlers_.end()) {
  673. // This can happen if a signal is delivered to our process at around
  674. // the same time as we unset our handler for it. It is not an error
  675. // condition, but it's unusual enough to be worth logging.
  676. LOG(LS_INFO) << "Received signal with no handler: " << signum;
  677. } else {
  678. // Otherwise, execute our handler.
  679. (*i->second)(signum);
  680. }
  681. }
  682. }
  683. }
  684. virtual int GetDescriptor() {
  685. return PosixSignalHandler::Instance()->GetDescriptor();
  686. }
  687. virtual bool IsDescriptorClosed() {
  688. return false;
  689. }
  690. void SetHandler(int signum, void (*handler)(int)) {
  691. handlers_[signum] = handler;
  692. }
  693. void ClearHandler(int signum) {
  694. handlers_.erase(signum);
  695. }
  696. bool HasHandlers() {
  697. return !handlers_.empty();
  698. }
  699. private:
  700. typedef std::map<int, void (*)(int)> HandlerMap;
  701. HandlerMap handlers_;
  702. // Our owner.
  703. PhysicalSocketServer *owner_;
  704. };
  705. class SocketDispatcher : public Dispatcher, public PhysicalSocket {
  706. public:
  707. explicit SocketDispatcher(PhysicalSocketServer *ss) : PhysicalSocket(ss) {
  708. }
  709. SocketDispatcher(SOCKET s, PhysicalSocketServer *ss) : PhysicalSocket(ss, s) {
  710. }
  711. virtual ~SocketDispatcher() {
  712. Close();
  713. }
  714. bool Initialize() {
  715. ss_->Add(this);
  716. fcntl(s_, F_SETFL, fcntl(s_, F_GETFL, 0) | O_NONBLOCK);
  717. return true;
  718. }
  719. virtual bool Create(int type) {
  720. return Create(AF_INET, type);
  721. }
  722. virtual bool Create(int family, int type) {
  723. // Change the socket to be non-blocking.
  724. if (!PhysicalSocket::Create(family, type))
  725. return false;
  726. return Initialize();
  727. }
  728. virtual int GetDescriptor() {
  729. return s_;
  730. }
  731. virtual bool IsDescriptorClosed() {
  732. // We don't have a reliable way of distinguishing end-of-stream
  733. // from readability. So test on each readable call. Is this
  734. // inefficient? Probably.
  735. char ch;
  736. ssize_t res = ::recv(s_, &ch, 1, MSG_PEEK);
  737. if (res > 0) {
  738. // Data available, so not closed.
  739. return false;
  740. } else if (res == 0) {
  741. // EOF, so closed.
  742. return true;
  743. } else { // error
  744. switch (errno) {
  745. // Returned if we've already closed s_.
  746. case EBADF:
  747. // Returned during ungraceful peer shutdown.
  748. case ECONNRESET:
  749. return true;
  750. default:
  751. // Assume that all other errors are just blocking errors, meaning the
  752. // connection is still good but we just can't read from it right now.
  753. // This should only happen when connecting (and at most once), because
  754. // in all other cases this function is only called if the file
  755. // descriptor is already known to be in the readable state. However,
  756. // it's not necessary a problem if we spuriously interpret a
  757. // "connection lost"-type error as a blocking error, because typically
  758. // the next recv() will get EOF, so we'll still eventually notice that
  759. // the socket is closed.
  760. LOG_ERR(LS_WARNING) << "Assuming benign blocking error";
  761. return false;
  762. }
  763. }
  764. }
  765. virtual uint32 GetRequestedEvents() {
  766. return enabled_events_;
  767. }
  768. virtual void OnPreEvent(uint32 ff) {
  769. if ((ff & DE_CONNECT) != 0)
  770. state_ = CS_CONNECTED;
  771. if ((ff & DE_CLOSE) != 0)
  772. state_ = CS_CLOSED;
  773. }
  774. virtual void OnEvent(uint32 ff, int err) {
  775. // Make sure we deliver connect/accept first. Otherwise, consumers may see
  776. // something like a READ followed by a CONNECT, which would be odd.
  777. if ((ff & DE_CONNECT) != 0) {
  778. enabled_events_ &= ~DE_CONNECT;
  779. SignalConnectEvent(this);
  780. }
  781. if ((ff & DE_ACCEPT) != 0) {
  782. enabled_events_ &= ~DE_ACCEPT;
  783. SignalReadEvent(this);
  784. }
  785. if ((ff & DE_READ) != 0) {
  786. enabled_events_ &= ~DE_READ;
  787. SignalReadEvent(this);
  788. }
  789. if ((ff & DE_WRITE) != 0) {
  790. enabled_events_ &= ~DE_WRITE;
  791. SignalWriteEvent(this);
  792. }
  793. if ((ff & DE_CLOSE) != 0) {
  794. // The socket is now dead to us, so stop checking it.
  795. enabled_events_ = 0;
  796. SignalCloseEvent(this, err);
  797. }
  798. }
  799. virtual int Close() {
  800. if (s_ == INVALID_SOCKET)
  801. return 0;
  802. ss_->Remove(this);
  803. return PhysicalSocket::Close();
  804. }
  805. };
  806. class FileDispatcher: public Dispatcher, public AsyncFile {
  807. public:
  808. FileDispatcher(int fd, PhysicalSocketServer *ss) : ss_(ss), fd_(fd) {
  809. set_readable(true);
  810. ss_->Add(this);
  811. fcntl(fd_, F_SETFL, fcntl(fd_, F_GETFL, 0) | O_NONBLOCK);
  812. }
  813. virtual ~FileDispatcher() {
  814. ss_->Remove(this);
  815. }
  816. SocketServer* socketserver() { return ss_; }
  817. virtual int GetDescriptor() {
  818. return fd_;
  819. }
  820. virtual bool IsDescriptorClosed() {
  821. return false;
  822. }
  823. virtual uint32 GetRequestedEvents() {
  824. return flags_;
  825. }
  826. virtual void OnPreEvent(uint32 ff) {
  827. }
  828. virtual void OnEvent(uint32 ff, int err) {
  829. if ((ff & DE_READ) != 0)
  830. SignalReadEvent(this);
  831. if ((ff & DE_WRITE) != 0)
  832. SignalWriteEvent(this);
  833. if ((ff & DE_CLOSE) != 0)
  834. SignalCloseEvent(this, err);
  835. }
  836. virtual bool readable() {
  837. return (flags_ & DE_READ) != 0;
  838. }
  839. virtual void set_readable(bool value) {
  840. flags_ = value ? (flags_ | DE_READ) : (flags_ & ~DE_READ);
  841. }
  842. virtual bool writable() {
  843. return (flags_ & DE_WRITE) != 0;
  844. }
  845. virtual void set_writable(bool value) {
  846. flags_ = value ? (flags_ | DE_WRITE) : (flags_ & ~DE_WRITE);
  847. }
  848. private:
  849. PhysicalSocketServer* ss_;
  850. int fd_;
  851. int flags_;
  852. };
  853. AsyncFile* PhysicalSocketServer::CreateFile(int fd) {
  854. return new FileDispatcher(fd, this);
  855. }
  856. #endif // POSIX
  857. #ifdef WIN32
  858. static uint32 FlagsToEvents(uint32 events) {
  859. uint32 ffFD = FD_CLOSE;
  860. if (events & DE_READ)
  861. ffFD |= FD_READ;
  862. if (events & DE_WRITE)
  863. ffFD |= FD_WRITE;
  864. if (events & DE_CONNECT)
  865. ffFD |= FD_CONNECT;
  866. if (events & DE_ACCEPT)
  867. ffFD |= FD_ACCEPT;
  868. return ffFD;
  869. }
  870. class EventDispatcher : public Dispatcher {
  871. public:
  872. EventDispatcher(PhysicalSocketServer *ss) : ss_(ss) {
  873. hev_ = WSACreateEvent();
  874. if (hev_) {
  875. ss_->Add(this);
  876. }
  877. }
  878. ~EventDispatcher() {
  879. if (hev_ != NULL) {
  880. ss_->Remove(this);
  881. WSACloseEvent(hev_);
  882. hev_ = NULL;
  883. }
  884. }
  885. virtual void Signal() {
  886. if (hev_ != NULL)
  887. WSASetEvent(hev_);
  888. }
  889. virtual uint32 GetRequestedEvents() {
  890. return 0;
  891. }
  892. virtual void OnPreEvent(uint32 ff) {
  893. WSAResetEvent(hev_);
  894. }
  895. virtual void OnEvent(uint32 ff, int err) {
  896. }
  897. virtual WSAEVENT GetWSAEvent() {
  898. return hev_;
  899. }
  900. virtual SOCKET GetSocket() {
  901. return INVALID_SOCKET;
  902. }
  903. virtual bool CheckSignalClose() { return false; }
  904. private:
  905. PhysicalSocketServer* ss_;
  906. WSAEVENT hev_;
  907. };
  908. class SocketDispatcher : public Dispatcher, public PhysicalSocket {
  909. public:
  910. static int next_id_;
  911. int id_;
  912. bool signal_close_;
  913. int signal_err_;
  914. SocketDispatcher(PhysicalSocketServer* ss)
  915. : PhysicalSocket(ss),
  916. id_(0),
  917. signal_close_(false) {
  918. }
  919. SocketDispatcher(SOCKET s, PhysicalSocketServer* ss)
  920. : PhysicalSocket(ss, s),
  921. id_(0),
  922. signal_close_(false) {
  923. }
  924. virtual ~SocketDispatcher() {
  925. Close();
  926. }
  927. bool Initialize() {
  928. ASSERT(s_ != INVALID_SOCKET);
  929. // Must be a non-blocking
  930. u_long argp = 1;
  931. ioctlsocket(s_, FIONBIO, &argp);
  932. ss_->Add(this);
  933. return true;
  934. }
  935. virtual bool Create(int type) {
  936. return Create(AF_INET, type);
  937. }
  938. virtual bool Create(int family, int type) {
  939. // Create socket
  940. if (!PhysicalSocket::Create(family, type))
  941. return false;
  942. if (!Initialize())
  943. return false;
  944. do { id_ = ++next_id_; } while (id_ == 0);
  945. return true;
  946. }
  947. virtual int Close() {
  948. if (s_ == INVALID_SOCKET)
  949. return 0;
  950. id_ = 0;
  951. signal_close_ = false;
  952. ss_->Remove(this);
  953. return PhysicalSocket::Close();
  954. }
  955. virtual uint32 GetRequestedEvents() {
  956. return enabled_events_;
  957. }
  958. virtual void OnPreEvent(uint32 ff) {
  959. if ((ff & DE_CONNECT) != 0)
  960. state_ = CS_CONNECTED;
  961. // We set CS_CLOSED from CheckSignalClose.
  962. }
  963. virtual void OnEvent(uint32 ff, int err) {
  964. int cache_id = id_;
  965. // Make sure we deliver connect/accept first. Otherwise, consumers may see
  966. // something like a READ followed by a CONNECT, which would be odd.
  967. if (((ff & DE_CONNECT) != 0) && (id_ == cache_id)) {
  968. if (ff != DE_CONNECT)
  969. LOG(LS_VERBOSE) << "Signalled with DE_CONNECT: " << ff;
  970. enabled_events_ &= ~DE_CONNECT;
  971. #ifdef _DEBUG
  972. dbg_addr_ = "Connected @ ";
  973. dbg_addr_.append(GetRemoteAddress().ToString());
  974. #endif // _DEBUG
  975. SignalConnectEvent(this);
  976. }
  977. if (((ff & DE_ACCEPT) != 0) && (id_ == cache_id)) {
  978. enabled_events_ &= ~DE_ACCEPT;
  979. SignalReadEvent(this);
  980. }
  981. if ((ff & DE_READ) != 0) {
  982. enabled_events_ &= ~DE_READ;
  983. SignalReadEvent(this);
  984. }
  985. if (((ff & DE_WRITE) != 0) && (id_ == cache_id)) {
  986. enabled_events_ &= ~DE_WRITE;
  987. SignalWriteEvent(this);
  988. }
  989. if (((ff & DE_CLOSE) != 0) && (id_ == cache_id)) {
  990. signal_close_ = true;
  991. signal_err_ = err;
  992. }
  993. }
  994. virtual WSAEVENT GetWSAEvent() {
  995. return WSA_INVALID_EVENT;
  996. }
  997. virtual SOCKET GetSocket() {
  998. return s_;
  999. }
  1000. virtual bool CheckSignalClose() {
  1001. if (!signal_close_)
  1002. return false;
  1003. char ch;
  1004. if (recv(s_, &ch, 1, MSG_PEEK) > 0)
  1005. return false;
  1006. state_ = CS_CLOSED;
  1007. signal_close_ = false;
  1008. SignalCloseEvent(this, signal_err_);
  1009. return true;
  1010. }
  1011. };
  1012. int SocketDispatcher::next_id_ = 0;
  1013. #endif // WIN32
  1014. // Sets the value of a boolean value to false when signaled.
  1015. class Signaler : public EventDispatcher {
  1016. public:
  1017. Signaler(PhysicalSocketServer* ss, bool* pf)
  1018. : EventDispatcher(ss), pf_(pf) {
  1019. }
  1020. virtual ~Signaler() { }
  1021. void OnEvent(uint32 ff, int err) {
  1022. if (pf_)
  1023. *pf_ = false;
  1024. }
  1025. private:
  1026. bool *pf_;
  1027. };
  1028. PhysicalSocketServer::PhysicalSocketServer()
  1029. : fWait_(false),
  1030. last_tick_tracked_(0),
  1031. last_tick_dispatch_count_(0) {
  1032. signal_wakeup_ = new Signaler(this, &fWait_);
  1033. #ifdef WIN32
  1034. socket_ev_ = WSACreateEvent();
  1035. #endif
  1036. }
  1037. PhysicalSocketServer::~PhysicalSocketServer() {
  1038. #ifdef WIN32
  1039. WSACloseEvent(socket_ev_);
  1040. #endif
  1041. #ifdef POSIX
  1042. signal_dispatcher_.reset();
  1043. #endif
  1044. delete signal_wakeup_;
  1045. ASSERT(dispatchers_.empty());
  1046. }
  1047. void PhysicalSocketServer::WakeUp() {
  1048. signal_wakeup_->Signal();
  1049. }
  1050. Socket* PhysicalSocketServer::CreateSocket(int type) {
  1051. return CreateSocket(AF_INET, type);
  1052. }
  1053. Socket* PhysicalSocketServer::CreateSocket(int family, int type) {
  1054. PhysicalSocket* socket = new PhysicalSocket(this);
  1055. if (socket->Create(family, type)) {
  1056. return socket;
  1057. } else {
  1058. delete socket;
  1059. return 0;
  1060. }
  1061. }
  1062. AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int type) {
  1063. return CreateAsyncSocket(AF_INET, type);
  1064. }
  1065. AsyncSocket* PhysicalSocketServer::CreateAsyncSocket(int family, int type) {
  1066. SocketDispatcher* dispatcher = new SocketDispatcher(this);
  1067. if (dispatcher->Create(family, type)) {
  1068. return dispatcher;
  1069. } else {
  1070. delete dispatcher;
  1071. return 0;
  1072. }
  1073. }
  1074. AsyncSocket* PhysicalSocketServer::WrapSocket(SOCKET s) {
  1075. SocketDispatcher* dispatcher = new SocketDispatcher(s, this);
  1076. if (dispatcher->Initialize()) {
  1077. return dispatcher;
  1078. } else {
  1079. delete dispatcher;
  1080. return 0;
  1081. }
  1082. }
  1083. void PhysicalSocketServer::Add(Dispatcher *pdispatcher) {
  1084. CritScope cs(&crit_);
  1085. // Prevent duplicates. This can cause dead dispatchers to stick around.
  1086. DispatcherList::iterator pos = std::find(dispatchers_.begin(),
  1087. dispatchers_.end(),
  1088. pdispatcher);
  1089. if (pos != dispatchers_.end())
  1090. return;
  1091. dispatchers_.push_back(pdispatcher);
  1092. }
  1093. void PhysicalSocketServer::Remove(Dispatcher *pdispatcher) {
  1094. CritScope cs(&crit_);
  1095. DispatcherList::iterator pos = std::find(dispatchers_.begin(),
  1096. dispatchers_.end(),
  1097. pdispatcher);
  1098. ASSERT(pos != dispatchers_.end());
  1099. size_t index = pos - dispatchers_.begin();
  1100. dispatchers_.erase(pos);
  1101. for (IteratorList::iterator it = iterators_.begin(); it != iterators_.end();
  1102. ++it) {
  1103. if (index < **it) {
  1104. --**it;
  1105. }
  1106. }
  1107. }
  1108. #ifdef POSIX
  1109. bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
  1110. // Calculate timing information
  1111. struct timeval *ptvWait = NULL;
  1112. struct timeval tvWait;
  1113. struct timeval tvStop;
  1114. if (cmsWait != kForever) {
  1115. // Calculate wait timeval
  1116. tvWait.tv_sec = cmsWait / 1000;
  1117. tvWait.tv_usec = (cmsWait % 1000) * 1000;
  1118. ptvWait = &tvWait;
  1119. // Calculate when to return in a timeval
  1120. gettimeofday(&tvStop, NULL);
  1121. tvStop.tv_sec += tvWait.tv_sec;
  1122. tvStop.tv_usec += tvWait.tv_usec;
  1123. if (tvStop.tv_usec >= 1000000) {
  1124. tvStop.tv_usec -= 1000000;
  1125. tvStop.tv_sec += 1;
  1126. }
  1127. }
  1128. // Zero all fd_sets. Don't need to do this inside the loop since
  1129. // select() zeros the descriptors not signaled
  1130. fd_set fdsRead;
  1131. FD_ZERO(&fdsRead);
  1132. fd_set fdsWrite;
  1133. FD_ZERO(&fdsWrite);
  1134. fWait_ = true;
  1135. while (fWait_) {
  1136. int fdmax = -1;
  1137. {
  1138. CritScope cr(&crit_);
  1139. for (size_t i = 0; i < dispatchers_.size(); ++i) {
  1140. // Query dispatchers for read and write wait state
  1141. Dispatcher *pdispatcher = dispatchers_[i];
  1142. ASSERT(pdispatcher);
  1143. if (!process_io && (pdispatcher != signal_wakeup_))
  1144. continue;
  1145. int fd = pdispatcher->GetDescriptor();
  1146. if (fd > fdmax)
  1147. fdmax = fd;
  1148. uint32 ff = pdispatcher->GetRequestedEvents();
  1149. if (ff & (DE_READ | DE_ACCEPT))
  1150. FD_SET(fd, &fdsRead);
  1151. if (ff & (DE_WRITE | DE_CONNECT))
  1152. FD_SET(fd, &fdsWrite);
  1153. }
  1154. }
  1155. // Wait then call handlers as appropriate
  1156. // < 0 means error
  1157. // 0 means timeout
  1158. // > 0 means count of descriptors ready
  1159. int n = select(fdmax + 1, &fdsRead, &fdsWrite, NULL, ptvWait);
  1160. // If error, return error.
  1161. if (n < 0) {
  1162. if (errno != EINTR) {
  1163. LOG_E(LS_ERROR, EN, errno) << "select";
  1164. return false;
  1165. }
  1166. // Else ignore the error and keep going. If this EINTR was for one of the
  1167. // signals managed by this PhysicalSocketServer, the
  1168. // PosixSignalDeliveryDispatcher will be in the signaled state in the next
  1169. // iteration.
  1170. } else if (n == 0) {
  1171. // If timeout, return success
  1172. return true;
  1173. } else {
  1174. // We have signaled descriptors
  1175. CritScope cr(&crit_);
  1176. for (size_t i = 0; i < dispatchers_.size(); ++i) {
  1177. Dispatcher *pdispatcher = dispatchers_[i];
  1178. int fd = pdispatcher->GetDescriptor();
  1179. uint32 ff = 0;
  1180. int errcode = 0;
  1181. // Reap any error code, which can be signaled through reads or writes.
  1182. // TODO: Should we set errcode if getsockopt fails?
  1183. if (FD_ISSET(fd, &fdsRead) || FD_ISSET(fd, &fdsWrite)) {
  1184. socklen_t len = sizeof(errcode);
  1185. ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &errcode, &len);
  1186. }
  1187. // Check readable descriptors. If we're waiting on an accept, signal
  1188. // that. Otherwise we're waiting for data, check to see if we're
  1189. // readable or really closed.
  1190. // TODO: Only peek at TCP descriptors.
  1191. if (FD_ISSET(fd, &fdsRead)) {
  1192. FD_CLR(fd, &fdsRead);
  1193. if (pdispatcher->GetRequestedEvents() & DE_ACCEPT) {
  1194. ff |= DE_ACCEPT;
  1195. } else if (errcode || pdispatcher->IsDescriptorClosed()) {
  1196. ff |= DE_CLOSE;
  1197. } else {
  1198. ff |= DE_READ;
  1199. }
  1200. }
  1201. // Check writable descriptors. If we're waiting on a connect, detect
  1202. // success versus failure by the reaped error code.
  1203. if (FD_ISSET(fd, &fdsWrite)) {
  1204. FD_CLR(fd, &fdsWrite);
  1205. if (pdispatcher->GetRequestedEvents() & DE_CONNECT) {
  1206. if (!errcode) {
  1207. ff |= DE_CONNECT;
  1208. } else {
  1209. ff |= DE_CLOSE;
  1210. }
  1211. } else {
  1212. ff |= DE_WRITE;
  1213. }
  1214. }
  1215. // Tell the descriptor about the event.
  1216. if (ff != 0) {
  1217. pdispatcher->OnPreEvent(ff);
  1218. pdispatcher->OnEvent(ff, errcode);
  1219. }
  1220. }
  1221. }
  1222. // Recalc the time remaining to wait. Doing it here means it doesn't get
  1223. // calced twice the first time through the loop
  1224. if (ptvWait) {
  1225. ptvWait->tv_sec = 0;
  1226. ptvWait->tv_usec = 0;
  1227. struct timeval tvT;
  1228. gettimeofday(&tvT, NULL);
  1229. if ((tvStop.tv_sec > tvT.tv_sec)
  1230. || ((tvStop.tv_sec == tvT.tv_sec)
  1231. && (tvStop.tv_usec > tvT.tv_usec))) {
  1232. ptvWait->tv_sec = tvStop.tv_sec - tvT.tv_sec;
  1233. ptvWait->tv_usec = tvStop.tv_usec - tvT.tv_usec;
  1234. if (ptvWait->tv_usec < 0) {
  1235. ASSERT(ptvWait->tv_sec > 0);
  1236. ptvWait->tv_usec += 1000000;
  1237. ptvWait->tv_sec -= 1;
  1238. }
  1239. }
  1240. }
  1241. }
  1242. return true;
  1243. }
  1244. static void GlobalSignalHandler(int signum) {
  1245. PosixSignalHandler::Instance()->OnPosixSignalReceived(signum);
  1246. }
  1247. bool PhysicalSocketServer::SetPosixSignalHandler(int signum,
  1248. void (*handler)(int)) {
  1249. // If handler is SIG_IGN or SIG_DFL then clear our user-level handler,
  1250. // otherwise set one.
  1251. if (handler == SIG_IGN || handler == SIG_DFL) {
  1252. if (!InstallSignal(signum, handler)) {
  1253. return false;
  1254. }
  1255. if (signal_dispatcher_) {
  1256. signal_dispatcher_->ClearHandler(signum);
  1257. if (!signal_dispatcher_->HasHandlers()) {
  1258. signal_dispatcher_.reset();
  1259. }
  1260. }
  1261. } else {
  1262. if (!signal_dispatcher_) {
  1263. signal_dispatcher_.reset(new PosixSignalDispatcher(this));
  1264. }
  1265. signal_dispatcher_->SetHandler(signum, handler);
  1266. if (!InstallSignal(signum, &GlobalSignalHandler)) {
  1267. return false;
  1268. }
  1269. }
  1270. return true;
  1271. }
  1272. Dispatcher* PhysicalSocketServer::signal_dispatcher() {
  1273. return signal_dispatcher_.get();
  1274. }
  1275. bool PhysicalSocketServer::InstallSignal(int signum, void (*handler)(int)) {
  1276. struct sigaction act;
  1277. // It doesn't really matter what we set this mask to.
  1278. if (sigemptyset(&act.sa_mask) != 0) {
  1279. LOG_ERR(LS_ERROR) << "Couldn't set mask";
  1280. return false;
  1281. }
  1282. act.sa_handler = handler;
  1283. // Use SA_RESTART so that our syscalls don't get EINTR, since we don't need it
  1284. // and it's a nuisance. Though some syscalls still return EINTR and there's no
  1285. // real standard for which ones. :(
  1286. act.sa_flags = SA_RESTART;
  1287. if (sigaction(signum, &act, NULL) != 0) {
  1288. LOG_ERR(LS_ERROR) << "Couldn't set sigaction";
  1289. return false;
  1290. }
  1291. return true;
  1292. }
  1293. #endif // POSIX
  1294. #ifdef WIN32
  1295. bool PhysicalSocketServer::Wait(int cmsWait, bool process_io) {
  1296. int cmsTotal = cmsWait;
  1297. int cmsElapsed = 0;
  1298. uint32 msStart = Time();
  1299. #if LOGGING
  1300. if (last_tick_dispatch_count_ == 0) {
  1301. last_tick_tracked_ = msStart;
  1302. }
  1303. #endif
  1304. fWait_ = true;
  1305. while (fWait_) {
  1306. std::vector<WSAEVENT> events;
  1307. std::vector<Dispatcher *> event_owners;
  1308. events.push_back(socket_ev_);
  1309. {
  1310. CritScope cr(&crit_);
  1311. size_t i = 0;
  1312. iterators_.push_back(&i);
  1313. // Don't track dispatchers_.size(), because we want to pick up any new
  1314. // dispatchers that were added while processing the loop.
  1315. while (i < dispatchers_.size()) {
  1316. Dispatcher* disp = dispatchers_[i++];
  1317. if (!process_io && (disp != signal_wakeup_))
  1318. continue;
  1319. SOCKET s = disp->GetSocket();
  1320. if (disp->CheckSignalClose()) {
  1321. // We just signalled close, don't poll this socket
  1322. } else if (s != INVALID_SOCKET) {
  1323. WSAEventSelect(s,
  1324. events[0],
  1325. FlagsToEvents(disp->GetRequestedEvents()));
  1326. } else {
  1327. events.push_back(disp->GetWSAEvent());
  1328. event_owners.push_back(disp);
  1329. }
  1330. }
  1331. ASSERT(iterators_.back() == &i);
  1332. iterators_.pop_back();
  1333. }
  1334. // Which is shorter, the delay wait or the asked wait?
  1335. int cmsNext;
  1336. if (cmsWait == kForever) {
  1337. cmsNext = cmsWait;
  1338. } else {
  1339. cmsNext = _max(0, cmsTotal - cmsElapsed);
  1340. }
  1341. // Wait for one of the events to signal
  1342. DWORD dw = WSAWaitForMultipleEvents(static_cast<DWORD>(events.size()),
  1343. &events[0],
  1344. false,
  1345. cmsNext,
  1346. false);
  1347. #if 0 // LOGGING
  1348. // we track this information purely for logging purposes.
  1349. last_tick_dispatch_count_++;
  1350. if (last_tick_dispatch_count_ >= 1000) {
  1351. int32 elapsed = TimeSince(last_tick_tracked_);
  1352. LOG(INFO) << "PhysicalSocketServer took " << elapsed
  1353. << "ms for 1000 events";
  1354. // If we get more than 1000 events in a second, we are spinning badly
  1355. // (normally it should take about 8-20 seconds).
  1356. ASSERT(elapsed > 1000);
  1357. last_tick_tracked_ = Time();
  1358. last_tick_dispatch_count_ = 0;
  1359. }
  1360. #endif
  1361. if (dw == WSA_WAIT_FAILED) {
  1362. // Failed?
  1363. // TODO: need a better strategy than this!
  1364. int error = WSAGetLastError();
  1365. ASSERT(false);
  1366. return false;
  1367. } else if (dw == WSA_WAIT_TIMEOUT) {
  1368. // Timeout?
  1369. return true;
  1370. } else {
  1371. // Figure out which one it is and call it
  1372. CritScope cr(&crit_);
  1373. int index = dw - WSA_WAIT_EVENT_0;
  1374. if (index > 0) {
  1375. --index; // The first event is the socket event
  1376. event_owners[index]->OnPreEvent(0);
  1377. event_owners[index]->OnEvent(0, 0);
  1378. } else if (process_io) {
  1379. size_t i = 0, end = dispatchers_.size();
  1380. iterators_.push_back(&i);
  1381. iterators_.push_back(&end); // Don't iterate over new dispatchers.
  1382. while (i < end) {
  1383. Dispatcher* disp = dispatchers_[i++];
  1384. SOCKET s = disp->GetSocket();
  1385. if (s == INVALID_SOCKET)
  1386. continue;
  1387. WSANETWORKEVENTS wsaEvents;
  1388. int err = WSAEnumNetworkEvents(s, events[0], &wsaEvents);
  1389. if (err == 0) {
  1390. #if LOGGING
  1391. {
  1392. if ((wsaEvents.lNetworkEvents & FD_READ) &&
  1393. wsaEvents.iErrorCode[FD_READ_BIT] != 0) {
  1394. LOG(WARNING) << "PhysicalSocketServer got FD_READ_BIT error "
  1395. << wsaEvents.iErrorCode[FD_READ_BIT];
  1396. }
  1397. if ((wsaEvents.lNetworkEvents & FD_WRITE) &&
  1398. wsaEvents.iErrorCode[FD_WRITE_BIT] != 0) {
  1399. LOG(WARNING) << "PhysicalSocketServer got FD_WRITE_BIT error "
  1400. << wsaEvents.iErrorCode[FD_WRITE_BIT];
  1401. }
  1402. if ((wsaEvents.lNetworkEvents & FD_CONNECT) &&
  1403. wsaEvents.iErrorCode[FD_CONNECT_BIT] != 0) {
  1404. LOG(WARNING) << "PhysicalSocketServer got FD_CONNECT_BIT error "
  1405. << wsaEvents.iErrorCode[FD_CONNECT_BIT];
  1406. }
  1407. if ((wsaEvents.lNetworkEvents & FD_ACCEPT) &&
  1408. wsaEvents.iErrorCode[FD_ACCEPT_BIT] != 0) {
  1409. LOG(WARNING) << "PhysicalSocketServer got FD_ACCEPT_BIT error "
  1410. << wsaEvents.iErrorCode[FD_ACCEPT_BIT];
  1411. }
  1412. if ((wsaEvents.lNetworkEvents & FD_CLOSE) &&
  1413. wsaEvents.iErrorCode[FD_CLOSE_BIT] != 0) {
  1414. LOG(WARNING) << "PhysicalSocketServer got FD_CLOSE_BIT error "
  1415. << wsaEvents.iErrorCode[FD_CLOSE_BIT];
  1416. }
  1417. }
  1418. #endif
  1419. uint32 ff = 0;
  1420. int errcode = 0;
  1421. if (wsaEvents.lNetworkEvents & FD_READ)
  1422. ff |= DE_READ;
  1423. if (wsaEvents.lNetworkEvents & FD_WRITE)
  1424. ff |= DE_WRITE;
  1425. if (wsaEvents.lNetworkEvents & FD_CONNECT) {
  1426. if (wsaEvents.iErrorCode[FD_CONNECT_BIT] == 0) {
  1427. ff |= DE_CONNECT;
  1428. } else {
  1429. ff |= DE_CLOSE;
  1430. errcode = wsaEvents.iErrorCode[FD_CONNECT_BIT];
  1431. }
  1432. }
  1433. if (wsaEvents.lNetworkEvents & FD_ACCEPT)
  1434. ff |= DE_ACCEPT;
  1435. if (wsaEvents.lNetworkEvents & FD_CLOSE) {
  1436. ff |= DE_CLOSE;
  1437. errcode = wsaEvents.iErrorCode[FD_CLOSE_BIT];
  1438. }
  1439. if (ff != 0) {
  1440. disp->OnPreEvent(ff);
  1441. disp->OnEvent(ff, errcode);
  1442. }
  1443. }
  1444. }
  1445. ASSERT(iterators_.back() == &end);
  1446. iterators_.pop_back();
  1447. ASSERT(iterators_.back() == &i);
  1448. iterators_.pop_back();
  1449. }
  1450. // Reset the network event until new activity occurs
  1451. WSAResetEvent(socket_ev_);
  1452. }
  1453. // Break?
  1454. if (!fWait_)
  1455. break;
  1456. cmsElapsed = TimeSince(msStart);
  1457. if ((cmsWait != kForever) && (cmsElapsed >= cmsWait)) {
  1458. break;
  1459. }
  1460. }
  1461. // Done
  1462. return true;
  1463. }
  1464. #endif // WIN32
  1465. } // namespace talk_base