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.

340 lines
9.6 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/async_tcp_socket.h"
  11. #include <stdint.h>
  12. #include <string.h>
  13. #include <algorithm>
  14. #include <memory>
  15. #include "rtc_base/byte_order.h"
  16. #include "rtc_base/checks.h"
  17. #include "rtc_base/logging.h"
  18. #include "rtc_base/network/sent_packet.h"
  19. #include "rtc_base/third_party/sigslot/sigslot.h"
  20. #include "rtc_base/time_utils.h" // for TimeMillis
  21. #if defined(WEBRTC_POSIX)
  22. #include <errno.h>
  23. #endif // WEBRTC_POSIX
  24. namespace rtc {
  25. static const size_t kMaxPacketSize = 64 * 1024;
  26. typedef uint16_t PacketLength;
  27. static const size_t kPacketLenSize = sizeof(PacketLength);
  28. static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
  29. // The input buffer will be resized so that at least kMinimumRecvSize bytes can
  30. // be received (but it will not grow above the maximum size passed to the
  31. // constructor).
  32. static const size_t kMinimumRecvSize = 128;
  33. static const int kListenBacklog = 5;
  34. // Binds and connects |socket|
  35. AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
  36. rtc::AsyncSocket* socket,
  37. const rtc::SocketAddress& bind_address,
  38. const rtc::SocketAddress& remote_address) {
  39. std::unique_ptr<rtc::AsyncSocket> owned_socket(socket);
  40. if (socket->Bind(bind_address) < 0) {
  41. RTC_LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
  42. return nullptr;
  43. }
  44. if (socket->Connect(remote_address) < 0) {
  45. RTC_LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
  46. return nullptr;
  47. }
  48. return owned_socket.release();
  49. }
  50. AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket,
  51. bool listen,
  52. size_t max_packet_size)
  53. : socket_(socket),
  54. listen_(listen),
  55. max_insize_(max_packet_size),
  56. max_outsize_(max_packet_size) {
  57. if (!listen_) {
  58. // Listening sockets don't send/receive data, so they don't need buffers.
  59. inbuf_.EnsureCapacity(kMinimumRecvSize);
  60. }
  61. RTC_DCHECK(socket_.get() != nullptr);
  62. socket_->SignalConnectEvent.connect(this,
  63. &AsyncTCPSocketBase::OnConnectEvent);
  64. socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
  65. socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
  66. socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
  67. if (listen_) {
  68. if (socket_->Listen(kListenBacklog) < 0) {
  69. RTC_LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
  70. }
  71. }
  72. }
  73. AsyncTCPSocketBase::~AsyncTCPSocketBase() {}
  74. SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
  75. return socket_->GetLocalAddress();
  76. }
  77. SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
  78. return socket_->GetRemoteAddress();
  79. }
  80. int AsyncTCPSocketBase::Close() {
  81. return socket_->Close();
  82. }
  83. AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
  84. switch (socket_->GetState()) {
  85. case Socket::CS_CLOSED:
  86. return STATE_CLOSED;
  87. case Socket::CS_CONNECTING:
  88. if (listen_) {
  89. return STATE_BOUND;
  90. } else {
  91. return STATE_CONNECTING;
  92. }
  93. case Socket::CS_CONNECTED:
  94. return STATE_CONNECTED;
  95. default:
  96. RTC_NOTREACHED();
  97. return STATE_CLOSED;
  98. }
  99. }
  100. int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
  101. return socket_->GetOption(opt, value);
  102. }
  103. int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
  104. return socket_->SetOption(opt, value);
  105. }
  106. int AsyncTCPSocketBase::GetError() const {
  107. return socket_->GetError();
  108. }
  109. void AsyncTCPSocketBase::SetError(int error) {
  110. return socket_->SetError(error);
  111. }
  112. int AsyncTCPSocketBase::SendTo(const void* pv,
  113. size_t cb,
  114. const SocketAddress& addr,
  115. const rtc::PacketOptions& options) {
  116. const SocketAddress& remote_address = GetRemoteAddress();
  117. if (addr == remote_address)
  118. return Send(pv, cb, options);
  119. // Remote address may be empty if there is a sudden network change.
  120. RTC_DCHECK(remote_address.IsNil());
  121. socket_->SetError(ENOTCONN);
  122. return -1;
  123. }
  124. int AsyncTCPSocketBase::SendRaw(const void* pv, size_t cb) {
  125. if (outbuf_.size() + cb > max_outsize_) {
  126. socket_->SetError(EMSGSIZE);
  127. return -1;
  128. }
  129. RTC_DCHECK(!listen_);
  130. outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
  131. return FlushOutBuffer();
  132. }
  133. int AsyncTCPSocketBase::FlushOutBuffer() {
  134. RTC_DCHECK(!listen_);
  135. int res = socket_->Send(outbuf_.data(), outbuf_.size());
  136. if (res <= 0) {
  137. return res;
  138. }
  139. if (static_cast<size_t>(res) > outbuf_.size()) {
  140. RTC_NOTREACHED();
  141. return -1;
  142. }
  143. size_t new_size = outbuf_.size() - res;
  144. if (new_size > 0) {
  145. memmove(outbuf_.data(), outbuf_.data() + res, new_size);
  146. }
  147. outbuf_.SetSize(new_size);
  148. return res;
  149. }
  150. void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
  151. RTC_DCHECK(outbuf_.size() + cb <= max_outsize_);
  152. RTC_DCHECK(!listen_);
  153. outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
  154. }
  155. void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
  156. SignalConnect(this);
  157. }
  158. void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
  159. RTC_DCHECK(socket_.get() == socket);
  160. if (listen_) {
  161. rtc::SocketAddress address;
  162. rtc::AsyncSocket* new_socket = socket->Accept(&address);
  163. if (!new_socket) {
  164. // TODO(stefan): Do something better like forwarding the error
  165. // to the user.
  166. RTC_LOG(LS_ERROR) << "TCP accept failed with error "
  167. << socket_->GetError();
  168. return;
  169. }
  170. HandleIncomingConnection(new_socket);
  171. // Prime a read event in case data is waiting.
  172. new_socket->SignalReadEvent(new_socket);
  173. } else {
  174. size_t total_recv = 0;
  175. while (true) {
  176. size_t free_size = inbuf_.capacity() - inbuf_.size();
  177. if (free_size < kMinimumRecvSize && inbuf_.capacity() < max_insize_) {
  178. inbuf_.EnsureCapacity(std::min(max_insize_, inbuf_.capacity() * 2));
  179. free_size = inbuf_.capacity() - inbuf_.size();
  180. }
  181. int len =
  182. socket_->Recv(inbuf_.data() + inbuf_.size(), free_size, nullptr);
  183. if (len < 0) {
  184. // TODO(stefan): Do something better like forwarding the error to the
  185. // user.
  186. if (!socket_->IsBlocking()) {
  187. RTC_LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
  188. }
  189. break;
  190. }
  191. total_recv += len;
  192. inbuf_.SetSize(inbuf_.size() + len);
  193. if (!len || static_cast<size_t>(len) < free_size) {
  194. break;
  195. }
  196. }
  197. if (!total_recv) {
  198. return;
  199. }
  200. size_t size = inbuf_.size();
  201. ProcessInput(inbuf_.data<char>(), &size);
  202. if (size > inbuf_.size()) {
  203. RTC_LOG(LS_ERROR) << "input buffer overflow";
  204. RTC_NOTREACHED();
  205. inbuf_.Clear();
  206. } else {
  207. inbuf_.SetSize(size);
  208. }
  209. }
  210. }
  211. void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
  212. RTC_DCHECK(socket_.get() == socket);
  213. if (outbuf_.size() > 0) {
  214. FlushOutBuffer();
  215. }
  216. if (outbuf_.size() == 0) {
  217. SignalReadyToSend(this);
  218. }
  219. }
  220. void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
  221. SignalClose(this, error);
  222. }
  223. // AsyncTCPSocket
  224. // Binds and connects |socket| and creates AsyncTCPSocket for
  225. // it. Takes ownership of |socket|. Returns null if bind() or
  226. // connect() fail (|socket| is destroyed in that case).
  227. AsyncTCPSocket* AsyncTCPSocket::Create(AsyncSocket* socket,
  228. const SocketAddress& bind_address,
  229. const SocketAddress& remote_address) {
  230. return new AsyncTCPSocket(
  231. AsyncTCPSocketBase::ConnectSocket(socket, bind_address, remote_address),
  232. false);
  233. }
  234. AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
  235. : AsyncTCPSocketBase(socket, listen, kBufSize) {}
  236. int AsyncTCPSocket::Send(const void* pv,
  237. size_t cb,
  238. const rtc::PacketOptions& options) {
  239. if (cb > kBufSize) {
  240. SetError(EMSGSIZE);
  241. return -1;
  242. }
  243. // If we are blocking on send, then silently drop this packet
  244. if (!IsOutBufferEmpty())
  245. return static_cast<int>(cb);
  246. PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
  247. AppendToOutBuffer(&pkt_len, kPacketLenSize);
  248. AppendToOutBuffer(pv, cb);
  249. int res = FlushOutBuffer();
  250. if (res <= 0) {
  251. // drop packet if we made no progress
  252. ClearOutBuffer();
  253. return res;
  254. }
  255. rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis(),
  256. options.info_signaled_after_sent);
  257. CopySocketInformationToPacketInfo(cb, *this, false, &sent_packet.info);
  258. SignalSentPacket(this, sent_packet);
  259. // We claim to have sent the whole thing, even if we only sent partial
  260. return static_cast<int>(cb);
  261. }
  262. void AsyncTCPSocket::ProcessInput(char* data, size_t* len) {
  263. SocketAddress remote_addr(GetRemoteAddress());
  264. while (true) {
  265. if (*len < kPacketLenSize)
  266. return;
  267. PacketLength pkt_len = rtc::GetBE16(data);
  268. if (*len < kPacketLenSize + pkt_len)
  269. return;
  270. SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
  271. TimeMicros());
  272. *len -= kPacketLenSize + pkt_len;
  273. if (*len > 0) {
  274. memmove(data, data + kPacketLenSize + pkt_len, *len);
  275. }
  276. }
  277. }
  278. void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
  279. SignalNewConnection(this, new AsyncTCPSocket(socket, false));
  280. }
  281. } // namespace rtc