blob: 120bcfbb64cddb7577d1200d6932b95ea7dbfba5 [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
11#include "webrtc/base/asynctcpsocket.h"
12
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
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000018#include "webrtc/base/byteorder.h"
jbauch3c165762016-02-26 09:31:32 -080019#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000020#include "webrtc/base/common.h"
21#include "webrtc/base/logging.h"
22
23#if defined(WEBRTC_POSIX)
24#include <errno.h>
25#endif // WEBRTC_POSIX
26
27namespace rtc {
28
29static const size_t kMaxPacketSize = 64 * 1024;
30
Peter Boström0c4e06b2015-10-07 12:23:21 +020031typedef uint16_t PacketLength;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000032static const size_t kPacketLenSize = sizeof(PacketLength);
33
34static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
35
jbauch313afba2016-03-03 03:41:05 -080036// The input buffer will be resized so that at least kMinimumRecvSize bytes can
37// be received (but it will not grow above the maximum size passed to the
38// constructor).
39static const size_t kMinimumRecvSize = 128;
40
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000041static const int kListenBacklog = 5;
42
43// Binds and connects |socket|
44AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
45 rtc::AsyncSocket* socket,
46 const rtc::SocketAddress& bind_address,
47 const rtc::SocketAddress& remote_address) {
jbauch555604a2016-04-26 03:13:22 -070048 std::unique_ptr<rtc::AsyncSocket> owned_socket(socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000049 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 owned_socket.release();
58}
59
60AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket, bool listen,
61 size_t max_packet_size)
62 : socket_(socket),
63 listen_(listen),
jbauch313afba2016-03-03 03:41:05 -080064 max_insize_(max_packet_size),
jbauch250fc652016-02-28 15:06:40 -080065 max_outsize_(max_packet_size) {
jbauch3c165762016-02-26 09:31:32 -080066 if (!listen_) {
67 // Listening sockets don't send/receive data, so they don't need buffers.
jbauch313afba2016-03-03 03:41:05 -080068 inbuf_.EnsureCapacity(kMinimumRecvSize);
jbauch3c165762016-02-26 09:31:32 -080069 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000070
jbauch3c165762016-02-26 09:31:32 -080071 RTC_DCHECK(socket_.get() != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000072 socket_->SignalConnectEvent.connect(
73 this, &AsyncTCPSocketBase::OnConnectEvent);
74 socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
75 socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
76 socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
77
78 if (listen_) {
79 if (socket_->Listen(kListenBacklog) < 0) {
80 LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
81 }
82 }
83}
84
jbauch3c165762016-02-26 09:31:32 -080085AsyncTCPSocketBase::~AsyncTCPSocketBase() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000086
87SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
88 return socket_->GetLocalAddress();
89}
90
91SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
92 return socket_->GetRemoteAddress();
93}
94
95int AsyncTCPSocketBase::Close() {
96 return socket_->Close();
97}
98
99AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
100 switch (socket_->GetState()) {
101 case Socket::CS_CLOSED:
102 return STATE_CLOSED;
103 case Socket::CS_CONNECTING:
104 if (listen_) {
105 return STATE_BOUND;
106 } else {
107 return STATE_CONNECTING;
108 }
109 case Socket::CS_CONNECTED:
110 return STATE_CONNECTED;
111 default:
jbauch3c165762016-02-26 09:31:32 -0800112 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000113 return STATE_CLOSED;
114 }
115}
116
117int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
118 return socket_->GetOption(opt, value);
119}
120
121int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
122 return socket_->SetOption(opt, value);
123}
124
125int AsyncTCPSocketBase::GetError() const {
126 return socket_->GetError();
127}
128
129void AsyncTCPSocketBase::SetError(int error) {
130 return socket_->SetError(error);
131}
132
133int AsyncTCPSocketBase::SendTo(const void *pv, size_t cb,
134 const SocketAddress& addr,
135 const rtc::PacketOptions& options) {
honghaizb19eba32015-08-03 10:23:31 -0700136 const SocketAddress& remote_address = GetRemoteAddress();
137 if (addr == remote_address)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000138 return Send(pv, cb, options);
honghaizb19eba32015-08-03 10:23:31 -0700139 // Remote address may be empty if there is a sudden network change.
jbauch3c165762016-02-26 09:31:32 -0800140 RTC_DCHECK(remote_address.IsNil());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000141 socket_->SetError(ENOTCONN);
142 return -1;
143}
144
145int AsyncTCPSocketBase::SendRaw(const void * pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800146 if (outbuf_.size() + cb > max_outsize_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000147 socket_->SetError(EMSGSIZE);
148 return -1;
149 }
150
jbauch250fc652016-02-28 15:06:40 -0800151 RTC_DCHECK(!listen_);
152 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000153
154 return FlushOutBuffer();
155}
156
157int AsyncTCPSocketBase::FlushOutBuffer() {
jbauch250fc652016-02-28 15:06:40 -0800158 RTC_DCHECK(!listen_);
159 int res = socket_->Send(outbuf_.data(), outbuf_.size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000160 if (res <= 0) {
161 return res;
162 }
jbauch250fc652016-02-28 15:06:40 -0800163 if (static_cast<size_t>(res) > outbuf_.size()) {
jbauch3c165762016-02-26 09:31:32 -0800164 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 return -1;
166 }
jbauch250fc652016-02-28 15:06:40 -0800167 size_t new_size = outbuf_.size() - res;
168 if (new_size > 0) {
169 memmove(outbuf_.data(), outbuf_.data() + res, new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000170 }
jbauch250fc652016-02-28 15:06:40 -0800171 outbuf_.SetSize(new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172 return res;
173}
174
175void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800176 RTC_DCHECK(outbuf_.size() + cb <= max_outsize_);
177 RTC_DCHECK(!listen_);
178 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000179}
180
181void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
182 SignalConnect(this);
183}
184
185void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800186 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000187
188 if (listen_) {
189 rtc::SocketAddress address;
190 rtc::AsyncSocket* new_socket = socket->Accept(&address);
191 if (!new_socket) {
jbauch313afba2016-03-03 03:41:05 -0800192 // TODO(stefan): Do something better like forwarding the error
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000193 // to the user.
194 LOG(LS_ERROR) << "TCP accept failed with error " << socket_->GetError();
195 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
211 int len = socket_->Recv(inbuf_.data() + inbuf_.size(), free_size);
212 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
263// it. Takes ownership of |socket|. Returns NULL if bind() or
264// 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
stefanc1aeaf02015-10-15 07:26:07 -0700299 rtc::SentPacket sent_packet(options.packet_id, rtc::Time());
300 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