Use mDNS/DNS-SD to find the server

This commit is contained in:
Guillaume Meunier
2022-11-11 15:59:55 +01:00
parent 128e221e64
commit c218891653
10 changed files with 2388 additions and 242 deletions
+1615
View File
File diff suppressed because it is too large Load Diff
+50 -26
View File
@@ -31,29 +31,10 @@
#include <string>
#include <tiny_gltf.h>
namespace
{
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
}},
.subpasses = {VkSubpassDescription{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
}},
.dependencies = {}};
} // namespace
scenes::lobby::~lobby() {}
scenes::lobby::lobby() :
status_string_rasterizer(device, physical_device, commandpool, queue), renderer(device, physical_device, queue)
status_string_rasterizer(device, physical_device, commandpool, queue), discover("_wivrn._tcp.local."), renderer(device, physical_device, queue)
{
// renderer.load_gltf("Lobby.gltf");
@@ -61,7 +42,23 @@ scenes::lobby::lobby() :
uint32_t height = swapchains[0].height();
// Create renderpass
renderpass_info.attachments[0].format = swapchains[0].format();
VkAttachmentReference color_ref{.attachment = 0, .layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
vk::renderpass::info renderpass_info{.attachments = {VkAttachmentDescription{
.format = swapchains[0].format(),
.samples = VK_SAMPLE_COUNT_1_BIT,
.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR,
.storeOp = VK_ATTACHMENT_STORE_OP_STORE,
.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED,
.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
}},
.subpasses = {VkSubpassDescription{
.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS,
.colorAttachmentCount = 1,
.pColorAttachments = &color_ref,
}},
.dependencies = {}};
renderpass = vk::renderpass(device, renderpass_info);
VkSamplerCreateInfo sampler_info{
@@ -233,18 +230,45 @@ void scenes::lobby::rasterize_status_string()
last_status_string = status_string;
}
void scenes::lobby::render()
std::unique_ptr<wivrn_session> connect_to_session(const std::vector<wivrn_discover::service>& services)
{
if (auto session = client.poll())
// TODO: make it asynchronous
for(const wivrn_discover::service& service: services)
{
next_scene.reset();
next_scene = stream::create(std::move(session));
int port = service.port;
for(const auto& address: service.addresses)
{
try
{
return std::visit([port](auto& address){
return std::make_unique<wivrn_session>(address, port);
}, address);
}
catch(std::exception& e)
{
spdlog::warn("Cannot connect to {}", service.hostname);
}
}
}
return {};
}
void scenes::lobby::render()
{
if (next_scene && !next_scene->alive())
next_scene.reset();
if (!next_scene)
{
auto services = discover.get_services();
if (auto session = connect_to_session(services))
{
next_scene = stream::create(std::move(session));
}
}
if (next_scene)
{
if (next_scene->ready())
+2 -1
View File
@@ -24,6 +24,7 @@
#include "vk/image.h"
#include "vk/renderpass.h"
#include "wivrn_client.h"
#include "wivrn_discover.h"
#include <tiny_gltf.h>
#include "render/scene_renderer.h"
@@ -60,7 +61,7 @@ class lobby : public scene
std::vector<std::vector<image_data>> images_data;
wivrn_client client;
wivrn_discover discover;
tinygltf::Model model;
std::vector<vk::device_memory> model_memory;
+57 -112
View File
@@ -36,128 +36,73 @@
using namespace std::chrono_literals;
static std::vector<std::pair<int, std::string>> get_network_interfaces()
{
ifaddrs * addresses;
if (getifaddrs(&addresses) < 0)
{
spdlog::warn("Cannot get network interfaces: {}", strerror(errno));
return {};
}
int fd = socket(AF_INET6, SOCK_DGRAM, 0);
const int required_flags = IFF_UP | IFF_MULTICAST;
const int forbidden_flags = IFF_LOOPBACK;
std::vector<std::pair<int, std::string>> interfaces;
for (ifaddrs * i = addresses; i; i = i->ifa_next)
{
if (i->ifa_addr == nullptr)
continue;
if (i->ifa_addr->sa_family != AF_INET6)
continue;
if ((i->ifa_flags & required_flags) != required_flags)
continue;
if ((i->ifa_flags & forbidden_flags) != 0)
continue;
if (std::any_of(interfaces.begin(), interfaces.end(), [&](const auto & j) { return j.second == i->ifa_name; }))
continue;
ifreq interface {};
strncpy(interface.ifr_name, i->ifa_name, sizeof(interface.ifr_name) - 1);
ioctl(fd, SIOCGIFINDEX, &interface);
interfaces.emplace_back(interface.ifr_ifindex, i->ifa_name);
}
close(fd);
freeifaddrs(addresses);
return interfaces;
}
wivrn_client::wivrn_client() :
listener(control_port)
{
auto interfaces = get_network_interfaces();
if (interfaces.empty())
{
spdlog::critical("No suitable network interface found");
throw std::runtime_error("No suitable network interface found"); // TODO class exception
}
for (auto [id, name]: interfaces)
{
auto & socket = broadcasters.emplace_back();
if (setsockopt(socket.get_fd(), IPPROTO_IPV6, IPV6_MULTICAST_IF, &id, sizeof(id)) < 0)
{
spdlog::error("setsockopt: {}", strerror(errno));
}
spdlog::info("Starting multicaster on {}", name);
socket.connect(announce_address, announce_port);
}
}
wivrn_session::wivrn_session(xrt::drivers::wivrn::TCP && tcp, in6_addr address) :
control(std::move(tcp)), stream()
wivrn_session::wivrn_session(in6_addr address, int port) : control(address, port), stream()
{
// TODO: negociate UDP port
stream.bind(stream_port);
stream.connect(address, stream_port);
stream.set_receive_buffer_size(1024 * 1024 * 5);
char buffer[100];
spdlog::info("Connection to {}:{}", inet_ntop(AF_INET6, &address, buffer, sizeof(buffer)), port);
}
std::unique_ptr<wivrn_session> wivrn_client::poll()
wivrn_session::wivrn_session(in_addr address, int port) : control(address, port), stream()
{
auto now = std::chrono::steady_clock::now();
// TODO: negociate UDP port
stream.bind(stream_port);
stream.connect(address, stream_port);
stream.set_receive_buffer_size(1024 * 1024 * 5);
auto time_since_last_broadcast = now - last_broadcast;
if (time_since_last_broadcast >= 1s)
{
last_broadcast = now;
details::hash_context h;
serialization_traits<from_headset::control_packets>::type_hash(h);
serialization_traits<to_headset::control_packets>::type_hash(h);
serialization_traits<from_headset::stream_packets>::type_hash(h);
serialization_traits<to_headset::stream_packets>::type_hash(h);
from_headset::client_announce_packet packet{
.magic = from_headset::client_announce_packet::magic_value,
.client_version = "WiVRn " GIT_VERSION,
.protocol_hash = h.hash,
};
for (auto & i: broadcasters)
i.send(packet);
}
pollfd fds{};
fds.events = POLLIN;
fds.fd = listener.get_fd();
int r = ::poll(&fds, 1, 0);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (r > 0 && (fds.revents & POLLIN))
{
auto [tcp, addr] = listener.accept();
char buffer[100];
spdlog::info("Connection from {}", inet_ntop(AF_INET6, &addr.sin6_addr, buffer, sizeof(buffer)));
return std::make_unique<wivrn_session>(std::move(tcp), addr.sin6_addr);
}
return {};
char buffer[100];
spdlog::info("Connection to {}:{}", inet_ntop(AF_INET, &address, buffer, sizeof(buffer)), port);
}
// std::unique_ptr<wivrn_session> wivrn_client::poll()
// {
// auto now = std::chrono::steady_clock::now();
//
// auto time_since_last_broadcast = now - last_broadcast;
//
// if (time_since_last_broadcast >= 1s)
// {
// last_broadcast = now;
//
// details::hash_context h;
// serialization_traits<from_headset::control_packets>::type_hash(h);
// serialization_traits<to_headset::control_packets>::type_hash(h);
// serialization_traits<from_headset::stream_packets>::type_hash(h);
// serialization_traits<to_headset::stream_packets>::type_hash(h);
//
// from_headset::client_announce_packet packet{
// .magic = from_headset::client_announce_packet::magic_value,
// .client_version = "WiVRn " GIT_VERSION,
// .protocol_hash = h.hash,
// };
//
// for (auto & i: broadcasters)
// i.send(packet);
// }
//
// pollfd fds{};
// fds.events = POLLIN;
// fds.fd = listener.get_fd();
//
// int r = ::poll(&fds, 1, 0);
// if (r < 0)
// throw std::system_error(errno, std::system_category());
//
// if (r > 0 && (fds.revents & POLLIN))
// {
// auto [tcp, addr] = listener.accept();
// char buffer[100];
// spdlog::info("Connection from {}", inet_ntop(AF_INET6, &addr.sin6_addr, buffer, sizeof(buffer)));
// return std::make_unique<wivrn_session>(std::move(tcp), addr.sin6_addr);
// }
//
// return {};
// }
void wivrn_session::send_control(const from_headset::control_packets & packet)
{
control.send(packet);
+2 -17
View File
@@ -26,29 +26,14 @@
using namespace xrt::drivers::wivrn;
class wivrn_session;
class wivrn_client
{
using broadcast_socket = typed_socket<UDP, void, from_headset::client_announce_packet>;
std::vector<broadcast_socket> broadcasters;
TCPListener listener;
std::chrono::steady_clock::time_point last_broadcast{};
public:
wivrn_client();
std::unique_ptr<wivrn_session> poll();
};
class wivrn_session
{
typed_socket<TCP, to_headset::control_packets, from_headset::control_packets> control;
typed_socket<UDP, to_headset::stream_packets, from_headset::stream_packets> stream;
public:
wivrn_session(TCP && tcp, in6_addr address);
wivrn_session(in6_addr address, int port);
wivrn_session(in_addr address, int port);
wivrn_session(const wivrn_session &) = delete;
wivrn_session & operator=(const wivrn_session &) = delete;
+561
View File
@@ -0,0 +1,561 @@
#include "wivrn_discover.h"
#include "external/mdns.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <poll.h>
#include <spdlog/spdlog.h>
#include <string>
#include <sys/ioctl.h>
#include <variant>
#include <vector>
using namespace std::chrono;
namespace
{
std::string ip_address_to_string(const in_addr & address)
{
char buffer[128];
if (inet_ntop(AF_INET, &address, buffer, sizeof(buffer)))
return buffer;
return "";
}
std::string ip_address_to_string(const in6_addr & address)
{
char buffer[128];
if (inet_ntop(AF_INET6, &address, buffer, sizeof(buffer)))
return buffer;
return "";
}
std::string ip_address_to_string(const sockaddr * address)
{
if (address->sa_family == AF_INET)
{
return ip_address_to_string(((struct sockaddr_in *)address)->sin_addr);
}
else if (address->sa_family == AF_INET6)
{
return ip_address_to_string(((struct sockaddr_in6 *)address)->sin6_addr);
}
return "";
}
} // namespace
static bool operator==(const in_addr & a, const in_addr & b)
{
return memcmp(&a, &b, sizeof(a)) == 0;
}
static bool operator==(const in6_addr & a, const in6_addr & b)
{
return memcmp(&a, &b, sizeof(a)) == 0;
}
class dnssd_cache
{
public:
using ptr = std::string;
struct srv
{
std::string hostname;
int port;
bool operator==(const srv &) const noexcept = default;
};
using a = in_addr;
using aaaa = in6_addr;
private:
struct cache_entry
{
steady_clock::time_point timeout;
std::string name;
std::variant<ptr, srv, a, aaaa> record;
bool operator==(const cache_entry & other) const noexcept
{
return name == other.name && record == other.record;
}
};
std::vector<cache_entry> cache;
std::vector<std::tuple<steady_clock::time_point, mdns_record_type, std::string>> last_queries;
// pollfds[0] is used for inter-thread communication, the others are for mDNS
std::vector<pollfd> pollfds;
int itc_fd;
void open_client_sockets(int port = 0)
{
close_client_sockets();
std::vector<int> sockets;
ifaddrs * addresses;
if (getifaddrs(&addresses) < 0)
{
spdlog::error("Cannot get network interfaces: {}", strerror(errno));
return;
}
const int required_flags = IFF_UP | IFF_MULTICAST;
const int forbidden_flags = IFF_LOOPBACK;
// std::vector<std::string> interfaces_ipv4;
// std::vector<std::string> interfaces_ipv6;
for (ifaddrs * i = addresses; i; i = i->ifa_next)
{
if (i->ifa_addr == nullptr)
continue;
if ((i->ifa_flags & required_flags) != required_flags)
continue;
if ((i->ifa_flags & forbidden_flags) != 0)
continue;
if (i->ifa_addr->sa_family == AF_INET6)
{
// if (std::any_of(interfaces_ipv6.begin(), interfaces_ipv6.end(), [&](const auto & j) { return j == i->ifa_name; }))
// continue;
struct sockaddr_in6 * saddr = (struct sockaddr_in6 *)i->ifa_addr;
// Ignore link-local addresses
if (saddr->sin6_scope_id)
{
spdlog::trace("Ignoring link-local address {}", ip_address_to_string(i->ifa_addr));
continue;
}
static const unsigned char localhost[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
static const unsigned char localhost_mapped[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x7f, 0, 0, 1};
if (memcmp(saddr->sin6_addr.s6_addr, localhost, 16) &&
memcmp(saddr->sin6_addr.s6_addr, localhost_mapped, 16))
{
saddr->sin6_port = htons(port);
int sock = mdns_socket_open_ipv6(saddr);
if (sock >= 0)
{
sockets.push_back(sock);
spdlog::info("Local IPv6 address: {}", ip_address_to_string(i->ifa_addr));
// interfaces_ipv6.push_back(i->ifa_name);
}
else
{
spdlog::info("Cannot open socket bound to {}: {}", ip_address_to_string(i->ifa_addr), strerror(errno));
}
}
}
else if (i->ifa_addr->sa_family == AF_INET)
{
// if (std::any_of(interfaces_ipv4.begin(), interfaces_ipv4.end(), [&](const auto & j) { return j == i->ifa_name; }))
// continue;
struct sockaddr_in * saddr = (struct sockaddr_in *)i->ifa_addr;
if (saddr->sin_addr.s_addr != htonl(INADDR_LOOPBACK))
{
saddr->sin_port = htons(port);
int sock = mdns_socket_open_ipv4(saddr);
if (sock >= 0)
{
sockets.push_back(sock);
spdlog::info("Local IPv4 address: {}", ip_address_to_string(i->ifa_addr));
// interfaces_ipv4.push_back(i->ifa_name);
}
else
{
spdlog::info("Cannot open socket bound to {}: {}", ip_address_to_string(i->ifa_addr), strerror(errno));
}
}
}
}
freeifaddrs(addresses);
pollfds.reserve(sockets.size() + 1);
int fds[2];
pipe(fds);
itc_fd = fds[1];
pollfds.push_back({.fd = fds[0], .events = POLLIN});
for (int socket: sockets)
pollfds.push_back(pollfd{.fd = socket, .events = POLLIN});
}
void close_client_sockets()
{
for (pollfd socket: pollfds)
mdns_socket_close(socket.fd);
pollfds.clear();
itc_fd = -1;
}
void log_entry(const cache_entry & entry)
{
std::string type;
std::string record;
if (std::holds_alternative<ptr>(entry.record))
{
type = "PTR";
record = std::get<ptr>(entry.record);
}
else if (std::holds_alternative<srv>(entry.record))
{
type = "SRV";
auto [addr, port] = std::get<srv>(entry.record);
record = addr + ":" + std::to_string(port);
}
else if (std::holds_alternative<a>(entry.record))
{
type = "A";
auto addr = std::get<a>(entry.record);
record = ip_address_to_string(addr);
}
else if (std::holds_alternative<aaaa>(entry.record))
{
type = "AAAA";
auto addr = std::get<aaaa>(entry.record);
record = ip_address_to_string(addr);
}
auto ttl = entry.timeout - steady_clock::now();
spdlog::info("{:40} {:4} {:40} TTL {}", entry.name, type, record, duration_cast<seconds>(ttl).count());
}
std::string_view record_type_name(mdns_record_type record_type)
{
switch (record_type)
{
case MDNS_RECORDTYPE_A:
return "A";
case MDNS_RECORDTYPE_AAAA:
return "AAAA";
case MDNS_RECORDTYPE_ANY:
return "ANY";
case MDNS_RECORDTYPE_PTR:
return "PTR";
case MDNS_RECORDTYPE_SRV:
return "SRV";
case MDNS_RECORDTYPE_TXT:
return "TXT";
default:
return "UNKNOWN";
}
}
void log_query(mdns_record_type record_type, std::string_view service_name)
{
spdlog::info("Sending query for {}, type {}", service_name, record_type_name(record_type));
}
void update(mdns_string_t entry, std::variant<ptr, srv, a, aaaa> record, int ttl)
{
auto now = steady_clock::now();
cache_entry e =
{
.timeout = now + seconds(ttl),
.name = std::string(entry.str, entry.length),
.record = std::move(record),
};
// log_entry(e);
if (ttl == 0)
{
std::erase_if(cache, [&e](const cache_entry & i) {
return i == e;
});
}
else
{
auto it = std::find(cache.begin(), cache.end(), e);
if (it == cache.end())
cache.push_back(std::move(e));
else
it->timeout = e.timeout;
}
}
static int query_callback(int sock, const sockaddr * from, size_t addrlen, mdns_entry_type_t entry, uint16_t query_id, uint16_t rtype, uint16_t rclass, uint32_t ttl, const void * data, size_t size, size_t name_offset, size_t name_length, size_t record_offset, size_t record_length, void * user_data)
{
dnssd_cache * self = (dnssd_cache *)user_data;
char namebuffer[256];
char entrybuffer[256];
sockaddr_in ipv4_buffer;
sockaddr_in6 ipv6_buffer;
mdns_string_t entrystr = mdns_string_extract(data, size, &name_offset, entrybuffer, sizeof(entrybuffer));
switch (rtype)
{
case MDNS_RECORDTYPE_PTR: {
auto ptr_record = mdns_record_parse_ptr(data, size, record_offset, record_length, namebuffer, sizeof(namebuffer));
self->update(entrystr, std::string{ptr_record.str, ptr_record.length}, ttl);
break;
}
case MDNS_RECORDTYPE_SRV: {
auto srv_record = mdns_record_parse_srv(data, size, record_offset, record_length, namebuffer, sizeof(namebuffer));
self->update(entrystr, srv{{srv_record.name.str, srv_record.name.length}, srv_record.port}, ttl);
break;
}
case MDNS_RECORDTYPE_A:
self->update(entrystr, mdns_record_parse_a(data, size, record_offset, record_length, &ipv4_buffer)->sin_addr, ttl);
break;
case MDNS_RECORDTYPE_AAAA:
self->update(entrystr, mdns_record_parse_aaaa(data, size, record_offset, record_length, &ipv6_buffer)->sin6_addr, ttl);
break;
default:
break;
}
return 0;
}
public:
void send_query(mdns_record_type record, std::string service_name)
{
auto now = steady_clock::now();
std::erase_if(last_queries, [now](const auto & q) {
return now - std::get<steady_clock::time_point>(q) > 5s;
});
for (const auto & [i, j, k]: last_queries)
{
if (j == record && k == service_name)
{
// spdlog::info("Query for {} {} already sent {}ms ago, skipping", service_name, record_type_name(record), duration_cast<milliseconds>(now - i).count());
return;
}
}
log_query(record, service_name);
std::array<uint8_t, 2048> buffer;
for(size_t i = 1; i < pollfds.size(); i++)
{
if (mdns_query_send(pollfds[i].fd, record, service_name.data(), service_name.size(), buffer.data(), buffer.size(), 0))
{
spdlog::error("Failed to send DNS-DS discovery for {}, record type {}: {}", service_name, record_type_name(record), strerror(errno));
}
}
last_queries.emplace_back(now, record, std::move(service_name));
}
void poll_response(milliseconds ms)
{
std::array<uint8_t, 2048> buffer;
int timeout = ms < 0ms ? -1 : std::min<int64_t>(std::numeric_limits<int>::max(), ms.count());
poll(pollfds.data(), pollfds.size(), timeout);
if (pollfds[0].revents & POLLIN)
{
::read(pollfds[0].fd, buffer.data(), buffer.size());
}
for(size_t i = 1; i < pollfds.size(); i++)
{
if (pollfds[i].revents & POLLIN)
{
mdns_query_recv(pollfds[i].fd, buffer.data(), buffer.size(), query_callback, this, 0);
}
}
}
void stop_polling()
{
char c = 0;
write(itc_fd, &c, 1);
}
template <typename T>
std::vector<std::pair<T, steady_clock::time_point>> read(const std::string & name)
{
std::vector<std::pair<T, steady_clock::time_point>> entries;
auto now = steady_clock::now();
std::erase_if(cache, [now](const cache_entry & i) {
return i.timeout < now;
});
for (const auto & i: cache)
{
if (i.name == name && std::holds_alternative<T>(i.record))
entries.emplace_back(std::get<T>(i.record), i.timeout);
}
return entries;
}
dnssd_cache()
{
open_client_sockets(5353);
}
dnssd_cache(const dnssd_cache &) = delete;
~dnssd_cache()
{
close_client_sockets();
}
};
void wivrn_discover::discover(std::string service_name)
{
cache->send_query(MDNS_RECORDTYPE_PTR, service_name);
milliseconds poll_timeout = poll_max_time;
std::vector<service> services_staging;
while (!quit)
{
poll_timeout = std::clamp(poll_timeout, poll_min_time, poll_max_time);
cache->poll_response(poll_timeout);
poll_timeout = poll_max_time;
auto now = steady_clock::now();
for (auto [ptr, ttl]: cache->read<dnssd_cache::ptr>(service_name))
{
bool srv_found = false;
auto srv_min_ttl = milliseconds::max();
service s;
// Remove the suffix
if (ptr.ends_with("." + service_name))
s.name = ptr.substr(0, ptr.size() - service_name.size() - 1);
else
s.name = ptr;
for (auto [srv, ttl]: cache->read<dnssd_cache::srv>(ptr))
{
srv_found = true;
srv_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), srv_min_ttl);
// Remove the suffix
if (srv.hostname.ends_with(".local."))
s.hostname = srv.hostname.substr(0, srv.hostname.size() - 7);
else if (srv.hostname.ends_with("."))
s.hostname = srv.hostname.substr(0, srv.hostname.size() - 1);
else
s.hostname = srv.hostname;
s.port = srv.port;
s.ttl = ttl;
bool address_found = false;
auto address_min_ttl = milliseconds::max();
for (auto [a, ttl]: cache->read<dnssd_cache::a>(srv.hostname))
{
address_found = true;
address_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), address_min_ttl);
// spdlog::info("PTR={}, SRV={}:{}, A={}, TTL={}ms", ptr, srv.hostname, srv.port, ip_address_to_string(a), ttl.count());
s.addresses.push_back(a);
}
for (auto [aaaa, ttl]: cache->read<dnssd_cache::aaaa>(srv.hostname))
{
address_found = true;
address_min_ttl = std::min(duration_cast<milliseconds>(ttl - now), address_min_ttl);
// spdlog::info("PTR={}, SRV={}:{}, AAAA={}, TTL={}ms", ptr, srv.hostname, srv.port, ip_address_to_string(aaaa), ttl.count());
s.addresses.push_back(aaaa);
}
if (!address_found || address_min_ttl < 5s)
{
cache->send_query(MDNS_RECORDTYPE_ANY, srv.hostname);
}
else // address_found && address_min_ttl >= 5s
{
poll_timeout = std::min(poll_timeout, address_min_ttl - 4s);
}
services_staging.push_back(s);
}
if (!srv_found || srv_min_ttl < 10s)
{
cache->send_query(MDNS_RECORDTYPE_SRV, ptr);
}
else // srv_found && srv_min_ttl >= 10s
{
poll_timeout = std::min(poll_timeout, srv_min_ttl - 9s);
}
}
std::lock_guard lock(mutex);
std::swap(services, services_staging);
services_staging.clear();
}
}
wivrn_discover::wivrn_discover(std::string service_name) : cache(std::make_unique<dnssd_cache>()), dnssd_thread(&wivrn_discover::discover, this, service_name)
{
}
wivrn_discover::~wivrn_discover()
{
quit = true;
cache->stop_polling();
dnssd_thread.join();
}
std::vector<wivrn_discover::service> wivrn_discover::get_services()
{
std::lock_guard lock(mutex);
auto now = steady_clock::now();
std::erase_if(services, [now](const service & i) {
return i.ttl < now;
});
return services;
}
// g++ wivrn_discover.cpp -I .. -g $(pkg-config spdlog --cflags --libs) -std=c++20 -DTEST && ./a.out
#ifdef TEST
int main()
{
wivrn_discover wd("_wivrn._tcp.local.");
while(true)
{
auto now = steady_clock::now();
auto services = wd.get_services();
spdlog::info("{} service(s) found", services.size());
for(auto& i: services)
{
spdlog::info(" {} at {}:{}, expires in {} s", i.name, i.hostname, i.port, duration_cast<seconds>(i.ttl - now).count());
for(auto& j: i.addresses)
{
std::visit([](const auto& addr){
spdlog::info(" {}", ip_address_to_string(addr));
}, j);
}
}
pollfd pfd{.fd = 0, .events = POLLIN};
poll(&pfd, 1, 1000);
if (pfd.revents & POLLIN)
break;
}
}
#endif
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include <memory>
#include <netinet/in.h>
#include <string>
#include <thread>
#include <variant>
#include <vector>
#include <chrono>
class dnssd_cache;
class wivrn_discover
{
public:
struct service
{
std::string name;
std::string hostname;
int port;
std::vector<std::variant<in_addr, in6_addr>> addresses;
std::chrono::steady_clock::time_point ttl;
};
static inline const std::chrono::milliseconds poll_min_time{500};
static inline const std::chrono::milliseconds poll_max_time{10000};
private:
std::unique_ptr<dnssd_cache> cache;
std::thread dnssd_thread;
std::mutex mutex;
std::vector<service> services;
std::atomic<bool> quit = false;
void discover(std::string service_name);
public:
wivrn_discover(std::string service_name = "_wivrn._tcp.local.");
wivrn_discover(const wivrn_discover &) = delete;
wivrn_discover(wivrn_discover &&) = delete;
wivrn_discover operator=(const wivrn_discover &) = delete;
wivrn_discover operator=(wivrn_discover &&) = delete;
~wivrn_discover();
std::vector<service> get_services();
};
-12
View File
@@ -95,20 +95,8 @@ enum video_codec
namespace from_headset
{
struct client_announce_packet
{
static const constexpr std::array<char, 5> magic_value = {'W', 'i', 'V', 'R', 'n'};
// Broadcast on the announce port, not typed
std::array<char, 5> magic;
std::string client_version;
uint64_t protocol_hash;
};
struct headset_info_packet
{
// First packet sent by the HMD on the control socket, not typed
uint32_t recommended_eye_width;
uint32_t recommended_eye_height;
std::vector<float> available_refresh_rates;
+49 -54
View File
@@ -83,6 +83,17 @@ void xrt::drivers::wivrn::UDP::connect(in6_addr address, int port)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::connect(in_addr address, int port)
{
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (::connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
throw std::system_error{errno, std::generic_category()};
}
void xrt::drivers::wivrn::UDP::subscribe_multicast(in6_addr address)
{
assert(IN6_IS_ADDR_MULTICAST(&address));
@@ -115,23 +126,28 @@ void xrt::drivers::wivrn::UDP::set_receive_buffer_size(int size)
setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
}
xrt::drivers::wivrn::TCP::TCP(int fd)
void xrt::drivers::wivrn::TCP::init()
{
this->fd = fd;
mutex = std::make_unique<std::mutex>();
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
mutex = std::make_unique<std::mutex>();
}
xrt::drivers::wivrn::TCP::TCP(int fd)
{
this->fd = fd;
init();
}
xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
mutex = std::make_unique<std::mutex>();
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -147,78 +163,57 @@ xrt::drivers::wivrn::TCP::TCP(in6_addr address, int port)
throw std::system_error{errno, std::generic_category()};
}
int nodelay = 1;
if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
xrt::drivers::wivrn::TCPListener::TCPListener(int port)
xrt::drivers::wivrn::TCP::TCP(in_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
int reuse_addr = 1;
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse_addr, sizeof(reuse_addr)) < 0)
sockaddr_in sa;
sa.sin_family = AF_INET;
sa.sin_addr = address;
sa.sin_port = htons(port);
if (connect(fd, (sockaddr *)&sa, sizeof(sa)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
sockaddr_in6 addr{};
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(port);
addr.sin6_addr = in6addr_any;
if (bind(fd, (sockaddr *)&addr, sizeof(addr)) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
int backlog = 1;
if (listen(fd, backlog) < 0)
{
::close(fd);
throw std::system_error{errno, std::generic_category()};
}
init();
}
std::pair<xrt::drivers::wivrn::TCP, sockaddr_in6> xrt::drivers::wivrn::TCPListener::accept()
{
sockaddr_in6 addr{};
socklen_t addrlen = sizeof(addr);
// std::pair<xrt::drivers::wivrn::deserialization_packet, sockaddr_in6> xrt::drivers::wivrn::UDP::receive_from_raw()
// {
// std::vector<uint8_t> buffer(2000);
//
// sockaddr_in6 addr;
// socklen_t addrlen = sizeof(addr);
//
// ssize_t received = recvfrom(fd, buffer.data(), buffer.size(), 0, (sockaddr *)&addr, &addrlen);
// if (received < 0)
// throw std::system_error{errno, std::generic_category()};
//
// buffer.resize(received);
//
// return {deserialization_packet{buffer}, addr};
// }
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
if (fd2 < 0)
throw std::system_error{errno, std::generic_category()};
return {TCP{fd2}, addr};
}
std::pair<xrt::drivers::wivrn::deserialization_packet, sockaddr_in6> xrt::drivers::wivrn::UDP::receive_from_raw()
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::UDP::receive_raw()
{
std::vector<uint8_t> buffer(2000);
sockaddr_in6 addr;
socklen_t addrlen = sizeof(addr);
ssize_t received = recvfrom(fd, buffer.data(), buffer.size(), 0, (sockaddr *)&addr, &addrlen);
ssize_t received = recv(fd, buffer.data(), buffer.size(), 0);
if (received < 0)
throw std::system_error{errno, std::generic_category()};
buffer.resize(received);
return {deserialization_packet{buffer}, addr};
}
xrt::drivers::wivrn::deserialization_packet xrt::drivers::wivrn::UDP::receive_raw()
{
return receive_from_raw().first;
return deserialization_packet{buffer};
}
void xrt::drivers::wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
+4 -20
View File
@@ -82,10 +82,10 @@ public:
UDP(UDP &&) = default;
deserialization_packet receive_raw();
std::pair<deserialization_packet, sockaddr_in6> receive_from_raw();
void send_raw(const std::vector<uint8_t> & data);
void connect(in6_addr address, int port);
void connect(in_addr address, int port);
void bind(int port);
void subscribe_multicast(in6_addr address);
void unsubscribe_multicast(in6_addr address);
@@ -97,8 +97,11 @@ class TCP : public socket_base
std::vector<uint8_t> buffer;
std::unique_ptr<std::mutex> mutex;
void init();
public:
TCP(in6_addr address, int port);
TCP(in_addr address, int port);
explicit TCP(int fd);
TCP(const TCP &) = delete;
TCP(TCP &&) = default;
@@ -107,16 +110,6 @@ public:
void send_raw(const std::vector<uint8_t> & data);
};
class TCPListener : public socket_base
{
public:
TCPListener(int port);
TCPListener(const TCPListener &) = delete;
TCPListener(TCPListener &&) = default;
std::pair<TCP, sockaddr_in6> accept();
};
template <typename Socket, typename ReceivedType, typename SentType>
class typed_socket : public Socket
{
@@ -135,15 +128,6 @@ public:
return packet.deserialize<ReceivedType>();
}
std::optional<std::pair<ReceivedType, sockaddr_in6>> receive_from()
{
auto [buffer, addr] = this->receive_from_raw();
if (buffer.empty())
return {};
return {deserialization_packet(std::move(buffer)).deserialize<ReceivedType>(), addr};
}
template <typename T = SentType, typename = std::enable_if_t<std::is_same_v<T, SentType>>>
void send(const T & data)
{