Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / remoting / client / plugin / pepper_packet_socket_factory.cc
1 // Copyright (c) 2012 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/client/plugin/pepper_packet_socket_factory.h"
6
7 #include "base/bind.h"
8 #include "base/logging.h"
9 #include "net/base/io_buffer.h"
10 #include "net/base/net_errors.h"
11 #include "ppapi/cpp/net_address.h"
12 #include "ppapi/cpp/udp_socket.h"
13 #include "ppapi/utility/completion_callback_factory.h"
14 #include "remoting/client/plugin/pepper_address_resolver.h"
15 #include "remoting/client/plugin/pepper_util.h"
16 #include "remoting/protocol/socket_util.h"
17 #include "third_party/webrtc/base/asyncpacketsocket.h"
18 #include "third_party/webrtc/base/nethelpers.h"
19
20 namespace remoting {
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 int PepperErrorToNetError(int error) {
34   switch (error) {
35     case PP_OK:
36       return net::OK;
37     case PP_OK_COMPLETIONPENDING:
38       return net::ERR_IO_PENDING;
39     case PP_ERROR_ABORTED:
40       return net::ERR_ABORTED;
41     case PP_ERROR_BADARGUMENT:
42       return net::ERR_INVALID_ARGUMENT;
43     case PP_ERROR_FILENOTFOUND:
44       return net::ERR_FILE_NOT_FOUND;
45     case PP_ERROR_TIMEDOUT:
46       return net::ERR_TIMED_OUT;
47     case PP_ERROR_FILETOOBIG:
48       return net::ERR_FILE_TOO_BIG;
49     case PP_ERROR_NOTSUPPORTED:
50       return net::ERR_NOT_IMPLEMENTED;
51     case PP_ERROR_NOMEMORY:
52       return net::ERR_OUT_OF_MEMORY;
53     case PP_ERROR_FILEEXISTS:
54       return net::ERR_FILE_EXISTS;
55     case PP_ERROR_NOSPACE:
56       return net::ERR_FILE_NO_SPACE;
57     case PP_ERROR_CONNECTION_CLOSED:
58       return net::ERR_CONNECTION_CLOSED;
59     case PP_ERROR_CONNECTION_RESET:
60       return net::ERR_CONNECTION_RESET;
61     case PP_ERROR_CONNECTION_REFUSED:
62       return net::ERR_CONNECTION_REFUSED;
63     case PP_ERROR_CONNECTION_ABORTED:
64       return net::ERR_CONNECTION_ABORTED;
65     case PP_ERROR_CONNECTION_FAILED:
66       return net::ERR_CONNECTION_FAILED;
67     case PP_ERROR_NAME_NOT_RESOLVED:
68       return net::ERR_NAME_NOT_RESOLVED;
69     case PP_ERROR_ADDRESS_INVALID:
70       return net::ERR_ADDRESS_INVALID;
71     case PP_ERROR_ADDRESS_UNREACHABLE:
72       return net::ERR_ADDRESS_UNREACHABLE;
73     case PP_ERROR_CONNECTION_TIMEDOUT:
74       return net::ERR_CONNECTION_TIMED_OUT;
75     case PP_ERROR_NOACCESS:
76       return net::ERR_NETWORK_ACCESS_DENIED;
77     case PP_ERROR_MESSAGE_TOO_BIG:
78       return net::ERR_MSG_TOO_BIG;
79     case PP_ERROR_ADDRESS_IN_USE:
80       return net::ERR_ADDRESS_IN_USE;
81     default:
82       return net::ERR_FAILED;
83   }
84 }
85
86 class UdpPacketSocket : public rtc::AsyncPacketSocket {
87  public:
88   explicit UdpPacketSocket(const pp::InstanceHandle& instance);
89   ~UdpPacketSocket() override;
90
91   // |min_port| and |max_port| are set to zero if the port number
92   // should be assigned by the OS.
93   bool Init(const rtc::SocketAddress& local_address,
94             uint16 min_port,
95             uint16 max_port);
96
97   // rtc::AsyncPacketSocket interface.
98   rtc::SocketAddress GetLocalAddress() const override;
99   rtc::SocketAddress GetRemoteAddress() const override;
100   int Send(const void* data,
101            size_t data_size,
102            const rtc::PacketOptions& options) override;
103   int SendTo(const void* data,
104              size_t data_size,
105              const rtc::SocketAddress& address,
106              const rtc::PacketOptions& options) override;
107   int Close() override;
108   State GetState() const override;
109   int GetOption(rtc::Socket::Option opt, int* value) override;
110   int SetOption(rtc::Socket::Option opt, int value) override;
111   int GetError() const override;
112   void SetError(int error) override;
113
114  private:
115   struct PendingPacket {
116     PendingPacket(const void* buffer,
117                   int buffer_size,
118                   const pp::NetAddress& address);
119
120     scoped_refptr<net::IOBufferWithSize> data;
121     pp::NetAddress address;
122     bool retried;
123   };
124
125   void OnBindCompleted(int error);
126
127   void DoSend();
128   void OnSendCompleted(int result);
129
130   void DoRead();
131   void OnReadCompleted(int result, pp::NetAddress address);
132   void HandleReadResult(int result, pp::NetAddress address);
133
134   pp::InstanceHandle instance_;
135
136   pp::UDPSocket socket_;
137
138   State state_;
139   int error_;
140
141   rtc::SocketAddress local_address_;
142
143   // Used to scan ports when necessary. Both values are set to 0 when
144   // the port number is assigned by OS.
145   uint16_t min_port_;
146   uint16_t max_port_;
147
148   std::vector<char> receive_buffer_;
149
150   bool send_pending_;
151   std::list<PendingPacket> send_queue_;
152   int send_queue_size_;
153
154   pp::CompletionCallbackFactory<UdpPacketSocket> callback_factory_;
155
156   DISALLOW_COPY_AND_ASSIGN(UdpPacketSocket);
157 };
158
159 UdpPacketSocket::PendingPacket::PendingPacket(
160     const void* buffer,
161     int buffer_size,
162     const pp::NetAddress& address)
163     : data(new net::IOBufferWithSize(buffer_size)),
164       address(address),
165       retried(true) {
166   memcpy(data->data(), buffer, buffer_size);
167 }
168
169 UdpPacketSocket::UdpPacketSocket(const pp::InstanceHandle& instance)
170     : instance_(instance),
171       socket_(instance),
172       state_(STATE_CLOSED),
173       error_(0),
174       min_port_(0),
175       max_port_(0),
176       send_pending_(false),
177       send_queue_size_(0),
178       callback_factory_(this) {
179 }
180
181 UdpPacketSocket::~UdpPacketSocket() {
182   Close();
183 }
184
185 bool UdpPacketSocket::Init(const rtc::SocketAddress& local_address,
186                            uint16 min_port,
187                            uint16 max_port) {
188   if (socket_.is_null()) {
189     return false;
190   }
191
192   local_address_ = local_address;
193   max_port_ = max_port;
194   min_port_ = min_port;
195
196   pp::NetAddress pp_local_address;
197   if (!SocketAddressToPpNetAddressWithPort(
198           instance_, local_address_, &pp_local_address, min_port_)) {
199     return false;
200   }
201
202   pp::CompletionCallback callback =
203       callback_factory_.NewCallback(&UdpPacketSocket::OnBindCompleted);
204   int result = socket_.Bind(pp_local_address, callback);
205   DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
206   state_ = STATE_BINDING;
207
208   return true;
209 }
210
211 void UdpPacketSocket::OnBindCompleted(int result) {
212   DCHECK(state_ == STATE_BINDING || state_ == STATE_CLOSED);
213
214   if (result == PP_ERROR_ABORTED) {
215     // Socket is being destroyed while binding.
216     return;
217   }
218
219   if (result == PP_OK) {
220     pp::NetAddress address = socket_.GetBoundAddress();
221     PpNetAddressToSocketAddress(address, &local_address_);
222     state_ = STATE_BOUND;
223     SignalAddressReady(this, local_address_);
224     DoRead();
225     return;
226   }
227
228   if (min_port_ < max_port_) {
229     // Try to bind to the next available port.
230     ++min_port_;
231     pp::NetAddress pp_local_address;
232     if (SocketAddressToPpNetAddressWithPort(
233             instance_, local_address_, &pp_local_address, min_port_)) {
234       pp::CompletionCallback callback =
235           callback_factory_.NewCallback(&UdpPacketSocket::OnBindCompleted);
236       int result = socket_.Bind(pp_local_address, callback);
237       DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
238     }
239   } else {
240     LOG(ERROR) << "Failed to bind UDP socket to " << local_address_.ToString()
241                << ", error: " << result;
242   }
243 }
244
245 rtc::SocketAddress UdpPacketSocket::GetLocalAddress() const {
246   DCHECK_EQ(state_, STATE_BOUND);
247   return local_address_;
248 }
249
250 rtc::SocketAddress UdpPacketSocket::GetRemoteAddress() const {
251   // UDP sockets are not connected - this method should never be called.
252   NOTREACHED();
253   return rtc::SocketAddress();
254 }
255
256 int UdpPacketSocket::Send(const void* data, size_t data_size,
257                           const rtc::PacketOptions& options) {
258   // UDP sockets are not connected - this method should never be called.
259   NOTREACHED();
260   return EWOULDBLOCK;
261 }
262
263 int UdpPacketSocket::SendTo(const void* data,
264                             size_t data_size,
265                             const rtc::SocketAddress& address,
266                             const rtc::PacketOptions& options) {
267   if (state_ != STATE_BOUND) {
268     // TODO(sergeyu): StunPort may try to send stun request before we
269     // are bound. Fix that problem and change this to DCHECK.
270     return EINVAL;
271   }
272
273   if (error_ != 0) {
274     return error_;
275   }
276
277   pp::NetAddress pp_address;
278   if (!SocketAddressToPpNetAddress(instance_, address, &pp_address)) {
279     return EINVAL;
280   }
281
282   if (send_queue_size_ >= kMaxSendBufferSize) {
283     return EWOULDBLOCK;
284   }
285
286   send_queue_.push_back(PendingPacket(data, data_size, pp_address));
287   send_queue_size_ += data_size;
288   DoSend();
289   return data_size;
290 }
291
292 int UdpPacketSocket::Close() {
293   state_ = STATE_CLOSED;
294   socket_.Close();
295   return 0;
296 }
297
298 rtc::AsyncPacketSocket::State UdpPacketSocket::GetState() const {
299   return state_;
300 }
301
302 int UdpPacketSocket::GetOption(rtc::Socket::Option opt, int* value) {
303   // Options are not supported for Pepper UDP sockets.
304   return -1;
305 }
306
307 int UdpPacketSocket::SetOption(rtc::Socket::Option opt, int value) {
308   // Options are not supported for Pepper UDP sockets.
309   return -1;
310 }
311
312 int UdpPacketSocket::GetError() const {
313   return error_;
314 }
315
316 void UdpPacketSocket::SetError(int error) {
317   error_ = error;
318 }
319
320 void UdpPacketSocket::DoSend() {
321   if (send_pending_ || send_queue_.empty())
322     return;
323
324   pp::CompletionCallback callback =
325       callback_factory_.NewCallback(&UdpPacketSocket::OnSendCompleted);
326   int result = socket_.SendTo(
327       send_queue_.front().data->data(), send_queue_.front().data->size(),
328       send_queue_.front().address,
329       callback);
330   DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
331   send_pending_ = true;
332 }
333
334 void UdpPacketSocket::OnSendCompleted(int result) {
335   if (result == PP_ERROR_ABORTED) {
336     // Send is aborted when the socket is being destroyed.
337     // |send_queue_| may be already destroyed, it's not safe to access
338     // it here.
339     return;
340   }
341
342   send_pending_ = false;
343
344   if (result < 0) {
345     int net_error = PepperErrorToNetError(result);
346     SocketErrorAction action = GetSocketErrorAction(net_error);
347     switch (action) {
348       case SOCKET_ERROR_ACTION_FAIL:
349         LOG(ERROR) << "Send failed on a UDP socket: " << result;
350         error_ = EINVAL;
351         return;
352
353       case SOCKET_ERROR_ACTION_RETRY:
354         // Retry resending only once.
355         if (!send_queue_.front().retried) {
356           send_queue_.front().retried = true;
357           DoSend();
358           return;
359         }
360         break;
361
362       case SOCKET_ERROR_ACTION_IGNORE:
363         break;
364     }
365   }
366
367   send_queue_size_ -= send_queue_.front().data->size();
368   send_queue_.pop_front();
369   DoSend();
370 }
371
372 void UdpPacketSocket::DoRead() {
373   receive_buffer_.resize(kReceiveBufferSize);
374   pp::CompletionCallbackWithOutput<pp::NetAddress> callback =
375       callback_factory_.NewCallbackWithOutput(
376           &UdpPacketSocket::OnReadCompleted);
377   int result =
378       socket_.RecvFrom(&receive_buffer_[0], receive_buffer_.size(), callback);
379   DCHECK_EQ(result, PP_OK_COMPLETIONPENDING);
380 }
381
382 void UdpPacketSocket::OnReadCompleted(int result, pp::NetAddress address) {
383   HandleReadResult(result, address);
384   if (result > 0) {
385     DoRead();
386   }
387 }
388
389 void UdpPacketSocket::HandleReadResult(int result, pp::NetAddress address) {
390   if (result > 0) {
391     rtc::SocketAddress socket_address;
392     PpNetAddressToSocketAddress(address, &socket_address);
393     SignalReadPacket(this, &receive_buffer_[0], result, socket_address,
394                      rtc::CreatePacketTime(0));
395   } else if (result != PP_ERROR_ABORTED) {
396     LOG(ERROR) << "Received error when reading from UDP socket: " << result;
397   }
398 }
399
400 }  // namespace
401
402 PepperPacketSocketFactory::PepperPacketSocketFactory(
403     const pp::InstanceHandle& instance)
404     : pp_instance_(instance) {
405 }
406
407 PepperPacketSocketFactory::~PepperPacketSocketFactory() {
408 }
409
410 rtc::AsyncPacketSocket* PepperPacketSocketFactory::CreateUdpSocket(
411       const rtc::SocketAddress& local_address,
412       uint16 min_port,
413       uint16 max_port) {
414   scoped_ptr<UdpPacketSocket> result(new UdpPacketSocket(pp_instance_));
415   if (!result->Init(local_address, min_port, max_port))
416     return NULL;
417   return result.release();
418 }
419
420 rtc::AsyncPacketSocket* PepperPacketSocketFactory::CreateServerTcpSocket(
421     const rtc::SocketAddress& local_address,
422     uint16 min_port,
423     uint16 max_port,
424     int opts) {
425   // We don't use TCP sockets for remoting connections.
426   NOTREACHED();
427   return NULL;
428 }
429
430 rtc::AsyncPacketSocket* PepperPacketSocketFactory::CreateClientTcpSocket(
431       const rtc::SocketAddress& local_address,
432       const rtc::SocketAddress& remote_address,
433       const rtc::ProxyInfo& proxy_info,
434       const std::string& user_agent,
435       int opts) {
436   // We don't use TCP sockets for remoting connections.
437   NOTREACHED();
438   return NULL;
439 }
440
441 rtc::AsyncResolverInterface*
442 PepperPacketSocketFactory::CreateAsyncResolver() {
443   return new PepperAddressResolver(pp_instance_);
444 }
445
446 }  // namespace remoting