1 // Copyright 2019 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 #ifndef PLATFORM_IMPL_STREAM_SOCKET_H_ 6 #define PLATFORM_IMPL_STREAM_SOCKET_H_ 7 8 #include <cstdint> 9 #include <memory> 10 #include <string> 11 12 #include "platform/api/network_interface.h" 13 #include "platform/base/error.h" 14 #include "platform/base/ip_address.h" 15 #include "platform/base/macros.h" 16 #include "platform/impl/socket_handle.h" 17 #include "platform/impl/socket_state.h" 18 19 namespace openscreen { 20 21 // StreamSocket is an incomplete abstraction of synchronous platform methods for 22 // creating, initializing, and closing stream sockets. Callers can use this 23 // class to define complete TCP and TLS socket classes, both synchronous and 24 // asynchronous. 25 class StreamSocket { 26 public: 27 StreamSocket() = default; 28 StreamSocket(const StreamSocket& other) = delete; 29 StreamSocket(StreamSocket&& other) noexcept = default; 30 virtual ~StreamSocket() = default; 31 32 StreamSocket& operator=(const StreamSocket& other) = delete; 33 StreamSocket& operator=(StreamSocket&& other) = default; 34 35 // Used by passive/server sockets to accept connection requests 36 // from a client. 37 virtual ErrorOr<std::unique_ptr<StreamSocket>> Accept() = 0; 38 39 // Bind to the address provided on socket construction. Socket should be 40 // unbound and not connected. 41 virtual Error Bind() = 0; 42 43 // Closes the socket. Socket must be opened before this method is called. 44 virtual Error Close() = 0; 45 46 // Connects the socket to a specified remote address. Socket should be 47 // initialized and bound, but not connected. 48 virtual Error Connect(const IPEndpoint& remote_endpoint) = 0; 49 50 // Marks the socket as passive, to receive incoming connections. 51 virtual Error Listen() = 0; 52 virtual Error Listen(int max_backlog_size) = 0; 53 54 // Returns the file descriptor (e.g. fd or HANDLE pointer) for this socket. 55 virtual const SocketHandle& socket_handle() const = 0; 56 57 // Returns the connected remote address, if socket is connected. 58 virtual absl::optional<IPEndpoint> remote_address() const = 0; 59 60 // Returns the local address, if one is assigned. 61 virtual absl::optional<IPEndpoint> local_address() const = 0; 62 63 // Returns the state of the socket. 64 virtual TcpSocketState state() const = 0; 65 66 // Returns the IP version of the socket. 67 virtual IPAddress::Version version() const = 0; 68 }; 69 70 } // namespace openscreen 71 72 #endif // PLATFORM_IMPL_STREAM_SOCKET_H_ 73