Add support for authentication and encryption

This commit is contained in:
Guillaume Meunier
2024-11-26 23:59:35 +01:00
committed by Patrick Nicolas
parent 447b77c35c
commit c6e773fd22
45 changed files with 1516 additions and 455 deletions
+4 -6
View File
@@ -127,14 +127,12 @@ int32_t wivrn::android::audio::microphone_data_cb(AAudioStream * stream, void *
size_t frame_size = AAudioStream_getChannelCount(stream) * sizeof(uint16_t);
wivrn::audio_data packet{
.timestamp = self->instance.now(),
.payload = std::span(audio_data, frame_size * num_frames),
};
try
{
self->session.send_control(packet);
self->session.send_control(wivrn::audio_data{
.timestamp = self->instance.now(),
.payload = std::span(audio_data, frame_size * num_frames),
});
}
catch (...)
{
+80 -6
View File
@@ -31,13 +31,17 @@
#include "stream.h"
#include "utils/overloaded.h"
#include "wivrn_client.h"
#include "wivrn_sockets.h"
#include "xr/passthrough.h"
#include "xr/space.h"
#include <algorithm>
#include <chrono>
#include <condition_variable>
#include <glm/gtc/matrix_access.hpp>
#include "wivrn_discover.h"
#include <cstdint>
#include <fstream>
#include <glm/gtc/quaternion.hpp>
#include <glm/matrix.hpp>
#include <magic_enum.hpp>
@@ -45,6 +49,7 @@
#include <simdjson.h>
#include <spdlog/spdlog.h>
#include <string>
#include <sys/poll.h>
#include <utils/ranges.h>
#include <vulkan/vulkan_raii.hpp>
@@ -53,6 +58,8 @@
#include <sys/socket.h>
#include <sys/types.h>
using namespace std::chrono_literals;
static bool force_autoconnect = false;
scenes::lobby::~lobby()
@@ -174,6 +181,19 @@ scenes::lobby::lobby()
spdlog::info("Composition layer color scale/bias NOT supported");
keyboard.set_layout(application::get_config().virtual_keyboard_layout);
const auto keypair_path = application::get_config_path() / "private_key.pem";
try
{
std::ifstream f{keypair_path};
keypair = crypto::key::from_private_key(std::string{(std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()});
}
catch (...)
{
keypair = crypto::key::generate_x448_keypair();
std::ofstream{keypair_path} << keypair.private_key();
spdlog::info("Generated X448 keypair");
}
}
static std::string ip_address_to_string(const in_addr & addr)
@@ -190,7 +210,7 @@ static std::string ip_address_to_string(const in6_addr & addr)
return buf;
}
std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service service, bool manual_connection)
std::unique_ptr<wivrn_session> scenes::lobby::connect_to_session(wivrn_discover::service service, bool manual_connection)
{
if (!manual_connection)
{
@@ -244,22 +264,76 @@ std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service servic
}
std::string error;
for (const auto & address: service.addresses)
for (const std::variant<in_addr, in6_addr> & address: service.addresses)
{
std::string address_string = std::visit([](auto & address) {
return ip_address_to_string(address);
},
address);
struct connection_cancelled
{};
try
{
spdlog::debug("Trying address {}", address_string);
spdlog::debug("Connection to {}", address_string);
return std::visit([port = service.port, tcp_only = service.tcp_only](auto & address) {
return std::make_unique<wivrn_session>(address, port, tcp_only);
return std::visit([this, port = service.port, tcp_only = service.tcp_only](auto & address) {
return std::make_unique<wivrn_session>(address, port, tcp_only, keypair, [&](int fd) {
auto request = pin_request.lock();
request->pin_requested = true;
request->pin_cancelled = false;
request->pin = "";
pin_buffer = "";
while (not request.wait_for(500ms, [&]() { return request->pin != "" or request->pin_cancelled; }))
{
pollfd fds{};
fds.events = POLLRDHUP;
fds.fd = fd;
int r = ::poll(&fds, 1, 0);
if (r < 0)
{
request->pin_requested = false;
throw std::system_error(errno, std::system_category());
}
if (fds.revents & (POLLHUP | POLLERR))
{
request->pin_requested = false;
throw std::runtime_error("Error on control socket");
}
if (fds.revents & POLLRDHUP)
{
request->pin_requested = false;
throw socket_shutdown{};
}
}
request->pin_requested = false;
if (request->pin_cancelled)
throw connection_cancelled{};
return request->pin;
});
},
address);
}
catch (connection_cancelled)
{
spdlog::info("Connection cancelled");
return nullptr;
}
catch (handshake_error & e)
{
spdlog::warn("Error during handshake to {} ({}): {}", service.hostname, address_string, e.what());
std::string txt = fmt::format(_F("Cannot connect to {} ({}): {}"), service.hostname, address_string, e.what());
throw std::runtime_error(txt);
}
catch (std::exception & e)
{
spdlog::warn("Cannot connect to {} ({}): {}", service.hostname, address_string, e.what());
@@ -376,7 +450,7 @@ void scenes::lobby::connect(const configuration::server_data & data)
async_error.reset();
async_session = utils::async<std::unique_ptr<wivrn_session>, std::string>(
[](auto token, wivrn_discover::service service, bool manual) {
[this](auto token, wivrn_discover::service service, bool manual) {
token.set_progress(_("Waiting for connection"));
return connect_to_session(service, manual);
},
+16
View File
@@ -21,16 +21,19 @@
#include "asset.h"
#include "configuration.h"
#include "crypto.h"
#include "render/scene_data.h"
#include "scene.h"
#include "scenes/hand_model.h"
#include "scenes/lobby_keyboard.h"
#include "utils/thread_safe.h"
#include "wifi_lock.h"
#include "wivrn_config.h"
#include "wivrn_discover.h"
#include <vulkan/vulkan_raii.hpp>
#include "xr/system.h"
#include <chrono>
#include <optional>
#include <vector>
@@ -130,6 +133,16 @@ class lobby : public scene_impl<lobby>
virtual_keyboard keyboard;
struct pin_request_data
{
bool pin_requested = false;
bool pin_cancelled = false;
std::string pin;
};
thread_safe_notifyable<pin_request_data> pin_request;
std::string pin_buffer;
void draw_features_status(XrTime predicted_display_time);
void gui_connecting();
void gui_server_list();
@@ -145,11 +158,14 @@ class lobby : public scene_impl<lobby>
void vibrate_on_hover();
void connect(const configuration::server_data & data);
std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service service, bool manual_connection);
std::optional<glm::vec3> check_recenter_gesture(const std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT> & joints);
std::optional<glm::vec3> check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position);
std::optional<glm::vec3> check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation);
crypto::key keypair;
public:
virtual ~lobby();
lobby();
+91 -48
View File
@@ -31,9 +31,11 @@
#include "stream.h"
#include "version.h"
#include <cassert>
#include <chrono>
#include <glm/gtc/quaternion.hpp>
#include <ranges>
#include <spdlog/fmt/fmt.h>
#include <string>
#include <utils/strings.h>
#include "IconsFontAwesome6.h"
@@ -165,56 +167,97 @@ void scenes::lobby::gui_connecting()
{
using constants::style::button_size;
std::string status;
if (next_scene)
ImVec2 size{600, 0};
auto pin_request = this->pin_request.lock();
std::string button_label = _("Cancel");
if (pin_request->pin_requested)
{
if (next_scene->current_state() == scenes::stream::state::stalled)
status = _("Video stream interrupted");
else if (server_name == "")
status = fmt::format(_F("Connection ready\nStart a VR application on your computer"));
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, {30, 30});
ImGui::PushFont(imgui_ctx->large_font);
ImGui::Text("%s", _S("Enter the PIN"));
if (ImGui::IsWindowAppearing())
ImGui::SetKeyboardFocusHere();
InputText("##PIN", pin_buffer, size, ImGuiInputTextFlags_CharsDecimal);
ImGui::PopFont();
ImGui::BeginDisabled(pin_buffer.size() != 6);
if (ImGui::Button("OK", button_size))
{
pin_request->pin = pin_buffer;
pin_request->pin_requested = false;
pin_request.notify_one();
}
vibrate_on_hover();
ImGui::EndDisabled();
ImGui::SameLine();
ImGui::Dummy({size.x - 2 * button_size.x - 2 * ImGui::GetStyle().ItemSpacing.x, 0});
ImGui::SameLine();
if (ImGui::Button(button_label.c_str(), button_size))
{
async_session.cancel();
next_scene.reset();
pin_request->pin_cancelled = true;
pin_request.notify_one();
ImGui::CloseCurrentPopup();
}
vibrate_on_hover();
ImGui::PopStyleVar(); // ItemSpacing
}
else
{
std::string status;
if (next_scene)
{
if (next_scene->current_state() == scenes::stream::state::stalled)
status = _("Video stream interrupted");
else if (server_name == "")
status = fmt::format(_F("Connection ready\nStart a VR application on your computer"));
else
status = fmt::format(_F("Connection ready\nStart a VR application on {}"), server_name);
}
else if (async_session.valid())
status = async_session.get_progress();
else if (async_error)
status = *async_error;
else
status = fmt::format(_F("Connection ready\nStart a VR application on {}"), server_name);
{
ImGui::CloseCurrentPopup();
return;
}
if (async_error)
button_label = _("Close");
ImGui::Dummy({1000, 1});
ImGui::PushFont(imgui_ctx->large_font);
if (server_name == "")
CenterTextH(fmt::format(_F("Connection")));
else
CenterTextH(fmt::format(_F("Connection to {}"), server_name));
ImGui::PopFont();
// ImGui::TextWrapped("%s", status.first.c_str());
ImGui::Text("%s", status.c_str());
ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - button_size.x - ImGui::GetStyle().WindowPadding.x);
if (ImGui::Button(button_label.c_str(), button_size))
{
async_session.cancel();
next_scene.reset();
pin_request->pin_cancelled = true;
ImGui::CloseCurrentPopup();
}
vibrate_on_hover();
}
else if (async_session.valid())
status = async_session.get_progress();
else if (async_error)
status = *async_error;
else
{
ImGui::CloseCurrentPopup();
return;
}
std::string button_label;
if (async_error)
button_label = _("Close");
else
button_label = _("Cancel");
ImGui::Dummy({1000, 1});
ImGui::PushFont(imgui_ctx->large_font);
if (server_name == "")
CenterTextH(fmt::format(_F("Connection")));
else
CenterTextH(fmt::format(_F("Connection to {}"), server_name));
ImGui::PopFont();
// ImGui::TextWrapped("%s", status.first.c_str());
ImGui::Text("%s", status.c_str());
ImGui::SetCursorPosX(ImGui::GetWindowContentRegionMax().x - button_size.x - ImGui::GetStyle().WindowPadding.x);
if (ImGui::Button(button_label.c_str(), button_size))
{
async_session.cancel();
next_scene.reset();
ImGui::CloseCurrentPopup();
}
vibrate_on_hover();
}
void scenes::lobby::gui_new_server()
@@ -457,7 +500,7 @@ void scenes::lobby::gui_server_list()
const auto & popup_layer = imgui_ctx->layers()[1];
const glm::vec2 popup_layer_center = popup_layer.vp_origin + popup_layer.vp_size / 2;
ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
ImGui::SetNextWindowPos({popup_layer_center.x, popup_layer_center.y}, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, constants::style::window_padding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, constants::style::window_rounding);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, constants::style::window_border_size);
+52 -46
View File
@@ -79,64 +79,65 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
std::shared_ptr<stream> self{new stream};
self->network_session = std::move(network_session);
from_headset::headset_info_packet info{};
self->network_session->send_control([&]() {
from_headset::headset_info_packet info{};
auto view = self->system.view_configuration_views(self->viewconfig)[0];
view = override_view(view, guess_model());
auto view = self->system.view_configuration_views(self->viewconfig)[0];
view = override_view(view, guess_model());
auto resolution_scale = application::get_config().resolution_scale;
auto resolution_scale = application::get_config().resolution_scale;
view.recommendedImageRectWidth *= resolution_scale;
view.recommendedImageRectHeight *= resolution_scale;
view.recommendedImageRectWidth *= resolution_scale;
view.recommendedImageRectHeight *= resolution_scale;
info.recommended_eye_width = view.recommendedImageRectWidth;
info.recommended_eye_height = view.recommendedImageRectHeight;
info.recommended_eye_width = view.recommendedImageRectWidth;
info.recommended_eye_height = view.recommendedImageRectHeight;
auto [flags, views] = self->session.locate_views(
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
self->instance.now(),
application::space(xr::spaces::view));
auto [flags, views] = self->session.locate_views(
XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO,
self->instance.now(),
application::space(xr::spaces::view));
assert(views.size() == info.fov.size());
assert(views.size() == info.fov.size());
for (auto [i, j]: std::views::zip(views, info.fov))
{
j = i.fov;
}
for (auto [i, j]: std::views::zip(views, info.fov))
{
j = i.fov;
}
const auto & config = application::get_config();
const auto & config = application::get_config();
if (self->instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
{
info.available_refresh_rates = self->session.get_refresh_rates();
if (std::ranges::find(info.available_refresh_rates, config.preferred_refresh_rate) != info.available_refresh_rates.end())
info.preferred_refresh_rate = config.preferred_refresh_rate;
else
info.preferred_refresh_rate = self->session.get_current_refresh_rate();
}
if (self->instance.has_extension(XR_FB_DISPLAY_REFRESH_RATE_EXTENSION_NAME))
{
info.available_refresh_rates = self->session.get_refresh_rates();
if (std::ranges::find(info.available_refresh_rates, config.preferred_refresh_rate) != info.available_refresh_rates.end())
info.preferred_refresh_rate = config.preferred_refresh_rate;
else
info.preferred_refresh_rate = self->session.get_current_refresh_rate();
}
if (info.preferred_refresh_rate == 0)
{
spdlog::warn("Unable to detect preferred refresh rate, using {}", guessed_fps);
info.preferred_refresh_rate = guessed_fps;
}
if (info.preferred_refresh_rate == 0)
{
spdlog::warn("Unable to detect preferred refresh rate, using {}", guessed_fps);
info.preferred_refresh_rate = guessed_fps;
}
if (info.available_refresh_rates.empty())
spdlog::warn("Unable to detect refresh rates");
if (info.available_refresh_rates.empty())
spdlog::warn("Unable to detect refresh rates");
info.hand_tracking = config.check_feature(feature::hand_tracking);
info.eye_gaze = config.check_feature(feature::eye_gaze);
info.face_tracking2_fb = config.check_feature(feature::face_tracking);
info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right);
info.passthrough = self->system.passthrough_supported() != xr::system::passthrough_type::no_passthrough;
info.hand_tracking = config.check_feature(feature::hand_tracking);
info.eye_gaze = config.check_feature(feature::eye_gaze);
info.face_tracking2_fb = config.check_feature(feature::face_tracking);
info.palm_pose = application::space(xr::spaces::palm_left) or application::space(xr::spaces::palm_right);
info.passthrough = self->system.passthrough_supported() != xr::system::passthrough_type::no_passthrough;
audio::get_audio_description(info);
if (not(config.check_feature(feature::microphone)))
info.microphone = {};
audio::get_audio_description(info);
if (not(config.check_feature(feature::microphone)))
info.microphone = {};
info.supported_codecs = decoder_impl::supported_codecs();
self->network_session->send_control(info);
info.supported_codecs = decoder_impl::supported_codecs();
return info;
}());
self->network_thread = utils::named_thread("network_thread", &stream::process_packets, self.get());
@@ -835,21 +836,26 @@ void scenes::stream::render(const XrFrameState & frame_state)
// Network operations may be blocking, do them once everything was submitted
{
// Keep a copy of the feedback packets as they can be modified if they're encrypted
std::vector<from_headset::feedback> feedbacks;
std::vector<serialization_packet> packets;
feedbacks.reserve(current_blit_handles.size());
packets.reserve(current_blit_handles.size());
for (const auto & handle: current_blit_handles)
{
if (handle)
{
auto & packet = packets.emplace_back();
wivrn_session::control_socket_t::serialize(packet, handle->feedback);
wivrn_session::control_socket_t::serialize(packet, feedbacks.emplace_back(handle->feedback));
}
}
if (not packets.empty())
{
try
{
network_session->send_control(std::span(packets));
network_session->send_control(std::move(packets));
}
catch (std::exception & e)
{
+1
View File
@@ -142,6 +142,7 @@ public:
void on_focused() override;
void on_unfocused() override;
void operator()(to_headset::crypto_handshake &&) {};
void operator()(to_headset::handshake &&) {};
void operator()(to_headset::video_stream_data_shard &&);
void operator()(to_headset::haptics &&);
+1 -1
View File
@@ -60,7 +60,7 @@ void scenes::stream::read_actions()
}
try
{
network_session->send_stream(inputs);
network_session->send_stream(std::move(inputs));
}
catch (std::exception & e)
{
+5 -5
View File
@@ -71,10 +71,10 @@ void scenes::stream::operator()(to_headset::video_stream_description && desc)
void scenes::stream::operator()(to_headset::timesync_query && query)
{
from_headset::timesync_response response{};
response.query = query.query;
response.response = instance.now();
network_session->send_stream(response);
network_session->send_stream(from_headset::timesync_response{
.query = query.query,
.response = instance.now(),
});
}
void scenes::stream::operator()(audio_data && data)
@@ -87,7 +87,7 @@ void scenes::stream::send_feedback(const wivrn::from_headset::feedback & feedbac
{
try
{
network_session->send_control(feedback);
network_session->send_control(wivrn::from_headset::feedback{feedback});
}
catch (std::exception & e)
{
+1 -1
View File
@@ -337,7 +337,7 @@ void scenes::stream::tracking()
wivrn_session::stream_socket_t::serialize(packets.emplace_back(), i);
}
network_session->send_stream(std::span(packets));
network_session->send_stream(std::move(packets));
t0 += tracking_period;
}
+84 -43
View File
@@ -18,6 +18,7 @@
*/
#include "wivrn_client.h"
#include "secrets.h"
#include "spdlog/common.h"
#include "wivrn_packets.h"
#include <arpa/inet.h>
@@ -39,6 +40,14 @@
using namespace std::chrono_literals;
const char * handshake_error::what() const noexcept
{
return message.c_str();
}
handshake_error::handshake_error(std::string_view message) :
message("Handshake error: " + std::string{message}) {}
namespace
{
template <typename T>
@@ -49,82 +58,114 @@ void init_stream(T & stream)
} // namespace
template <typename T>
void wivrn_session::handshake(T address, bool tcp_only)
void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter)
{
// FIXME this comment
// Wait for handshake on control socket,
// then send ours on stream or control socket,
// finally wait for second server handshake
pollfd fds{};
fds.events = POLLIN;
fds.fd = control.get_fd();
auto timeout = std::chrono::steady_clock::now() + 5s;
auto receive = [&](std::optional<std::chrono::seconds> timeout = std::nullopt) {
std::chrono::steady_clock::time_point timeout_abs{};
if (timeout)
timeout_abs = std::chrono::steady_clock::now() + *timeout;
// Loop because TCP socket may return partial data
while (true)
{
int r = ::poll(&fds, 1, 5000);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (r > 0 && (fds.revents & POLLIN))
while (true)
{
auto packet = control.receive();
if (not packet)
continue;
try
{
auto h = std::get<to_headset::handshake>(*packet);
if (h.stream_port > 0 && !tcp_only)
{
stream = decltype(stream)();
stream.connect(address, h.stream_port);
init_stream(stream);
}
break;
}
catch (std::exception & e)
{
spdlog::error("Error when expecting handshake: {}", e.what());
throw std::runtime_error("Invalid handshake received");
}
}
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(timeout_abs - std::chrono::steady_clock::now());
int r = ::poll(&fds, 1, std::max<int>(ms.count(), 100));
if (r < 0)
throw std::system_error(errno, std::system_category());
if (std::chrono::steady_clock::now() >= timeout)
throw std::runtime_error("No handshake received");
if (r > 0 && (fds.revents & POLLIN))
{
auto packet = control.receive();
if (not packet)
continue;
return std::move(*packet);
}
if (std::chrono::steady_clock::now() >= timeout_abs)
throw std::runtime_error("Timeout");
}
};
send_control(from_headset::crypto_handshake{.public_key = headset_keypair.public_key()});
to_headset::crypto_handshake crypto_handshake = std::get<to_headset::crypto_handshake>(receive(10s));
crypto::key server_key = crypto::key::from_public_key(crypto_handshake.public_key);
const std::string pin = crypto_handshake.pin_required ? pin_enter(control.get_fd()) : "000000";
spdlog::info("Using pin \"{}\"", pin);
secrets s{headset_keypair, server_key, pin};
control.set_aes_key_and_ivs(s.control_key, s.control_iv_to_headset, s.control_iv_from_headset);
// Confirm that encryption is set up
send_control(from_headset::crypto_handshake{});
to_headset::handshake h{std::get<to_headset::handshake>(receive(10s))};
if (h.stream_port > 0 && !tcp_only)
{
stream = decltype(stream)();
stream.set_aes_key_and_ivs(s.stream_key, s.stream_iv_header_to_headset, s.stream_iv_header_from_headset);
stream.connect(address, h.stream_port);
init_stream(stream);
}
// may be on control socket if forced TCP
send_stream(from_headset::handshake{});
// Wait for second handshake
auto timeout = std::chrono::steady_clock::now() + 10s;
while (true)
{
if (poll(
[](const auto && packet) { return std::is_same_v<std::remove_cvref_t<decltype(packet)>, to_headset::handshake>; },
std::chrono::milliseconds(100)))
if (poll([](const auto && packet) { return std::is_same_v<std::remove_cvref_t<decltype(packet)>, to_headset::handshake>; }, 100ms))
{
return;
}
if (std::chrono::steady_clock::now() >= timeout)
throw std::runtime_error("Failed to establish connection");
// If using stream socket, the handshake might be lost
if (stream)
{
stream.send(from_headset::handshake{});
}
}
}
wivrn_session::wivrn_session(in6_addr address, int port, bool tcp_only) :
wivrn_session::wivrn_session(in6_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address, port), stream(-1), address(address)
{
char buffer[100];
spdlog::info("Connection to {}:{}", inet_ntop(AF_INET6, &address, buffer, sizeof(buffer)), port);
handshake(address, tcp_only);
try
{
handshake(address, tcp_only, headset_keypair, pin_enter);
}
catch (std::exception & e)
{
throw handshake_error{e.what()};
}
}
wivrn_session::wivrn_session(in_addr address, int port, bool tcp_only) :
wivrn_session::wivrn_session(in_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter) :
control(address, port), stream(-1), address(address)
{
char buffer[100];
spdlog::info("Connection to {}:{}", inet_ntop(AF_INET, &address, buffer, sizeof(buffer)), port);
handshake(address, tcp_only);
try
{
handshake(address, tcp_only, headset_keypair, pin_enter);
}
catch (std::exception & e)
{
throw handshake_error{e.what()};
}
}
+14 -15
View File
@@ -19,12 +19,23 @@
#pragma once
#include "crypto.h"
#include "wivrn_packets.h"
#include "wivrn_sockets.h"
#include <chrono>
#include <poll.h>
using namespace wivrn;
class handshake_error : public std::exception
{
std::string message;
public:
const char * what() const noexcept override;
handshake_error(std::string_view message);
};
class wivrn_session
{
public:
@@ -36,13 +47,13 @@ private:
stream_socket_t stream;
template <typename T>
void handshake(T address, bool tcp_only);
void handshake(T address, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
public:
std::variant<in_addr, in6_addr> address;
wivrn_session(in6_addr address, int port, bool tcp_only);
wivrn_session(in_addr address, int port, bool tcp_only);
wivrn_session(in6_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(in_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function<std::string(int fd)> pin_enter);
wivrn_session(const wivrn_session &) = delete;
wivrn_session & operator=(const wivrn_session &) = delete;
@@ -52,12 +63,6 @@ public:
control.send(std::forward<T>(packet));
}
template <typename T>
void serialize_control(serialization_packet & p, const T & data)
{
control.serialize<T>(p, data);
}
template <typename T>
void send_stream(T && packet)
{
@@ -67,12 +72,6 @@ public:
control.send(std::forward<T>(packet));
}
template <typename T>
void serialize_stream(serialization_packet & p, const T & data)
{
stream.serialize<T>(p, data);
}
template <typename T>
int poll(T && visitor, std::chrono::milliseconds timeout)
{
+1
View File
@@ -31,6 +31,7 @@ add_library(wivrn-common-base STATIC
add_library(wivrn-common STATIC
crypto.cpp
secrets.cpp
wivrn_sockets.cpp
utils/xdg_base_directory.cpp
vk/allocation.cpp
+32
View File
@@ -0,0 +1,32 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "secrets.h"
#include <cstring>
#include <type_traits>
secrets::secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin)
{
std::vector<uint8_t> dh = crypto::key::diffie_hellman(my_key, peer_key);
std::vector<uint8_t> secret = crypto::argon2(pin, "saltsalt", dh, sizeof(*this));
static_assert(std::is_standard_layout_v<secrets>);
static_assert(std::has_unique_object_representations_v<secrets>);
memcpy(this, secret.data(), secret.size());
}
+38
View File
@@ -0,0 +1,38 @@
/*
* WiVRn VR streaming
* Copyright (C) 2022 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2022 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "crypto.h"
#include <array>
#include <cstdint>
#include <string>
struct secrets
{
std::array<std::uint8_t, 16> control_key;
std::array<std::uint8_t, 16> control_iv_to_headset;
std::array<std::uint8_t, 16> control_iv_from_headset;
std::array<std::uint8_t, 16> stream_key;
std::array<std::uint8_t, 8> stream_iv_header_to_headset;
std::array<std::uint8_t, 8> stream_iv_header_from_headset;
secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin);
};
+180
View File
@@ -0,0 +1,180 @@
/*
* WiVRn VR streaming
* Copyright (C) 2024 Guillaume Meunier <guillaume.meunier@centraliens.net>
* Copyright (C) 2024 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <condition_variable>
#include <mutex>
template <typename T>
class thread_safe_notifyable;
template <typename T, typename Mutex = std::mutex>
class locked
{
friend class thread_safe_notifyable<T>;
T & value;
std::unique_lock<Mutex> lock;
public:
locked(T & value, Mutex & mutex) :
value(value),
lock(mutex)
{}
T * operator->()
{
return &value;
}
const T * operator->() const
{
return &value;
}
T & operator*()
{
return value;
}
const T & operator*() const
{
return value;
}
};
template <typename T, typename Mutex = std::mutex>
class thread_safe
{
T value;
Mutex mutex;
public:
template <typename... Args>
thread_safe(Args &&... args) :
value(std::forward<Args>(args)...)
{}
locked<T, Mutex> lock()
{
return locked<T, Mutex>(value, mutex);
}
};
template <typename T>
class locked_notifiable
{
friend class thread_safe_notifyable<T>;
T & value;
std::unique_lock<std::mutex> lock;
std::condition_variable & cv;
public:
locked_notifiable(T & value, std::mutex & mutex, std::condition_variable & cv) :
value(value),
lock(mutex),
cv(cv)
{}
T * operator->()
{
return &value;
}
const T * operator->() const
{
return &value;
}
T & operator*()
{
return value;
}
const T & operator*() const
{
return value;
}
void notify_one() noexcept
{
cv.notify_one();
}
void notify_all() noexcept
{
cv.notify_all();
}
void wait()
{
cv.wait(lock);
}
template <class Predicate>
void wait(Predicate && pred)
{
cv.wait(lock, std::forward<Predicate>(pred));
}
template <class Rep, class Period>
std::cv_status wait_for(const std::chrono::duration<Rep, Period> & rel_time)
{
return cv.wait_for(lock, rel_time);
}
template <class Rep, class Period, class Predicate>
bool wait_for(const std::chrono::duration<Rep, Period> & rel_time, Predicate pred)
{
return cv.wait_for(lock, rel_time, pred);
}
template <class Clock, class Duration>
std::cv_status wait_until(const std::chrono::time_point<Clock, Duration> & abs_time)
{
return cv.wait_until(lock, abs_time);
}
template <class Clock, class Duration, class Predicate>
bool wait_until(const std::chrono::time_point<Clock, Duration> & abs_time, Predicate pred)
{
return cv.wait_until(lock, abs_time, pred);
}
};
template <typename T>
class thread_safe_notifyable : public thread_safe<T, std::mutex>
{
T value;
std::mutex mutex;
std::condition_variable cv;
public:
template <typename... Args>
thread_safe_notifyable(Args &&... args) :
thread_safe<T, std::mutex>(std::forward<Args>(args)...)
{}
locked_notifiable<T> lock()
{
return locked_notifiable<T>(value, mutex, cv);
}
};
+14 -4
View File
@@ -23,6 +23,7 @@
#include <chrono>
#include <cstdint>
#include <netinet/in.h>
#include <openssl/aes.h>
#include <optional>
#include <span>
#include <variant>
@@ -97,6 +98,11 @@ struct audio_data
namespace from_headset
{
struct crypto_handshake
{
std::string public_key; // In PEM format
std::string name;
};
struct headset_info_packet
{
@@ -255,11 +261,16 @@ struct battery
bool charging;
};
using packets = std::variant<headset_info_packet, feedback, audio_data, handshake, tracking, trackings, hand_tracking, inputs, timesync_response, battery>;
using packets = std::variant<crypto_handshake, headset_info_packet, feedback, audio_data, handshake, tracking, trackings, hand_tracking, inputs, timesync_response, battery>;
} // namespace from_headset
namespace to_headset
{
struct crypto_handshake
{
std::string public_key; // In PEM format
bool pin_required;
};
struct handshake
{
@@ -274,6 +285,7 @@ struct foveation_parameter_item
float a;
float b;
};
struct foveation_parameter
{
foveation_parameter_item x;
@@ -404,8 +416,6 @@ struct tracking_control
std::array<bool, size_t(id::last) + 1> enabled;
};
using packets = std::variant<handshake, audio_stream_description, video_stream_description, audio_data, video_stream_data_shard, haptics, timesync_query, tracking_control>;
using packets = std::variant<crypto_handshake, handshake, audio_stream_description, video_stream_description, audio_data, video_stream_data_shard, haptics, timesync_query, tracking_control>;
} // namespace to_headset
} // namespace wivrn
+30 -8
View File
@@ -98,9 +98,29 @@ size_t serialized_size(const T & x)
class deserialization_error : public std::runtime_error
{
static std::string hexdump(std::span<uint8_t> raw_data)
{
std::string s;
char buf[10];
for (int i = 0; i < raw_data.size(); i += 16)
{
sprintf(buf, "%04x ", i);
s += buf;
for (int j = i; j < std::min<int>(raw_data.size(), i + 16); j++)
{
sprintf(buf, "%02x ", (int)raw_data[j]);
s += buf;
}
s += "\n";
}
return s;
}
public:
deserialization_error() :
std::runtime_error("Deserialization error") {}
deserialization_error(std::span<uint8_t> raw_data) :
std::runtime_error("Deserialization error\n" + hexdump(raw_data)) {}
};
class serialization_packet
@@ -144,11 +164,11 @@ public:
serialization_traits<T>::serialize(value, *this);
}
operator const std::vector<std::span<uint8_t>> *()
operator std::vector<std::span<uint8_t>> *()
{
return &this->operator const std::vector<std::span<uint8_t>> &();
return &this->operator std::vector<std::span<uint8_t>> &();
}
operator const std::vector<std::span<uint8_t>> &()
operator std::vector<std::span<uint8_t>> &()
{
exp_spans.clear();
struct visitor
@@ -181,10 +201,12 @@ class deserialization_packet
std::span<uint8_t> buffer;
public:
std::span<uint8_t> initial_buffer;
deserialization_packet() = default;
explicit deserialization_packet(std::shared_ptr<uint8_t[]> memory, std::span<uint8_t> buffer) :
memory(memory),
buffer(buffer)
buffer(buffer),
initial_buffer(buffer)
{}
void read(void * data, size_t size)
@@ -211,7 +233,7 @@ public:
void check_remaining_size(size_t min_size) const
{
if (min_size > buffer.size_bytes())
throw deserialization_error();
throw deserialization_error(initial_buffer);
}
template <typename T>
@@ -773,7 +795,7 @@ struct serialization_traits<std::variant<T...>>
{
uint8_t type_index = packet.deserialize<uint8_t>();
if (type_index >= sizeof...(T))
throw deserialization_error();
throw deserialization_error(packet.initial_buffer);
return deserialize_aux(packet, type_index, std::make_index_sequence<sizeof...(T)>());
}
-6
View File
@@ -28,12 +28,6 @@ namespace wivrn
// contains the data referenced by spans
struct data_holder
{
data_holder() = default;
data_holder(const data_holder &) = delete;
data_holder(data_holder &&) = default;
data_holder & operator=(const data_holder &) = delete;
data_holder & operator=(data_holder &&) = default;
std::shared_ptr<uint8_t[]> c;
};
+173 -54
View File
@@ -19,6 +19,8 @@
#include "wivrn_sockets.h"
#include "crypto.h"
#include <algorithm>
#include <arpa/inet.h>
#include <cassert>
#include <memory>
@@ -26,12 +28,16 @@
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <string.h>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <system_error>
#include <unistd.h>
thread_local crypto::encrypt_context wivrn::UDP::encrypter{EVP_aes_128_ctr()};
std::atomic<uint64_t> wivrn::UDP::iv_counter;
const char * wivrn::invalid_packet::what() const noexcept
{
return "Invalid packet";
@@ -63,6 +69,7 @@ wivrn::fd_base::~fd_base()
wivrn::UDP::UDP()
{
fd = socket(AF_INET6, SOCK_DGRAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -175,6 +182,7 @@ wivrn::TCP::TCP(int fd)
wivrn::TCP::TCP(in6_addr address, int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -196,6 +204,7 @@ wivrn::TCP::TCP(in6_addr address, int port)
wivrn::TCP::TCP(in_addr address, int port)
{
fd = socket(AF_INET, SOCK_STREAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd < 0)
throw std::system_error{errno, std::generic_category()};
@@ -214,10 +223,6 @@ wivrn::TCP::TCP(in_addr address, int port)
init();
}
wivrn::TCPListener::TCPListener()
{
}
wivrn::TCPListener::TCPListener(int port)
{
fd = socket(AF_INET6, SOCK_STREAM, 0);
@@ -271,8 +276,25 @@ std::pair<wivrn::deserialization_packet, sockaddr_in6> wivrn::UDP::receive_from_
bytes_received_ += received;
auto tmp = buffer.get();
return {deserialization_packet{std::move(buffer), std::span(tmp, received)}, addr};
std::span message{buffer.get(), (size_t)received};
if (encrypted)
{
// Not big enough for the IV: drop the packet
if (received < sizeof(uint64_t))
return {};
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), buffer.get(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), recv_iv_header.data(), recv_iv_header.size());
message = message.subspan(sizeof(uint64_t));
decrypter.set_iv(full_iv);
decrypter.decrypt_in_place(message);
}
return {deserialization_packet{std::move(buffer), message}, addr};
}
wivrn::deserialization_packet wivrn::UDP::receive_pending()
@@ -311,6 +333,7 @@ wivrn::deserialization_packet wivrn::UDP::receive_raw()
.iov_base = buffer.get() + message_size * i,
.iov_len = message_size,
});
mmsgs.push_back(
{
.msg_hdr = {
@@ -328,66 +351,114 @@ wivrn::deserialization_packet wivrn::UDP::receive_raw()
throw socket_shutdown();
messages.reserve(received);
for (int i = received - 1; i > 0; --i)
for (int i = received - 1; i >= 0; --i)
{
messages.emplace_back(
(uint8_t *)iovecs[i].iov_base,
mmsgs[i].msg_len);
bytes_received_ += mmsgs[i].msg_len;
std::span<uint8_t> message{(uint8_t *)iovecs[i].iov_base, mmsgs[i].msg_len};
assert(message.data() != nullptr);
if (encrypted)
{
// Not big enough for the IV: drop the packet
if (message.size() < sizeof(uint64_t))
throw std::runtime_error("Packet too small: " + std::to_string(message.size()));
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), message.data(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), recv_iv_header.data(), recv_iv_header.size());
message = message.subspan(sizeof(uint64_t));
decrypter.set_iv(full_iv);
decrypter.decrypt_in_place(message);
}
if (i == 0)
return deserialization_packet{buffer, message};
messages.push_back(message);
}
return deserialization_packet{buffer, std::span(buffer.get(), mmsgs[0].msg_len)};
__builtin_unreachable();
}
void wivrn::UDP::send_raw(const std::vector<uint8_t> & data)
void wivrn::UDP::send_raw(serialization_packet && packet)
{
ssize_t sent = ::send(fd, data.data(), data.size(), 0);
if (sent < 0)
throw std::system_error{errno, std::generic_category()};
thread_local std::vector<iovec> iovecs;
iovecs.clear();
bytes_sent_ += sent;
}
std::vector<std::span<uint8_t>> & data = packet;
uint64_t counter;
if (encrypted)
{
counter = iv_counter.fetch_add(1);
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), &counter, sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), send_iv_header.data(), send_iv_header.size());
iovecs.emplace_back(&counter, sizeof(uint64_t));
encrypter.set_key_and_iv(key, full_iv);
encrypter.encrypt_in_place(data);
}
void wivrn::UDP::send_raw(const std::vector<std::span<uint8_t>> & data)
{
thread_local std::vector<iovec> spans;
spans.clear();
for (const auto & span: data)
spans.emplace_back((void *)span.data(), span.size());
iovecs.emplace_back(span.data(), span.size());
if (::writev(fd, spans.data(), spans.size()) < 0)
if (::writev(fd, iovecs.data(), iovecs.size()) < 0)
throw std::system_error{errno, std::generic_category()};
}
void wivrn::UDP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data)
void wivrn::UDP::send_many_raw(std::vector<serialization_packet> && packets)
{
thread_local std::vector<iovec> iovecs;
thread_local std::vector<mmsghdr> mmsgs;
thread_local std::vector<uint64_t> iv_counters;
iovecs.clear();
mmsgs.clear();
for (const auto & message: data)
iv_counters.clear();
iv_counters.reserve(packets.size());
for (serialization_packet & packet: packets)
{
for (const auto & span: *message)
std::vector<std::span<uint8_t>> & data = packet;
if (encrypted)
{
iovecs.push_back(
{
.iov_base = span.data(),
.iov_len = span.size_bytes(),
});
iv_counters.push_back(iv_counter.fetch_add(1));
std::array<uint8_t, 16> full_iv;
memcpy(full_iv.data(), &iv_counters.back(), sizeof(uint64_t)); // TODO: endianness?
memcpy(full_iv.data() + sizeof(uint64_t), send_iv_header.data(), send_iv_header.size());
iovecs.emplace_back(&iv_counters.back(), sizeof(uint64_t));
encrypter.set_key_and_iv(key, full_iv);
encrypter.encrypt_in_place(data);
}
for (const auto & span: data)
{
iovecs.emplace_back(span.data(), span.size_bytes());
}
if (encrypted)
mmsgs.push_back({.msg_hdr = {.msg_iovlen = data.size() + 1}});
else
mmsgs.push_back({.msg_hdr = {.msg_iovlen = data.size()}});
}
size_t i = 0;
for (const auto & message: data)
for (size_t i = 0, j = 0; i < packets.size(); ++i)
{
mmsgs.push_back(
{
.msg_hdr = {
.msg_iov = &iovecs[i],
.msg_iovlen = message->size(),
},
});
i += message->size();
mmsgs[i].msg_hdr.msg_iov = &iovecs[j];
j += mmsgs[i].msg_hdr.msg_iovlen;
}
// sendmmsg may not send all messages, just consider them as lost for UDP
if (sendmmsg(fd, mmsgs.data(), mmsgs.size(), 0) < 0)
throw std::system_error{errno, std::generic_category()};
@@ -422,18 +493,24 @@ wivrn::deserialization_packet wivrn::TCP::receive_raw()
capacity_left = new_size - data.size_bytes();
}
ssize_t received = recv(fd, &*data.end(), capacity_left, MSG_DONTWAIT);
ssize_t received_size = recv(fd, &*data.end(), capacity_left, MSG_DONTWAIT);
if (received < 0)
if (received_size < 0)
throw std::system_error{errno, std::generic_category()};
if (received == 0)
if (received_size == 0)
throw socket_shutdown{};
bytes_received_ += received;
bytes_received_ += received_size;
data = std::span(data.data(), data.size() + received);
capacity_left -= received;
if (decrypter)
{
std::span<uint8_t> received_data{&*data.end(), (size_t)received_size};
decrypter.decrypt_in_place(received_data);
}
data = std::span(data.data(), data.size() + received_size);
capacity_left -= received_size;
if (data.size_bytes() < sizeof(uint16_t))
return {};
@@ -466,14 +543,16 @@ wivrn::deserialization_packet wivrn::TCP::receive_pending()
return deserialization_packet{buffer, span};
}
void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
void wivrn::TCP::send_raw(serialization_packet && packet)
{
thread_local std::vector<iovec> iovecs;
iovecs.clear();
std::vector<std::span<uint8_t>> & data = packet;
uint16_t size = 0;
iovecs.emplace_back(&size, sizeof(size));
for (const auto & span: spans)
for (const auto & span: data)
{
size += span.size_bytes();
iovecs.emplace_back(span.data(), span.size_bytes());
@@ -490,9 +569,14 @@ void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
};
std::lock_guard lock(*mutex);
if (encrypter)
{
data.insert(data.begin(), {(uint8_t *)&size, sizeof(size)});
encrypter.encrypt_in_place(data);
}
while (true)
{
const auto & data = spans[0];
ssize_t sent = ::sendmsg(fd, &hdr, MSG_NOSIGNAL);
if (sent == 0)
@@ -517,22 +601,30 @@ void wivrn::TCP::send_raw(const std::vector<std::span<uint8_t>> & spans)
}
}
void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data)
void wivrn::TCP::send_many_raw(std::vector<serialization_packet> && packets)
{
thread_local std::vector<iovec> iovecs;
thread_local std::vector<uint16_t> sizes;
thread_local std::vector<std::span<uint8_t>> spans;
iovecs.clear();
sizes.clear();
spans.clear();
sizes.reserve(data.size());
for (const auto & spans: data)
sizes.reserve(packets.size());
for (serialization_packet & packet: packets)
{
std::vector<std::span<uint8_t>> & data = packet;
auto & size = sizes.emplace_back(0);
iovecs.emplace_back(&size, sizeof(size));
for (const auto & span: *spans)
spans.emplace_back((uint8_t *)&size, sizeof(size));
for (const auto & span: data)
{
size += span.size_bytes();
iovecs.emplace_back(span.data(), span.size_bytes());
spans.emplace_back(span.data(), span.size_bytes());
}
}
@@ -547,6 +639,11 @@ void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *
};
std::lock_guard lock(*mutex);
if (encrypter)
{
encrypter.encrypt_in_place(spans);
}
while (true)
{
ssize_t sent = ::sendmsg(fd, &hdr, MSG_NOSIGNAL);
@@ -572,3 +669,25 @@ void wivrn::TCP::send_many_raw(std::span<const std::vector<std::span<uint8_t>> *
hdr.msg_iov[0].iov_len -= sent;
}
}
void wivrn::UDP::set_aes_key_and_ivs(std::span<std::uint8_t, 16> key_, std::span<std::uint8_t, 8> recv_iv_header_, std::span<std::uint8_t, 8> send_iv_header_)
{
decrypter = crypto::decrypt_context{EVP_aes_128_ctr()};
decrypter.set_key(key_);
std::ranges::copy(key_, key.begin());
std::ranges::copy(recv_iv_header_, recv_iv_header.begin());
std::ranges::copy(send_iv_header_, send_iv_header.begin());
encrypted = true;
}
void wivrn::TCP::set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 16> recv_iv, std::span<std::uint8_t, 16> send_iv)
{
encrypter = crypto::encrypt_context{EVP_aes_128_ctr()};
encrypter.set_key(key);
encrypter.set_iv(send_iv);
decrypter = crypto::decrypt_context{EVP_aes_128_ctr()};
decrypter.set_key(key);
decrypter.set_iv(recv_iv);
}
+37 -13
View File
@@ -19,11 +19,13 @@
#pragma once
#include "crypto.h"
#include "wivrn_serialization.h"
#include <atomic>
#include <cassert>
#include <exception>
#include <fcntl.h>
#include <memory>
#include <mutex>
#include <netinet/ip.h>
@@ -103,6 +105,16 @@ class UDP : public fd_base
std::shared_ptr<uint8_t[]> buffer;
std::vector<std::span<uint8_t>> messages;
crypto::decrypt_context decrypter;
static thread_local crypto::encrypt_context encrypter;
static std::atomic<uint64_t> iv_counter;
static_assert(sizeof(iv_counter) == 8);
bool encrypted = false;
std::array<uint8_t, 16> key;
std::array<uint8_t, 16 - sizeof(iv_counter)> recv_iv_header;
std::array<uint8_t, 16 - sizeof(iv_counter)> send_iv_header;
public:
UDP();
explicit UDP(int fd);
@@ -110,9 +122,8 @@ public:
deserialization_packet receive_raw();
deserialization_packet receive_pending();
std::pair<wivrn::deserialization_packet, sockaddr_in6> receive_from_raw();
void send_raw(const std::vector<uint8_t> & data);
void send_raw(const std::vector<std::span<uint8_t>> & data);
void send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data);
void send_raw(serialization_packet && packet);
void send_many_raw(std::vector<serialization_packet> && packets);
void connect(in6_addr address, int port);
void connect(in_addr address, int port);
@@ -122,6 +133,8 @@ public:
void set_receive_buffer_size(int size);
void set_send_buffer_size(int size);
void set_tos(int type_of_service);
void set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 8> recv_iv_header, std::span<std::uint8_t, 8> send_iv_header);
};
class TCP : public fd_base
@@ -133,15 +146,21 @@ class TCP : public fd_base
void init();
crypto::decrypt_context decrypter;
crypto::encrypt_context encrypter;
public:
TCP() = default;
TCP(in6_addr address, int port);
TCP(in_addr address, int port);
explicit TCP(int fd);
deserialization_packet receive_raw();
deserialization_packet receive_pending();
void send_raw(const std::vector<std::span<uint8_t>> & data);
void send_many_raw(std::span<const std::vector<std::span<uint8_t>> *> data);
void send_raw(serialization_packet && packet);
void send_many_raw(std::vector<serialization_packet> && packets);
void set_aes_key_and_ivs(std::span<std::uint8_t, 16> key, std::span<std::uint8_t, 16> recv_iv, std::span<std::uint8_t, 16> send_iv);
};
using UnixDatagram = UDP;
@@ -149,7 +168,7 @@ using UnixDatagram = UDP;
class TCPListener : public fd_base
{
public:
TCPListener();
TCPListener() = default;
TCPListener(int port);
template <typename T = TCP>
@@ -160,6 +179,7 @@ public:
socklen_t addrlen = sizeof(addr);
int fd2 = ::accept(fd, (sockaddr *)&addr, &addrlen);
fcntl(fd, F_SETFD, FD_CLOEXEC);
if (fd2 < 0)
throw std::system_error{errno, std::generic_category()};
@@ -185,6 +205,10 @@ struct Index<T, std::tuple<U, Types...>>
{
static const std::size_t value = 1 + Index<T, std::tuple<Types...>>::value;
};
template <typename T>
concept not_lvalue_reference = !std::is_lvalue_reference_v<T>;
} // namespace details
template <typename Socket, typename ReceivedType, typename... VariantTypes>
@@ -224,21 +248,21 @@ public:
p.serialize(data);
}
template <typename T>
void send(const T & data)
template <details::not_lvalue_reference T>
void send(T && data)
{
thread_local serialization_packet p;
serialize(p, data);
this->send_raw(p);
this->send_raw(std::move(p));
}
void send(const std::span<serialization_packet> & packets)
void send(std::vector<serialization_packet> && packets)
{
thread_local std::vector<const std::vector<std::span<uint8_t>> *> data;
thread_local std::vector<serialization_packet> data;
data.clear();
for (auto & packet: packets)
for (serialization_packet & packet: packets)
data.emplace_back(packet);
this->send_many_raw(data);
this->send_many_raw(std::move(data));
}
};
+12
View File
@@ -138,6 +138,9 @@ main_window::main_window()
connect(server_interface, &wivrn_server::supportedCodecsChanged, this, &main_window::on_supported_codecs_changed);
connect(server_interface, &wivrn_server::steamCommandChanged, this, &main_window::on_steam_command_changed);
connect(server_interface, &wivrn_server::pinChanged, this, &main_window::on_pin_changed);
on_pin_changed(server_interface->pin());
connect(ui->button_start, &QPushButton::clicked, this, &main_window::start_server);
connect(ui->button_stop, &QPushButton::clicked, this, &main_window::stop_server);
connect(ui->button_settings, &QPushButton::clicked, this, &main_window::on_action_settings);
@@ -168,6 +171,9 @@ main_window::main_window()
ui->banner_capsysnice->hide();
#endif
// TODO implement this
ui->button_known_headsets->hide();
retranslate();
}
@@ -528,6 +534,12 @@ void main_window::on_steam_command_changed(QString value)
ui->label_steam_command->setText(value);
}
void main_window::on_pin_changed(QString value)
{
ui->widget_authentication->setVisible(value != "");
ui->label_pin->setText(value);
}
void main_window::on_server_finished(int exit_code, QProcess::ExitStatus status)
{
qDebug() << "Server exited with code" << exit_code << ", status" << status;
+1
View File
@@ -100,6 +100,7 @@ private:
void on_speaker_changed();
void on_supported_codecs_changed(QStringList value);
void on_steam_command_changed(QString value);
void on_pin_changed(QString value);
void on_android_device_list_changed(const std::vector<adb::device> &);
+55 -3
View File
@@ -14,7 +14,7 @@
<string>WiVRn dashboard</string>
</property>
<property name="windowIcon">
<iconset resource="../wivrn-dashboard.qrc">
<iconset>
<normaloff>:/images/wivrn.svg</normaloff>:/images/wivrn.svg</iconset>
</property>
<widget class="QWidget" name="centralwidget">
@@ -79,7 +79,7 @@ border-radius: 5px;
<string/>
</property>
<property name="pixmap">
<pixmap resource="../wivrn-dashboard.qrc">:/images/wivrn.svg</pixmap>
<pixmap>:/images/wivrn.svg</pixmap>
</property>
</widget>
</item>
@@ -136,7 +136,7 @@ border-radius: 5px;
<string/>
</property>
<property name="pixmap">
<pixmap resource="../wivrn-dashboard.qrc">:/images/wivrn.svg</pixmap>
<pixmap>:/images/wivrn.svg</pixmap>
</property>
</widget>
</item>
@@ -178,6 +178,58 @@ border-radius: 5px;
</item>
</layout>
</item>
<item>
<layout class="QHBoxLayout" name="layout_authentication" stretch=""/>
</item>
<item>
<widget class="QWidget" name="widget_authentication" native="true">
<layout class="QHBoxLayout" name="horizontalLayout_8" stretch="0,1,0">
<property name="leftMargin">
<number>0</number>
</property>
<property name="topMargin">
<number>0</number>
</property>
<property name="rightMargin">
<number>0</number>
</property>
<property name="bottomMargin">
<number>0</number>
</property>
<item>
<widget class="QLabel" name="label_16">
<property name="font">
<font>
<pointsize>14</pointsize>
</font>
</property>
<property name="text">
<string>PIN:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_pin">
<property name="font">
<font>
<pointsize>14</pointsize>
</font>
</property>
<property name="text">
<string notr="true">000000</string>
</property>
</widget>
</item>
<item>
<widget class="QPushButton" name="button_known_headsets">
<property name="text">
<string>Known headsets</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
+5
View File
@@ -102,6 +102,11 @@ void wivrn_server::on_server_properties_changed(const QString & interface_name,
m_jsonConfiguration = changed_properties["JsonConfiguration"].toString();
}
if (changed_properties.contains("Pin"))
{
pinChanged(m_pin = changed_properties["Pin"].toString());
}
if (changed_properties.contains("RecommendedEyeSize"))
{
const auto arg = qvariant_cast<QDBusArgument>(changed_properties["RecommendedEyeSize"]);
+9
View File
@@ -47,6 +47,7 @@ public:
Q_PROPERTY(bool serverRunning READ isServerRunning NOTIFY serverRunningChanged)
Q_PROPERTY(bool headsetConnected READ isHeadsetConnected NOTIFY headsetConnectedChanged)
Q_PROPERTY(QString jsonConfiguration READ jsonConfiguration WRITE setJsonConfiguration)
Q_PROPERTY(QString pin READ pin NOTIFY pinChanged)
// Headset information, valid only if HeadsetConnected is true
Q_PROPERTY(QSize recommendedEyeSize READ recommendedEyeSize NOTIFY recommendedEyeSizeChanged)
@@ -83,6 +84,11 @@ public:
void setJsonConfiguration(QString);
QString pin() const
{
return m_pin;
}
QSize recommendedEyeSize() const
{
return m_recommendedEyeSize;
@@ -163,6 +169,8 @@ private:
bool m_serverRunning{};
bool m_headsetConnected{};
QString m_jsonConfiguration{};
QString m_pin{};
QSize m_recommendedEyeSize{};
std::vector<float> m_availableRefreshRates{};
float m_preferredRefreshRate{};
@@ -180,6 +188,7 @@ private:
Q_SIGNALS:
void serverRunningChanged(bool);
void headsetConnectedChanged(bool);
void pinChanged(QString);
void recommendedEyeSizeChanged(QSize);
void availableRefreshRatesChanged(const std::vector<float> &);
+5
View File
@@ -125,6 +125,11 @@ wizard::wizard() :
});
ui->label_steam_command->setText(server->steamCommand());
connect(server, &wivrn_server::pinChanged, this, [this](QString value) {
ui->label_pin->setText(value);
});
ui->label_pin->setText(server->pin());
setPixmap(WatermarkPixmap, QPixmap(":/images/wivrn.svg"));
for (const headset & i: headsets_info)
{
+22
View File
@@ -440,6 +440,28 @@
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_3">
<property name="text">
<string>Use the following PIN to connect your headset:</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_pin">
<property name="font">
<font>
<pointsize>14</pointsize>
</font>
</property>
<property name="text">
<string notr="true">000000</string>
</property>
<property name="margin">
<number>12</number>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="label_10">
<property name="text">
+13
View File
@@ -28,6 +28,13 @@
<interface name="io.github.wivrn.Server">
<method name="Disconnect"/>
<method name="Quit"/>
<method name="RevokeKey">
<arg type="s" name="PublicKey"/>
</method>
<method name="RenameKey">
<arg type="s" name="PublicKey"/>
<arg type="s" name="Name"/>
</method>
<property name="HeadsetConnected" type="b" access="read"/>
<property name="SteamCommand" type="s" access="read"/>
@@ -52,5 +59,11 @@
<property name="EyeGaze" type="b" access="read"/>
<property name="FaceTracking" type="b" access="read"/>
<property name="SupportedCodecs" type="as" access="read"/>
<property name="Pin" type="s" access="read"/>
<property name="KnownKeys" type="a(ss)" access="read">
<annotation name="org.qtproject.QtDBus.QtTypeName" value="QList&lt;std::pair&lt;QString,QString&gt;&gt;"/>
<!-- first: name, second: public key -->
</property>
</interface>
</node>
+2 -2
View File
@@ -32,7 +32,7 @@ static void handle_event_from_main_loop(to_monado::disconnect)
std::unique_ptr<wivrn::TCP> wivrn::accept_connection(int watch_fd, std::function<bool()> quit)
{
wivrn_ipc_socket_monado->send(from_monado::headsdet_disconnected{});
wivrn_ipc_socket_monado->send(from_monado::headset_disconnected{});
wivrn::TCPListener listener(wivrn::default_port);
@@ -55,7 +55,7 @@ std::unique_ptr<wivrn::TCP> wivrn::accept_connection(int watch_fd, std::function
if (fds[1].revents & POLLIN)
{
wivrn_ipc_socket_monado->send(from_monado::headsdet_connected{});
wivrn_ipc_socket_monado->send(from_monado::headset_connected{});
return std::make_unique<wivrn::TCP>(listener.accept().first);
}
+6 -7
View File
@@ -305,15 +305,14 @@ void pipewire_device::speaker_process(void * self_v)
if (not data.data)
return;
audio_data packet{
.timestamp = self->session.get_offset().to_headset(os_monotonic_get_ns()),
.payload = std::span(
(uint8_t *)data.data + data.chunk->offset,
data.chunk->size),
};
try
{
self->session.send_control(packet);
self->session.send_control(audio_data{
.timestamp = self->session.get_offset().to_headset(os_monotonic_get_ns()),
.payload = std::span(
(uint8_t *)data.data + data.chunk->offset,
data.chunk->size),
});
}
catch (std::exception & e)
{
+4 -4
View File
@@ -301,7 +301,6 @@ struct pulse_device : public audio_device
// use buffers of up to 2ms
// read buffers must be smaller than buffer size on client or we will discard chunks often
const size_t buffer_size = (desc.speaker->sample_rate * sample_size * 2) / 1000;
wivrn::audio_data packet;
std::vector<uint8_t> buffer(buffer_size, 0);
size_t remainder = 0;
@@ -338,12 +337,13 @@ struct pulse_device : public audio_device
size += remainder; // full size of available data
remainder = size % sample_size; // data to keep for next iteration
size -= remainder; // size of data to send
packet.payload = std::span<uint8_t>(buffer.begin(), size);
packet.timestamp = session.get_offset().to_headset(os_monotonic_get_ns());
try
{
session.send_control(packet);
session.send_control(wivrn::audio_data{
.timestamp = session.get_offset().to_headset(os_monotonic_get_ns()),
.payload = std::span<uint8_t>(buffer.begin(), size),
});
}
catch (std::exception & e)
{
+97 -2
View File
@@ -17,16 +17,18 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <filesystem>
#include <fstream>
#define JSON_DISABLE_ENUM_SERIALIZATION 1
#ifdef JSON_DIAGNOSTICS
#undef JSON_DIAGNOSTICS
#endif
#define JSON_DIAGNOSTICS 1
#include <algorithm>
#include <filesystem>
#include <fstream>
#include <nlohmann/json.hpp>
#include <random>
#include <stdlib.h>
#include <string>
#include "util/u_logging.h"
@@ -34,6 +36,7 @@
#include "utils/xdg_base_directory.h"
static std::filesystem::path config_file = xdg_config_home() / "wivrn" / "config.json";
static std::filesystem::path known_keys_file = xdg_config_home() / "wivrn" / "known_keys.json";
static std::filesystem::path cookie_file = xdg_config_home() / "wivrn" / "cookie";
namespace wivrn
@@ -181,4 +184,96 @@ std::string server_cookie()
return buffer;
}
}
std::vector<headset_key> known_keys()
{
if (not std::filesystem::exists(known_keys_file))
return {};
try
{
std::ifstream file(known_keys_file);
std::vector<headset_key> keys;
auto json = nlohmann::json::parse(file);
for (const auto & key: json)
{
keys.emplace_back(key["key"], key["name"]);
}
return keys;
}
catch (const std::exception & e)
{
U_LOG_E("Invalid key file: %s", e.what());
return {};
}
}
static void save_keys(const std::vector<headset_key> & keys)
{
nlohmann::json json;
for (const auto & key: keys)
{
json.push_back(nlohmann::json{
{"key", key.public_key},
{"name", key.name},
});
}
std::string json_str = json.dump();
std::filesystem::path known_keys_file_new = known_keys_file;
known_keys_file_new += ".new";
std::ofstream file(known_keys_file_new);
file.write(json_str.data(), json_str.size());
std::error_code ec;
std::filesystem::rename(known_keys_file_new, known_keys_file, ec);
if (ec)
U_LOG_E("Failed to save keys: %s", ec.message().c_str());
}
void add_known_key(headset_key key)
{
std::vector<headset_key> keys = known_keys();
if (key.name == "")
key.name = "Unknown headset";
int n = 1;
std::string original_name = key.name;
while (std::ranges::any_of(keys, [&](const headset_key & k) { return k.name == key.name; }))
{
key.name = original_name + " (" + std::to_string(++n) + ")";
}
keys.push_back(key);
save_keys(keys);
}
void remove_known_key(const std::string & key)
{
std::vector<headset_key> keys = known_keys();
std::erase_if(keys, [&](const headset_key & k) { return k.public_key == key; });
save_keys(keys);
}
void rename_known_key(headset_key key)
{
std::vector<headset_key> keys = known_keys();
for (headset_key & k: keys)
{
if (k.public_key == key.public_key)
k.name = key.name;
}
save_keys(keys);
}
} // namespace wivrn
+12 -1
View File
@@ -29,7 +29,6 @@
namespace wivrn
{
struct configuration
{
struct encoder
@@ -58,4 +57,16 @@ struct configuration
};
std::string server_cookie();
struct headset_key
{
std::string public_key;
std::string name;
};
std::vector<headset_key> known_keys();
void add_known_key(headset_key key);
void remove_known_key(const std::string & key);
void rename_known_key(headset_key key);
} // namespace wivrn
+3 -3
View File
@@ -124,7 +124,7 @@ static void create_encoders(wivrn_comp_target * cn)
assert(cn->wivrn_bundle);
cn->psc.status = 0;
auto & desc = cn->desc;
to_headset::video_stream_description & desc = cn->desc;
desc.width = cn->width;
desc.height = cn->height;
desc.foveation = cn->cnx.set_foveated_size(desc.width, desc.height);
@@ -148,7 +148,7 @@ static void create_encoders(wivrn_comp_target * cn)
std::string name = "encoder " + std::to_string(group);
pthread_setname_np(thread.native_handle(), name.c_str());
}
cn->cnx.send_control(desc);
cn->cnx.send_control(to_headset::video_stream_description{desc});
}
static VkResult create_images(struct wivrn_comp_target * cn, vk::ImageUsageFlags flags)
@@ -746,7 +746,7 @@ void wivrn_comp_target::reset_encoders()
pacer.reset();
for (auto & encoder: encoders)
encoder->reset();
cnx.send_control(desc);
cnx.send_control(to_headset::video_stream_description{desc});
}
void wivrn_comp_target::render_dynamic_foveation(std::array<to_headset::foveation_parameter, 2> foveation)
+149 -76
View File
@@ -19,11 +19,16 @@
#include "wivrn_connection.h"
#include "configuration.h"
#include "util/u_logging.h"
#include "secrets.h"
#include "wivrn_ipc.h"
#include "wivrn_packets.h"
#include <algorithm>
#include <arpa/inet.h>
#include <chrono>
#include <poll.h>
#include <regex>
#include <sys/socket.h>
#include <variant>
using namespace std::chrono_literals;
@@ -32,16 +37,30 @@ static void handle_event_from_main_loop(to_monado::disconnect)
// Ignore disconnect request when no headset is connected
}
wivrn::wivrn_connection::wivrn_connection(TCP && tcp) :
control(std::move(tcp)), stream(-1)
static std::string clean_key(std::string key)
{
init();
static const std::regex header{"^-+BEGIN .*-+$", std::regex_constants::multiline};
static const std::regex footer{"^-+END .*-+$", std::regex_constants::multiline};
static const std::regex whitespace{"[[:space:]]"};
key = std::regex_replace(key, header, "");
key = std::regex_replace(key, footer, "");
key = std::regex_replace(key, whitespace, "");
return key;
}
void wivrn::wivrn_connection::init()
wivrn::wivrn_connection::wivrn_connection(std::stop_token stop_token, const std::string & pin, TCP && tcp) :
control(std::move(tcp)),
stream(-1),
pin(pin)
{
init(stop_token);
}
void wivrn::wivrn_connection::init(std::stop_token stop_token, std::function<void()> tick)
{
active = false;
stream = -1;
sockaddr_in6 server_address;
socklen_t len = sizeof(server_address);
@@ -58,9 +77,6 @@ void wivrn::wivrn_connection::init()
throw std::system_error(errno, std::system_category(), "Cannot get client address");
}
// Wait for client to send handshake
auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(10);
if (configuration::read_user_configuration().tcp_only)
{
port = -1;
@@ -71,84 +87,141 @@ void wivrn::wivrn_connection::init()
stream.bind(port);
}
auto receive = [&](std::optional<std::chrono::seconds> timeout = std::nullopt, bool allow_stream_socket = false) {
// Returns the packet and the port (on the stream socket) or -1 (on the control socket)
std::chrono::steady_clock::time_point timeout_abs{};
if (timeout)
timeout_abs = std::chrono::steady_clock::now() + *timeout;
while (true)
{
if (stop_token.stop_requested())
throw std::runtime_error("Connection cancelled");
tick();
pollfd fds[3] = {};
if (allow_stream_socket)
{
fds[0].events = POLLIN;
fds[0].fd = stream.get_fd();
}
fds[1].events = POLLIN;
fds[1].fd = control.get_fd();
fds[2].events = POLLIN;
fds[2].fd = wivrn_ipc_socket_monado->get_fd();
// Make sure tick() is called at least every 100ms
int r = ::poll(fds, std::size(fds), 100);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (allow_stream_socket and (fds[0].revents & (POLLHUP | POLLERR)))
throw std::runtime_error("Error on stream socket");
if (fds[1].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on control socket");
if (fds[2].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on IPC socket");
if (allow_stream_socket and (fds[0].revents & POLLIN))
{
auto [raw_packet, peer_addr] = stream.receive_from_raw();
// Ignore packets sent from the wrong address
if (memcmp(&peer_addr.sin6_addr, &client_address.sin6_addr, sizeof(peer_addr.sin6_addr)) == 0)
return std::make_pair(raw_packet.deserialize<from_headset::packets>(), (int)htons(peer_addr.sin6_port));
}
if (fds[1].revents & POLLIN)
{
std::optional<from_headset::packets> packet = control.receive();
if (packet)
return std::make_pair(std::move(*packet), -1);
}
if (fds[2].revents & POLLIN)
{
auto packet = receive_from_main();
if (packet)
std::visit([](auto && x) { handle_event_from_main_loop(x); }, *packet);
}
if (timeout and std::chrono::steady_clock::now() > timeout_abs)
{
throw std::runtime_error("No handshake received from client");
}
}
};
// Wait for client to send handshake packet
auto crypto_handshake = std::get<from_headset::crypto_handshake>(receive(10s).first);
crypto::key headset_key = crypto::key::from_public_key(crypto_handshake.public_key);
bool is_public_key_known = std::ranges::any_of(
wivrn::known_keys(),
[key = clean_key(crypto_handshake.public_key)](const wivrn::headset_key & k) {
return k.public_key == key;
});
// Generate an ephemeral key pair just for exchanging the AES key
crypto::key server_key = crypto::key::generate_x448_keypair();
control.send(to_headset::crypto_handshake{
.public_key = server_key.public_key(),
.pin_required = not is_public_key_known,
});
secrets s{server_key, headset_key, is_public_key_known ? "000000" : pin};
control.set_aes_key_and_ivs(s.control_key, s.control_iv_from_headset, s.control_iv_to_headset);
stream.set_aes_key_and_ivs(s.stream_key, s.stream_iv_header_from_headset, s.stream_iv_header_to_headset);
// Wait for confirmation that the client has set up encryption
if (not std::holds_alternative<from_headset::crypto_handshake>(receive().first))
throw std::runtime_error("No handshake received from client");
control.send(to_headset::handshake{.stream_port = port});
while (true)
auto [stream_handshake, client_port] = receive(10s, true);
// Check the packet type
if (not std::holds_alternative<from_headset::handshake>(stream_handshake))
{
pollfd fds[3] = {};
fds[0].events = POLLIN;
fds[0].fd = stream.get_fd();
fds[1].events = POLLIN;
fds[1].fd = control.get_fd();
fds[2].fd = wivrn_ipc_socket_monado->get_fd();
fds[2].events = POLLIN;
int r = ::poll(fds, std::size(fds), 1000);
if (r < 0)
throw std::system_error(errno, std::system_category());
if (fds[0].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on stream socket");
if (fds[1].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on control socket");
if (fds[2].revents & (POLLHUP | POLLERR))
throw std::runtime_error("Error on IPC socket");
if (fds[0].revents & POLLIN)
{
auto [packet, peer_addr] = stream.receive_from_raw();
if (memcmp(&peer_addr.sin6_addr, &client_address.sin6_addr, sizeof(peer_addr.sin6_addr)) == 0)
{
int client_port = htons(peer_addr.sin6_port);
stream.connect(peer_addr.sin6_addr, client_port);
U_LOG_D("Stream socket connected, client port %d", client_port);
stream.set_send_buffer_size(1024 * 1024 * 5);
break;
}
}
if (fds[1].revents & POLLIN)
{
auto packet = control.receive();
if (packet)
{
if (std::holds_alternative<from_headset::handshake>(*packet))
{
stream = decltype(stream)(-1);
port = -1;
U_LOG_I("Using TCP only");
break;
}
else
{
throw std::runtime_error("Invalid handshake received from client");
}
}
}
if (fds[2].revents & POLLIN)
{
auto packet = receive_from_main();
if (packet)
std::visit([](auto && x) { handle_event_from_main_loop(x); }, *packet);
}
if (std::chrono::steady_clock::now() > timeout)
{
throw std::runtime_error("No handshake received from client");
}
throw std::runtime_error("No handshake received from client");
}
if (client_port >= 0)
{
stream.connect(client_address.sin6_addr, client_port);
stream.set_send_buffer_size(1024 * 1024 * 5);
}
else
{
// No stream socket
}
control.send(to_headset::handshake{.stream_port = port});
info_packet = std::get<from_headset::headset_info_packet>(receive(10s).first);
active = true;
if (not is_public_key_known)
wivrn::add_known_key({
.public_key = clean_key(headset_key.public_key()),
.name = crypto_handshake.name,
});
}
void wivrn::wivrn_connection::reset(TCP && tcp)
void wivrn::wivrn_connection::reset(TCP && tcp, std::function<void()> tick)
{
if (stream)
stream = decltype(stream)();
control = std::move(tcp);
init();
init({}, tick);
}
void wivrn::wivrn_connection::shutdown()
+20 -8
View File
@@ -27,21 +27,24 @@
#include <optional>
#include <poll.h>
#include <stdexcept>
#include <stop_token>
#include <system_error>
namespace wivrn
{
class wivrn_connection
{
typed_socket<TCP, from_headset::packets, to_headset::packets> control;
typed_socket<UDP, from_headset::packets, to_headset::packets> stream;
std::atomic<bool> active = false;
std::string pin;
void init();
wivrn::from_headset::headset_info_packet info_packet;
void init(std::stop_token stop_token, std::function<void()> tick = []() {});
public:
wivrn_connection(TCP && tcp);
wivrn_connection(std::stop_token stop_token, const std::string & pin, TCP && tcp);
wivrn_connection(const wivrn_connection &) = delete;
wivrn_connection & operator=(const wivrn_connection &) = delete;
@@ -49,7 +52,7 @@ public:
{
return active;
}
void reset(TCP && tcp);
void reset(TCP && tcp, std::function<void()> tick = []() {});
void shutdown();
template <typename T>
@@ -66,15 +69,19 @@ public:
throw;
}
}
template <typename T>
void send_stream(T && packet)
{
try
{
if (active and stream)
stream.send(std::forward<T>(packet));
else
control.send(std::forward<T>(packet));
if (active)
{
if (stream)
stream.send(std::forward<T>(packet));
else
control.send(std::forward<T>(packet));
}
}
catch (...)
{
@@ -85,6 +92,11 @@ public:
std::optional<from_headset::packets> poll_control(int timeout);
const wivrn::from_headset::headset_info_packet & info() const
{
return info_packet;
}
template <typename T>
int poll(T && visitor, int timeout)
{
+30 -32
View File
@@ -122,24 +122,16 @@ bool wivrn::tracking_control_t::set_enabled(to_headset::tracking_control::id id,
return changed;
}
wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
wivrn::wivrn_session::wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system & system) :
xrt_system_devices{
.get_roles = [](xrt_system_devices * self, xrt_system_roles * out_roles) { return ((wivrn_session *)self)->get_roles(out_roles); },
.feature_inc = [](xrt_system_devices * self, xrt_device_feature_type f) { return ((wivrn_session *)self)->feature_inc(f); },
.feature_dec = [](xrt_system_devices * self, xrt_device_feature_type f) { return ((wivrn_session *)self)->feature_dec(f); },
.destroy = [](xrt_system_devices * self) { delete ((wivrn_session *)self); },
},
connection(std::move(tcp)),
info([](wivrn_connection & connection) {
std::optional<wivrn::from_headset::packets> control;
while (not(control = connection.poll_control(-1)))
{
// FIXME: timeout
}
return std::get<from_headset::headset_info_packet>(*control);
}(connection)),
connection(std::move(connection)),
xrt_system(system),
hmd(this, info),
hmd(this, get_info()),
left_hand(0, &hmd, this),
right_hand(1, &hmd, this)
{
@@ -150,7 +142,7 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
"WiVRn(microphone)",
"wivrn.sink",
"WiVRn",
info,
get_info(),
*this);
if (audio_handle)
send_control(audio_handle->description());
@@ -198,14 +190,14 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
}
}
#endif
if (info.eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
if (get_info().eye_gaze || is_forced_extension("EXT_eye_gaze_interaction"))
{
eye_tracker = std::make_unique<wivrn_eye_tracker>(&hmd);
foveation = std::make_unique<wivrn_foveation>();
static_roles.eyes = eye_tracker.get();
xdevs[xdev_count++] = eye_tracker.get();
}
if (info.face_tracking2_fb || is_forced_extension("FB_face_tracking2"))
if (get_info().face_tracking2_fb || is_forced_extension("FB_face_tracking2"))
{
fb_face2_tracker = std::make_unique<wivrn_fb_face2_tracker>(&hmd, *this);
static_roles.face = fb_face2_tracker.get();
@@ -234,10 +226,10 @@ wivrn::wivrn_session::wivrn_session(wivrn::TCP && tcp, u_system & system) :
wivrn_session::~wivrn_session()
{
connection.shutdown();
connection->shutdown();
}
xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
xrt_result_t wivrn::wivrn_session::create_session(std::unique_ptr<wivrn_connection> connection,
u_system & system,
xrt_system_devices ** out_xsysd,
xrt_space_overseer ** out_xspovrs,
@@ -246,7 +238,7 @@ xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
std::unique_ptr<wivrn_session> self;
try
{
self.reset(new wivrn_session(std::move(tcp), system));
self.reset(new wivrn_session(std::move(connection), system));
}
catch (std::exception & e)
{
@@ -254,9 +246,9 @@ xrt_result_t wivrn::wivrn_session::create_session(wivrn::TCP && tcp,
return XRT_ERROR_DEVICE_CREATION_FAILED;
}
send_to_main(self->info);
send_to_main(self->get_info());
wivrn_comp_target_factory ctf(*self, self->info.preferred_refresh_rate);
wivrn_comp_target_factory ctf(*self, self->get_info().preferred_refresh_rate);
auto xret = comp_main_create_system_compositor(&self->hmd, &ctf, out_xsysc);
if (xret != XRT_SUCCESS)
{
@@ -294,7 +286,7 @@ clock_offset wivrn_session::get_offset()
bool wivrn_session::connected()
{
return connection.is_active();
return connection->is_active();
}
void wivrn_session::operator()(from_headset::headset_info_packet &&)
@@ -379,7 +371,7 @@ void wivrn_session::set_enabled(to_headset::tracking_control::id id, bool enable
void wivrn_session::set_enabled(device_id id, bool enabled)
{
if (tracking_control.set_enabled(to_tracking_control(id), enabled) and enabled)
tracking_control.send(connection, true);
tracking_control.send(*connection, true);
}
void wivrn_session::operator()(from_headset::feedback && feedback)
@@ -426,9 +418,9 @@ void wivrn_session::run(std::stop_token stop)
{
try
{
offset_est.request_sample(connection);
tracking_control.send(connection);
connection.poll(*this, 20);
offset_est.request_sample(*connection);
tracking_control.send(*connection);
connection->poll(*this, 20);
}
catch (const std::exception & e)
{
@@ -504,17 +496,18 @@ void wivrn_session::reconnect()
if (not tcp)
exit(0);
struct no_client_connected
{};
try
{
offset_est.reset();
connection.reset(std::move(*tcp));
std::optional<wivrn::from_headset::packets> control;
while (not(control = connection.poll_control(100)))
{
// FIXME: timeout
quit_if_no_client(xrt_system);
}
const auto & info = std::get<from_headset::headset_info_packet>(*control);
connection->reset(std::move(*tcp), [this]() {
if (quit_if_no_client(xrt_system))
throw no_client_connected{};
});
// const auto & info = connection->info();
// FIXME: ensure new client is compatible
comp_target->reset_encoders();
@@ -529,6 +522,11 @@ void wivrn_session::reconnect()
U_LOG_W("Failed to notify session state change");
}
}
catch (no_client_connected)
{
U_LOG_I("No OpenXR application connected");
exit(0);
}
catch (const std::exception & e)
{
U_LOG_E("Reconnection failed: %s", e.what());
+8 -8
View File
@@ -77,8 +77,7 @@ public:
class wivrn_session : public xrt_system_devices
{
friend wivrn_comp_target_factory;
wivrn_connection connection;
from_headset::headset_info_packet info{};
std::unique_ptr<wivrn_connection> connection;
u_system & xrt_system;
xrt_space_overseer * space_overseer;
@@ -113,12 +112,12 @@ class wivrn_session : public xrt_system_devices
std::jthread thread;
wivrn_session(TCP && tcp, u_system &);
wivrn_session(std::unique_ptr<wivrn_connection> connection, u_system &);
public:
~wivrn_session();
static xrt_result_t create_session(TCP && tcp,
static xrt_result_t create_session(std::unique_ptr<wivrn_connection> connection,
u_system & system,
xrt_system_devices ** out_xsysd,
xrt_space_overseer ** out_xspovrs,
@@ -128,7 +127,7 @@ public:
bool connected();
const from_headset::headset_info_packet & get_info()
{
return info;
return connection->info();
};
void add_predict_offset(std::chrono::nanoseconds off)
@@ -139,8 +138,9 @@ public:
void set_enabled(to_headset::tracking_control::id id, bool enabled);
void set_enabled(device_id id, bool enabled);
void operator()(from_headset::handshake &&) {}
void operator()(from_headset::crypto_handshake &&) {}
void operator()(from_headset::headset_info_packet &&);
void operator()(from_headset::handshake &&) {}
void operator()(from_headset::trackings &&);
void operator()(const from_headset::tracking &);
void operator()(from_headset::hand_tracking &&);
@@ -155,13 +155,13 @@ public:
template <typename T>
void send_stream(T && packet)
{
connection.send_stream(std::forward<T>(packet));
connection->send_stream(std::forward<T>(packet));
}
template <typename T>
void send_control(T && packet)
{
connection.send_control(std::forward<T>(packet));
connection->send_control(std::forward<T>(packet));
}
std::array<to_headset::foveation_parameter, 2> set_foveated_size(uint32_t width, uint32_t height);
+1 -1
View File
@@ -340,7 +340,7 @@ void video_encoder::SendData(std::span<uint8_t> data, bool end_of_frame)
shard.payload = {begin, next};
try
{
cnx->send_stream(shard);
cnx->send_stream(to_headset::video_stream_data_shard{shard});
}
catch (...)
{
+154 -40
View File
@@ -12,11 +12,13 @@
#include "active_runtime.h"
#include "avahi_publisher.h"
#include "driver/configuration.h"
#include "driver/wivrn_connection.h"
#include "exit_codes.h"
#include "hostname.h"
#include "protocol_version.h"
#include "start_application.h"
#include "utils/flatpak.h"
#include "utils/overloaded.h"
#include "version.h"
#include "wivrn_config.h"
#include "wivrn_ipc.h"
@@ -32,9 +34,11 @@
#include <iterator>
#include <memory>
#include <poll.h>
#include <random>
#include <sys/signalfd.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <gio/gio.h>
@@ -78,7 +82,8 @@ int create_listen_socket()
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, sock_file.c_str());
int fd = socket(PF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
fcntl(fd, F_SETFD, FD_CLOEXEC);
int ret = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
// no other instance is running, or we would have never arrived here
@@ -187,6 +192,7 @@ bool use_systemd;
guint server_watch;
guint server_kill_watch;
pid_t server_pid;
std::optional<std::jthread> connection_thread;
guint app_watch;
guint app_kill_watch;
@@ -198,6 +204,8 @@ bool avahi_publish;
guint listener_watch;
std::string pin;
WivrnServer * dbus_server;
/* TODO: Document FSM
@@ -209,6 +217,8 @@ std::optional<sleep_inhibitor> inhibitor;
gboolean headset_connected(gint fd, GIOCondition condition, gpointer user_data);
void stop_listening();
void on_headset_info_packet(const wivrn::from_headset::headset_info_packet & info);
void expose_known_keys_on_dbus();
void choose_pin();
void start_publishing();
void stop_publishing();
@@ -246,8 +256,6 @@ void start_app()
void start_server()
{
stop_listening();
stop_publishing();
server_pid = do_fork ? fork() : 0;
if (server_pid < 0)
@@ -385,11 +393,13 @@ void stop_publishing()
void update_fsm()
{
bool server_running = server_watch != 0;
bool server_running = server_watch != 0 or connection_thread;
bool app_running = app_watch != 0;
if (quitting_main_loop)
{
connection_thread.reset();
if (server_running)
kill_server();
@@ -426,22 +436,59 @@ int sigint(void * sig_nr)
return G_SOURCE_CONTINUE;
}
gboolean headset_connected(gint fd, GIOCondition condition, gpointer user_data)
gboolean headset_connected_success(void *)
{
assert(server_watch == 0);
assert(app_watch == 0);
assert(connection_thread);
connection_thread.reset();
assert(listener);
tcp = std::make_unique<wivrn::TCP>(listener->accept().first);
init_cleanup_functions();
std::cout << "Client connected" << std::endl;
expose_known_keys_on_dbus();
start_server();
start_app();
return true;
connection.reset();
return G_SOURCE_REMOVE;
}
gboolean headset_connected_failed(void *)
{
assert(connection_thread);
connection_thread.reset();
update_fsm();
return G_SOURCE_REMOVE;
}
gboolean headset_connected(gint fd, GIOCondition condition, gpointer user_data)
{
assert(server_watch == 0);
assert(app_watch == 0);
assert(not connection_thread);
assert(listener);
wivrn::TCP tcp = listener->accept().first;
stop_listening();
stop_publishing();
connection_thread.emplace([](std::stop_token stop_token, wivrn::TCP && tcp) {
try
{
connection = std::make_unique<wivrn::wivrn_connection>(stop_token, pin, std::move(tcp));
g_main_context_invoke(nullptr, &headset_connected_success, nullptr);
}
catch (std::exception & e)
{
std::cerr << "Client connection failed: " << e.what() << std::endl;
g_main_context_invoke(nullptr, &headset_connected_failed, nullptr);
}
},
std::move(tcp));
return G_SOURCE_CONTINUE;
}
gboolean control_received(gint fd, GIOCondition condition, gpointer user_data)
@@ -449,48 +496,91 @@ gboolean control_received(gint fd, GIOCondition condition, gpointer user_data)
auto packet = wivrn_ipc_socket_main_loop->receive();
if (packet)
{
if (std::holds_alternative<wivrn::from_headset::headset_info_packet>(*packet))
{
on_headset_info_packet(std::get<wivrn::from_headset::headset_info_packet>(*packet));
inhibitor.emplace();
wivrn_server_set_headset_connected(dbus_server, true);
}
else if (std::holds_alternative<from_monado::headsdet_connected>(*packet))
{
stop_publishing();
inhibitor.emplace();
wivrn_server_set_headset_connected(dbus_server, true);
}
else if (std::holds_alternative<from_monado::headsdet_disconnected>(*packet))
{
start_publishing();
inhibitor.reset();
wivrn_server_set_headset_connected(dbus_server, false);
}
std::visit(utils::overloaded{
[&](const wivrn::from_headset::headset_info_packet & info) {
on_headset_info_packet(std::get<wivrn::from_headset::headset_info_packet>(*packet));
inhibitor.emplace();
wivrn_server_set_headset_connected(dbus_server, true);
},
[&](const from_monado::headset_connected &) {
stop_publishing();
inhibitor.emplace();
wivrn_server_set_headset_connected(dbus_server, true);
},
[&](const from_monado::headset_disconnected &) {
start_publishing();
inhibitor.reset();
wivrn_server_set_headset_connected(dbus_server, false);
},
},
*packet);
}
return true;
return G_SOURCE_CONTINUE;
}
gboolean
on_handle_disconnect(WivrnServer * skeleton,
GDBusMethodInvocation * invocation,
gpointer user_data)
void choose_pin()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> distrib(0, 999999);
char buffer[7];
snprintf(buffer, 7, "%06d", distrib(gen));
pin = buffer;
std::cerr << "PIN code: " << pin << std::endl;
wivrn_server_set_pin(dbus_server, buffer);
}
gboolean on_handle_disconnect(WivrnServer * skeleton,
GDBusMethodInvocation * invocation,
gpointer user_data)
{
wivrn_ipc_socket_main_loop->send(to_monado::disconnect{});
return true;
return G_SOURCE_CONTINUE;
}
gboolean
on_handle_quit(WivrnServer * skeleton,
GDBusMethodInvocation * invocation,
gpointer user_data)
gboolean on_handle_quit(WivrnServer * skeleton, GDBusMethodInvocation * invocation, gpointer user_data)
{
quitting_main_loop = true;
update_fsm();
return true;
return G_SOURCE_CONTINUE;
}
gboolean on_handle_revoke_key(WivrnServer * skeleton, GDBusMethodInvocation * invocation, gpointer user_data)
{
GVariant * args = g_dbus_method_invocation_get_parameters(invocation);
char * publickey;
g_variant_get_child(args, 0, "s", &publickey);
wivrn::remove_known_key(publickey);
g_free(publickey);
expose_known_keys_on_dbus();
return G_SOURCE_CONTINUE;
}
gboolean on_handle_rename_key(WivrnServer * skeleton, GDBusMethodInvocation * invocation, gpointer user_data)
{
GVariant * args = g_dbus_method_invocation_get_parameters(invocation);
char * publickey;
char * name;
g_variant_get_child(args, 0, "s", &publickey);
g_variant_get_child(args, 1, "s", &name);
wivrn::rename_known_key({.public_key = publickey, .name = name});
g_free(publickey);
g_free(name);
expose_known_keys_on_dbus();
return G_SOURCE_CONTINUE;
}
void on_json_configuration(WivrnServer * server, const GParamSpec * pspec, gpointer data)
@@ -511,6 +601,18 @@ void on_json_configuration(WivrnServer * server, const GParamSpec * pspec, gpoin
std::cerr << "Failed to save configuration: " << ec.message() << std::endl;
}
void expose_known_keys_on_dbus()
{
GVariantBuilder * builder = g_variant_builder_new(G_VARIANT_TYPE("a(ss)"));
for (const auto & i: known_keys())
{
g_variant_builder_add(builder, "(ss)", i.name.c_str(), i.public_key.c_str());
}
GVariant * value = g_variant_new("a(ss)", builder);
g_variant_builder_unref(builder);
wivrn_server_set_known_keys(dbus_server, value);
}
void on_headset_info_packet(const wivrn::from_headset::headset_info_packet & info)
{
GVariantBuilder * builder;
@@ -579,6 +681,16 @@ void on_name_acquired(GDBusConnection * connection, const gchar * name, gpointer
G_CALLBACK(on_handle_quit),
NULL);
g_signal_connect(dbus_server,
"handle-revoke-key",
G_CALLBACK(on_handle_revoke_key),
NULL);
g_signal_connect(dbus_server,
"handle-rename-key",
G_CALLBACK(on_handle_rename_key),
NULL);
wivrn_server_set_steam_command(dbus_server, steam_command().c_str());
on_headset_info_packet({});
@@ -587,6 +699,8 @@ void on_name_acquired(GDBusConnection * connection, const gchar * name, gpointer
std::string config{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()};
wivrn_server_set_json_configuration(dbus_server, config.c_str());
choose_pin();
expose_known_keys_on_dbus();
g_signal_connect(dbus_server, "notify::json-configuration", G_CALLBACK(on_json_configuration), NULL);
+2 -4
View File
@@ -17,6 +17,7 @@
#include <assert.h>
#include "driver/wivrn_session.h"
#include "wivrn_ipc.h"
/*
*
@@ -24,8 +25,6 @@
*
*/
extern std::unique_ptr<wivrn::TCP> tcp;
static xrt_result_t
wivrn_instance_create_system(struct xrt_instance * xinst,
struct xrt_system ** out_xsys,
@@ -41,13 +40,12 @@ wivrn_instance_create_system(struct xrt_instance * xinst,
struct xrt_system_compositor * xsysc = NULL;
auto res = wivrn::wivrn_session::create_session(
std::move(*tcp),
std::move(connection),
*u_sys,
out_xsysd,
out_xspovrs,
out_xsysc);
u_system_set_system_compositor(u_sys, *out_xsysc);
tcp.reset();
return res;
}
+2 -1
View File
@@ -18,12 +18,13 @@
*/
#include "wivrn_ipc.h"
#include "driver/wivrn_connection.h"
#include <algorithm>
#include <sys/mman.h>
#include <sys/wait.h>
std::unique_ptr<wivrn::TCP> tcp;
std::unique_ptr<wivrn::wivrn_connection> connection;
struct cleanup_function
{
+13 -7
View File
@@ -27,16 +27,22 @@
#include <stdint.h>
#include <variant>
extern std::unique_ptr<wivrn::TCP> tcp;
namespace wivrn
{
class wivrn_connection;
}
extern std::unique_ptr<wivrn::wivrn_connection> connection;
namespace from_monado
{
struct headsdet_connected
{};
struct headsdet_disconnected
struct headset_connected
{};
using packets = std::variant<wivrn::from_headset::headset_info_packet, headsdet_connected, headsdet_disconnected>;
struct headset_disconnected
{};
using packets = std::variant<wivrn::from_headset::headset_info_packet, headset_connected, headset_disconnected>;
} // namespace from_monado
namespace to_monado
@@ -51,9 +57,9 @@ extern std::optional<wivrn::typed_socket<wivrn::UnixDatagram, to_monado::packets
std::optional<to_monado::packets> receive_from_main();
template <typename T>
void send_to_main(T && packet)
void send_to_main(T packet)
{
wivrn_ipc_socket_monado->send(std::forward<T>(packet));
wivrn_ipc_socket_monado->send(std::move(packet));
}
void init_cleanup_functions();
+37
View File
@@ -643,6 +643,43 @@ struct tree_traits<abbrev, std::chrono::nanoseconds>
}
};
template <details::fixed_string abbrev>
struct tree_traits<abbrev, std::chrono::seconds>
{
static inline int field_handle = -1;
using T = std::chrono::seconds::rep;
static void info()
{
hf_register_info hf = {
.p_id = &field_handle,
.hfinfo = {
.name = strdup(details::name_from_abbrev(abbrev.value).c_str()),
.abbrev = abbrev.value,
.type = details::field_type<T>,
.display = BASE_DEC | BASE_UNIT_STRING,
.strings = &units_seconds,
.bitmask = 0,
.blurb = "",
}};
HFILL_INIT(hf);
fields.push_back(hf);
}
static void dissect(proto_tree * tree, tvbuff_t * tvb, int & start)
{
proto_tree_add_item(tree, field_handle, tvb, start, sizeof(T), ENC_LITTLE_ENDIAN);
start += sizeof(T);
}
static size_t size(tvbuff_t * tvb, int & start)
{
start += sizeof(T);
return sizeof(T);
}
};
template <details::fixed_string abbrev>
struct tree_traits<abbrev, std::span<uint8_t>>
{