blob: d03ae32dde48f6933888192235aeab1dbeac3a7d [file] [log] [blame]
henrike@webrtc.orgf0488722014-05-13 18:00:26 +00001/*
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
Steve Anton10542f22019-01-11 09:11:00 -080011#include "rtc_base/async_tcp_socket.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
Yves Gerey3e707812018-11-28 16:47:49 +010013#include <stdint.h>
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000014#include <string.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020015
jbauch313afba2016-03-03 03:41:05 -080016#include <algorithm>
jbauch555604a2016-04-26 03:13:22 -070017#include <memory>
jbauch313afba2016-03-03 03:41:05 -080018
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/byte_order.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
21#include "rtc_base/logging.h"
Yves Gerey3e707812018-11-28 16:47:49 +010022#include "rtc_base/network/sent_packet.h"
23#include "rtc_base/third_party/sigslot/sigslot.h"
Steve Anton10542f22019-01-11 09:11:00 -080024#include "rtc_base/time_utils.h" // for TimeMillis
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000025
26#if defined(WEBRTC_POSIX)
27#include <errno.h>
28#endif // WEBRTC_POSIX
29
30namespace rtc {
31
32static const size_t kMaxPacketSize = 64 * 1024;
33
Peter Boström0c4e06b2015-10-07 12:23:21 +020034typedef uint16_t PacketLength;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000035static const size_t kPacketLenSize = sizeof(PacketLength);
36
37static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
38
jbauch313afba2016-03-03 03:41:05 -080039// The input buffer will be resized so that at least kMinimumRecvSize bytes can
40// be received (but it will not grow above the maximum size passed to the
41// constructor).
42static const size_t kMinimumRecvSize = 128;
43
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000044static const int kListenBacklog = 5;
45
46// Binds and connects |socket|
47AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
48 rtc::AsyncSocket* socket,
49 const rtc::SocketAddress& bind_address,
50 const rtc::SocketAddress& remote_address) {
jbauch555604a2016-04-26 03:13:22 -070051 std::unique_ptr<rtc::AsyncSocket> owned_socket(socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000052 if (socket->Bind(bind_address) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010053 RTC_LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
deadbeef37f5ecf2017-02-27 14:06:41 -080054 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055 }
56 if (socket->Connect(remote_address) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010057 RTC_LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
deadbeef37f5ecf2017-02-27 14:06:41 -080058 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000059 }
60 return owned_socket.release();
61}
62
Yves Gerey665174f2018-06-19 15:03:05 +020063AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket,
64 bool listen,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065 size_t max_packet_size)
66 : socket_(socket),
67 listen_(listen),
jbauch313afba2016-03-03 03:41:05 -080068 max_insize_(max_packet_size),
jbauch250fc652016-02-28 15:06:40 -080069 max_outsize_(max_packet_size) {
jbauch3c165762016-02-26 09:31:32 -080070 if (!listen_) {
71 // Listening sockets don't send/receive data, so they don't need buffers.
jbauch313afba2016-03-03 03:41:05 -080072 inbuf_.EnsureCapacity(kMinimumRecvSize);
jbauch3c165762016-02-26 09:31:32 -080073 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000074
deadbeef37f5ecf2017-02-27 14:06:41 -080075 RTC_DCHECK(socket_.get() != nullptr);
Yves Gerey665174f2018-06-19 15:03:05 +020076 socket_->SignalConnectEvent.connect(this,
77 &AsyncTCPSocketBase::OnConnectEvent);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000078 socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
79 socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
80 socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
81
82 if (listen_) {
83 if (socket_->Listen(kListenBacklog) < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010084 RTC_LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085 }
86 }
87}
88
jbauch3c165762016-02-26 09:31:32 -080089AsyncTCPSocketBase::~AsyncTCPSocketBase() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000090
91SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
92 return socket_->GetLocalAddress();
93}
94
95SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
96 return socket_->GetRemoteAddress();
97}
98
99int AsyncTCPSocketBase::Close() {
100 return socket_->Close();
101}
102
103AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
104 switch (socket_->GetState()) {
105 case Socket::CS_CLOSED:
106 return STATE_CLOSED;
107 case Socket::CS_CONNECTING:
108 if (listen_) {
109 return STATE_BOUND;
110 } else {
111 return STATE_CONNECTING;
112 }
113 case Socket::CS_CONNECTED:
114 return STATE_CONNECTED;
115 default:
jbauch3c165762016-02-26 09:31:32 -0800116 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000117 return STATE_CLOSED;
118 }
119}
120
121int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
122 return socket_->GetOption(opt, value);
123}
124
125int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
126 return socket_->SetOption(opt, value);
127}
128
129int AsyncTCPSocketBase::GetError() const {
130 return socket_->GetError();
131}
132
133void AsyncTCPSocketBase::SetError(int error) {
134 return socket_->SetError(error);
135}
136
Yves Gerey665174f2018-06-19 15:03:05 +0200137int AsyncTCPSocketBase::SendTo(const void* pv,
138 size_t cb,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000139 const SocketAddress& addr,
140 const rtc::PacketOptions& options) {
honghaizb19eba32015-08-03 10:23:31 -0700141 const SocketAddress& remote_address = GetRemoteAddress();
142 if (addr == remote_address)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000143 return Send(pv, cb, options);
honghaizb19eba32015-08-03 10:23:31 -0700144 // Remote address may be empty if there is a sudden network change.
jbauch3c165762016-02-26 09:31:32 -0800145 RTC_DCHECK(remote_address.IsNil());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146 socket_->SetError(ENOTCONN);
147 return -1;
148}
149
Yves Gerey665174f2018-06-19 15:03:05 +0200150int AsyncTCPSocketBase::SendRaw(const void* pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800151 if (outbuf_.size() + cb > max_outsize_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152 socket_->SetError(EMSGSIZE);
153 return -1;
154 }
155
jbauch250fc652016-02-28 15:06:40 -0800156 RTC_DCHECK(!listen_);
157 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000158
159 return FlushOutBuffer();
160}
161
162int AsyncTCPSocketBase::FlushOutBuffer() {
jbauch250fc652016-02-28 15:06:40 -0800163 RTC_DCHECK(!listen_);
164 int res = socket_->Send(outbuf_.data(), outbuf_.size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 if (res <= 0) {
166 return res;
167 }
jbauch250fc652016-02-28 15:06:40 -0800168 if (static_cast<size_t>(res) > outbuf_.size()) {
jbauch3c165762016-02-26 09:31:32 -0800169 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 return -1;
171 }
jbauch250fc652016-02-28 15:06:40 -0800172 size_t new_size = outbuf_.size() - res;
173 if (new_size > 0) {
174 memmove(outbuf_.data(), outbuf_.data() + res, new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000175 }
jbauch250fc652016-02-28 15:06:40 -0800176 outbuf_.SetSize(new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000177 return res;
178}
179
180void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800181 RTC_DCHECK(outbuf_.size() + cb <= max_outsize_);
182 RTC_DCHECK(!listen_);
183 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000184}
185
186void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
187 SignalConnect(this);
188}
189
190void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800191 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192
193 if (listen_) {
194 rtc::SocketAddress address;
195 rtc::AsyncSocket* new_socket = socket->Accept(&address);
196 if (!new_socket) {
jbauch313afba2016-03-03 03:41:05 -0800197 // TODO(stefan): Do something better like forwarding the error
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 // to the user.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100199 RTC_LOG(LS_ERROR) << "TCP accept failed with error "
200 << socket_->GetError();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000201 return;
202 }
203
204 HandleIncomingConnection(new_socket);
205
206 // Prime a read event in case data is waiting.
207 new_socket->SignalReadEvent(new_socket);
208 } else {
jbauch313afba2016-03-03 03:41:05 -0800209 size_t total_recv = 0;
210 while (true) {
211 size_t free_size = inbuf_.capacity() - inbuf_.size();
212 if (free_size < kMinimumRecvSize && inbuf_.capacity() < max_insize_) {
213 inbuf_.EnsureCapacity(std::min(max_insize_, inbuf_.capacity() * 2));
214 free_size = inbuf_.capacity() - inbuf_.size();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000215 }
jbauch313afba2016-03-03 03:41:05 -0800216
Stefan Holmer9131efd2016-05-23 18:19:26 +0200217 int len =
218 socket_->Recv(inbuf_.data() + inbuf_.size(), free_size, nullptr);
jbauch313afba2016-03-03 03:41:05 -0800219 if (len < 0) {
220 // TODO(stefan): Do something better like forwarding the error to the
221 // user.
222 if (!socket_->IsBlocking()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100223 RTC_LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
jbauch313afba2016-03-03 03:41:05 -0800224 }
225 break;
226 }
227
228 total_recv += len;
229 inbuf_.SetSize(inbuf_.size() + len);
230 if (!len || static_cast<size_t>(len) < free_size) {
231 break;
232 }
233 }
234
235 if (!total_recv) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236 return;
237 }
238
jbauch313afba2016-03-03 03:41:05 -0800239 size_t size = inbuf_.size();
240 ProcessInput(inbuf_.data<char>(), &size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241
jbauch313afba2016-03-03 03:41:05 -0800242 if (size > inbuf_.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100243 RTC_LOG(LS_ERROR) << "input buffer overflow";
jbauch3c165762016-02-26 09:31:32 -0800244 RTC_NOTREACHED();
jbauch313afba2016-03-03 03:41:05 -0800245 inbuf_.Clear();
246 } else {
247 inbuf_.SetSize(size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248 }
249 }
250}
251
252void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800253 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254
jbauch250fc652016-02-28 15:06:40 -0800255 if (outbuf_.size() > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000256 FlushOutBuffer();
257 }
258
jbauch250fc652016-02-28 15:06:40 -0800259 if (outbuf_.size() == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000260 SignalReadyToSend(this);
261 }
262}
263
264void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
265 SignalClose(this, error);
266}
267
268// AsyncTCPSocket
269// Binds and connects |socket| and creates AsyncTCPSocket for
deadbeef37f5ecf2017-02-27 14:06:41 -0800270// it. Takes ownership of |socket|. Returns null if bind() or
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000271// connect() fail (|socket| is destroyed in that case).
Yves Gerey665174f2018-06-19 15:03:05 +0200272AsyncTCPSocket* AsyncTCPSocket::Create(AsyncSocket* socket,
273 const SocketAddress& bind_address,
274 const SocketAddress& remote_address) {
275 return new AsyncTCPSocket(
276 AsyncTCPSocketBase::ConnectSocket(socket, bind_address, remote_address),
277 false);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000278}
279
280AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
Yves Gerey665174f2018-06-19 15:03:05 +0200281 : AsyncTCPSocketBase(socket, listen, kBufSize) {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000282
Yves Gerey665174f2018-06-19 15:03:05 +0200283int AsyncTCPSocket::Send(const void* pv,
284 size_t cb,
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000285 const rtc::PacketOptions& options) {
286 if (cb > kBufSize) {
287 SetError(EMSGSIZE);
288 return -1;
289 }
290
291 // If we are blocking on send, then silently drop this packet
292 if (!IsOutBufferEmpty())
293 return static_cast<int>(cb);
294
295 PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
296 AppendToOutBuffer(&pkt_len, kPacketLenSize);
297 AppendToOutBuffer(pv, cb);
298
299 int res = FlushOutBuffer();
300 if (res <= 0) {
301 // drop packet if we made no progress
302 ClearOutBuffer();
303 return res;
304 }
305
Qingsi Wang6e641e62018-04-11 20:14:17 -0700306 rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis(),
307 options.info_signaled_after_sent);
Qingsi Wang4ea53b32018-04-16 18:22:31 -0700308 CopySocketInformationToPacketInfo(cb, *this, false, &sent_packet.info);
stefanc1aeaf02015-10-15 07:26:07 -0700309 SignalSentPacket(this, sent_packet);
310
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000311 // We claim to have sent the whole thing, even if we only sent partial
312 return static_cast<int>(cb);
313}
314
Yves Gerey665174f2018-06-19 15:03:05 +0200315void AsyncTCPSocket::ProcessInput(char* data, size_t* len) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000316 SocketAddress remote_addr(GetRemoteAddress());
317
318 while (true) {
319 if (*len < kPacketLenSize)
320 return;
321
322 PacketLength pkt_len = rtc::GetBE16(data);
323 if (*len < kPacketLenSize + pkt_len)
324 return;
325
326 SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
Niels Möller15ca5a92018-11-01 14:32:47 +0100327 TimeMicros());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000328
329 *len -= kPacketLenSize + pkt_len;
330 if (*len > 0) {
331 memmove(data, data + kPacketLenSize + pkt_len, *len);
332 }
333 }
334}
335
336void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
337 SignalNewConnection(this, new AsyncTCPSocket(socket, false));
338}
339
340} // namespace rtc