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.

472 lines
13 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. // Copyright 2010 Google Inc. All Rights Reserved.
  2. // thaloun@google.com (Tim Haloun)
  3. //
  4. // MacAsyncSocket is a kind of AsyncSocket. It does not support the SOCK_DGRAM
  5. // type (yet). It works asynchronously, which means that users of this socket
  6. // should connect to the various events declared in asyncsocket.h to receive
  7. // notifications about this socket. It uses CFSockets for signals, but prefers
  8. // the basic bsd socket operations rather than their CFSocket wrappers when
  9. // possible.
  10. #include <CoreFoundation/CoreFoundation.h>
  11. #include <fcntl.h>
  12. #include "talk/base/macasyncsocket.h"
  13. #include "talk/base/logging.h"
  14. #include "talk/base/macsocketserver.h"
  15. namespace talk_base {
  16. static const int kCallbackFlags = kCFSocketReadCallBack |
  17. kCFSocketConnectCallBack |
  18. kCFSocketWriteCallBack;
  19. MacAsyncSocket::MacAsyncSocket(MacBaseSocketServer* ss, int family)
  20. : ss_(ss),
  21. socket_(NULL),
  22. native_socket_(INVALID_SOCKET),
  23. source_(NULL),
  24. current_callbacks_(0),
  25. disabled_(false),
  26. error_(0),
  27. state_(CS_CLOSED),
  28. resolver_(NULL) {
  29. Initialize(family);
  30. }
  31. MacAsyncSocket::~MacAsyncSocket() {
  32. Close();
  33. }
  34. // Returns the address to which the socket is bound. If the socket is not
  35. // bound, then the any-address is returned.
  36. SocketAddress MacAsyncSocket::GetLocalAddress() const {
  37. SocketAddress address;
  38. // The CFSocket doesn't pick up on implicit binds from the connect call.
  39. // Calling bind in before connect explicitly causes errors, so just query
  40. // the underlying bsd socket.
  41. sockaddr_storage addr;
  42. socklen_t addrlen = sizeof(addr);
  43. int result = ::getsockname(native_socket_,
  44. reinterpret_cast<sockaddr*>(&addr), &addrlen);
  45. if (result >= 0) {
  46. SocketAddressFromSockAddrStorage(addr, &address);
  47. }
  48. return address;
  49. }
  50. // Returns the address to which the socket is connected. If the socket is not
  51. // connected, then the any-address is returned.
  52. SocketAddress MacAsyncSocket::GetRemoteAddress() const {
  53. SocketAddress address;
  54. // Use native_socket for consistency with GetLocalAddress.
  55. sockaddr_storage addr;
  56. socklen_t addrlen = sizeof(addr);
  57. int result = ::getpeername(native_socket_,
  58. reinterpret_cast<sockaddr*>(&addr), &addrlen);
  59. if (result >= 0) {
  60. SocketAddressFromSockAddrStorage(addr, &address);
  61. }
  62. return address;
  63. }
  64. // Bind the socket to a local address.
  65. int MacAsyncSocket::Bind(const SocketAddress& address) {
  66. sockaddr_storage saddr = {0};
  67. size_t len = address.ToSockAddrStorage(&saddr);
  68. int err = ::bind(native_socket_, reinterpret_cast<sockaddr*>(&saddr), len);
  69. if (err == SOCKET_ERROR) error_ = errno;
  70. return err;
  71. }
  72. void MacAsyncSocket::OnResolveResult(SignalThread* thread) {
  73. if (thread != resolver_) {
  74. return;
  75. }
  76. int error = resolver_->error();
  77. if (error == 0) {
  78. error = DoConnect(resolver_->address());
  79. } else {
  80. Close();
  81. }
  82. if (error) {
  83. error_ = error;
  84. SignalCloseEvent(this, error_);
  85. }
  86. }
  87. // Connect to a remote address.
  88. int MacAsyncSocket::Connect(const SocketAddress& addr) {
  89. // TODO(djw): Consolidate all the connect->resolve->doconnect implementations.
  90. if (state_ != CS_CLOSED) {
  91. SetError(EALREADY);
  92. return SOCKET_ERROR;
  93. }
  94. if (addr.IsUnresolved()) {
  95. LOG(LS_VERBOSE) << "Resolving addr in MacAsyncSocket::Connect";
  96. resolver_ = new AsyncResolver();
  97. resolver_->set_address(addr);
  98. resolver_->SignalWorkDone.connect(this,
  99. &MacAsyncSocket::OnResolveResult);
  100. resolver_->Start();
  101. state_ = CS_CONNECTING;
  102. return 0;
  103. }
  104. return DoConnect(addr);
  105. }
  106. int MacAsyncSocket::DoConnect(const SocketAddress& addr) {
  107. if (!valid()) {
  108. Initialize(addr.family());
  109. if (!valid())
  110. return SOCKET_ERROR;
  111. }
  112. sockaddr_storage saddr;
  113. size_t len = addr.ToSockAddrStorage(&saddr);
  114. int result = ::connect(native_socket_, reinterpret_cast<sockaddr*>(&saddr),
  115. len);
  116. if (result != SOCKET_ERROR) {
  117. state_ = CS_CONNECTED;
  118. } else {
  119. error_ = errno;
  120. if (error_ == EINPROGRESS) {
  121. state_ = CS_CONNECTING;
  122. result = 0;
  123. }
  124. }
  125. return result;
  126. }
  127. // Send to the remote end we're connected to.
  128. int MacAsyncSocket::Send(const void* buffer, size_t length) {
  129. if (!valid()) {
  130. return SOCKET_ERROR;
  131. }
  132. int sent = ::send(native_socket_, buffer, length, 0);
  133. if (sent == SOCKET_ERROR) {
  134. error_ = errno;
  135. if (IsBlocking()) {
  136. // Reenable the writable callback (once), since we are flow controlled.
  137. CFSocketEnableCallBacks(socket_, kCallbackFlags);
  138. current_callbacks_ = kCallbackFlags;
  139. }
  140. }
  141. return sent;
  142. }
  143. // Send to the given address. We may or may not be connected to anyone.
  144. int MacAsyncSocket::SendTo(const void* buffer, size_t length,
  145. const SocketAddress& address) {
  146. if (!valid()) {
  147. return SOCKET_ERROR;
  148. }
  149. sockaddr_storage saddr;
  150. size_t len = address.ToSockAddrStorage(&saddr);
  151. int sent = ::sendto(native_socket_, buffer, length, 0,
  152. reinterpret_cast<sockaddr*>(&saddr), len);
  153. if (sent == SOCKET_ERROR) {
  154. error_ = errno;
  155. }
  156. return sent;
  157. }
  158. // Read data received from the remote end we're connected to.
  159. int MacAsyncSocket::Recv(void* buffer, size_t length) {
  160. int received = ::recv(native_socket_, reinterpret_cast<char*>(buffer),
  161. length, 0);
  162. if (received == SOCKET_ERROR) error_ = errno;
  163. // Recv should only be called when there is data to read
  164. ASSERT((received != 0) || (length == 0));
  165. return received;
  166. }
  167. // Read data received from any remote party
  168. int MacAsyncSocket::RecvFrom(void* buffer, size_t length,
  169. SocketAddress* out_addr) {
  170. sockaddr_storage saddr;
  171. socklen_t addr_len = sizeof(saddr);
  172. int received = ::recvfrom(native_socket_, reinterpret_cast<char*>(buffer),
  173. length, 0, reinterpret_cast<sockaddr*>(&saddr),
  174. &addr_len);
  175. if (received >= 0 && out_addr != NULL) {
  176. SocketAddressFromSockAddrStorage(saddr, out_addr);
  177. } else if (received == SOCKET_ERROR) {
  178. error_ = errno;
  179. }
  180. return received;
  181. }
  182. int MacAsyncSocket::Listen(int backlog) {
  183. if (!valid()) {
  184. return SOCKET_ERROR;
  185. }
  186. int res = ::listen(native_socket_, backlog);
  187. if (res != SOCKET_ERROR)
  188. state_ = CS_CONNECTING;
  189. else
  190. error_ = errno;
  191. return res;
  192. }
  193. MacAsyncSocket* MacAsyncSocket::Accept(SocketAddress* out_addr) {
  194. sockaddr_storage saddr;
  195. socklen_t addr_len = sizeof(saddr);
  196. int socket_fd = ::accept(native_socket_, reinterpret_cast<sockaddr*>(&saddr),
  197. &addr_len);
  198. if (socket_fd == INVALID_SOCKET) {
  199. error_ = errno;
  200. return NULL;
  201. }
  202. MacAsyncSocket* s = new MacAsyncSocket(ss_, saddr.ss_family, socket_fd);
  203. if (s && s->valid()) {
  204. s->state_ = CS_CONNECTED;
  205. if (out_addr)
  206. SocketAddressFromSockAddrStorage(saddr, out_addr);
  207. } else {
  208. delete s;
  209. s = NULL;
  210. }
  211. return s;
  212. }
  213. int MacAsyncSocket::Close() {
  214. if (source_ != NULL) {
  215. CFRunLoopSourceInvalidate(source_);
  216. CFRelease(source_);
  217. if (ss_) ss_->UnregisterSocket(this);
  218. source_ = NULL;
  219. }
  220. if (socket_ != NULL) {
  221. CFSocketInvalidate(socket_);
  222. CFRelease(socket_);
  223. socket_ = NULL;
  224. }
  225. if (resolver_) {
  226. resolver_->Destroy(false);
  227. resolver_ = NULL;
  228. }
  229. native_socket_ = INVALID_SOCKET; // invalidates the socket
  230. error_ = 0;
  231. state_ = CS_CLOSED;
  232. return 0;
  233. }
  234. int MacAsyncSocket::EstimateMTU(uint16* mtu) {
  235. ASSERT(false && "NYI");
  236. return -1;
  237. }
  238. int MacAsyncSocket::GetError() const {
  239. return error_;
  240. }
  241. void MacAsyncSocket::SetError(int error) {
  242. error_ = error;
  243. }
  244. Socket::ConnState MacAsyncSocket::GetState() const {
  245. return state_;
  246. }
  247. int MacAsyncSocket::GetOption(Option opt, int* value) {
  248. ASSERT(false && "NYI");
  249. return -1;
  250. }
  251. int MacAsyncSocket::SetOption(Option opt, int value) {
  252. ASSERT(false && "NYI");
  253. return -1;
  254. }
  255. void MacAsyncSocket::EnableCallbacks() {
  256. if (valid()) {
  257. disabled_ = false;
  258. CFSocketEnableCallBacks(socket_, current_callbacks_);
  259. }
  260. }
  261. void MacAsyncSocket::DisableCallbacks() {
  262. if (valid()) {
  263. disabled_ = true;
  264. CFSocketDisableCallBacks(socket_, kCallbackFlags);
  265. }
  266. }
  267. MacAsyncSocket::MacAsyncSocket(MacBaseSocketServer* ss, int family,
  268. int native_socket)
  269. : ss_(ss),
  270. socket_(NULL),
  271. native_socket_(native_socket),
  272. source_(NULL),
  273. current_callbacks_(0),
  274. disabled_(false),
  275. error_(0),
  276. state_(CS_CLOSED),
  277. resolver_(NULL) {
  278. Initialize(family);
  279. }
  280. // Create a new socket, wrapping the native socket if provided or creating one
  281. // otherwise. In case of any failure, consume the native socket. We assume the
  282. // wrapped socket is in the closed state. If this is not the case you must
  283. // update the state_ field for this socket yourself.
  284. void MacAsyncSocket::Initialize(int family) {
  285. CFSocketContext ctx = { 0 };
  286. ctx.info = this;
  287. // First create the CFSocket
  288. CFSocketRef cf_socket = NULL;
  289. bool res = false;
  290. if (native_socket_ == INVALID_SOCKET) {
  291. cf_socket = CFSocketCreate(kCFAllocatorDefault,
  292. family, SOCK_STREAM, IPPROTO_TCP,
  293. kCallbackFlags, MacAsyncSocketCallBack, &ctx);
  294. } else {
  295. cf_socket = CFSocketCreateWithNative(kCFAllocatorDefault,
  296. native_socket_, kCallbackFlags,
  297. MacAsyncSocketCallBack, &ctx);
  298. }
  299. if (cf_socket) {
  300. res = true;
  301. socket_ = cf_socket;
  302. native_socket_ = CFSocketGetNative(cf_socket);
  303. current_callbacks_ = kCallbackFlags;
  304. }
  305. if (res) {
  306. // Make the underlying socket asynchronous
  307. res = (-1 != ::fcntl(native_socket_, F_SETFL,
  308. ::fcntl(native_socket_, F_GETFL, 0) | O_NONBLOCK));
  309. }
  310. if (res) {
  311. // Add this socket to the run loop, at priority 1 so that it will be
  312. // queued behind any pending signals.
  313. source_ = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 1);
  314. res = (source_ != NULL);
  315. if (!res) errno = EINVAL;
  316. }
  317. if (res) {
  318. if (ss_) ss_->RegisterSocket(this);
  319. CFRunLoopAddSource(CFRunLoopGetCurrent(), source_, kCFRunLoopCommonModes);
  320. }
  321. if (!res) {
  322. int error = errno;
  323. Close(); // Clears error_.
  324. error_ = error;
  325. }
  326. }
  327. // Call CFRelease on the result when done using it
  328. CFDataRef MacAsyncSocket::CopyCFAddress(const SocketAddress& address) {
  329. sockaddr_storage saddr;
  330. size_t len = address.ToSockAddrStorage(&saddr);
  331. const UInt8* bytes = reinterpret_cast<UInt8*>(&saddr);
  332. CFDataRef cf_address = CFDataCreate(kCFAllocatorDefault,
  333. bytes, len);
  334. ASSERT(cf_address != NULL);
  335. return cf_address;
  336. }
  337. void MacAsyncSocket::MacAsyncSocketCallBack(CFSocketRef s,
  338. CFSocketCallBackType callbackType,
  339. CFDataRef address,
  340. const void* data,
  341. void* info) {
  342. MacAsyncSocket* this_socket =
  343. reinterpret_cast<MacAsyncSocket*>(info);
  344. ASSERT(this_socket != NULL && this_socket->socket_ == s);
  345. // Don't signal any socket messages if the socketserver is not listening on
  346. // them. When we are reenabled they will be requeued and will fire again.
  347. if (this_socket->disabled_)
  348. return;
  349. switch (callbackType) {
  350. case kCFSocketReadCallBack:
  351. // This callback is invoked in one of 3 situations:
  352. // 1. A new connection is waiting to be accepted.
  353. // 2. The remote end closed the connection (a recv will return 0).
  354. // 3. Data is available to read.
  355. // 4. The connection closed unhappily (recv will return -1).
  356. if (this_socket->state_ == CS_CONNECTING) {
  357. // Case 1.
  358. this_socket->SignalReadEvent(this_socket);
  359. } else {
  360. char ch, amt;
  361. amt = ::recv(this_socket->native_socket_, &ch, 1, MSG_PEEK);
  362. if (amt == 0) {
  363. // Case 2.
  364. this_socket->state_ = CS_CLOSED;
  365. // Disable additional callbacks or we will signal close twice.
  366. CFSocketDisableCallBacks(this_socket->socket_, kCFSocketReadCallBack);
  367. this_socket->current_callbacks_ &= ~kCFSocketReadCallBack;
  368. this_socket->SignalCloseEvent(this_socket, 0);
  369. } else if (amt > 0) {
  370. // Case 3.
  371. this_socket->SignalReadEvent(this_socket);
  372. } else {
  373. // Case 4.
  374. int error = errno;
  375. if (error == EAGAIN) {
  376. // Observed in practice. Let's hope it's a spurious or out of date
  377. // signal, since we just eat it.
  378. } else {
  379. this_socket->error_ = error;
  380. this_socket->SignalCloseEvent(this_socket, error);
  381. }
  382. }
  383. }
  384. break;
  385. case kCFSocketConnectCallBack:
  386. if (data != NULL) {
  387. // An error occured in the background while connecting
  388. this_socket->error_ = errno;
  389. this_socket->state_ = CS_CLOSED;
  390. this_socket->SignalCloseEvent(this_socket, this_socket->error_);
  391. } else {
  392. this_socket->state_ = CS_CONNECTED;
  393. this_socket->SignalConnectEvent(this_socket);
  394. }
  395. break;
  396. case kCFSocketWriteCallBack:
  397. // Update our callback tracking. Write doesn't reenable, so it's off now.
  398. this_socket->current_callbacks_ &= ~kCFSocketWriteCallBack;
  399. this_socket->SignalWriteEvent(this_socket);
  400. break;
  401. default:
  402. ASSERT(false && "Invalid callback type for socket");
  403. }
  404. }
  405. } // namespace talk_base