Refactor tcp socket.

This is a pre-requisite for http server refactoring,
https://codereview.chromium.org/296053012/.

1) Introduce SocketLibevent for tcp and unix domain sockets.
2) TCPSocketLibevent utilizes SocketLibevent.
3) For backward compatibility, TCPSocketLibevent::AdoptConnectedSocket()
   allows the empty address.

BUG=371906

Review URL: https://codereview.chromium.org/348803003

git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282121 0039d316-1c4b-4281-b951-d872f2087c98
parent 273ae5ab
......@@ -7,6 +7,7 @@
#include <queue>
#include <string>
#include "base/location.h"
#include "base/logging.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/ref_counted.h"
......
......@@ -196,14 +196,10 @@ int TCPSocket::Listen(const std::string& address,
DCHECK(!socket_.get());
socket_mode_ = SERVER;
scoped_ptr<net::IPEndPoint> bind_address(new net::IPEndPoint());
if (!StringAndPortToIPEndPoint(address, port, bind_address.get()))
return net::ERR_INVALID_ARGUMENT;
if (!server_socket_.get()) {
server_socket_.reset(new net::TCPServerSocket(NULL, net::NetLog::Source()));
}
int result = server_socket_->Listen(*bind_address, backlog);
int result = server_socket_->ListenWithAddressAndPort(address, port, backlog);
if (result)
*error_msg = kSocketListenError;
return result;
......
......@@ -435,6 +435,8 @@ component("net") {
if (is_win) {
sources -= [
"http/http_auth_handler_ntlm_portable.cc",
"socket/socket_libevent.cc",
"socket/socket_libevent.h",
"socket/tcp_socket_libevent.cc",
"socket/tcp_socket_libevent.h",
"udp/udp_socket_libevent.cc",
......
......@@ -5,6 +5,7 @@
#include "net/base/net_util.h"
#include <errno.h>
#include <string.h>
#include <algorithm>
#include <iterator>
......@@ -501,6 +502,18 @@ bool IsIPAddressReserved(const IPAddressNumber& host_addr) {
return false;
}
SockaddrStorage::SockaddrStorage(const SockaddrStorage& other)
: addr_len(other.addr_len),
addr(reinterpret_cast<struct sockaddr*>(&addr_storage)) {
memcpy(addr, other.addr, addr_len);
}
void SockaddrStorage::operator=(const SockaddrStorage& other) {
addr_len = other.addr_len;
// addr is already set to &this->addr_storage by default ctor.
memcpy(addr, other.addr, addr_len);
}
// Extracts the address and port portions of a sockaddr.
bool GetIPAddressFromSockAddr(const struct sockaddr* sock_addr,
socklen_t sock_addr_len,
......
......@@ -114,6 +114,9 @@ NET_EXPORT bool IsIPAddressReserved(const IPAddressNumber& address);
struct SockaddrStorage {
SockaddrStorage() : addr_len(sizeof(addr_storage)),
addr(reinterpret_cast<struct sockaddr*>(&addr_storage)) {}
SockaddrStorage(const SockaddrStorage& other);
void operator=(const SockaddrStorage& other);
struct sockaddr_storage addr_storage;
socklen_t addr_len;
struct sockaddr* const addr;
......
......@@ -392,6 +392,8 @@
[ 'OS == "win"', {
'sources!': [
'http/http_auth_handler_ntlm_portable.cc',
'socket/socket_libevent.cc',
'socket/socket_libevent.h',
'socket/tcp_socket_libevent.cc',
'socket/tcp_socket_libevent.h',
'udp/udp_socket_libevent.cc',
......
......@@ -947,9 +947,12 @@
'socket/client_socket_pool_manager_impl.h',
'socket/nss_ssl_util.cc',
'socket/nss_ssl_util.h',
'socket/server_socket.cc',
'socket/server_socket.h',
'socket/socket_descriptor.cc',
'socket/socket_descriptor.h',
'socket/socket_libevent.cc',
'socket/socket_libevent.h',
'socket/socket_net_log_params.cc',
'socket/socket_net_log_params.h',
'socket/socks5_client_socket.cc',
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/socket/server_socket.h"
#include "net/base/ip_endpoint.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
namespace net {
ServerSocket::ServerSocket() {
}
ServerSocket::~ServerSocket() {
}
int ServerSocket::ListenWithAddressAndPort(const std::string& address_string,
int port,
int backlog) {
IPAddressNumber address_number;
if (!ParseIPLiteralToNumber(address_string, &address_number)) {
return ERR_ADDRESS_INVALID;
}
return Listen(IPEndPoint(address_number, port), backlog);
}
} // namespace net
......@@ -5,6 +5,8 @@
#ifndef NET_SOCKET_SERVER_SOCKET_H_
#define NET_SOCKET_SERVER_SOCKET_H_
#include <string>
#include "base/memory/scoped_ptr.h"
#include "net/base/completion_callback.h"
#include "net/base/net_export.h"
......@@ -16,17 +18,25 @@ class StreamSocket;
class NET_EXPORT ServerSocket {
public:
ServerSocket() { }
virtual ~ServerSocket() { }
ServerSocket();
virtual ~ServerSocket();
// Bind the socket and start listening. Destroy the socket to stop
// Binds the socket and starts listening. Destroy the socket to stop
// listening.
virtual int Listen(const net::IPEndPoint& address, int backlog) = 0;
// Binds the socket with address and port, and starts listening. It expects
// a valid IPv4 or IPv6 address. Otherwise, it returns ERR_ADDRESS_INVALID.
// Subclasses may override this function if |address_string| is in a different
// format, for example, unix domain socket path.
virtual int ListenWithAddressAndPort(const std::string& address_string,
int port,
int backlog);
// Gets current address the socket is bound to.
virtual int GetLocalAddress(IPEndPoint* address) const = 0;
// Accept connection. Callback is called when new connection is
// Accepts connection. Callback is called when new connection is
// accepted.
virtual int Accept(scoped_ptr<StreamSocket>* socket,
const CompletionCallback& callback) = 0;
......
This diff is collapsed.
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_SOCKET_SOCKET_LIBEVENT_H_
#define NET_SOCKET_SOCKET_LIBEVENT_H_
#include "base/basictypes.h"
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/thread_checker.h"
#include "net/base/completion_callback.h"
#include "net/base/net_util.h"
#include "net/socket/socket_descriptor.h"
namespace net {
class IOBuffer;
class IPEndPoint;
// Socket class to provide asynchronous read/write operations on top of the
// posix socket api. It supports AF_INET, AF_INET6, and AF_UNIX addresses.
class SocketLibevent : public base::MessageLoopForIO::Watcher {
public:
SocketLibevent();
virtual ~SocketLibevent();
// Opens a socket and returns net::OK if |address_family| is AF_INET, AF_INET6
// or AF_UNIX. Otherwise, it does DCHECK() and returns a net error.
int Open(int address_family);
// Takes ownership of |socket|.
int AdoptConnectedSocket(SocketDescriptor socket,
const SockaddrStorage& peer_address);
int Bind(const SockaddrStorage& address);
int Listen(int backlog);
int Accept(scoped_ptr<SocketLibevent>* socket,
const CompletionCallback& callback);
// Connects socket. On non-ERR_IO_PENDING error, sets errno and returns a net
// error code. On ERR_IO_PENDING, |callback| is called with a net error code,
// not errno, though errno is set if connect event happens with error.
// TODO(byungchul): Need more robust way to pass system errno.
int Connect(const SockaddrStorage& address,
const CompletionCallback& callback);
bool IsConnected() const;
bool IsConnectedAndIdle() const;
// Multiple outstanding requests of the same type are not supported.
// Full duplex mode (reading and writing at the same time) is supported.
// On error which is not ERR_IO_PENDING, sets errno and returns a net error
// code. On ERR_IO_PENDING, |callback| is called with a net error code, not
// errno, though errno is set if read or write events happen with error.
// TODO(byungchul): Need more robust way to pass system errno.
int Read(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
int Write(IOBuffer* buf, int buf_len, const CompletionCallback& callback);
// Waits for next write event. This is called by TCPsocketLibevent for TCP
// fastopen after sending first data. Returns ERR_IO_PENDING if it starts
// waiting for write event successfully. Otherwise, returns a net error code.
// It must not be called after Write() because Write() calls it internally.
int WaitForWrite(IOBuffer* buf, int buf_len,
const CompletionCallback& callback);
int GetLocalAddress(SockaddrStorage* address) const;
int GetPeerAddress(SockaddrStorage* address) const;
void SetPeerAddress(const SockaddrStorage& address);
// Returns true if peer address has been set regardless of socket state.
bool HasPeerAddress() const;
void Close();
SocketDescriptor socket_fd() const { return socket_fd_; }
private:
// base::MessageLoopForIO::Watcher methods.
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
int DoAccept(scoped_ptr<SocketLibevent>* socket);
void AcceptCompleted();
int DoConnect();
void ConnectCompleted();
int DoRead(IOBuffer* buf, int buf_len);
void ReadCompleted();
int DoWrite(IOBuffer* buf, int buf_len);
void WriteCompleted();
SocketDescriptor socket_fd_;
base::MessageLoopForIO::FileDescriptorWatcher accept_socket_watcher_;
scoped_ptr<SocketLibevent>* accept_socket_;
CompletionCallback accept_callback_;
base::MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_;
scoped_refptr<IOBuffer> read_buf_;
int read_buf_len_;
// External callback; called when read is complete.
CompletionCallback read_callback_;
base::MessageLoopForIO::FileDescriptorWatcher write_socket_watcher_;
scoped_refptr<IOBuffer> write_buf_;
int write_buf_len_;
// External callback; called when write or connect is complete.
CompletionCallback write_callback_;
// A connect operation is pending. In this case, |write_callback_| needs to be
// called when connect is complete.
bool waiting_connect_;
scoped_ptr<SockaddrStorage> peer_address_;
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(SocketLibevent);
};
} // namespace net
#endif // NET_SOCKET_SOCKET_LIBEVENT_H_
......@@ -6,6 +6,7 @@
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/location.h"
#include "base/memory/ref_counted.h"
#include "base/threading/worker_pool.h"
......
This diff is collapsed.
......@@ -8,30 +8,27 @@
#include "base/basictypes.h"
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/threading/non_thread_safe.h"
#include "net/base/address_family.h"
#include "net/base/completion_callback.h"
#include "net/base/net_export.h"
#include "net/base/net_log.h"
#include "net/socket/socket_descriptor.h"
namespace net {
class AddressList;
class IOBuffer;
class IPEndPoint;
class SocketLibevent;
class NET_EXPORT TCPSocketLibevent : public base::NonThreadSafe {
class NET_EXPORT TCPSocketLibevent {
public:
TCPSocketLibevent(NetLog* net_log, const NetLog::Source& source);
virtual ~TCPSocketLibevent();
int Open(AddressFamily family);
// Takes ownership of |socket|.
int AdoptConnectedSocket(int socket, const IPEndPoint& peer_address);
// Takes ownership of |socket_fd|.
int AdoptConnectedSocket(int socket_fd, const IPEndPoint& peer_address);
int Bind(const IPEndPoint& address);
......@@ -69,7 +66,7 @@ class NET_EXPORT TCPSocketLibevent : public base::NonThreadSafe {
void Close();
bool UsingTCPFastOpen() const;
bool IsValid() const { return socket_ != kInvalidSocket; }
bool IsValid() const;
// Marks the start/end of a series of connect attempts for logging purpose.
//
......@@ -136,76 +133,39 @@ class NET_EXPORT TCPSocketLibevent : public base::NonThreadSafe {
FAST_OPEN_MAX_VALUE
};
// Watcher simply forwards notifications to Closure objects set via the
// constructor.
class Watcher: public base::MessageLoopForIO::Watcher {
public:
Watcher(const base::Closure& read_ready_callback,
const base::Closure& write_ready_callback);
virtual ~Watcher();
// base::MessageLoopForIO::Watcher methods.
virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE;
virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE;
private:
base::Closure read_ready_callback_;
base::Closure write_ready_callback_;
DISALLOW_COPY_AND_ASSIGN(Watcher);
};
int AcceptInternal(scoped_ptr<TCPSocketLibevent>* socket,
void AcceptCompleted(scoped_ptr<TCPSocketLibevent>* tcp_socket,
IPEndPoint* address,
const CompletionCallback& callback,
int rv);
int HandleAcceptCompleted(scoped_ptr<TCPSocketLibevent>* tcp_socket,
IPEndPoint* address,
int rv);
int BuildTcpSocketLibevent(scoped_ptr<TCPSocketLibevent>* tcp_socket,
IPEndPoint* address);
int DoConnect();
void DoConnectComplete(int result);
void LogConnectBegin(const AddressList& addresses);
void LogConnectEnd(int net_error);
void DidCompleteRead();
void DidCompleteWrite();
void DidCompleteConnect();
void DidCompleteConnectOrWrite();
void DidCompleteAccept();
// Internal function to write to a socket. Returns an OS error.
int InternalWrite(IOBuffer* buf, int buf_len);
void ConnectCompleted(const CompletionCallback& callback, int rv) const;
int HandleConnectCompleted(int rv) const;
void LogConnectBegin(const AddressList& addresses) const;
void LogConnectEnd(int net_error) const;
void ReadCompleted(IOBuffer* buf,
const CompletionCallback& callback,
int rv);
int HandleReadCompleted(IOBuffer* buf, int rv);
void WriteCompleted(IOBuffer* buf,
const CompletionCallback& callback,
int rv) const;
int HandleWriteCompleted(IOBuffer* buf, int rv) const;
int TcpFastOpenWrite(IOBuffer* buf,
int buf_len,
const CompletionCallback& callback);
// Called when the socket is known to be in a connected state.
void RecordFastOpenStatus();
int socket_;
base::MessageLoopForIO::FileDescriptorWatcher accept_socket_watcher_;
Watcher accept_watcher_;
scoped_ptr<TCPSocketLibevent>* accept_socket_;
IPEndPoint* accept_address_;
CompletionCallback accept_callback_;
// The socket's libevent wrappers for reads and writes.
base::MessageLoopForIO::FileDescriptorWatcher read_socket_watcher_;
base::MessageLoopForIO::FileDescriptorWatcher write_socket_watcher_;
// The corresponding watchers for reads and writes.
Watcher read_watcher_;
Watcher write_watcher_;
// The buffer used for reads.
scoped_refptr<IOBuffer> read_buf_;
int read_buf_len_;
// The buffer used for writes.
scoped_refptr<IOBuffer> write_buf_;
int write_buf_len_;
// External callback; called when read is complete.
CompletionCallback read_callback_;
// External callback; called when write or connect is complete.
CompletionCallback write_callback_;
scoped_ptr<SocketLibevent> socket_;
scoped_ptr<SocketLibevent> accept_socket_;
// Enables experimental TCP FastOpen option.
const bool use_tcp_fastopen_;
......@@ -215,14 +175,6 @@ class NET_EXPORT TCPSocketLibevent : public base::NonThreadSafe {
FastOpenStatus fast_open_status_;
// A connect operation is pending. In this case, |write_callback_| needs to be
// called when connect is complete.
bool waiting_connect_;
scoped_ptr<IPEndPoint> peer_address_;
// The OS error that a connect attempt last completed with.
int connect_os_error_;
bool logging_multiple_connect_attempts_;
BoundNetLog net_log_;
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment