Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
session_socket.h
Go to the documentation of this file.
1
4#pragma once
5#include <algorithm>
6#include <cerrno>
7#include <chrono>
8#include <cstdint>
9#include <cstring>
10#include <poll.h>
11#include <string>
12#include <sys/socket.h>
13#include <sys/un.h>
14#include <unistd.h>
15
16namespace platf::kwin {
17 inline int connect_session_socket(const std::string &path, std::string &error) {
18 sockaddr_un address {};
19 address.sun_family = AF_UNIX;
20 if (path.empty() || path.front() != '/' || path.find('\0') != std::string::npos || path.size() >= sizeof(address.sun_path)) {
21 error = "A private session connection requires an absolute Unix socket path";
22 return -1;
23 }
24 std::memcpy(address.sun_path, path.c_str(), path.size() + 1);
25 int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0);
26 if (fd < 0) {
27 error = std::strerror(errno);
28 return -1;
29 }
30 if (::connect(fd, reinterpret_cast<sockaddr *>(&address), sizeof(address)) == 0) {
31 return fd;
32 }
33 // AF_UNIX returns EAGAIN for a full accept queue; it is not a completed
34 // connection. Never turn that condition into a connection to another socket.
35 if (errno == EINPROGRESS) {
36 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
37 pollfd event {fd, POLLOUT, 0};
38 int result;
39 do {
40 result = ::poll(&event, 1, static_cast<int>(std::max<std::int64_t>(0, std::chrono::duration_cast<std::chrono::milliseconds>(deadline - std::chrono::steady_clock::now()).count())));
41 } while (result < 0 && errno == EINTR && std::chrono::steady_clock::now() < deadline);
42 int socket_error = 0;
43 socklen_t size = sizeof(socket_error);
44 if (result > 0 && ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &socket_error, &size) == 0 && socket_error == 0) {
45 return fd;
46 }
47 error = result == 0 ? "Private session connection timed out" :
48 std::strerror(socket_error ? socket_error : errno);
49 } else {
50 error = std::strerror(errno);
51 }
52 ::close(fd);
53 return -1;
54 }
55
56} // namespace platf::kwin