blob: 9e0589c194ef519e90197265c7f7950be2de4e9c [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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010049 RTC_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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010053 RTC_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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +010079 RTC_LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000080 }
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.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100193 RTC_LOG(LS_ERROR) << "TCP accept failed with error "
194 << socket_->GetError();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000195 return;
196 }
197
198 HandleIncomingConnection(new_socket);
199
200 // Prime a read event in case data is waiting.
201 new_socket->SignalReadEvent(new_socket);
202 } else {
jbauch313afba2016-03-03 03:41:05 -0800203 size_t total_recv = 0;
204 while (true) {
205 size_t free_size = inbuf_.capacity() - inbuf_.size();
206 if (free_size < kMinimumRecvSize && inbuf_.capacity() < max_insize_) {
207 inbuf_.EnsureCapacity(std::min(max_insize_, inbuf_.capacity() * 2));
208 free_size = inbuf_.capacity() - inbuf_.size();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000209 }
jbauch313afba2016-03-03 03:41:05 -0800210
Stefan Holmer9131efd2016-05-23 18:19:26 +0200211 int len =
212 socket_->Recv(inbuf_.data() + inbuf_.size(), free_size, nullptr);
jbauch313afba2016-03-03 03:41:05 -0800213 if (len < 0) {
214 // TODO(stefan): Do something better like forwarding the error to the
215 // user.
216 if (!socket_->IsBlocking()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100217 RTC_LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
jbauch313afba2016-03-03 03:41:05 -0800218 }
219 break;
220 }
221
222 total_recv += len;
223 inbuf_.SetSize(inbuf_.size() + len);
224 if (!len || static_cast<size_t>(len) < free_size) {
225 break;
226 }
227 }
228
229 if (!total_recv) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000230 return;
231 }
232
jbauch313afba2016-03-03 03:41:05 -0800233 size_t size = inbuf_.size();
234 ProcessInput(inbuf_.data<char>(), &size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000235
jbauch313afba2016-03-03 03:41:05 -0800236 if (size > inbuf_.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100237 RTC_LOG(LS_ERROR) << "input buffer overflow";
jbauch3c165762016-02-26 09:31:32 -0800238 RTC_NOTREACHED();
jbauch313afba2016-03-03 03:41:05 -0800239 inbuf_.Clear();
240 } else {
241 inbuf_.SetSize(size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000242 }
243 }
244}
245
246void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800247 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000248
jbauch250fc652016-02-28 15:06:40 -0800249 if (outbuf_.size() > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000250 FlushOutBuffer();
251 }
252
jbauch250fc652016-02-28 15:06:40 -0800253 if (outbuf_.size() == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000254 SignalReadyToSend(this);
255 }
256}
257
258void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
259 SignalClose(this, error);
260}
261
262// AsyncTCPSocket
263// Binds and connects |socket| and creates AsyncTCPSocket for
deadbeef37f5ecf2017-02-27 14:06:41 -0800264// it. Takes ownership of |socket|. Returns null if bind() or
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000265// connect() fail (|socket| is destroyed in that case).
266AsyncTCPSocket* AsyncTCPSocket::Create(
267 AsyncSocket* socket,
268 const SocketAddress& bind_address,
269 const SocketAddress& remote_address) {
270 return new AsyncTCPSocket(AsyncTCPSocketBase::ConnectSocket(
271 socket, bind_address, remote_address), false);
272}
273
274AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
275 : AsyncTCPSocketBase(socket, listen, kBufSize) {
276}
277
278int AsyncTCPSocket::Send(const void *pv, size_t cb,
279 const rtc::PacketOptions& options) {
280 if (cb > kBufSize) {
281 SetError(EMSGSIZE);
282 return -1;
283 }
284
285 // If we are blocking on send, then silently drop this packet
286 if (!IsOutBufferEmpty())
287 return static_cast<int>(cb);
288
289 PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
290 AppendToOutBuffer(&pkt_len, kPacketLenSize);
291 AppendToOutBuffer(pv, cb);
292
293 int res = FlushOutBuffer();
294 if (res <= 0) {
295 // drop packet if we made no progress
296 ClearOutBuffer();
297 return res;
298 }
299
Honghai Zhang82d78622016-05-06 11:29:15 -0700300 rtc::SentPacket sent_packet(options.packet_id, rtc::TimeMillis());
stefanc1aeaf02015-10-15 07:26:07 -0700301 SignalSentPacket(this, sent_packet);
302
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000303 // We claim to have sent the whole thing, even if we only sent partial
304 return static_cast<int>(cb);
305}
306
307void AsyncTCPSocket::ProcessInput(char * data, size_t* len) {
308 SocketAddress remote_addr(GetRemoteAddress());
309
310 while (true) {
311 if (*len < kPacketLenSize)
312 return;
313
314 PacketLength pkt_len = rtc::GetBE16(data);
315 if (*len < kPacketLenSize + pkt_len)
316 return;
317
318 SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
319 CreatePacketTime(0));
320
321 *len -= kPacketLenSize + pkt_len;
322 if (*len > 0) {
323 memmove(data, data + kPacketLenSize + pkt_len, *len);
324 }
325 }
326}
327
328void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
329 SignalNewConnection(this, new AsyncTCPSocket(socket, false));
330}
331
332} // namespace rtc