1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "remoting/protocol/chromium_socket_factory.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "jingle/glue/utils.h"
11 #include "net/base/io_buffer.h"
12 #include "net/base/ip_endpoint.h"
13 #include "net/base/net_errors.h"
14 #include "net/udp/udp_server_socket.h"
15 #include "remoting/protocol/socket_util.h"
16 #include "third_party/webrtc/base/asyncpacketsocket.h"
17 #include "third_party/webrtc/base/nethelpers.h"
24 // Size of the buffer to allocate for RecvFrom().
25 const int kReceiveBufferSize = 65536;
27 // Maximum amount of data in the send buffers. This is necessary to
28 // prevent out-of-memory crashes if the caller sends data faster than
29 // Pepper's UDP API can handle it. This maximum should never be
30 // reached under normal conditions.
31 const int kMaxSendBufferSize = 256 * 1024;
33 class UdpPacketSocket : public rtc::AsyncPacketSocket {
36 ~UdpPacketSocket() override;
38 bool Init(const rtc::SocketAddress& local_address,
39 uint16 min_port, uint16 max_port);
41 // rtc::AsyncPacketSocket interface.
42 rtc::SocketAddress GetLocalAddress() const override;
43 rtc::SocketAddress GetRemoteAddress() const override;
44 int Send(const void* data,
46 const rtc::PacketOptions& options) override;
47 int SendTo(const void* data,
49 const rtc::SocketAddress& address,
50 const rtc::PacketOptions& options) override;
52 State GetState() const override;
53 int GetOption(rtc::Socket::Option option, int* value) override;
54 int SetOption(rtc::Socket::Option option, int value) override;
55 int GetError() const override;
56 void SetError(int error) override;
59 struct PendingPacket {
60 PendingPacket(const void* buffer,
62 const net::IPEndPoint& address);
64 scoped_refptr<net::IOBufferWithSize> data;
65 net::IPEndPoint address;
69 void OnBindCompleted(int error);
72 void OnSendCompleted(int result);
75 void OnReadCompleted(int result);
76 void HandleReadResult(int result);
78 scoped_ptr<net::UDPServerSocket> socket_;
83 rtc::SocketAddress local_address_;
85 // Receive buffer and address are populated by asynchronous reads.
86 scoped_refptr<net::IOBuffer> receive_buffer_;
87 net::IPEndPoint receive_address_;
90 std::list<PendingPacket> send_queue_;
93 DISALLOW_COPY_AND_ASSIGN(UdpPacketSocket);
96 UdpPacketSocket::PendingPacket::PendingPacket(
99 const net::IPEndPoint& address)
100 : data(new net::IOBufferWithSize(buffer_size)),
103 memcpy(data->data(), buffer, buffer_size);
106 UdpPacketSocket::UdpPacketSocket()
107 : state_(STATE_CLOSED),
109 send_pending_(false),
110 send_queue_size_(0) {
113 UdpPacketSocket::~UdpPacketSocket() {
117 bool UdpPacketSocket::Init(const rtc::SocketAddress& local_address,
118 uint16 min_port, uint16 max_port) {
119 net::IPEndPoint local_endpoint;
120 if (!jingle_glue::SocketAddressToIPEndPoint(
121 local_address, &local_endpoint)) {
125 for (uint16 port = min_port; port <= max_port; ++port) {
126 socket_.reset(new net::UDPServerSocket(NULL, net::NetLog::Source()));
127 int result = socket_->Listen(
128 net::IPEndPoint(local_endpoint.address(), port));
129 if (result == net::OK) {
136 if (!socket_.get()) {
137 // Failed to bind the socket.
141 if (socket_->GetLocalAddress(&local_endpoint) != net::OK ||
142 !jingle_glue::IPEndPointToSocketAddress(local_endpoint,
147 state_ = STATE_BOUND;
153 rtc::SocketAddress UdpPacketSocket::GetLocalAddress() const {
154 DCHECK_EQ(state_, STATE_BOUND);
155 return local_address_;
158 rtc::SocketAddress UdpPacketSocket::GetRemoteAddress() const {
159 // UDP sockets are not connected - this method should never be called.
161 return rtc::SocketAddress();
164 int UdpPacketSocket::Send(const void* data, size_t data_size,
165 const rtc::PacketOptions& options) {
166 // UDP sockets are not connected - this method should never be called.
171 int UdpPacketSocket::SendTo(const void* data, size_t data_size,
172 const rtc::SocketAddress& address,
173 const rtc::PacketOptions& options) {
174 if (state_ != STATE_BOUND) {
183 net::IPEndPoint endpoint;
184 if (!jingle_glue::SocketAddressToIPEndPoint(address, &endpoint)) {
188 if (send_queue_size_ >= kMaxSendBufferSize) {
192 send_queue_.push_back(PendingPacket(data, data_size, endpoint));
193 send_queue_size_ += data_size;
199 int UdpPacketSocket::Close() {
200 state_ = STATE_CLOSED;
205 rtc::AsyncPacketSocket::State UdpPacketSocket::GetState() const {
209 int UdpPacketSocket::GetOption(rtc::Socket::Option option, int* value) {
210 // This method is never called by libjingle.
215 int UdpPacketSocket::SetOption(rtc::Socket::Option option, int value) {
216 if (state_ != STATE_BOUND) {
222 case rtc::Socket::OPT_DONTFRAGMENT:
226 case rtc::Socket::OPT_RCVBUF: {
227 int net_error = socket_->SetReceiveBufferSize(value);
228 return (net_error == net::OK) ? 0 : -1;
231 case rtc::Socket::OPT_SNDBUF: {
232 int net_error = socket_->SetSendBufferSize(value);
233 return (net_error == net::OK) ? 0 : -1;
236 case rtc::Socket::OPT_NODELAY:
237 // OPT_NODELAY is only for TCP sockets.
241 case rtc::Socket::OPT_IPV6_V6ONLY:
245 case rtc::Socket::OPT_DSCP:
249 case rtc::Socket::OPT_RTP_SENDTIME_EXTN_ID:
258 int UdpPacketSocket::GetError() const {
262 void UdpPacketSocket::SetError(int error) {
266 void UdpPacketSocket::DoSend() {
267 if (send_pending_ || send_queue_.empty())
270 PendingPacket& packet = send_queue_.front();
271 int result = socket_->SendTo(
275 base::Bind(&UdpPacketSocket::OnSendCompleted, base::Unretained(this)));
276 if (result == net::ERR_IO_PENDING) {
277 send_pending_ = true;
279 OnSendCompleted(result);
283 void UdpPacketSocket::OnSendCompleted(int result) {
284 send_pending_ = false;
287 SocketErrorAction action = GetSocketErrorAction(result);
289 case SOCKET_ERROR_ACTION_FAIL:
290 LOG(ERROR) << "Send failed on a UDP socket: " << result;
294 case SOCKET_ERROR_ACTION_RETRY:
295 // Retry resending only once.
296 if (!send_queue_.front().retried) {
297 send_queue_.front().retried = true;
303 case SOCKET_ERROR_ACTION_IGNORE:
308 // Don't need to worry about partial sends because this is a datagram
310 send_queue_size_ -= send_queue_.front().data->size();
311 send_queue_.pop_front();
315 void UdpPacketSocket::DoRead() {
317 while (result >= 0) {
318 receive_buffer_ = new net::IOBuffer(kReceiveBufferSize);
319 result = socket_->RecvFrom(
320 receive_buffer_.get(),
323 base::Bind(&UdpPacketSocket::OnReadCompleted, base::Unretained(this)));
324 HandleReadResult(result);
328 void UdpPacketSocket::OnReadCompleted(int result) {
329 HandleReadResult(result);
335 void UdpPacketSocket::HandleReadResult(int result) {
336 if (result == net::ERR_IO_PENDING) {
341 rtc::SocketAddress address;
342 if (!jingle_glue::IPEndPointToSocketAddress(receive_address_, &address)) {
344 LOG(ERROR) << "Failed to convert address received from RecvFrom().";
347 SignalReadPacket(this, receive_buffer_->data(), result, address,
348 rtc::CreatePacketTime(0));
350 LOG(ERROR) << "Received error when reading from UDP socket: " << result;
356 ChromiumPacketSocketFactory::ChromiumPacketSocketFactory() {
359 ChromiumPacketSocketFactory::~ChromiumPacketSocketFactory() {
362 rtc::AsyncPacketSocket* ChromiumPacketSocketFactory::CreateUdpSocket(
363 const rtc::SocketAddress& local_address,
364 uint16 min_port, uint16 max_port) {
365 scoped_ptr<UdpPacketSocket> result(new UdpPacketSocket());
366 if (!result->Init(local_address, min_port, max_port))
368 return result.release();
371 rtc::AsyncPacketSocket*
372 ChromiumPacketSocketFactory::CreateServerTcpSocket(
373 const rtc::SocketAddress& local_address,
374 uint16 min_port, uint16 max_port,
376 // We don't use TCP sockets for remoting connections.
381 rtc::AsyncPacketSocket*
382 ChromiumPacketSocketFactory::CreateClientTcpSocket(
383 const rtc::SocketAddress& local_address,
384 const rtc::SocketAddress& remote_address,
385 const rtc::ProxyInfo& proxy_info,
386 const std::string& user_agent,
388 // We don't use TCP sockets for remoting connections.
393 rtc::AsyncResolverInterface*
394 ChromiumPacketSocketFactory::CreateAsyncResolver() {
395 return new rtc::AsyncResolver();
398 } // namespace protocol
399 } // namespace remoting