Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / remoting / protocol / chromium_socket_factory.cc
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.
4
5 #include "remoting/protocol/chromium_socket_factory.h"
6
7 #include "base/bind.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"
18
19 namespace remoting {
20 namespace protocol {
21
22 namespace {
23
24 // Size of the buffer to allocate for RecvFrom().
25 const int kReceiveBufferSize = 65536;
26
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;
32
33 class UdpPacketSocket : public rtc::AsyncPacketSocket {
34  public:
35   UdpPacketSocket();
36   ~UdpPacketSocket() override;
37
38   bool Init(const rtc::SocketAddress& local_address,
39             uint16 min_port, uint16 max_port);
40
41   // rtc::AsyncPacketSocket interface.
42   rtc::SocketAddress GetLocalAddress() const override;
43   rtc::SocketAddress GetRemoteAddress() const override;
44   int Send(const void* data,
45            size_t data_size,
46            const rtc::PacketOptions& options) override;
47   int SendTo(const void* data,
48              size_t data_size,
49              const rtc::SocketAddress& address,
50              const rtc::PacketOptions& options) override;
51   int Close() 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;
57
58  private:
59   struct PendingPacket {
60     PendingPacket(const void* buffer,
61                   int buffer_size,
62                   const net::IPEndPoint& address);
63
64     scoped_refptr<net::IOBufferWithSize> data;
65     net::IPEndPoint address;
66     bool retried;
67   };
68
69   void OnBindCompleted(int error);
70
71   void DoSend();
72   void OnSendCompleted(int result);
73
74   void DoRead();
75   void OnReadCompleted(int result);
76   void HandleReadResult(int result);
77
78   scoped_ptr<net::UDPServerSocket> socket_;
79
80   State state_;
81   int error_;
82
83   rtc::SocketAddress local_address_;
84
85   // Receive buffer and address are populated by asynchronous reads.
86   scoped_refptr<net::IOBuffer> receive_buffer_;
87   net::IPEndPoint receive_address_;
88
89   bool send_pending_;
90   std::list<PendingPacket> send_queue_;
91   int send_queue_size_;
92
93   DISALLOW_COPY_AND_ASSIGN(UdpPacketSocket);
94 };
95
96 UdpPacketSocket::PendingPacket::PendingPacket(
97     const void* buffer,
98     int buffer_size,
99     const net::IPEndPoint& address)
100     : data(new net::IOBufferWithSize(buffer_size)),
101       address(address),
102       retried(false) {
103   memcpy(data->data(), buffer, buffer_size);
104 }
105
106 UdpPacketSocket::UdpPacketSocket()
107     : state_(STATE_CLOSED),
108       error_(0),
109       send_pending_(false),
110       send_queue_size_(0) {
111 }
112
113 UdpPacketSocket::~UdpPacketSocket() {
114   Close();
115 }
116
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)) {
122     return false;
123   }
124
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) {
130       break;
131     } else {
132       socket_.reset();
133     }
134   }
135
136   if (!socket_.get()) {
137     // Failed to bind the socket.
138     return false;
139   }
140
141   if (socket_->GetLocalAddress(&local_endpoint) != net::OK ||
142       !jingle_glue::IPEndPointToSocketAddress(local_endpoint,
143                                               &local_address_)) {
144     return false;
145   }
146
147   state_ = STATE_BOUND;
148   DoRead();
149
150   return true;
151 }
152
153 rtc::SocketAddress UdpPacketSocket::GetLocalAddress() const {
154   DCHECK_EQ(state_, STATE_BOUND);
155   return local_address_;
156 }
157
158 rtc::SocketAddress UdpPacketSocket::GetRemoteAddress() const {
159   // UDP sockets are not connected - this method should never be called.
160   NOTREACHED();
161   return rtc::SocketAddress();
162 }
163
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.
167   NOTREACHED();
168   return EWOULDBLOCK;
169 }
170
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) {
175     NOTREACHED();
176     return EINVAL;
177   }
178
179   if (error_ != 0) {
180     return error_;
181   }
182
183   net::IPEndPoint endpoint;
184   if (!jingle_glue::SocketAddressToIPEndPoint(address, &endpoint)) {
185     return EINVAL;
186   }
187
188   if (send_queue_size_ >= kMaxSendBufferSize) {
189     return EWOULDBLOCK;
190   }
191
192   send_queue_.push_back(PendingPacket(data, data_size, endpoint));
193   send_queue_size_ += data_size;
194
195   DoSend();
196   return data_size;
197 }
198
199 int UdpPacketSocket::Close() {
200   state_ = STATE_CLOSED;
201   socket_.reset();
202   return 0;
203 }
204
205 rtc::AsyncPacketSocket::State UdpPacketSocket::GetState() const {
206   return state_;
207 }
208
209 int UdpPacketSocket::GetOption(rtc::Socket::Option option, int* value) {
210   // This method is never called by libjingle.
211   NOTIMPLEMENTED();
212   return -1;
213 }
214
215 int UdpPacketSocket::SetOption(rtc::Socket::Option option, int value) {
216   if (state_ != STATE_BOUND) {
217     NOTREACHED();
218     return EINVAL;
219   }
220
221   switch (option) {
222     case rtc::Socket::OPT_DONTFRAGMENT:
223       NOTIMPLEMENTED();
224       return -1;
225
226     case rtc::Socket::OPT_RCVBUF: {
227       int net_error = socket_->SetReceiveBufferSize(value);
228       return (net_error == net::OK) ? 0 : -1;
229     }
230
231     case rtc::Socket::OPT_SNDBUF: {
232       int net_error = socket_->SetSendBufferSize(value);
233       return (net_error == net::OK) ? 0 : -1;
234     }
235
236     case rtc::Socket::OPT_NODELAY:
237       // OPT_NODELAY is only for TCP sockets.
238       NOTREACHED();
239       return -1;
240
241     case rtc::Socket::OPT_IPV6_V6ONLY:
242       NOTIMPLEMENTED();
243       return -1;
244
245     case rtc::Socket::OPT_DSCP:
246       NOTIMPLEMENTED();
247       return -1;
248
249     case rtc::Socket::OPT_RTP_SENDTIME_EXTN_ID:
250       NOTIMPLEMENTED();
251       return -1;
252   }
253
254   NOTREACHED();
255   return -1;
256 }
257
258 int UdpPacketSocket::GetError() const {
259   return error_;
260 }
261
262 void UdpPacketSocket::SetError(int error) {
263   error_ = error;
264 }
265
266 void UdpPacketSocket::DoSend() {
267   if (send_pending_ || send_queue_.empty())
268     return;
269
270   PendingPacket& packet = send_queue_.front();
271   int result = socket_->SendTo(
272       packet.data.get(),
273       packet.data->size(),
274       packet.address,
275       base::Bind(&UdpPacketSocket::OnSendCompleted, base::Unretained(this)));
276   if (result == net::ERR_IO_PENDING) {
277     send_pending_ = true;
278   } else {
279     OnSendCompleted(result);
280   }
281 }
282
283 void UdpPacketSocket::OnSendCompleted(int result) {
284   send_pending_ = false;
285
286   if (result < 0) {
287     SocketErrorAction action = GetSocketErrorAction(result);
288     switch (action) {
289       case SOCKET_ERROR_ACTION_FAIL:
290         LOG(ERROR) << "Send failed on a UDP socket: " << result;
291         error_ = EINVAL;
292         return;
293
294       case SOCKET_ERROR_ACTION_RETRY:
295         // Retry resending only once.
296         if (!send_queue_.front().retried) {
297           send_queue_.front().retried = true;
298           DoSend();
299           return;
300         }
301         break;
302
303       case SOCKET_ERROR_ACTION_IGNORE:
304         break;
305     }
306   }
307
308   // Don't need to worry about partial sends because this is a datagram
309   // socket.
310   send_queue_size_ -= send_queue_.front().data->size();
311   send_queue_.pop_front();
312   DoSend();
313 }
314
315 void UdpPacketSocket::DoRead() {
316   int result = 0;
317   while (result >= 0) {
318     receive_buffer_ = new net::IOBuffer(kReceiveBufferSize);
319     result = socket_->RecvFrom(
320         receive_buffer_.get(),
321         kReceiveBufferSize,
322         &receive_address_,
323         base::Bind(&UdpPacketSocket::OnReadCompleted, base::Unretained(this)));
324     HandleReadResult(result);
325   }
326 }
327
328 void UdpPacketSocket::OnReadCompleted(int result) {
329   HandleReadResult(result);
330   if (result >= 0) {
331     DoRead();
332   }
333 }
334
335 void UdpPacketSocket::HandleReadResult(int result) {
336   if (result == net::ERR_IO_PENDING) {
337     return;
338   }
339
340   if (result > 0) {
341     rtc::SocketAddress address;
342     if (!jingle_glue::IPEndPointToSocketAddress(receive_address_, &address)) {
343       NOTREACHED();
344       LOG(ERROR) << "Failed to convert address received from RecvFrom().";
345       return;
346     }
347     SignalReadPacket(this, receive_buffer_->data(), result, address,
348                      rtc::CreatePacketTime(0));
349   } else {
350     LOG(ERROR) << "Received error when reading from UDP socket: " << result;
351   }
352 }
353
354 }  // namespace
355
356 ChromiumPacketSocketFactory::ChromiumPacketSocketFactory() {
357 }
358
359 ChromiumPacketSocketFactory::~ChromiumPacketSocketFactory() {
360 }
361
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))
367     return NULL;
368   return result.release();
369 }
370
371 rtc::AsyncPacketSocket*
372 ChromiumPacketSocketFactory::CreateServerTcpSocket(
373     const rtc::SocketAddress& local_address,
374     uint16 min_port, uint16 max_port,
375     int opts) {
376   // We don't use TCP sockets for remoting connections.
377   NOTIMPLEMENTED();
378   return NULL;
379 }
380
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,
387       int opts) {
388   // We don't use TCP sockets for remoting connections.
389   NOTREACHED();
390   return NULL;
391 }
392
393 rtc::AsyncResolverInterface*
394 ChromiumPacketSocketFactory::CreateAsyncResolver() {
395   return new rtc::AsyncResolver();
396 }
397
398 }  // namespace protocol
399 }  // namespace remoting