104 sockaddr_un address {};
105 address.sun_family = AF_UNIX;
106 if (path.empty() || path.size() >=
sizeof(address.sun_path) || path.find(
'\0') != std::string::npos) {
107 return {.reply = std::nullopt, .error =
"invalid Unix socket path"};
109 if (request.empty() || request.size() > 64 * 1024 || request.back() !=
'\n' || request.find(
'\0') != std::string::npos) {
110 return {.reply = std::nullopt, .error =
"invalid or oversized request"};
112 std::memcpy(address.sun_path, path.data(), path.size());
113 owned_fd fd {::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)};
115 return failure(
"create socket");
119 const int send_buffer = 16 * 1024;
120 ::setsockopt(fd.value, SOL_SOCKET, SO_SNDBUF, &send_buffer,
sizeof(send_buffer));
121 const auto deadline = clock::now() +
timeout;
122 if (!connect_socket(fd.value, address, deadline)) {
123 return failure(
"connect");
125 for (std::size_t offset = 0; offset < request.size();) {
126 if (!wait_ready(fd.value, POLLOUT, deadline)) {
127 return failure(
"send request");
129 const auto count = ::send(fd.value, request.data() + offset, request.size() - offset, MSG_NOSIGNAL);
130 if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
134 return failure(
"send request");
136 offset +=
static_cast<std::size_t
>(count);
138 ::shutdown(fd.value, SHUT_WR);
140 constexpr std::size_t maximum_reply = 4096;
142 std::array<char, 512> buffer {};
143 while (reply.size() < maximum_reply) {
144 if (!wait_ready(fd.value, POLLIN, deadline)) {
145 return failure(
"read reply");
147 const auto count = ::read(fd.value, buffer.data(), std::min(buffer.size(), maximum_reply - reply.size()));
148 if (count < 0 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK)) {
152 return failure(
"read reply");
155 return {.reply = std::nullopt, .error =
"broker closed before a complete reply"};
157 reply.append(buffer.data(),
static_cast<std::size_t
>(count));
158 if (
const auto newline = reply.find(
'\n'); newline != std::string::npos) {
159 reply.resize(newline);
160 if (reply.empty() || reply.find(
'\0') != std::string::npos) {
161 return {.reply = std::nullopt, .error =
"empty or malformed broker reply"};
163 return {.reply = std::move(reply), .error = {}};
166 return {.reply = std::nullopt, .error =
"broker reply exceeds 4096 bytes"};