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.

287 lines
7.7 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * libjingle
  3. * Copyright 2004--2010, 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. #include "talk/base/asynctcpsocket.h"
  28. #include <cstring>
  29. #include "talk/base/byteorder.h"
  30. #include "talk/base/common.h"
  31. #include "talk/base/logging.h"
  32. #ifdef POSIX
  33. #include <errno.h>
  34. #endif // POSIX
  35. namespace talk_base {
  36. static const size_t MAX_PACKET_SIZE = 64 * 1024;
  37. typedef uint16 PacketLength;
  38. static const size_t PKT_LEN_SIZE = sizeof(PacketLength);
  39. static const size_t BUF_SIZE = MAX_PACKET_SIZE + PKT_LEN_SIZE;
  40. static const int LISTEN_BACKLOG = 5;
  41. // Binds and connects |socket| and creates AsyncTCPSocket for
  42. // it. Takes ownership of |socket|. Returns NULL if bind() or
  43. // connect() fail (|socket| is destroyed in that case).
  44. AsyncTCPSocket* AsyncTCPSocket::Create(
  45. AsyncSocket* socket,
  46. const SocketAddress& bind_address,
  47. const SocketAddress& remote_address) {
  48. scoped_ptr<AsyncSocket> owned_socket(socket);
  49. if (socket->Bind(bind_address) < 0) {
  50. LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
  51. return NULL;
  52. }
  53. if (socket->Connect(remote_address) < 0) {
  54. LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
  55. return NULL;
  56. }
  57. return new AsyncTCPSocket(owned_socket.release(), false);
  58. }
  59. AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
  60. : socket_(socket),
  61. listen_(listen),
  62. insize_(BUF_SIZE),
  63. inpos_(0),
  64. outsize_(BUF_SIZE),
  65. outpos_(0) {
  66. inbuf_ = new char[insize_];
  67. outbuf_ = new char[outsize_];
  68. ASSERT(socket_.get() != NULL);
  69. socket_->SignalConnectEvent.connect(this, &AsyncTCPSocket::OnConnectEvent);
  70. socket_->SignalReadEvent.connect(this, &AsyncTCPSocket::OnReadEvent);
  71. socket_->SignalWriteEvent.connect(this, &AsyncTCPSocket::OnWriteEvent);
  72. socket_->SignalCloseEvent.connect(this, &AsyncTCPSocket::OnCloseEvent);
  73. if (listen_) {
  74. if (socket_->Listen(LISTEN_BACKLOG) < 0) {
  75. LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
  76. }
  77. }
  78. }
  79. AsyncTCPSocket::~AsyncTCPSocket() {
  80. delete [] inbuf_;
  81. delete [] outbuf_;
  82. }
  83. SocketAddress AsyncTCPSocket::GetLocalAddress() const {
  84. return socket_->GetLocalAddress();
  85. }
  86. SocketAddress AsyncTCPSocket::GetRemoteAddress() const {
  87. return socket_->GetRemoteAddress();
  88. }
  89. int AsyncTCPSocket::Send(const void *pv, size_t cb) {
  90. if (cb > MAX_PACKET_SIZE) {
  91. socket_->SetError(EMSGSIZE);
  92. return -1;
  93. }
  94. // If we are blocking on send, then silently drop this packet
  95. if (outpos_)
  96. return static_cast<int>(cb);
  97. PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
  98. memcpy(outbuf_, &pkt_len, PKT_LEN_SIZE);
  99. memcpy(outbuf_ + PKT_LEN_SIZE, pv, cb);
  100. outpos_ = PKT_LEN_SIZE + cb;
  101. int res = Flush();
  102. if (res <= 0) {
  103. // drop packet if we made no progress
  104. outpos_ = 0;
  105. return res;
  106. }
  107. // We claim to have sent the whole thing, even if we only sent partial
  108. return static_cast<int>(cb);
  109. }
  110. int AsyncTCPSocket::SendTo(const void *pv, size_t cb,
  111. const SocketAddress& addr) {
  112. if (addr == GetRemoteAddress())
  113. return Send(pv, cb);
  114. ASSERT(false);
  115. socket_->SetError(ENOTCONN);
  116. return -1;
  117. }
  118. int AsyncTCPSocket::Close() {
  119. return socket_->Close();
  120. }
  121. AsyncTCPSocket::State AsyncTCPSocket::GetState() const {
  122. switch (socket_->GetState()) {
  123. case Socket::CS_CLOSED:
  124. return STATE_CLOSED;
  125. case Socket::CS_CONNECTING:
  126. if (listen_) {
  127. return STATE_BOUND;
  128. } else {
  129. return STATE_CONNECTING;
  130. }
  131. case Socket::CS_CONNECTED:
  132. return STATE_CONNECTED;
  133. default:
  134. ASSERT(false);
  135. return STATE_CLOSED;
  136. }
  137. }
  138. int AsyncTCPSocket::GetOption(Socket::Option opt, int* value) {
  139. return socket_->GetOption(opt, value);
  140. }
  141. int AsyncTCPSocket::SetOption(Socket::Option opt, int value) {
  142. return socket_->SetOption(opt, value);
  143. }
  144. int AsyncTCPSocket::GetError() const {
  145. return socket_->GetError();
  146. }
  147. void AsyncTCPSocket::SetError(int error) {
  148. return socket_->SetError(error);
  149. }
  150. int AsyncTCPSocket::SendRaw(const void * pv, size_t cb) {
  151. if (outpos_ + cb > outsize_) {
  152. socket_->SetError(EMSGSIZE);
  153. return -1;
  154. }
  155. memcpy(outbuf_ + outpos_, pv, cb);
  156. outpos_ += cb;
  157. return Flush();
  158. }
  159. void AsyncTCPSocket::ProcessInput(char * data, size_t& len) {
  160. SocketAddress remote_addr(GetRemoteAddress());
  161. while (true) {
  162. if (len < PKT_LEN_SIZE)
  163. return;
  164. PacketLength pkt_len;
  165. memcpy(&pkt_len, data, PKT_LEN_SIZE);
  166. pkt_len = NetworkToHost16(pkt_len);
  167. if (len < PKT_LEN_SIZE + pkt_len)
  168. return;
  169. SignalReadPacket(this, data + PKT_LEN_SIZE, pkt_len, remote_addr);
  170. len -= PKT_LEN_SIZE + pkt_len;
  171. if (len > 0) {
  172. memmove(data, data + PKT_LEN_SIZE + pkt_len, len);
  173. }
  174. }
  175. }
  176. int AsyncTCPSocket::Flush() {
  177. int res = socket_->Send(outbuf_, outpos_);
  178. if (res <= 0) {
  179. return res;
  180. }
  181. if (static_cast<size_t>(res) <= outpos_) {
  182. outpos_ -= res;
  183. } else {
  184. ASSERT(false);
  185. return -1;
  186. }
  187. if (outpos_ > 0) {
  188. memmove(outbuf_, outbuf_ + res, outpos_);
  189. }
  190. return res;
  191. }
  192. void AsyncTCPSocket::OnConnectEvent(AsyncSocket* socket) {
  193. SignalConnect(this);
  194. }
  195. void AsyncTCPSocket::OnReadEvent(AsyncSocket* socket) {
  196. ASSERT(socket_.get() == socket);
  197. if (listen_) {
  198. talk_base::SocketAddress address;
  199. talk_base::AsyncSocket* new_socket = socket->Accept(&address);
  200. if (!new_socket) {
  201. // TODO: Do something better like forwarding the error
  202. // to the user.
  203. LOG(LS_ERROR) << "TCP accept failed with error " << socket_->GetError();
  204. return;
  205. }
  206. SignalNewConnection(this, new AsyncTCPSocket(new_socket, false));
  207. // Prime a read event in case data is waiting.
  208. new_socket->SignalReadEvent(new_socket);
  209. } else {
  210. int len = socket_->Recv(inbuf_ + inpos_, insize_ - inpos_);
  211. if (len < 0) {
  212. // TODO: Do something better like forwarding the error to the user.
  213. if (!socket_->IsBlocking()) {
  214. LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
  215. }
  216. return;
  217. }
  218. inpos_ += len;
  219. ProcessInput(inbuf_, inpos_);
  220. if (inpos_ >= insize_) {
  221. LOG(LS_ERROR) << "input buffer overflow";
  222. ASSERT(false);
  223. inpos_ = 0;
  224. }
  225. }
  226. }
  227. void AsyncTCPSocket::OnWriteEvent(AsyncSocket* socket) {
  228. ASSERT(socket_.get() == socket);
  229. if (outpos_ > 0) {
  230. Flush();
  231. }
  232. }
  233. void AsyncTCPSocket::OnCloseEvent(AsyncSocket* socket, int error) {
  234. SignalClose(this, error);
  235. }
  236. } // namespace talk_base