[cdc_rsync] Move sockets to common (#95)

There are no real changes, just moving files around. Sockets will be
used in the future to find available ports in cdc_stream. Therefore,
they need to be in common.
This commit is contained in:
Lutz Justen
2023-03-10 09:17:27 +01:00
committed by GitHub
parent c481b6a27f
commit 09cee120b2
25 changed files with 124 additions and 124 deletions

View File

@@ -52,6 +52,33 @@ cc_test(
],
)
cc_library(
name = "build_version",
srcs = ["build_version.cc"],
hdrs = ["build_version.h"],
# This definition should be replaced by release flow.
copts = ["-DCDC_BUILD_VERSION=DEV"],
)
cc_library(
name = "client_socket",
srcs = ["client_socket.cc"],
hdrs = ["client_socket.h"],
linkopts = select({
"//tools:windows": [
"/DEFAULTLIB:Ws2_32.lib", # Sockets, e.g. recv, send, WSA*.
],
"//conditions:default": [],
}),
target_compatible_with = ["@platforms//os:windows"],
deps = [
":log",
":socket",
":status",
":util",
],
)
cc_library(
name = "clock",
srcs = ["clock.cc"],
@@ -62,14 +89,6 @@ cc_library(
],
)
cc_library(
name = "build_version",
srcs = ["build_version.cc"],
hdrs = ["build_version.h"],
# This definition should be replaced by release flow.
copts = ["-DCDC_BUILD_VERSION=DEV"],
)
cc_library(
name = "dir_iter",
srcs = ["dir_iter.cc"],
@@ -127,6 +146,16 @@ cc_test(
],
)
cc_library(
name = "fake_socket",
srcs = ["fake_socket.cc"],
hdrs = ["fake_socket.h"],
deps = [
":socket",
"@com_google_absl//absl/status",
],
)
cc_library(
name = "file_watcher",
srcs = [
@@ -442,6 +471,39 @@ cc_test(
],
)
cc_library(
name = "server_socket",
srcs = ["server_socket.cc"],
hdrs = ["server_socket.h"],
linkopts = select({
"//tools:windows": [
"/DEFAULTLIB:Ws2_32.lib", # Sockets, e.g. recv, send, WSA*.
],
"//conditions:default": [],
}),
deps = [
":log",
":socket",
":status",
":util",
"@com_google_absl//absl/status",
"@com_google_absl//absl/status:statusor",
],
)
cc_library(
name = "socket",
srcs = ["socket.cc"],
hdrs = ["socket.h"],
deps = [
":log",
":platform",
":status",
":util",
"@com_google_absl//absl/status",
],
)
cc_library(
name = "stats_collector",
srcs = ["stats_collector.cc"],

165
common/client_socket.cc Normal file
View File

@@ -0,0 +1,165 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/client_socket.h"
#include <winsock2.h>
#include <ws2tcpip.h>
#include <cassert>
#include "common/log.h"
#include "common/status.h"
#include "common/util.h"
namespace cdc_ft {
namespace {
// Creates a status with the given |message| and the last WSA error.
// Assigns Tag::kSocketEof for WSAECONNRESET errors.
absl::Status MakeSocketStatus(const char* message) {
const int err = WSAGetLastError();
absl::Status status = MakeStatus("%s: %s", message, Util::GetWin32Error(err));
if (err == WSAECONNRESET) {
status = SetTag(status, Tag::kSocketEof);
}
return status;
}
} // namespace
struct ClientSocketInfo {
SOCKET socket;
ClientSocketInfo() : socket(INVALID_SOCKET) {}
};
ClientSocket::ClientSocket() = default;
ClientSocket::~ClientSocket() { Disconnect(); }
absl::Status ClientSocket::Connect(int port) {
addrinfo hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// Resolve the server address and port.
addrinfo* addr_infos = nullptr;
int result = getaddrinfo("localhost", std::to_string(port).c_str(), &hints,
&addr_infos);
if (result != 0) {
return MakeStatus("getaddrinfo() failed: %i", result);
}
socket_info_ = std::make_unique<ClientSocketInfo>();
int count = 0;
for (addrinfo* curr = addr_infos; curr; curr = curr->ai_next, count++) {
socket_info_->socket =
socket(curr->ai_family, curr->ai_socktype, curr->ai_protocol);
if (socket_info_->socket == INVALID_SOCKET) {
LOG_DEBUG("socket() failed for addr_info %i: %s", count,
Util::GetWin32Error(WSAGetLastError()));
continue;
}
// Connect to server.
result = connect(socket_info_->socket, curr->ai_addr,
static_cast<int>(curr->ai_addrlen));
if (result == SOCKET_ERROR) {
LOG_DEBUG("connect() failed for addr_info %i: %s", count,
Util::GetWin32Error(WSAGetLastError()));
closesocket(socket_info_->socket);
socket_info_->socket = INVALID_SOCKET;
continue;
}
// Success!
break;
}
freeaddrinfo(addr_infos);
if (socket_info_->socket == INVALID_SOCKET) {
socket_info_.reset();
return MakeStatus("Unable to connect to port %i", port);
}
LOG_INFO("Client socket connected to port %i", port);
return absl::OkStatus();
}
void ClientSocket::Disconnect() {
if (!socket_info_) {
return;
}
if (socket_info_->socket != INVALID_SOCKET) {
closesocket(socket_info_->socket);
socket_info_->socket = INVALID_SOCKET;
}
socket_info_.reset();
}
absl::Status ClientSocket::Send(const void* buffer, size_t size) {
int result = send(socket_info_->socket, static_cast<const char*>(buffer),
static_cast<int>(size), /*flags */ 0);
if (result == SOCKET_ERROR) {
return MakeSocketStatus("send() failed");
}
return absl::OkStatus();
}
absl::Status ClientSocket::Receive(void* buffer, size_t size,
bool allow_partial_read,
size_t* bytes_received) {
*bytes_received = 0;
if (size == 0) {
return absl::OkStatus();
}
int flags = allow_partial_read ? 0 : MSG_WAITALL;
int bytes_read = recv(socket_info_->socket, static_cast<char*>(buffer),
static_cast<int>(size), flags);
if (bytes_read == SOCKET_ERROR) {
return MakeSocketStatus("recv() failed");
}
if (bytes_read == 0) {
// EOF
return SetTag(MakeStatus("EOF detected"), Tag::kSocketEof);
}
if (bytes_read != size && !allow_partial_read) {
// Can this happen?
return MakeStatus("Partial read");
}
*bytes_received = bytes_read;
return absl::OkStatus();
}
absl::Status ClientSocket::ShutdownSendingEnd() {
int result = shutdown(socket_info_->socket, SD_SEND);
if (result == SOCKET_ERROR) {
return MakeSocketStatus("shutdown() failed");
}
return absl::OkStatus();
}
} // namespace cdc_ft

53
common/client_socket.h Normal file
View File

@@ -0,0 +1,53 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_CLIENT_SOCKET_H_
#define COMMON_CLIENT_SOCKET_H_
#include <memory>
#include "absl/status/status.h"
#include "common/socket.h"
namespace cdc_ft {
class ClientSocket : public Socket {
public:
ClientSocket();
~ClientSocket();
// Connects to localhost on |port|.
absl::Status Connect(int port);
// Disconnects again. No-op if not connected.
void Disconnect();
// Shuts down the sending end of the socket. This will interrupt any receive
// calls on the server and shut it down.
absl::Status ShutdownSendingEnd();
// Socket:
absl::Status Send(const void* buffer, size_t size) override;
absl::Status Receive(void* buffer, size_t size, bool allow_partial_read,
size_t* bytes_received) override;
private:
std::unique_ptr<struct ClientSocketInfo> socket_info_;
};
} // namespace cdc_ft
#endif // COMMON_CLIENT_SOCKET_H_

71
common/fake_socket.cc Normal file
View File

@@ -0,0 +1,71 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/fake_socket.h"
namespace cdc_ft {
FakeSocket::FakeSocket() = default;
FakeSocket::~FakeSocket() = default;
absl::Status FakeSocket::Send(const void* buffer, size_t size) {
// Wait until we can send again.
std::unique_lock<std::mutex> suspend_lock(suspend_mutex_);
suspend_cv_.wait(suspend_lock, [this]() { return !sending_suspended_; });
suspend_lock.unlock();
std::unique_lock<std::mutex> lock(data_mutex_);
data_.append(static_cast<const char*>(buffer), size);
lock.unlock();
data_cv_.notify_all();
return absl::OkStatus();
}
absl::Status FakeSocket::Receive(void* buffer, size_t size,
bool allow_partial_read,
size_t* bytes_received) {
*bytes_received = 0;
std::unique_lock<std::mutex> lock(data_mutex_);
data_cv_.wait(lock, [this, size, allow_partial_read]() {
size_t min_size = allow_partial_read ? 1 : size;
return data_.size() >= min_size || shutdown_;
});
if (shutdown_) {
return absl::UnavailableError("Pipe is shut down");
}
size_t to_copy = std::min(size, data_.size());
memcpy(buffer, data_.data(), to_copy);
*bytes_received = to_copy;
// This is horribly inefficent, but should be OK in a fake.
data_.erase(0, to_copy);
return absl::OkStatus();
}
void FakeSocket::ShutdownSendingEnd() {
std::unique_lock<std::mutex> lock(data_mutex_);
shutdown_ = true;
lock.unlock();
data_cv_.notify_all();
}
void FakeSocket::SuspendSending(bool suspended) {
std::unique_lock<std::mutex> lock(suspend_mutex_);
sending_suspended_ = suspended;
lock.unlock();
suspend_cv_.notify_all();
}
} // namespace cdc_ft

57
common/fake_socket.h Normal file
View File

@@ -0,0 +1,57 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_FAKE_SOCKET_H_
#define COMMON_FAKE_SOCKET_H_
#include <condition_variable>
#include <mutex>
#include "absl/status/status.h"
#include "common/socket.h"
namespace cdc_ft {
// Fake socket that receives the same data it sends.
class FakeSocket : public Socket {
public:
FakeSocket();
~FakeSocket();
// Socket:
absl::Status Send(const void* buffer, size_t size) override; // thread-safe
absl::Status Receive(void* buffer, size_t size, bool allow_partial_read,
size_t* bytes_received) override; // thread-safe
void ShutdownSendingEnd();
// If set to true, blocks on Send() until it is set to false again.
void SuspendSending(bool suspended);
private:
std::mutex data_mutex_;
std::condition_variable data_cv_;
std::string data_;
bool shutdown_ = false;
bool sending_suspended_ = false;
std::mutex suspend_mutex_;
std::condition_variable suspend_cv_;
};
} // namespace cdc_ft
#endif // CDC_RSYNC_BASE_FAKE_SOCKET_H_

355
common/server_socket.cc Normal file
View File

@@ -0,0 +1,355 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "common/server_socket.h"
#include "common/log.h"
#include "common/platform.h"
#include "common/status.h"
#include "common/util.h"
#if PLATFORM_WINDOWS
#include <winsock2.h>
#include <ws2tcpip.h>
#elif PLATFORM_LINUX
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <cerrno>
#endif
namespace cdc_ft {
namespace {
#if PLATFORM_WINDOWS
using SocketType = SOCKET;
using SockAddrType = SOCKADDR;
constexpr SocketType kInvalidSocket = INVALID_SOCKET;
constexpr int kSocketError = SOCKET_ERROR;
constexpr int kSendingEnd = SD_SEND;
constexpr int kErrAgain = WSAEWOULDBLOCK; // There's no EAGAIN on Windows.
constexpr int kErrWouldBlock = WSAEWOULDBLOCK;
constexpr int kErrAddrInUse = WSAEADDRINUSE;
int GetLastError() { return WSAGetLastError(); }
std::string GetErrorStr(int err) { return Util::GetWin32Error(err); }
void Close(SocketType* socket) {
if (*socket != kInvalidSocket) {
closesocket(*socket);
*socket = kInvalidSocket;
}
}
// Not necessary on Windows.
#define HANDLE_EINTR(x) (x)
#elif PLATFORM_LINUX
using SocketType = int;
using SockAddrType = sockaddr;
constexpr SocketType kInvalidSocket = -1;
constexpr int kSocketError = -1;
constexpr int kSendingEnd = SHUT_WR;
constexpr int kErrAgain = EAGAIN;
constexpr int kErrWouldBlock = EWOULDBLOCK;
constexpr int kErrAddrInUse = EADDRINUSE;
int GetLastError() { return errno; }
std::string GetErrorStr(int err) { return strerror(err); }
void Close(SocketType* socket) {
if (*socket != kInvalidSocket) {
close(*socket);
*socket = kInvalidSocket;
}
}
// Keep re-evaluating the expression |x| while it returns EINTR.
#define HANDLE_EINTR(x) \
({ \
decltype(x) eintr_wrapper_result; \
do { \
eintr_wrapper_result = (x); \
} while (eintr_wrapper_result == -1 && errno == EINTR); \
eintr_wrapper_result; \
})
#endif
std::string GetLastErrorStr() { return GetErrorStr(GetLastError()); }
class AddrInfoReleaser {
public:
AddrInfoReleaser(addrinfo* addr_infos) : addr_infos_(addr_infos) {}
~AddrInfoReleaser() { freeaddrinfo(addr_infos_); }
private:
addrinfo* addr_infos_;
};
} // namespace
struct ServerSocketInfo {
// Listening socket file descriptor (where new connections are accepted).
SocketType listen_sock = kInvalidSocket;
// Connection socket file descriptor (where data is sent to/received from).
SocketType conn_sock = kInvalidSocket;
};
ServerSocket::ServerSocket()
: Socket(), socket_info_(std::make_unique<ServerSocketInfo>()) {}
ServerSocket::~ServerSocket() {
Disconnect();
StopListening();
}
absl::StatusOr<int> ServerSocket::StartListening(int port) {
if (socket_info_->listen_sock != kInvalidSocket) {
return MakeStatus("Already listening");
}
// Find addrinfos suitable for listening via IPV4 and IPV6.
addrinfo hints;
addrinfo* addr_infos = nullptr;
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
// AI_PASSIVE indicates that the addresses are used with bind(). The returned
// addresses will be the unspecified addresses for each family.
hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
int result = getaddrinfo(/*address=*/nullptr, std::to_string(port).c_str(),
&hints, &addr_infos);
if (result != 0) {
return MakeStatus("Getting address infos failed: %s", GetLastErrorStr());
}
AddrInfoReleaser releaser(addr_infos);
// Prefer IPV6 sockets. They can also accept IPV4 connections.
for (addrinfo* curr = addr_infos; curr; curr = curr->ai_next) {
if (curr->ai_family == PF_INET6) {
return StartListeningInternal(port, curr);
}
}
// Fall back to IPV4 sockets.
for (addrinfo* curr = addr_infos; curr; curr = curr->ai_next) {
if (curr->ai_family == PF_INET) {
return StartListeningInternal(port, curr);
}
}
return MakeStatus("No IPV4 and IPV6 network addresses available");
}
absl::StatusOr<int> ServerSocket::StartListeningInternal(int port,
addrinfo* addr) {
assert(addr->ai_family == PF_INET || addr->ai_family == PF_INET6);
const char* family = addr->ai_family == PF_INET ? "IPV4" : "IPV6";
// Open a socket with the correct address family for this address.
LOG_DEBUG("Open %s listen socket", family);
socket_info_->listen_sock =
socket(addr->ai_family, addr->ai_socktype, addr->ai_protocol);
if (socket_info_->listen_sock == kInvalidSocket) {
return MakeStatus("Creating %s listen socket failed: %s", family,
GetLastErrorStr());
}
// If the program terminates abnormally, the socket might remain in a
// TIME_WAIT state and report "address already in use" on bind(). Setting
// SO_REUSEADDR works around that. See
// https://hea-www.harvard.edu/~fine/Tech/addrinuse.html
const int enable = 1;
int result =
setsockopt(socket_info_->listen_sock, SOL_SOCKET, SO_REUSEADDR,
reinterpret_cast<const char*>(&enable), sizeof(enable));
if (result == kSocketError) {
LOG_DEBUG("Enabling address reusal failed");
}
// Allow ipv4 connections on the ipv6 socket. By default, ipv6 sockets only
// allow ipv4 connections on Windows.
if (addr->ai_family == PF_INET6) {
const int disable = 0;
result =
setsockopt(socket_info_->listen_sock, IPPROTO_IPV6, IPV6_V6ONLY,
reinterpret_cast<const char*>(&disable), sizeof(disable));
if (result == kSocketError) {
LOG_DEBUG("Disabling IPV6-only failed");
}
}
LOG_DEBUG("Bind socket");
result = bind(socket_info_->listen_sock, addr->ai_addr,
static_cast<int>(addr->ai_addrlen));
if (result == kSocketError) {
int err = GetLastError();
absl::Status status =
MakeStatus("Binding to port %i failed: %s", port, GetErrorStr(err));
if (err == kErrAddrInUse) {
// Happens when two instances are run at the same time. Help callers to
// print reasonable errors.
status = SetTag(status, Tag::kAddressInUse);
}
Close(&socket_info_->listen_sock);
return status;
}
if (port == 0) {
// Find out which port was auto-selected.
socklen_t len = addr->ai_addrlen;
result = getsockname(socket_info_->listen_sock, addr->ai_addr, &len);
if (result == kSocketError) {
Close(&socket_info_->listen_sock);
return MakeStatus("Getting port failed: %s", GetLastErrorStr());
}
if (addr->ai_family == PF_INET) {
port = ntohs(reinterpret_cast<sockaddr_in*>(addr->ai_addr)->sin_port);
} else if (addr->ai_family == PF_INET6) {
port = ntohs(reinterpret_cast<sockaddr_in6*>(addr->ai_addr)->sin6_port);
}
}
LOG_DEBUG("Listen");
result = listen(socket_info_->listen_sock, 1);
if (result == kSocketError) {
int err = GetLastError();
Close(&socket_info_->listen_sock);
return MakeStatus("Listening to socket failed: %s", GetErrorStr(err));
}
return port;
}
void ServerSocket::StopListening() {
Close(&socket_info_->listen_sock);
LOG_INFO("Stopped listening.");
}
absl::Status ServerSocket::WaitForConnection() {
if (socket_info_->conn_sock != kInvalidSocket) {
return MakeStatus("Already connected");
}
if (socket_info_->listen_sock == kInvalidSocket) {
return MakeStatus("Not listening");
}
socket_info_->conn_sock = accept(socket_info_->listen_sock, nullptr, nullptr);
if (socket_info_->conn_sock == kInvalidSocket) {
return MakeStatus("Accepting connection failed: %s", GetLastErrorStr());
}
LOG_DEBUG("Client connected");
return absl::OkStatus();
}
void ServerSocket::Disconnect() {
Close(&socket_info_->conn_sock);
LOG_INFO("Disconnected");
}
absl::Status ServerSocket::ShutdownSendingEnd() {
int result = shutdown(socket_info_->conn_sock, kSendingEnd);
if (result == kSocketError) {
return MakeStatus("Socket shutdown failed: %s", GetLastErrorStr());
}
return absl::OkStatus();
}
absl::Status ServerSocket::Send(const void* buffer, size_t size) {
const char* curr_ptr = reinterpret_cast<const char*>(buffer);
assert(size <= INT_MAX);
int bytes_left = static_cast<int>(size);
while (bytes_left > 0) {
int bytes_written = HANDLE_EINTR(
send(socket_info_->conn_sock, curr_ptr, bytes_left, /*flags*/ 0));
if (bytes_written < 0) {
const int err = GetLastError();
if (err == kErrAgain || err == kErrWouldBlock) {
// Shouldn't happen as the socket should be blocking.
LOG_DEBUG("Socket would block");
continue;
}
return MakeStatus("Sending to socket failed: %s", GetErrorStr(err));
}
bytes_left -= bytes_written;
curr_ptr += bytes_written;
}
return absl::OkStatus();
}
absl::Status ServerSocket::Receive(void* buffer, size_t size,
bool allow_partial_read,
size_t* bytes_received) {
*bytes_received = 0;
if (size == 0) {
return absl::OkStatus();
}
char* curr_ptr = static_cast<char*>(buffer);
assert(size <= INT_MAX);
int bytes_left = size;
while (bytes_left > 0) {
int bytes_read = HANDLE_EINTR(
recv(socket_info_->conn_sock, curr_ptr, bytes_left, /*flags*/ 0));
if (bytes_read < 0) {
const int err = GetLastError();
if (err == kErrAgain || err == kErrWouldBlock) {
// Shouldn't happen as the socket should be blocking.
LOG_DEBUG("Socket would block");
continue;
}
return MakeStatus("Receiving from socket failed: %s", GetErrorStr(err));
}
bytes_left -= bytes_read;
*bytes_received += bytes_read;
curr_ptr += bytes_read;
if (bytes_read == 0) {
// EOF. Make sure we're not in the middle of a message.
if (bytes_left < static_cast<int>(size)) {
return MakeStatus("EOF after partial read");
}
LOG_DEBUG("EOF() detected");
return SetTag(MakeStatus("EOF detected"), Tag::kSocketEof);
}
if (allow_partial_read) {
break;
}
}
return absl::OkStatus();
}
} // namespace cdc_ft

68
common/server_socket.h Normal file
View File

@@ -0,0 +1,68 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_SERVER_SOCKET_H_
#define COMMON_SERVER_SOCKET_H_
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "common/socket.h"
struct addrinfo;
namespace cdc_ft {
class ServerSocket : public Socket {
public:
ServerSocket();
~ServerSocket();
// Starts listening for connections on |port|.
// Passing 0 as port will bind to any available port.
// Returns the port that was bound to.
absl::StatusOr<int> StartListening(int port);
// Stops listening for connections. No-op if already stopped/never started.
void StopListening();
// Waits for a client to connect. Only supports one connection. Repeating
// the call with an existing connection results in an error.
absl::Status WaitForConnection();
// Disconnects the client. No-op if not connected.
void Disconnect();
// Shuts down the sending end of the socket. This will interrupt any receive
// calls on the client and shut it down.
absl::Status ShutdownSendingEnd();
// Socket:
absl::Status Send(const void* buffer, size_t size) override;
absl::Status Receive(void* buffer, size_t size, bool allow_partial_read,
size_t* bytes_received) override;
private:
// Called by StartListening() for a specific IPV4 or IPV6 |addr_info|.
// Passing 0 as port will bind to any available port.
// Returns the port that was bound to.
absl::StatusOr<int> StartListeningInternal(int port, addrinfo* addr);
std::unique_ptr<struct ServerSocketInfo> socket_info_;
};
} // namespace cdc_ft
#endif // CDC_RSYNC_SERVER_SERVER_SOCKET_H_

65
common/socket.cc Normal file
View File

@@ -0,0 +1,65 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "common/socket.h"
#include "common/log.h"
#include "common/platform.h"
#include "common/status.h"
#include "common/util.h"
#if PLATFORM_WINDOWS
#include <winsock2.h>
#endif
namespace cdc_ft {
// static
absl::Status Socket::Initialize() {
#if PLATFORM_WINDOWS
WSADATA wsaData;
const int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
return MakeStatus("WSAStartup() failed: %s", Util::GetWin32Error(result));
}
return absl::OkStatus();
#elif PLATFORM_LINUX
return absl::OkStatus();
#endif
}
// static
absl::Status Socket::Shutdown() {
#if PLATFORM_WINDOWS
const int result = WSACleanup();
if (result == SOCKET_ERROR) {
return MakeStatus("WSACleanup() failed: %s",
Util::GetWin32Error(WSAGetLastError()));
}
return absl::OkStatus();
#elif PLATFORM_LINUX
return absl::OkStatus();
#endif
}
SocketFinalizer::~SocketFinalizer() {
absl::Status status = Socket::Shutdown();
if (!status.ok()) {
LOG_ERROR("Socket shutdown failed: %s", status.message())
}
};
} // namespace cdc_ft

59
common/socket.h Normal file
View File

@@ -0,0 +1,59 @@
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef COMMON_SOCKET_H_
#define COMMON_SOCKET_H_
#include "absl/status/status.h"
namespace cdc_ft {
class Socket {
public:
Socket() = default;
virtual ~Socket() = default;
// Calls WSAStartup() on Windows, no-op on Linux.
// Must be called before using sockets.
static absl::Status Initialize();
// Calls WSACleanup() on Windows, no-op on Linux.
// Must be called after using sockets.
static absl::Status Shutdown();
// Send data to the socket.
virtual absl::Status Send(const void* buffer, size_t size) = 0;
// Receives data from the socket. Blocks until data is available or the
// sending end of the socket gets shut down by the sender.
// If |allow_partial_read| is false, blocks until |size| bytes are available.
// If |allow_partial_read| is true, may return with success if less than
// |size| (but more than 0) bytes were received.
// The number of bytes written to |buffer| is returned in |bytes_received|.
virtual absl::Status Receive(void* buffer, size_t size,
bool allow_partial_read,
size_t* bytes_received) = 0;
};
// Convenience class that calls Shutdown() on destruction. Logs on errors.
class SocketFinalizer {
public:
~SocketFinalizer();
};
} // namespace cdc_ft
#endif // COMMON_SOCKET_H_