blob: d3d88bc9d65acfc12fbaeefc665b65c10271d8e5 [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "rtc_base/asynctcpsocket.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000012
13#include <string.h>
14
jbauch313afba2016-03-03 03:41:05 -080015#include <algorithm>
jbauch555604a2016-04-26 03:13:22 -070016#include <memory>
jbauch313afba2016-03-03 03:41:05 -080017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/byteorder.h"
19#include "rtc_base/checks.h"
20#include "rtc_base/logging.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000021
22#if defined(WEBRTC_POSIX)
23#include <errno.h>
24#endif // WEBRTC_POSIX
25
26namespace rtc {
27
28static const size_t kMaxPacketSize = 64 * 1024;
29
Peter Boström0c4e06b2015-10-07 12:23:21 +020030typedef uint16_t PacketLength;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000031static const size_t kPacketLenSize = sizeof(PacketLength);
32
33static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
34
jbauch313afba2016-03-03 03:41:05 -080035// The input buffer will be resized so that at least kMinimumRecvSize bytes can
36// be received (but it will not grow above the maximum size passed to the
37// constructor).
38static const size_t kMinimumRecvSize = 128;
39
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000040static const int kListenBacklog = 5;
41
42// Binds and connects |socket|
43AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
44 rtc::AsyncSocket* socket,
45 const rtc::SocketAddress& bind_address,
46 const rtc::SocketAddress& remote_address) {
jbauch555604a2016-04-26 03:13:22 -070047 std::unique_ptr<rtc::AsyncSocket> owned_socket(socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000048 if (socket->Bind(bind_address) < 0) {
49 LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
deadbeef37f5ecf2017-02-27 14:06:41 -080050 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000051 }
52 if (socket->Connect(remote_address) < 0) {
53 LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
deadbeef37f5ecf2017-02-27 14:06:41 -080054 return nullptr;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000055 }
56 return owned_socket.release();
57}
58
59AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket, bool listen,
60 size_t max_packet_size)
61 : socket_(socket),
62 listen_(listen),
jbauch313afba2016-03-03 03:41:05 -080063 max_insize_(max_packet_size),
jbauch250fc652016-02-28 15:06:40 -080064 max_outsize_(max_packet_size) {
jbauch3c165762016-02-26 09:31:32 -080065 if (!listen_) {
66 // Listening sockets don't send/receive data, so they don't need buffers.
jbauch313afba2016-03-03 03:41:05 -080067 inbuf_.EnsureCapacity(kMinimumRecvSize);
jbauch3c165762016-02-26 09:31:32 -080068 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000069
deadbeef37f5ecf2017-02-27 14:06:41 -080070 RTC_DCHECK(socket_.get() != nullptr);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000071 socket_->SignalConnectEvent.connect(
72 this, &AsyncTCPSocketBase::OnConnectEvent);
73 socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
74 socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
75 socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
76
77 if (listen_) {
78 if (socket_->Listen(kListenBacklog) < 0) {
79 LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
80 }
81 }
82}
83
jbauch3c165762016-02-26 09:31:32 -080084AsyncTCPSocketBase::~AsyncTCPSocketBase() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000085
86SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
87 return socket_->GetLocalAddress();
88}
89
90SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
91 return socket_->GetRemoteAddress();
92}
93
94int AsyncTCPSocketBase::Close() {
95 return socket_->Close();
96}
97
98AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
99 switch (socket_->GetState()) {
100 case Socket::CS_CLOSED:
101 return STATE_CLOSED;
102 case Socket::CS_CONNECTING:
103 if (listen_) {
104 return STATE_BOUND;
105 } else {
106 return STATE_CONNECTING;
107 }
108 case Socket::CS_CONNECTED:
109 return STATE_CONNECTED;
110 default:
jbauch3c165762016-02-26 09:31:32 -0800111 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000112 return STATE_CLOSED;
113 }
114}
115
116int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
117 return socket_->GetOption(opt, value);
118}
119
120int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
121 return socket_->SetOption(opt, value);
122}
123
124int AsyncTCPSocketBase::GetError() const {
125 return socket_->GetError();
126}
127
128void AsyncTCPSocketBase::SetError(int error) {
129 return socket_->SetError(error);
130}
131
132int AsyncTCPSocketBase::SendTo(const void *pv, size_t cb,
133 const SocketAddress& addr,
134 const rtc::PacketOptions& options) {
honghaizb19eba32015-08-03 10:23:31 -0700135 const SocketAddress& remote_address = GetRemoteAddress();
136 if (addr == remote_address)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000137 return Send(pv, cb, options);
honghaizb19eba32015-08-03 10:23:31 -0700138 // Remote address may be empty if there is a sudden network change.
jbauch3c165762016-02-26 09:31:32 -0800139 RTC_DCHECK(remote_address.IsNil());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 socket_->SetError(ENOTCONN);
141 return -1;
142}
143
144int AsyncTCPSocketBase::SendRaw(const void * pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800145 if (outbuf_.size() + cb > max_outsize_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146 socket_->SetError(EMSGSIZE);
147 return -1;
148 }
149
jbauch250fc652016-02-28 15:06:40 -0800150 RTC_DCHECK(!listen_);
151 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000152
153 return FlushOutBuffer();
154}
155
156int AsyncTCPSocketBase::FlushOutBuffer() {
jbauch250fc652016-02-28 15:06:40 -0800157 RTC_DCHECK(!listen_);
158 int res = socket_->Send(outbuf_.data(), outbuf_.size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000159 if (res <= 0) {
160 return res;
161 }
jbauch250fc652016-02-28 15:06:40 -0800162 if (static_cast<size_t>(res) > outbuf_.size()) {
jbauch3c165762016-02-26 09:31:32 -0800163 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000164 return -1;
165 }
jbauch250fc652016-02-28 15:06:40 -0800166 size_t new_size = outbuf_.size() - res;
167 if (new_size > 0) {
168 memmove(outbuf_.data(), outbuf_.data() + res, new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000169 }
jbauch250fc652016-02-28 15:06:40 -0800170 outbuf_.SetSize(new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000171 return res;
172}
173
174void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800175 RTC_DCHECK(outbuf_.size() + cb <= max_outsize_);
176 RTC_DCHECK(!listen_);
177 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000178}
179
180void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
181 SignalConnect(this);
182}
183
184void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800185 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000186
187 if (listen_) {
188 rtc::SocketAddress address;
189 rtc::AsyncSocket* new_socket = socket->Accept(&address);
190 if (!new_socket) {
jbauch313afba2016-03-03 03:41:05 -0800191 // TODO(stefan): Do something better like forwarding the error
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000192 // to the user.
193 LOG(LS_ERROR) << "TCP accept failed with error " << socket_->GetError();
194 return;
195 }
196
197 HandleIncomingConnection(new_socket);
198
199 // Prime a read event in case data is waiting.
200 new_socket->SignalReadEvent(new_socket);
201 } else {
jbauch313afba2016-03-03 03:41:05 -0800202 size_t total_recv = 0;
203 while (true) {
204 size_t free_size = inbuf_.capacity() - inbuf_.size();
205 if (free_size < kMinimumRecvSize && inbuf_.capacity() < max_insize_) {
206 inbuf_.EnsureCapacity(std::min(max_insize_, inbuf_.capacity() * 2));
207 free_size = inbuf_.capacity() - inbuf_.size();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000208 }
jbauch313afba2016-03-03 03:41:05 -0800209
Stefan Holmer9131efd2016-05-23 18:19:26 +0200210 int len =
211 socket_->Recv(inbuf_.data() + inbuf_.size(), free_size, nullptr);
jbauch313afba2016-03-03 03:41:05 -0800212 if (len < 0) {
213 // TODO(stefan): Do something better like forwarding the error to the
214 // user.
215 if (!socket_->IsBlocking()) {
216 LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
217 }
218 break;
219 }
220
221 total_recv += len;
222 inbuf_.SetSize(inbuf_.size() + len);
223 if (!len || static_cast<size_t>(len) < free_size) {
224 break;
225 }
226 }
227
228 if (!total_recv) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000229 return;
230 }
231
jbauch313afba2016-03-03 03:41:05 -0800232 size_t size = inbuf_.size();
233 ProcessInput(inbuf_.data<char>(), &size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000234
jbauch313afba2016-03-03 03:41:05 -0800235 if (size > inbuf_.size()) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000236 LOG(LS_ERROR) << "input buffer overflow";
jbauch3c165762016-02-26 09:31:32 -0800237 RTC_NOTREACHED();
jbauch313afba2016-03-03 03:41:05 -0800238 inbuf_.Clear();
239 } else {
240 inbuf_.SetSize(size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000241 }
242 }
243}
244
245void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800246 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000247
jbauch250fc652016-02-28 15:06:40 -0800248 if (outbuf_.size() > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000249 FlushOutBuffer();
250 }
251
jbauch250fc652016-02-28 15:06:40 -0800252 if (outbuf_.size() == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000253 SignalReadyToSend(this);
254 }
255}
256
257void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
258 SignalClose(this, error);
259}
260
261// AsyncTCPSocket
262// Binds and connects |socket| and creates AsyncTCPSocket for
deadbeef37f5ecf2017-02-27 14:06:41 -0800263// it. Takes ownership of |socket|. Returns null if bind() or
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000264// connect() fail (|socket| is destroyed in that case).
265AsyncTCPSocket* AsyncTCPSocket::Create(
266 AsyncSocket* socket,
267 const SocketAddress& bind_address,
268 const SocketAddress& remote_address) {
269 return new AsyncTCPSocket(AsyncTCPSocketBase::ConnectSocket(
270 socket, bind_address, remote_address), false);
271}
272
273AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
274 : AsyncTCPSocketBase(socket, listen, kBufSize) {
275}
276
277int AsyncTCPSocket::Send(const void *pv, size_t cb,
278 const rtc::PacketOptions& options) {
279 if (cb > kBufSize) {
280 SetError(EMSGSIZE);
281 return -1;
282 }
283
284 // If we are blocking on send, then silently drop this packet
285 if (!IsOutBufferEmpty())
286 return static_cast<int>(cb);
287
288 PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
289 AppendToOutBuffer(&pkt_len, kPacketLenSize);
290 AppendToOutBuffer(pv, cb);
291
292 int res = FlushOutBuffer();
293 if (res <= 0) {
294 // drop packet if we made no progress
295 ClearOutBuffer();
296 return res;
297 }
298
Honghai Zhang82d78622016-05-06 11:29:15 -0700299 rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis());
stefanc1aeaf02015-10-15 07:26:07 -0700300 SignalSentPacket(this, sent_packet);
301
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000302 // We claim to have sent the whole thing, even if we only sent partial
303 return static_cast<int>(cb);
304}
305
306void AsyncTCPSocket::ProcessInput(char * data, size_t* len) {
307 SocketAddress remote_addr(GetRemoteAddress());
308
309 while (true) {
310 if (*len < kPacketLenSize)
311 return;
312
313 PacketLength pkt_len = rtc::GetBE16(data);
314 if (*len < kPacketLenSize + pkt_len)
315 return;
316
317 SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
318 CreatePacketTime(0));
319
320 *len -= kPacketLenSize + pkt_len;
321 if (*len > 0) {
322 memmove(data, data + kPacketLenSize + pkt_len, *len);
323 }
324 }
325}
326
327void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
328 SignalNewConnection(this, new AsyncTCPSocket(socket, false));
329}
330
331} // namespace rtc