Upstream version 11.40.271.0
[platform/framework/web/crosswalk.git] / src / mojo / services / network / tcp_server_socket_impl.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 "mojo/services/network/tcp_server_socket_impl.h"
6
7 #include "mojo/services/network/net_adapters.h"
8 #include "mojo/services/network/net_address_type_converters.h"
9 #include "mojo/services/network/tcp_connected_socket_impl.h"
10 #include "net/base/net_errors.h"
11
12 namespace mojo {
13
14 TCPServerSocketImpl::TCPServerSocketImpl(scoped_ptr<net::TCPSocket> socket)
15     : socket_(socket.Pass()) {
16 }
17
18 TCPServerSocketImpl::~TCPServerSocketImpl() {
19 }
20
21 void TCPServerSocketImpl::Accept(
22     ScopedDataPipeConsumerHandle send_stream,
23     ScopedDataPipeProducerHandle receive_stream,
24     InterfaceRequest<TCPConnectedSocket> client_socket,
25     const AcceptCallback& callback) {
26   // One possible future enhancement would be to enqueue multiple Accept calls
27   // on this object. This would allow the client to accept some number of
28   // incoming connections rapidly without doing an IPC round-trip.
29   if (!pending_callback_.is_null()) {
30     // Already have a pending accept on this socket.
31     callback.Run(MakeNetworkError(net::ERR_UNEXPECTED), NetAddressPtr());
32     return;
33   }
34
35   int result = socket_->Accept(
36       &accepted_socket_, &accepted_address_,
37       base::Bind(&TCPServerSocketImpl::OnAcceptCompleted,
38                  base::Unretained(this)));
39   if (result == net::OK || result == net::ERR_IO_PENDING) {
40     pending_callback_ = callback;
41     pending_send_stream_ = send_stream.Pass();
42     pending_receive_stream_ = receive_stream.Pass();
43     pending_client_socket_ = client_socket.Pass();
44     if (result == net::OK)
45       OnAcceptCompleted(net::OK);
46   } else {
47     callback.Run(MakeNetworkError(result), NetAddressPtr());
48   }
49 }
50
51 void TCPServerSocketImpl::OnAcceptCompleted(int result) {
52   if (result != net::OK) {
53     pending_callback_.Run(MakeNetworkError(result), NetAddressPtr());
54     pending_send_stream_.reset();
55     pending_receive_stream_.reset();
56     pending_client_socket_ = InterfaceRequest<TCPConnectedSocket>();
57   } else {
58     BindToRequest(new TCPConnectedSocketImpl(
59         accepted_socket_.Pass(),
60         pending_send_stream_.Pass(),
61         pending_receive_stream_.Pass()), &pending_client_socket_);
62     pending_callback_.Run(MakeNetworkError(net::OK),
63                           NetAddress::From(accepted_address_));
64   }
65
66   pending_callback_ = AcceptCallback();
67 }
68
69 }  // namespace mojo