blob: 31dec92367fc1c876e1b1c4fba1c92eb49b8c91f [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
15#include "webrtc/base/byteorder.h"
jbauch3c165762016-02-26 09:31:32 -080016#include "webrtc/base/checks.h"
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000017#include "webrtc/base/common.h"
18#include "webrtc/base/logging.h"
19
20#if defined(WEBRTC_POSIX)
21#include <errno.h>
22#endif // WEBRTC_POSIX
23
24namespace rtc {
25
26static const size_t kMaxPacketSize = 64 * 1024;
27
Peter Boström0c4e06b2015-10-07 12:23:21 +020028typedef uint16_t PacketLength;
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000029static const size_t kPacketLenSize = sizeof(PacketLength);
30
31static const size_t kBufSize = kMaxPacketSize + kPacketLenSize;
32
33static const int kListenBacklog = 5;
34
35// Binds and connects |socket|
36AsyncSocket* AsyncTCPSocketBase::ConnectSocket(
37 rtc::AsyncSocket* socket,
38 const rtc::SocketAddress& bind_address,
39 const rtc::SocketAddress& remote_address) {
40 rtc::scoped_ptr<rtc::AsyncSocket> owned_socket(socket);
41 if (socket->Bind(bind_address) < 0) {
42 LOG(LS_ERROR) << "Bind() failed with error " << socket->GetError();
43 return NULL;
44 }
45 if (socket->Connect(remote_address) < 0) {
46 LOG(LS_ERROR) << "Connect() failed with error " << socket->GetError();
47 return NULL;
48 }
49 return owned_socket.release();
50}
51
52AsyncTCPSocketBase::AsyncTCPSocketBase(AsyncSocket* socket, bool listen,
53 size_t max_packet_size)
54 : socket_(socket),
55 listen_(listen),
56 insize_(max_packet_size),
57 inpos_(0),
jbauch250fc652016-02-28 15:06:40 -080058 max_outsize_(max_packet_size) {
jbauch3c165762016-02-26 09:31:32 -080059 if (!listen_) {
60 // Listening sockets don't send/receive data, so they don't need buffers.
61 inbuf_.reset(new char[insize_]);
jbauch3c165762016-02-26 09:31:32 -080062 }
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000063
jbauch3c165762016-02-26 09:31:32 -080064 RTC_DCHECK(socket_.get() != NULL);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000065 socket_->SignalConnectEvent.connect(
66 this, &AsyncTCPSocketBase::OnConnectEvent);
67 socket_->SignalReadEvent.connect(this, &AsyncTCPSocketBase::OnReadEvent);
68 socket_->SignalWriteEvent.connect(this, &AsyncTCPSocketBase::OnWriteEvent);
69 socket_->SignalCloseEvent.connect(this, &AsyncTCPSocketBase::OnCloseEvent);
70
71 if (listen_) {
72 if (socket_->Listen(kListenBacklog) < 0) {
73 LOG(LS_ERROR) << "Listen() failed with error " << socket_->GetError();
74 }
75 }
76}
77
jbauch3c165762016-02-26 09:31:32 -080078AsyncTCPSocketBase::~AsyncTCPSocketBase() {}
henrike@webrtc.orgf0488722014-05-13 18:00:26 +000079
80SocketAddress AsyncTCPSocketBase::GetLocalAddress() const {
81 return socket_->GetLocalAddress();
82}
83
84SocketAddress AsyncTCPSocketBase::GetRemoteAddress() const {
85 return socket_->GetRemoteAddress();
86}
87
88int AsyncTCPSocketBase::Close() {
89 return socket_->Close();
90}
91
92AsyncTCPSocket::State AsyncTCPSocketBase::GetState() const {
93 switch (socket_->GetState()) {
94 case Socket::CS_CLOSED:
95 return STATE_CLOSED;
96 case Socket::CS_CONNECTING:
97 if (listen_) {
98 return STATE_BOUND;
99 } else {
100 return STATE_CONNECTING;
101 }
102 case Socket::CS_CONNECTED:
103 return STATE_CONNECTED;
104 default:
jbauch3c165762016-02-26 09:31:32 -0800105 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000106 return STATE_CLOSED;
107 }
108}
109
110int AsyncTCPSocketBase::GetOption(Socket::Option opt, int* value) {
111 return socket_->GetOption(opt, value);
112}
113
114int AsyncTCPSocketBase::SetOption(Socket::Option opt, int value) {
115 return socket_->SetOption(opt, value);
116}
117
118int AsyncTCPSocketBase::GetError() const {
119 return socket_->GetError();
120}
121
122void AsyncTCPSocketBase::SetError(int error) {
123 return socket_->SetError(error);
124}
125
126int AsyncTCPSocketBase::SendTo(const void *pv, size_t cb,
127 const SocketAddress& addr,
128 const rtc::PacketOptions& options) {
honghaizb19eba32015-08-03 10:23:31 -0700129 const SocketAddress& remote_address = GetRemoteAddress();
130 if (addr == remote_address)
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000131 return Send(pv, cb, options);
honghaizb19eba32015-08-03 10:23:31 -0700132 // Remote address may be empty if there is a sudden network change.
jbauch3c165762016-02-26 09:31:32 -0800133 RTC_DCHECK(remote_address.IsNil());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000134 socket_->SetError(ENOTCONN);
135 return -1;
136}
137
138int AsyncTCPSocketBase::SendRaw(const void * pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800139 if (outbuf_.size() + cb > max_outsize_) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000140 socket_->SetError(EMSGSIZE);
141 return -1;
142 }
143
jbauch250fc652016-02-28 15:06:40 -0800144 RTC_DCHECK(!listen_);
145 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000146
147 return FlushOutBuffer();
148}
149
150int AsyncTCPSocketBase::FlushOutBuffer() {
jbauch250fc652016-02-28 15:06:40 -0800151 RTC_DCHECK(!listen_);
152 int res = socket_->Send(outbuf_.data(), outbuf_.size());
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000153 if (res <= 0) {
154 return res;
155 }
jbauch250fc652016-02-28 15:06:40 -0800156 if (static_cast<size_t>(res) > outbuf_.size()) {
jbauch3c165762016-02-26 09:31:32 -0800157 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000158 return -1;
159 }
jbauch250fc652016-02-28 15:06:40 -0800160 size_t new_size = outbuf_.size() - res;
161 if (new_size > 0) {
162 memmove(outbuf_.data(), outbuf_.data() + res, new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000163 }
jbauch250fc652016-02-28 15:06:40 -0800164 outbuf_.SetSize(new_size);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000165 return res;
166}
167
168void AsyncTCPSocketBase::AppendToOutBuffer(const void* pv, size_t cb) {
jbauch250fc652016-02-28 15:06:40 -0800169 RTC_DCHECK(outbuf_.size() + cb <= max_outsize_);
170 RTC_DCHECK(!listen_);
171 outbuf_.AppendData(static_cast<const uint8_t*>(pv), cb);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000172}
173
174void AsyncTCPSocketBase::OnConnectEvent(AsyncSocket* socket) {
175 SignalConnect(this);
176}
177
178void AsyncTCPSocketBase::OnReadEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800179 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000180
181 if (listen_) {
182 rtc::SocketAddress address;
183 rtc::AsyncSocket* new_socket = socket->Accept(&address);
184 if (!new_socket) {
185 // TODO: Do something better like forwarding the error
186 // to the user.
187 LOG(LS_ERROR) << "TCP accept failed with error " << socket_->GetError();
188 return;
189 }
190
191 HandleIncomingConnection(new_socket);
192
193 // Prime a read event in case data is waiting.
194 new_socket->SignalReadEvent(new_socket);
195 } else {
jbauch3c165762016-02-26 09:31:32 -0800196 RTC_DCHECK(inbuf_.get());
197 int len = socket_->Recv(inbuf_.get() + inpos_, insize_ - inpos_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000198 if (len < 0) {
199 // TODO: Do something better like forwarding the error to the user.
200 if (!socket_->IsBlocking()) {
201 LOG(LS_ERROR) << "Recv() returned error: " << socket_->GetError();
202 }
203 return;
204 }
205
206 inpos_ += len;
207
jbauch3c165762016-02-26 09:31:32 -0800208 ProcessInput(inbuf_.get(), &inpos_);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000209
210 if (inpos_ >= insize_) {
211 LOG(LS_ERROR) << "input buffer overflow";
jbauch3c165762016-02-26 09:31:32 -0800212 RTC_NOTREACHED();
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000213 inpos_ = 0;
214 }
215 }
216}
217
218void AsyncTCPSocketBase::OnWriteEvent(AsyncSocket* socket) {
jbauch3c165762016-02-26 09:31:32 -0800219 RTC_DCHECK(socket_.get() == socket);
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000220
jbauch250fc652016-02-28 15:06:40 -0800221 if (outbuf_.size() > 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000222 FlushOutBuffer();
223 }
224
jbauch250fc652016-02-28 15:06:40 -0800225 if (outbuf_.size() == 0) {
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000226 SignalReadyToSend(this);
227 }
228}
229
230void AsyncTCPSocketBase::OnCloseEvent(AsyncSocket* socket, int error) {
231 SignalClose(this, error);
232}
233
234// AsyncTCPSocket
235// Binds and connects |socket| and creates AsyncTCPSocket for
236// it. Takes ownership of |socket|. Returns NULL if bind() or
237// connect() fail (|socket| is destroyed in that case).
238AsyncTCPSocket* AsyncTCPSocket::Create(
239 AsyncSocket* socket,
240 const SocketAddress& bind_address,
241 const SocketAddress& remote_address) {
242 return new AsyncTCPSocket(AsyncTCPSocketBase::ConnectSocket(
243 socket, bind_address, remote_address), false);
244}
245
246AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket, bool listen)
247 : AsyncTCPSocketBase(socket, listen, kBufSize) {
248}
249
250int AsyncTCPSocket::Send(const void *pv, size_t cb,
251 const rtc::PacketOptions& options) {
252 if (cb > kBufSize) {
253 SetError(EMSGSIZE);
254 return -1;
255 }
256
257 // If we are blocking on send, then silently drop this packet
258 if (!IsOutBufferEmpty())
259 return static_cast<int>(cb);
260
261 PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
262 AppendToOutBuffer(&pkt_len, kPacketLenSize);
263 AppendToOutBuffer(pv, cb);
264
265 int res = FlushOutBuffer();
266 if (res <= 0) {
267 // drop packet if we made no progress
268 ClearOutBuffer();
269 return res;
270 }
271
stefanc1aeaf02015-10-15 07:26:07 -0700272 rtc::SentPacket sent_packet(options.packet_id, rtc::Time());
273 SignalSentPacket(this, sent_packet);
274
henrike@webrtc.orgf0488722014-05-13 18:00:26 +0000275 // We claim to have sent the whole thing, even if we only sent partial
276 return static_cast<int>(cb);
277}
278
279void AsyncTCPSocket::ProcessInput(char * data, size_t* len) {
280 SocketAddress remote_addr(GetRemoteAddress());
281
282 while (true) {
283 if (*len < kPacketLenSize)
284 return;
285
286 PacketLength pkt_len = rtc::GetBE16(data);
287 if (*len < kPacketLenSize + pkt_len)
288 return;
289
290 SignalReadPacket(this, data + kPacketLenSize, pkt_len, remote_addr,
291 CreatePacketTime(0));
292
293 *len -= kPacketLenSize + pkt_len;
294 if (*len > 0) {
295 memmove(data, data + kPacketLenSize + pkt_len, *len);
296 }
297 }
298}
299
300void AsyncTCPSocket::HandleIncomingConnection(AsyncSocket* socket) {
301 SignalNewConnection(this, new AsyncTCPSocket(socket, false));
302}
303
304} // namespace rtc