From c6e773fd220bce6b4bf0f0e8b294e98f8bcac01f Mon Sep 17 00:00:00 2001 From: Guillaume Meunier Date: Wed, 6 Nov 2024 22:10:22 +0100 Subject: [PATCH] Add support for authentication and encryption --- client/audio/android/audio.cpp | 10 +- client/scenes/lobby.cpp | 86 +++++++++- client/scenes/lobby.h | 16 ++ client/scenes/lobby_gui.cpp | 139 ++++++++++------ client/scenes/stream.cpp | 98 +++++------ client/scenes/stream.h | 1 + client/scenes/stream_actions.cpp | 2 +- client/scenes/stream_network.cpp | 10 +- client/scenes/stream_tracking.cpp | 2 +- client/wivrn_client.cpp | 127 +++++++++----- client/wivrn_client.h | 29 ++-- common/CMakeLists.txt | 1 + common/secrets.cpp | 32 ++++ common/secrets.h | 38 +++++ {client => common}/utils/overloaded.h | 0 common/utils/thread_safe.h | 180 ++++++++++++++++++++ common/wivrn_packets.h | 18 +- common/wivrn_serialization.h | 38 ++++- common/wivrn_serialization_types.h | 6 - common/wivrn_sockets.cpp | 227 ++++++++++++++++++++------ common/wivrn_sockets.h | 50 ++++-- dashboard/main_window.cpp | 12 ++ dashboard/main_window.h | 1 + dashboard/main_window.ui | 58 ++++++- dashboard/wivrn_server.cpp | 5 + dashboard/wivrn_server.h | 9 + dashboard/wizard.cpp | 5 + dashboard/wizard.ui | 22 +++ dbus/io.github.wivrn.Server.xml | 13 ++ server/accept_connection.cpp | 4 +- server/audio/audio_pipewire.cpp | 13 +- server/audio/audio_pulse.cpp | 8 +- server/driver/configuration.cpp | 99 ++++++++++- server/driver/configuration.h | 13 +- server/driver/wivrn_comp_target.cpp | 6 +- server/driver/wivrn_connection.cpp | 225 ++++++++++++++++--------- server/driver/wivrn_connection.h | 28 +++- server/driver/wivrn_session.cpp | 62 ++++--- server/driver/wivrn_session.h | 16 +- server/encoder/video_encoder.cpp | 2 +- server/main.cpp | 194 +++++++++++++++++----- server/target_instance_wivrn.cpp | 6 +- server/wivrn_ipc.cpp | 3 +- server/wivrn_ipc.h | 20 ++- tools/wireshark/dissector.cpp | 37 +++++ 45 files changed, 1516 insertions(+), 455 deletions(-) create mode 100644 common/secrets.cpp create mode 100644 common/secrets.h rename {client => common}/utils/overloaded.h (100%) create mode 100644 common/utils/thread_safe.h diff --git a/client/audio/android/audio.cpp b/client/audio/android/audio.cpp index a260b799..f6305457 100644 --- a/client/audio/android/audio.cpp +++ b/client/audio/android/audio.cpp @@ -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 (...) { diff --git a/client/scenes/lobby.cpp b/client/scenes/lobby.cpp index f2358ecd..f5468929 100644 --- a/client/scenes/lobby.cpp +++ b/client/scenes/lobby.cpp @@ -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 +#include +#include #include #include "wivrn_discover.h" #include +#include #include #include #include @@ -45,6 +49,7 @@ #include #include #include +#include #include #include @@ -53,6 +58,8 @@ #include #include +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(f)), std::istreambuf_iterator()}); + } + 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 connect_to_session(wivrn_discover::service service, bool manual_connection) +std::unique_ptr scenes::lobby::connect_to_session(wivrn_discover::service service, bool manual_connection) { if (!manual_connection) { @@ -244,22 +264,76 @@ std::unique_ptr connect_to_session(wivrn_discover::service servic } std::string error; - for (const auto & address: service.addresses) + for (const std::variant & 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(address, port, tcp_only); + return std::visit([this, port = service.port, tcp_only = service.tcp_only](auto & address) { + return std::make_unique(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::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); }, diff --git a/client/scenes/lobby.h b/client/scenes/lobby.h index 079a96ef..3b82fd40 100644 --- a/client/scenes/lobby.h +++ b/client/scenes/lobby.h @@ -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 #include "xr/system.h" +#include #include #include @@ -130,6 +133,16 @@ class lobby : public scene_impl virtual_keyboard keyboard; + struct pin_request_data + { + bool pin_requested = false; + bool pin_cancelled = false; + std::string pin; + }; + + thread_safe_notifyable 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 void vibrate_on_hover(); void connect(const configuration::server_data & data); + std::unique_ptr connect_to_session(wivrn_discover::service service, bool manual_connection); std::optional check_recenter_gesture(const std::array & joints); std::optional check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position); std::optional check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation); + crypto::key keypair; + public: virtual ~lobby(); lobby(); diff --git a/client/scenes/lobby_gui.cpp b/client/scenes/lobby_gui.cpp index d6872557..ea84b6b7 100644 --- a/client/scenes/lobby_gui.cpp +++ b/client/scenes/lobby_gui.cpp @@ -31,9 +31,11 @@ #include "stream.h" #include "version.h" #include +#include #include #include #include +#include #include #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); diff --git a/client/scenes/stream.cpp b/client/scenes/stream.cpp index 1325789a..3a3f9d41 100644 --- a/client/scenes/stream.cpp +++ b/client/scenes/stream.cpp @@ -79,64 +79,65 @@ std::shared_ptr scenes::stream::create(std::unique_ptr 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 feedbacks; std::vector 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) { diff --git a/client/scenes/stream.h b/client/scenes/stream.h index 7961fd09..b501d713 100644 --- a/client/scenes/stream.h +++ b/client/scenes/stream.h @@ -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 &&); diff --git a/client/scenes/stream_actions.cpp b/client/scenes/stream_actions.cpp index 512c4128..b7d2f07e 100644 --- a/client/scenes/stream_actions.cpp +++ b/client/scenes/stream_actions.cpp @@ -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) { diff --git a/client/scenes/stream_network.cpp b/client/scenes/stream_network.cpp index 971ae639..d5794cbc 100644 --- a/client/scenes/stream_network.cpp +++ b/client/scenes/stream_network.cpp @@ -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) { diff --git a/client/scenes/stream_tracking.cpp b/client/scenes/stream_tracking.cpp index bbb3a6f9..3f22bb3a 100644 --- a/client/scenes/stream_tracking.cpp +++ b/client/scenes/stream_tracking.cpp @@ -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; } diff --git a/client/wivrn_client.cpp b/client/wivrn_client.cpp index 7a36f291..2b917839 100644 --- a/client/wivrn_client.cpp +++ b/client/wivrn_client.cpp @@ -18,6 +18,7 @@ */ #include "wivrn_client.h" +#include "secrets.h" #include "spdlog/common.h" #include "wivrn_packets.h" #include @@ -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 @@ -49,82 +58,114 @@ void init_stream(T & stream) } // namespace template -void wivrn_session::handshake(T address, bool tcp_only) +void wivrn_session::handshake(T address, bool tcp_only, crypto::key & headset_keypair, std::function 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 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(*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(timeout_abs - std::chrono::steady_clock::now()); + int r = ::poll(&fds, 1, std::max(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(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(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, to_headset::handshake>; }, - std::chrono::milliseconds(100))) + if (poll([](const auto && packet) { return std::is_same_v, 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 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 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()}; + } } diff --git a/client/wivrn_client.h b/client/wivrn_client.h index d02cd3d0..4ba14f08 100644 --- a/client/wivrn_client.h +++ b/client/wivrn_client.h @@ -19,12 +19,23 @@ #pragma once +#include "crypto.h" #include "wivrn_packets.h" #include "wivrn_sockets.h" +#include #include 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 - void handshake(T address, bool tcp_only); + void handshake(T address, bool tcp_only, crypto::key & headset_keypair, std::function pin_enter); public: std::variant 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 pin_enter); + wivrn_session(in_addr address, int port, bool tcp_only, crypto::key & headset_keypair, std::function pin_enter); wivrn_session(const wivrn_session &) = delete; wivrn_session & operator=(const wivrn_session &) = delete; @@ -52,12 +63,6 @@ public: control.send(std::forward(packet)); } - template - void serialize_control(serialization_packet & p, const T & data) - { - control.serialize(p, data); - } - template void send_stream(T && packet) { @@ -67,12 +72,6 @@ public: control.send(std::forward(packet)); } - template - void serialize_stream(serialization_packet & p, const T & data) - { - stream.serialize(p, data); - } - template int poll(T && visitor, std::chrono::milliseconds timeout) { diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 8dcd3003..7830e29f 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -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 diff --git a/common/secrets.cpp b/common/secrets.cpp new file mode 100644 index 00000000..3347390d --- /dev/null +++ b/common/secrets.cpp @@ -0,0 +1,32 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#include "secrets.h" +#include +#include + +secrets::secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin) +{ + std::vector dh = crypto::key::diffie_hellman(my_key, peer_key); + std::vector secret = crypto::argon2(pin, "saltsalt", dh, sizeof(*this)); + + static_assert(std::is_standard_layout_v); + static_assert(std::has_unique_object_representations_v); + memcpy(this, secret.data(), secret.size()); +} diff --git a/common/secrets.h b/common/secrets.h new file mode 100644 index 00000000..08b274c6 --- /dev/null +++ b/common/secrets.h @@ -0,0 +1,38 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2022 Guillaume Meunier + * Copyright (C) 2022 Patrick Nicolas + * + * 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 . + */ + +#pragma once + +#include "crypto.h" +#include +#include +#include + +struct secrets +{ + std::array control_key; + std::array control_iv_to_headset; + std::array control_iv_from_headset; + + std::array stream_key; + std::array stream_iv_header_to_headset; + std::array stream_iv_header_from_headset; + + secrets(crypto::key & my_key, crypto::key & peer_key, const std::string & pin); +}; diff --git a/client/utils/overloaded.h b/common/utils/overloaded.h similarity index 100% rename from client/utils/overloaded.h rename to common/utils/overloaded.h diff --git a/common/utils/thread_safe.h b/common/utils/thread_safe.h new file mode 100644 index 00000000..c7d706c1 --- /dev/null +++ b/common/utils/thread_safe.h @@ -0,0 +1,180 @@ +/* + * WiVRn VR streaming + * Copyright (C) 2024 Guillaume Meunier + * Copyright (C) 2024 Patrick Nicolas + * + * 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 . + */ + +#pragma once + +#include +#include + +template +class thread_safe_notifyable; + +template +class locked +{ + friend class thread_safe_notifyable; + + T & value; + std::unique_lock 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 +class thread_safe +{ + T value; + Mutex mutex; + +public: + template + thread_safe(Args &&... args) : + value(std::forward(args)...) + {} + + locked lock() + { + return locked(value, mutex); + } +}; + +template +class locked_notifiable +{ + friend class thread_safe_notifyable; + + T & value; + std::unique_lock 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 + void wait(Predicate && pred) + { + cv.wait(lock, std::forward(pred)); + } + + template + std::cv_status wait_for(const std::chrono::duration & rel_time) + { + return cv.wait_for(lock, rel_time); + } + + template + bool wait_for(const std::chrono::duration & rel_time, Predicate pred) + { + return cv.wait_for(lock, rel_time, pred); + } + + template + std::cv_status wait_until(const std::chrono::time_point & abs_time) + { + return cv.wait_until(lock, abs_time); + } + + template + bool wait_until(const std::chrono::time_point & abs_time, Predicate pred) + { + return cv.wait_until(lock, abs_time, pred); + } +}; + +template +class thread_safe_notifyable : public thread_safe +{ + T value; + std::mutex mutex; + std::condition_variable cv; + +public: + template + thread_safe_notifyable(Args &&... args) : + thread_safe(std::forward(args)...) + {} + + locked_notifiable lock() + { + return locked_notifiable(value, mutex, cv); + } +}; diff --git a/common/wivrn_packets.h b/common/wivrn_packets.h index 81af4c85..2528a8bb 100644 --- a/common/wivrn_packets.h +++ b/common/wivrn_packets.h @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -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; +using packets = std::variant; } // 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 enabled; }; -using packets = std::variant; - +using packets = std::variant; } // namespace to_headset - } // namespace wivrn diff --git a/common/wivrn_serialization.h b/common/wivrn_serialization.h index e1cb2459..a85dfe7c 100644 --- a/common/wivrn_serialization.h +++ b/common/wivrn_serialization.h @@ -98,9 +98,29 @@ size_t serialized_size(const T & x) class deserialization_error : public std::runtime_error { + static std::string hexdump(std::span 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(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 raw_data) : + std::runtime_error("Deserialization error\n" + hexdump(raw_data)) {} }; class serialization_packet @@ -144,11 +164,11 @@ public: serialization_traits::serialize(value, *this); } - operator const std::vector> *() + operator std::vector> *() { - return &this->operator const std::vector> &(); + return &this->operator std::vector> &(); } - operator const std::vector> &() + operator std::vector> &() { exp_spans.clear(); struct visitor @@ -181,10 +201,12 @@ class deserialization_packet std::span buffer; public: + std::span initial_buffer; deserialization_packet() = default; explicit deserialization_packet(std::shared_ptr memory, std::span 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 @@ -773,7 +795,7 @@ struct serialization_traits> { uint8_t type_index = packet.deserialize(); if (type_index >= sizeof...(T)) - throw deserialization_error(); + throw deserialization_error(packet.initial_buffer); return deserialize_aux(packet, type_index, std::make_index_sequence()); } diff --git a/common/wivrn_serialization_types.h b/common/wivrn_serialization_types.h index f4917934..613db470 100644 --- a/common/wivrn_serialization_types.h +++ b/common/wivrn_serialization_types.h @@ -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 c; }; diff --git a/common/wivrn_sockets.cpp b/common/wivrn_sockets.cpp index 23b5f647..4431aad7 100644 --- a/common/wivrn_sockets.cpp +++ b/common/wivrn_sockets.cpp @@ -19,6 +19,8 @@ #include "wivrn_sockets.h" +#include "crypto.h" +#include #include #include #include @@ -26,12 +28,16 @@ #include #include #include +#include #include #include #include #include #include +thread_local crypto::encrypt_context wivrn::UDP::encrypter{EVP_aes_128_ctr()}; +std::atomic 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::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 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 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 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 & 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 iovecs; + iovecs.clear(); - bytes_sent_ += sent; -} + std::vector> & data = packet; + + uint64_t counter; + if (encrypted) + { + counter = iv_counter.fetch_add(1); + + std::array 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> & data) -{ - thread_local std::vector 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> *> data) +void wivrn::UDP::send_many_raw(std::vector && packets) { thread_local std::vector iovecs; thread_local std::vector mmsgs; + thread_local std::vector 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> & 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 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 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> & spans) +void wivrn::TCP::send_raw(serialization_packet && packet) { thread_local std::vector iovecs; iovecs.clear(); + std::vector> & 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> & 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> & spans) } } -void wivrn::TCP::send_many_raw(std::span> *> data) +void wivrn::TCP::send_many_raw(std::vector && packets) { thread_local std::vector iovecs; thread_local std::vector sizes; + thread_local std::vector> 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> & 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> * }; 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> * hdr.msg_iov[0].iov_len -= sent; } } + +void wivrn::UDP::set_aes_key_and_ivs(std::span key_, std::span recv_iv_header_, std::span 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 key, std::span recv_iv, std::span 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); +} diff --git a/common/wivrn_sockets.h b/common/wivrn_sockets.h index 10801430..07627072 100644 --- a/common/wivrn_sockets.h +++ b/common/wivrn_sockets.h @@ -19,11 +19,13 @@ #pragma once +#include "crypto.h" #include "wivrn_serialization.h" #include #include #include +#include #include #include #include @@ -103,6 +105,16 @@ class UDP : public fd_base std::shared_ptr buffer; std::vector> messages; + crypto::decrypt_context decrypter; + static thread_local crypto::encrypt_context encrypter; + static std::atomic iv_counter; + static_assert(sizeof(iv_counter) == 8); + + bool encrypted = false; + std::array key; + std::array recv_iv_header; + std::array send_iv_header; + public: UDP(); explicit UDP(int fd); @@ -110,9 +122,8 @@ public: deserialization_packet receive_raw(); deserialization_packet receive_pending(); std::pair receive_from_raw(); - void send_raw(const std::vector & data); - void send_raw(const std::vector> & data); - void send_many_raw(std::span> *> data); + void send_raw(serialization_packet && packet); + void send_many_raw(std::vector && 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 key, std::span recv_iv_header, std::span 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> & data); - void send_many_raw(std::span> *> data); + void send_raw(serialization_packet && packet); + void send_many_raw(std::vector && packets); + + void set_aes_key_and_ivs(std::span key, std::span recv_iv, std::span 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 @@ -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> { static const std::size_t value = 1 + Index>::value; }; + +template +concept not_lvalue_reference = !std::is_lvalue_reference_v; + } // namespace details template @@ -224,21 +248,21 @@ public: p.serialize(data); } - template - void send(const T & data) + template + 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 & packets) + void send(std::vector && packets) { - thread_local std::vector> *> data; + thread_local std::vector 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)); } }; diff --git a/dashboard/main_window.cpp b/dashboard/main_window.cpp index 4de808ab..625766e1 100644 --- a/dashboard/main_window.cpp +++ b/dashboard/main_window.cpp @@ -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; diff --git a/dashboard/main_window.h b/dashboard/main_window.h index 0cc7bd90..00f1ed2c 100644 --- a/dashboard/main_window.h +++ b/dashboard/main_window.h @@ -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 &); diff --git a/dashboard/main_window.ui b/dashboard/main_window.ui index 44c3a8fa..3003ba46 100644 --- a/dashboard/main_window.ui +++ b/dashboard/main_window.ui @@ -14,7 +14,7 @@ WiVRn dashboard - + :/images/wivrn.svg:/images/wivrn.svg @@ -79,7 +79,7 @@ border-radius: 5px; - :/images/wivrn.svg + :/images/wivrn.svg @@ -136,7 +136,7 @@ border-radius: 5px; - :/images/wivrn.svg + :/images/wivrn.svg @@ -178,6 +178,58 @@ border-radius: 5px; + + + + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + + 14 + + + + PIN: + + + + + + + + 14 + + + + 000000 + + + + + + + Known headsets + + + + + + diff --git a/dashboard/wivrn_server.cpp b/dashboard/wivrn_server.cpp index ac23230a..bd48c167 100644 --- a/dashboard/wivrn_server.cpp +++ b/dashboard/wivrn_server.cpp @@ -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(changed_properties["RecommendedEyeSize"]); diff --git a/dashboard/wivrn_server.h b/dashboard/wivrn_server.h index 41c5c80b..ca9d1f1d 100644 --- a/dashboard/wivrn_server.h +++ b/dashboard/wivrn_server.h @@ -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 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 &); diff --git a/dashboard/wizard.cpp b/dashboard/wizard.cpp index 266107fb..ad8269d5 100644 --- a/dashboard/wizard.cpp +++ b/dashboard/wizard.cpp @@ -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) { diff --git a/dashboard/wizard.ui b/dashboard/wizard.ui index cc05312f..139de087 100644 --- a/dashboard/wizard.ui +++ b/dashboard/wizard.ui @@ -440,6 +440,28 @@ + + + + Use the following PIN to connect your headset: + + + + + + + + 14 + + + + 000000 + + + 12 + + + diff --git a/dbus/io.github.wivrn.Server.xml b/dbus/io.github.wivrn.Server.xml index 176560be..87801191 100644 --- a/dbus/io.github.wivrn.Server.xml +++ b/dbus/io.github.wivrn.Server.xml @@ -28,6 +28,13 @@ + + + + + + + @@ -52,5 +59,11 @@ + + + + + + diff --git a/server/accept_connection.cpp b/server/accept_connection.cpp index 29d3e96c..99003ae9 100644 --- a/server/accept_connection.cpp +++ b/server/accept_connection.cpp @@ -32,7 +32,7 @@ static void handle_event_from_main_loop(to_monado::disconnect) std::unique_ptr wivrn::accept_connection(int watch_fd, std::function 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::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(listener.accept().first); } diff --git a/server/audio/audio_pipewire.cpp b/server/audio/audio_pipewire.cpp index 57a99dac..991a68af 100644 --- a/server/audio/audio_pipewire.cpp +++ b/server/audio/audio_pipewire.cpp @@ -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) { diff --git a/server/audio/audio_pulse.cpp b/server/audio/audio_pulse.cpp index 89b0558b..3a3d5f7e 100644 --- a/server/audio/audio_pulse.cpp +++ b/server/audio/audio_pulse.cpp @@ -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 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(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(buffer.begin(), size), + }); } catch (std::exception & e) { diff --git a/server/driver/configuration.cpp b/server/driver/configuration.cpp index 49a141e4..b23d5666 100644 --- a/server/driver/configuration.cpp +++ b/server/driver/configuration.cpp @@ -17,16 +17,18 @@ * along with this program. If not, see . */ -#include -#include #define JSON_DISABLE_ENUM_SERIALIZATION 1 #ifdef JSON_DIAGNOSTICS #undef JSON_DIAGNOSTICS #endif #define JSON_DIAGNOSTICS 1 +#include +#include +#include #include #include #include +#include #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 known_keys() +{ + if (not std::filesystem::exists(known_keys_file)) + return {}; + + try + { + std::ifstream file(known_keys_file); + std::vector 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 & 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 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 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 keys = known_keys(); + for (headset_key & k: keys) + { + if (k.public_key == key.public_key) + k.name = key.name; + } + + save_keys(keys); +} + } // namespace wivrn diff --git a/server/driver/configuration.h b/server/driver/configuration.h index c91804c2..a185299e 100644 --- a/server/driver/configuration.h +++ b/server/driver/configuration.h @@ -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 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 diff --git a/server/driver/wivrn_comp_target.cpp b/server/driver/wivrn_comp_target.cpp index e2259237..dbeba657 100644 --- a/server/driver/wivrn_comp_target.cpp +++ b/server/driver/wivrn_comp_target.cpp @@ -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 foveation) diff --git a/server/driver/wivrn_connection.cpp b/server/driver/wivrn_connection.cpp index d801d14a..e13975a4 100644 --- a/server/driver/wivrn_connection.cpp +++ b/server/driver/wivrn_connection.cpp @@ -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 #include #include #include +#include +#include +#include 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 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 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(), (int)htons(peer_addr.sin6_port)); + } + + if (fds[1].revents & POLLIN) + { + std::optional 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(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(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(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(*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(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 tick) { + if (stream) + stream = decltype(stream)(); + control = std::move(tcp); - init(); + init({}, tick); } void wivrn::wivrn_connection::shutdown() diff --git a/server/driver/wivrn_connection.h b/server/driver/wivrn_connection.h index 3eb8e712..0ec8f6f4 100644 --- a/server/driver/wivrn_connection.h +++ b/server/driver/wivrn_connection.h @@ -27,21 +27,24 @@ #include #include #include +#include #include namespace wivrn { - class wivrn_connection { typed_socket control; typed_socket stream; std::atomic active = false; + std::string pin; - void init(); + wivrn::from_headset::headset_info_packet info_packet; + + void init(std::stop_token stop_token, std::function 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 tick = []() {}); void shutdown(); template @@ -66,15 +69,19 @@ public: throw; } } + template void send_stream(T && packet) { try { - if (active and stream) - stream.send(std::forward(packet)); - else - control.send(std::forward(packet)); + if (active) + { + if (stream) + stream.send(std::forward(packet)); + else + control.send(std::forward(packet)); + } } catch (...) { @@ -85,6 +92,11 @@ public: std::optional poll_control(int timeout); + const wivrn::from_headset::headset_info_packet & info() const + { + return info_packet; + } + template int poll(T && visitor, int timeout) { diff --git a/server/driver/wivrn_session.cpp b/server/driver/wivrn_session.cpp index 29dd7f6e..81c50a34 100644 --- a/server/driver/wivrn_session.cpp +++ b/server/driver/wivrn_session.cpp @@ -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 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 control; - while (not(control = connection.poll_control(-1))) - { - // FIXME: timeout - } - return std::get(*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(&hmd); foveation = std::make_unique(); 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(&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 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 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 control; - while (not(control = connection.poll_control(100))) - { - // FIXME: timeout - quit_if_no_client(xrt_system); - } - const auto & info = std::get(*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()); diff --git a/server/driver/wivrn_session.h b/server/driver/wivrn_session.h index de478c56..810ebf07 100644 --- a/server/driver/wivrn_session.h +++ b/server/driver/wivrn_session.h @@ -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 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 connection, u_system &); public: ~wivrn_session(); - static xrt_result_t create_session(TCP && tcp, + static xrt_result_t create_session(std::unique_ptr 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 void send_stream(T && packet) { - connection.send_stream(std::forward(packet)); + connection->send_stream(std::forward(packet)); } template void send_control(T && packet) { - connection.send_control(std::forward(packet)); + connection->send_control(std::forward(packet)); } std::array set_foveated_size(uint32_t width, uint32_t height); diff --git a/server/encoder/video_encoder.cpp b/server/encoder/video_encoder.cpp index d52a5acb..eea13d60 100644 --- a/server/encoder/video_encoder.cpp +++ b/server/encoder/video_encoder.cpp @@ -340,7 +340,7 @@ void video_encoder::SendData(std::span 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 (...) { diff --git a/server/main.cpp b/server/main.cpp index 889ef380..55607b14 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -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 #include #include +#include #include #include #include +#include #include #include @@ -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 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 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(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(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(*packet)) - { - on_headset_info_packet(std::get(*packet)); - inhibitor.emplace(); - wivrn_server_set_headset_connected(dbus_server, true); - } - else if (std::holds_alternative(*packet)) - { - stop_publishing(); - inhibitor.emplace(); - wivrn_server_set_headset_connected(dbus_server, true); - } - else if (std::holds_alternative(*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(*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(file), std::istreambuf_iterator()}; 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); diff --git a/server/target_instance_wivrn.cpp b/server/target_instance_wivrn.cpp index 43c477ed..b2a3352f 100644 --- a/server/target_instance_wivrn.cpp +++ b/server/target_instance_wivrn.cpp @@ -17,6 +17,7 @@ #include #include "driver/wivrn_session.h" +#include "wivrn_ipc.h" /* * @@ -24,8 +25,6 @@ * */ -extern std::unique_ptr 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; } diff --git a/server/wivrn_ipc.cpp b/server/wivrn_ipc.cpp index d167d976..78429b4b 100644 --- a/server/wivrn_ipc.cpp +++ b/server/wivrn_ipc.cpp @@ -18,12 +18,13 @@ */ #include "wivrn_ipc.h" +#include "driver/wivrn_connection.h" #include #include #include -std::unique_ptr tcp; +std::unique_ptr connection; struct cleanup_function { diff --git a/server/wivrn_ipc.h b/server/wivrn_ipc.h index 445966f5..1c27ecd7 100644 --- a/server/wivrn_ipc.h +++ b/server/wivrn_ipc.h @@ -27,16 +27,22 @@ #include #include -extern std::unique_ptr tcp; +namespace wivrn +{ +class wivrn_connection; +} + +extern std::unique_ptr connection; namespace from_monado { -struct headsdet_connected -{}; -struct headsdet_disconnected +struct headset_connected {}; -using packets = std::variant; +struct headset_disconnected +{}; + +using packets = std::variant; } // namespace from_monado namespace to_monado @@ -51,9 +57,9 @@ extern std::optional receive_from_main(); template -void send_to_main(T && packet) +void send_to_main(T packet) { - wivrn_ipc_socket_monado->send(std::forward(packet)); + wivrn_ipc_socket_monado->send(std::move(packet)); } void init_cleanup_functions(); diff --git a/tools/wireshark/dissector.cpp b/tools/wireshark/dissector.cpp index fe189582..dad97b4a 100644 --- a/tools/wireshark/dissector.cpp +++ b/tools/wireshark/dissector.cpp @@ -643,6 +643,43 @@ struct tree_traits } }; +template +struct tree_traits +{ + 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, + .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 struct tree_traits> {