From 502635b156db334e412862668b7f9e79d604a9e6 Mon Sep 17 00:00:00 2001 From: VallierDev <24893073+VallierDev@users.noreply.github.com> Date: Wed, 14 Oct 2026 23:53:16 +0800 Subject: [PATCH] Initial import of uu-remote-linux Unofficial Linux host for NetEase UU Remote: X11 (production-tested on GNOME/Ubuntu 24.04), experimental Wayland (Hyprland) and portal (GNOME/KDE) backends; video, input, clipboard, file transfer, terminal, sound, quality/fps/resolution settings, lock/unlock and system actions. Co-Authored-By: Claude Opus 5.5 --- .gitignore | 3 + Cargo.lock | 3131 +++++++++++++++++ Cargo.toml | 43 + README.en.md | 206 ++ README.md | 193 + build.rs | 83 + c_engine/clipboard.c | 134 + c_engine/clipboard_test.c | 72 + c_engine/login_window.c | 321 ++ c_engine/pam_check.c | 76 + c_engine/portal_clipboard.inc | 130 + c_engine/portal_engine.c | 466 +++ c_engine/portal_engine.h | 22 + .../virtual-keyboard-unstable-v1.xml | 113 + ...lr-output-power-management-unstable-v1.xml | 128 + .../wlr-screencopy-unstable-v1.xml | 232 ++ .../wlr-virtual-pointer-unstable-v1.xml | 152 + c_engine/wayland_engine.c | 277 ++ c_engine/x11_engine.c | 272 ++ config.example.json | 12 + docs/images/login-window.png | Bin 0 -> 85875 bytes src/audio.rs | 92 + src/auth.rs | 205 ++ src/capability.rs | 75 + src/capture.rs | 142 + src/capture_setting.rs | 237 ++ src/clipboard.rs | 193 + src/clipboard_probe.rs | 68 + src/clipboard_protocol.rs | 145 + src/clipboard_rich.rs | 186 + src/config.rs | 43 + src/control_protocol.rs | 207 ++ src/cursor.rs | 189 + src/desktop_backend.rs | 39 + src/file_trans.rs | 741 ++++ src/initialization.rs | 296 ++ src/input.rs | 200 ++ src/input_mapping.rs | 174 + src/login.rs | 374 ++ src/login_ui.rs | 78 + src/main.rs | 345 ++ src/network_diagnostics.rs | 227 ++ src/port_forward.rs | 61 + src/portal.rs | 182 + src/portal_permissions.rs | 71 + src/power.rs | 35 + src/protocol.rs | 108 + src/rtp_metadata.rs | 65 + src/session_ice.rs | 64 + src/session_lock.rs | 207 ++ src/signaling.rs | 250 ++ src/system_actions.rs | 274 ++ src/system_metrics.rs | 118 + src/terminal.rs | 321 ++ src/video.rs | 410 +++ src/viewer_metrics.rs | 72 + src/wayland.rs | 90 + src/webrtc.rs | 942 +++++ vendor/webrtc-dtls/.cargo-ok | 1 + vendor/webrtc-dtls/.cargo_vcs_info.json | 6 + vendor/webrtc-dtls/.gitignore | 12 + vendor/webrtc-dtls/CHANGELOG.md | 26 + vendor/webrtc-dtls/Cargo.toml | 172 + vendor/webrtc-dtls/Cargo.toml.orig | 82 + vendor/webrtc-dtls/LICENSE-APACHE | 201 ++ vendor/webrtc-dtls/LICENSE-MIT | 21 + vendor/webrtc-dtls/README.md | 30 + vendor/webrtc-dtls/codecov.yml | 23 + vendor/webrtc-dtls/doc/webrtc.rs.png | Bin 0 -> 33276 bytes .../examples/certificates/README.md | 60 + .../examples/certificates/client.csr | 7 + .../examples/certificates/client.pem | 5 + .../certificates/client.pem.private_key.pem | 5 + .../examples/certificates/client.pub.pem | 9 + .../examples/certificates/extfile.conf | 1 + .../examples/certificates/server.csr | 7 + .../examples/certificates/server.pem | 5 + .../certificates/server.pem.private_key.pem | 5 + .../examples/certificates/server.pub.pem | 9 + .../webrtc-dtls/examples/dial/psk/dial_psk.rs | 83 + .../examples/dial/selfsign/dial_selfsign.rs | 82 + .../examples/dial/verify/dial_verify.rs | 93 + .../examples/listen/psk/listen_psk.rs | 89 + .../listen/selfsign/listen_selfsign.rs | 87 + .../examples/listen/verify/listen_verify.rs | 118 + vendor/webrtc-dtls/src/alert/alert_test.rs | 50 + vendor/webrtc-dtls/src/alert/mod.rs | 185 + vendor/webrtc-dtls/src/application_data.rs | 37 + .../change_cipher_spec_test.rs | 37 + .../webrtc-dtls/src/change_cipher_spec/mod.rs | 42 + .../cipher_suite/cipher_suite_aes_128_ccm.rs | 118 + .../cipher_suite_aes_128_gcm_sha256.rs | 113 + .../cipher_suite_aes_256_cbc_sha.rs | 113 + ..._suite_tls_ecdhe_ecdsa_with_aes_128_ccm.rs | 12 + ...suite_tls_ecdhe_ecdsa_with_aes_128_ccm8.rs | 12 + .../cipher_suite_tls_psk_with_aes_128_ccm.rs | 12 + .../cipher_suite_tls_psk_with_aes_128_ccm8.rs | 12 + ...r_suite_tls_psk_with_aes_128_gcm_sha256.rs | 96 + vendor/webrtc-dtls/src/cipher_suite/mod.rs | 227 ++ .../src/client_certificate_type.rs | 16 + vendor/webrtc-dtls/src/compression_methods.rs | 60 + vendor/webrtc-dtls/src/config.rs | 190 + vendor/webrtc-dtls/src/conn/conn_test.rs | 2457 +++++++++++++ vendor/webrtc-dtls/src/conn/mod.rs | 1206 +++++++ .../src/conn/post_handshake_regression.rs | 78 + vendor/webrtc-dtls/src/content.rs | 81 + vendor/webrtc-dtls/src/crypto/crypto_cbc.rs | 128 + vendor/webrtc-dtls/src/crypto/crypto_ccm.rs | 188 + vendor/webrtc-dtls/src/crypto/crypto_gcm.rs | 119 + vendor/webrtc-dtls/src/crypto/crypto_test.rs | 221 ++ vendor/webrtc-dtls/src/crypto/mod.rs | 522 +++ vendor/webrtc-dtls/src/curve/mod.rs | 17 + vendor/webrtc-dtls/src/curve/named_curve.rs | 83 + vendor/webrtc-dtls/src/error.rs | 224 ++ .../src/extension/extension_server_name.rs | 56 + .../extension_server_name_test.rs | 26 + .../extension_supported_elliptic_curves.rs | 46 + ...xtension_supported_elliptic_curves_test.rs | 32 + .../extension_supported_point_formats.rs | 49 + .../extension_supported_point_formats_test.rs | 33 + ...xtension_supported_signature_algorithms.rs | 50 + ...ion_supported_signature_algorithms_test.rs | 48 + .../extension_use_extended_master_secret.rs | 35 + ...tension_use_extended_master_secret_test.rs | 32 + .../src/extension/extension_use_srtp.rs | 80 + .../extension_use_srtp_test.rs | 32 + vendor/webrtc-dtls/src/extension/mod.rs | 130 + .../src/extension/renegotiation_info.rs | 48 + .../renegotiation_info_test.rs | 26 + vendor/webrtc-dtls/src/flight/flight0.rs | 203 ++ vendor/webrtc-dtls/src/flight/flight1.rs | 193 + vendor/webrtc-dtls/src/flight/flight2.rs | 131 + vendor/webrtc-dtls/src/flight/flight3.rs | 470 +++ vendor/webrtc-dtls/src/flight/flight4.rs | 850 +++++ vendor/webrtc-dtls/src/flight/flight5.rs | 771 ++++ vendor/webrtc-dtls/src/flight/flight6.rs | 190 + vendor/webrtc-dtls/src/flight/mod.rs | 87 + .../fragment_buffer/fragment_buffer_test.rs | 174 + vendor/webrtc-dtls/src/fragment_buffer/mod.rs | 160 + .../src/handshake/handshake_cache.rs | 241 ++ .../handshake_cache/handshake_cache_test.rs | 658 ++++ .../src/handshake/handshake_header.rs | 50 + .../handshake_message_certificate.rs | 70 + .../handshake_message_certificate_test.rs | 79 + .../handshake_message_certificate_request.rs | 77 + ...dshake_message_certificate_request_test.rs | 64 + .../handshake_message_certificate_verify.rs | 52 + ...ndshake_message_certificate_verify_test.rs | 40 + .../handshake_message_client_hello.rs | 196 ++ .../handshake_message_client_hello_test.rs | 75 + .../handshake_message_client_key_exchange.rs | 70 + ...dshake_message_client_key_exchange_test.rs | 35 + .../handshake/handshake_message_finished.rs | 34 + .../handshake_message_finished_test.rs | 32 + .../handshake_message_hello_verify_request.rs | 72 + ...shake_message_hello_verify_request_test.rs | 40 + .../handshake_message_server_hello.rs | 151 + .../handshake_message_server_hello_test.rs | 56 + .../handshake_message_server_hello_done.rs | 27 + ...andshake_message_server_hello_done_test.rs | 28 + .../handshake_message_server_key_exchange.rs | 133 + ...dshake_message_server_key_exchange_test.rs | 50 + .../src/handshake/handshake_random.rs | 67 + .../src/handshake/handshake_test.rs | 70 + vendor/webrtc-dtls/src/handshake/mod.rs | 238 ++ vendor/webrtc-dtls/src/handshaker.rs | 410 +++ vendor/webrtc-dtls/src/lib.rs | 57 + vendor/webrtc-dtls/src/listener.rs | 95 + vendor/webrtc-dtls/src/prf/mod.rs | 315 ++ vendor/webrtc-dtls/src/prf/prf_test.rs | 261 ++ vendor/webrtc-dtls/src/record_layer/mod.rs | 107 + .../src/record_layer/record_layer_header.rs | 90 + .../src/record_layer/record_layer_test.rs | 118 + .../src/signature_hash_algorithm/mod.rs | 215 ++ .../signature_hash_algorithm_test.rs | 141 + vendor/webrtc-dtls/src/state.rs | 304 ++ 176 files changed, 30257 insertions(+) create mode 100644 .gitignore create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 README.en.md create mode 100644 README.md create mode 100644 build.rs create mode 100644 c_engine/clipboard.c create mode 100644 c_engine/clipboard_test.c create mode 100644 c_engine/login_window.c create mode 100644 c_engine/pam_check.c create mode 100644 c_engine/portal_clipboard.inc create mode 100644 c_engine/portal_engine.c create mode 100644 c_engine/portal_engine.h create mode 100644 c_engine/wayland-protocols/virtual-keyboard-unstable-v1.xml create mode 100644 c_engine/wayland-protocols/wlr-output-power-management-unstable-v1.xml create mode 100644 c_engine/wayland-protocols/wlr-screencopy-unstable-v1.xml create mode 100644 c_engine/wayland-protocols/wlr-virtual-pointer-unstable-v1.xml create mode 100644 c_engine/wayland_engine.c create mode 100644 c_engine/x11_engine.c create mode 100644 config.example.json create mode 100644 docs/images/login-window.png create mode 100644 src/audio.rs create mode 100644 src/auth.rs create mode 100644 src/capability.rs create mode 100644 src/capture.rs create mode 100644 src/capture_setting.rs create mode 100644 src/clipboard.rs create mode 100644 src/clipboard_probe.rs create mode 100644 src/clipboard_protocol.rs create mode 100644 src/clipboard_rich.rs create mode 100644 src/config.rs create mode 100644 src/control_protocol.rs create mode 100644 src/cursor.rs create mode 100644 src/desktop_backend.rs create mode 100644 src/file_trans.rs create mode 100644 src/initialization.rs create mode 100644 src/input.rs create mode 100644 src/input_mapping.rs create mode 100644 src/login.rs create mode 100644 src/login_ui.rs create mode 100644 src/main.rs create mode 100644 src/network_diagnostics.rs create mode 100644 src/port_forward.rs create mode 100644 src/portal.rs create mode 100644 src/portal_permissions.rs create mode 100644 src/power.rs create mode 100644 src/protocol.rs create mode 100644 src/rtp_metadata.rs create mode 100644 src/session_ice.rs create mode 100644 src/session_lock.rs create mode 100644 src/signaling.rs create mode 100644 src/system_actions.rs create mode 100644 src/system_metrics.rs create mode 100644 src/terminal.rs create mode 100644 src/video.rs create mode 100644 src/viewer_metrics.rs create mode 100644 src/wayland.rs create mode 100644 src/webrtc.rs create mode 100644 vendor/webrtc-dtls/.cargo-ok create mode 100644 vendor/webrtc-dtls/.cargo_vcs_info.json create mode 100644 vendor/webrtc-dtls/.gitignore create mode 100644 vendor/webrtc-dtls/CHANGELOG.md create mode 100644 vendor/webrtc-dtls/Cargo.toml create mode 100644 vendor/webrtc-dtls/Cargo.toml.orig create mode 100644 vendor/webrtc-dtls/LICENSE-APACHE create mode 100644 vendor/webrtc-dtls/LICENSE-MIT create mode 100644 vendor/webrtc-dtls/README.md create mode 100644 vendor/webrtc-dtls/codecov.yml create mode 100644 vendor/webrtc-dtls/doc/webrtc.rs.png create mode 100644 vendor/webrtc-dtls/examples/certificates/README.md create mode 100644 vendor/webrtc-dtls/examples/certificates/client.csr create mode 100644 vendor/webrtc-dtls/examples/certificates/client.pem create mode 100644 vendor/webrtc-dtls/examples/certificates/client.pem.private_key.pem create mode 100644 vendor/webrtc-dtls/examples/certificates/client.pub.pem create mode 100644 vendor/webrtc-dtls/examples/certificates/extfile.conf create mode 100644 vendor/webrtc-dtls/examples/certificates/server.csr create mode 100644 vendor/webrtc-dtls/examples/certificates/server.pem create mode 100644 vendor/webrtc-dtls/examples/certificates/server.pem.private_key.pem create mode 100644 vendor/webrtc-dtls/examples/certificates/server.pub.pem create mode 100644 vendor/webrtc-dtls/examples/dial/psk/dial_psk.rs create mode 100644 vendor/webrtc-dtls/examples/dial/selfsign/dial_selfsign.rs create mode 100644 vendor/webrtc-dtls/examples/dial/verify/dial_verify.rs create mode 100644 vendor/webrtc-dtls/examples/listen/psk/listen_psk.rs create mode 100644 vendor/webrtc-dtls/examples/listen/selfsign/listen_selfsign.rs create mode 100644 vendor/webrtc-dtls/examples/listen/verify/listen_verify.rs create mode 100644 vendor/webrtc-dtls/src/alert/alert_test.rs create mode 100644 vendor/webrtc-dtls/src/alert/mod.rs create mode 100644 vendor/webrtc-dtls/src/application_data.rs create mode 100644 vendor/webrtc-dtls/src/change_cipher_spec/change_cipher_spec_test.rs create mode 100644 vendor/webrtc-dtls/src/change_cipher_spec/mod.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_ccm.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_gcm_sha256.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_256_cbc_sha.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm8.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_gcm_sha256.rs create mode 100644 vendor/webrtc-dtls/src/cipher_suite/mod.rs create mode 100644 vendor/webrtc-dtls/src/client_certificate_type.rs create mode 100644 vendor/webrtc-dtls/src/compression_methods.rs create mode 100644 vendor/webrtc-dtls/src/config.rs create mode 100644 vendor/webrtc-dtls/src/conn/conn_test.rs create mode 100644 vendor/webrtc-dtls/src/conn/mod.rs create mode 100644 vendor/webrtc-dtls/src/conn/post_handshake_regression.rs create mode 100644 vendor/webrtc-dtls/src/content.rs create mode 100644 vendor/webrtc-dtls/src/crypto/crypto_cbc.rs create mode 100644 vendor/webrtc-dtls/src/crypto/crypto_ccm.rs create mode 100644 vendor/webrtc-dtls/src/crypto/crypto_gcm.rs create mode 100644 vendor/webrtc-dtls/src/crypto/crypto_test.rs create mode 100644 vendor/webrtc-dtls/src/crypto/mod.rs create mode 100644 vendor/webrtc-dtls/src/curve/mod.rs create mode 100644 vendor/webrtc-dtls/src/curve/named_curve.rs create mode 100644 vendor/webrtc-dtls/src/error.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_server_name.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_server_name/extension_server_name_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves/extension_supported_elliptic_curves_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_point_formats.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_point_formats/extension_supported_point_formats_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms/extension_supported_signature_algorithms_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret/extension_use_extended_master_secret_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_use_srtp.rs create mode 100644 vendor/webrtc-dtls/src/extension/extension_use_srtp/extension_use_srtp_test.rs create mode 100644 vendor/webrtc-dtls/src/extension/mod.rs create mode 100644 vendor/webrtc-dtls/src/extension/renegotiation_info.rs create mode 100644 vendor/webrtc-dtls/src/extension/renegotiation_info/renegotiation_info_test.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight0.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight1.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight2.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight3.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight4.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight5.rs create mode 100644 vendor/webrtc-dtls/src/flight/flight6.rs create mode 100644 vendor/webrtc-dtls/src/flight/mod.rs create mode 100644 vendor/webrtc-dtls/src/fragment_buffer/fragment_buffer_test.rs create mode 100644 vendor/webrtc-dtls/src/fragment_buffer/mod.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_cache.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_cache/handshake_cache_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_header.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate/handshake_message_certificate_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request/handshake_message_certificate_request_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify/handshake_message_certificate_verify_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_client_hello.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_client_hello/handshake_message_client_hello_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange/handshake_message_client_key_exchange_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_finished.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_finished/handshake_message_finished_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request/handshake_message_hello_verify_request_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_hello.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_hello/handshake_message_server_hello_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done/handshake_message_server_hello_done_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange/handshake_message_server_key_exchange_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_random.rs create mode 100644 vendor/webrtc-dtls/src/handshake/handshake_test.rs create mode 100644 vendor/webrtc-dtls/src/handshake/mod.rs create mode 100644 vendor/webrtc-dtls/src/handshaker.rs create mode 100644 vendor/webrtc-dtls/src/lib.rs create mode 100644 vendor/webrtc-dtls/src/listener.rs create mode 100644 vendor/webrtc-dtls/src/prf/mod.rs create mode 100644 vendor/webrtc-dtls/src/prf/prf_test.rs create mode 100644 vendor/webrtc-dtls/src/record_layer/mod.rs create mode 100644 vendor/webrtc-dtls/src/record_layer/record_layer_header.rs create mode 100644 vendor/webrtc-dtls/src/record_layer/record_layer_test.rs create mode 100644 vendor/webrtc-dtls/src/signature_hash_algorithm/mod.rs create mode 100644 vendor/webrtc-dtls/src/signature_hash_algorithm/signature_hash_algorithm_test.rs create mode 100644 vendor/webrtc-dtls/src/state.rs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8e84b83 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +target/ +*.log +.DS_Store diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..e0d8d80 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,3131 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "aes" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures 0.2.17", +] + +[[package]] +name = "aes-gcm" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "831010a0f742e1209b3bcea8fab6a8e149051ba6099432c8cb2cc117dec3ead1" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ghash", + "subtle", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "arc-swap" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b" +dependencies = [ + "rustversion", +] + +[[package]] +name = "asn1-rs" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6fd5ddaf0351dff5b8da21b2fb4ff8e08ddd02857f0bf69c47639106c0fff0" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom", + "num-traits", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "synstructure 0.12.6", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base64" +version = "0.21.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567" + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bincode" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad" +dependencies = [ + "serde", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block-padding" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8894febbff9f758034a5b8e12d87918f56dfc64a8e1fe757d65e29041538d93" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cbc" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26b52a9543ae338f279b96b0b9fed9c8093744685043739079ce85cd58f289a6" +dependencies = [ + "cipher", +] + +[[package]] +name = "cc" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "ccm" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae3c82e4355234767756212c570e29833699ab63e6ffd161887314cc5b43847" +dependencies = [ + "aead", + "cipher", + "ctr", + "subtle", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "typenum", +] + +[[package]] +name = "ctr" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" +dependencies = [ + "cipher", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "defmt" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1" +dependencies = [ + "bitflags 1.3.2", + "defmt-macros", +] + +[[package]] +name = "defmt-macros" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8" +dependencies = [ + "defmt-parser", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "defmt-parser" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der-parser" +version = "8.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbd676fbbab537128ef0278adb5576cf363cff6aa22a7b24effe97347cfab61e" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom", + "num-bigint", + "num-traits", + "rusticata-macros", +] + +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "env_filter" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900d271a03799a1ee8d1ca9b19893b48ca674a9284fefcfb85f05e74ed314217" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de671bd27a75a797dc9ae289ba1e77276e75e2026408aab65185384e2d5cd3f6" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "ghash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0d8a4362ccb29cb0b265253fb0a2728f592895ee6854fd9bc13f2ffda266ff1" +dependencies = [ + "opaque-debug", + "polyval", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls 0.23.45", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots 1.0.9", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2 0.6.5", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0" + +[[package]] +name = "icu_properties" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa" + +[[package]] +name = "icu_provider" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "block-padding", + "generic-array", +] + +[[package]] +name = "interceptor" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b12e186d2a4c21225df6beb8ae5d81817c928da12e7ce78d0953fc74d88b590" +dependencies = [ + "async-trait", + "bytes", + "log", + "rand 0.8.8", + "rtcp", + "rtp", + "thiserror 1.0.69", + "tokio", + "waitgroup", + "webrtc-srtp", + "webrtc-util", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2b005715dcbeb0089a3c0dab99f2ff1cc3b2525323552703d648585d342a383" +dependencies = [ + "defmt", + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c" +dependencies = [ + "defmt", + "log", +] + +[[package]] +name = "jiff-static" +version = "0.2.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cc9817253cf7c7ee4684451bd327e88d6f3658014e54a29198625590650695c" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.190" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memoffset" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5de893c32cde5f383baa4c04c5d6dbdd735cfd4a794b0debdb2bb1b421da5ff4" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nix" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "598beaf3cc6fdd9a5dfb1630c2800c7acd31df7aaf0f565796fba2b53ca1af1b" +dependencies = [ + "bitflags 1.3.2", + "cfg-if", + "libc", + "memoffset", + "pin-utils", +] + +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "oid-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bedf36ffb6ba96c2eb7144ef6270557b52e54b20c0a8e1eb2ff99a6c6959bff" +dependencies = [ + "asn1-rs", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64 0.22.1", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "polyval" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1fe60d06143b2430aa532c94cfe9e29783047f06c0d7fd359a9a51b729fa25" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls 0.23.45", + "socket2 0.6.5", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.3", + "rand_pcg", + "ring 0.17.14", + "rustc-hash", + "rustls 0.23.45", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2 0.6.5", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rcgen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52c4f3084aa3bc7dfbba4eff4fab2a54db4324965d8872ab933565e6fbd83bc6" +dependencies = [ + "pem", + "ring 0.16.20", + "time", + "x509-parser", + "yasna", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls 0.23.45", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "webpki-roots 1.0.9", +] + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted 0.7.1", + "web-sys", + "winapi", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted 0.9.0", + "windows-sys 0.52.0", +] + +[[package]] +name = "rtcp" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33648a781874466a62d89e265fee9f17e32bc7d05a256e6cca41bf97eadcd8aa" +dependencies = [ + "bytes", + "thiserror 1.0.69", + "webrtc-util", +] + +[[package]] +name = "rtp" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47fca9bd66ae0b1f3f649b8f5003d6176433d7293b78b0fce7e1031816bdd99d" +dependencies = [ + "bytes", + "rand 0.8.8", + "serde", + "thiserror 1.0.69", + "webrtc-util", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom", +] + +[[package]] +name = "rustls" +version = "0.21.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f56a14d1f48b391359b22f731fd4bd7e43c97f3c50eee276f3aa09c94784d3e" +dependencies = [ + "log", + "ring 0.17.14", + "rustls-webpki 0.101.7", + "sct", +] + +[[package]] +name = "rustls" +version = "0.23.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d41d731c7d2f962d1ccc364cec258de3c0e93b38c2fb3ba97ac74513048d634" +dependencies = [ + "once_cell", + "ring 0.17.14", + "rustls-pki-types", + "rustls-webpki 0.103.15", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.101.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b6275d1ee7a1cd780b64aca7726599a1dbc893b1e64144529e55c3c2f745765" +dependencies = [ + "ring 0.17.14", + "untrusted 0.9.0", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2" +dependencies = [ + "ring 0.17.14", + "rustls-pki-types", + "untrusted 0.9.0", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sct" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da046153aa2352493d6cb7da4b6e5c0c057d8a1d0a9aa8560baffdd945acd414" +dependencies = [ + "ring 0.17.14", + "untrusted 0.9.0", +] + +[[package]] +name = "sdp" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13254db766b17451aced321e7397ebf0a446ef0c8d2942b6e67a95815421093f" +dependencies = [ + "rand 0.8.8", + "substring", + "thiserror 1.0.69", + "url", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "socket2" +version = "0.5.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678" +dependencies = [ + "libc", + "windows-sys 0.52.0", +] + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "stun" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3f371788132e9d623e6eab4ba28aac083763a4133f045e6ebaee5ceb869803d" +dependencies = [ + "base64 0.21.7", + "crc", + "lazy_static", + "md-5", + "rand 0.8.8", + "ring 0.17.14", + "subtle", + "thiserror 1.0.69", + "tokio", + "url", + "webrtc-util", +] + +[[package]] +name = "substring" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42ee6433ecef213b2e72f587ef64a2f5943e7cd16fbd82dbe8bc07486c534c86" +dependencies = [ + "autocfg", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.12.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" +dependencies = [ + "proc-macro2", + "quote", + "syn 1.0.109", + "unicode-xid", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.53.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2 0.6.5", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls 0.23.45", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6989540ced10490aaf14e6bad2e3d33728a2813310a0c71d1574304c49631cd" +dependencies = [ + "futures-util", + "log", + "rustls 0.23.45", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e2ce1e47ed2994fd43b04c8f618008d4cabdd5ee34027cf14f9d918edd9c8" +dependencies = [ + "byteorder", + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.8.8", + "rustls 0.23.45", + "rustls-pki-types", + "sha1", + "thiserror 1.0.69", + "utf-8", +] + +[[package]] +name = "turn" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffb2ac4f331064513ad510b7a36edc0df555bd61672986607f7c9ff46f98f415" +dependencies = [ + "async-trait", + "base64 0.21.7", + "futures", + "log", + "md-5", + "rand 0.8.8", + "ring 0.17.14", + "stun", + "thiserror 1.0.69", + "tokio", + "tokio-util", + "webrtc-util", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "uu-remote-linux" +version = "1.0.0" +dependencies = [ + "base64 0.22.1", + "bytes", + "cc", + "env_logger", + "flate2", + "futures-util", + "hex", + "hmac", + "libc", + "log", + "nix 0.29.0", + "qrcode", + "reqwest", + "serde", + "serde_json", + "sha2", + "tokio", + "tokio-tungstenite", + "webrtc", +] + +[[package]] +name = "uuid" +version = "1.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606" +dependencies = [ + "getrandom 0.4.3", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "waitgroup" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1f50000a783467e6c0200f9d10642f4bc424e39efc1b770203e88b488f79292" +dependencies = [ + "atomic-waker", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.9", +] + +[[package]] +name = "webpki-roots" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webrtc" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbdf025f0fa62f4bf252b2fb0cff0a04d3eac2021c440096649e62f4e48553d" +dependencies = [ + "arc-swap", + "async-trait", + "bytes", + "cfg-if", + "hex", + "interceptor", + "lazy_static", + "log", + "rand 0.8.8", + "rcgen", + "regex", + "ring 0.17.14", + "rtcp", + "rtp", + "rustls 0.21.12", + "sdp", + "serde", + "serde_json", + "sha2", + "smol_str", + "stun", + "thiserror 1.0.69", + "time", + "tokio", + "turn", + "url", + "waitgroup", + "webrtc-data", + "webrtc-dtls", + "webrtc-ice", + "webrtc-mdns", + "webrtc-media", + "webrtc-sctp", + "webrtc-srtp", + "webrtc-util", +] + +[[package]] +name = "webrtc-data" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8c08e648e10572b9edbe741074e0f4d3cb221aa7cdf9a814ee71606de312f33" +dependencies = [ + "bytes", + "log", + "thiserror 1.0.69", + "tokio", + "webrtc-sctp", + "webrtc-util", +] + +[[package]] +name = "webrtc-dtls" +version = "0.9.0" +dependencies = [ + "aes", + "aes-gcm", + "async-trait", + "bincode", + "byteorder", + "cbc", + "ccm", + "der-parser", + "hkdf", + "hmac", + "log", + "p256", + "p384", + "rand 0.8.8", + "rand_core 0.6.4", + "rcgen", + "ring 0.17.14", + "rustls 0.21.12", + "sec1", + "serde", + "sha1", + "sha2", + "subtle", + "thiserror 1.0.69", + "tokio", + "webrtc-util", + "x25519-dalek", + "x509-parser", +] + +[[package]] +name = "webrtc-ice" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1bbd6b3dea22cc6e961e22b012e843d8869e2ac8e76b96e54d4a25e311857ad" +dependencies = [ + "arc-swap", + "async-trait", + "crc", + "log", + "rand 0.8.8", + "serde", + "serde_json", + "stun", + "thiserror 1.0.69", + "tokio", + "turn", + "url", + "uuid", + "waitgroup", + "webrtc-mdns", + "webrtc-util", +] + +[[package]] +name = "webrtc-mdns" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce981f93104a8debb3563bb0cedfe4aa2f351fdf6b53f346ab50009424125c08" +dependencies = [ + "log", + "socket2 0.5.10", + "thiserror 1.0.69", + "tokio", + "webrtc-util", +] + +[[package]] +name = "webrtc-media" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "280017b6b9625ef7329146332518b339c3cceff231cc6f6a9e0e6acab25ca4af" +dependencies = [ + "byteorder", + "bytes", + "rand 0.8.8", + "rtp", + "thiserror 1.0.69", +] + +[[package]] +name = "webrtc-sctp" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df75ec042002fe995194712cbeb2029107a60a7eab646f1b789eb1be94d0e367" +dependencies = [ + "arc-swap", + "async-trait", + "bytes", + "crc", + "log", + "rand 0.8.8", + "thiserror 1.0.69", + "tokio", + "webrtc-util", +] + +[[package]] +name = "webrtc-srtp" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383b0f0f73ee6cce396bdbc4d54ec661861a59eae9fc988914c1a8d82c5ac272" +dependencies = [ + "aead", + "aes", + "aes-gcm", + "byteorder", + "bytes", + "ctr", + "hmac", + "log", + "rtcp", + "rtp", + "sha1", + "subtle", + "thiserror 1.0.69", + "tokio", + "webrtc-util", +] + +[[package]] +name = "webrtc-util" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e85154ef743d9a2a116d104faaaa82740a281b8b4bed5ee691a2df6c133d873" +dependencies = [ + "async-trait", + "bitflags 1.3.2", + "bytes", + "ipnet", + "lazy_static", + "libc", + "log", + "nix 0.26.4", + "rand 0.8.8", + "thiserror 1.0.69", + "tokio", + "winapi", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x25519-dalek" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7e468321c81fb07fa7f4c636c3972b9100f0346e5b6a9f2bd0603a52f7ed277" +dependencies = [ + "curve25519-dalek", + "rand_core 0.6.4", + "serde", + "zeroize", +] + +[[package]] +name = "x509-parser" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7069fba5b66b9193bd2c5d3d4ff12b839118f6bcbef5328efafafb5395cf63da" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom", + "oid-registry", + "ring 0.16.20", + "rusticata-macros", + "thiserror 1.0.69", + "time", +] + +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zerocopy" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86502bf56ac7c77571a32e2647bb2a15894565e981fb2a48d7bde2d91c965a9d" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.62" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5457206954b06561e2608c7e19cf58b1926586d999c246eebe4502f7e2039d1a" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure 0.14.0", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..af2a98a --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,43 @@ +[package] +name = "uu-remote-linux" +version = "1.0.0" +edition = "2021" +authors = ["uu-remote-linux contributors"] +description = "Unofficial Linux host for NetEase UU Remote: control a Linux desktop from the official clients" +readme = "README.md" + +# The executable keeps its established name (deploy scripts, systemd units, docs). +[[bin]] +name = "uuremote-server" +path = "src/main.rs" + +[features] +default = [] +wayland = [] +portal = [] + +[dependencies] +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = { version = "0.23", features = ["rustls-tls-webpki-roots"] } +futures-util = "0.3" +serde = { version = "1.0", features = ["derive"] } +serde_json = "1.0" +reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] } +hmac = "0.12" +sha2 = "0.10" +hex = "0.4" +base64 = "0.22" +flate2 = "1.0" +bytes = "1" +webrtc = "0.10" +libc = "0.2" +nix = { version = "0.29", features = ["term", "process", "fs", "ioctl", "signal"] } +log = "0.4" +qrcode = { version = "0.14", default-features = false } +env_logger = "0.11" + +[build-dependencies] +cc = "1.0" + +[patch.crates-io] +webrtc-dtls = { path = "vendor/webrtc-dtls" } diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..03117ef --- /dev/null +++ b/README.en.md @@ -0,0 +1,206 @@ +# uu-remote-linux · Unofficial Linux host for NetEase UU Remote + +[简体中文](README.md) | **English** + +> **A note first** +> +> NetEase UU Remote (网易 UU 远程) is a great remote-desktop tool, but there is no Linux version on its +> official website. So, with the help of Claude and Codex, I wrote this open-source Linux host: install it, +> and you can control your Linux machine from the official Mac / Windows / mobile UU Remote clients. +> +> This is a personal hobby project. **It is not affiliated with NetEase and is not an official client.** +> If NetEase considers this project infringing or inappropriate, please DM me on X +> **[@ai_fengshou](https://x.com/ai_fengshou)** and I will take it down right away. + +

QR login window on the Linux host

+

The QR login window shown on first run (QR code blurred). The UI is in Chinese, like the official app.

+ + + + +## What it is + +- A native Linux program written in Rust: no Wine, no Windows or macOS components. +- Log in by scanning a QR code with your own UU Remote account. The Linux machine then appears in the + official clients' device list and is used just like a Windows host. +- **Host only.** To control other machines you still use the official Mac / Windows / mobile apps. + +## Features + +| Feature | Notes | +|---|---| +| QR login | GTK login window (or a terminal QR code with `login --no-gui`); expired codes refresh automatically; the service opens the login window by itself when credentials are missing or expired | +| Remote desktop | H.264 video, NVENC hardware encoding on NVIDIA GPUs, libx264 otherwise; the viewer draws its local pointer, so there is no double cursor | +| Mouse / keyboard | Absolute and relative motion, clicks, wheel, keys; no spurious key repeat on high-latency links | +| Pointer shape | Remote cursor shape is mirrored to the viewer (X11) | +| Clipboard | Two-way text sync | +| Quality / frame rate / resolution | Auto, Original 20M, Ultra 8M, HD 2M, custom; 30/60/90/144 fps; "other resolutions" are scaled by the encoder, the host monitor is left untouched | +| Sound | System audio captured from PulseAudio / PipeWire and sent as Opus | +| File transfer | Upload, download (including folders), create folder, rename, delete | +| Terminal | The official "Terminal" tool, PTY sessions, multiple sessions, rename | +| Lock state and auto unlock | Lock state is reported to the viewer; with "auto unlock" enabled in the client, the password is verified with PAM and the session is unlocked | +| Lock after remote session | Stored on the host, so it still applies after reconnecting | +| Mute host while controlled | Host speakers are muted while the viewer still hears the sound; the previous mute state is restored afterwards | +| System actions | Lock, show desktop, task manager (system monitor), reboot, shut down | +| Reconnects | Every tool window has its own connection; they do not disturb each other | + +## Supported Linux desktops + +| Desktop | Display protocol | Status | Build | +|---|---|---|---| +| GNOME (Ubuntu 24.04) | X11 / Xorg | ✅ In daily use on real hardware; every feature above accepted | default | +| KDE Plasma | X11 | ✅ Tested in a VM | default | +| Xfce | X11 | ✅ Tested in a VM | default | +| Cinnamon / MATE | X11 | ✅ Tested in a VM | default | +| Hyprland | Wayland (native wlroots protocols) | ✅ Tested in a VM (some features limited, see below) | `--features wayland` | +| GNOME / KDE Plasma | Wayland (xdg-desktop-portal) | ✅ Tested in a VM (some features limited, see below) | `--features wayland,portal` | + +Apart from GNOME on X11, these desktops have been tested in virtual machines so far. If something goes wrong on +real hardware, please [open an issue](../../issues) with your distribution, desktop, GPU and the relevant lines from +`journalctl --user -u uuremote-native.service`. + +Wayland limits: single screen, fixed resolution. The portal backend does not support clipboard, screen wake or +dynamic resolution yet. On the first connection the desktop asks for "Remote Desktop / Screen Sharing" +permission; the permission is remembered once granted. + +## Not implemented / not supported + +| Feature | Status | +|---|---| +| Switching between multiple monitors | In progress | +| True color (4:4:4) | Not implemented; not declared in the handshake, so the client does not enable it | +| HDR | Not implemented | +| Super screen / virtual display | Not implemented | +| Privacy screen on the host | Not implemented | +| Microphone (viewer audio played on the host) | Not implemented (needs a virtual sound card) | +| Plugins such as the WoW queue notifier | Not supported; the client is told that no plugins exist | +| Access before login (greeter / no user logged in) | Not supported; only an already logged-in desktop session can be controlled | +| Port mapping | Code exists, not yet accepted | +| Relay connections on restrictive networks | Uses the ICE servers provided by the UU cloud; complex network setups are not thoroughly tested | +| Acting as a viewer (controlling other machines from Linux) | Out of scope | + +## Installation + +### 1. Dependencies (Ubuntu / Debian) + +```sh +sudo apt install build-essential pkg-config \ + libx11-dev libxext-dev libxtst-dev libxfixes-dev \ + libgtk-3-dev ffmpeg +# optional: Wayland backend +sudo apt install libwayland-dev libxkbcommon-dev wl-clipboard +# optional: GNOME/KDE portal backend +sudo apt install libglib2.0-dev libpipewire-0.3-dev +``` + +- A Rust toolchain is required (). +- `libgtk-3-dev` is optional. Without GTK, login works with a QR code in the terminal (`UU_NO_GTK=1` disables + the login window explicitly). +- On NVIDIA GPUs use an FFmpeg build with `h264_nvenc`; otherwise the CPU encoder (libx264) is used. + +### 2. Build + +```sh +cargo build --release # X11 +cargo build --release --features wayland # + Hyprland +cargo build --release --features wayland,portal # + GNOME/KDE on Wayland +``` + +### 3. Log in + +Run inside your graphical session: + +```sh +./target/release/uuremote-server login +``` + +Scan the code with the **NetEase UU Remote mobile app** and confirm. Credentials are stored only on this +machine, in `~/.config/uuremote/config.json` (mode 0600). + +### 4. Run as a user service + +`~/.config/systemd/user/uuremote-native.service`: + +```ini +[Unit] +Description=UU Remote Linux host (unofficial) +After=graphical-session.target + +[Service] +Environment=RUST_LOG=info +# X11 desktops need the display; on GNOME, XAUTHORITY is usually /run/user//gdm/Xauthority +Environment=DISPLAY=:0 +ExecStart=%h/.local/bin/uuremote-server +Restart=always +RestartSec=5 + +[Install] +WantedBy=default.target +``` + +```sh +install -Dm755 target/release/uuremote-server ~/.local/bin/uuremote-server +systemctl --user daemon-reload +systemctl --user enable --now uuremote-native.service +journalctl --user -u uuremote-native.service -f # online once you see availability=Some("ready") +``` + +If you have not logged in yet, the service opens the QR login window on your desktop. + +## Configuration + +Common environment variables: + +| Variable | Purpose | +|---|---| +| `UU_CONFIG` | Config file path (default `~/.config/uuremote/config.json`) | +| `UU_DESKTOP_BACKEND` | `auto` / `x11` / `wayland` / `portal` | +| `UU_VIDEO_ENCODER=cpu` | Force CPU encoding | +| `UU_FFMPEG_ROOT` | Use FFmpeg from this prefix | +| `UU_AUDIO=0` | Disable sound; `UU_AUDIO_SOURCE` picks the PulseAudio source | +| `UU_LOGIN_WINDOW=0` | Do not open the login window automatically when credentials are missing | + +Host settings such as "lock after remote session" and "mute host" are stored in +`~/.config/uuremote/host_settings.json`. + +## How it works + +```mermaid +flowchart LR + App["Official client
Mac / Windows / mobile"] <-- "WebRTC: video · audio · data channels" --> Host["uuremote-server
(Linux)"] + App <-- signaling --> Cloud["UU Remote cloud"] + Host <-- "Socket.IO signaling · device login" --> Cloud + Host --> X11["X11 / Wayland
capture and input"] + Host --> FF["FFmpeg
H.264 / Opus"] + Host --> Sys["PAM · logind · PipeWire"] +``` + +- The host registers with UU Remote as a "Windows PC", so the official clients recognize it directly. +- The screen is encoded to H.264 and the sound to Opus with FFmpeg, both sent over WebRTC; keyboard, mouse, + clipboard, files and terminal use WebRTC data channels. +- Protocol details were learned by observing the official clients' traffic and analyzing their publicly + released programs, for interoperability only. This repository contains **no** NetEase programs, logos or assets. + +## Security and privacy + +- Logs never contain keystrokes, terminal text, clipboard contents, file contents, passwords or tokens. +- For auto unlock the password is stored in the **viewer** (the official client). The host only checks it + once with PAM; it is never written to disk or logs. +- Only devices logged in to the same UU account can connect. Keep your UU account safe. + +## Disclaimer + +- "NetEase", "网易" and "UU 远程 / UU Remote" are names and trademarks of NetEase, Inc. This project is not + affiliated with, authorized or endorsed by NetEase. +- It was built for interoperability. Use it in accordance with the UU Remote user agreement and your local + laws, at your own risk. +- NetEase or other rights holders with concerns: please contact [@ai_fengshou](https://x.com/ai_fengshou) + on X and I will cooperate or take the project down. + +## Acknowledgements + +- The NetEase UU Remote team, for a remote tool that is a pleasure to use. +- [webrtc-rs](https://github.com/webrtc-rs/webrtc), FFmpeg, GTK and the other open-source projects this builds on. +- Most of the code was written with the help of Claude and Codex. diff --git a/README.md b/README.md new file mode 100644 index 0000000..4e0ad29 --- /dev/null +++ b/README.md @@ -0,0 +1,193 @@ +# uu-remote-linux · UU 远程 Linux 被控端(非官方) + +**简体中文** | [English](README.en.md) + +> **写在前面** +> +> 网易 UU 远程非常好用,但官网一直没有 Linux 版本。于是我借助 Claude 和 Codex,写了这个开源的 Linux 被控端: +> 装上之后,就能用官方的 Mac / Windows / 手机客户端远程控制你的 Linux 电脑。 +> +> 这是个人兴趣项目,**与网易无关,也不是官方客户端**。如果网易认为本项目侵权或有不妥, +> 请在推特私信我 **[@ai_fengshou](https://x.com/ai_fengshou)**,我会第一时间自行下架。 + +

Linux 主机扫码登录窗口

+

首次运行时弹出的扫码登录窗口(二维码已打码)

+ + + + +## 它是什么 + +- 一个纯 Rust 写的 Linux 原生程序(不需要 Wine,也不需要任何 Windows/macOS 组件)。 +- 用你自己的 UU 远程账号扫码登录后,这台 Linux 会出现在官方客户端的设备列表里,用法和 Windows 被控端一样。 +- 只做**被控端**:用来控制别人的客户端,仍然是官方的 Mac / Windows / 手机 App。 + +## 已实现的功能 + +| 功能 | 说明 | +|---|---| +| 扫码登录 | GTK 登录窗口(或 `login --no-gui` 终端二维码);二维码过期自动刷新;登录凭证失效时服务会自动弹出登录窗口 | +| 远程桌面 | H.264 视频,NVIDIA 显卡用 NVENC 硬件编码,否则用 libx264;查看端绘制本地鼠标,不会出现双光标 | +| 鼠标 / 键盘 | 绝对/相对移动、点击、滚轮、按键;修复了网络延迟导致的按键连发 | +| 鼠标指针样式 | 远端指针形状实时同步(X11) | +| 剪贴板 | 双向文本同步 | +| 画质 / 帧率 / 分辨率 | 自动、原画 20M、超清 8M、高清 2M、自定义;30/60/90/144 帧;「其他分辨率」由编码器缩放,不改动主机显示器 | +| 声音 | 采集系统声音(PulseAudio / PipeWire),Opus 编码传到控制端 | +| 文件传输 | 上传、下载(含文件夹)、新建文件夹、重命名、删除 | +| 终端 | 官方「终端」工具,PTY 会话,支持多会话和重命名 | +| 锁屏与自动解锁 | 向控制端上报锁屏状态;开启「自动解锁被控端」后,通过 PAM 校验密码并解锁当前会话 | +| 远程结束后自动锁屏 | 设置保存在本机,重连后依然生效 | +| 被控端静音运行 | 主机扬声器静音,控制端照常能听到声音;结束后恢复原来的音量设置 | +| 系统操作 | 锁屏、显示桌面、任务管理器(系统监视器)、重启、关机 | +| 多次重连 | 每个工具窗口独立连接,互不影响 | + +## 支持的 Linux 桌面 + +| 桌面环境 | 显示协议 | 状态 | 编译方式 | +|---|---|---|---| +| GNOME(Ubuntu 24.04) | X11 / Xorg | ✅ 实机长期使用,以上功能全部验收 | 默认 | +| KDE Plasma | X11 | ✅ 虚拟机测试通过 | 默认 | +| Xfce | X11 | ✅ 虚拟机测试通过 | 默认 | +| Cinnamon / MATE | X11 | ✅ 虚拟机测试通过 | 默认 | +| Hyprland | Wayland(wlroots 原生协议) | ✅ 虚拟机测试通过(部分功能受限,见下) | `--features wayland` | +| GNOME / KDE Plasma | Wayland(xdg-desktop-portal) | ✅ 虚拟机测试通过(部分功能受限,见下) | `--features wayland,portal` | + +除 GNOME(X11)外,其余桌面目前都是在虚拟机里测试的。如果你在真机上遇到问题,欢迎[提交 issue](../../issues), +请附上发行版、桌面环境、显卡型号和 `journalctl --user -u uuremote-native.service` 里的相关日志。 + +Wayland 下的限制:只支持单屏、固定分辨率;portal 后端暂不支持剪贴板、唤醒屏幕和动态分辨率。 +首次连接时,桌面会弹窗请求「远程桌面 / 屏幕共享」授权,同意后会记住授权。 + +## 尚未实现 / 不支持 + +| 功能 | 状态 | +|---|---| +| 多显示器切换 | 开发中 | +| 真彩(4:4:4) | 未实现,握手时不声明,客户端不会启用 | +| HDR | 未实现 | +| 超级屏 / 虚拟显示器 | 未实现 | +| 被控端防窥模式 | 未实现 | +| 麦克风(控制端声音传到被控端) | 未实现(需要虚拟声卡) | +| 魔兽世界排队提醒等插件 | 不支持,会明确告诉客户端「无插件」 | +| 登录前(登录界面 / 无人登录)访问 | 不支持,只能控制已登录的桌面会话 | +| 端口映射 | 有代码,未经验收 | +| 跨运营商 / 受限网络的中继连接 | 已接入官方下发的 ICE 服务器,但复杂网络环境未充分测试 | +| 作为控制端(在 Linux 上控制别的电脑) | 不在本项目范围 | + +## 安装 + +### 1. 依赖(Ubuntu / Debian) + +```sh +sudo apt install build-essential pkg-config \ + libx11-dev libxext-dev libxtst-dev libxfixes-dev \ + libgtk-3-dev ffmpeg +# 可选:Wayland 后端 +sudo apt install libwayland-dev libxkbcommon-dev wl-clipboard +# 可选:GNOME/KDE portal 后端 +sudo apt install libglib2.0-dev libpipewire-0.3-dev +``` + +- 需要 Rust 工具链()。 +- `libgtk-3-dev` 是可选的:没有 GTK 时只能在终端里扫码登录(也可以设置 `UU_NO_GTK=1` 主动关闭登录窗口)。 +- NVIDIA 显卡用户需要使用带 `h264_nvenc` 的 FFmpeg,否则自动回落到 CPU 编码(libx264)。 + +### 2. 编译 + +```sh +cargo build --release # X11 +cargo build --release --features wayland # + Hyprland +cargo build --release --features wayland,portal # + GNOME/KDE Wayland +``` + +### 3. 登录 + +在图形桌面里运行: + +```sh +./target/release/uuremote-server login +``` + +用手机上的 **网易 UU 远程 App** 扫码并确认即可。登录信息只保存在本机的 +`~/.config/uuremote/config.json`(权限 0600)里。 + +### 4. 作为用户服务常驻 + +`~/.config/systemd/user/uuremote-native.service`: + +```ini +[Unit] +Description=UU Remote Linux host (unofficial) +After=graphical-session.target + +[Service] +Environment=RUST_LOG=info +# X11 桌面需要指明显示器;GNOME 的 XAUTHORITY 一般在 /run/user//gdm/Xauthority +Environment=DISPLAY=:0 +ExecStart=%h/.local/bin/uuremote-server +Restart=always +RestartSec=5 + +[Install] +WantedBy=default.target +``` + +```sh +install -Dm755 target/release/uuremote-server ~/.local/bin/uuremote-server +systemctl --user daemon-reload +systemctl --user enable --now uuremote-native.service +journalctl --user -u uuremote-native.service -f # 看到 availability=Some("ready") 即上线 +``` + +如果还没有登录,服务会自动在桌面上弹出扫码窗口。 + +## 配置 + +常用环境变量: + +| 变量 | 作用 | +|---|---| +| `UU_CONFIG` | 配置文件路径(默认 `~/.config/uuremote/config.json`) | +| `UU_DESKTOP_BACKEND` | `auto` / `x11` / `wayland` / `portal` | +| `UU_VIDEO_ENCODER=cpu` | 强制使用 CPU 编码 | +| `UU_FFMPEG_ROOT` | 使用指定目录下的 FFmpeg | +| `UU_AUDIO=0` | 关闭声音转发;`UU_AUDIO_SOURCE` 指定 PulseAudio 采集源 | +| `UU_LOGIN_WINDOW=0` | 凭证缺失时不自动弹出登录窗口 | + +「远程结束后自动锁屏」「静音运行」等设置保存在 `~/.config/uuremote/host_settings.json`。 + +## 工作原理 + +```mermaid +flowchart LR + App["官方客户端
Mac / Windows / 手机"] <-- "WebRTC:视频 · 音频 · 数据通道" --> Host["uuremote-server
(Linux)"] + App <-- 信令 --> Cloud["UU 远程云服务"] + Host <-- "Socket.IO 信令 · 设备登录" --> Cloud + Host --> X11["X11 / Wayland
采集与输入"] + Host --> FF["FFmpeg
H.264 / Opus"] + Host --> Sys["PAM · logind · PipeWire"] +``` + +- 主机以「Windows PC」类型注册到 UU 远程,官方客户端因此能直接识别它。 +- 画面经 FFmpeg 编码成 H.264,声音编码成 Opus,都通过 WebRTC 发送;键鼠、剪贴板、文件和终端走 WebRTC 数据通道。 +- 协议细节通过观察官方客户端的通信,以及分析其公开发布的程序得到,仅用于实现互通。 + 本仓库**不包含**任何网易的程序、图标或素材。 + +## 安全与隐私 + +- 日志不记录键盘输入、终端内容、剪贴板内容、文件内容、密码和令牌。 +- 自动解锁的密码保存在**控制端**(官方客户端)里,被控端只拿来做一次 PAM 校验,不落盘、不写日志。 +- 能连上这台机器的,只有登录了同一个 UU 账号的设备。请保管好你的 UU 账号。 + +## 免责声明 + +- 「网易」「UU 远程」等名称和商标归网易公司所有。本项目与网易公司没有任何关联,未获其授权或认可。 +- 本项目基于互操作目的开发,请在遵守 UU 远程用户协议和当地法律的前提下使用,风险自负。 +- 网易或权利人如有异议,请通过推特 [@ai_fengshou](https://x.com/ai_fengshou) 联系,我会配合处理或下架。 + +## 致谢 + +- 网易 UU 远程团队:做了一个好用的远程工具。 +- [webrtc-rs](https://github.com/webrtc-rs/webrtc)、FFmpeg、GTK 等开源项目。 +- 本项目的大部分代码在 Claude 和 Codex 的协助下完成。 diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..734f0b6 --- /dev/null +++ b/build.rs @@ -0,0 +1,83 @@ +fn main() { + println!("cargo:rerun-if-changed=c_engine/portal_clipboard.inc"); + println!("cargo:rerun-if-changed=c_engine/x11_engine.c"); + println!("cargo:rerun-if-changed=c_engine/clipboard.c"); + println!("cargo:rerun-if-changed=c_engine/login_window.c"); + println!("cargo:rerun-if-changed=c_engine/pam_check.c"); + println!("cargo:rerun-if-env-changed=UU_NO_GTK"); + println!("cargo:rustc-check-cfg=cfg(uu_gtk)"); + + let target_os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default(); + if target_os == "linux" { + cc::Build::new() + .file("c_engine/x11_engine.c") + .file("c_engine/clipboard.c") + .file("c_engine/pam_check.c") + .compile("x11_engine"); + + println!("cargo:rustc-link-lib=X11"); + println!("cargo:rustc-link-lib=Xext"); + println!("cargo:rustc-link-lib=Xtst"); + println!("cargo:rustc-link-lib=Xfixes"); + println!("cargo:rustc-link-lib=dl"); // pam_check.c loads libpam at runtime + // Optional GTK3 login window: built when gtk+-3.0 is installed, else `login` stays text-only. + let gtk = |arg: &str| std::process::Command::new("pkg-config").args([arg, "gtk+-3.0"]).output().ok() + .filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).into_owned()); + match (std::env::var_os("UU_NO_GTK").is_none()).then(|| gtk("--cflags").zip(gtk("--libs"))).flatten() { + Some((cflags, libs)) => { + let mut build = cc::Build::new(); + build.file("c_engine/login_window.c").flag_if_supported("-Wno-deprecated-declarations"); + for flag in cflags.split_whitespace() { build.flag(flag); } + build.compile("uu_login_window"); + for flag in libs.split_whitespace() { + if let Some(lib) = flag.strip_prefix("-l") { println!("cargo:rustc-link-lib={lib}"); } + else if let Some(dir) = flag.strip_prefix("-L") { println!("cargo:rustc-link-search=native={dir}"); } + } + println!("cargo:rustc-link-lib=pthread"); + println!("cargo:rustc-cfg=uu_gtk"); + } + None => println!("cargo:warning=gtk+-3.0 not found: building without the login window"), + } + if std::env::var_os("CARGO_FEATURE_PORTAL").is_some() { + println!("cargo:rerun-if-changed=c_engine/portal_engine.c"); + println!("cargo:rerun-if-changed=c_engine/portal_engine.h"); + let flags=|kind:&str| { + let output=std::process::Command::new("pkg-config").args([kind,"gio-2.0","gio-unix-2.0","libpipewire-0.3"]).output() + .expect("Install pkg-config and GIO/PipeWire development libraries"); + assert!(output.status.success(),"Portal requires GIO and PipeWire development libraries"); + String::from_utf8(output.stdout).expect("pkg-config flags must be UTF-8") + }; + let mut build=cc::Build::new(); + build.file("c_engine/portal_engine.c").flag_if_supported("-Wno-unused-parameter"); + for flag in flags("--cflags").split_whitespace() { build.flag(flag); } + build.compile("uu_portal_engine"); + for flag in flags("--libs").split_whitespace() { + if let Some(lib)=flag.strip_prefix("-l") { println!("cargo:rustc-link-lib={lib}"); } + else if let Some(dir)=flag.strip_prefix("-L") { println!("cargo:rustc-link-search=native={dir}"); } + } + println!("cargo:rustc-link-lib=pthread"); + } + if std::env::var_os("CARGO_FEATURE_WAYLAND").is_some() { + let out = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap()); + let mut build = cc::Build::new(); + build.flag_if_supported("-Wno-unused-parameter"); // protocol listener signatures + build.file("c_engine/wayland_engine.c").include(&out); + for name in ["wlr-screencopy-unstable-v1", "wlr-virtual-pointer-unstable-v1", "virtual-keyboard-unstable-v1", "wlr-output-power-management-unstable-v1"] { + let xml = format!("c_engine/wayland-protocols/{name}.xml"); + println!("cargo:rerun-if-changed={xml}"); + for (mode, suffix) in [("client-header", "client-protocol.h"), ("private-code", "protocol.c")] { + let target = out.join(format!("{name}-{suffix}")); + let status = std::process::Command::new("wayland-scanner").args([mode, &xml]).arg(&target).status() + .expect("Install wayland-scanner to build the Wayland backend"); + assert!(status.success(), "wayland-scanner failed"); + if mode == "private-code" { build.file(target); } + } + } + println!("cargo:rerun-if-changed=c_engine/wayland_engine.c"); + build.compile("uu_wayland_engine"); + println!("cargo:rustc-link-lib=wayland-client"); + println!("cargo:rustc-link-lib=xkbcommon"); + } + } +} + diff --git a/c_engine/clipboard.c b/c_engine/clipboard.c new file mode 100644 index 0000000..70c6bf0 --- /dev/null +++ b/c_engine/clipboard.c @@ -0,0 +1,134 @@ +/* Text-only X11 selection bridge. Each worker owns its own Display connection. + * Existing selection contents are not requested when the bridge starts. + * XFixes reports subsequent copies, including copies by the same owner. */ +#include +#include +#include +#include +#include + +#define CLIP_LIMIT (64 * 1024) +typedef struct { + Display *display; + Window window; + Atom selection, utf8, targets, text, property; + int fixes_event; + Time request_time; + unsigned char *owned; + size_t owned_length; + int owns_selection; +} NativeClipboard; + +void *clipboard_open(const char *display_name) { + NativeClipboard *c = calloc(1, sizeof(*c)); + if (!c) return NULL; + c->display = XOpenDisplay(display_name); + if (!c->display) { free(c); return NULL; } + int error; + if (!XFixesQueryExtension(c->display, &c->fixes_event, &error)) { + XCloseDisplay(c->display); free(c); return NULL; + } + c->window = XCreateSimpleWindow(c->display, DefaultRootWindow(c->display), + 0, 0, 1, 1, 0, 0, 0); + c->selection = XInternAtom(c->display, "CLIPBOARD", False); + c->utf8 = XInternAtom(c->display, "UTF8_STRING", False); + c->targets = XInternAtom(c->display, "TARGETS", False); + c->text = XInternAtom(c->display, "TEXT", False); + c->property = XInternAtom(c->display, "UU_NATIVE_CLIPBOARD", False); + XFixesSelectSelectionInput(c->display, c->window, c->selection, + XFixesSetSelectionOwnerNotifyMask | XFixesSelectionWindowDestroyNotifyMask | + XFixesSelectionClientCloseNotifyMask); + XFlush(c->display); + return c; +} + +int clipboard_set(void *handle, const unsigned char *text, size_t length) { + NativeClipboard *c = handle; + if (length > CLIP_LIMIT) return -1; + unsigned char *copy = malloc(length + 1); + if (!copy) return -1; + memcpy(copy, text, length); copy[length] = 0; + XSetSelectionOwner(c->display, c->selection, c->window, CurrentTime); + if (XGetSelectionOwner(c->display, c->selection) != c->window) { + free(copy); return -1; + } + free(c->owned); c->owned = copy; c->owned_length = length; + c->owns_selection = 1; + XFlush(c->display); + return 0; +} + +static void answer_request(NativeClipboard *c, XSelectionRequestEvent *r) { + XEvent reply; memset(&reply, 0, sizeof(reply)); + reply.xselection.type = SelectionNotify; + reply.xselection.display = r->display; + reply.xselection.requestor = r->requestor; + reply.xselection.selection = r->selection; + reply.xselection.target = r->target; + reply.xselection.time = r->time; + reply.xselection.property = None; + Atom property = r->property == None ? r->target : r->property; + if (r->selection == c->selection && c->owns_selection) { + if (r->target == c->targets) { + Atom targets[] = { c->targets, c->utf8, c->text }; + XChangeProperty(c->display, r->requestor, property, XA_ATOM, 32, + PropModeReplace, (unsigned char *)targets, 3); + reply.xselection.property = property; + } else if (r->target == c->utf8 || r->target == c->text) { + XChangeProperty(c->display, r->requestor, property, c->utf8, 8, + PropModeReplace, c->owned, c->owned_length); + reply.xselection.property = property; + } + } + XSendEvent(c->display, r->requestor, False, 0, &reply); + XFlush(c->display); +} + +/* -2: no text update, -1: unsupported/oversized conversion, >=0: byte length. + * INCR and non-UTF8 content are intentionally refused, never guessed as text. */ +int clipboard_poll(void *handle, unsigned char *out, size_t capacity) { + NativeClipboard *c = handle; + for (int count = 0; count < 64 && XPending(c->display); ++count) { + XEvent event; XNextEvent(c->display, &event); + if (event.type == SelectionRequest) { + answer_request(c, &event.xselectionrequest); + } else if (event.type == SelectionClear) { + c->owns_selection = 0; + } else if (event.type == c->fixes_event + XFixesSelectionNotify) { + XFixesSelectionNotifyEvent *change = (void *)&event; + if (change->selection != c->selection || change->owner == c->window || + change->owner == None) continue; + c->request_time = change->selection_timestamp; + XDeleteProperty(c->display, c->window, c->property); + XConvertSelection(c->display, c->selection, c->utf8, c->property, + c->window, c->request_time); + XFlush(c->display); + } else if (event.type == SelectionNotify) { + XSelectionEvent *n = &event.xselection; + if (n->selection != c->selection || n->time != c->request_time || + n->property == None || c->owns_selection) continue; + Atom actual; int format; unsigned long length, remaining; + unsigned char *data = NULL; + int status = XGetWindowProperty(c->display, c->window, c->property, + 0, (CLIP_LIMIT + 3) / 4, True, AnyPropertyType, + &actual, &format, &length, &remaining, &data); + int result = -1; + if (status == Success && actual == c->utf8 && format == 8 && + remaining == 0 && length <= capacity) { + if (length) memcpy(out, data, length); + result = (int)length; + } + if (data) XFree(data); + XDeleteProperty(c->display, c->window, c->property); + return result; + } + } + return -2; +} + +void clipboard_close(void *handle) { + NativeClipboard *c = handle; + XDestroyWindow(c->display, c->window); + XCloseDisplay(c->display); + free(c->owned); free(c); +} diff --git a/c_engine/clipboard_test.c b/c_engine/clipboard_test.c new file mode 100644 index 0000000..d546cf1 --- /dev/null +++ b/c_engine/clipboard_test.c @@ -0,0 +1,72 @@ +/* Run only in a dedicated Xvfb display; never touches the desktop clipboard. */ +#include +#include +#include +#include +#include +#include +void *clipboard_open(const char *); +int clipboard_set(void *, const unsigned char *, size_t); +int clipboard_poll(void *, unsigned char *, size_t); +void clipboard_close(void *); + +int main(void) { + XInitThreads(); + Display *d = XOpenDisplay(NULL); assert(d); + Window w = XCreateSimpleWindow(d, DefaultRootWindow(d), 0,0,1,1,0,0,0); + Atom selection = XInternAtom(d,"CLIPBOARD",False); + Atom utf8 = XInternAtom(d,"UTF8_STRING",False); + Atom property = XInternAtom(d,"TEST_CLIPBOARD",False); + XSetSelectionOwner(d,selection,w,CurrentTime); XSync(d,False); + void *bridge = clipboard_open(NULL); assert(bridge); + unsigned char buffer[65536]; + assert(clipboard_poll(bridge,buffer,sizeof(buffer)) == -2); + /* Two copies by the SAME owner must both notify the bridge. */ + for (int copy=0;copy<2;++copy) { + const char *test = copy ? "second copy\n中文🙂" : "first copy\n中文🙂"; + XSetSelectionOwner(d,selection,w,CurrentTime); XSync(d,False); + int result = -2; + for (int i=0;i<300 && result<0;++i) { + result = clipboard_poll(bridge,buffer,sizeof(buffer)); + while(XPending(d)) { + XEvent event; XNextEvent(d,&event); + if(event.type!=SelectionRequest) continue; + XSelectionRequestEvent *r=&event.xselectionrequest; + assert(r->target==utf8); + XChangeProperty(d,r->requestor,r->property,utf8,8,PropModeReplace, + (const unsigned char *)test,strlen(test)); + XEvent reply; memset(&reply,0,sizeof(reply)); + reply.xselection=(XSelectionEvent){.type=SelectionNotify,.display=d, + .requestor=r->requestor,.selection=r->selection,.target=r->target, + .property=r->property,.time=r->time}; + XSendEvent(d,r->requestor,False,0,&reply); XFlush(d); + } + usleep(1000); + } + assert(result==(int)strlen(test)); assert(!memcmp(buffer,test,result)); + } + const char *remote="remote copy\n中文🙂"; + assert(clipboard_set(bridge,(const unsigned char *)remote,strlen(remote))==0); + XConvertSelection(d,selection,utf8,property,w,CurrentTime); XFlush(d); + int received=0; + for(int i=0;i<300 && !received;++i) { + /* Owning our own remote copy must not send it back in an echo loop. */ + assert(clipboard_poll(bridge,buffer,sizeof(buffer))==-2); + while(XPending(d)) { + XEvent event; XNextEvent(d,&event); + if(event.type!=SelectionNotify) continue; + assert(event.xselection.property!=None); + Atom actual; int format; unsigned long n,remaining; unsigned char *data; + assert(XGetWindowProperty(d,w,property,0,65536/4,True,AnyPropertyType, + &actual,&format,&n,&remaining,&data)==Success); + assert(actual==utf8 && format==8 && !remaining); + assert(n==strlen(remote) && !memcmp(data,remote,n)); XFree(data); + received=1; + } + usleep(1000); + } + assert(received); + assert(clipboard_set(bridge,buffer,65537)==-1); + clipboard_close(bridge); XDestroyWindow(d,w); XCloseDisplay(d); + puts("PASS: no initial read; same-owner copies; Unicode both directions; no echo; size bound"); +} diff --git a/c_engine/login_window.c b/c_engine/login_window.c new file mode 100644 index 0000000..47abe54 --- /dev/null +++ b/c_engine/login_window.c @@ -0,0 +1,321 @@ +// GTK3 QR login window for `uuremote-server login`. The window runs its own GTK main loop on a +// dedicated thread; the Rust login flow pushes QR images and status text through g_idle_add. +// Layout follows the official login window (QR on the left), but uses no NetEase assets: the +// mark is drawn with cairo and the right column shows this host's hardware summary instead of SMS. +#include +#include +#include +#include +#include + +static const char *CSS = + "window { background-image: linear-gradient(165deg, #d6e8ff 0%, #eaf3ff 40%, #ffffff 100%); }\n" + "* { font-family: 'Noto Sans CJK SC', 'Noto Sans SC', sans-serif; }\n" + ".title { font-size: 26px; font-weight: 800; color: #111111; }\n" + ".subtitle { font-size: 13px; color: #6b7280; }\n" + ".heading { font-size: 19px; font-weight: 700; color: #1d1d1f; }\n" + ".card { background-color: #ffffff; border-radius: 10px; padding: 14px; }\n" + ".caption { font-size: 14px; color: #555555; }\n" + ".status { font-size: 13px; color: #2f6bff; }\n" + ".status.ok { color: #16a34a; }\n" + ".status.error { color: #dc2626; }\n" + ".key { font-size: 13px; color: #8a8f98; }\n" + ".value { font-size: 13px; color: #222222; }\n" + ".note { font-size: 12px; color: #6b7280; }\n" + ".done-mark { font-size: 72px; color: #16a34a; }\n" + ".done-text { font-size: 17px; font-weight: 700; color: #1d1d1f; }\n" + ".footer { font-size: 12px; color: #9ca3af; }\n" + "button.primary { background-image: none; background-color: #2f6bff; color: #ffffff; border: none;" + " border-radius: 6px; padding: 6px 28px; font-size: 15px; }\n" + "button.primary:hover { background-color: #1f5ae6; }\n" + "separator { background-color: #dfe5ee; min-width: 1px; }\n"; + +typedef struct { unsigned char *rgba; int edge; } QrUpdate; +typedef struct { char *text; int kind; } StatusUpdate; + +static atomic_int closed; +static pthread_t ui_thread; +static int ui_started; +static pthread_mutex_t init_lock = PTHREAD_MUTEX_INITIALIZER; +static pthread_cond_t init_cond = PTHREAD_COND_INITIALIZER; +static int init_state; // 0 pending, 1 ok, -1 failed +static char *info[4]; +static GtkWidget *window, *stack, *qr_image, *status_label, *done_label, *done_button; + +static gboolean draw_mark(GtkWidget *w, cairo_t *cr, gpointer data) { + (void)w; (void)data; + cairo_pattern_t *g = cairo_pattern_create_linear(0, 0, 44, 44); + cairo_pattern_add_color_stop_rgb(g, 0, 0.13, 0.83, 0.93); + cairo_pattern_add_color_stop_rgb(g, 1, 0.18, 0.42, 1.0); + double r = 11, s = 44; + cairo_new_sub_path(cr); + cairo_arc(cr, s - r, r, r, -G_PI / 2, 0); + cairo_arc(cr, s - r, s - r, r, 0, G_PI / 2); + cairo_arc(cr, r, s - r, r, G_PI / 2, G_PI); + cairo_arc(cr, r, r, r, G_PI, 3 * G_PI / 2); + cairo_close_path(cr); + cairo_set_source(cr, g); + cairo_fill(cr); + cairo_pattern_destroy(g); + cairo_set_source_rgb(cr, 1, 1, 1); + cairo_select_font_face(cr, "sans-serif", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD); + cairo_set_font_size(cr, 19); + cairo_text_extents_t e; + cairo_text_extents(cr, "UU", &e); + cairo_move_to(cr, (s - e.width) / 2 - e.x_bearing, (s - e.height) / 2 - e.y_bearing); + cairo_show_text(cr, "UU"); + return TRUE; +} + +static GtkWidget *label(const char *text, const char *cls) { + GtkWidget *l = gtk_label_new(text); + gtk_style_context_add_class(gtk_widget_get_style_context(l), cls); + return l; +} + +static void info_row(GtkGrid *grid, int row, const char *key, const char *value) { + GtkWidget *k = label(key, "key"), *v = label(value && *value ? value : "-", "value"); + gtk_widget_set_halign(k, GTK_ALIGN_START); + gtk_widget_set_valign(k, GTK_ALIGN_START); + gtk_widget_set_halign(v, GTK_ALIGN_START); + gtk_label_set_xalign(GTK_LABEL(v), 0); + gtk_label_set_line_wrap(GTK_LABEL(v), TRUE); + gtk_label_set_max_width_chars(GTK_LABEL(v), 26); + gtk_grid_attach(grid, k, 0, row, 1, 1); + gtk_grid_attach(grid, v, 1, row, 1, 1); +} + +static void on_destroy(GtkWidget *w, gpointer data) { + (void)w; (void)data; + atomic_store(&closed, 1); + window = NULL; + gtk_main_quit(); +} + +static void on_done_clicked(GtkButton *b, gpointer data) { + (void)b; (void)data; + if (window) gtk_widget_destroy(window); +} + +static void build_window(void) { + GtkCssProvider *css = gtk_css_provider_new(); + gtk_css_provider_load_from_data(css, CSS, -1, NULL); + gtk_style_context_add_provider_for_screen(gdk_screen_get_default(), GTK_STYLE_PROVIDER(css), + GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); + g_object_unref(css); + + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window), "UU 远程 Linux 主机 - 登录"); + gtk_window_set_default_size(GTK_WINDOW(window), 720, 520); + gtk_window_set_resizable(GTK_WINDOW(window), FALSE); + gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); + g_signal_connect(window, "destroy", G_CALLBACK(on_destroy), NULL); + + GtkWidget *root = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_container_set_border_width(GTK_CONTAINER(root), 24); + gtk_container_add(GTK_CONTAINER(window), root); + + GtkWidget *header = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 12); + gtk_widget_set_halign(header, GTK_ALIGN_CENTER); + GtkWidget *mark = gtk_drawing_area_new(); + gtk_widget_set_size_request(mark, 44, 44); + gtk_widget_set_valign(mark, GTK_ALIGN_CENTER); + g_signal_connect(mark, "draw", G_CALLBACK(draw_mark), NULL); + GtkWidget *titles = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + GtkWidget *title = label("UU 远程 · Linux 主机", "title"); + gtk_widget_set_halign(title, GTK_ALIGN_START); + GtkWidget *subtitle = label("登录后,本机会出现在你的 UU 远程设备列表中", "subtitle"); + gtk_widget_set_halign(subtitle, GTK_ALIGN_START); + gtk_box_pack_start(GTK_BOX(titles), title, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(titles), subtitle, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(header), mark, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(header), titles, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(root), header, FALSE, FALSE, 4); + + GtkWidget *columns = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + gtk_box_set_homogeneous(GTK_BOX(columns), FALSE); + gtk_widget_set_margin_top(columns, 22); + gtk_box_pack_start(GTK_BOX(root), columns, TRUE, TRUE, 0); + + // Left: QR login. + GtkWidget *left = gtk_box_new(GTK_ORIENTATION_VERTICAL, 12); + gtk_widget_set_size_request(left, 330, -1); + gtk_box_pack_start(GTK_BOX(left), label("扫码登录", "heading"), FALSE, FALSE, 0); + GtkWidget *card = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_style_context_add_class(gtk_widget_get_style_context(card), "card"); + gtk_widget_set_halign(card, GTK_ALIGN_CENTER); + gtk_widget_set_size_request(card, 252, 252); + stack = gtk_stack_new(); + gtk_stack_set_transition_type(GTK_STACK(stack), GTK_STACK_TRANSITION_TYPE_CROSSFADE); + GtkWidget *loading = gtk_box_new(GTK_ORIENTATION_VERTICAL, 10); + gtk_widget_set_valign(loading, GTK_ALIGN_CENTER); + GtkWidget *spinner = gtk_spinner_new(); + gtk_spinner_start(GTK_SPINNER(spinner)); + gtk_widget_set_size_request(spinner, 32, 32); + gtk_box_pack_start(GTK_BOX(loading), spinner, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(loading), label("正在获取二维码…", "caption"), FALSE, FALSE, 0); + gtk_stack_add_named(GTK_STACK(stack), loading, "loading"); + qr_image = gtk_image_new(); + gtk_stack_add_named(GTK_STACK(stack), qr_image, "qr"); + GtkWidget *done = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4); + gtk_widget_set_valign(done, GTK_ALIGN_CENTER); + gtk_box_pack_start(GTK_BOX(done), label("✓", "done-mark"), FALSE, FALSE, 0); + done_label = label("登录成功", "done-text"); + gtk_label_set_justify(GTK_LABEL(done_label), GTK_JUSTIFY_CENTER); + gtk_label_set_line_wrap(GTK_LABEL(done_label), TRUE); + gtk_box_pack_start(GTK_BOX(done), done_label, FALSE, FALSE, 0); + gtk_stack_add_named(GTK_STACK(stack), done, "done"); + gtk_box_pack_start(GTK_BOX(card), stack, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(left), card, FALSE, FALSE, 0); + GtkWidget *caption = label("请使用网易 UU 远程 App 扫一扫\n可快速登录", "caption"); + gtk_label_set_justify(GTK_LABEL(caption), GTK_JUSTIFY_CENTER); + gtk_box_pack_start(GTK_BOX(left), caption, FALSE, FALSE, 0); + status_label = label("", "status"); + gtk_label_set_line_wrap(GTK_LABEL(status_label), TRUE); + gtk_label_set_justify(GTK_LABEL(status_label), GTK_JUSTIFY_CENTER); + gtk_label_set_max_width_chars(GTK_LABEL(status_label), 34); + gtk_box_pack_start(GTK_BOX(left), status_label, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(columns), left, TRUE, TRUE, 0); + + GtkWidget *sep = gtk_separator_new(GTK_ORIENTATION_VERTICAL); + gtk_widget_set_margin_top(sep, 6); + gtk_widget_set_margin_bottom(sep, 24); + gtk_box_pack_start(GTK_BOX(columns), sep, FALSE, FALSE, 0); + + // Right: what will be registered. + GtkWidget *right = gtk_box_new(GTK_ORIENTATION_VERTICAL, 14); + gtk_widget_set_margin_start(right, 30); + gtk_widget_set_size_request(right, 300, -1); + GtkWidget *rh = label("本机信息", "heading"); + gtk_box_pack_start(GTK_BOX(right), rh, FALSE, FALSE, 0); + GtkWidget *grid = gtk_grid_new(); + gtk_grid_set_row_spacing(GTK_GRID(grid), 12); + gtk_grid_set_column_spacing(GTK_GRID(grid), 16); + gtk_widget_set_margin_top(grid, 10); + const char *keys[4] = {"设备名称", "操作系统", "处理器", "显卡"}; + for (int i = 0; i < 4; i++) info_row(GTK_GRID(grid), i, keys[i], info[i]); + gtk_box_pack_start(GTK_BOX(right), grid, FALSE, FALSE, 0); + GtkWidget *note = label("登录后可在 Mac / Windows / 手机上的官方 UU 远程客户端中连接本机的桌面、文件传输和终端。" + "登录信息只保存在本机配置文件中。", "note"); + gtk_label_set_line_wrap(GTK_LABEL(note), TRUE); + gtk_label_set_max_width_chars(GTK_LABEL(note), 30); + gtk_label_set_xalign(GTK_LABEL(note), 0); + gtk_widget_set_margin_top(note, 10); + gtk_box_pack_start(GTK_BOX(right), note, FALSE, FALSE, 0); + done_button = gtk_button_new_with_label("完成"); + gtk_style_context_add_class(gtk_widget_get_style_context(done_button), "primary"); + gtk_widget_set_halign(done_button, GTK_ALIGN_START); + gtk_widget_set_no_show_all(done_button, TRUE); + g_signal_connect(done_button, "clicked", G_CALLBACK(on_done_clicked), NULL); + gtk_box_pack_end(GTK_BOX(right), done_button, FALSE, FALSE, 20); + gtk_box_pack_start(GTK_BOX(columns), right, TRUE, TRUE, 0); + + GtkWidget *footer = label("开源 Linux 主机端 · 非网易官方客户端", "footer"); + gtk_box_pack_end(GTK_BOX(root), footer, FALSE, FALSE, 0); + gtk_widget_show_all(window); +} + +static void *ui_main(void *arg) { + (void)arg; + int ok = gtk_init_check(NULL, NULL); + if (ok) build_window(); + pthread_mutex_lock(&init_lock); + init_state = ok ? 1 : -1; + pthread_cond_signal(&init_cond); + pthread_mutex_unlock(&init_lock); + if (ok) gtk_main(); + else atomic_store(&closed, 1); + return NULL; +} + +// Returns 0 when the window is shown, -1 when no display is usable. +int uu_login_ui_start(const char *name, const char *os, const char *cpu, const char *gpu) { + if (ui_started) return init_state == 1 ? 0 : -1; + const char *src[4] = {name, os, cpu, gpu}; + for (int i = 0; i < 4; i++) info[i] = g_strdup(src[i] ? src[i] : ""); + if (pthread_create(&ui_thread, NULL, ui_main, NULL) != 0) return -1; + ui_started = 1; + pthread_mutex_lock(&init_lock); + while (init_state == 0) pthread_cond_wait(&init_cond, &init_lock); + pthread_mutex_unlock(&init_lock); + if (init_state != 1) { pthread_join(ui_thread, NULL); return -1; } + return 0; +} + +static gboolean apply_qr(gpointer data) { + QrUpdate *u = data; + if (window) { + GdkPixbuf *pb = gdk_pixbuf_new_from_data(u->rgba, GDK_COLORSPACE_RGB, TRUE, 8, u->edge, u->edge, u->edge * 4, + (GdkPixbufDestroyNotify)g_free, NULL); + gtk_image_set_from_pixbuf(GTK_IMAGE(qr_image), pb); + g_object_unref(pb); + gtk_stack_set_visible_child_name(GTK_STACK(stack), "qr"); + } else g_free(u->rgba); + g_free(u); + return G_SOURCE_REMOVE; +} + +void uu_login_ui_set_qr(const unsigned char *rgba, int edge) { + if (atomic_load(&closed) || edge <= 0) return; + QrUpdate *u = g_new(QrUpdate, 1); + u->rgba = g_memdup2(rgba, (gsize)edge * edge * 4); + u->edge = edge; + g_idle_add(apply_qr, u); +} + +static gboolean apply_status(gpointer data) { + StatusUpdate *u = data; + if (window) { + GtkStyleContext *ctx = gtk_widget_get_style_context(status_label); + gtk_style_context_remove_class(ctx, "ok"); + gtk_style_context_remove_class(ctx, "error"); + if (u->kind == 1) gtk_style_context_add_class(ctx, "ok"); + if (u->kind == 2) gtk_style_context_add_class(ctx, "error"); + gtk_label_set_text(GTK_LABEL(status_label), u->text); + if (u->kind == 2 && !gtk_image_get_pixbuf(GTK_IMAGE(qr_image))) + gtk_widget_hide(gtk_stack_get_child_by_name(GTK_STACK(stack), "loading")); + } + g_free(u->text); + g_free(u); + return G_SOURCE_REMOVE; +} + +// kind: 0 info, 1 success, 2 error. +void uu_login_ui_set_status(const char *text, int kind) { + if (atomic_load(&closed)) return; + StatusUpdate *u = g_new(StatusUpdate, 1); + u->text = g_strdup(text ? text : ""); + u->kind = kind; + g_idle_add(apply_status, u); +} + +static gboolean apply_done(gpointer data) { + if (window) { + gtk_label_set_text(GTK_LABEL(done_label), data); + gtk_stack_set_visible_child_name(GTK_STACK(stack), "done"); + gtk_widget_show(done_button); + gtk_widget_grab_focus(done_button); + } + g_free(data); + return G_SOURCE_REMOVE; +} + +void uu_login_ui_set_done(const char *text) { + if (atomic_load(&closed)) return; + g_idle_add(apply_done, g_strdup(text ? text : "")); +} + +int uu_login_ui_closed(void) { return atomic_load(&closed); } + +static gboolean apply_close(gpointer data) { + (void)data; + if (window) gtk_widget_destroy(window); + return G_SOURCE_REMOVE; +} + +void uu_login_ui_close(void) { + if (!ui_started) return; + if (!atomic_load(&closed)) g_idle_add(apply_close, NULL); + pthread_join(ui_thread, NULL); + ui_started = 0; +} diff --git a/c_engine/pam_check.c b/c_engine/pam_check.c new file mode 100644 index 0000000..2847584 --- /dev/null +++ b/c_engine/pam_check.c @@ -0,0 +1,76 @@ +// Verifies the desktop user's own password with PAM for remote auto-unlock (SimpleAction 15). +// libpam is loaded at runtime, so building needs no PAM headers and hosts without libpam simply +// report auto-unlock as unsupported. The PAM ABI types below are stable (Linux-PAM / OpenPAM). +// Non-root pam_unix checks the caller's own password through its setgid unix_chkpwd helper. +#include +#include +#include + +struct pam_message { int msg_style; const char *msg; }; +struct pam_response { char *resp; int resp_retcode; }; +struct pam_conv { + int (*conv)(int, const struct pam_message **, struct pam_response **, void *); + void *appdata_ptr; +}; +typedef struct pam_handle pam_handle_t; + +#define PAM_SUCCESS 0 +#define PAM_BUF_ERR 5 +#define PAM_CONV_ERR 19 +#define PAM_AUTH_ERR 7 +#define PAM_PROMPT_ECHO_OFF 1 +#define PAM_PROMPT_ECHO_ON 2 +#define PAM_SILENT 0x8000 + +typedef int (*start_fn)(const char *, const char *, const struct pam_conv *, pam_handle_t **); +typedef int (*auth_fn)(pam_handle_t *, int); +typedef int (*end_fn)(pam_handle_t *, int); + +static void *load_pam(void) { + void *lib = dlopen("libpam.so.0", RTLD_NOW | RTLD_LOCAL); + return lib ? lib : dlopen("libpam.so", RTLD_NOW | RTLD_LOCAL); +} + +static int conversation(int n, const struct pam_message **msg, struct pam_response **resp, void *data) { + if (n <= 0) return PAM_CONV_ERR; + struct pam_response *out = calloc((size_t)n, sizeof *out); + if (!out) return PAM_BUF_ERR; + for (int i = 0; i < n; i++) { + // Answer the password prompt only; informational messages get empty responses. + if (msg[i]->msg_style == PAM_PROMPT_ECHO_OFF) { + out[i].resp = strdup((const char *)data); + if (!out[i].resp) { free(out); return PAM_BUF_ERR; } + } else if (msg[i]->msg_style == PAM_PROMPT_ECHO_ON) { + free(out); return PAM_CONV_ERR; // unexpected (e.g. username/OTP): do not guess + } + } + *resp = out; + return PAM_SUCCESS; +} + +int uu_pam_available(void) { + void *lib = load_pam(); + if (!lib) return 0; + int ok = dlsym(lib, "pam_start") && dlsym(lib, "pam_authenticate") && dlsym(lib, "pam_end"); + dlclose(lib); + return ok; +} + +// 0 password accepted, 1 rejected, -1 PAM unavailable or failed to run. +int uu_pam_check(const char *service, const char *user, const char *password) { + void *lib = load_pam(); + if (!lib) return -1; + start_fn start = (start_fn)dlsym(lib, "pam_start"); + auth_fn authenticate = (auth_fn)dlsym(lib, "pam_authenticate"); + end_fn end = (end_fn)dlsym(lib, "pam_end"); + if (!start || !authenticate || !end) { dlclose(lib); return -1; } + struct pam_conv conv = { conversation, (void *)password }; + pam_handle_t *handle = NULL; + int rc = start(service, user, &conv, &handle); + if (rc != PAM_SUCCESS) { dlclose(lib); return -1; } + rc = authenticate(handle, PAM_SILENT); + end(handle, rc); + dlclose(lib); + if (rc == PAM_SUCCESS) return 0; + return rc == PAM_AUTH_ERR ? 1 : -1; +} diff --git a/c_engine/portal_clipboard.inc b/c_engine/portal_clipboard.inc new file mode 100644 index 0000000..3f8ca6e --- /dev/null +++ b/c_engine/portal_clipboard.inc @@ -0,0 +1,130 @@ +/* Included after uu_portal definition. One Clipboard permission shares RemoteDesktop. */ +#include +#include +#include +#include +#define CLIPBOARD "org.freedesktop.portal.Clipboard" +#define CLIP_LIMIT (30 * 1024) +static int text_mime(const char *mime) { + return !strcmp(mime,"text/plain;charset=utf-8") || !strcmp(mime,"text/plain") || !strcmp(mime,"UTF8_STRING"); +} +static int clipboard_fd(struct uu_portal *p, const char *method, GVariant *args) { + GUnixFDList *fds=NULL; + GVariant *reply=g_dbus_connection_call_with_unix_fd_list_sync(p->bus,DEST,PATH,CLIPBOARD,method, + args,G_VARIANT_TYPE("(h)"),G_DBUS_CALL_FLAGS_NONE,2000,NULL,&fds,NULL,NULL); + int fd=-1; + if (reply && fds) { gint index; g_variant_get(reply,"(h)",&index); fd=g_unix_fd_list_get(fds,index,NULL); } + if (reply) g_variant_unref(reply); + if (fds) g_object_unref(fds); + if (fd>=0 && fcntl(fd,F_SETFL,fcntl(fd,F_GETFL)|O_NONBLOCK)<0) { close(fd); return -1; } + return fd; +} +static int clipboard_io(int fd, uint8_t *bytes, size_t capacity, int writing) { + struct timespec started,now; clock_gettime(CLOCK_MONOTONIC,&started); + size_t used=0; + sigset_t blocked,previous,pending; sigemptyset(&blocked); sigaddset(&blocked,SIGPIPE); + sigpending(&pending); int had_pipe=sigismember(&pending,SIGPIPE); + if (writing) pthread_sigmask(SIG_BLOCK,&blocked,&previous); + int result=-1,broken=0; + for (;;) { + if (writing && used==capacity) { result=(int)used; break; } + clock_gettime(CLOCK_MONOTONIC,&now); + long elapsed=(now.tv_sec-started.tv_sec)*1000+(now.tv_nsec-started.tv_nsec)/1000000; + if (elapsed>=2000) break; + struct pollfd item={.fd=fd,.events=writing?POLLOUT:POLLIN}; + int polled=poll(&item,1,(int)(2000-elapsed)); + if (polled<0 && errno==EINTR) continue; + if (polled<=0 || (item.revents&POLLNVAL)) break; + ssize_t count=writing?write(fd,bytes+used,capacity-used):read(fd,bytes+used,capacity-used); + if (count<0 && (errno==EINTR || errno==EAGAIN)) continue; + if (count<0) { broken=errno==EPIPE; break; } + if (!count) { result=writing?-1:(int)used; break; } + used+=(size_t)count; + if (!writing && used==capacity) break; /* oversize: never publish truncated data */ + } + if (writing) { + if (broken && !had_pipe) { struct timespec zero={0}; (void)sigtimedwait(&blocked,NULL,&zero); } + pthread_sigmask(SIG_SETMASK,&previous,NULL); + } + return result; +} +static void selection_owner(GDBusConnection *bus,const gchar *sender,const gchar *path, + const gchar *interface,const gchar *signal,GVariant *parameters,gpointer data) { + (void)bus;(void)sender;(void)path;(void)interface;(void)signal; + struct uu_portal *p=data; const char *session; GVariant *options; + g_variant_get(parameters,"(&o@a{sv})",&session,&options); + if (!strcmp(session,p->session)) { + gboolean owner=FALSE; g_variant_lookup(options,"session_is_owner","b",&owner); + GVariant *types=g_variant_lookup_value(options,"mime_types",G_VARIANT_TYPE_STRING_ARRAY); + char *selected=NULL; + if (!owner && types) { + GVariantIter iter; const char *type; g_variant_iter_init(&iter,types); + while (g_variant_iter_next(&iter,"&s",&type)) if (text_mime(type)) { + g_free(selected); selected=g_strdup(type); if (!strcmp(type,"text/plain;charset=utf-8")) break; + } + } + if (getenv("UU_CLIPBOARD_DIAGNOSTICS")) fprintf(stderr,"Portal clipboard owner: own=%d text=%d\n",owner,selected!=NULL); + pthread_mutex_lock(&p->lock); + g_free(p->clipboard_mime); p->clipboard_mime=selected; + p->clipboard_changed=!owner && selected!=NULL; p->clipboard_revision++; + pthread_mutex_unlock(&p->lock); + if (types) g_variant_unref(types); + } + g_variant_unref(options); +} +static void selection_transfer(GDBusConnection *bus,const gchar *sender,const gchar *path, + const gchar *interface,const gchar *signal,GVariant *parameters,gpointer data) { + (void)bus;(void)sender;(void)path;(void)interface;(void)signal; + struct uu_portal *p=data; const char *session,*mime; guint serial; + g_variant_get(parameters,"(&o&su)",&session,&mime,&serial); + if (strcmp(session,p->session)) return; + uint8_t *copy=NULL; size_t length=0; + pthread_mutex_lock(&p->lock); + if (text_mime(mime) && p->clipboard_text) { + length=p->clipboard_length; copy=g_memdup2(p->clipboard_text,length+1); + } + pthread_mutex_unlock(&p->lock); + int success=0; + if (copy && uu_portal_alive(p)) { + int fd=clipboard_fd(p,"SelectionWrite",g_variant_new("(ou)",p->session,serial)); + if (fd>=0) { success=clipboard_io(fd,copy,length,1)==(int)length; close(fd); } + } + g_free(copy); + GVariant *reply=g_dbus_connection_call_sync(p->bus,DEST,PATH,CLIPBOARD,"SelectionWriteDone", + g_variant_new("(oub)",p->session,serial,success),NULL,G_DBUS_CALL_FLAGS_NONE,2000,NULL,NULL); + if (reply) g_variant_unref(reply); +} +int uu_portal_clipboard_ready(struct uu_portal *p) { return p && p->clipboard_enabled && uu_portal_alive(p); } +int uu_portal_clipboard_set(struct uu_portal *p,const uint8_t *text,size_t length) { + if (!uu_portal_clipboard_ready(p) || length>CLIP_LIMIT || !g_utf8_validate((const char *)text,(gssize)length,NULL)) return -1; + char *copy=g_malloc(length+1); memcpy(copy,text,length); copy[length]=0; + pthread_mutex_lock(&p->lock); + g_free(p->clipboard_text); p->clipboard_text=copy; p->clipboard_length=length; + p->clipboard_changed=0; + pthread_mutex_unlock(&p->lock); + const char *types[]={"text/plain;charset=utf-8","text/plain",NULL}; + GVariantBuilder options; g_variant_builder_init(&options,G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&options,"{sv}","mime_types",g_variant_new_strv(types,-1)); + GVariant *reply=g_dbus_connection_call_sync(p->bus,DEST,PATH,CLIPBOARD,"SetSelection", + g_variant_new("(o@a{sv})",p->session,g_variant_builder_end(&options)),NULL,G_DBUS_CALL_FLAGS_NONE,2000,NULL,NULL); + if (!reply) return -1; + g_variant_unref(reply); return 0; +} +int uu_portal_clipboard_poll(struct uu_portal *p,uint8_t *out,size_t capacity) { + if (!out || !uu_portal_clipboard_ready(p) || capacitylock); + char *mime=p->clipboard_changed?g_strdup(p->clipboard_mime):NULL; p->clipboard_changed=0; + uint64_t revision=p->clipboard_revision; + pthread_mutex_unlock(&p->lock); + if (!mime) return -1; + int fd=clipboard_fd(p,"SelectionRead",g_variant_new("(os)",p->session,mime)); g_free(mime); + if (fd<0) { if (getenv("UU_CLIPBOARD_DIAGNOSTICS")) fprintf(stderr,"Portal clipboard read: fd unavailable\n"); return -1; } + uint8_t *buffer=g_malloc(CLIP_LIMIT+1); int length=clipboard_io(fd,buffer,CLIP_LIMIT+1,0); close(fd); + if (getenv("UU_CLIPBOARD_DIAGNOSTICS")) fprintf(stderr,"Portal clipboard read: length=%d\n",length); + pthread_mutex_lock(&p->lock); + if (p->clipboard_revision!=revision) length=-1; + if (length>=0 && length<=CLIP_LIMIT && g_utf8_validate((const char *)buffer,length,NULL)) memcpy(out,buffer,(size_t)length); + else length=-1; + pthread_mutex_unlock(&p->lock); + g_free(buffer); return length; +} diff --git a/c_engine/portal_engine.c b/c_engine/portal_engine.c new file mode 100644 index 0000000..d421651 --- /dev/null +++ b/c_engine/portal_engine.c @@ -0,0 +1,466 @@ +#define _GNU_SOURCE +#include "portal_engine.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEST "org.freedesktop.portal.Desktop" +#define PATH "/org/freedesktop/portal/desktop" +#define REMOTE "org.freedesktop.portal.RemoteDesktop" +#define SCREEN "org.freedesktop.portal.ScreenCast" +#define REQUEST "org.freedesktop.portal.Request" +#define SESSION "org.freedesktop.portal.Session" + +struct uu_portal { + GDBusConnection *bus; + GMainContext *context; + GMainLoop *main_loop; + pthread_t dbus_thread; + int dbus_started; + char *session; + char *restore_token; + guint closed_subscription, clipboard_owner_subscription, clipboard_transfer_subscription; + int clipboard_enabled, clipboard_changed; + char *clipboard_text, *clipboard_mime; + size_t clipboard_length; + uint64_t clipboard_revision; + struct pw_thread_loop *pw_loop; + struct pw_context *pw_context; + struct pw_core *core; + struct pw_stream *stream; + struct spa_hook stream_listener; + pthread_mutex_t lock; + pthread_cond_t changed; + atomic_int closed; + int error; + uint32_t node, width, height; + int logical_width, logical_height; + enum spa_video_format format; + uint8_t *frame; + size_t frame_length; + uint64_t sequence; +}; +#include "portal_clipboard.inc" + +static pthread_once_t pw_once = PTHREAD_ONCE_INIT; +static atomic_uint token_sequence = 1; +static void initialize_pipewire(void) { pw_init(NULL, NULL); } +static GVariant *empty_options(void) { return g_variant_new_array(G_VARIANT_TYPE("{sv}"), NULL, 0); } +static void fail(struct uu_portal *p, int error) { + pthread_mutex_lock(&p->lock); + if (!p->error) p->error = error; + pthread_cond_broadcast(&p->changed); + pthread_mutex_unlock(&p->lock); +} +struct response { int done; guint code; GVariant *results; }; +static void response_received(GDBusConnection *bus, const gchar *sender, const gchar *path, + const gchar *interface, const gchar *signal, GVariant *parameters, gpointer data) { + (void)bus; (void)sender; (void)path; (void)interface; (void)signal; + struct response *r = data; + if (r->done) return; + g_variant_get(parameters, "(u@a{sv})", &r->code, &r->results); + r->done = 1; +} +static void close_request(struct uu_portal *p, const char *path) { + if (!path) return; + GVariant *r = g_dbus_connection_call_sync(p->bus, DEST, path, REQUEST, "Close", + NULL, NULL, G_DBUS_CALL_FLAGS_NONE, 3000, NULL, NULL); + if (r) g_variant_unref(r); +} +/* Subscribe before invocation, using the documented handle_token path. */ +static GVariant *request(struct uu_portal *p, const char *interface, const char *method, + GVariantBuilder *options, int mode, int *error) { + char token[64]; + snprintf(token, sizeof(token), "uu_%u_%u", (unsigned)getpid(), atomic_fetch_add(&token_sequence, 1)); + g_variant_builder_add(options, "{sv}", "handle_token", g_variant_new_string(token)); + char *sender = g_strdup(g_dbus_connection_get_unique_name(p->bus) + 1); + for (char *c = sender; *c; c++) if (*c == '.') *c = '_'; + char *expected = g_strdup_printf("/org/freedesktop/portal/desktop/request/%s/%s", sender, token); + g_free(sender); + struct response response = {0}; + guint subscription = g_dbus_connection_signal_subscribe(p->bus, DEST, REQUEST, "Response", expected, + NULL, G_DBUS_SIGNAL_FLAGS_NONE, response_received, &response, NULL); + GVariant *args = mode == 0 ? g_variant_new("(@a{sv})", g_variant_builder_end(options)) : + mode == 1 ? g_variant_new("(o@a{sv})", p->session, g_variant_builder_end(options)) : + g_variant_new("(os@a{sv})", p->session, "", g_variant_builder_end(options)); + GVariant *reply = g_dbus_connection_call_sync(p->bus, DEST, PATH, interface, method, args, + G_VARIANT_TYPE("(o)"), G_DBUS_CALL_FLAGS_NONE, 10000, NULL, NULL); + char *actual = NULL; + if (!reply) { *error = 3; goto finish; } + const char *handle; + g_variant_get(reply, "(&o)", &handle); + actual = g_strdup(handle); + g_variant_unref(reply); + if (strcmp(actual, expected)) { *error = 3; goto finish; } + unsigned consent_seconds=120; + const char *configured_timeout=getenv("UU_PORTAL_CONSENT_TIMEOUT_SECONDS"); + if(configured_timeout) { + char *end=NULL; + unsigned long parsed=strtoul(configured_timeout,&end,10); + if(end && !*end && parsed>=30 && parsed<=900) consent_seconds=(unsigned)parsed; + } + gint64 deadline = g_get_monotonic_time() + consent_seconds * G_TIME_SPAN_SECOND; + while (!response.done && !atomic_load(&p->closed) && g_get_monotonic_time() < deadline) { + while (g_main_context_iteration(p->context, FALSE)) {} + if (!response.done) g_usleep(5000); + } + if (!response.done) *error = atomic_load(&p->closed) ? 9 : 5; + else if (response.code != 0) *error = 4; +finish: + if (*error) close_request(p, actual ? actual : expected); + g_dbus_connection_signal_unsubscribe(p->bus, subscription); + g_free(actual); g_free(expected); + if (*error && response.results) { g_variant_unref(response.results); response.results = NULL; } + return response.results; +} +static void session_closed(GDBusConnection *bus, const gchar *sender, const gchar *path, + const gchar *interface, const gchar *signal, GVariant *parameters, gpointer data) { + (void)bus; (void)sender; (void)path; (void)interface; (void)signal; (void)parameters; + struct uu_portal *p = data; + atomic_store(&p->closed, 1); fail(p, 9); +} +static void *run_dbus(void *data) { + struct uu_portal *p = data; + g_main_context_push_thread_default(p->context); + g_main_loop_run(p->main_loop); + g_main_context_pop_thread_default(p->context); + return NULL; +} +static int has_interface(struct uu_portal *p, const char *interface) { + GVariant *r = g_dbus_connection_call_sync(p->bus, DEST, PATH, "org.freedesktop.DBus.Properties", + "Get", g_variant_new("(ss)", interface, "version"), G_VARIANT_TYPE("(v)"), + G_DBUS_CALL_FLAGS_NONE, 5000, NULL, NULL); + if (!r) return 0; + g_variant_unref(r); return 1; +} +static void stream_state(void *data, enum pw_stream_state old, enum pw_stream_state state, const char *message) { + (void)old; (void)message; + if (state == PW_STREAM_STATE_ERROR || state == PW_STREAM_STATE_UNCONNECTED) fail(data, 9); +} +static void stream_format(void *data, uint32_t id, const struct spa_pod *param) { + struct uu_portal *p = data; + if (id != SPA_PARAM_Format || !param) return; + struct spa_video_info_raw info = {0}; + if (spa_format_video_raw_parse(param, &info) < 0 || !info.size.width || !info.size.height || + info.size.width > 8192 || info.size.height > 8192 || + (info.format != SPA_VIDEO_FORMAT_BGRA && info.format != SPA_VIDEO_FORMAT_BGRx && + info.format != SPA_VIDEO_FORMAT_RGBA && info.format != SPA_VIDEO_FORMAT_RGBx)) { fail(p, 8); return; } + pthread_mutex_lock(&p->lock); + if (p->width && (p->width != info.size.width || p->height != info.size.height)) { + p->error = 8; pthread_cond_broadcast(&p->changed); pthread_mutex_unlock(&p->lock); return; + } + size_t length = (size_t)info.size.width * info.size.height * 4; + if (!p->frame) p->frame = malloc(length); + if (!p->frame) { p->error = 8; pthread_mutex_unlock(&p->lock); return; } + p->width = info.size.width; p->height = info.size.height; p->format = info.format; + p->frame_length = length; + pthread_cond_broadcast(&p->changed); + pthread_mutex_unlock(&p->lock); +} +/* Called with the frame mutex held. Invalid transient chunks are discarded; + * allocation capacity is not evidence that valid pixels have been supplied. */ +static void copy_video_buffer(struct uu_portal *p, struct spa_buffer *spa) { + if (!p->error && p->frame && spa->n_datas >= 1) { + struct spa_data *d = &spa->datas[0]; + struct spa_meta_header *header = spa_buffer_find_meta_data(spa, SPA_META_Header, sizeof(*header)); + if (!d->chunk || (d->chunk->flags & SPA_CHUNK_FLAG_CORRUPTED) || + (header && (header->flags & SPA_META_HEADER_FLAG_CORRUPTED))) return; + if (d->chunk->flags & SPA_CHUNK_FLAG_EMPTY) { + /* EMPTY denotes media-neutral (black) video, never old pixels. */ + memset(p->frame, 0, p->frame_length); + for (size_t pixel = 0; pixel < p->frame_length / 4; pixel++) p->frame[pixel * 4 + 3] = 255; + p->sequence++; + return; + } + struct spa_meta_region *crop = spa_buffer_find_meta_data(spa, SPA_META_VideoCrop, sizeof(*crop)); + if (crop && spa_meta_region_is_valid(crop) && (crop->region.position.x || crop->region.position.y || + crop->region.size.width != p->width || crop->region.size.height != p->height)) p->error = 8; + if (!d->data || d->chunk->stride < (int32_t)(p->width * 4) || !d->chunk->size || + d->chunk->offset > d->maxsize || + (d->type != SPA_DATA_MemPtr && d->type != SPA_DATA_MemFd)) return; + uint64_t required = (uint64_t)(p->height - 1) * (uint32_t)d->chunk->stride + p->width * 4; + if (required > d->maxsize - d->chunk->offset || required > d->chunk->size) return; + if (!p->error) { + uint8_t *src = (uint8_t *)d->data + d->chunk->offset; + for (uint32_t y = 0; y < p->height; y++) { + uint8_t *row = src + (size_t)y * d->chunk->stride; + uint8_t *dst = p->frame + (size_t)y * p->width * 4; + if (p->format == SPA_VIDEO_FORMAT_BGRA || p->format == SPA_VIDEO_FORMAT_BGRx) memcpy(dst, row, p->width * 4); + else for (uint32_t x = 0; x < p->width; x++) { + dst[4*x] = row[4*x+2]; dst[4*x+1] = row[4*x+1]; dst[4*x+2] = row[4*x]; dst[4*x+3] = 255; + } + } + p->sequence++; + } + } +} +static void stream_process(void *data) { + struct uu_portal *p = data; + struct pw_buffer *buffer, *newest = NULL; + while ((buffer = pw_stream_dequeue_buffer(p->stream))) { + if (newest) pw_stream_queue_buffer(p->stream, newest); + newest = buffer; + } + if (!newest) return; + pthread_mutex_lock(&p->lock); + copy_video_buffer(p, newest->buffer); + pthread_cond_broadcast(&p->changed); + pthread_mutex_unlock(&p->lock); + pw_stream_queue_buffer(p->stream, newest); +} +static const struct pw_stream_events stream_events = { + PW_VERSION_STREAM_EVENTS, .state_changed = stream_state, .param_changed = stream_format, .process = stream_process +}; +static int connect_pipewire(struct uu_portal *p) { + GUnixFDList *fds = NULL; + GVariant *reply = g_dbus_connection_call_with_unix_fd_list_sync(p->bus, DEST, PATH, SCREEN, + "OpenPipeWireRemote", g_variant_new("(o@a{sv})", p->session, empty_options()), + G_VARIANT_TYPE("(h)"), G_DBUS_CALL_FLAGS_NONE, 10000, NULL, &fds, NULL, NULL); + if (!reply) return 7; + gint32 index; g_variant_get(reply, "(h)", &index); + int fd = g_unix_fd_list_get(fds, index, NULL); + g_variant_unref(reply); g_object_unref(fds); + if (fd < 0) return 7; + pthread_once(&pw_once, initialize_pipewire); + p->pw_loop = pw_thread_loop_new("uuremote-portal", NULL); + if (!p->pw_loop) { close(fd); return 7; } + p->pw_context = pw_context_new(pw_thread_loop_get_loop(p->pw_loop), NULL, 0); + if (!p->pw_context) { close(fd); return 7; } + /* pw_context_connect_fd takes ownership of fd, including failure. */ + p->core = pw_context_connect_fd(p->pw_context, fd, NULL, 0); + if (!p->core) return 7; + p->stream = pw_stream_new(p->core, "uuremote-portal-capture", pw_properties_new( + PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", PW_KEY_MEDIA_ROLE, "Screen", NULL)); + if (!p->stream) return 7; + pw_stream_add_listener(p->stream, &p->stream_listener, &stream_events, p); + uint8_t storage[1024]; struct spa_pod_builder builder = SPA_POD_BUILDER_INIT(storage, sizeof(storage)); + const struct spa_pod *params[2]; + params[0] = spa_pod_builder_add_object(&builder, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat, + SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), + SPA_FORMAT_VIDEO_format, SPA_POD_CHOICE_ENUM_Id(4, SPA_VIDEO_FORMAT_BGRA, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_RGBA, SPA_VIDEO_FORMAT_RGBx), + SPA_FORMAT_VIDEO_size, SPA_POD_CHOICE_RANGE_Rectangle(&SPA_RECTANGLE(1920,1080), &SPA_RECTANGLE(1,1), &SPA_RECTANGLE(8192,8192)), + SPA_FORMAT_VIDEO_framerate, SPA_POD_CHOICE_RANGE_Fraction(&SPA_FRACTION(60,1), &SPA_FRACTION(0,1), &SPA_FRACTION(60,1))); + params[1] = spa_pod_builder_add_object(&builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, + SPA_PARAM_BUFFERS_dataType, SPA_POD_CHOICE_FLAGS_Int((1 << SPA_DATA_MemPtr) | (1 << SPA_DATA_MemFd))); + /* Node ID belongs to this portal's restricted remote. Do not put it into + * target.object, whose numeric value means object.serial on modern PW. */ + if (pw_stream_connect(p->stream, PW_DIRECTION_INPUT, p->node, + PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS, params, 2) < 0) return 7; + if (pw_thread_loop_start(p->pw_loop) < 0) return 7; + struct timespec until; clock_gettime(CLOCK_REALTIME, &until); until.tv_sec += 10; + pthread_mutex_lock(&p->lock); + while (!p->sequence && !p->error) { + if (pthread_cond_timedwait(&p->changed, &p->lock, &until)) break; + } + int result = p->error ? p->error : p->sequence ? 0 : 10; + pthread_mutex_unlock(&p->lock); + return result; +} +struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)(const char *, void *), void *data, int *error, uint32_t *width, uint32_t *height) { + *error = 0; *width = *height = 0; + struct uu_portal *p = calloc(1, sizeof(*p)); + if (!p) { *error = 8; return NULL; } + pthread_mutex_init(&p->lock, NULL); pthread_cond_init(&p->changed, NULL); + p->context = g_main_context_new(); g_main_context_push_thread_default(p->context); + p->bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); + if (!p->bus) { *error = 1; goto done; } + if (!has_interface(p, REMOTE) || !has_interface(p, SCREEN)) { *error = 2; goto done; } + GVariantBuilder options; GVariant *results; + g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT); + char token[64]; snprintf(token, sizeof(token), "uu_session_%u_%u", (unsigned)getpid(), atomic_fetch_add(&token_sequence, 1)); + g_variant_builder_add(&options, "{sv}", "session_handle_token", g_variant_new_string(token)); + results = request(p, REMOTE, "CreateSession", &options, 0, error); + if (!results) goto done; + const char *handle = NULL; + if (g_variant_lookup(results, "session_handle", "&s", &handle)) p->session = g_strdup(handle); + g_variant_unref(results); + if (!p->session || !g_variant_is_object_path(p->session)) { *error = 3; goto done; } + p->closed_subscription = g_dbus_connection_signal_subscribe(p->bus, DEST, SESSION, "Closed", p->session, + NULL, G_DBUS_SIGNAL_FLAGS_NONE, session_closed, p, NULL); + g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&options, "{sv}", "types", g_variant_new_uint32(3)); + GVariant *version_reply = g_dbus_connection_call_sync(p->bus, DEST, PATH, + "org.freedesktop.DBus.Properties", "Get", g_variant_new("(ss)", REMOTE, "version"), + G_VARIANT_TYPE("(v)"), G_DBUS_CALL_FLAGS_NONE, 3000, NULL, NULL); + guint version = 0; + if (version_reply) { + GVariant *value; g_variant_get(version_reply, "(v)", &value); + if (g_variant_is_of_type(value, G_VARIANT_TYPE_UINT32)) version = g_variant_get_uint32(value); + g_variant_unref(value); g_variant_unref(version_reply); + } + if (version >= 2) { + g_variant_builder_add(&options, "{sv}", "persist_mode", g_variant_new_uint32(2)); + if (restore && *restore) g_variant_builder_add(&options, "{sv}", "restore_token", g_variant_new_string(restore)); + } + + results = request(p, REMOTE, "SelectDevices", &options, 1, error); + if (!results) goto done; + g_variant_unref(results); + g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT); + g_variant_builder_add(&options, "{sv}", "types", g_variant_new_uint32(1)); + g_variant_builder_add(&options, "{sv}", "multiple", g_variant_new_boolean(FALSE)); + /* Hidden cursor avoids duplicate pointer; supported since ScreenCast v1. */ + results = request(p, SCREEN, "SelectSources", &options, 1, error); + if (!results) goto done; + g_variant_unref(results); + if (has_interface(p, CLIPBOARD)) { + p->clipboard_owner_subscription=g_dbus_connection_signal_subscribe(p->bus,DEST,CLIPBOARD, + "SelectionOwnerChanged",PATH,NULL,G_DBUS_SIGNAL_FLAGS_NONE,selection_owner,p,NULL); + p->clipboard_transfer_subscription=g_dbus_connection_signal_subscribe(p->bus,DEST,CLIPBOARD, + "SelectionTransfer",PATH,NULL,G_DBUS_SIGNAL_FLAGS_NONE,selection_transfer,p,NULL); + GVariant *reply=g_dbus_connection_call_sync(p->bus,DEST,PATH,CLIPBOARD,"RequestClipboard", + g_variant_new("(o@a{sv})",p->session,empty_options()),NULL,G_DBUS_CALL_FLAGS_NONE,3000,NULL,NULL); + if (reply) g_variant_unref(reply); + } + g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT); + results = request(p, REMOTE, "Start", &options, 2, error); + if (!results) goto done; + gboolean clipboard_enabled=FALSE; + g_variant_lookup(results,"clipboard_enabled","b",&clipboard_enabled); + p->clipboard_enabled=clipboard_enabled; + fprintf(stderr,"Portal clipboard permission: granted=%d\n",clipboard_enabled); + guint devices = 0; GVariant *streams = g_variant_lookup_value(results, "streams", G_VARIANT_TYPE("a(ua{sv})")); + gboolean has_devices=g_variant_lookup(results, "devices", "u", &devices); + fprintf(stderr,"Portal authorization result: devices_present=%d device_bits=%u stream_count=%zu\n",has_devices,devices,streams?(size_t)g_variant_n_children(streams):0); + if (!has_devices || (devices & 3) != 3 || !streams || g_variant_n_children(streams) != 1) { + *error = 6; + } else { + GVariant *entry = g_variant_get_child_value(streams, 0), *properties; + g_variant_get(entry, "(u@a{sv})", &p->node, &properties); + /* 'size' is compositor logical coordinates, not the pixel frame size. */ + g_variant_lookup(properties, "size", "(ii)", &p->logical_width, &p->logical_height); + g_variant_unref(properties); g_variant_unref(entry); + } + if (!*error) { + const char *next = NULL; + if (g_variant_lookup(results, "restore_token", "&s", &next) && next && strlen(next) <= 4096) + p->restore_token = g_strdup(next); + fprintf(stderr, "Portal persistence: requested=%d restore_attempted=%d token_returned=%d\n", + version >= 2, restore && *restore, p->restore_token && *p->restore_token); + } + if (!*error && p->restore_token && save_token) save_token(p->restore_token, data); + if (streams) g_variant_unref(streams); + g_variant_unref(results); + if (*error) goto done; + p->main_loop = g_main_loop_new(p->context, FALSE); + g_main_context_pop_thread_default(p->context); + if (pthread_create(&p->dbus_thread, NULL, run_dbus, p)) { *error = 3; uu_portal_close(p); return NULL; } + p->dbus_started = 1; + *error = connect_pipewire(p); + if (*error) { uu_portal_close(p); return NULL; } + *width = p->width; *height = p->height; + return p; +done: + g_main_context_pop_thread_default(p->context); + uu_portal_close(p); return NULL; +} +struct uu_portal *uu_portal_open_restore(const char *restore, int *error, uint32_t *width, uint32_t *height) { + return uu_portal_open_persist(restore, NULL, NULL, error, width, height); +} +struct uu_portal *uu_portal_open(int *error, uint32_t *width, uint32_t *height) { + return uu_portal_open_restore(NULL, error, width, height); +} +const char *uu_portal_restore_token(struct uu_portal *p) { return p ? p->restore_token : NULL; } +static gboolean quit_dbus_loop(gpointer data) { g_main_loop_quit(data); return G_SOURCE_REMOVE; } +void uu_portal_close(struct uu_portal *p) { + if (!p) return; + atomic_store(&p->closed, 1); + if (p->bus && p->session) { + GVariant *reply = g_dbus_connection_call_sync(p->bus, DEST, p->session, SESSION, "Close", + NULL, NULL, G_DBUS_CALL_FLAGS_NONE, 3000, NULL, NULL); + if (reply) g_variant_unref(reply); + } + if (p->clipboard_owner_subscription) g_dbus_connection_signal_unsubscribe(p->bus,p->clipboard_owner_subscription); + if (p->clipboard_transfer_subscription) g_dbus_connection_signal_unsubscribe(p->bus,p->clipboard_transfer_subscription); + if (p->closed_subscription) g_dbus_connection_signal_unsubscribe(p->bus, p->closed_subscription); + if (p->dbus_started) { + /* A queued source also handles close racing with thread startup; an + * immediate g_main_loop_quit before run would leave run blocking. */ + GSource *quit = g_idle_source_new(); + g_source_set_callback(quit, quit_dbus_loop, p->main_loop, NULL); + g_source_attach(quit, p->context); g_source_unref(quit); + g_main_context_wakeup(p->context); pthread_join(p->dbus_thread, NULL); + } + if (p->pw_loop) pw_thread_loop_stop(p->pw_loop); + if (p->stream) pw_stream_destroy(p->stream); + if (p->core) pw_core_disconnect(p->core); + if (p->pw_context) pw_context_destroy(p->pw_context); + if (p->pw_loop) pw_thread_loop_destroy(p->pw_loop); + if (p->main_loop) g_main_loop_unref(p->main_loop); + if (p->context) g_main_context_unref(p->context); + if (p->bus) g_object_unref(p->bus); + g_free(p->clipboard_text); g_free(p->clipboard_mime); g_free(p->restore_token); free(p->session); free(p->frame); + pthread_cond_destroy(&p->changed); pthread_mutex_destroy(&p->lock); free(p); +} +void uu_portal_reset_frame(struct uu_portal *p) { + if (!p) return; + pthread_mutex_lock(&p->lock); + p->sequence = 0; + if (p->frame) memset(p->frame, 0, p->frame_length); + pthread_mutex_unlock(&p->lock); +} +int uu_portal_capture(struct uu_portal *p, uint8_t *frame, size_t length) { + if (!p || !frame) return 11; + pthread_mutex_lock(&p->lock); + int result = atomic_load(&p->closed) ? 9 : p->error ? p->error : !p->sequence ? 10 : length != p->frame_length ? 11 : 0; + if (!result) memcpy(frame, p->frame, length); + pthread_mutex_unlock(&p->lock); return result; +} +int uu_portal_alive(struct uu_portal *p) { + if (!p || atomic_load(&p->closed)) return 0; + pthread_mutex_lock(&p->lock); + int alive = !p->error; + pthread_mutex_unlock(&p->lock); + return alive; +} +static int notify(struct uu_portal *p, const char *method, GVariant *parameters) { + if (!uu_portal_alive(p)) { g_variant_ref_sink(parameters); g_variant_unref(parameters); return 9; } + GError *error = NULL; + GVariant *reply = g_dbus_connection_call_sync(p->bus, DEST, PATH, REMOTE, method, parameters, + NULL, G_DBUS_CALL_FLAGS_NONE, 3000, NULL, &error); + if (!reply) { + static atomic_uint failures = 0; + if (atomic_fetch_add(&failures, 1) < 12) { + char *name = error ? g_dbus_error_get_remote_error(error) : NULL; + fprintf(stderr, "Portal input method failed: method=%s remote_error=%s\n", method, name ? name : "unavailable"); + g_free(name); + } + g_clear_error(&error); return 9; + } + g_variant_unref(reply); return 0; +} +int uu_portal_move(struct uu_portal *p, double x, double y, int relative) { + if (!p || !isfinite(x) || !isfinite(y)) return 11; + if (p->logical_width <= 0 || p->logical_height <= 0 || !p->width || !p->height) return 11; + if (relative) return notify(p, "NotifyPointerMotion", g_variant_new("(o@a{sv}dd)", p->session, empty_options(), + x * p->logical_width / p->width, y * p->logical_height / p->height)); + if (x < 0 || y < 0 || x >= p->width || y >= p->height) return 11; + return notify(p, "NotifyPointerMotionAbsolute", g_variant_new("(o@a{sv}udd)", p->session, empty_options(), p->node, + x * p->logical_width / p->width, y * p->logical_height / p->height)); +} +int uu_portal_button(struct uu_portal *p, int button, int pressed) { + if (!p) return 11; + if (button >= 4 && button <= 7) { + if (!pressed) return 0; + return notify(p, "NotifyPointerAxisDiscrete", g_variant_new("(o@a{sv}ui)", p->session, empty_options(), + (guint)(button <= 5 ? 0 : 1), button == 4 || button == 6 ? -1 : 1)); + } + int code = button == 1 ? 0x110 : button == 2 ? 0x112 : button == 3 ? 0x111 : button == 8 ? 0x113 : button == 9 ? 0x114 : 0; + if (!code) return 11; + return notify(p, "NotifyPointerButton", g_variant_new("(o@a{sv}iu)", p->session, empty_options(), code, (guint)!!pressed)); +} +int uu_portal_key(struct uu_portal *p, uint32_t symbol, int pressed) { + if (!p || !symbol || symbol > INT32_MAX) return 11; + return notify(p, "NotifyKeyboardKeysym", g_variant_new("(o@a{sv}iu)", p->session, empty_options(), (gint)symbol, (guint)!!pressed)); +} diff --git a/c_engine/portal_engine.h b/c_engine/portal_engine.h new file mode 100644 index 0000000..7fe1167 --- /dev/null +++ b/c_engine/portal_engine.h @@ -0,0 +1,22 @@ +#ifndef UU_PORTAL_ENGINE_H +#define UU_PORTAL_ENGINE_H +#include +#include +struct uu_portal; +/* One object owns one consent/session and one PipeWire stream. */ +struct uu_portal *uu_portal_open(int *error, uint32_t *width, uint32_t *height); +/* Saves the rotated token immediately after Start, before video initialization. */ +struct uu_portal *uu_portal_open_persist(const char *restore, void (*save_token)(const char *, void *), void *data, int *error, uint32_t *width, uint32_t *height); +struct uu_portal *uu_portal_open_restore(const char *restore, int *error, uint32_t *width, uint32_t *height); +const char *uu_portal_restore_token(struct uu_portal *portal); +void uu_portal_close(struct uu_portal *portal); +int uu_portal_clipboard_ready(struct uu_portal *portal); +int uu_portal_clipboard_set(struct uu_portal *portal, const uint8_t *text, size_t length); +int uu_portal_clipboard_poll(struct uu_portal *portal, uint8_t *text, size_t capacity); +int uu_portal_alive(struct uu_portal *portal); +void uu_portal_reset_frame(struct uu_portal *portal); +int uu_portal_capture(struct uu_portal *portal, uint8_t *bgra, size_t length); +int uu_portal_move(struct uu_portal *portal, double x, double y, int relative); +int uu_portal_button(struct uu_portal *portal, int button, int pressed); +int uu_portal_key(struct uu_portal *portal, uint32_t keysym, int pressed); +#endif diff --git a/c_engine/wayland-protocols/virtual-keyboard-unstable-v1.xml b/c_engine/wayland-protocols/virtual-keyboard-unstable-v1.xml new file mode 100644 index 0000000..5095c91 --- /dev/null +++ b/c_engine/wayland-protocols/virtual-keyboard-unstable-v1.xml @@ -0,0 +1,113 @@ + + + + Copyright © 2008-2011 Kristian Høgsberg + Copyright © 2010-2013 Intel Corporation + Copyright © 2012-2013 Collabora, Ltd. + Copyright © 2018 Purism SPC + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + The virtual keyboard provides an application with requests which emulate + the behaviour of a physical keyboard. + + This interface can be used by clients on its own to provide raw input + events, or it can accompany the input method protocol. + + + + + Provide a file descriptor to the compositor which can be + memory-mapped to provide a keyboard mapping description. + + Format carries a value from the keymap_format enumeration. + + + + + + + + + + + + + A key was pressed or released. + The time argument is a timestamp with millisecond granularity, with an + undefined base. All requests regarding a single object must share the + same clock. + + Keymap must be set before issuing this request. + + State carries a value from the key_state enumeration. + + + + + + + + + Notifies the compositor that the modifier and/or group state has + changed, and it should update state. + + The client should use wl_keyboard.modifiers event to synchronize its + internal state with seat state. + + Keymap must be set before issuing this request. + + + + + + + + + + + + + + + A virtual keyboard manager allows an application to provide keyboard + input events as if they came from a physical keyboard. + + + + + + + + + Creates a new virtual keyboard associated to a seat. + + If the compositor enables a keyboard to perform arbitrary actions, it + should present an error when an untrusted client requests a new + keyboard. + + + + + + diff --git a/c_engine/wayland-protocols/wlr-output-power-management-unstable-v1.xml b/c_engine/wayland-protocols/wlr-output-power-management-unstable-v1.xml new file mode 100644 index 0000000..a977839 --- /dev/null +++ b/c_engine/wayland-protocols/wlr-output-power-management-unstable-v1.xml @@ -0,0 +1,128 @@ + + + + Copyright © 2019 Purism SPC + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol allows clients to control power management modes + of outputs that are currently part of the compositor space. The + intent is to allow special clients like desktop shells to power + down outputs when the system is idle. + + To modify outputs not currently part of the compositor space see + wlr-output-management. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This interface is a manager that allows creating per-output power + management mode controls. + + + + + Create a output power management mode control that can be used to + adjust the power management mode for a given output. + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object offers requests to set the power management mode of + an output. + + + + + + + + + + + + + + Set an output's power save mode to the given mode. The mode change + is effective immediately. If the output does not support the given + mode a failed event is sent. + + + + + + + Report the power management mode change of an output. + + The mode event is sent after an output changed its power + management mode. The reason can be a client using set_mode or the + compositor deciding to change an output's mode. + This event is also sent immediately when the object is created + so the client is informed about the current power management mode. + + + + + + + This event indicates that the output power management mode control + is no longer valid. This can happen for a number of reasons, + including: + - The output doesn't support power management + - Another client already has exclusive power management mode control + for this output + - The output disappeared + + Upon receiving this event, the client should destroy this object. + + + + + + Destroys the output power management mode control object. + + + + diff --git a/c_engine/wayland-protocols/wlr-screencopy-unstable-v1.xml b/c_engine/wayland-protocols/wlr-screencopy-unstable-v1.xml new file mode 100644 index 0000000..50b1b7d --- /dev/null +++ b/c_engine/wayland-protocols/wlr-screencopy-unstable-v1.xml @@ -0,0 +1,232 @@ + + + + Copyright © 2018 Simon Ser + Copyright © 2019 Andri Yngvason + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + This protocol allows clients to ask the compositor to copy part of the + screen content to a client buffer. + + Warning! The protocol described in this file is experimental and + backward incompatible changes may be made. Backward compatible changes + may be added together with the corresponding interface version bump. + Backward incompatible changes are done by bumping the version number in + the protocol and interface names and resetting the interface version. + Once the protocol is to be declared stable, the 'z' prefix and the + version number in the protocol and interface names are removed and the + interface version number is reset. + + + + + This object is a manager which offers requests to start capturing from a + source. + + + + + Capture the next frame of an entire output. + + + + + + + + + Capture the next frame of an output's region. + + The region is given in output logical coordinates, see + xdg_output.logical_size. The region will be clipped to the output's + extents. + + + + + + + + + + + + + All objects created by the manager will still remain valid, until their + appropriate destroy request has been called. + + + + + + + This object represents a single frame. + + When created, a series of buffer events will be sent, each representing a + supported buffer type. The "buffer_done" event is sent afterwards to + indicate that all supported buffer types have been enumerated. The client + will then be able to send a "copy" request. If the capture is successful, + the compositor will send a "flags" followed by a "ready" event. + + For objects version 2 or lower, wl_shm buffers are always supported, ie. + the "buffer" event is guaranteed to be sent. + + If the capture failed, the "failed" event is sent. This can happen anytime + before the "ready" event. + + Once either a "ready" or a "failed" event is received, the client should + destroy the frame. + + + + + Provides information about wl_shm buffer parameters that need to be + used for this frame. This event is sent once after the frame is created + if wl_shm buffers are supported. + + + + + + + + + + Copy the frame to the supplied buffer. The buffer must have a the + correct size, see zwlr_screencopy_frame_v1.buffer and + zwlr_screencopy_frame_v1.linux_dmabuf. The buffer needs to have a + supported format. + + If the frame is successfully copied, a "flags" and a "ready" events are + sent. Otherwise, a "failed" event is sent. + + + + + + + + + + + + + + + + Provides flags about the frame. This event is sent once before the + "ready" event. + + + + + + + Called as soon as the frame is copied, indicating it is available + for reading. This event includes the time at which presentation happened + at. + + The timestamp is expressed as tv_sec_hi, tv_sec_lo, tv_nsec triples, + each component being an unsigned 32-bit value. Whole seconds are in + tv_sec which is a 64-bit value combined from tv_sec_hi and tv_sec_lo, + and the additional fractional part in tv_nsec as nanoseconds. Hence, + for valid timestamps tv_nsec must be in [0, 999999999]. The seconds part + may have an arbitrary offset at start. + + After receiving this event, the client should destroy the object. + + + + + + + + + This event indicates that the attempted frame copy has failed. + + After receiving this event, the client should destroy the object. + + + + + + Destroys the frame. This request can be sent at any time by the client. + + + + + + + Same as copy, except it waits until there is damage to copy. + + + + + + + This event is sent right before the ready event when copy_with_damage is + requested. It may be generated multiple times for each copy_with_damage + request. + + The arguments describe a box around an area that has changed since the + last copy request that was derived from the current screencopy manager + instance. + + The union of all regions received between the call to copy_with_damage + and a ready event is the total damage since the prior ready event. + + + + + + + + + + + Provides information about linux-dmabuf buffer parameters that need to + be used for this frame. This event is sent once after the frame is + created if linux-dmabuf buffers are supported. + + + + + + + + + This event is sent once after all buffer events have been sent. + + The client should proceed to create a buffer of one of the supported + types, and send a "copy" request. + + + + diff --git a/c_engine/wayland-protocols/wlr-virtual-pointer-unstable-v1.xml b/c_engine/wayland-protocols/wlr-virtual-pointer-unstable-v1.xml new file mode 100644 index 0000000..ea243e7 --- /dev/null +++ b/c_engine/wayland-protocols/wlr-virtual-pointer-unstable-v1.xml @@ -0,0 +1,152 @@ + + + + Copyright © 2019 Josef Gajdusek + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice (including the next + paragraph) shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. + + + + + This protocol allows clients to emulate a physical pointer device. The + requests are mostly mirror opposites of those specified in wl_pointer. + + + + + + + + + + The pointer has moved by a relative amount to the previous request. + + Values are in the global compositor space. + + + + + + + + + The pointer has moved in an absolute coordinate frame. + + Value of x can range from 0 to x_extent, value of y can range from 0 + to y_extent. + + + + + + + + + + + A button was pressed or released. + + + + + + + + + Scroll and other axis requests. + + + + + + + + + Indicates the set of events that logically belong together. + + + + + + Source information for scroll and other axis. + + + + + + + Stop notification for scroll and other axes. + + + + + + + + Discrete step information for scroll and other axes. + + This event allows the client to extend data normally sent using the axis + event with discrete value. + + + + + + + + + + + + + + + This object allows clients to create individual virtual pointer objects. + + + + + Creates a new virtual pointer. The optional seat is a suggestion to the + compositor. + + + + + + + + + + + + + Creates a new virtual pointer. The seat and the output arguments are + optional. If the seat argument is set, the compositor should assign the + input device to the requested seat. If the output argument is set, the + compositor should map the input device to the requested output. + + + + + + + diff --git a/c_engine/wayland_engine.c b/c_engine/wayland_engine.c new file mode 100644 index 0000000..14eda3a --- /dev/null +++ b/c_engine/wayland_engine.c @@ -0,0 +1,277 @@ +/* Native Hyprland/wlroots desktop bridge. Protocol XMLs retain upstream licenses. */ +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "wlr-screencopy-unstable-v1-client-protocol.h" +#include "wlr-virtual-pointer-unstable-v1-client-protocol.h" +#include "virtual-keyboard-unstable-v1-client-protocol.h" +#include "wlr-output-power-management-unstable-v1-client-protocol.h" + +static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; +static struct wl_display *display; +static struct wl_shm *shm; +static struct wl_seat *seat; +static struct zwlr_screencopy_manager_v1 *copy_manager; +static struct zwlr_virtual_pointer_manager_v1 *pointer_manager; +static struct zwp_virtual_keyboard_manager_v1 *keyboard_manager; +static struct zwlr_virtual_pointer_v1 *pointer; +static struct zwp_virtual_keyboard_v1 *keyboard; +static struct zwlr_output_power_manager_v1 *power_manager; +static struct zwlr_output_power_v1 *power; +static int power_failed; +static struct xkb_context *xkb; +static struct xkb_keymap *keymap; +static struct xkb_state *key_state; +static unsigned char held_keys[768]; +struct output { struct wl_output *handle; char name[128]; int transform,scale; uint32_t width,height; }; +static struct output outputs[32]; +static unsigned output_count, selected; +static uint32_t width,height,stride,format,flags; +static int done,failed,initialized; +static struct wl_buffer *buffer; +static void *pixels; +static size_t pixel_length; + +static uint32_t timestamp(void) { + struct timespec t; clock_gettime(CLOCK_MONOTONIC,&t); + return (uint32_t)((uint64_t)t.tv_sec*1000+t.tv_nsec/1000000); +} +/* Never let a disappearing compositor block a worker indefinitely. */ +static int dispatch_until(int *condition) { + uint32_t start=timestamp(); + while (!*condition) { + while (wl_display_prepare_read(display)!=0) { + if (wl_display_dispatch_pending(display)<0) return -1; + if (*condition) return 0; + } + if (wl_display_flush(display)<0) { wl_display_cancel_read(display); return -1; } + struct pollfd fd={wl_display_get_fd(display),POLLIN,0}; + int wait=poll(&fd,1,100); + if (wait>0 && (fd.revents&POLLIN)) { + if (wl_display_read_events(display)<0) return -1; + if (wl_display_dispatch_pending(display)<0) return -1; + } else { wl_display_cancel_read(display); if (wait<0 || fd.revents&(POLLERR|POLLHUP)) return -1; } + if ((uint32_t)(timestamp()-start)>3000) return -1; + } + return 0; +} +static void sync_done(void *data,struct wl_callback *cb,uint32_t serial) { *(int*)data=1; wl_callback_destroy(cb); } +static const struct wl_callback_listener sync_listener={sync_done}; +static int sync_display(void) { + int ready=0; struct wl_callback *cb=wl_display_sync(display); + wl_callback_add_listener(cb,&sync_listener,&ready); + int result=dispatch_until(&ready); + if (!ready) wl_callback_destroy(cb); + return result; +} +static void output_geometry(void*d,struct wl_output*o,int32_t x,int32_t y,int32_t w,int32_t h,int32_t sub,const char*m,const char*model,int32_t transform) { ((struct output*)d)->transform=transform; } +static void output_mode(void*d,struct wl_output*o,uint32_t f,int32_t w,int32_t h,int32_t rate) { + if(f&WL_OUTPUT_MODE_CURRENT) { ((struct output*)d)->width=w; ((struct output*)d)->height=h; } +} +static void output_done(void*d,struct wl_output*o) {} +static void output_scale(void*d,struct wl_output*o,int32_t scale) { if(scale>0 && scale<=16) ((struct output*)d)->scale=scale; } +static void output_name(void*d,struct wl_output*o,const char*name) { snprintf(((struct output*)d)->name,128,"%s",name); } +static void output_description(void*d,struct wl_output*o,const char*desc) {} +static const struct wl_output_listener output_listener={output_geometry,output_mode,output_done,output_scale,output_name,output_description}; +static void global(void*d,struct wl_registry*r,uint32_t id,const char*interface,uint32_t version) { + if (!strcmp(interface,"wl_shm")) shm=wl_registry_bind(r,id,&wl_shm_interface,1); + else if (!strcmp(interface,"wl_seat") && !seat) seat=wl_registry_bind(r,id,&wl_seat_interface,1); + else if (!strcmp(interface,"wl_output") && output_count<32) { + struct output *o=&outputs[output_count++]; + o->scale=1; + o->handle=wl_registry_bind(r,id,&wl_output_interface,version<4?version:4); + wl_output_add_listener(o->handle,&output_listener,o); + } else if (!strcmp(interface,"zwlr_screencopy_manager_v1")) copy_manager=wl_registry_bind(r,id,&zwlr_screencopy_manager_v1_interface,version<3?version:3); + else if (!strcmp(interface,"zwlr_virtual_pointer_manager_v1") && version>=2) pointer_manager=wl_registry_bind(r,id,&zwlr_virtual_pointer_manager_v1_interface,2); + else if (!strcmp(interface,"zwp_virtual_keyboard_manager_v1")) keyboard_manager=wl_registry_bind(r,id,&zwp_virtual_keyboard_manager_v1_interface,1); + else if (!strcmp(interface,"zwlr_output_power_manager_v1")) power_manager=wl_registry_bind(r,id,&zwlr_output_power_manager_v1_interface,1); +} +static void global_remove(void*d,struct wl_registry*r,uint32_t id) { /* failed captures are returned to caller */ } +static const struct wl_registry_listener registry_listener={global,global_remove}; +static void power_mode(void*d,struct zwlr_output_power_v1*p,uint32_t mode) {} +static void power_failure(void*d,struct zwlr_output_power_v1*p) { power_failed=1; } +static const struct zwlr_output_power_v1_listener power_listener={power_mode,power_failure}; +static void copy_buffer(void*d,struct zwlr_screencopy_frame_v1*f,uint32_t fmt,uint32_t w,uint32_t h,uint32_t s) { + format=fmt; width=w; height=h; stride=s; + if (w==0 || h==0 || w>16384 || h>16384 || s131072 || (uint64_t)s*h>256*1024*1024 || + (fmt!=WL_SHM_FORMAT_XRGB8888 && fmt!=WL_SHM_FORMAT_ARGB8888 && + fmt!=WL_SHM_FORMAT_XBGR8888 && fmt!=WL_SHM_FORMAT_ABGR8888)) { failed=done=1; return; } + size_t length=(size_t)s*h; + if (buffer) { wl_buffer_destroy(buffer); buffer=NULL; } + if (pixels) { munmap(pixels,pixel_length); pixels=NULL; } + int fd=memfd_create("uuremote-wayland-frame",MFD_CLOEXEC); + if (fd<0 || ftruncate(fd,(off_t)length)!=0) { if(fd>=0)close(fd); failed=done=1; return; } + pixels=mmap(NULL,length,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); + if (pixels==MAP_FAILED) { pixels=NULL; close(fd); failed=done=1; return; } + pixel_length=length; + struct wl_shm_pool *pool=wl_shm_create_pool(shm,fd,(int32_t)length); + buffer=wl_shm_pool_create_buffer(pool,0,w,h,s,fmt); + wl_shm_pool_destroy(pool); close(fd); + /* copy is valid immediately for SHM, including frame versions <3. */ + if (zwlr_screencopy_frame_v1_get_version(f)<3) zwlr_screencopy_frame_v1_copy(f,buffer); +} +static void copy_flags(void*d,struct zwlr_screencopy_frame_v1*f,uint32_t value) { flags=value; } +static void copy_ready(void*d,struct zwlr_screencopy_frame_v1*f,uint32_t hi,uint32_t lo,uint32_t ns) { done=1; } +static void copy_failed(void*d,struct zwlr_screencopy_frame_v1*f) { failed=done=1; } +static void copy_damage(void*d,struct zwlr_screencopy_frame_v1*f,uint32_t x,uint32_t y,uint32_t w,uint32_t h) {} +static void copy_dmabuf(void*d,struct zwlr_screencopy_frame_v1*f,uint32_t fmt,uint32_t w,uint32_t h) {} +static void copy_buffer_done(void*d,struct zwlr_screencopy_frame_v1*f) { if(buffer && !failed) zwlr_screencopy_frame_v1_copy(f,buffer); else failed=done=1; } +static const struct zwlr_screencopy_frame_v1_listener copy_listener={copy_buffer,copy_flags,copy_ready,copy_failed,copy_damage,copy_dmabuf,copy_buffer_done}; +static int capture(void) { + done=failed=0; flags=0; + if(buffer) { wl_buffer_destroy(buffer); buffer=NULL; } + /* Initial milestone: video excludes cursor, viewer draws its own pointer. */ + struct zwlr_screencopy_frame_v1 *f=zwlr_screencopy_manager_v1_capture_output(copy_manager,0,outputs[selected].handle); + zwlr_screencopy_frame_v1_add_listener(f,©_listener,NULL); + int result=dispatch_until(&done); + zwlr_screencopy_frame_v1_destroy(f); + return result==0 && !failed && pixels ? 0:-1; +} +static void reset(void) { + if (key_state) xkb_state_unref(key_state); + if (keymap) xkb_keymap_unref(keymap); + if (xkb) xkb_context_unref(xkb); + if (pixels) munmap(pixels,pixel_length); + /* Disconnect drops every proxy; failure never leaves an initialized backend. */ + if (display) wl_display_disconnect(display); + display=NULL; shm=NULL; seat=NULL; copy_manager=NULL; pointer_manager=NULL; keyboard_manager=NULL; + pointer=NULL; keyboard=NULL; xkb=NULL; keymap=NULL; key_state=NULL; buffer=NULL; pixels=NULL; + power_manager=NULL; power=NULL; power_failed=0; + pixel_length=0; output_count=0; initialized=0; memset(outputs,0,sizeof(outputs)); + memset(held_keys,0,sizeof(held_keys)); +} +int uu_wl_init(int32_t *w,int32_t *h) { + pthread_mutex_lock(&lock); + if(initialized) { *w=width; *h=height; pthread_mutex_unlock(&lock); return 0; } + int result=-1; + display=wl_display_connect(NULL); if (!display) goto end; + struct wl_registry *registry=wl_display_get_registry(display); + wl_registry_add_listener(registry,®istry_listener,NULL); + if(sync_display()!=0 || sync_display()!=0) goto end; + if(!shm || !seat || !copy_manager || !pointer_manager || !keyboard_manager || !output_count) goto end; + const char *name=getenv("UU_WAYLAND_OUTPUT"); selected=0; + if(name && *name) { + for(selected=0;selected16384 || height>16384 || (uint64_t)width*height*4>256*1024*1024) goto end; + if(power_manager) { + power=zwlr_output_power_manager_v1_get_output_power(power_manager,outputs[selected].handle); + zwlr_output_power_v1_add_listener(power,&power_listener,NULL); + } + pointer=zwlr_virtual_pointer_manager_v1_create_virtual_pointer_with_output(pointer_manager,seat,outputs[selected].handle); + keyboard=zwp_virtual_keyboard_manager_v1_create_virtual_keyboard(keyboard_manager,seat); + xkb=xkb_context_new(XKB_CONTEXT_NO_FLAGS); + if(!xkb) goto end; + struct xkb_rule_names names={.layout="us"}; + keymap=xkb_keymap_new_from_names(xkb,&names,XKB_KEYMAP_COMPILE_NO_FLAGS); + if(!keymap) goto end; + key_state=xkb_state_new(keymap); if(!key_state) goto end; + char *map=xkb_keymap_get_as_string(keymap,XKB_KEYMAP_FORMAT_TEXT_V1); + if(!map) goto end; + size_t length=strlen(map)+1; + int fd=memfd_create("uuremote-keymap",MFD_CLOEXEC); + if(fd<0) { free(map); goto end; } + if(ftruncate(fd,(off_t)length)!=0 || write(fd,map,length)!=(ssize_t)length) { free(map); close(fd); goto end; } + free(map); + zwp_virtual_keyboard_v1_keymap(keyboard,WL_KEYBOARD_KEYMAP_FORMAT_XKB_V1,fd,length); close(fd); + if(sync_display()!=0) goto end; + initialized=1; *w=width; *h=height; result=0; +end: + if(result!=0) reset(); + pthread_mutex_unlock(&lock); return result; +} +int uu_wl_wake(void) { + pthread_mutex_lock(&lock); int result=-1; + if(initialized && power && !power_failed) { + zwlr_output_power_v1_set_mode(power,ZWLR_OUTPUT_POWER_V1_MODE_ON); + if(sync_display()==0 && !power_failed) result=0; + } + pthread_mutex_unlock(&lock); return result; +} +int uu_wl_capture(uint8_t *out,size_t length) { + pthread_mutex_lock(&lock); + int result=-1; + if(initialized && capture()==0 && length==(size_t)width*height*4) { + for(uint32_t y=0;y=0 && y>=0 && x<(int32_t)width && y<(int32_t)height) zwlr_virtual_pointer_v1_motion_absolute(pointer,timestamp(),x,y,width,height); + else goto end; + zwlr_virtual_pointer_v1_frame(pointer); result=wl_display_flush(display)<0?-1:0; + } +end: pthread_mutex_unlock(&lock); return result; +} +int uu_wl_button(int button,int pressed) { + pthread_mutex_lock(&lock); int result=-1; + if(initialized) { + if(button>=4 && button<=7) { + if(pressed) { + uint32_t axis=(button<=5)?WL_POINTER_AXIS_VERTICAL_SCROLL:WL_POINTER_AXIS_HORIZONTAL_SCROLL; + int direction=(button==4 || button==6)?-1:1; + zwlr_virtual_pointer_v1_axis_source(pointer,WL_POINTER_AXIS_SOURCE_WHEEL); + zwlr_virtual_pointer_v1_axis_discrete(pointer,timestamp(),axis,wl_fixed_from_int(direction*10),direction); + } + } else { + int code=button==1?0x110:button==2?0x112:button==3?0x111:button==8?0x113:button==9?0x114:0; + if(!code) goto end; + zwlr_virtual_pointer_v1_button(pointer,timestamp(),code,pressed?WL_POINTER_BUTTON_STATE_PRESSED:WL_POINTER_BUTTON_STATE_RELEASED); + } + zwlr_virtual_pointer_v1_frame(pointer); result=wl_display_flush(display)<0?-1:0; + } +end: pthread_mutex_unlock(&lock); return result; +} +int uu_wl_key(uint64_t symbol,int pressed) { + pthread_mutex_lock(&lock); int result=-1; + if(initialized) { + for(xkb_keycode_t code=xkb_keymap_min_keycode(keymap);code<=xkb_keymap_max_keycode(keymap);code++) { + int matches=0; + for(xkb_level_index_t level=0;level=sizeof(held_keys)) continue; + if(held_keys[code]==!!pressed) { result=0; break; } + held_keys[code]=!!pressed; + zwp_virtual_keyboard_v1_key(keyboard,timestamp(),code-8,pressed?WL_KEYBOARD_KEY_STATE_PRESSED:WL_KEYBOARD_KEY_STATE_RELEASED); + xkb_state_update_key(key_state,code,pressed?XKB_KEY_DOWN:XKB_KEY_UP); + zwp_virtual_keyboard_v1_modifiers(keyboard, + xkb_state_serialize_mods(key_state,XKB_STATE_MODS_DEPRESSED), + xkb_state_serialize_mods(key_state,XKB_STATE_MODS_LATCHED), + xkb_state_serialize_mods(key_state,XKB_STATE_MODS_LOCKED), + xkb_state_serialize_layout(key_state,XKB_STATE_LAYOUT_EFFECTIVE)); + result=wl_display_flush(display)<0?-1:0; break; + } + } + pthread_mutex_unlock(&lock); return result; +} diff --git a/c_engine/x11_engine.c b/c_engine/x11_engine.c new file mode 100644 index 0000000..dc39537 --- /dev/null +++ b/c_engine/x11_engine.c @@ -0,0 +1,272 @@ +/** + * Native Linux X11 High-Performance Capture & Input Injection Engine + * Zero-Wine dependency, zero-overhead, thread-safe. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static Display *g_display = NULL; +static Window g_root = 0; +static int g_screen = 0; +static int g_width = 0; +static int g_height = 0; +static int g_depth = 0; + +static XShmSegmentInfo g_shminfo; +static XImage *g_shm_image = NULL; +static int g_use_shm = 0; +static unsigned char g_injected_down[32]; // keycodes currently held by the remote viewer +static int g_injected_count = 0; +static int g_restore_repeat = 0; + +// Injected keys must not auto-repeat on the host: the viewer sends its own repeats, and with +// network delay the key-up can arrive after the 500 ms X repeat delay ("wunnnnnnami"). +// XTEST events repeat through the master keyboard, so global auto-repeat is switched off only +// while a remote key is held and restored when the last one is released. +static void track_injected_key(int keycode, int is_press) { + if (keycode < 0 || keycode > 255) return; + unsigned char bit = 1u << (keycode & 7), *slot = &g_injected_down[keycode >> 3]; + if (is_press && !(*slot & bit)) { + if (g_injected_count++ == 0) { + XKeyboardState state; + XGetKeyboardControl(g_display, &state); + g_restore_repeat = state.global_auto_repeat == AutoRepeatModeOn; + if (g_restore_repeat) XAutoRepeatOff(g_display); + } + *slot |= bit; + } else if (!is_press && (*slot & bit)) { + *slot &= ~bit; + if (--g_injected_count == 0 && g_restore_repeat) { XAutoRepeatOn(g_display); g_restore_repeat = 0; } + } +} + +int x11_init(const char *display_name) { + if (g_display) return 0; + + XInitThreads(); + if (display_name && *display_name) { + g_display = XOpenDisplay(display_name); + } else { + const char *configured = getenv("DISPLAY"); + if (configured && *configured) g_display = XOpenDisplay(configured); + if (!g_display) g_display = XOpenDisplay(":0"); + if (!g_display) g_display = XOpenDisplay(":1"); + } + if (!g_display) { + return -1; + } + + g_screen = DefaultScreen(g_display); + g_root = RootWindow(g_display, g_screen); + g_width = DisplayWidth(g_display, g_screen); + g_height = DisplayHeight(g_display, g_screen); + g_depth = DefaultDepth(g_display, g_screen); + + // 尝试初始化 XShm + if (XShmQueryExtension(g_display)) { + g_shm_image = XShmCreateImage(g_display, DefaultVisual(g_display, g_screen), + g_depth, ZPixmap, NULL, &g_shminfo, g_width, g_height); + if (g_shm_image) { + g_shminfo.shmid = shmget(IPC_PRIVATE, g_shm_image->bytes_per_line * g_shm_image->height, IPC_CREAT | 0777); + if (g_shminfo.shmid != -1) { + g_shminfo.shmaddr = g_shm_image->data = (char *)shmat(g_shminfo.shmid, 0, 0); + g_shminfo.readOnly = False; + if (g_shminfo.shmaddr != (char *)-1) { + if (XShmAttach(g_display, &g_shminfo)) { + XSync(g_display, False); + shmctl(g_shminfo.shmid, IPC_RMID, 0); // 标记删除,进程退出时自动回收 + g_use_shm = 1; + } + } + } + } + } + + return 0; +} + +int x11_get_dimensions(int *out_w, int *out_h) { + if (!g_display) return -1; + *out_w = g_width; + *out_h = g_height; + return 0; +} + +/** + * 截取一帧画面(RGBA/BGRA 格式) + * @param out_buffer 输出缓冲区,大小必须至少为 width * height * 4 + */ +int x11_capture_frame(unsigned char *out_buffer, int *out_w, int *out_h) { + if (!g_display) return -1; + *out_w = g_width; + *out_h = g_height; + + if (g_use_shm && g_shm_image) { + if (!XShmGetImage(g_display, g_root, g_shm_image, 0, 0, AllPlanes)) { + return -2; + } + memcpy(out_buffer, g_shm_image->data, g_width * g_height * 4); + return 0; + } + + // Fallback: XGetImage + XImage *img = XGetImage(g_display, g_root, 0, 0, g_width, g_height, AllPlanes, ZPixmap); + if (!img) return -3; + memcpy(out_buffer, img->data, g_width * g_height * 4); + XDestroyImage(img); + return 0; +} + +// ============ 原生输入注入 ============ + +const char *x11_display_name(void) { + return g_display ? DisplayString(g_display) : NULL; +} + +/* Reset display-idle activity during an active remote session without moving + * the pointer or changing the screen-lock policy. */ +int x11_wake_display(void) { + if (!g_display) return -1; + XTestFakeRelativeMotionEvent(g_display, 0, 0, CurrentTime); + XFlush(g_display); + return 0; +} + +int x11_mouse_move(int x, int y) { + if (!g_display) return -1; + XTestFakeMotionEvent(g_display, g_screen, x, y, CurrentTime); + XFlush(g_display); + return 0; +} + +int x11_mouse_relative(int dx, int dy) { + if (!g_display) return -1; + XTestFakeRelativeMotionEvent(g_display, dx, dy, CurrentTime); + XFlush(g_display); + return 0; +} + +int x11_mouse_button(int button, int is_press) { + if (!g_display) return -1; + // button: 1=Left, 2=Middle, 3=Right, 4=ScrollUp, 5=ScrollDown + int ok = XTestFakeButtonEvent(g_display, button, is_press ? True : False, CurrentTime); + XFlush(g_display); + return ok ? 0 : -2; +} + +int x11_pointer_state(int *x, int *y, unsigned int *mask) { + if (!g_display) return -1; + Window root, child; int wx, wy; + return XQueryPointer(g_display,g_root,&root,&child,x,y,&wx,&wy,mask) ? 0 : -2; +} + +int x11_key_symbol(unsigned long symbol, int is_press) { + if (!g_display) return -1; + KeyCode code = XKeysymToKeycode(g_display, (KeySym)symbol); + if (!code) return -2; + if (is_press) track_injected_key(code, 1); + XTestFakeKeyEvent(g_display, code, is_press ? True : False, CurrentTime); + if (!is_press) track_injected_key(code, 0); + XFlush(g_display); + return 0; +} + +int x11_key_event(int keycode, int is_press) { + if (!g_display) return -1; + if (is_press) track_injected_key(keycode, 1); + XTestFakeKeyEvent(g_display, keycode, is_press ? True : False, CurrentTime); + if (!is_press) track_injected_key(keycode, 0); + XFlush(g_display); + return 0; +} + +void x11_close() { + if (!g_display) return; + if (g_use_shm) { + XShmDetach(g_display, &g_shminfo); + if (g_shm_image) { + XDestroyImage(g_shm_image); + g_shm_image = NULL; + } + if (g_shminfo.shmaddr && g_shminfo.shmaddr != (char *)-1) { + shmdt(g_shminfo.shmaddr); + } + } + XCloseDisplay(g_display); + g_display = NULL; +} + +// ============ Pointer shape monitor ============ +// A dedicated connection: input injection shares g_display across threads, +// while this one is owned by the single monitor thread. +static Display *g_cursor_display = NULL; +static int g_cursor_event_base = 0; +static unsigned long g_cursor_serial = 0; + +int x11_cursor_open(const char *display_name) { + if (g_cursor_display) return 0; + g_cursor_display = XOpenDisplay(display_name); + if (!g_cursor_display) return -1; + int error_base; + if (!XFixesQueryExtension(g_cursor_display, &g_cursor_event_base, &error_base)) { + XCloseDisplay(g_cursor_display); + g_cursor_display = NULL; + return -2; + } + XFixesSelectCursorInput(g_cursor_display, DefaultRootWindow(g_cursor_display), + XFixesDisplayCursorNotifyMask); + XFlush(g_cursor_display); + return 0; +} + +/* Blocks until the X server has an event (e.g. a cursor change) or timeout_ms passes, + * so a shape change is forwarded immediately instead of on the next polling tick. */ +int x11_cursor_wait(int timeout_ms) { + if (!g_cursor_display) return -1; + if (XPending(g_cursor_display)) return 1; + struct pollfd fd = { ConnectionNumber(g_cursor_display), POLLIN, 0 }; + return poll(&fd, 1, timeout_ms); +} + +/* Copies the current cursor when it changed (or when force is set). + * pixels receive premultiplied ARGB32. Returns 1 copied, 0 unchanged, <0 error. */ +int x11_cursor_poll(uint32_t *pixels, int max_pixels, int *width, int *height, + int *hot_x, int *hot_y, int force) { + if (!g_cursor_display) return -1; + int changed = force; + while (XPending(g_cursor_display)) { + XEvent event; + XNextEvent(g_cursor_display, &event); + if (event.type == g_cursor_event_base + XFixesCursorNotify) changed = 1; + } + if (!changed) return 0; + XFixesCursorImage *image = XFixesGetCursorImage(g_cursor_display); + if (!image) return -2; + int result = 0; + if (force || image->cursor_serial != g_cursor_serial) { + int count = image->width * image->height; + if (image->width == 0 || image->height == 0 || count > max_pixels) { + result = -3; + } else { + for (int i = 0; i < count; i++) pixels[i] = (uint32_t)image->pixels[i]; + *width = image->width; + *height = image->height; + *hot_x = image->xhot; + *hot_y = image->yhot; + g_cursor_serial = image->cursor_serial; + result = 1; + } + } + XFree(image); + return result; +} diff --git a/config.example.json b/config.example.json new file mode 100644 index 0000000..d297b1e --- /dev/null +++ b/config.example.json @@ -0,0 +1,12 @@ +{ + "_comment": "Written by `uuremote-server login`; you normally do not edit this file.", + "user_id": "", + "device_id": "", + "client_id": "", + "system_id": "", + "machine_guid": "", + "token": "", + "csrf": "", + "sign_key": "", + "ffmpeg_root": "" +} diff --git a/docs/images/login-window.png b/docs/images/login-window.png new file mode 100644 index 0000000000000000000000000000000000000000..dc67fb65a703524e65d546e0d97aaae89d39c366 GIT binary patch literal 85875 zcmZsCbyQXDx9&y+6eL7Slul`oknWJ~4gqNa>1GoGN+aFf-Q7~s-QBV2hQ0S)eBbY! zd&a%TG5m+I_FC^dd(LM*zZB&q(NPIeK_C$NXDKmd5a`(q@SottGvF`1k$h?(1Q6)6 zn6RpA%8?$DD~{y5H2#6@4G|HkpP){^=4P4iF7ZZ;$}IsC$}l`>G#u2LhGyWOj+6+t zlutt{Y}BNSC2_fViHgP{-fJ*=rF6*i0&+auoQ{rIvo_$t!GcW?tX-*kVHz`*MNvt} zq0B&Qj6N|&MTw5RQ`qiTAYoiD)sAsNOKJR!+k78FFQ$t5E1$@bHh5zMJtopf>+L~q zri@6j3Gr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8y4F?es?&?rbh+g63~9tzjE^rm@`zD9BR4aO%VY2nQtSX ztOGp@lC+q+J{9Cp0oR9$h_cI)YeT6opvM)or_h=GFTfk>LzP{^yWNY~Uf_mO6>s`^ zsy$%Z4+-9XKOgq=I+XY+fE51k0HDI;?EK0ngRXwkXc5rvZD>2l-wcQwH1WTS@>CS+ z(5B|YpLV0s3V_dm=gD{dUt>6Kco@U!k(jJ3GHAc?@zJ(Me8@v^#N$D6?}v7cVODb= zu(<$y@=v1>P-mBZsVq&O)M-owqUR$-ihu_NT4jIptvgu%EYIsy z3pTr z(hHP{f((zrA>m7q$6Cgv3$i``d{?L}YfzRE=qvG1rVvoZ92gbtHF*H||Nnv5SXt~n zg(f04i17u+7>P`%5HKG4g8se-4AsW->m)otreYl0P?nG%`cVE&bwGP}{=TPKnDin4 zH)ycK@xSK%pRve02H23p7cM%|Ji!P4aq$)Pk~Sp(TH!2?K#t=Ch2n?Ul|JfTwHju0 zV%AX|n`y@52ZiW=EK78R4%c_NngdnO=n7`n=Wp51KWV1_q zMSRX2ivi3=njy*Xp>_Wu6DI%@J6WBD48^sQKpFTK#J`RfDEA=)CdU?HGn>KicsCq= z7m48;C^F&}eDEcpr`b&v6#&Nu}8l95mp JuMss4{(op)mQ4Tv literal 0 HcmV?d00001 diff --git a/src/audio.rs b/src/audio.rs new file mode 100644 index 0000000..e9ffebc --- /dev/null +++ b/src/audio.rs @@ -0,0 +1,92 @@ +//! Desktop sound for the viewer's 声音 menu: the default output's monitor (PulseAudio or +//! PipeWire-pulse) is encoded to Opus by FFmpeg and sent on the negotiated audio m-line. +//! PipeWire monitors ignore the sink's mute by default, so 被控端静音运行 keeps the stream audible. +//! `UU_AUDIO=0` disables it; `UU_AUDIO_SOURCE` picks another Pulse source. + +use std::io::Read; +use std::process::{Child, Command, Stdio}; +use std::sync::Arc; +use std::time::Duration; +use webrtc::media::io::ogg_reader::OggReader; +use webrtc::media::Sample; +use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState; +use webrtc::peer_connection::RTCPeerConnection; +use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample; + +/// One Opus packet per Ogg page (FFmpeg -page_duration), 20 ms each. +const FRAME: Duration = Duration::from_millis(20); + +pub fn enabled() -> bool { std::env::var("UU_AUDIO").map_or(true, |v| v != "0") } + +struct Encoder(Child); +impl Drop for Encoder { fn drop(&mut self) { let _ = self.0.kill(); let _ = self.0.wait(); } } + +fn spawn_encoder() -> Result { + let source = std::env::var("UU_AUDIO_SOURCE").unwrap_or_else(|_| "@DEFAULT_MONITOR@".into()); + let mut command = match crate::config::ffmpeg_root() { + Some(root) => { let mut c = Command::new(root.join("bin/ffmpeg")); c.env("LD_LIBRARY_PATH", root.join("lib/x86_64-linux-gnu")); c } + None => Command::new("ffmpeg"), + }; + command.args(["-hide_banner", "-loglevel", "error", "-nostdin", + "-f", "pulse", "-fragment_size", "1920", "-i", &source, "-vn", + "-c:a", "libopus", "-ar", "48000", "-ac", "2", "-b:a", "128k", "-application", "lowdelay", + "-frame_duration", "20", "-page_duration", "20000", "-flush_packets", "1", "-f", "ogg", "pipe:1"]) + .stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::inherit()); + command.spawn().map(Encoder).map_err(|e| format!("Start audio encoder: {e}")) +} + +/// Reads Opus packets until the encoder ends or `tx` closes. Blocking. +fn read_packets(stdout: impl Read, tx: &tokio::sync::mpsc::Sender) -> Result<(), String> { + let (mut reader, _) = OggReader::new(stdout, false).map_err(|e| format!("Audio Ogg header: {e}"))?; + loop { + let (payload, _) = reader.parse_next_page().map_err(|e| format!("Audio Ogg page: {e}"))?; + if payload.starts_with(b"OpusTags") { continue; } + if tx.blocking_send(payload.freeze()).is_err() { return Ok(()); } + } +} + +fn closed(pc: &RTCPeerConnection) -> bool { + matches!(pc.connection_state(), RTCPeerConnectionState::Closed | RTCPeerConnectionState::Failed) +} + +/// Streams desktop sound to one viewer until its connection closes; restarts a failed encoder. +pub async fn stream_audio(pc: Arc, track: Arc) { + while pc.connection_state() != RTCPeerConnectionState::Connected { + if closed(&pc) { return; } + tokio::time::sleep(Duration::from_millis(100)).await; + } + let mut failures = 0u32; + while !closed(&pc) { + let mut encoder = match spawn_encoder() { + Ok(encoder) => encoder, + Err(e) => { log::warn!("{e}"); return; } + }; + let Some(stdout) = encoder.0.stdout.take() else { return }; + let (tx, mut rx) = tokio::sync::mpsc::channel::(25); + let reader = tokio::task::spawn_blocking(move || read_packets(stdout, &tx)); + log::info!("Desktop audio started: opus 48k stereo"); + let mut packets = 0u64; + let mut health = tokio::time::interval(Duration::from_millis(500)); + loop { + tokio::select! { + packet = rx.recv() => { + let Some(data) = packet else { break }; + if let Err(e) = track.write_sample(&Sample { data, duration: FRAME, ..Default::default() }).await { + log::warn!("Audio send: {e}"); break; + } + packets += 1; + }, + _ = health.tick() => if closed(&pc) { break }, + } + } + drop(rx); + drop(encoder); // kills FFmpeg, which ends the blocking reader + let result = reader.await.unwrap_or_else(|e| Err(e.to_string())); + if closed(&pc) { break; } + log::warn!("Desktop audio stopped after {packets} packets: {:?}", result.err()); + failures = if packets > 250 { 0 } else { failures + 1 }; + if failures >= 5 { log::warn!("Desktop audio disabled for this connection"); return; } + tokio::time::sleep(Duration::from_secs(2)).await; + } + log::info!("Desktop audio ended"); +} diff --git a/src/auth.rs b/src/auth.rs new file mode 100644 index 0000000..bfe897b --- /dev/null +++ b/src/auth.rs @@ -0,0 +1,205 @@ +//! UU Remote Official Authentication & REST Client + +use hmac::{Hmac, Mac}; +use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; +use serde::{Deserialize, Serialize}; +use sha2::Sha256; +use std::collections::BTreeMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +type HmacSha256 = Hmac; + +/// Request-signing key built into the official UU PC client (x-param-plat=1); the same for +/// every user. Config "sign_key" / UU_SIGN_KEY override it if NetEase rotates the key. +pub const DEFAULT_SIGN_KEY: &str = "alWiSzXZTLu3WfFnw13uBru3"; +/// API code for an invalid or expired login token ("Token无效或已过期", HTTP 422). +pub const TOKEN_INVALID: i64 = 1120; + +#[derive(Debug)] +pub enum RoomError { LoginExpired, Other(String) } +impl std::fmt::Display for RoomError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { RoomError::LoginExpired => f.write_str("login token invalid or expired"), RoomError::Other(e) => f.write_str(e) } + } +} + +pub const BASE_URL: &str = "https://api.nrd.nie.163.com"; + +/// Account binding and request-signing key. Never committed: loaded at startup from +/// a private config file or environment variables (see config.example.json). +#[derive(Clone, Serialize, Deserialize, Default)] +pub struct Credentials { + pub user_id: String, + pub device_id: String, + pub client_id: String, + pub system_id: String, + pub token: String, + pub csrf: String, + /// HMAC-SHA256 key for x-param-sign. + pub sign_key: String, +} + +impl std::fmt::Debug for Credentials { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("Credentials { .. }") + } +} + +impl Credentials { + /// Environment variables win over the file (UU_USER_ID, UU_DEVICE_ID, UU_CLIENT_ID, + /// UU_SYSTEM_ID, UU_TOKEN, UU_CSRF, UU_SIGN_KEY). + pub fn load(file: Option<&serde_json::Value>) -> Result { + let get = |key: &str| -> String { + std::env::var(format!("UU_{}", key.to_uppercase())).ok().filter(|v| !v.is_empty()) + .or_else(|| file.and_then(|f| f.get(key)).and_then(|v| v.as_str()).map(str::to_owned)) + .unwrap_or_default() + }; + let creds = Self { + user_id: get("user_id"), device_id: get("device_id"), client_id: get("client_id"), + system_id: get("system_id"), token: get("token"), csrf: get("csrf"), + sign_key: Some(get("sign_key")).filter(|k| !k.is_empty()).unwrap_or_else(|| DEFAULT_SIGN_KEY.into()), + }; + let missing: Vec<&str> = [("user_id", &creds.user_id), ("device_id", &creds.device_id), ("client_id", &creds.client_id), + ("system_id", &creds.system_id), ("token", &creds.token), ("csrf", &creds.csrf), ("sign_key", &creds.sign_key)] + .iter().filter(|(_, v)| v.is_empty()).map(|(k, _)| *k).collect(); + if missing.is_empty() { Ok(creds) } else { Err(format!("missing credential settings: {}", missing.join(", "))) } + } +} + +#[derive(Debug, Deserialize)] +pub struct ApiResponse { + pub code: i32, + pub msg: String, + pub data: Option, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct RoomData { + pub signaling_server: String, + pub token: String, + pub signaling_list: Option>, + pub ws_connect_timeout_ms: Option, +} + +pub struct UUAuthClient { + pub creds: Credentials, + http: reqwest::Client, +} + +impl UUAuthClient { + pub fn new(creds: Credentials) -> Self { + let http = reqwest::Client::builder() + .timeout(std::time::Duration::from_secs(12)) + .build() + .unwrap(); + Self { creds, http } + } + + /// 计算网易 NRD HMAC-SHA256 签名 + pub fn sign_request( + &self, + method: &str, + path: &str, + headers: &BTreeMap, + body_str: &str, + ) -> String { + let mut filtered: BTreeMap = BTreeMap::new(); + for (k, v) in headers { + let kl = k.to_lowercase(); + if kl.starts_with("x-param-") && kl != "x-param-sign" { + filtered.insert(kl, v.clone()); + } + } + let params_str = filtered + .iter() + .map(|(k, v)| format!("{}={}", k, v)) + .collect::>() + .join("&"); + + let string_to_sign = format!("{}{}{}{}", method.to_uppercase(), path, params_str, body_str); + let mut mac = HmacSha256::new_from_slice(self.creds.sign_key.as_bytes()).expect("HMAC can take key"); + mac.update(string_to_sign.as_bytes()); + hex::encode(mac.finalize().into_bytes()) + } + + pub fn build_headers( + &self, + method: &str, + path: &str, + body_str: &str, + ) -> HeaderMap { + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + let ts = now.to_string(); + + let mut param_map = BTreeMap::new(); + param_map.insert("x-param-plat".into(), "1".into()); + param_map.insert("x-param-vn".into(), "4.42.0.2770".into()); + param_map.insert("x-param-vc".into(), "2770".into()); + param_map.insert("x-param-pkgn".into(), "com.netease.gameviewer".into()); + param_map.insert("x-param-chn".into(), "gwqd".into()); + param_map.insert("x-param-lang".into(), "zh-CN".into()); + param_map.insert("x-param-cnt".into(), "CN".into()); + // Before login some identifiers do not exist yet; absent ones are not sent or signed. + for (key, value) in [("x-param-client-id", &self.creds.client_id), ("x-param-device-id", &self.creds.device_id), + ("x-param-system-id", &self.creds.system_id), ("x-param-user-id", &self.creds.user_id)] { + if !value.is_empty() { param_map.insert(key.into(), value.clone()); } + } + param_map.insert("x-param-ts".into(), ts); + + let sign = self.sign_request(method, path, ¶m_map, body_str); + + let mut headers = HeaderMap::new(); + headers.insert("Content-Type", HeaderValue::from_static("application/json")); + headers.insert("Accept", HeaderValue::from_static("application/json")); + headers.insert( + "User-Agent", + HeaderValue::from_static("UURemote/4.42.0 (Windows NT 10.0; Win64; x64)"), + ); + if !self.creds.token.is_empty() { + if let Ok(v) = HeaderValue::from_str(&format!("Bearer {}", self.creds.token)) { headers.insert("Authorization", v); } + if let Ok(v) = HeaderValue::from_str(&format!("nrd_access_token={}; nrd_csrf_access_token={}", self.creds.token, self.creds.csrf)) { + headers.insert("Cookie", v); + } + if let Ok(v) = HeaderValue::from_str(&self.creds.csrf) { headers.insert("X-CSRF-TOKEN", v); } + } + + for (k, v) in param_map { + if let Ok(name) = HeaderName::from_bytes(k.as_bytes()) { + if let Ok(val) = HeaderValue::from_str(&v) { + headers.insert(name, val); + } + } + } + headers.insert("X-Param-SIGN", HeaderValue::from_str(&sign).unwrap()); + + headers + } + + /// Signed JSON POST; returns (HTTP status, decoded body). + pub async fn post_json(&self, path: &str, body: &serde_json::Value) -> Result<(u16, serde_json::Value), String> { + let body_str = serde_json::to_string(body).map_err(|e| e.to_string())?; + let resp = self.http.post(format!("{}{}", BASE_URL, path)) + .headers(self.build_headers("POST", path, &body_str)).body(body_str) + .send().await.map_err(|e| format!("HTTP post {path} failed: {e}"))?; + let status = resp.status().as_u16(); + let value = resp.json().await.unwrap_or(serde_json::Value::Null); + Ok((status, value)) + } + + /// 向网易服务器请求创建房间,获取最新的信令服务器与鉴权 Token + pub async fn create_room(&self) -> Result { + let (status, body) = self.post_json("/api/v1/room/create", &serde_json::json!({})).await.map_err(RoomError::Other)?; + let code = body.get("code").and_then(|c| c.as_i64()).unwrap_or(-1); + if code == TOKEN_INVALID { return Err(RoomError::LoginExpired); } + if status == 200 && code == 0 { + if let Some(data) = body.get("data") { + return serde_json::from_value(data.clone()).map_err(|e| RoomError::Other(format!("room data decode failed: {e}"))); + } + } + Err(RoomError::Other(format!("create_room error http {status} code {code}: {}", + body.get("msg").and_then(|m| m.as_str()).unwrap_or("")))) + } +} diff --git a/src/capability.rs b/src/capability.rs new file mode 100644 index 0000000..345926f --- /dev/null +++ b/src/capability.rs @@ -0,0 +1,75 @@ +//! Wire payloads reconstructed from the official libstreamer ARM64 serializers. +//! See analysis/protocol-fix-20261013/datachannel for address-bound evidence. +//! These payloads do not claim server acceptance or invent missing handshake steps. + +use serde_json::{json, Value}; + +pub const ICE_FINISHED_EVENT: &str = "ice_finished_log"; +pub const FORWARD_SETTING_EVENT: &str = "forward_setting"; +pub const VIDEO_CODEC_H264: i32 = 1; +pub const CODEC_IMPL_NVENC: i32 = 0; + +/// Official serializer emits exactly two string fields (0x107190). +/// The event is telemetry emitted for official pc::State 6; it is not an ACK. +pub fn ice_finished(ice_id: &str, app_control_id: &str) -> Value { + json!({"ice_id": ice_id, "app_control_id": app_control_id}) +} + +/// Supply the stable id of a display that this host can actually capture. +/// Official Mac display construction uses type 0 and HDR disabled value 0. +/// `codec_impl` is caller-selected: the observed names are 0 NVENC, 1 AMD AMF, +/// 2 Intel QSV, 3 VideoToolbox, 4 MediaCodec; values >=5 log as SoftWare. +/// Using 5 as software is an inference and must be runtime-validated by caller. +pub fn h264_device_capability( + client_id: &str, + ice_id: &str, + display_id: i32, + fps: i32, + codec_impl: i32, +) -> Value { + json!({ + "client_id": client_id, + "type": "device_capability", + "data": { + "display_info": [{"id": display_id, "fps": fps, "type": 0, "hdr": 0}], + "video_codec_capability": [{ + "video_codec": VIDEO_CODEC_H264, + "chroma_sampling": 1, + "codec_impl": codec_impl, + "bit_depth": 8 + }], + "ice_id": ice_id + } + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ice_finished_keeps_string_identifiers_and_exact_fields() { + let payload = ice_finished("ice-example", "control-example"); + assert_eq!(payload.as_object().unwrap().len(), 2); + assert!(payload["ice_id"].is_string()); + assert_eq!(payload["app_control_id"], "control-example"); + assert_eq!(ICE_FINISHED_EVENT, "ice_finished_log"); + } + + #[test] + fn device_capability_uses_object_data_and_string_ice_id() { + let payload = h264_device_capability("client-example", "ice-example", 11, 60, 0); + assert_eq!(payload["type"], "device_capability"); + assert!(payload["data"].is_object()); + assert_eq!(payload["data"]["ice_id"], "ice-example"); + let display = &payload["data"]["display_info"][0]; + assert_eq!(display.as_object().unwrap().len(), 4); + assert_eq!(display["id"], 11); + assert_eq!(display["fps"], 60); + let codec = &payload["data"]["video_codec_capability"][0]; + assert_eq!(codec.as_object().unwrap().len(), 4); + assert_eq!(codec["video_codec"], 1); + assert_eq!(codec["codec_impl"], 0); + assert_eq!(codec["bit_depth"], 8); + } +} diff --git a/src/capture.rs b/src/capture.rs new file mode 100644 index 0000000..3e4caaa --- /dev/null +++ b/src/capture.rs @@ -0,0 +1,142 @@ +//! Native Linux X11 Capture Engine via XShm + +use std::sync::Mutex; + +#[cfg(target_os = "linux")] +extern "C" { + fn x11_init(display_name: *const libc::c_char) -> libc::c_int; + fn x11_get_dimensions(out_w: *mut libc::c_int, out_h: *mut libc::c_int) -> libc::c_int; + fn x11_capture_frame( + out_buffer: *mut libc::c_uchar, + out_w: *mut libc::c_int, + out_h: *mut libc::c_int, + ) -> libc::c_int; + fn x11_close(); + fn x11_wake_display() -> libc::c_int; + fn x11_display_name() -> *const libc::c_char; +} + +#[cfg(not(target_os = "linux"))] +unsafe fn x11_init(_: *const libc::c_char) -> libc::c_int { 0 } +#[cfg(not(target_os = "linux"))] +unsafe fn x11_get_dimensions(out_w: *mut libc::c_int, out_h: *mut libc::c_int) -> libc::c_int { + *out_w = 1920; + *out_h = 1080; + 0 +} +#[cfg(not(target_os = "linux"))] +unsafe fn x11_capture_frame( + out_buffer: *mut libc::c_uchar, + out_w: *mut libc::c_int, + out_h: *mut libc::c_int, +) -> libc::c_int { + *out_w = 1920; + *out_h = 1080; + std::ptr::write_bytes(out_buffer, 0, (1920 * 1080 * 4) as usize); + 0 +} +#[cfg(not(target_os = "linux"))] +unsafe fn x11_close() {} + +#[cfg(not(target_os = "linux"))] +unsafe fn x11_display_name() -> *const libc::c_char { b":0\0".as_ptr().cast() } + +pub struct ScreenCapture { + pub backend: crate::desktop_backend::DesktopBackend, + pub init_error: Option, + pub portal: Option>, + pub display: String, + pub width: u32, + pub height: u32, + buffer: Mutex>, +} + +impl ScreenCapture { + pub fn new() -> Result { + let backend=crate::desktop_backend::detect()?; + if backend == crate::desktop_backend::DesktopBackend::Portal { + let session=std::sync::Arc::new(crate::portal::PortalSession::open()?); + let (width,height)=(session.width,session.height); + return Ok(Self { backend,init_error:None,portal:Some(session),display:"wayland:portal".into(),width,height, + buffer:Mutex::new(vec![0;(width as usize)*(height as usize)*4]) }); + } + if backend == crate::desktop_backend::DesktopBackend::Wayland { + let (width,height)=crate::wayland::init()?; + return Ok(Self { backend, init_error:None, portal:None, display:"wayland:native".into(), width,height, + buffer:Mutex::new(vec![0;(width as usize)*(height as usize)*4]) }); + } + let ret = unsafe { x11_init(std::ptr::null()) }; + if ret != 0 { + return Err(format!("x11_init failed with code {}", ret)); + } + + let mut w: libc::c_int = 0; + let mut h: libc::c_int = 0; + unsafe { x11_get_dimensions(&mut w, &mut h) }; + + if w <= 0 || h <= 0 { + return Err(format!("Invalid screen dimensions: {}x{}", w, h)); + } + + let buf_size = (w * h * 4) as usize; + let buffer = Mutex::new(vec![0u8; buf_size]); + + log::info!("ScreenCapture initialized: {}x{}", w, h); + let display_ptr = unsafe { x11_display_name() }; + if display_ptr.is_null() { return Err("Capture display name unavailable".into()); } + let display = unsafe { std::ffi::CStr::from_ptr(display_ptr) }.to_string_lossy().into_owned(); + log::info!("Selected capture display: {}", display); + Ok(Self { + backend, + init_error:None, + portal:None, + display, + width: w as u32, + height: h as u32, + buffer, + }) + } + + /// Metadata for non-desktop tools. Never advertise a usable fake screen. + pub fn unavailable(error:String)->Self { + Self { backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), + init_error:Some(error), portal:None, display:String::new(), width:0,height:0,buffer:Mutex::new(Vec::new()) } + } + + /// 截取一帧 BGRA 图像 + pub fn capture_frame(&self) -> Result, String> { + if let Some(error)=&self.init_error { return Err(error.clone()); } + let mut buf = self.buffer.lock().unwrap(); + if let Some(session)=&self.portal { session.capture(&mut buf)?; return Ok(buf.clone()); } + if self.backend == crate::desktop_backend::DesktopBackend::Wayland { + crate::wayland::capture(&mut buf)?; + return Ok(buf.clone()); + } + let mut w: libc::c_int = self.width as libc::c_int; + let mut h: libc::c_int = self.height as libc::c_int; + + let ret = unsafe { x11_capture_frame(buf.as_mut_ptr(), &mut w, &mut h) }; + if ret != 0 { + return Err(format!("x11_capture_frame failed with code {}", ret)); + } + + Ok(buf.clone()) + } +} + +impl Drop for ScreenCapture { + fn drop(&mut self) { + if self.init_error.is_none() && self.backend==crate::desktop_backend::DesktopBackend::X11 { unsafe { x11_close() }; } + } +} + +/// Keep the display visible only while a peer is streaming; never unlock it. +pub fn keep_display_awake() -> Result<(), String> { + if crate::desktop_backend::detect()? == crate::desktop_backend::DesktopBackend::Portal { return Ok(()); } + if crate::desktop_backend::detect()? == crate::desktop_backend::DesktopBackend::Wayland { + return crate::wayland::wake(); + } + #[cfg(target_os = "linux")] + if unsafe { x11_wake_display() } != 0 { return Err("X11 display wake failed".into()); } + Ok(()) +} diff --git a/src/capture_setting.rs b/src/capture_setting.rs new file mode 100644 index 0000000..2578f85 --- /dev/null +++ b/src/capture_setting.rs @@ -0,0 +1,237 @@ +//! Viewer quality/frame-rate settings (画质 / 帧率) for the desktop stream. +//! +//! The viewer only sends settings to a host whose echo FeatureFlag declares ff_capture_setting +//! (field 1); our echo declares FF_CAPTURE_SETTING_CUSTOM_BITRATE = 4. Requests arrive as +//! Message 21 RpcRequest { 1 RequestHeader, 2 CaptureSettingRequest | 3 FpsSettingRequest | +//! 4 VideoQualitySettingReqeust } and are answered with Message 22 RpcResponse { 1 ResponseHeader +//! (same request_id), 2 CaptureSettingResponse { 1 errors (none = applied) } }. The applied values +//! are then reported with Message 25 CaptureSettingSync. Field maps: server-field-maps.json. + +use crate::protocol::{decode_wire, WireField, WireValue}; +use tokio::sync::watch; + +/// Official GvPb_VideoQuality values. +pub const QUALITY_FAST: u64 = 1; +pub const QUALITY_GENERAL: u64 = 2; +pub const QUALITY_HD: u64 = 3; +pub const QUALITY_BLURAY: u64 = 4; +pub const QUALITY_AUTO: u64 = 5; +pub const QUALITY_CUSTOM: u64 = 6; + +/// FeatureFlag.ff_capture_setting we declare: fps, preset quality and custom bitrate. +/// (Chroma 4:4:4, DPI scaling and HDR are higher versions and are not implemented.) +pub const FEATURE_VERSION: u64 = 4; + +const MIN_FPS: u32 = 5; +const MAX_FPS: u32 = 144; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VideoSettings { + pub fps: u32, + pub quality: u64, + /// Viewer max_custom_bitrate (only used for QUALITY_CUSTOM): Mbit/s, or kbit/s above 1000. + pub custom_mbps: u32, + /// Scaled stream size (其他分辨率); None streams the native desktop size. + pub output: Option<(u32, u32)>, +} + +impl Default for VideoSettings { + fn default() -> Self { Self { fps: 60, quality: QUALITY_AUTO, custom_mbps: 0, output: None } } +} + +/// Selectable smaller stream sizes with the desktop's aspect ratio (even dimensions). +/// The host display itself is never reconfigured; the encoder scales. +pub fn scaled_sizes(native: (u32, u32)) -> Vec<(u32, u32)> { + [5u32, 4, 3, 2].iter().map(|sixths| (native.0 * sixths / 6 & !1, native.1 * sixths / 6 & !1)) + .filter(|(w, h)| *w >= 640 && *h >= 360).collect() +} + +/// Requested size clamped to the desktop: None (native) when at least as large. +fn clamp_output(native: (u32, u32), width: u64, height: u64) -> Option<(u32, u32)> { + if width == 0 || height == 0 { return None; } + if width >= u64::from(native.0) || height >= u64::from(native.1) { return None; } + Some(((width as u32).max(320) & !1, (height as u32).max(180) & !1)) +} + +impl VideoSettings { + /// Constant-quality level: presets must look different even on a mostly static desktop, + /// where a bitrate cap alone never binds (measured ~2.7 Mbit/s at CQ18). + pub fn cq(&self) -> u32 { + match self.quality { QUALITY_BLURAY => 17, QUALITY_HD => 21, QUALITY_GENERAL => 26, QUALITY_FAST => 30, _ => 18 } + } + + /// Encoder bitrate cap in kbit/s; None keeps the constant-quality default (自动). + /// Preset caps follow the viewer menu labels: 高清 2M, 超清 8M, 原画 20M. + pub fn max_kbps(&self) -> Option { + match self.quality { + QUALITY_FAST => Some(1_000), + QUALITY_GENERAL => Some(2_000), + QUALITY_HD => Some(8_000), + QUALITY_BLURAY => Some(20_000), + QUALITY_CUSTOM if self.custom_mbps > 0 => + Some(if self.custom_mbps > 1_000 { self.custom_mbps } else { self.custom_mbps * 1_000 }.min(100_000)), + _ => None, + } + } +} + +fn varint(mut v: u64, out: &mut Vec) { while v >= 128 { out.push((v as u8 & 127) | 128); v >>= 7; } out.push(v as u8); } +fn put_varint(field: u64, v: u64, out: &mut Vec) { varint(field << 3, out); varint(v, out); } +fn put_bytes(field: u64, v: &[u8], out: &mut Vec) { varint(field << 3 | 2, out); varint(v.len() as u64, out); out.extend_from_slice(v); } + +fn number(fields: &[WireField], n: u32) -> Option { + fields.iter().find_map(|f| match (f.number, &f.value) { (x, WireValue::Varint(v)) if x == n => Some(*v), _ => None }) +} +fn message<'a>(fields: &[WireField<'a>], n: u32) -> Option<&'a [u8]> { + fields.iter().find_map(|f| match (f.number, &f.value) { (x, WireValue::Bytes(b)) if x == n => Some(*b), _ => None }) +} + +/// Frame rate from a value that is either an fps option index (observed 1 = 30, 2 = 60; +/// 3/4 assumed 90/144 from the menu order) or already frames per second. +fn fps_from_option(value: u64) -> Option { + match value { 0 => None, 1 => Some(30), 2 => Some(60), 3 => Some(90), 4 => Some(144), v => Some(v) } +} + +/// Applies a capture-setting RPC to `settings` and returns the RpcResponse payload (Message 22), +/// or None when the RPC is not a capture/fps/quality setting. +pub fn handle_rpc(rpc: &[WireField], settings: &watch::Sender, native: (u32, u32)) -> Option> { + let header = message(rpc, 1).unwrap_or(&[]); + let mut next = *settings.borrow(); + if let Some(request) = message(rpc, 2) { + let fields = decode_wire(request).ok()?; + // Numbers only: fps, quality, bitrate, resolution and flags carry no user content. + log::info!("Capture setting request: {:?}", fields.iter().filter_map(|f| match f.value { + WireValue::Varint(v) => Some((f.number, v)), _ => None }).collect::>()); + // Field 1 is the viewer's fps option index (1 = 30, 2 = 60, ...); 18 fpsCount is the frame rate. + if let Some(fps) = number(&fields, 18).filter(|v| *v > 0).or_else(|| number(&fields, 1).and_then(fps_from_option)) { next.fps = fps as u32; } + if let Some(quality) = number(&fields, 2).filter(|v| *v > 0) { next.quality = quality; } + if let Some(bitrate) = number(&fields, 8).filter(|v| *v > 0) { next.custom_mbps = bitrate as u32; } + // ChooseResolutionType 3 = follow remote (native); otherwise pixel size, else logical size. + if number(&fields, 10) == Some(3) { next.output = None; } + else if let Some((w, h)) = number(&fields, 16).zip(number(&fields, 17)).or_else(|| number(&fields, 5).zip(number(&fields, 6))) { + next.output = clamp_output(native, w, h); + } + } else if let Some(request) = message(rpc, 6) { + let fields = decode_wire(request).ok()?; + let (w, h) = (number(&fields, 1).unwrap_or(0), number(&fields, 2).unwrap_or(0)); + log::info!("Resolution setting request: {}x{}", w, h); + next.output = clamp_output(native, w, h); + } else if let Some(request) = message(rpc, 3) { + let fields = decode_wire(request).ok()?; + log::info!("Fps setting request: fps={:?}", number(&fields, 1)); + if let Some(fps) = number(&fields, 1).and_then(fps_from_option) { next.fps = fps as u32; } + } else if let Some(request) = message(rpc, 4) { + let fields = decode_wire(request).ok()?; + log::info!("Video quality setting request: quality={:?}", number(&fields, 1)); + if let Some(quality) = number(&fields, 1).filter(|v| *v > 0) { next.quality = quality; } + } else { + return None; + } + next.fps = next.fps.clamp(MIN_FPS, MAX_FPS); + settings.send_if_modified(|current| if *current != next { + log::info!("Desktop video settings: fps={} quality={} max_kbps={:?} output={:?}", next.fps, next.quality, next.max_kbps(), next.output); + *current = next; true + } else { false }); + let mut out = Vec::new(); + put_bytes(1, header, &mut out); + put_bytes(2, &[], &mut out); // CaptureSettingResponse without errors: applied + Some(out) +} + +/// Message 7 ScreenSources for the single desktop: native size, scaled choices, current size. +pub fn screen_sources(seq: u64, timestamp: u64, native: (u32, u32), output: Option<(u32, u32)>, name: &str) -> Result, String> { + use crate::initialization::{Screen, WinRect}; + let (w, h) = (native.0 as i32, native.1 as i32); + let scaled: Vec<(i32, i32)> = scaled_sizes(native).into_iter().map(|(w, h)| (w as i32, h as i32)).collect(); + let resolution = WinRect { left: 0, top: 0, width: w, height: h, pixel_width: w, pixel_height: h }; + let screens = [Screen { id: 0, fps: crate::video::FPS as i32, resolution, primary: true, dpr: 1.0, + display_name: name, video_track_index: 0, screen_type: 0, builtin_screen_type: 0, + scaled: &scaled, current: output.map(|(w, h)| (w as i32, h as i32)) }]; + crate::initialization::encode_screen_sources(seq, timestamp, &screens, 0) +} + +/// Message 25 CaptureSettingSync payload reporting what the host now encodes. +pub fn sync_payload(settings: &VideoSettings, native: (u32, u32)) -> Vec { + let size = settings.output.unwrap_or(native); + let mut out = Vec::new(); + put_varint(1, u64::from(settings.fps), &mut out); + put_varint(2, settings.quality, &mut out); + put_varint(3, 1, &mut out); // ChromaFormat_420 + if settings.custom_mbps > 0 { put_varint(4, u64::from(settings.custom_mbps), &mut out); } + put_varint(5, u64::from(size.0), &mut out); + put_varint(6, u64::from(size.1), &mut out); + put_varint(9, u64::from(size.0), &mut out); + put_varint(10, u64::from(size.1), &mut out); + out +} + +#[cfg(test)] +mod tests { + use super::*; + + fn rpc(request_id: u64, field: u64, body: &[u8]) -> Vec { + let mut header = Vec::new(); + put_varint(1, request_id, &mut header); + let mut out = Vec::new(); + put_bytes(1, &header, &mut out); + put_bytes(field, body, &mut out); + out + } + + #[test] + fn capture_setting_request_updates_fps_and_quality_and_echoes_request_id() { + let (tx, rx) = watch::channel(VideoSettings::default()); + let mut body = Vec::new(); + put_varint(1, 1, &mut body); // option index, not fps + put_varint(2, QUALITY_GENERAL, &mut body); + put_varint(18, 30, &mut body); + let request = rpc(77, 2, &body); + let response = handle_rpc(&decode_wire(&request).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(*rx.borrow(), VideoSettings { fps: 30, quality: QUALITY_GENERAL, custom_mbps: 0, output: None }); + assert_eq!(rx.borrow().max_kbps(), Some(2_000)); + let fields = decode_wire(&response).unwrap(); + assert_eq!(message(&fields, 1), Some(&[8u8, 77][..])); + assert_eq!(message(&fields, 2), Some(&[][..])); + } + + #[test] + fn separate_fps_and_quality_requests_and_limits() { + let (tx, rx) = watch::channel(VideoSettings::default()); + handle_rpc(&decode_wire(&rpc(1, 3, &[8, 200, 1])).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(rx.borrow().fps, MAX_FPS); + // Observed viewer request: option 2 with fpsCount 60 must stream 60 fps, not 2. + let observed = [8, 2, 16, 4, 40, 128, 15, 48, 184, 8, 144, 1, 60]; + handle_rpc(&decode_wire(&rpc(4, 2, &observed)).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(rx.borrow().fps, 60); + handle_rpc(&decode_wire(&rpc(2, 4, &[8, QUALITY_BLURAY as u8])).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(rx.borrow().max_kbps(), Some(20_000)); + assert!(handle_rpc(&decode_wire(&rpc(3, 9, &[])).unwrap(), &tx, (1920, 1080)).is_none()); + } + + #[test] + fn resolution_requests_scale_below_native_only() { + let (tx, rx) = watch::channel(VideoSettings::default()); + handle_rpc(&decode_wire(&rpc(1, 6, &[8, 128, 10, 16, 208, 5])).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(rx.borrow().output, Some((1280, 720))); + handle_rpc(&decode_wire(&rpc(2, 6, &[8, 160, 32, 16, 160, 20])).unwrap(), &tx, (1920, 1080)).unwrap(); + assert_eq!(rx.borrow().output, None); + assert_eq!(scaled_sizes((1920, 1080)), vec![(1600, 900), (1280, 720), (960, 540), (640, 360)]); + } + + #[test] + fn auto_quality_keeps_constant_quality_encoding() { + assert_eq!(VideoSettings::default().max_kbps(), None); + assert_eq!(VideoSettings { quality: QUALITY_CUSTOM, custom_mbps: 0, ..Default::default() }.max_kbps(), None); + assert_eq!(VideoSettings { quality: QUALITY_CUSTOM, custom_mbps: 12, ..Default::default() }.max_kbps(), Some(12_000)); + } + + #[test] + fn sync_reports_fps_quality_and_resolution() { + let payload = sync_payload(&VideoSettings::default(), (1920, 1080)); + let fields = decode_wire(&payload).unwrap(); + assert_eq!(number(&fields, 1), Some(60)); + assert_eq!(number(&fields, 2), Some(QUALITY_AUTO)); + assert_eq!(number(&fields, 5), Some(1920)); + assert_eq!(number(&fields, 10), Some(1080)); + } +} diff --git a/src/clipboard.rs b/src/clipboard.rs new file mode 100644 index 0000000..b50546d --- /dev/null +++ b/src/clipboard.rs @@ -0,0 +1,193 @@ +//! Session-scoped native X11 text selection worker. No content is logged. +use tokio::sync::watch; + +// Keep worst-case UTF-16 plus protobuf framing below webrtc0.10's65535-byte reader. +pub const MAX_TEXT: usize = 30 * 1024; + +pub struct ClipboardBridge { + pub incoming: watch::Sender>, + pub outgoing: watch::Receiver>, + pub ready: tokio::sync::oneshot::Receiver, +} + +#[cfg(target_os = "linux")] +extern "C" { + fn clipboard_open(display: *const libc::c_char) -> *mut libc::c_void; + fn clipboard_set(handle: *mut libc::c_void, text: *const u8, length: usize) -> libc::c_int; + fn clipboard_poll(handle: *mut libc::c_void, out: *mut u8, capacity: usize) -> libc::c_int; + fn clipboard_close(handle: *mut libc::c_void); +} + +pub fn start(display: String) -> ClipboardBridge { + if display == "wayland:native" { return start_wayland(); } + if display == "wayland:portal" { + let (incoming,_)=watch::channel(None);let (_,outgoing)=watch::channel(None); + let (sender,ready)=tokio::sync::oneshot::channel();let _=sender.send(false); + return ClipboardBridge {incoming,outgoing,ready}; + } + let (incoming, mut input) = watch::channel::>(None); + let (output, outgoing) = watch::channel(None); + let (ready_tx, ready) = tokio::sync::oneshot::channel(); + #[cfg(target_os = "linux")] + tokio::task::spawn_blocking(move || { + let Ok(display) = std::ffi::CString::new(display) else { + let _ = ready_tx.send(false); return; + }; + let handle = unsafe { clipboard_open(display.as_ptr()) }; + if handle.is_null() { let _ = ready_tx.send(false); return; } + let _ = ready_tx.send(true); + let mut buffer = vec![0; MAX_TEXT]; + while !output.is_closed() && input.has_changed().is_ok() { + if input.has_changed().unwrap_or(false) { + let text = input.borrow_and_update().clone(); + if let Some(text) = text { + if text.len() <= MAX_TEXT { + let result = unsafe { clipboard_set(handle, text.as_ptr(), text.len()) }; + if result != 0 { log::warn!("Native clipboard ownership failed"); } + } + } + } + let length = unsafe { clipboard_poll(handle, buffer.as_mut_ptr(), buffer.len()) }; + if length >= 0 { + if let Ok(text) = std::str::from_utf8(&buffer[..length as usize]) { + output.send_replace(Some(text.to_owned())); + } + } + std::thread::sleep(std::time::Duration::from_millis(10)); + } + unsafe { clipboard_close(handle) }; + }); + #[cfg(not(target_os = "linux"))] + { + let _ = (display, input, output); + let _ = ready_tx.send(false); + } + ClipboardBridge { incoming, outgoing, ready } +} + +fn start_wayland() -> ClipboardBridge { + use tokio::io::{AsyncReadExt,AsyncWriteExt}; + use std::process::Stdio; + let (incoming,mut input)=watch::channel::>(None); + let (output,outgoing)=watch::channel(None); + let (ready_tx,ready)=tokio::sync::oneshot::channel(); + tokio::spawn(async move { + for program in ["wl-copy","wl-paste"] { + let result=tokio::time::timeout(std::time::Duration::from_secs(2), + tokio::process::Command::new(program).arg("--version").kill_on_drop(true) + .stdout(Stdio::null()).stderr(Stdio::null()).status()).await; + if !matches!(result,Ok(Ok(status)) if status.success()) { let _=ready_tx.send(false); return; } + } + let _=ready_tx.send(true); + let mut owner:Option=None; + let mut last=None; + let mut tick=tokio::time::interval(std::time::Duration::from_millis(250)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tokio::select! { + _=output.closed()=>break, + changed=input.changed()=>{ + if changed.is_err() { break; } + let text=input.borrow_and_update().clone(); + if let Some(text)=text.filter(|s|s.len()<=MAX_TEXT) { + if let Some(mut child)=owner.take() { let _=child.kill().await; } + if let Ok(mut child)=tokio::process::Command::new("wl-copy") + .args(["--foreground","--type","text/plain;charset=utf-8"]) + .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).spawn() { + if let Some(mut stdin)=child.stdin.take() { + let written=tokio::time::timeout(std::time::Duration::from_secs(2),stdin.write_all(text.as_bytes())).await; + if matches!(written,Ok(Ok(()))) { last=Some(text); } + } + owner=Some(child); + } + } + }, + _=tick.tick()=>{ + // Bound both content and duration; never log clipboard text. + let read=async { + let mut child=tokio::process::Command::new("wl-paste").args(["--no-newline","--type","text"]) + .stdout(Stdio::piped()).stderr(Stdio::null()).kill_on_drop(true).spawn().ok()?; + let mut bytes=Vec::new(); + child.stdout.take()?.take((MAX_TEXT+1) as u64).read_to_end(&mut bytes).await.ok()?; + if bytes.len()>MAX_TEXT { return None; } + if !child.wait().await.ok()?.success() { return None; } + String::from_utf8(bytes).ok() + }; + if let Ok(Some(text))=tokio::time::timeout(std::time::Duration::from_secs(2),read).await { + if last.as_ref()!=Some(&text) { last=Some(text.clone()); output.send_replace(Some(text)); } + } + }, + } + } + if let Some(mut child)=owner { let _=child.kill().await; } + }); + ClipboardBridge { incoming,outgoing,ready } +} + +#[cfg(all(test,target_os="linux",feature="wayland"))] +mod wayland_acceptance { + use super::*; + use tokio::io::AsyncWriteExt; + use std::process::Stdio; + #[tokio::test] + #[ignore = "requires the isolated uu-hyprland-test desktop"] + async fn native_clipboard_roundtrip() { + assert!(std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap().trim()=="uu-hyprland-test", + "Refusing to alter clipboard outside the isolated test VM"); + assert!(std::env::var_os("WAYLAND_DISPLAY").is_some()); + let mut bridge=start("wayland:native".into()); + assert!(tokio::time::timeout(std::time::Duration::from_secs(3),&mut bridge.ready).await.unwrap().unwrap()); + let incoming="UU Wayland test\n中文 ✓"; + bridge.incoming.send_replace(Some(incoming.into())); + let received=tokio::time::timeout(std::time::Duration::from_secs(3),async { + loop { + use tokio::io::AsyncReadExt; + let mut child=tokio::process::Command::new("wl-paste").args(["--no-newline","--type","text"]) + .kill_on_drop(true).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().unwrap(); + let mut bytes=Vec::new(); + child.stdout.take().unwrap().take((MAX_TEXT+1) as u64).read_to_end(&mut bytes).await.unwrap(); + if bytes.len()<=MAX_TEXT && child.wait().await.unwrap().success() && bytes==incoming.as_bytes() { break; } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + } + }).await; + assert!(received.is_ok(),"Native clipboard did not receive inbound text"); + let mut owner=tokio::process::Command::new("wl-copy").args(["--foreground","--type","text/plain;charset=utf-8"]) + .stdin(Stdio::piped()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true).spawn().unwrap(); + let external="UU native outbound test"; + let mut pipe=owner.stdin.take().unwrap(); pipe.write_all(external.as_bytes()).await.unwrap(); drop(pipe); + let changed=tokio::time::timeout(std::time::Duration::from_secs(3),async { + loop { + bridge.outgoing.changed().await.unwrap(); + if bridge.outgoing.borrow_and_update().as_deref()==Some(external) { break; } + } + }).await; + assert!(changed.is_ok(),"Bridge did not report native outbound text"); + drop(bridge); + owner.kill().await.unwrap(); + } +} + +/// Portal Clipboard shares the authorized video/input Arc and survives native handle renewal. +pub fn start_portal(session: std::sync::Arc) -> ClipboardBridge { + let (incoming,mut input)=watch::channel::>(None); + let (output,outgoing)=watch::channel(None); + let (ready_tx,ready)=tokio::sync::oneshot::channel(); + tokio::task::spawn_blocking(move || { + let available=session.clipboard_ready(); let _=ready_tx.send(available); + if !available { return; } + let mut last=None; let mut pending=None; + while !output.is_closed() && input.has_changed().is_ok() { + if input.has_changed().unwrap_or(false) { + pending=input.borrow_and_update().clone().filter(|text|text.len()<=MAX_TEXT); + } + if let Some(text)=pending.as_ref() { + if session.clipboard_set(text).is_ok() { last=pending.take(); } + } + if let Some(text)=session.clipboard_poll() { + if last.as_ref()!=Some(&text) { last=Some(text.clone()); output.send_replace(Some(text)); } + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + }); + ClipboardBridge {incoming,outgoing,ready} +} diff --git a/src/clipboard_probe.rs b/src/clipboard_probe.rs new file mode 100644 index 0000000..f2c73ea --- /dev/null +++ b/src/clipboard_probe.rs @@ -0,0 +1,68 @@ +//! Synthetic clipboard acceptance; never prints clipboard data. +use std::{io::{BufRead,BufReader,Write},process::{Command,Stdio},sync::Arc,time::{Duration,Instant}}; +pub fn run() -> Result<(),String> { + if std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default().trim()!="uu-hyprland-test" { + return Err("Clipboard acceptance is restricted to the isolated VM".into()); + } + let session=Arc::new(crate::portal::PortalSession::open()?); + let bridge=crate::clipboard::start_portal(session.clone()); + if !bridge.ready.blocking_recv().unwrap_or(false) { return Err("Portal clipboard permission not granted".into()); } + let mut child=Command::new("python3").arg("/home/uuremote/clipboard-acceptance.py") + .env("GDK_BACKEND","wayland").env("GSK_RENDERER","cairo") + .stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::null()).spawn().map_err(|_|"Start GTK clipboard fixture")?; + let result=(|| { + let mut writer=child.stdin.take().ok_or("Clipboard fixture stdin missing")?; + let mut reader=BufReader::new(child.stdout.take().ok_or("Clipboard fixture stdout missing")?); + let mut line=String::new(); reader.read_line(&mut line).map_err(|_|"Clipboard fixture not ready")?; + let ready:serde_json::Value=serde_json::from_str(&line).map_err(|_|"Invalid clipboard fixture readiness")?; + if ready["ready"]!=true || ready["native_wayland"]!=true { return Err("Clipboard fixture is not native Wayland".into()); } + std::thread::sleep(Duration::from_secs(2)); + let mut outgoing=bridge.outgoing; + let mut check=|op:&str,text:&str|->Result { + writeln!(writer,"{}",serde_json::json!({"op":op,"text":text})).map_err(|_|"Clipboard fixture write failed")?; + writer.flush().map_err(|_|"Clipboard fixture write failed")?; + let mut line=String::new();reader.read_line(&mut line).map_err(|_|"Clipboard fixture read failed")?; + let result:serde_json::Value=serde_json::from_str(&line).map_err(|_|"Invalid clipboard fixture result")?; + Ok(result["ok"]==true) + }; + for (name,text) in [("unicode", "UU incoming 中文🙂\nsecond line".to_owned()),("empty",String::new()),("maximum_utf8","中".repeat(crate::clipboard::MAX_TEXT/3))] { + bridge.incoming.send_replace(Some(text.clone())); + let deadline=Instant::now()+Duration::from_secs(6);let mut matched=false; + while Instant::now(), +} +impl Assembly { + pub fn accept(&mut self, message: &[u8]) -> Result, &'static str> { + let result = self.decode(message); + if result.is_err() { self.pending = None; } + result + } + fn decode(&mut self, message: &[u8]) -> Result, &'static str> { + if message.len() > MAX_TEXT + 256 { return Err("clipboard message exceeds limit"); } + let fields = decode_wire(message).map_err(|_| "invalid clipboard wire")?; + let mut id = 0; + let mut text = ""; + let mut more = false; + let mut seen = [false; 3]; + for field in fields { + if !(1..=3).contains(&field.number) { continue; } + let index = field.number as usize - 1; + if seen[index] { return Err("duplicate clipboard field"); } + seen[index] = true; + match (field.number, field.value) { + (1, WireValue::Varint(value)) => id = u32::try_from(value).map_err(|_| "invalid clipboard content id")?, + (2, WireValue::Bytes(value)) => text = std::str::from_utf8(value).map_err(|_| "invalid clipboard UTF-8")?, + (3, WireValue::Varint(value @ 0..=1)) => more = value != 0, + _ => return Err("invalid clipboard field type"), + } + } + let now = Instant::now(); + let mut combined = match self.pending.take() { + Some((previous, text, started)) if previous == id && now.duration_since(started) < Duration::from_secs(5) => (text, started), + _ => (String::new(), now), + }; + if combined.0.len() + text.len() > MAX_TEXT { return Err("clipboard text exceeds limit"); } + combined.0.push_str(text); + if more { self.pending = Some((id, combined.0, combined.1)); Ok(None) } + else { Ok(Some(combined.0)) } + } +} + +pub(crate) fn varint(mut value: u64, out: &mut Vec) { + while value >= 128 { out.push(value as u8 & 127 | 128); value >>= 7; } + out.push(value as u8); +} +pub(crate) fn nested(field: u32, payload: &[u8], out: &mut Vec) { + varint(u64::from(field) << 3 | 2, out); + varint(payload.len() as u64, out); out.extend_from_slice(payload); +} +pub fn text_request(request_id: u64, text: &str) -> Vec { + let mut header=vec![8];varint(request_id,&mut header); + // Official ClipboardMobileManager uses format_id=1 for text. + let data=encode(1,text,false); + let mut request=Vec::new();nested(1,&header,&mut request);nested(10,&data,&mut request);request +} +pub fn read_text_request(request: &[u8]) -> Result,String)>, &'static str> { + if request.len()>MAX_TEXT+256 {return Err("clipboard RPC exceeds limit");} + let fields=decode_wire(request).map_err(|_|"invalid clipboard RPC")?; + let data=fields.iter().find(|f|f.number==10); + let Some(data)=data else {return Ok(None);}; + let header=fields.iter().find(|f|f.number==1).ok_or("missing clipboard RPC header")?; + let WireValue::Bytes(header)=header.value else {return Err("invalid clipboard RPC header");}; + if header.len()>32 {return Err("invalid clipboard RPC header length");} + let header_fields=decode_wire(header).map_err(|_|"invalid clipboard RPC request id")?; + if header_fields.iter().any(|f|f.number!=1 || !matches!(f.value,WireValue::Varint(_))) {return Err("invalid clipboard RPC request id");} + let WireValue::Bytes(data)=data.value else {return Err("invalid clipboard RPC text");}; + let parts=decode_wire(data).map_err(|_|"invalid clipboard RPC text")?; + if !parts.iter().any(|f|f.number==1 && f.value==WireValue::Varint(1)) || parts.iter().any(|f|f.number==1 && f.value!=WireValue::Varint(1)) {return Err("unsupported clipboard RPC format");} + let text=Assembly::default().accept(data)?.ok_or("incomplete clipboard RPC text")?; + Ok(Some((header.to_vec(),text))) +} +pub fn text_response(header: &[u8]) -> Vec { + let mut response=Vec::new();nested(1,header,&mut response); + nested(6,&[8,1],&mut response); // TextChangeResponse.err=CB_SUCCEEDED + response +} +pub fn encode(id: u32, text: &str, more: bool) -> Vec { + let mut out = vec![8]; varint(u64::from(id), &mut out); + out.push(18); varint(text.len() as u64, &mut out); out.extend_from_slice(text.as_bytes()); + if more { out.extend_from_slice(&[24, 1]); } + out +} + +pub fn chunks(text: &str) -> Result, &'static str> { + if text.len() > MAX_TEXT { return Err("clipboard text exceeds limit"); } + if text.is_empty() { return Ok(vec![""]); } + let mut chunks = Vec::new(); + let mut remaining = text; + while !remaining.is_empty() { + let mut end = remaining.len().min(8192); + while !remaining.is_char_boundary(end) { end -= 1; } + chunks.push(&remaining[..end]); remaining = &remaining[end..]; + } + Ok(chunks) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn rpc_text_roundtrip_preserves_request_id_and_returns_official_success() { + let text="UU-test-中文🙂\n"; + let request=text_request(0x12345678,text); + let (header,received)=read_text_request(&request).unwrap().unwrap(); + assert_eq!(received,text); + assert_eq!(header,vec![8,0xf8,0xac,0xd1,0x91,1]); + let response=text_response(&header); + assert_eq!(&response[response.len()-4..],&[50,2,8,1]); + assert_eq!(&response[2..2+header.len()],header.as_slice()); + assert!(read_text_request(&[10,1,255,82,0]).is_err()); + assert!(read_text_request(&[10,0,82,2,8,2]).is_err()); + assert!(read_text_request(&[10,0,74,0]).unwrap().is_none()); + } + #[test] + fn unicode_chunk_roundtrip_and_empty_copy() { + let text = "中文🙂\n".repeat(1600); + let parts = chunks(&text).unwrap(); assert!(parts.len() > 1); + let mut assembly = Assembly::default(); + for (i, part) in parts.iter().enumerate() { + let result = assembly.accept(&encode(u32::MAX, part, i + 1 < parts.len())).unwrap(); + if i + 1 == parts.len() { assert_eq!(result.as_deref(), Some(text.as_str())); } + else { assert!(result.is_none()); } + } + assert_eq!(assembly.accept(&encode(0,"",false)).unwrap(),Some(String::new())); + } + #[test] + fn resets_for_new_id_and_rejects_malformed_and_oversized_text() { + let mut assembly = Assembly::default(); + assembly.accept(&encode(1,"stale",true)).unwrap(); + assert_eq!(assembly.accept(&encode(2,"new",false)).unwrap(),Some("new".into())); + assert!(assembly.accept(&[18,1,255]).is_err()); + assert!(assembly.accept(&[8,1,8,2]).is_err()); + assert!(assembly.accept(&[24,2]).is_err()); + assert!(chunks(&"a".repeat(MAX_TEXT+1)).is_err()); + assembly.accept(&encode(1,&"a".repeat(MAX_TEXT),true)).unwrap(); + assert!(assembly.accept(&encode(1,"b",false)).is_err()); + assert_eq!(assembly.accept(&encode(1,"fresh",false)).unwrap(),Some("fresh".into())); + } +} diff --git a/src/clipboard_rich.rs b/src/clipboard_rich.rs new file mode 100644 index 0000000..087c362 --- /dev/null +++ b/src/clipboard_rich.rs @@ -0,0 +1,186 @@ +//! Text-only desktop clipboard format negotiation. No file formats are offered. +use crate::clipboard::MAX_TEXT; +use crate::clipboard_protocol::{nested,varint}; +use crate::protocol::{decode_wire,WireValue}; +use std::collections::BTreeMap; + +const UNICODE_TEXT:u64=13; +const BLOCK_BYTES:usize=0x20000; +const MAX_BYTES:usize=MAX_TEXT*2+2; +pub struct ResultMessages {pub messages:Vec<(u32,Vec)>,pub text:Option} +impl Default for ResultMessages {fn default()->Self{Self{messages:Vec::new(),text:None}}} +struct Pending {key:String, count:Option, blocks:BTreeMap>} +#[derive(Default)] +pub struct State {local:Option, pending:Option} +pub fn format_ids(rpc:&[u8])->Vec{ + let Ok(Some(clip))=bytes(rpc,9) else{return Vec::new();}; + let Ok(Some(list))=bytes(clip,1) else{return Vec::new();}; + let Ok(fields)=decode_wire(list) else{return Vec::new();}; + fields.iter().filter(|f|f.number==1).filter_map(|f|match f.value{WireValue::Bytes(format)=>number(format,1).ok(),_=>None}).take(32).collect() +} + +fn int(field:u32,value:u64,out:&mut Vec){varint(u64::from(field)<<3,out);varint(value,out);} +fn string(field:u32,value:&str,out:&mut Vec){nested(field,value.as_bytes(),out);} +fn number(data:&[u8],field:u32)->Result{ + let fields=decode_wire(data).map_err(|_|"invalid clipboard message")?; + match fields.iter().find(|f|f.number==field).map(|f|&f.value){ + Some(WireValue::Varint(v))=>Ok(*v),None=>Ok(0),_=>Err("invalid clipboard integer"), + } +} +fn bytes(data:&[u8],field:u32)->Result,&'static str>{ + let fields=decode_wire(data).map_err(|_|"invalid clipboard message")?; + match fields.iter().find(|f|f.number==field).map(|f|&f.value){ + Some(WireValue::Bytes(v))=>Ok(Some(*v)),None=>Ok(None),_=>Err("invalid clipboard bytes"), + } +} +fn text_field(data:&[u8],field:u32)->Result<&str,&'static str>{ + std::str::from_utf8(bytes(data,field)?.unwrap_or(&[])).map_err(|_|"invalid clipboard string") +} +fn header(data:&[u8])->Result<&[u8],&'static str>{ + let h=bytes(data,1)?.ok_or("missing clipboard request header")?; + if h.len()>32{return Err("clipboard header exceeds limit");} + number(h,1)?;Ok(h) +} +fn request(id:u64,kind:u32,body:&[u8])->Vec{ + let mut h=Vec::new();int(1,id,&mut h); + let mut clip=Vec::new();nested(kind,body,&mut clip); + let mut rpc=Vec::new();nested(1,&h,&mut rpc);nested(9,&clip,&mut rpc);rpc +} +fn response(h:&[u8],kind:u32,body:&[u8])->Vec{ + let mut clip=Vec::new();nested(kind,body,&mut clip); + let mut rpc=Vec::new();nested(1,h,&mut rpc);nested(5,&clip,&mut rpc);rpc +} +fn encode_windows(text:&str)->Vec{ + text.replace("\r\n","\n").replace('\n',"\r\n").encode_utf16().chain(std::iter::once(0)).flat_map(u16::to_le_bytes).collect() +} +fn decode_windows(data:&[u8])->Result{ + if data.len()>MAX_BYTES||data.len()%2!=0{return Err("invalid Unicode clipboard length");} + let mut chars:Vec=data.chunks_exact(2).map(|v|u16::from_le_bytes([v[0],v[1]])).collect(); + if chars.last()==Some(&0){chars.pop();} + if chars.contains(&0){return Err("embedded NUL in clipboard text");} + let text=String::from_utf16(&chars).map_err(|_|"invalid Unicode clipboard text")?.replace("\r\n","\n"); + if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");}Ok(text) +} +impl State{ + pub fn offer(&mut self,id:u64,text:String)->Result,&'static str>{ + if text.len()>MAX_TEXT{return Err("clipboard text exceeds limit");} + if text.contains('\0')||encode_windows(&text).len()>MAX_BYTES{return Err("clipboard encoded text exceeds limit");} + self.local=Some(text); + let mut format=Vec::new();int(1,UNICODE_TEXT,&mut format);string(2,"CF_UNICODETEXT",&mut format); + let mut list=Vec::new();nested(1,&format,&mut list); + Ok(request(id,1,&list)) + } + pub fn request(&mut self,rpc:&[u8],next:&mut impl FnMut()->u64)->Result{ + if rpc.len()>MAX_BYTES+512{return Err("clipboard RPC exceeds limit");} + let Some(clip)=bytes(rpc,9)? else{return Ok(ResultMessages::default());}; + let h=header(rpc)?; + let mut out=ResultMessages::default(); + if let Some(list)=bytes(clip,1)?{ + out.messages.push((22,response(h,1,&[]))); + let fields=decode_wire(list).map_err(|_|"invalid clipboard format list")?; + let supports_text=fields.iter().filter(|f|f.number==1).any(|f|match f.value{WireValue::Bytes(format)=>number(format,1)==Ok(UNICODE_TEXT),_=>false}); + self.pending=None; + if supports_text{ + let id=next(); + let epoch=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() as u32; + let key=format!("{epoch:08x}-0000-4000-8000-{:012x}",id & 0xffffffffffff); + let mut ask=Vec::new();int(1,UNICODE_TEXT,&mut ask);string(2,&key,&mut ask);string(3,"CF_UNICODETEXT",&mut ask); + self.pending=Some(Pending{key,count:None,blocks:BTreeMap::new()}); + out.messages.push((21,request(id,2,&ask))); + } + }else if let Some(ask)=bytes(clip,2)?{ + let key=text_field(ask,2)?; + if key.len()>256||key.is_empty(){return Err("invalid clipboard block key");} + let available=number(ask,1)?==UNICODE_TEXT&&self.local.is_some(); + let mut confirm=Vec::new();int(1,if available{1}else{2},&mut confirm);string(2,key,&mut confirm); + let data=if available{Some(encode_windows(self.local.as_ref().unwrap()))}else{None}; + if let Some(data)=&data{int(3,data.chunks(BLOCK_BYTES).len() as u64,&mut confirm);} + out.messages.push((22,response(h,2,&confirm))); + if let Some(data)=data{ + for (index,part) in data.chunks(BLOCK_BYTES).enumerate(){ + let mut block=Vec::new();string(1,key,&mut block);int(2,index as u64,&mut block);nested(3,part,&mut block); + out.messages.push((21,request(next(),3,&block))); + } + } + }else if let Some(block)=bytes(clip,3)?{ + let key=text_field(block,1)?; + let index=usize::try_from(number(block,2)?).map_err(|_|"invalid clipboard block index")?; + let data=bytes(block,3)?.unwrap_or(&[]); + log::info!("Clipboard incoming block metadata: index={} bytes={}",index,data.len()); + if index>MAX_BYTES/BLOCK_BYTES+1||data.len()>MAX_BYTES{return Err("clipboard block exceeds limit");} + let pending=self.pending.as_mut().ok_or("unsolicited clipboard block")?; + if key!=pending.key{return Err("unexpected clipboard block key");} + if let Some(existing)=pending.blocks.get(&index){ + if existing!=data{return Err("conflicting clipboard block");} + }else{ + if pending.blocks.values().map(Vec::len).sum::()+data.len()>MAX_BYTES{return Err("clipboard transfer exceeds limit");} + pending.blocks.insert(index,data.to_vec()); + } + let mut confirm=Vec::new();string(1,key,&mut confirm);int(2,index as u64,&mut confirm);int(3,1,&mut confirm); + out.messages.push((22,response(h,3,&confirm))); + out.text=self.complete()?; + } + Ok(out) + } + pub fn response(&mut self,rpc:&[u8])->Result,&'static str>{ + let Some(clip)=bytes(rpc,5)? else{return Ok(None);}; + let Some(confirm)=bytes(clip,2)? else{return Ok(None);}; + let Some(pending)=self.pending.as_mut() else{return Ok(None);}; + if text_field(confirm,2)?!=pending.key{return Ok(None);} + let status=number(confirm,1)?; + log::info!("Clipboard data confirmation metadata: status={} block_count={}",status,number(confirm,3)?); + if status!=1{self.pending=None;return Ok(None);} + let count=usize::try_from(number(confirm,3)?).map_err(|_|"invalid clipboard block count")?; + if count==0||count>MAX_BYTES/BLOCK_BYTES+2{self.pending=None;return Err("invalid clipboard block count");} + pending.count=Some(count);self.complete() + } + fn complete(&mut self)->Result,&'static str>{ + let Some(pending)=&self.pending else{return Ok(None);}; + let Some(count)=pending.count else{return Ok(None);}; + // Native providers may number wire blocks from one while their internal + // buffer slicing uses a zero-based index. Accept a complete contiguous + // set in either convention; never complete from a missing middle block. + let first=if (0..count).all(|i|pending.blocks.contains_key(&i)){0} + else if (1..=count).all(|i|pending.blocks.contains_key(&i)){1} + else{return Ok(None);}; + let data:Vec=(first..first+count).flat_map(|i|pending.blocks[&i].iter().copied()).collect(); + self.pending=None;decode_windows(&data).map(Some) + } +} + +#[cfg(test)] +mod tests{ + use super::*; + #[test] + fn desktop_clipboard_negotiates_and_buffers_unicode_until_confirmation(){ + let text="UU-test-中文🙂\n".repeat(900); + let mut provider=State::default();let mut receiver=State::default();let mut id=10;let mut next=||{id+=1;id}; + let offer=provider.offer(1,text.clone()).unwrap(); + let result=receiver.request(&offer,&mut next).unwrap();assert_eq!(result.messages.len(),2); + let send=provider.request(&result.messages[1].1,&mut next).unwrap();assert_eq!(send.messages.len(),2); + // Blocks may arrive before DataConfirm; completion waits for both. + for (_,block) in send.messages.iter().skip(1).rev(){assert!(receiver.request(block,&mut next).unwrap().text.is_none());} + assert_eq!(receiver.response(&send.messages[0].1).unwrap(),Some(text)); + } + #[test] + fn rejects_invalid_unicode_unsolicited_blocks_and_unknown_formats(){ + assert!(decode_windows(&[0,0xd8,0,0]).is_err()); + assert!(decode_windows(&[1]).is_err()); + let mut s=State::default();let mut block=Vec::new();string(1,"unknown",&mut block);nested(3,&[0,0],&mut block); + assert!(s.request(&request(1,3,&block),&mut||2).is_err()); + let mut format=Vec::new();int(1,15,&mut format);let mut list=Vec::new();nested(1,&format,&mut list); + let out=s.request(&request(1,1,&list),&mut||2).unwrap();assert_eq!(out.messages.len(),1);assert!(s.pending.is_none()); + } + #[test] + fn accepts_one_based_wire_blocks_without_breaking_zero_based_provider(){ + let mut source=State::default();let mut target=State::default();let mut id=10;let mut next=||{id+=1;id}; + let offer=source.offer(1,"中文🙂".into()).unwrap(); + let offered=target.request(&offer,&mut next).unwrap(); + let sent=source.request(&offered.messages[1].1,&mut next).unwrap(); + assert!(target.response(&sent.messages[0].1).unwrap().is_none()); + let clip=bytes(&sent.messages[1].1,9).unwrap().unwrap(); + let original=bytes(clip,3).unwrap().unwrap(); + let mut block=Vec::new();string(1,text_field(original,1).unwrap(),&mut block);int(2,1,&mut block);nested(3,bytes(original,3).unwrap().unwrap(),&mut block); + assert_eq!(target.request(&request(99,3,&block),&mut next).unwrap().text,Some("中文🙂".into())); + } +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..82d3db4 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,43 @@ +//! Runtime configuration. Nothing machine- or account-specific is compiled in. +//! File: $UU_CONFIG, else $XDG_CONFIG_HOME/uuremote/config.json, else ~/.config/uuremote/config.json. +//! Environment variables override file values. Keep the file private (chmod 600). + +use std::path::PathBuf; +use std::sync::OnceLock; + +pub fn path() -> PathBuf { + if let Some(p) = std::env::var_os("UU_CONFIG") { return PathBuf::from(p); } + let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) + .unwrap_or_else(|| PathBuf::from(".")); + base.join("uuremote/config.json") +} + +/// Re-reads the config file (used after `login` rewrites it while the server runs). +pub fn read_fresh() -> Result, String> { + let p = path(); + match std::fs::read(&p) { + Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| format!("invalid config {}: {e}", p.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("cannot read config {}: {e}", p.display())), + } +} + +/// Parsed config file, or None when absent. A malformed file is an error, not silently ignored. +pub fn file() -> Result, String> { + static FILE: OnceLock, String>> = OnceLock::new(); + FILE.get_or_init(|| { + let p = path(); + match std::fs::read(&p) { + Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| format!("invalid config {}: {e}", p.display())), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(e) => Err(format!("cannot read config {}: {e}", p.display())), + } + }).as_ref().map(|v| v.as_ref()).map_err(Clone::clone) +} + +/// Optional bundled FFmpeg prefix: UU_FFMPEG_ROOT or config "ffmpeg_root". +pub fn ffmpeg_root() -> Option { + std::env::var_os("UU_FFMPEG_ROOT").filter(|v| !v.is_empty()).map(PathBuf::from) + .or_else(|| file().ok().flatten().and_then(|f| f.get("ffmpeg_root")).and_then(|v| v.as_str()).map(PathBuf::from)) +} diff --git a/src/control_protocol.rs b/src/control_protocol.rs new file mode 100644 index 0000000..9b2acfc --- /dev/null +++ b/src/control_protocol.rs @@ -0,0 +1,207 @@ +//! Mac UU CONTROL JSON messages recovered from the shipped ARM64 client. +//! Wire parsing accepts UTF-8 JSON carried by binary SCTP messages as well as text. +//! Coordinates and key/button identifiers remain wire values; Linux translation +//! belongs to the input engine. Only the verified protobuf echo-response shape +//! is encoded; other protobuf messages remain opaque. + +use serde_json::Value; + +#[derive(Debug, Clone, PartialEq)] +pub enum ControlInput { + Keyboard { key: i32, pressed: bool }, + KeyboardClick { key: i32 }, + MouseButton { button: i32, pressed: bool }, + MouseClick { button: i32 }, + MouseAbsolute { x: f64, y: f64 }, + MouseRelative { dx: i32, dy: i32 }, + MouseScroll { dx: i32, dy: i32 }, +} + +#[derive(Debug, Clone, PartialEq)] +pub enum ControlMessage { + KeyboardHeartbeat, + Input(ControlInput), + Unsupported(Value), +} + +fn integer(v: &Value, name: &str) -> Result { + v.get(name) + .and_then(Value::as_i64) + .and_then(|n| i32::try_from(n).ok()) + .ok_or_else(|| format!("CONTROL field {name} must be an i32 integer")) +} + +fn coordinate(v: &Value, name: &str) -> Result { + v.get(name).and_then(Value::as_f64).filter(|n| n.is_finite()) + .ok_or_else(|| format!("CONTROL field {name} must be a finite number")) +} + +pub fn decode_control(data: &[u8]) -> Result { + let v: Value = serde_json::from_slice(data) + .map_err(|_| "CONTROL payload is not valid JSON".to_owned())?; + if v.get("heartbeat").and_then(Value::as_str) == Some("kbd_heartbeat") { + return Ok(ControlMessage::KeyboardHeartbeat); + } + let Some(action) = v.get("action").and_then(Value::as_str) else { + return Ok(ControlMessage::Unsupported(v)); + }; + let event = match action { + "kbd_press" => ControlInput::Keyboard { key: integer(&v, "key")?, pressed: true }, + "kbd_release" => ControlInput::Keyboard { key: integer(&v, "key")?, pressed: false }, + "kbd_click" => ControlInput::KeyboardClick { key: integer(&v, "key")? }, + "mouse_press" => ControlInput::MouseButton { button: integer(&v, "button")?, pressed: true }, + "mouse_release" => ControlInput::MouseButton { button: integer(&v, "button")?, pressed: false }, + "mouse_click" => ControlInput::MouseClick { button: integer(&v, "button")? }, + "mouse_move_absolute" => ControlInput::MouseAbsolute { + x: coordinate(&v, "abs_x")?, y: coordinate(&v, "abs_y")?, + }, + "mouse_move_relative" => ControlInput::MouseRelative { + dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?, + }, + "mouse_scroll" => ControlInput::MouseScroll { + dx: integer(&v, "delta_x")?, dy: integer(&v, "delta_y")?, + }, + _ => return Ok(ControlMessage::Unsupported(v)), + }; + Ok(ControlMessage::Input(event)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn recognizes_binary_carried_keyboard_heartbeat() { + let bytes = br#"{"heartbeat":"kbd_heartbeat"}"#; + assert_eq!(bytes.len(), 29); + assert_eq!(decode_control(bytes).unwrap(), ControlMessage::KeyboardHeartbeat); + } + + #[test] + fn decodes_mac_absolute_and_relative_wire_keys() { + assert_eq!(decode_control(br#"{"action":"mouse_move_absolute","abs_x":12,"abs_y":34}"#).unwrap(), + ControlMessage::Input(ControlInput::MouseAbsolute { x: 12.0, y: 34.0 })); + assert_eq!(decode_control(br#"{"action":"mouse_move_relative","delta_x":-4,"delta_y":5}"#).unwrap(), + ControlMessage::Input(ControlInput::MouseRelative { dx: -4, dy: 5 })); + } + + #[test] + fn preserves_wire_key_and_button_identifiers() { + assert_eq!(decode_control(br#"{"action":"kbd_release","key":65}"#).unwrap(), + ControlMessage::Input(ControlInput::Keyboard { key: 65, pressed: false })); + assert_eq!(decode_control(br#"{"action":"mouse_press","button":2}"#).unwrap(), + ControlMessage::Input(ControlInput::MouseButton { button: 2, pressed: true })); + } + + #[test] + fn rejects_missing_or_unrepresentable_input_fields() { + assert!(decode_control(br#"{"action":"kbd_press"}"#).is_err()); + assert!(decode_control(br#"{"action":"kbd_press","key":2147483648}"#).is_err()); + assert!(decode_control(br#"{"action":"kbd_press","key":1.5}"#).is_err()); + assert!(decode_control(&[0xff, 0x08]).is_err()); + } + + #[test] + fn encodes_echo_response_without_advertising_unverified_features() { + let reply = encode_echo_response_for(1, 2, 200); + assert_eq!(&reply[..4], &[8, 1, 16, 2]); + assert!(reply.windows(11).any(|b| b == br#"{"seq":200}"#)); + assert!(reply.ends_with(&[34, 8, 8, 4, 16, 2, 24, 2, 48, 2])); + assert!(reply.windows(2).any(|b| b == [8, 1])); + } + + #[test] + fn advertises_verified_text_rpc_clipboard_when_backend_ready() { + use crate::protocol::{decode_wire,WireValue}; + let response = encode_echo_response_with_clipboard(1,2,200,true); + let outer=decode_wire(&response).unwrap(); + let action=outer.iter().find(|f|f.number==3).unwrap(); + let WireValue::Bytes(action)=action.value else {panic!("action type")}; + let fields=decode_wire(action).unwrap(); + let flag=fields.iter().find(|f|f.number==4).unwrap(); + let WireValue::Bytes(flag)=flag.value else {panic!("flag type")}; + let features=decode_wire(flag).unwrap(); + let numbers:Vec<(u32,u64)>=features.iter().map(|f|match f.value {WireValue::Varint(v)=>(f.number,v),_=>panic!("flag type")}).collect(); + assert_eq!(numbers,vec![(1,4),(2,2),(3,2),(6,2),(8,3)]); + } + + #[test] + fn names_only_official_simple_action_values() { + assert_eq!(simple_action_name(4), Some("capture_desktop")); + assert_eq!(simple_action_name(22), Some("acquire_system_info")); + assert_eq!(simple_action_name(27), Some("need_restart_userapp")); + assert_eq!(simple_action_name(28), None); + assert_eq!(simple_action_name(u64::MAX), None); + } + + #[test] + fn does_not_invent_actions_for_unknown_json() { + assert!(matches!(decode_control(br#"{"action":"unverified"}"#).unwrap(), ControlMessage::Unsupported(_))); + } +} + +/// Generate the verified protobuf SimpleAction echoResponse envelope. +/// The caller chooses sequence/timestamp policy; no peer feature flags are copied. +pub fn encode_echo_response(seq: u64, timestamp: u64) -> Vec { + encode_echo_response_for(seq, timestamp, seq) +} + +/// Correlate the response using the official args JSON request-sequence field. +/// An explicit empty FeatureFlag advertises no unimplemented feature versions. +pub fn encode_echo_response_for(seq: u64, timestamp: u64, request_seq: u64) -> Vec { + encode_echo_response_with_clipboard(seq, timestamp, request_seq, false) +} + +/// Advertise only the verified legacy text bridge when the native backend is ready. +/// FeatureFlag.ff_clipboard field 8: SUPPORT_TEXT_CHANGE=3; no file-transfer claim. +pub fn encode_echo_response_with_clipboard(seq: u64, timestamp: u64, request_seq: u64, clipboard: bool) -> Vec { + fn put_varint(mut v: u64, out: &mut Vec) { + while v >= 128 { + out.push((v as u8 & 127) | 128); + v >>= 7; + } + out.push(v as u8); + } + let args = format!(r#"{{"seq":{request_seq}}}"#); + let mut action = vec![8, 1, 18]; + put_varint(args.len() as u64, &mut action); + action.extend_from_slice(args.as_bytes()); + // FeatureFlag: 1 ff_capture_setting = CUSTOM_BITRATE (fps/quality/bitrate RPCs), + // 2 ff_simple_action = AUTO_LOCK (mute + lock after session), 3 ff_system_metrics = SETTING_AUTO_LOCK, + // 6 ff_file_transfer_ftp = LIST_COMPRESS (zlib dir_data), 8 ff_clipboard = SUPPORT_TEXT_CHANGE. + let mut flags = vec![8, crate::capture_setting::FEATURE_VERSION as u8, + 16, crate::system_actions::FF_SIMPLE_ACTION, 24, crate::system_actions::FF_SYSTEM_METRICS, 48, 2]; + if clipboard { flags.extend_from_slice(&[64, 3]); } + action.push(34); + action.push(flags.len() as u8); + action.extend_from_slice(&flags); + let mut out = Vec::new(); + if seq != 0 { + out.push(8); + put_varint(seq, &mut out); + } + if timestamp != 0 { + out.push(16); + put_varint(timestamp, &mut out); + } + out.push(26); // Message.simpleAction + put_varint(action.len() as u64, &mut out); + out.extend_from_slice(&action); + out +} + +/// Official ActionType map recovered from _ProtoNameProviding's 28-entry table. +/// This describes messages; it does not authorize or execute system actions. +pub fn simple_action_name(action: u64) -> Option<&'static str> { + const NAMES: [&str; 28] = [ + "echo_request", "echo_response", "show_desktop", "show_windows", + "capture_desktop", "capture_window", "capture_mumu", "stop_capture", + "restart_capture", "reboot_system", "lock_system", "key_toggle", + "shutdown_system", "show_taskmgr", "mute_system", "auto_unlock_system", + "mute_restore", "mute_permanent", "mute_temporary", "set_auto_lock", + "stop_acquire_update", "quit_capture", "acquire_system_info", + "microphone_opened", "microphone_closed", "speaker_opened", + "speaker_closed", "need_restart_userapp", + ]; + usize::try_from(action).ok().and_then(|n| NAMES.get(n).copied()) +} diff --git a/src/cursor.rs b/src/cursor.rs new file mode 100644 index 0000000..01b5402 --- /dev/null +++ b/src/cursor.rs @@ -0,0 +1,189 @@ +//! Pointer shape mirroring. The video no longer contains the pointer (x11grab +//! -draw_mouse 0), so the viewer draws its local pointer; this tells it which shape. +//! Wire layout recovered from the official Mac host sendCursorShape (UURemoteServer +//! arm64 0x1000065ac..0x100006d3c): Message.which=15 SystemStateChange, field 2 +//! CursorShape { 1 pos_x, 2 pos_y = hotspot, 3 width, 4 height, 5 byte_value = PNG +//! (representationUsingType 4), 6 cursor_type = 0 with image, 7/8 coordinate x/y +//! scale = video pixels per screen point (double), 9 screen_id }. + +use std::sync::{Arc, OnceLock}; +use tokio::sync::watch; + +#[cfg(target_os = "linux")] +extern "C" { + fn x11_cursor_open(display_name: *const libc::c_char) -> libc::c_int; + fn x11_cursor_wait(timeout_ms: libc::c_int) -> libc::c_int; + fn x11_cursor_poll(pixels: *mut u32, max_pixels: libc::c_int, width: *mut libc::c_int, height: *mut libc::c_int, + hot_x: *mut libc::c_int, hot_y: *mut libc::c_int, force: libc::c_int) -> libc::c_int; +} + +#[cfg(target_os = "linux")] +const MAX_EDGE: usize = 256; +/// Upper bound between checks; cursor-change events wake the monitor immediately. +#[cfg(target_os = "linux")] +const WAIT_MS: libc::c_int = 250; + +#[derive(Debug, PartialEq)] +pub struct CursorImage { pub width: u32, pub height: u32, pub hot_x: i32, pub hot_y: i32, pub png: Vec } + +/// XFixes delivers premultiplied ARGB32; PNG needs straight-alpha RGBA. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn argb_premultiplied_to_rgba(pixels: &[u32]) -> Vec { + let mut rgba = Vec::with_capacity(pixels.len() * 4); + for &pixel in pixels { + let a = pixel >> 24; + let straight = |shift: u32| -> u8 { + let c = (pixel >> shift) & 0xff; + if a == 0 { 0 } else { ((c * 255 + a / 2) / a).min(255) as u8 } + }; + rgba.extend_from_slice(&[straight(16), straight(8), straight(0), a as u8]); + } + rgba +} + +/// Minimal 8-bit RGBA PNG (filter 0) using the existing flate2 dependency. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +pub(crate) fn encode_png(width: u32, height: u32, rgba: &[u8]) -> Vec { + use std::io::Write; + fn chunk(out: &mut Vec, kind: &[u8; 4], data: &[u8]) { + out.extend_from_slice(&(data.len() as u32).to_be_bytes()); + let mut crc = flate2::Crc::new(); + crc.update(kind); + crc.update(data); + out.extend_from_slice(kind); + out.extend_from_slice(data); + out.extend_from_slice(&crc.sum().to_be_bytes()); + } + let mut header = Vec::with_capacity(13); + header.extend_from_slice(&width.to_be_bytes()); + header.extend_from_slice(&height.to_be_bytes()); + header.extend_from_slice(&[8, 6, 0, 0, 0]); // 8-bit, RGBA, deflate, filter 0, no interlace + let mut scanlines = Vec::with_capacity(rgba.len() + height as usize); + for row in rgba.chunks(width as usize * 4) { + scanlines.push(0); + scanlines.extend_from_slice(row); + } + let mut encoder = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + encoder.write_all(&scanlines).expect("in-memory zlib"); + let compressed = encoder.finish().expect("in-memory zlib"); + let mut png = b"\x89PNG\r\n\x1a\n".to_vec(); + chunk(&mut png, b"IHDR", &header); + chunk(&mut png, b"IDAT", &compressed); + chunk(&mut png, b"IEND", &[]); + png +} + +fn varint(mut value: u64, out: &mut Vec) { + while value >= 128 { out.push((value as u8 & 127) | 128); value >>= 7; } + out.push(value as u8); +} + +/// Message.which=15 SystemStateChange { 2: CursorShape } for an unscaled source screen 0. +pub fn encode_cursor_shape(seq: u64, timestamp: u64, cursor: &CursorImage) -> Vec { + let mut shape = Vec::new(); + for (field, value) in [(1, cursor.hot_x), (2, cursor.hot_y), (3, cursor.width as i32), (4, cursor.height as i32)] { + if value != 0 { varint(field << 3, &mut shape); varint(value as i64 as u64, &mut shape); } + } + varint(5 << 3 | 2, &mut shape); + varint(cursor.png.len() as u64, &mut shape); + shape.extend_from_slice(&cursor.png); + // cursor_type 0 (image present) and screen_id 0 are protobuf defaults and omitted. + for field in [7u64, 8] { + varint(field << 3 | 1, &mut shape); + shape.extend_from_slice(&1.0f64.to_le_bytes()); + } + let mut change = Vec::new(); + varint(2 << 3 | 2, &mut change); + varint(shape.len() as u64, &mut change); + change.extend_from_slice(&shape); + crate::initialization::envelope(seq, timestamp, 15, &change) +} + +/// One process-wide monitor thread; every session subscribes to the latest shape. +pub fn monitor(display: &str) -> watch::Receiver>> { + if display.starts_with("wayland:") { + // XFixes cannot observe native Wayland cursors; no false XWayland monitor. + let (_,receiver)=watch::channel(None); return receiver; + } + static LATEST: OnceLock>>> = OnceLock::new(); + LATEST.get_or_init(|| { + let (tx, _) = watch::channel(None); + start_thread(display.to_owned(), tx.clone()); + tx + }).subscribe() +} + +#[cfg(target_os = "linux")] +fn start_thread(display: String, tx: watch::Sender>>) { + let spawned = std::thread::Builder::new().name("cursor-shape".into()).spawn(move || { + let Ok(name) = std::ffi::CString::new(display) else { return }; + let opened = unsafe { x11_cursor_open(name.as_ptr()) }; + if opened != 0 { log::warn!("Cursor shape monitor unavailable: {}", opened); return; } + let mut pixels = vec![0u32; MAX_EDGE * MAX_EDGE]; + let mut force = 1; + loop { + let (mut w, mut h, mut x, mut y) = (0, 0, 0, 0); + let result = unsafe { x11_cursor_poll(pixels.as_mut_ptr(), pixels.len() as i32, &mut w, &mut h, &mut x, &mut y, force) }; + if result == 1 { + let (width, height) = (w as u32, h as u32); + let rgba = argb_premultiplied_to_rgba(&pixels[..(width * height) as usize]); + tx.send_replace(Some(Arc::new(CursorImage { width, height, hot_x: x, hot_y: y, png: encode_png(width, height, &rgba) }))); + force = 0; + } else if result < 0 { + log::warn!("Cursor shape poll failed: {}", result); + std::thread::sleep(std::time::Duration::from_secs(1)); + } + unsafe { x11_cursor_wait(WAIT_MS) }; + } + }); + if let Err(e) = spawned { log::warn!("Cursor shape thread failed: {}", e); } +} + +#[cfg(not(target_os = "linux"))] +fn start_thread(_: String, _: watch::Sender>>) {} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn unpremultiplies_alpha_for_png() { + // Opaque white, half-transparent premultiplied red (0x80,0x80,0,0), fully transparent. + assert_eq!(argb_premultiplied_to_rgba(&[0xffffffff, 0x80800000, 0x00000000]), + vec![255,255,255,255, 255,0,0,128, 0,0,0,0]); + } + #[test] + fn png_has_valid_structure_and_decodes_back() { + let rgba: Vec = (0..2*3*4).map(|i| i as u8 * 10).collect(); + let png = encode_png(2, 3, &rgba); + assert!(png.starts_with(b"\x89PNG\r\n\x1a\n")); + assert_eq!(&png[12..16], b"IHDR"); + assert_eq!(u32::from_be_bytes(png[16..20].try_into().unwrap()), 2); + assert_eq!(u32::from_be_bytes(png[20..24].try_into().unwrap()), 3); + assert!(png.ends_with(&[0,0,0,0, b'I',b'E',b'N',b'D', 0xae,0x42,0x60,0x82])); + // IDAT inflates to filtered scanlines: each row = filter byte 0 + 8 pixels bytes. + let idat_len = u32::from_be_bytes(png[33..37].try_into().unwrap()) as usize; + assert_eq!(&png[37..41], b"IDAT"); + let mut raw = Vec::new(); + std::io::Read::read_to_end(&mut flate2::read::ZlibDecoder::new(&png[41..41+idat_len]), &mut raw).unwrap(); + assert_eq!(raw.len(), 3 * (1 + 8)); + assert_eq!(&raw[1..9], &rgba[0..8]); + assert_eq!(raw[9], 0); + } + #[test] + fn cursor_shape_matches_official_field_layout() { + let cursor = CursorImage { width: 24, height: 24, hot_x: 4, hot_y: 2, png: vec![1, 2, 3] }; + let message = encode_cursor_shape(7, 9, &cursor); + // Message: seq 7, timestamp 9, field 15 (tag 0x7a) SystemStateChange. + assert_eq!(&message[..4], &[8, 7, 16, 9]); + assert_eq!(message[4], 0x7a); + let change = &message[6..]; + assert_eq!(change[0], 0x12); // SystemStateChange.field2 cursor_shape + let shape = &change[2..]; + assert_eq!(&shape[..8], &[8, 4, 16, 2, 24, 24, 32, 24]); // hotspot, width, height + assert_eq!(&shape[8..13], &[0x2a, 3, 1, 2, 3]); // byte_value PNG + assert_eq!(shape[13], 0x39); // field 7 double + assert_eq!(&shape[14..22], &1.0f64.to_le_bytes()); + assert_eq!(shape[22], 0x41); // field 8 double + assert_eq!(shape.len(), 31); + } +} diff --git a/src/desktop_backend.rs b/src/desktop_backend.rs new file mode 100644 index 0000000..7f387f6 --- /dev/null +++ b/src/desktop_backend.rs @@ -0,0 +1,39 @@ +//! Select the host desktop, not the presence of an XWayland DISPLAY socket. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DesktopBackend { X11, Wayland, Portal } + +pub fn detect() -> Result { + let backend=select(std::env::var("UU_DESKTOP_BACKEND").ok().as_deref(), + std::env::var("XDG_SESSION_TYPE").ok().as_deref(), + std::env::var("WAYLAND_DISPLAY").ok().as_deref())?; + let explicit=std::env::var("UU_DESKTOP_BACKEND").unwrap_or_else(|_|"auto".into()); + let desktop=std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default(); + Ok(if explicit=="auto" && backend==DesktopBackend::Wayland && desktop.split(':').any(|s|s.eq_ignore_ascii_case("gnome")||s.eq_ignore_ascii_case("kde")) { DesktopBackend::Portal } else { backend }) +} + +fn select(explicit: Option<&str>, session: Option<&str>, socket: Option<&str>) -> Result { + match explicit { + Some("x11") => Ok(DesktopBackend::X11), + Some("wayland") => Ok(DesktopBackend::Wayland), + Some("portal") => Ok(DesktopBackend::Portal), + None | Some("auto") => { + if session == Some("wayland") || socket.is_some_and(|s| !s.is_empty()) { + Ok(DesktopBackend::Wayland) + } else { Ok(DesktopBackend::X11) } + }, + Some(_) => Err("UU_DESKTOP_BACKEND must be auto, x11, wayland or portal".into()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn xwayland_does_not_override_wayland_session() { + assert_eq!(select(None,Some("wayland"),Some("wayland-0")),Ok(DesktopBackend::Wayland)); + assert_eq!(select(None,None,Some("wayland-1")),Ok(DesktopBackend::Wayland)); + assert_eq!(select(None,Some("x11"),None),Ok(DesktopBackend::X11)); + assert_eq!(select(Some("x11"),Some("wayland"),Some("wayland-0")),Ok(DesktopBackend::X11)); + assert!(select(Some("typo"),None,None).is_err()); + } +} diff --git a/src/file_trans.rs b/src/file_trans.rs new file mode 100644 index 0000000..8a9a587 --- /dev/null +++ b/src/file_trans.rs @@ -0,0 +1,741 @@ +//! UU file-transfer RPC (FILE_DATA_CHANNEL) for the Linux desktop. +//! Wire shapes come from the official Mac host's SwiftProtobuf name maps and field +//! descriptors: analysis/tools-fix-20261013/server-field-maps.json and server-fieldmd.json. +//! Message 21 RpcRequest{1 header{1 request_id}, 8 FileTransferFtpRequest}; +//! Message 22 RpcResponse{1 header, 4 FileTransferFtpResponse}. +//! Logs carry counts and sizes only, never file names, paths or contents. + +use crate::protocol::{decode_wire, WireField, WireValue}; +use std::collections::HashMap; +use std::io::{Read, Seek, SeekFrom, Write}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use tokio::sync::{mpsc, oneshot}; + +// FileTransferError +pub const FT_SUCCEEDED: u64 = 1; +const FT_UNEXPECTED: u64 = 2; +const FT_PROTOCOL: u64 = 3; +const FT_PERMISSION: u64 = 4; +const FT_DISK: u64 = 5; +const FT_IO: u64 = 6; +const FT_CANCELED: u64 = 7; +const FT_NOT_FOUND: u64 = 9; +// FileType +const FT_DIR: u64 = 0; +const FT_DIR_DRIVE: u64 = 3; +const FT_FILE: u64 = 4; +// FileOperationStrategy +const FOS_DUPLICATE: u64 = 2; +const FOS_SKIP: u64 = 3; +const FOS_RESUME: u64 = 4; + +const DOWNLOAD_BLOCK: usize = 32 * 1024; +const DOWNLOAD_WINDOW: usize = 16; + +// ---------- protobuf helpers ---------- +fn varint(mut v: u64, out: &mut Vec) { + while v >= 128 { out.push((v as u8 & 127) | 128); v >>= 7; } + out.push(v as u8); +} +#[derive(Default)] +struct Enc(Vec); +impl Enc { + fn uint(mut self, field: u32, v: u64) -> Self { + if v != 0 { varint(u64::from(field) << 3, &mut self.0); varint(v, &mut self.0); } + self + } + fn boolean(self, field: u32, v: bool) -> Self { self.uint(field, v as u64) } + fn bytes(mut self, field: u32, v: &[u8]) -> Self { + varint((u64::from(field) << 3) | 2, &mut self.0); varint(v.len() as u64, &mut self.0); + self.0.extend_from_slice(v); self + } + fn text(self, field: u32, v: &str) -> Self { if v.is_empty() { self } else { self.bytes(field, v.as_bytes()) } } + fn msg(self, field: u32, v: Enc) -> Self { self.bytes(field, &v.0) } +} + +fn get_uint(fields: &[WireField], n: u32) -> u64 { + fields.iter().rev().find_map(|f| match (f.number == n, &f.value) { (true, WireValue::Varint(v)) => Some(*v), _ => None }).unwrap_or(0) +} +fn get_bytes<'a>(fields: &[WireField<'a>], n: u32) -> Option<&'a [u8]> { + fields.iter().rev().find_map(|f| match (f.number == n, &f.value) { (true, WireValue::Bytes(v)) => Some(*v), _ => None }) +} +fn get_all<'a>(fields: &[WireField<'a>], n: u32) -> Vec<&'a [u8]> { + fields.iter().filter_map(|f| match (f.number == n, &f.value) { (true, WireValue::Bytes(v)) => Some(*v), _ => None }).collect() +} +fn get_text(fields: &[WireField], n: u32) -> String { + get_bytes(fields, n).map(|b| String::from_utf8_lossy(b).into_owned()).unwrap_or_default() +} + +/// GvPb_TaskId {1 task_id, 2 file_index} +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)] +pub struct TaskId { pub task: u64, pub index: u64 } +impl TaskId { + fn parse(fields: &[WireField]) -> Self { + get_bytes(fields, 1).and_then(|b| decode_wire(b).ok()) + .map(|f| TaskId { task: get_uint(&f, 1), index: get_uint(&f, 2) }).unwrap_or_default() + } + fn enc(self) -> Enc { Enc::default().uint(1, self.task).uint(2, self.index) } +} + +/// GvPb_FileInfo {1 rel_path, 2 size, 3 modified_time} +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FileInfo { pub rel_path: String, pub size: u64, pub modified: u64 } +impl FileInfo { + fn parse(b: &[u8]) -> Option { + let f = decode_wire(b).ok()?; + Some(Self { rel_path: get_text(&f, 1), size: get_uint(&f, 2), modified: get_uint(&f, 3) }) + } + fn enc(&self) -> Enc { Enc::default().text(1, &self.rel_path).uint(2, self.size).uint(3, self.modified) } +} + +/// Files may arrive inline (repeated field) or as list_data: a FileList {1 files}, compressed +/// when FF_FILE_TRANSFER_FTP_LIST_COMPRESS is negotiated (zlib; gzip/raw deflate tolerated). +fn parse_files(inline: Vec<&[u8]>, list_data: Option<&[u8]>) -> Vec { + let mut out: Vec = inline.into_iter().filter_map(FileInfo::parse).collect(); + if out.is_empty() { + if let Some(data) = list_data.filter(|d| !d.is_empty()) { + let mut candidates = Vec::new(); + let mut buf = Vec::new(); + if flate2::read::ZlibDecoder::new(data).read_to_end(&mut buf).is_ok() { candidates.push(std::mem::take(&mut buf)); } + if flate2::read::GzDecoder::new(data).read_to_end(&mut buf).is_ok() { candidates.push(std::mem::take(&mut buf)); } + if flate2::read::DeflateDecoder::new(data).read_to_end(&mut buf).is_ok() { candidates.push(std::mem::take(&mut buf)); } + candidates.push(data.to_vec()); + for c in candidates { + if let Ok(f) = decode_wire(&c) { + let files: Vec = get_all(&f, 1).into_iter().filter_map(FileInfo::parse).collect(); + if !files.is_empty() { out = files; break; } + } + } + if out.is_empty() { + log::warn!("File transfer list_data not decoded: bytes={} magic={:02x?}", data.len(), &data[..data.len().min(2)]); + } + } + } + out +} + +/// zlib(FileList{1 files}) for list_data. +fn list_data(files: &[FileInfo]) -> Vec { + let mut list = Enc::default(); + for f in files { list = list.msg(1, f.enc()); } + zlib(&list.0) +} + +fn zlib(data: &[u8]) -> Vec { + let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::default()); + let _ = enc.write_all(data); + enc.finish().unwrap_or_default() +} + +fn unix_secs(t: std::io::Result) -> u64 { + t.ok().and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs()).unwrap_or(0) +} + +fn io_error(e: &std::io::Error) -> u64 { + match e.kind() { + std::io::ErrorKind::NotFound => FT_NOT_FOUND, + std::io::ErrorKind::PermissionDenied => FT_PERMISSION, + _ if e.raw_os_error() == Some(libc::ENOSPC) => FT_DISK, + _ => FT_IO, + } +} + +/// Mirrors the official Mac path translation (UURemoteServer 0x1000b8100): backslashes +/// become "/", a leading "~" is the user's home directory (the viewer opens on "~/"), +/// anything else is rooted at "/". +pub fn normalize(path: &str) -> PathBuf { + let p = path.replace('\\', "/"); + // The host registers as a PC, so the viewer builds drive paths ("C:/x", or ":/" when it + // knows no drive letter). Linux has a single root: any drive prefix maps to "/". + let p = match p.split_once(':') { + Some((drive, rest)) if drive.len() <= 1 && drive.chars().all(|c| c.is_ascii_alphabetic()) + && (rest.is_empty() || rest.starts_with('/')) => rest.to_string(), + _ => p, + }; + let (mut out, p) = match p.strip_prefix('~') { + Some(rest) if rest.is_empty() || rest.starts_with('/') => (home(), rest.to_string()), + _ => (PathBuf::from("/"), p), + }; + for part in p.split('/') { + match part { "" | "." => {}, ".." => { out.pop(); }, x => out.push(x) } + } + out +} + +fn home() -> PathBuf { std::env::var_os("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/")) } + +/// GvPb_FileEntry {1 entry_type, 2 name, 3 size, 4 modified_time, 5 full_path, 6 icon_type} +fn entry(kind: u64, name: &str, size: u64, modified: u64, full: &str) -> Enc { + Enc::default().uint(1, kind).text(2, name).uint(3, size).uint(4, modified).text(5, full) +} + +/// The viewer treats this host as a PC and opens "此电脑" by asking for the bare drive root +/// (":/" — no drive letter is known) or an empty path. +pub fn is_this_pc(path: &str) -> bool { + let p = path.trim().replace('\\', "/"); + if p.is_empty() { return true; } + let p = p.trim_end_matches('/'); + p.ends_with(':') && p.len() <= 2 && p[..p.len() - 1].chars().all(|c| c.is_ascii_alphabetic()) +} + +/// XDG user directory (e.g. XDG_DOCUMENTS_DIR="$HOME/文档") when it exists. +fn xdg_dir(key: &str) -> Option { + let home = home(); + let conf = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).unwrap_or_else(|| home.join(".config")); + let text = std::fs::read_to_string(conf.join("user-dirs.dirs")).ok()?; + let value = text.lines().find_map(|l| l.trim().strip_prefix(&format!("{key}=")))?.trim().trim_matches('"').to_string(); + let path = PathBuf::from(value.replace("$HOME", &home.to_string_lossy())); + (path != home && path.is_dir()).then_some(path) +} + +/// "此电脑": like Windows, user folders first (Documents, Desktop, Downloads), then the home +/// folder, then the filesystem root as the only "drive". +fn this_pc() -> Vec { + let home = home(); + let name = |p: &Path| p.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| p.to_string_lossy().into_owned()); + let modified = |p: &Path| unix_secs(std::fs::metadata(p).and_then(|m| m.modified())); + let mut out = Vec::new(); + for key in ["XDG_DOCUMENTS_DIR", "XDG_DESKTOP_DIR", "XDG_DOWNLOAD_DIR"] { + if let Some(dir) = xdg_dir(key) { out.push(entry(FT_DIR, &name(&dir), 0, modified(&dir), &dir.to_string_lossy())); } + } + out.push(entry(FT_DIR, &name(&home), 0, modified(&home), &home.to_string_lossy())); + out.push(entry(FT_DIR_DRIVE, "/", 0, 0, "/")); + out +} + +pub fn list_directory(path: &str) -> Result, u64> { + if is_this_pc(path) { return Ok(this_pc()); } + let dir = normalize(path); + let read = std::fs::read_dir(&dir).map_err(|e| io_error(&e))?; + let mut list = Vec::new(); + for item in read.flatten() { + let name = item.file_name().to_string_lossy().into_owned(); + let full = dir.join(&name); + // Follow links so linked folders stay navigable. + let Ok(meta) = std::fs::metadata(&full).or_else(|_| item.metadata()) else { continue }; + let kind = if meta.is_dir() { FT_DIR } else { FT_FILE }; + let size = if meta.is_dir() { 0 } else { meta.len() }; + list.push((meta.is_dir(), name.to_lowercase(), entry(kind, &name, size, unix_secs(meta.modified()), &full.to_string_lossy()))); + } + list.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.cmp(&b.1))); + Ok(list.into_iter().map(|(_, _, e)| e).collect()) +} + +/// Recursive file list for a download request: (folder_name, files). For a folder, rel paths are +/// relative to it; for a single file, folder_name is empty and rel_path is the file name. +fn collect_download(root: &Path) -> std::io::Result<(String, Vec<(FileInfo, PathBuf)>)> { + let meta = std::fs::metadata(root)?; + let name = root.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default(); + let mut out = Vec::new(); + if !meta.is_dir() { + out.push((FileInfo { rel_path: name.clone(), size: meta.len(), modified: unix_secs(meta.modified()) }, root.to_path_buf())); + return Ok((String::new(), out)); + } + let mut stack = vec![root.to_path_buf()]; + while let Some(dir) = stack.pop() { + for item in std::fs::read_dir(&dir)?.flatten() { + let p = item.path(); + let Ok(m) = std::fs::metadata(&p) else { continue }; + if m.is_dir() { stack.push(p); continue; } + if !m.is_file() { continue; } + let rel = p.strip_prefix(root).map(|r| r.to_string_lossy().into_owned()).unwrap_or_default(); + // Relative to folder_name, which the response carries separately. + out.push((FileInfo { rel_path: rel, size: m.len(), modified: unix_secs(m.modified()) }, p)); + } + } + Ok((name, out)) +} + +fn unique_path(p: &Path) -> PathBuf { + if !p.exists() { return p.to_path_buf(); } + let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); + let ext = p.extension().map(|e| format!(".{}", e.to_string_lossy())).unwrap_or_default(); + for i in 1..10_000 { + let c = p.with_file_name(format!("{stem} ({i}){ext}")); + if !c.exists() { return c; } + } + p.to_path_buf() +} + +struct UploadTask { target: PathBuf, folder: String, strategy: u64, files: Vec, open: HashMap } + +/// Per-connection file-transfer state. Outgoing messages are fully framed `Message`s. +pub struct FileSession { + out: mpsc::UnboundedSender>, + seq: Arc, + next_request: AtomicU64, + /// Like the official host's FileTransferDownloadResponseKey: replies are matched by + /// (response case, task, file index, block id) because the viewer's RpcResponse header + /// does not echo the host's request_id (observed 0). + pending: Mutex>>>, + uploads: Mutex>, + /// Downloads run one at a time, in request order (the viewer may ask for several at once). + downloading: Arc>, + first_upload_block: Mutex>, +} + +fn now() -> u64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() } + +impl FileSession { + pub fn new(out: mpsc::UnboundedSender>, seq: Arc) -> Arc { + Arc::new(Self { out, seq, next_request: AtomicU64::new(1 << 32), pending: Mutex::new(HashMap::new()), + uploads: Mutex::new(HashMap::new()), downloading: Arc::new(Default::default()), first_upload_block: Mutex::new(None) }) + } + + fn send(&self, which: u32, body: Enc) { + let seq = self.seq.fetch_add(1, Ordering::Relaxed); + let _ = self.out.send(crate::initialization::envelope(seq, now(), which, &body.0)); + } + /// RpcResponse{1 header{1 request_id}, 4 ftp{case}} + fn respond(&self, request_id: u64, case: u32, body: Enc) { + let header = Enc::default().uint(1, request_id); + self.send(22, Enc::default().msg(1, header).msg(4, Enc::default().msg(case, body))); + } + /// Host-initiated RpcRequest{1 header, 8 ftp{case}}; resolves with the response's ftp payload. + async fn request(&self, case: u32, body: Enc, key: (u32, u64, u64, u64)) -> Option> { + let id = self.next_request.fetch_add(1, Ordering::Relaxed); + let (tx, rx) = oneshot::channel(); + self.pending.lock().unwrap().insert(key, tx); + let header = Enc::default().uint(1, id); + self.send(21, Enc::default().msg(1, header).msg(8, Enc::default().msg(case, body))); + match tokio::time::timeout(std::time::Duration::from_secs(30), rx).await { + Ok(Ok(v)) => Some(v), + _ => { self.pending.lock().unwrap().remove(&key); None } + } + } + + /// Key of a FileTransferFtpResponse: 3 file_confirm{id}, 4 block_confirm{id, block_id}, 6 result{id}. + fn response_key(ftp: &[u8]) -> Option<(u32, u64, u64, u64)> { + let fields = decode_wire(ftp).ok()?; + let case = fields.iter().find(|f| matches!(f.value, WireValue::Bytes(_)))?; + let WireValue::Bytes(inner) = case.value else { return None }; + let inner = decode_wire(inner).ok()?; + let id = TaskId::parse(&inner); + let block = if case.number == 4 { get_uint(&inner, 2) } else { 0 }; + Some((case.number, id.task, id.index, block)) + } + + /// Handles one decoded Message. Returns true when it carried file-transfer RPC. + pub fn handle(self: &Arc, message: &[WireField]) -> bool { + let mut handled = false; + for field in message { + match (field.number, &field.value) { + (21, WireValue::Bytes(rpc)) => { + let Ok(rpc) = decode_wire(rpc) else { continue }; + let Some(ftp) = get_bytes(&rpc, 8) else { continue }; + let request_id = get_bytes(&rpc, 1).and_then(|h| decode_wire(h).ok()).map(|h| get_uint(&h, 1)).unwrap_or(0); + handled = true; + if let Ok(ftp) = decode_wire(ftp) { self.on_request(request_id, &ftp); } + } + (22, WireValue::Bytes(rpc)) => { + let Ok(rpc) = decode_wire(rpc) else { continue }; + let Some(ftp) = get_bytes(&rpc, 4) else { continue }; + handled = true; + match Self::response_key(ftp) { + Some(key) => match self.pending.lock().unwrap().remove(&key) { + Some(tx) => { let _ = tx.send(ftp.to_vec()); } + None => log::info!("File transfer response without pending request: case={} task={} index={} block={}", key.0, key.1, key.2, key.3), + }, + None => log::info!("File transfer response undecodable: bytes={}", ftp.len()), + } + } + _ => {} + } + } + handled + } + + fn on_request(self: &Arc, rid: u64, ftp: &[WireField]) { + let Some(case) = ftp.iter().find(|f| matches!(f.value, WireValue::Bytes(_))) else { + log::warn!("File transfer request without payload: fields={:?}", ftp.iter().map(|f| f.number).collect::>()); + return; + }; + let WireValue::Bytes(body) = case.value else { return }; + let Ok(f) = decode_wire(body) else { log::warn!("File transfer request {} undecodable", case.number); return }; + match case.number { + 10 => self.read_dir(rid, &f), + 1 => self.receive_request(rid, &f), + 3 => self.file_ask(rid, &f), + 4 => self.file_block(rid, &f), + 9 => self.complete(rid, &f), + 2 => self.send_request(rid, &f), + 5 | 6 | 7 | 8 => self.file_operation(rid, case.number, &f), + 11 => self.file_exist(rid, &f), + 12 => { log::info!("File transfer clear_send_temp"); self.respond(rid, 5, Enc::default().uint(1, FT_SUCCEEDED)); } + n => log::info!("File transfer request case {} not implemented: fields={:?}", n, f.iter().map(|x| x.number).collect::>()), + } + } + + /// read_dir {1 id, 2 path} -> file_directory {1 id, 2 path, 3 entries, 4 file_error} + fn read_dir(&self, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let requested = get_text(f, 2); + let drive = requested.len() >= 2 && requested.as_bytes()[1] == b':' && requested.as_bytes()[0].is_ascii_alphabetic(); + log::info!("File transfer read_dir path shape: len={} drive_letter={} backslashes={} leading_slash={} exists={}", + requested.chars().count(), drive, requested.matches('\\').count(), requested.starts_with('/'), + !requested.is_empty() && normalize(&requested).is_dir()); + if !requested.is_empty() && requested.chars().count() <= 16 && !normalize(&requested).is_dir() { + // Short unresolved names are viewer-side virtual locations; record them to map correctly. + log::info!("File transfer read_dir unresolved short path: {:?}", requested); + } + // Like the official Mac reader: only the virtual root path lists roots; anything else + // is read as-is (backslashes normalized) and errors are reported, never redirected. + let path = requested; + let mut body = id.enc(); + body = Enc::default().msg(1, body).text(2, &path); + match list_directory(&path) { + Ok(entries) => { + // FF_FILE_TRANSFER_FTP_LIST_COMPRESS: the official host sends the listing as + // zlib(DirectoryData{1 entries}) in dir_data; entries are kept for older viewers. + let mut listing = Enc::default(); + for e in &entries { listing = listing.bytes(1, &e.0); } + let compressed = zlib(&listing.0); + log::info!("File transfer read_dir: request_id={} root={} entries={} dir_data_bytes={}", rid, path.is_empty(), entries.len(), compressed.len()); + for e in entries { body = body.msg(3, e); } + body = body.uint(4, FT_SUCCEEDED).bytes(5, &compressed); + } + Err(code) => { log::info!("File transfer read_dir failed: request_id={} error={}", rid, code); body = body.uint(4, code); } + } + self.respond(rid, 7, body); + } + + /// rename{1 path,2 new_name} dir_create{1 path} remove_file{1 path} remove_dir{1 id,2 path,3 recursive} + fn file_operation(&self, rid: u64, case: u32, f: &[WireField]) { + let path_field = if case == 8 { 2 } else { 1 }; + let raw = get_text(f, path_field); + let path = normalize(&raw); + let result = match case { + 5 => { let new = get_text(f, 2); if new.contains('/') || new.contains('\\') || new.is_empty() { Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)) } else { std::fs::rename(&path, path.with_file_name(new)) } } + 6 => std::fs::create_dir_all(&path), + 7 => std::fs::remove_file(&path), + // The viewer confirms with the user and sends remove_dir for any selected item without + // the recursive flag (like Explorer): files are unlinked, folders removed with contents. + _ => match std::fs::symlink_metadata(&path) { + Ok(m) if m.is_dir() => std::fs::remove_dir_all(&path), + Ok(_) => std::fs::remove_file(&path), + Err(e) => Err(e), + }, + }; + let code = match &result { Ok(()) => FT_SUCCEEDED, Err(e) => io_error(e) }; + log::info!("File transfer operation: case={} result={} os_error={:?}", case, code, result.as_ref().err().and_then(|e| e.raw_os_error())); + let msg = result.err().map(|e| e.to_string()).unwrap_or_default(); + if case == 8 { + // Official removeDir reply (UURemoteServer "文件操作-removeDir 回包"): the response oneof is + // `result` (field 6) = FileTransferResult{1 id, 2 file_error} echoing the request's TaskId, + // not operation_result; the viewer reported 删除文件失败 for operation_result. + self.respond(rid, 6, Enc::default().msg(1, TaskId::parse(f).enc()).uint(2, code)); + return; + } + self.respond(rid, 5, Enc::default().uint(1, code).text(2, &msg).text(3, &raw)); + } + + /// file_exist{1 path, 2 names} -> file_exist_response{1 path, 2 results{1 name,2 has_same,3 has_transfering}} + fn file_exist(&self, rid: u64, f: &[WireField]) { + let raw = get_text(f, 1); + let dir = normalize(&raw); + let mut body = Enc::default().text(1, &raw); + let names = get_all(f, 2); + let mut same = 0; + for n in &names { + let name = String::from_utf8_lossy(n); + let exists = dir.join(name.as_ref()).exists(); + same += exists as usize; + body = body.msg(2, Enc::default().text(1, &name).boolean(2, exists)); + } + log::info!("File transfer file_exist: names={} existing={}", names.len(), same); + self.respond(rid, 8, body); + } + + /// Upload to this host. receive_request{1 id,2 path,3 files,4 strategy,5 folder_name,6 list_data,7 task_unique_id} + fn receive_request(&self, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let target = normalize(&get_text(f, 2)); + let folder = get_text(f, 5); + let strategy = get_uint(f, 4); + let files = parse_files(get_all(f, 3), get_bytes(f, 6)); + let prefixed = files.iter().filter(|x| !folder.is_empty() && x.rel_path.replace('\\', "/").starts_with(&format!("{folder}/"))).count(); + log::info!("File transfer receive_request: task={} files={} bytes={} folder={} rel_prefixed={} strategy={} target_dir={}", + id.task, files.len(), files.iter().map(|x| x.size).sum::(), !folder.is_empty(), prefixed, strategy, target.is_dir()); + let err = if !target.is_dir() { FT_NOT_FOUND } else { FT_SUCCEEDED }; + let mut body = Enc::default().msg(1, id.enc()); + for x in &files { body = body.msg(2, x.enc()); } + body = body.uint(3, err); + if err == FT_SUCCEEDED && !folder.is_empty() { + // Like the official createEmptyFolderIfNeeded: a folder (possibly empty) is created even + // when its file list is empty. + let mut dir = target.clone(); + for part in folder.replace('\\', "/").split('/') { match part { "" | "." | ".." => {}, x => dir.push(x) } } + if let Err(e) = std::fs::create_dir_all(&dir) { log::warn!("File transfer folder create failed: {}", io_error(&e)); } + } + if err == FT_SUCCEEDED { + self.uploads.lock().unwrap().insert(id.task, UploadTask { target, folder, strategy, files, open: HashMap::new() }); + } + self.respond(rid, 1, body); + } + + /// TaskId.file_index is 1-based (observed: the first file of a task is index 1). + fn file_slot(index: u64) -> Option { (index as usize).checked_sub(1) } + + fn upload_path(task: &UploadTask, index: u64) -> Option { + let info = task.files.get(Self::file_slot(index)?)?; + let rel = info.rel_path.replace('\\', "/"); + let rel = if !task.folder.is_empty() && !rel.starts_with(&format!("{}/", task.folder)) { format!("{}/{}", task.folder, rel) } else { rel }; + let mut p = task.target.clone(); + for part in rel.split('/') { match part { "" | "." | ".." => {}, x => p.push(x) } } + Some(p) + } + + /// file_ask{1 id,2 last_modified,3 file_size} -> file_confirm{1 id,2 skip,3 err,4 resume_point} + fn file_ask(&self, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let size = get_uint(f, 3); + let mut uploads = self.uploads.lock().unwrap(); + let (skip, err, resume) = match uploads.get_mut(&id.task) { + None => (false, FT_PROTOCOL, 0), + Some(task) => match Self::upload_path(task, id.index) { + None => (false, FT_PROTOCOL, 0), + Some(mut path) => { + let existing = std::fs::metadata(&path).ok().filter(|m| m.is_file()).map(|m| m.len()); + if existing.is_some() && task.strategy == FOS_SKIP { (true, FT_SUCCEEDED, 0) } + else { + let resume = if task.strategy == FOS_RESUME { existing.filter(|e| *e <= size).unwrap_or(0) } else { 0 }; + if existing.is_some() && task.strategy == FOS_DUPLICATE { path = unique_path(&path); } + let opened = path.parent().map(std::fs::create_dir_all).unwrap_or(Ok(())) + .and_then(|_| std::fs::OpenOptions::new().create(true).write(true).truncate(resume == 0).open(&path)) + .and_then(|mut file| { file.seek(SeekFrom::Start(resume))?; Ok(file) }); + match opened { + Ok(file) => { task.open.insert(id.index, (file, path, resume)); (false, FT_SUCCEEDED, resume) } + Err(e) => (false, io_error(&e), 0), + } + } + } + }, + }; + log::info!("File transfer file_ask: task={} index={} size={} skip={} err={} resume={}", id.task, id.index, size, skip, err, resume); + self.respond(rid, 3, Enc::default().msg(1, id.enc()).boolean(2, skip).uint(3, err).uint(4, resume)); + } + + /// file_block{1 id,2 block_id,3 data} -> block_confirm{1 id,2 block_id,3 err,4 block_len} + fn file_block(&self, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let block = get_uint(f, 2); + let data = get_bytes(f, 3).unwrap_or_default(); + { + let mut first = self.first_upload_block.lock().unwrap(); + if first.is_none() { *first = Some(block); log::info!("File transfer first upload block: block_id={} len={}", block, data.len()); } + } + let err = match self.uploads.lock().unwrap().get_mut(&id.task).and_then(|t| t.open.get_mut(&id.index)) { + None => FT_PROTOCOL, + Some((file, _, written)) => match file.write_all(data) { Ok(()) => { *written += data.len() as u64; FT_SUCCEEDED } Err(e) => io_error(&e) }, + }; + if err != FT_SUCCEEDED { log::warn!("File transfer block failed: task={} index={} block={} err={}", id.task, id.index, block, err); } + self.respond(rid, 4, Enc::default().msg(1, id.enc()).uint(2, block).uint(3, err).uint(4, data.len() as u64)); + } + + /// complete{1 id,2 error} -> result{1 id,2 file_error,3 err_msg} + fn complete(&self, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let error = get_uint(f, 2); + let mut uploads = self.uploads.lock().unwrap(); + let mut code = FT_SUCCEEDED; + if let Some(task) = uploads.get_mut(&id.task) { + if let Some((file, path, written)) = task.open.remove(&id.index) { + let expected = Self::file_slot(id.index).and_then(|i| task.files.get(i)).map(|x| x.size).unwrap_or(written); + drop(file); + if error != FT_SUCCEEDED && error != 0 { let _ = std::fs::remove_file(&path); code = error; } + else if written != expected { code = FT_IO; } + log::info!("File transfer upload file done: task={} index={} bytes={} expected={} viewer_error={} result={}", id.task, id.index, written, expected, error, code); + } + if task.open.is_empty() && id.index as usize >= task.files.len() { uploads.remove(&id.task); } + } + self.respond(rid, 6, Enc::default().msg(1, id.enc()).uint(2, code)); + } + + /// Download from this host. send_request{1 id,2 path,3 list_data} -> send_response{1 id,2 err,3 files,4 folder_name} + fn send_request(self: &Arc, rid: u64, f: &[WireField]) { + let id = TaskId::parse(f); + let raw = get_text(f, 2); + let path = normalize(&raw); + let collected = collect_download(&path).map_err(|e| io_error(&e)); + let mut body = Enc::default().msg(1, id.enc()); + match collected { + Ok((folder, files)) => { + log::info!("File transfer send_request: task={} files={} bytes={} folder={}", id.task, files.len(), files.iter().map(|x| x.0.size).sum::(), !folder.is_empty()); + body = body.uint(2, FT_SUCCEEDED); + for (info, _) in &files { body = body.msg(3, info.enc()); } + // The viewer indexes this list by file_index; with LIST_COMPRESS it reads list_data. + let infos: Vec = files.iter().map(|(i, _)| i.clone()).collect(); + body = body.text(4, &folder).bytes(5, &list_data(&infos)); + self.respond(rid, 2, body); + let me = self.clone(); + tokio::spawn(async move { + let _turn = me.downloading.clone().lock_owned().await; + me.run_download(id.task, files).await; + }); + } + Err(code) => { + log::info!("File transfer send_request failed: task={} error={}", id.task, code); + self.respond(rid, 2, body.uint(2, code)); + } + } + } + + async fn run_download(self: &Arc, task: u64, files: Vec<(FileInfo, PathBuf)>) { + let ok = self.download_files(task, &files).await; + // Official host (FileTransferDownloadCoordinator.startDownloadTransfer, 0x1001cd860): after the + // last file it sends, without waiting, complete{id{task, file_index = -1}, error}. The viewer + // treats an index past its list as the task end and marks the download accepted. + let id = TaskId { task, index: u64::MAX }; // int32 -1, sign-extended varint + self.send(21, Enc::default().msg(1, Enc::default().uint(1, self.next_request.fetch_add(1, Ordering::Relaxed))) + .msg(8, Enc::default().msg(9, Enc::default().msg(1, id.enc()).uint(2, if ok { FT_SUCCEEDED } else { FT_UNEXPECTED })))); + log::info!("File transfer download task done: task={} files={} ok={}", task, files.len(), ok); + } + + async fn download_files(self: &Arc, task: u64, files: &[(FileInfo, PathBuf)]) -> bool { + // Block ids follow the viewer's own uploads (observed 0-based); file indexes are 1-based. + let first_block = self.first_upload_block.lock().unwrap().unwrap_or(0); + for (index, (info, path)) in files.iter().enumerate() { + let index = index + 1; + let id = TaskId { task, index: index as u64 }; + let Some(confirm) = self.request(3, Enc::default().msg(1, id.enc()).uint(2, info.modified).uint(3, info.size), (3, id.task, id.index, 0)).await else { + log::warn!("File transfer download: no file_confirm task={} index={}", task, index); return false; + }; + let [skip, err, resume] = case_uints(&confirm, 3, [2, 3, 4]); + let skip = skip != 0; + log::info!("File transfer download file_confirm: task={} index={} skip={} err={} resume={}", task, index, skip, err, resume); + if err == FT_CANCELED { return false; } + if skip || (err != FT_SUCCEEDED && err != 0) { continue; } + let result = self.send_file(id, path, resume.min(info.size), first_block).await; + let code = match result { Ok(()) => FT_SUCCEEDED, Err(c) => c }; + let reply = self.request(9, Enc::default().msg(1, id.enc()).uint(2, code), (6, id.task, id.index, 0)).await; + let r = reply.map(|r| case_uints(&r, 6, [2])[0]).unwrap_or(0); + log::info!("File transfer download file done: task={} index={} bytes={} result={} viewer_result={}", task, index, info.size, code, r); + if code == FT_CANCELED { return false; } + } + true + } + + async fn send_file(self: &Arc, id: TaskId, path: &Path, resume: u64, first_block: u64) -> Result<(), u64> { + let mut file = std::fs::File::open(path).map_err(|e| io_error(&e))?; + file.seek(SeekFrom::Start(resume)).map_err(|e| io_error(&e))?; + let mut block_id = first_block + resume / DOWNLOAD_BLOCK as u64; + let mut inflight = tokio::task::JoinSet::new(); + loop { + let mut buf = vec![0u8; DOWNLOAD_BLOCK]; + let n = file.read(&mut buf).map_err(|e| io_error(&e))?; + if n == 0 { break; } + buf.truncate(n); + while inflight.len() >= DOWNLOAD_WINDOW { + if let Some(Ok(code)) = inflight.join_next().await { if code != FT_SUCCEEDED { return Err(code); } } + } + let me = self.clone(); + let body = Enc::default().msg(1, id.enc()).uint(2, block_id).bytes(3, &buf); + let key = (4, id.task, id.index, block_id); + inflight.spawn(async move { + match me.request(4, body, key).await { + Some(r) => { let [e] = case_uints(&r, 4, [3]); if e == 0 { FT_SUCCEEDED } else { e } } + None => FT_IO, + } + }); + block_id += 1; + } + while let Some(r) = inflight.join_next().await { + if let Ok(code) = r { if code != FT_SUCCEEDED { return Err(code); } } + } + Ok(()) + } +} + +/// Reads varint fields of one FileTransferFtpResponse case (0 when absent). +fn case_uints(ftp: &[u8], case: u32, numbers: [u32; N]) -> [u64; N] { + let fields = decode_wire(ftp).ok().and_then(|f| get_bytes(&f, case)).and_then(|b| decode_wire(b).ok()).unwrap_or_default(); + numbers.map(|n| get_uint(&fields, n)) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn normalizes_windows_and_relative_paths() { + assert_eq!(normalize("C:\\..\\home\\a\\.\\b"), PathBuf::from("/home/a/b")); + assert_eq!(normalize("/tmp//x/../y"), PathBuf::from("/tmp/y")); + assert_eq!(normalize("~/"), home()); + assert_eq!(normalize("~\\a"), home().join("a")); + assert_eq!(normalize("~x"), PathBuf::from("/~x")); + assert_eq!(normalize(":/"), PathBuf::from("/")); + assert_eq!(normalize("C:\\home\\a"), PathBuf::from("/home/a")); + assert_eq!(normalize(":/home/a"), PathBuf::from("/home/a")); + assert!(is_this_pc(":/") && is_this_pc("") && is_this_pc("C:\\") && is_this_pc("c:")); + assert!(!is_this_pc("/") && !is_this_pc(":/home") && !is_this_pc("ab:/")); + assert_eq!(normalize("/tmp/a:b"), PathBuf::from("/tmp/a:b")); + } + #[test] + fn read_dir_round_trip_uses_official_field_numbers() { + let dir = std::env::temp_dir().join(format!("uu-ft-{}", std::process::id())); + std::fs::create_dir_all(dir.join("sub")).unwrap(); + std::fs::write(dir.join("a.txt"), b"hello").unwrap(); + let (tx, mut rx) = mpsc::unbounded_channel(); + let s = FileSession::new(tx, Arc::new(AtomicU64::new(1))); + let read = Enc::default().msg(1, TaskId { task: 7, index: 0 }.enc()).text(2, &dir.to_string_lossy()); + let rpc = Enc::default().msg(1, Enc::default().uint(1, 99)).msg(8, Enc::default().msg(10, read)); + let msg = crate::initialization::envelope(5, 6, 21, &rpc.0); + assert!(s.handle(&decode_wire(&msg).unwrap())); + let out = rx.try_recv().unwrap(); + let outer = decode_wire(&out).unwrap(); + let rsp = decode_wire(get_bytes(&outer, 22).unwrap()).unwrap(); + assert_eq!(get_uint(&decode_wire(get_bytes(&rsp, 1).unwrap()).unwrap(), 1), 99); + let ftp = decode_wire(get_bytes(&rsp, 4).unwrap()).unwrap(); + let fd = decode_wire(get_bytes(&ftp, 7).unwrap()).unwrap(); + assert_eq!(get_uint(&fd, 4), FT_SUCCEEDED); + let mut listing = Vec::new(); + flate2::read::ZlibDecoder::new(get_bytes(&fd, 5).unwrap()).read_to_end(&mut listing).unwrap(); + assert_eq!(get_all(&decode_wire(&listing).unwrap(), 1).len(), 2); + let entries: Vec<_> = get_all(&fd, 3).into_iter().map(|e| decode_wire(e).unwrap()).collect(); + assert_eq!(entries.len(), 2); + assert_eq!(get_text(&entries[0], 2), "sub"); + assert_eq!(get_uint(&entries[0], 1), FT_DIR); + assert_eq!(get_text(&entries[1], 2), "a.txt"); + assert_eq!(get_uint(&entries[1], 1), FT_FILE); + assert_eq!(get_uint(&entries[1], 3), 5); + std::fs::remove_dir_all(dir).unwrap(); + } + #[test] + fn list_data_round_trips_through_compression() { + let files = vec![FileInfo { rel_path: "d/a.txt".into(), size: 3, modified: 9 }]; + assert_eq!(parse_files(vec![], Some(&list_data(&files))), files); + let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + let mut plain = Enc::default(); plain = plain.msg(1, files[0].enc()); + gz.write_all(&plain.0).unwrap(); + assert_eq!(parse_files(vec![], Some(&gz.finish().unwrap())), files); + } + #[test] + fn upload_writes_blocks_and_confirms() { + let dir = std::env::temp_dir().join(format!("uu-up-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let (tx, mut rx) = mpsc::unbounded_channel(); + let s = FileSession::new(tx, Arc::new(AtomicU64::new(1))); + let id = TaskId { task: 3, index: 1 }; + let call = |case: u32, body: Enc| { + let rpc = Enc::default().msg(1, Enc::default().uint(1, 1)).msg(8, Enc::default().msg(case, body)); + s.handle(&decode_wire(&crate::initialization::envelope(1, 1, 21, &rpc.0)).unwrap()); + }; + let info = FileInfo { rel_path: "x.bin".into(), size: 6, modified: 0 }; + call(1, Enc::default().msg(1, id.enc()).text(2, &dir.to_string_lossy()).msg(3, info.enc())); + call(3, Enc::default().msg(1, id.enc()).uint(3, 6)); + call(4, Enc::default().msg(1, id.enc()).uint(2, 1).bytes(3, b"abc")); + call(4, Enc::default().msg(1, id.enc()).uint(2, 2).bytes(3, b"def")); + call(9, Enc::default().msg(1, id.enc()).uint(2, FT_SUCCEEDED)); + let mut cases = Vec::new(); + while let Ok(m) = rx.try_recv() { + let o = decode_wire(&m).unwrap(); + let r = decode_wire(get_bytes(&o, 22).unwrap()).unwrap(); + let ftp = decode_wire(get_bytes(&r, 4).unwrap()).unwrap(); + cases.push(ftp[0].number); + } + assert_eq!(cases, vec![1, 3, 4, 4, 6]); + assert_eq!(std::fs::read(dir.join("x.bin")).unwrap(), b"abcdef"); + std::fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/initialization.rs b/src/initialization.rs new file mode 100644 index 0000000..268c7fc --- /dev/null +++ b/src/initialization.rs @@ -0,0 +1,296 @@ +//! Official CONTROL initialization protobuf payloads recovered from the Mac app. +//! See analysis/protocol-fix-20261013/control/screen-state-field-maps.json. +//! The caller supplies measured Linux geometry, track binding and permissions. +//! No hardware capabilities or successful actions are inferred here. + +fn varint(mut value: u64, out: &mut Vec) { + while value >= 128 { + out.push((value as u8 & 127) | 128); + value >>= 7; + } + out.push(value as u8); +} +fn integer(number: u32, value: i32, out: &mut Vec) { + if value != 0 { + varint(u64::from(number) << 3, out); + varint(value as i64 as u64, out); + } +} +fn boolean(number: u32, value: bool, out: &mut Vec) { + if value { integer(number, 1, out); } +} +fn bytes(number: u32, value: &[u8], out: &mut Vec) { + varint((u64::from(number) << 3) | 2, out); + varint(value.len() as u64, out); + out.extend_from_slice(value); +} +fn text(number: u32, value: &str, out: &mut Vec) { + if !value.is_empty() { bytes(number, value.as_bytes(), out); } +} +pub fn envelope(seq: u64, timestamp: u64, which: u32, payload: &[u8]) -> Vec { + let mut out = Vec::new(); + if seq != 0 { out.push(8); varint(seq, &mut out); } + if timestamp != 0 { out.push(16); varint(timestamp, &mut out); } + bytes(which, payload, &mut out); + out +} + +#[derive(Debug, Clone, Copy)] +pub struct WinRect { + pub left: i32, + pub top: i32, + pub width: i32, + pub height: i32, + pub pixel_width: i32, + pub pixel_height: i32, +} +impl WinRect { + fn encode(self) -> Result, String> { + if self.width <= 0 || self.height <= 0 || self.pixel_width <= 0 || self.pixel_height <= 0 { + return Err("Screen geometry must have positive logical and pixel dimensions".into()); + } + let mut out = Vec::new(); + for (field, value) in [(1,self.left),(2,self.top),(3,self.width),(4,self.height),(5,self.pixel_width),(6,self.pixel_height)] { + integer(field, value, &mut out); + } + Ok(out) + } +} + +pub struct Screen<'a> { + pub id: i32, + pub fps: i32, + pub resolution: WinRect, + pub primary: bool, + /// Measured pixel/logical scale; never zero or guessed from a display name. + pub dpr: f64, + pub display_name: &'a str, + pub video_track_index: i32, + /// Official enum: 0 physical, 1 virtual, 2 super-screen. + pub screen_type: i32, + /// Official enum: 0 unknown, 1 built-in, 2 not built-in. + pub builtin_screen_type: i32, + /// Further selectable (scaled) stream sizes besides `resolution`, for 其他分辨率. + pub scaled: &'a [(i32, i32)], + /// Size currently streamed when it differs from `resolution`. + pub current: Option<(i32, i32)>, +} +impl Screen<'_> { + fn encode(&self) -> Result, String> { + if self.id < 0 || self.fps <= 0 || self.video_track_index < 0 { + return Err("Screen id/track must be nonnegative and fps positive".into()); + } + if !self.dpr.is_finite() || self.dpr <= 0.0 { + return Err("Screen dpr must be positive and finite".into()); + } + if !(0..=2).contains(&self.screen_type) || !(0..=2).contains(&self.builtin_screen_type) { + return Err("Unknown Screen enum value".into()); + } + let rect = self.resolution.encode()?; + let mut out = Vec::new(); + integer(1, self.id, &mut out); + integer(2, self.fps, &mut out); + bytes(3, &rect, &mut out); // the measured native resolution first + let sized = |(width, height): (i32, i32)| WinRect { width, height, pixel_width: width, pixel_height: height, ..self.resolution }.encode(); + for size in self.scaled { bytes(3, &sized(*size)?, &mut out); } + let current = match self.current { Some(size) => sized(size)?, None => rect.clone() }; + bytes(4, ¤t, &mut out); // current_resolution + integer(5, self.screen_type, &mut out); + bytes(6, &rect, &mut out); // init_resolution + boolean(7, self.primary, &mut out); + out.push(65); // field 8 Double: fixed64, not varint + out.extend_from_slice(&self.dpr.to_le_bytes()); + // Field 9 dpi_scale omitted: no unmeasured monitor-DPI claim. + text(10, self.display_name, &mut out); + // Field 11 resolution_type omitted: default UNKNOWN is truthful. + integer(12, self.video_track_index, &mut out); + integer(13, self.builtin_screen_type, &mut out); + Ok(out) + } +} + +/// Message.which field 7 ScreenSources, including the selected screen id. +pub fn encode_screen_sources(seq: u64, timestamp: u64, screens: &[Screen<'_>], current_id: i32) -> Result, String> { + if screens.is_empty() || !screens.iter().any(|s| s.id == current_id) { + return Err("Selected screen must exist in the measured inventory".into()); + } + let mut ids = std::collections::HashSet::new(); + let mut tracks = std::collections::HashSet::new(); + let mut payload = Vec::new(); + for screen in screens { + if !ids.insert(screen.id) || !tracks.insert(screen.video_track_index) { + return Err("Screen ids and video track indices must be unique".into()); + } + bytes(1, &screen.encode()?, &mut payload); + } + integer(2, current_id, &mut payload); + Ok(envelope(seq, timestamp, 7, &payload)) +} + +/// Message.which field 8 CaptureChange. Enum: desktop=0, window=1, +/// MuMu=2, hook=3, none=99. Caller confirms the active capture before emitting. +pub fn encode_capture_change(seq: u64, timestamp: u64, capture_type: i32, type_value: i32, description: &str) -> Result, String> { + if !matches!(capture_type, 0 | 1 | 2 | 3 | 99) { + return Err("Unknown CaptureChange type".into()); + } + let mut payload = Vec::new(); + integer(1, capture_type, &mut payload); + integer(2, type_value, &mut payload); + text(3, description, &mut payload); + Ok(envelope(seq, timestamp, 8, &payload)) +} + +/// Minimal initialization for the caller's measured single Linux framebuffer. +/// Current deployment binding is source_id=0, video_track_index=0. Dimensions +/// describe the source desktop, not the downscaled H264 bitstream. No monitor +/// DPI, audio, input permission, or optional feature versions are advertised. +/// Invalid dimensions/fps produce no messages, never invented fallback values. +pub fn initial_messages(width: u32, height: u32, fps: u32) -> Vec<(u32, Vec)> { + let (Ok(width), Ok(height), Ok(fps)) = (i32::try_from(width), i32::try_from(height), i32::try_from(fps)) else { return Vec::new(); }; + let screen = Screen { + id: 0, fps, + resolution: WinRect { left: 0, top: 0, width, height, pixel_width: width, pixel_height: height }, + primary: true, dpr: 1.0, display_name: "", video_track_index: 0, + screen_type: 0, builtin_screen_type: 0, scaled: &[], current: None, + }; + let Ok(encoded_screen) = screen.encode() else { return Vec::new(); }; + let mut inventory = Vec::new(); + bytes(1, &encoded_screen, &mut inventory); + // current_screen_id=0 is an ordinary scalar default. CaptureChange's + // desktop=0/type_value=0 defaults are still represented by the which tag. + vec![(7, inventory), (8, Vec::new())] +} + +#[derive(Debug, Clone, Copy)] +pub struct Permissions { + pub assistant: bool, + pub video_capture_allowed: bool, + pub capture_content_visible: bool, + pub audio_capture_allowed: bool, + pub floating_ball: bool, +} +/// Message.field15 SystemStateChange.field3 PermissionState. +pub fn encode_permissions(seq: u64, timestamp: u64, permissions: Permissions) -> Vec { + let mut state = Vec::new(); + for (n, v) in [(1,permissions.assistant),(2,permissions.video_capture_allowed),(3,permissions.capture_content_visible),(4,permissions.audio_capture_allowed),(5,permissions.floating_ball)] { + boolean(n, v, &mut state); + } + let mut change = Vec::new(); + bytes(3, &state, &mut change); + envelope(seq, timestamp, 15, &change) +} + +/// QuerySystemState StateId=1 expects this secure desktop state notification. +/// Locked/SAS/support flags must come from the current Linux session's evidence. +pub fn encode_secure_desktop(seq: u64, timestamp: u64, locked: bool, sas_shown: bool, supports_auto_logon: bool) -> Vec { + let mut state = Vec::new(); + boolean(1, locked, &mut state); + boolean(2, sas_shown, &mut state); + boolean(5, supports_auto_logon, &mut state); + let mut change = Vec::new(); + bytes(1, &state, &mut change); + envelope(seq, timestamp, 15, &change) +} + +/// Message.field12 ReportError { 2: error_code, 3: error_msg } (action left default, as the +/// Mac host does for a failed AUTO_UNLOCK_SYSTEM). +pub fn encode_report_error(seq: u64, timestamp: u64, error_code: i32, error_msg: &str) -> Vec { + let mut report = Vec::new(); + integer(2, error_code, &mut report); + text(3, error_msg, &mut report); + envelope(seq, timestamp, 12, &report) +} + +#[cfg(test)] +#[path = "protocol.rs"] +mod wire_test_support; + +#[cfg(test)] +mod tests { + use super::*; + use super::wire_test_support::{decode_wire, WireValue}; + fn nested(data: &[u8], field: u32) -> Vec { + decode_wire(data).unwrap().into_iter().find_map(|f| { + if f.number == field { if let WireValue::Bytes(b) = f.value { return Some(b.to_vec()); } } + None + }).expect("expected nested field") + } + fn number(data: &[u8], field: u32) -> Option { + decode_wire(data).unwrap().into_iter().find_map(|f| { + if f.number == field { if let WireValue::Varint(v) = f.value { return Some(v); } } + None + }) + } + fn screen() -> Screen<'static> { + Screen { id: 1, fps: 10, resolution: WinRect { left: -1920, top: 0, width: 1920, height: 1080, pixel_width: 1920, pixel_height: 1080 }, primary: true, dpr: 1.0, display_name: "test display", video_track_index: 0, screen_type: 0, builtin_screen_type: 0, scaled: &[], current: None } + } + #[test] + fn screen_inventory_uses_correct_nested_rect_and_fixed64_scale() { + let msg = encode_screen_sources(7, 9, &[screen()], 1).unwrap(); + let inventory = nested(&msg, 7); + assert_eq!(number(&inventory, 2), Some(1)); + let display = nested(&inventory, 1); + let rect = nested(&display, 4); + assert_eq!(number(&rect, 1), Some((-1920i64) as u64)); + assert_eq!(number(&rect, 3), Some(1920)); + assert_eq!(number(&rect, 4), Some(1080)); + assert_eq!(number(&rect, 5), Some(1920)); + assert_eq!(number(&rect, 6), Some(1080)); + assert_eq!(number(&display, 12).unwrap_or(0), 0); + assert!(decode_wire(&display).unwrap().iter().any(|f| f.number == 8 && f.value == WireValue::Fixed64(1.0f64.to_le_bytes()))); + assert_eq!(nested(&display, 3), rect); + assert_eq!(nested(&display, 6), rect); + } + #[test] + fn minimal_messages_preserve_actual_source_size_and_binding_zero() { + let m = initial_messages(1920, 1080, 10); + assert_eq!(m.len(), 2); + assert_eq!(m[0].0, 7); + assert_eq!(m[1], (8, Vec::::new())); + let display = nested(&m[0].1, 1); + assert_eq!(number(&display, 1).unwrap_or(0), 0); + assert_eq!(number(&display, 12).unwrap_or(0), 0); + let rect = nested(&display, 4); + assert_eq!(number(&rect, 3), Some(1920)); + assert_eq!(number(&rect, 4), Some(1080)); + assert!(initial_messages(0, 1080, 10).is_empty()); + assert!(initial_messages(u32::MAX, 1080, 10).is_empty()); + } + + #[test] + fn rejects_missing_or_invalid_measured_inventory() { + assert!(encode_screen_sources(1, 1, &[], 1).is_err()); + assert!(encode_screen_sources(1, 1, &[screen()], 2).is_err()); + let mut s = screen(); s.resolution.width = 0; + assert!(encode_screen_sources(1, 1, &[s], 1).is_err()); + let mut s = screen(); s.dpr = f64::NAN; + assert!(encode_screen_sources(1, 1, &[s], 1).is_err()); + assert!(encode_screen_sources(1, 1, &[screen(), screen()], 1).is_err()); + } + #[test] + fn permission_state_does_not_claim_audio_or_extra_features() { + let m = encode_permissions(1, 2, Permissions { assistant: false, video_capture_allowed: true, capture_content_visible: true, audio_capture_allowed: false, floating_ball: false }); + let p = nested(&nested(&m, 15), 3); + assert_eq!(number(&p, 2), Some(1)); + assert_eq!(number(&p, 3), Some(1)); + assert_eq!(number(&p, 4), None); + assert_eq!(number(&p, 5), None); + } + #[test] + fn default_secure_state_is_explicitly_present() { + let report = encode_report_error(3, 4, -5, "linux auto unlock failed"); + let error = nested(&report, 12); + assert_eq!(number(&error, 2), Some((-5i64) as u64)); // int32 negative: 10-byte varint + assert_eq!(number(&error, 1), None); + let state = encode_secure_desktop(1, 2, false, false, false); + assert_eq!(nested(&nested(&state, 15), 1), Vec::::new()); + } + #[test] + fn capture_change_preserves_official_desktop_enum_default() { + let c = encode_capture_change(1, 2, 0, 1, "test capture").unwrap(); + let p = nested(&c, 8); + assert_eq!(number(&p, 1).unwrap_or(0), 0); + assert_eq!(number(&p, 2), Some(1)); + assert!(encode_capture_change(1, 2, 4, 1, "").is_err()); + } +} diff --git a/src/input.rs b/src/input.rs new file mode 100644 index 0000000..4f3ec5f --- /dev/null +++ b/src/input.rs @@ -0,0 +1,200 @@ +//! Native Linux X11 Input Injection Engine via XTest + +#[cfg(target_os = "linux")] +extern "C" { + fn x11_mouse_move(x: libc::c_int, y: libc::c_int) -> libc::c_int; + fn x11_mouse_relative(dx: libc::c_int, dy: libc::c_int) -> libc::c_int; + fn x11_mouse_button(button: libc::c_int, is_press: libc::c_int) -> libc::c_int; + fn x11_pointer_state(x:*mut libc::c_int,y:*mut libc::c_int,mask:*mut libc::c_uint)->libc::c_int; + fn x11_key_symbol(symbol: libc::c_ulong, is_press: libc::c_int) -> libc::c_int; + fn x11_key_event(keycode: libc::c_int, is_press: libc::c_int) -> libc::c_int; +} + +#[cfg(not(target_os = "linux"))] +unsafe fn x11_mouse_move(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 } +#[cfg(not(target_os = "linux"))] +unsafe fn x11_mouse_button(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 } +#[cfg(not(target_os = "linux"))] +unsafe fn x11_key_event(_: libc::c_int, _: libc::c_int) -> libc::c_int { 0 } + +#[cfg(not(target_os = "linux"))] +unsafe fn x11_key_symbol(_: libc::c_ulong, _: libc::c_int) -> libc::c_int { 0 } + +#[cfg(not(target_os = "linux"))] +unsafe fn x11_mouse_relative(_: libc::c_int, _: libc::c_int) -> libc::c_int {0} + +#[derive(Default)] +struct PendingPointer { + absolute: Option<(i32,i32)>, + relative: (i64,i64), + scroll: (i64,i64), +} +#[cfg(not(target_os = "linux"))] +unsafe fn x11_pointer_state(_: *mut libc::c_int,_:*mut libc::c_int,_:*mut libc::c_uint)->libc::c_int {-1} +#[derive(Default)] +struct HeldInput { buttons: std::collections::BTreeSet, keys: std::collections::BTreeSet } +pub struct InputInjector { portal:std::sync::Mutex>>, backend: crate::desktop_backend::DesktopBackend, pending: std::sync::Mutex, held: std::sync::Mutex } + +impl InputInjector { + pub fn new() -> Self { + Self { portal:std::sync::Mutex::new(None), backend:crate::desktop_backend::detect().unwrap_or(crate::desktop_backend::DesktopBackend::X11), pending: std::sync::Mutex::new(PendingPointer::default()), held:std::sync::Mutex::new(HeldInput::default()) } + } + + pub fn bind_portal(&self,session:Option>) { *self.portal.lock().unwrap()=session; } + pub fn mouse_move(&self, x: i32, y: i32) { + self.inject_move(x,y,false); + } + + pub fn mouse_absolute_normalized(&self, x: f64, y: f64, size: (u32,u32)) { + if let Some(position) = crate::input_mapping::normalized_pointer(x,y,size.0,size.1) { + let mut pending = self.pending.lock().unwrap(); + pending.absolute = Some(position); + pending.relative = (0,0); + } + } + pub fn mouse_relative(&self, dx: i32, dy: i32) { + if dx.unsigned_abs() <= 65535 && dy.unsigned_abs() <= 65535 { + let mut pending = self.pending.lock().unwrap(); + pending.relative.0 = (pending.relative.0 + i64::from(dx)).clamp(-65535,65535); + pending.relative.1 = (pending.relative.1 + i64::from(dy)).clamp(-65535,65535); + } + } + pub fn mouse_scroll(&self, dx: i32, dy: i32) { + // Official Mac normal wheel=120; precise trackpads use smaller values. + let mut pending = self.pending.lock().unwrap(); + pending.scroll.0 = (pending.scroll.0 + i64::from(dx)).clamp(-12000,12000); + pending.scroll.1 = (pending.scroll.1 + i64::from(dy)).clamp(-12000,12000); + } + pub fn start_pointer_worker(self: &std::sync::Arc) -> tokio::task::JoinHandle<()> { + let input = self.clone(); + tokio::spawn(async move { + let mut tick = tokio::time::interval(std::time::Duration::from_millis(4)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { tick.tick().await; input.flush_pointer(); } + }) + } + pub fn discard_pointer(&self) { *self.pending.lock().unwrap() = PendingPointer::default(); } + pub fn flush_pointer(&self) { + // Hold the queue lock through injection so an older timer tick cannot + // overwrite a newer position flushed before a button transition. + let mut pending = self.pending.lock().unwrap(); + let motion = std::mem::take(&mut *pending); + pending.scroll = (motion.scroll.0 % 120, motion.scroll.1 % 120); + if let Some((x,y)) = motion.absolute { self.inject_move(x,y,false); } + if motion.relative != (0,0) { self.inject_move(motion.relative.0 as i32,motion.relative.1 as i32,true); } + for (value, positive, negative) in [(motion.scroll.1,4,5),(motion.scroll.0,7,6)] { + let count = value / 120; + let button = if count > 0 { positive } else { negative }; + for _ in 0..count.unsigned_abs().min(100) { + self.inject_button(button,true); self.inject_button(button,false); + } + } + } + pub fn wire_mouse_button(&self, button: i32, is_press: bool) { + if let Some(mapped) = crate::input_mapping::mouse_button_to_x11(button) { self.mouse_button(mapped,is_press); } + } + pub fn mouse_button(&self, button: i32, is_press: bool) { + self.flush_pointer(); + let result = self.inject_button(button,is_press); + if result == 0 { + let mut held = self.held.lock().unwrap(); + if is_press { held.buttons.insert(button); } else { held.buttons.remove(&button); } + } else { log::warn!("Desktop mouse injection failed: {}",result); } + static BUTTON_AUDIT:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); + if self.backend==crate::desktop_backend::DesktopBackend::X11 && BUTTON_AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed)<24 { + let (mut x,mut y,mut mask)=(0,0,0); + let query=unsafe {x11_pointer_state(&mut x,&mut y,&mut mask)}; + log::info!("Pointer button audit: button={} down={} result={} query={} x={} y={} mask={}",button,is_press,result,query,x,y,mask); + } + } + + pub fn windows_key_event(&self, key: i32, is_press: bool) { + if let Some(symbol) = crate::input_mapping::windows_vk_to_keysym(key) { + let result = self.inject_key(symbol,is_press); + static AUDIT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if AUDIT.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 8 { + log::info!("Desktop keyboard injection outcome: result={result}"); + } + if result == 0 { + let mut held=self.held.lock().unwrap(); + if is_press {held.keys.insert(symbol);} else {held.keys.remove(&symbol);} + } + } + } + + pub fn release_held(&self) { + self.discard_pointer(); + let mut held=self.held.lock().unwrap(); + for button in &held.buttons {self.inject_button(*button,false);} + for key in &held.keys {self.inject_key(*key,false);} + *held=HeldInput::default(); + } + fn inject_move(&self,x:i32,y:i32,relative:bool)->i32 { + if let Some(portal)=self.portal.lock().unwrap().as_ref() { return if portal.move_pointer(f64::from(x),f64::from(y),relative).is_ok() {0} else {-1}; } + if self.backend==crate::desktop_backend::DesktopBackend::Portal {return -1;} + if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::move_pointer(x,y,relative) } + else if relative { unsafe { x11_mouse_relative(x,y) } } else { unsafe { x11_mouse_move(x,y) } } + } + fn inject_button(&self,button:i32,pressed:bool)->i32 { + if let Some(portal)=self.portal.lock().unwrap().as_ref() { return if portal.button(button,pressed).is_ok() {0} else {-1}; } + if self.backend==crate::desktop_backend::DesktopBackend::Portal {return -1;} + if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::button(button,pressed) } + else { unsafe { x11_mouse_button(button,i32::from(pressed)) } } + } + fn inject_key(&self,symbol:u64,pressed:bool)->i32 { + if let Some(portal)=self.portal.lock().unwrap().as_ref() { return if portal.key(symbol,pressed).is_ok() {0} else {-1}; } + if self.backend==crate::desktop_backend::DesktopBackend::Portal {return -1;} + if self.backend==crate::desktop_backend::DesktopBackend::Wayland { crate::wayland::key(symbol,pressed) } + else { unsafe { x11_key_symbol(symbol as libc::c_ulong,i32::from(pressed)) } } + } + pub fn key_event(&self, keycode: i32, is_press: bool) { + if self.backend!=crate::desktop_backend::DesktopBackend::X11 { return; } + unsafe { x11_key_event(keycode, if is_press { 1 } else { 0 }) }; + } +} + +#[cfg(test)] +mod motion_tests { + use super::*; + #[test] + fn coalesces_absolute_history_to_latest_position() { + let input = InputInjector::new(); + input.mouse_absolute_normalized(0.1,0.1,(1920,1080)); + input.mouse_absolute_normalized(0.9,0.9,(1920,1080)); + assert_eq!(input.pending.lock().unwrap().absolute,Some((1727,971))); + } + #[test] + fn preserves_relative_distance_after_latest_absolute() { + let input = InputInjector::new(); + input.mouse_relative(10,20); + input.mouse_absolute_normalized(0.5,0.5,(1920,1080)); + input.mouse_relative(3,-2); input.mouse_relative(4,5); + let state = input.pending.lock().unwrap(); + assert_eq!(state.absolute,Some((960,540))); + assert_eq!(state.relative,(7,3)); + } + #[test] + fn button_transition_flushes_motion_and_teardown_discards_pending() { + let input = InputInjector::new(); + input.mouse_absolute_normalized(0.5,0.5,(1920,1080)); + input.mouse_button(1,true); + assert!(input.pending.lock().unwrap().absolute.is_none()); + input.mouse_relative(1,2); input.discard_pointer(); + assert_eq!(input.pending.lock().unwrap().relative,(0,0)); + } +} + +#[cfg(test)] +mod scroll_tests { + use super::*; + #[test] + fn precise_scroll_accumulates_sub_notch_remainder() { + let input = InputInjector::new(); + input.mouse_scroll(0, 2); input.flush_pointer(); + assert_eq!(input.pending.lock().unwrap().scroll,(0,2)); + input.mouse_scroll(0,118); input.flush_pointer(); + assert_eq!(input.pending.lock().unwrap().scroll,(0,0)); + input.mouse_scroll(-125,-125); input.flush_pointer(); + assert_eq!(input.pending.lock().unwrap().scroll,(-5,-5)); + } +} diff --git a/src/input_mapping.rs b/src/input_mapping.rs new file mode 100644 index 0000000..5a10e12 --- /dev/null +++ b/src/input_mapping.rs @@ -0,0 +1,174 @@ +//! Translate UU's verified Windows-VK input path into X11 KeySyms. +//! A KeySym is not an X11 keycode: the input engine must resolve it against the +//! active X keyboard mapping (e.g. XKeysymToKeycode) before XTest injection. +//! Letters use the unshifted lowercase symbol; separate modifier events carry +//! Shift/Ctrl/Alt state. Unknown VKs are ignored instead of injecting raw values. + +/// Map an official Windows virtual-key identifier to a base X11 KeySym. +/// The wire has no extended-key bit; VK_RETURN consequently means Return. +/// OEM punctuation follows the US base-symbol interpretation; other physical +/// layouts may need their own OEM policy. OEM_102 is deliberately unsupported. +pub fn windows_vk_to_keysym(vk: i32) -> Option { + let keysym = match vk { + 0x30..=0x39 => vk as u64, // 0..9 + 0x41..=0x5a => (vk + 0x20) as u64, // A..Z -> a..z + 0x60..=0x69 => 0xffb0 + (vk - 0x60) as u64, // KP_0..KP_9 + 0x70..=0x87 => 0xffbe + (vk - 0x70) as u64, // F1..F24 + 0x08 => 0xff08, // BackSpace + 0x09 => 0xff09, // Tab + 0x0c => 0xff0b, // Clear + 0x0d => 0xff0d, // Return + 0x10 | 0xa0 => 0xffe1, // Shift / Shift_L + 0xa1 => 0xffe2, // Shift_R + 0x11 | 0xa2 => 0xffe3, // Control / Control_L + 0xa3 => 0xffe4, // Control_R + 0x12 | 0xa4 => 0xffe9, // Alt / Alt_L + 0xa5 => 0xffea, // Alt_R + 0x13 => 0xff13, // Pause + 0x14 => 0xffe5, // Caps_Lock + 0x1b => 0xff1b, // Escape + 0x20 => 0x0020, // space + 0x21 => 0xff55, // Prior / Page_Up + 0x22 => 0xff56, // Next / Page_Down + 0x23 => 0xff57, // End + 0x24 => 0xff50, // Home + 0x25 => 0xff51, // Left + 0x26 => 0xff52, // Up + 0x27 => 0xff53, // Right + 0x28 => 0xff54, // Down + 0x2c => 0xff61, // Print + 0x2d => 0xff63, // Insert + 0x2e => 0xffff, // Delete + 0x5b => 0xffeb, // Super_L + 0x5c => 0xffec, // Super_R + 0x5d => 0xff67, // Menu + 0x6a => 0xffaa, // KP_Multiply + 0x6b => 0xffab, // KP_Add + 0x6c => 0xffac, // KP_Separator + 0x6d => 0xffad, // KP_Subtract + 0x6e => 0xffae, // KP_Decimal + 0x6f => 0xffaf, // KP_Divide + 0x90 => 0xff7f, // Num_Lock + 0x91 => 0xff14, // Scroll_Lock + 0xba => 0x003b, // OEM_1: semicolon + 0xbb => 0x003d, // OEM_PLUS: equal + 0xbc => 0x002c, // OEM_COMMA + 0xbd => 0x002d, // OEM_MINUS + 0xbe => 0x002e, // OEM_PERIOD + 0xbf => 0x002f, // OEM_2: slash + 0xc0 => 0x0060, // OEM_3: grave + 0xdb => 0x005b, // OEM_4: bracketleft + 0xdc => 0x005c, // OEM_5: backslash + 0xdd => 0x005d, // OEM_6: bracketright + 0xde => 0x0027, // OEM_7: apostrophe + // OEM_102 depends on the physical keyboard/layout; do not guess. + _ => return None, + }; + Some(keysym) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn verified_shift_and_left_use_named_keysyms() { + assert_eq!(windows_vk_to_keysym(160), Some(0xffe1)); + assert_eq!(windows_vk_to_keysym(37), Some(0xff51)); + assert_ne!(windows_vk_to_keysym(160), Some(160)); + } + + #[test] + fn letters_use_unshifted_symbols_and_digits_keep_ascii() { + assert_eq!(windows_vk_to_keysym(65), Some(u64::from(b'a'))); + assert_eq!(windows_vk_to_keysym(90), Some(u64::from(b'z'))); + for digit in b'0'..=b'9' { + assert_eq!(windows_vk_to_keysym(i32::from(digit)), Some(u64::from(digit))); + } + } + + #[test] + fn modifiers_preserve_left_and_right_identity() { + let variants = [ + (0x10, 0xffe1), (0xa0, 0xffe1), (0xa1, 0xffe2), + (0x11, 0xffe3), (0xa2, 0xffe3), (0xa3, 0xffe4), + (0x12, 0xffe9), (0xa4, 0xffe9), (0xa5, 0xffea), + (0x5b, 0xffeb), (0x5c, 0xffec), + ]; + for (vk, expected) in variants { + assert_eq!(windows_vk_to_keysym(vk), Some(expected)); + } + } + + #[test] + fn function_and_keypad_ranges_have_correct_endpoints() { + assert_eq!(windows_vk_to_keysym(112), Some(0xffbe)); + assert_eq!(windows_vk_to_keysym(135), Some(0xffd5)); + assert_eq!(windows_vk_to_keysym(96), Some(0xffb0)); + assert_eq!(windows_vk_to_keysym(105), Some(0xffb9)); + assert_eq!(windows_vk_to_keysym(106), Some(0xffaa)); + assert_eq!(windows_vk_to_keysym(111), Some(0xffaf)); + } + + #[test] + fn navigation_and_oem_base_keys_are_not_raw_keycodes() { + assert_eq!(windows_vk_to_keysym(46), Some(0xffff)); + assert_eq!(windows_vk_to_keysym(36), Some(0xff50)); + assert_eq!(windows_vk_to_keysym(186), Some(u64::from(b';'))); + assert_eq!(windows_vk_to_keysym(187), Some(u64::from(b'='))); + assert_eq!(windows_vk_to_keysym(220), Some(u64::from(b'\\'))); + assert_eq!(windows_vk_to_keysym(222), Some(u64::from(b'\''))); + } + + #[test] + fn unknown_or_layout_specific_keys_are_ignored() { + for vk in [-1, 0, 7, 21, 136, 226, 255, 256, i32::MAX] { + assert_eq!(windows_vk_to_keysym(vk), None); + } + } +} + +/// Official Mac CONTROL absolute coordinates are normalized to the source screen. +pub fn normalized_pointer(x: f64, y: f64, width: u32, height: u32) -> Option<(i32, i32)> { + if width == 0 || height == 0 || width > i32::MAX as u32 || height > i32::MAX as u32 + || !x.is_finite() || !y.is_finite() || !(0.0..=1.0).contains(&x) || !(0.0..=1.0).contains(&y) { return None; } + Some(((x * (width - 1) as f64).round() as i32, (y * (height - 1) as f64).round() as i32)) +} + +#[cfg(test)] +mod pointer_tests { + use super::normalized_pointer; + #[test] + fn maps_source_screen_edges_and_center() { + assert_eq!(normalized_pointer(0.0, 0.0, 1920, 1080), Some((0,0))); + assert_eq!(normalized_pointer(1.0, 1.0, 1920, 1080), Some((1919,1079))); + assert_eq!(normalized_pointer(0.5, 0.5, 1920, 1080), Some((960,540))); + } + #[test] + fn maps_observed_editor_titlebar_coordinate() { + assert_eq!(normalized_pointer(0.6805736636245111, 0.15990730011587487,1920,1080),Some((1306,173))); + } + #[test] + fn rejects_invalid_coordinate_or_screen_dimensions() { + assert_eq!(normalized_pointer(f64::NAN,0.5,1920,1080),None); + assert_eq!(normalized_pointer(0.5,f64::INFINITY,1920,1080),None); + assert_eq!(normalized_pointer(-0.1,0.5,1920,1080),None); + assert_eq!(normalized_pointer(0.5,1.1,1920,1080),None); + assert_eq!(normalized_pointer(0.5,0.5,0,1080),None); + } +} + +/// Official Mac sends mouse button bitmasks, not X11 button ordinals. +pub fn mouse_button_to_x11(button: i32) -> Option { + match button { 1 => Some(1), 2 => Some(3), 4 => Some(2), _ => None } +} +#[cfg(test)] +mod button_tests { + #[test] + fn maps_verified_button_bitmasks() { + assert_eq!(super::mouse_button_to_x11(1),Some(1)); + assert_eq!(super::mouse_button_to_x11(2),Some(3)); + assert_eq!(super::mouse_button_to_x11(4),Some(2)); + assert_eq!(super::mouse_button_to_x11(3),None); + } +} diff --git a/src/login.rs b/src/login.rs new file mode 100644 index 0000000..6b1e592 --- /dev/null +++ b/src/login.rs @@ -0,0 +1,374 @@ +//! `uuremote-server login`: register this machine as a UU PC host and bind it to an account +//! by scanning a QR code with the UU mobile app, the same flow as the official clients: +//! 1. POST /api/v1/device/windows/init (anonymous, hardware summary) -> device_id +//! 2. POST /api/v1/qrcode/gen/login -> qrcode_jump_url (QR content), token (login ticket) +//! 3. POST /api/v1/qrcode/login/status {token, qrcode_jump_url, login_status}: long poll, 1..4 +//! 4. POST /api/v1/login/by_qrcode {token, qrcode_jump_url} -> user_id, token (JWT carries csrf) +//! Field names: server 422 validation and the official Mac client's Codable models +//! (analysis/tools-fix-20261013/viewer-fieldmd.json). Results are written to the private +//! config file (chmod 600). Tokens and tickets are never printed or logged. + +use crate::auth::{Credentials, UUAuthClient}; +use crate::login_ui::{LoginUi, Tone}; +use serde_json::{json, Value}; +use std::time::Duration; + +fn read(path: &str) -> String { std::fs::read_to_string(path).map(|s| s.trim().to_string()).unwrap_or_default() } + +fn random_uuid() -> String { + let mut b = [0u8; 16]; + if let Ok(mut f) = std::fs::File::open("/dev/urandom") { use std::io::Read; let _ = f.read_exact(&mut b); } + b[6] = (b[6] & 0x0f) | 0x40; + b[8] = (b[8] & 0x3f) | 0x80; + let h = hex::encode(b); + format!("{}-{}-{}-{}-{}", &h[..8], &h[8..12], &h[12..16], &h[16..20], &h[20..]) +} + +/// /etc/machine-id as a GUID, the closest Linux analogue of Windows MachineGuid. +fn machine_guid() -> String { + let id = read("/etc/machine-id"); + if id.len() == 32 && id.bytes().all(|c| c.is_ascii_hexdigit()) { + format!("{}-{}-{}-{}-{}", &id[..8], &id[8..12], &id[12..16], &id[16..20], &id[20..]) + } else { random_uuid() } +} + +fn os_name() -> String { + read("/etc/os-release").lines().find_map(|l| l.strip_prefix("PRETTY_NAME=")).map(|v| v.trim_matches('"').to_string()) + .unwrap_or_else(|| "Linux".into()) +} + +fn cpu_name() -> String { + read("/proc/cpuinfo").lines().find_map(|l| l.strip_prefix("model name").and_then(|r| r.split_once(':')).map(|(_, v)| v.trim().to_string())) + .unwrap_or_else(|| std::env::consts::ARCH.into()) +} + +fn base_board() -> String { + let v = [read("/sys/class/dmi/id/board_vendor"), read("/sys/class/dmi/id/board_name")].join(" "); + if v.trim().is_empty() { "Unknown".into() } else { v.trim().to_string() } +} + +fn video() -> Vec { + if let Ok(out) = std::process::Command::new("lspci").output() { + let list: Vec = String::from_utf8_lossy(&out.stdout).lines() + .filter(|l| l.contains("VGA compatible controller") || l.contains("3D controller") || l.contains("Display controller")) + .filter_map(|l| l.splitn(2, ": ").nth(1).map(str::to_owned)).collect(); + if !list.is_empty() { return list; } + } + let mut list = Vec::new(); + if let Ok(dir) = std::fs::read_dir("/sys/class/drm") { + for e in dir.flatten() { + let n = e.file_name().to_string_lossy().into_owned(); + if n.starts_with("card") && !n.contains('-') { + let dev = e.path().join("device"); + list.push(format!("PCI {}:{}", read(&dev.join("vendor").to_string_lossy()).trim_start_matches("0x"), + read(&dev.join("device").to_string_lossy()).trim_start_matches("0x"))); + } + } + } + if list.is_empty() { list.push("Unknown".into()); } + list +} + +/// Short GPU name for display: lspci "Vendor Corporation Chip [Marketing name] (rev x)" -> "Vendor Marketing name". +fn gpu_label(line: &str) -> String { + let vendor = match line.split_whitespace().next().unwrap_or("") { "Advanced" => "AMD", v => v }; + match (line.rfind('['), line.rfind(']')) { + (Some(a), Some(b)) if a < b && &line[a + 1..b] != "AMD/ATI" => format!("{vendor} {}", &line[a + 1..b]), + _ => line.split(" (rev").next().unwrap_or(line).to_string(), + } +} + +/// MAC of the first physical interface (one backed by a device), uppercase dash form like Windows. +fn mac() -> String { + let mut names: Vec = std::fs::read_dir("/sys/class/net").map(|d| d.flatten() + .filter(|e| e.path().join("device").exists()).map(|e| e.file_name().to_string_lossy().into_owned()).collect()).unwrap_or_default(); + names.sort(); + names.iter().map(|n| read(&format!("/sys/class/net/{n}/address"))).find(|m| !m.is_empty() && m != "00:00:00:00:00:00") + .map(|m| m.to_uppercase().replace(':', "-")).unwrap_or_default() +} + +fn memory_mb() -> u64 { + read("/proc/meminfo").lines().find_map(|l| l.strip_prefix("MemTotal:")) + .and_then(|v| v.trim().trim_end_matches("kB").trim().parse::().ok()).map(|kb| kb / 1024).unwrap_or(0) +} + +fn screen() -> String { + crate::capture::ScreenCapture::new().map(|c| format!("{}x{}", c.width, c.height)).unwrap_or_else(|_| "1920x1080".into()) +} + +fn hostname() -> String { + let h = read("/proc/sys/kernel/hostname"); + if h.is_empty() { "Linux".into() } else { h } +} + +/// csrf claim inside the JWT access token. +fn csrf_from_token(token: &str) -> Option { + use base64::Engine; + let payload = token.split('.').nth(1)?; + let bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(payload.trim_end_matches('=')).ok()?; + serde_json::from_slice::(&bytes).ok()?.get("csrf")?.as_str().map(str::to_owned) +} + +fn data<'a>(path: &str, status: u16, body: &'a Value) -> Result<&'a Value, String> { + let code = body.get("code").and_then(|c| c.as_i64()).unwrap_or(-1); + if status == 200 && code == 0 { return Ok(body.get("data").unwrap_or(&Value::Null)); } + let fields: Vec = body.get("data").and_then(|d| d.as_array()).map(|a| a.iter() + .filter_map(|e| e.get("loc").map(|l| l.to_string())).collect()).unwrap_or_default(); + Err(format!("{path}: http {status} code {code} {} {}", body.get("msg").and_then(|m| m.as_str()).unwrap_or(""), + if fields.is_empty() { String::new() } else { format!("fields={}", fields.join(",")) })) +} + +fn render_qr(content: &str) -> Result { + let code = qrcode::QrCode::new(content.as_bytes()).map_err(|e| format!("QR encode failed: {e}"))?; + Ok(code.render::().quiet_zone(true) + .dark_color(qrcode::render::unicode::Dense1x2::Light).light_color(qrcode::render::unicode::Dense1x2::Dark).build()) +} + +/// API code for an expired login QR code. +const QR_EXPIRED: i64 = 1190; + +/// QR modules as RGBA pixels: `scale` pixels per module, `quiet` light modules around the code. +fn qr_rgba(content: &str, scale: usize, quiet: usize) -> Result<(Vec, usize), String> { + let code = qrcode::QrCode::new(content.as_bytes()).map_err(|e| format!("QR encode failed: {e}"))?; + let edge = (code.width() + 2 * quiet) * scale; + let mut rgba = vec![255; edge * edge * 4]; + for y in 0..code.width() { for x in 0..code.width() { + if code[(x, y)] == qrcode::Color::Dark { + for dy in 0..scale { for dx in 0..scale { + let offset = (((y + quiet) * scale + dy) * edge + (x + quiet) * scale + dx) * 4; + rgba[offset..offset + 3].fill(0); + }} + } + }} + Ok((rgba, edge)) +} + +fn write_config(cfg: &Value) -> Result { + use std::io::Write; + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + let path = crate::config::path(); + let dir = path.parent().ok_or("config path has no parent")?; + std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; + let tmp = path.with_extension("json.tmp"); + let mut f = std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&tmp) + .map_err(|e| format!("write {}: {e}", tmp.display()))?; + f.write_all(serde_json::to_string_pretty(cfg).unwrap_or_default().as_bytes()).map_err(|e| e.to_string())?; + f.sync_all().map_err(|e| e.to_string())?; + std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)).map_err(|e| e.to_string())?; + std::fs::rename(&tmp, &path).map_err(|e| format!("replace {}: {e}", path.display()))?; + Ok(path) +} + +/// One login at a time per config file (a manual `login` and the service's window would race +/// for the same QR session). The lock is released when the returned file is dropped. +fn single_instance() -> Result { + use std::os::unix::{fs::OpenOptionsExt, io::AsRawFd}; + let path = crate::config::path().with_file_name("login.lock"); + if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; } + let file = std::fs::OpenOptions::new().create(true).write(true).mode(0o600).open(&path) + .map_err(|e| format!("open {}: {e}", path.display()))?; + if unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { + return Err("another login is already in progress (login window already open)".into()); + } + Ok(file) +} + +/// Service side: no usable login. Like the official host, show the login window, as a `login` +/// child process so GTK never runs inside the daemon, when a display is available and +/// UU_LOGIN_WINDOW is not 0. Returns once the config holds credentials whose token differs +/// from `stale_token` (written by that window or by a manual `uuremote-server login`). +pub async fn wait_for_credentials(stale_token: Option) -> Credentials { + let display = std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some(); + let mut window = None; + if display && std::env::var("UU_LOGIN_WINDOW").map_or(true, |v| v != "0") { + // stdout carries the terminal QR (a login ticket): never into the journal. + match std::env::current_exe().and_then(|exe| tokio::process::Command::new(exe).arg("login") + .stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).spawn()) { + Ok(child) => { log::info!("Opened the QR login window on the desktop"); window = Some(child); } + Err(e) => log::error!("Opening the login window failed: {e}"), + } + } + if window.is_none() { + log::error!("UU login required: run `uuremote-server login` and scan the QR code; watching {}", crate::config::path().display()); + } + loop { + tokio::time::sleep(Duration::from_secs(2)).await; + if let Some(child) = window.as_mut() { + if let Ok(Some(status)) = child.try_wait() { + log::info!("Login window exited ({status}); run `uuremote-server login` to sign in later"); + window = None; + } + } + if let Ok(creds) = crate::config::read_fresh().and_then(|f| Credentials::load(f.as_ref())) { + if stale_token.as_deref() != Some(creds.token.as_str()) { + log::info!("UU login found in {}; going online", crate::config::path().display()); + return creds; // a still-open window keeps showing its success page until closed + } + } + } +} + +/// `gui`: also show the GTK login window when one can be opened (the terminal QR is always printed). +pub async fn run(gui: bool) -> Result<(), String> { + let _lock = single_instance().map_err(|e| { eprintln!("login failed: {e}"); e })?; + let ui = if gui { LoginUi::open(&hostname(), &os_name(), &cpu_name(), &video().iter().map(|v| gpu_label(v)).collect::>().join("\n")) } else { LoginUi::none() }; + let result = tokio::select! { + r = flow(&ui) => r, + _ = ui.wait_closed() => Err("login window closed".into()), + }; + match &result { + Ok(name) => { + ui.done(&format!("登录成功\n{name}")); + ui.status("登录信息已保存到本机配置,可以关闭此窗口", Tone::Ok); + } + Err(e) => { eprintln!("login failed: {e}"); ui.status(&format!("登录失败:{e}"), Tone::Error); } + } + if ui.shown() { ui.wait_closed().await; } + result.map(|_| ()) +} + +/// Returns the account nickname (or user id) on success. +async fn flow(ui: &LoginUi) -> Result { + let mut cfg = crate::config::file()?.cloned().unwrap_or_else(|| json!({})); + let get = |cfg: &Value, k: &str| std::env::var(format!("UU_{}", k.to_uppercase())).ok().filter(|v| !v.is_empty()) + .or_else(|| cfg.get(k).and_then(|v| v.as_str()).map(str::to_owned)).unwrap_or_default(); + let sign_key = Some(get(&cfg, "sign_key")).filter(|k| !k.is_empty()).unwrap_or_else(|| crate::auth::DEFAULT_SIGN_KEY.into()); + // Stable host identity: reused across logins so the account keeps one device. + for (key, make) in [("client_id", random_uuid as fn() -> String), ("system_id", || random_uuid().to_uppercase()), ("machine_guid", machine_guid)] { + if get(&cfg, key).is_empty() { cfg[key] = json!(make()); } + } + let mut creds = Credentials { client_id: get(&cfg, "client_id"), system_id: get(&cfg, "system_id"), sign_key, ..Default::default() }; + + if get(&cfg, "device_id").is_empty() { + let body = json!({ + "name": hostname(), "client_id": creds.client_id, "system_id": creds.system_id, "machine_guid": get(&cfg, "machine_guid"), + "os": os_name(), "base_board": base_board(), "cpu": cpu_name(), "video": video(), "mac": mac(), + "memory": memory_mb(), "screen": screen(), + }); + let (status, resp) = UUAuthClient::new(creds.clone()).post_json("/api/v1/device/windows/init", &body).await?; + let d = data("device init", status, &resp)?; + let id = d.get("device_id").and_then(|v| v.as_str()).ok_or("device init returned no device_id")?; + println!("Registered device: name={} id={}", d.get("alias").and_then(|v| v.as_str()).unwrap_or(""), id); + cfg["device_id"] = json!(id); + write_config(&cfg)?; // keep the device even if the QR step is abandoned + } + creds.device_id = get(&cfg, "device_id"); + let client = UUAuthClient::new(creds.clone()); + + loop { + let (status, resp) = client.post_json("/api/v1/qrcode/gen/login", &json!({})).await?; + let d = data("qrcode gen", status, &resp)?; + let url = d.get("qrcode_jump_url").and_then(|v| v.as_str()).ok_or("qrcode gen returned no qrcode_jump_url")?.to_string(); + let ticket = d.get("token").or_else(|| d.get("status_query_ticket")).and_then(|v| v.as_str()) + .ok_or("qrcode gen returned no token")?.to_string(); + if ui.shown() { + let modules = qrcode::QrCode::new(url.as_bytes()).map_err(|e| e.to_string())?.width() + 2; + let (rgba, edge) = qr_rgba(&url, (224 / modules).max(2), 1)?; + ui.qr(&rgba, edge); + ui.status("等待扫码…", Tone::Info); + } + if let Some(path)=std::env::var_os("UU_LOGIN_QR_PNG") { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let (rgba, edge) = qr_rgba(&url, 8, 4)?; + let mut file=std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(path).map_err(|e|e.to_string())?; + file.write_all(&crate::cursor::encode_png(edge as u32,edge as u32,&rgba)).map_err(|e|e.to_string())?; + } + println!("\nScan with the UU Remote mobile app (网易UU远程 App 扫码登录):\n{}", render_qr(&url)?); + // Status is a long poll: send the state already shown (server enum 1..4; observed: + // 1 waiting, 2 scanned, 4 after the phone confirmed); the server answers when it changes. + let mut login_status = 1i64; + let mut expired = false; + for _ in 0..150 { + let query = json!({"token": ticket, "qrcode_jump_url": url, "login_status": login_status}); + let (status, resp) = match client.post_json("/api/v1/qrcode/login/status", &query).await { + Ok(r) => r, + Err(_) => continue, // long-poll timeout: ask again + }; + // Code 1190 (HTTP 400, "二维码已失效"): the QR expired; generate a new one. + if resp.get("code").and_then(|c| c.as_i64()) == Some(QR_EXPIRED) { + ui.status("二维码已过期,正在刷新…", Tone::Info); + expired = true; break; + } + let st = data("qrcode status", status, &resp)?.get("status").and_then(|v| v.as_i64()).unwrap_or(login_status); + if st == login_status { continue; } + login_status = st; + match st { + 2 => { + println!("已扫码,请在手机上确认 (scanned, confirm on the phone)"); + ui.status("已扫码,请在手机上确认登录", Tone::Ok); + } + 3 | 4 => { + // A final state: confirmed logs in; cancelled/expired is refused and a new QR follows. + let body = json!({"token": ticket, "qrcode_jump_url": url}); + let (status, resp) = client.post_json("/api/v1/login/by_qrcode", &body).await?; + let d = match data("qrcode login", status, &resp) { + Ok(d) => d, + Err(e) => { + println!("QR status {st}: login not granted ({e})"); + ui.status("手机端未确认登录,正在刷新二维码…", Tone::Error); + expired = true; break; + } + }; + let token = d.get("token").and_then(|v| v.as_str()).ok_or("login returned no token")?; + let user = d.get("user_id").and_then(|v| v.as_str()).ok_or("login returned no user_id")?; + cfg["token"] = json!(token); + cfg["user_id"] = json!(user); + cfg["csrf"] = json!(csrf_from_token(token).ok_or("token carries no csrf claim")?); + let path = write_config(&cfg)?; + let nickname = d.get("nickname").and_then(|v| v.as_str()).unwrap_or(""); + println!("Logged in as {} ({}); saved to {}", nickname, user, path.display()); + return Ok(if nickname.is_empty() { user.to_string() } else { nickname.to_string() }); + } + _ => { println!("QR status: {st}"); ui.status("二维码已失效,正在刷新…", Tone::Error); expired = true; break; } + } + } + println!("{}", if expired { "QR code expired; generating a new one" } else { "QR code timed out; generating a new one" }); + tokio::time::sleep(Duration::from_secs(1)).await; // never spin if the server keeps refusing + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[tokio::test] + async fn service_waits_until_a_new_token_is_saved() { + let dir = std::env::temp_dir().join(format!("uu-login-wait-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("config.json"); + let creds = |token: &str| json!({"user_id": "u", "device_id": "d", "client_id": "c", "system_id": "s", "token": token, "csrf": "x"}); + std::fs::write(&path, creds("old").to_string()).unwrap(); + std::env::set_var("UU_CONFIG", &path); + std::env::set_var("UU_LOGIN_WINDOW", "0"); + let writer = path.clone(); + tokio::spawn(async move { + tokio::time::sleep(Duration::from_millis(2500)).await; + std::fs::write(&writer, creds("new").to_string()).unwrap(); + }); + let got = tokio::time::timeout(Duration::from_secs(10), wait_for_credentials(Some("old".into()))).await.unwrap(); + assert_eq!(got.token, "new"); // the expired token in the file is not accepted + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn csrf_is_read_from_jwt_payload() { + use base64::Engine; + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"sub":"u","csrf":"c-1"}"#); + assert_eq!(csrf_from_token(&format!("h.{payload}.s")), Some("c-1".into())); + assert_eq!(csrf_from_token("bad"), None); + } + #[test] + fn generated_ids_are_uuid_shaped() { + let u = random_uuid(); + assert_eq!(u.len(), 36); + assert_eq!(u.as_bytes()[14], b'4'); + assert!(render_qr("https://example.com/x").unwrap().lines().count() > 10); + assert_eq!(gpu_label("NVIDIA Corporation GA102 [GeForce RTX 3090] (rev a1)"), "NVIDIA GeForce RTX 3090"); + assert_eq!(gpu_label("Advanced Micro Devices, Inc. [AMD/ATI] Navi 21 [Radeon RX 6800] (rev c1)"), "AMD Radeon RX 6800"); + assert_eq!(gpu_label("Advanced Micro Devices, Inc. [AMD/ATI] Navi 21 (rev c1)"), "Advanced Micro Devices, Inc. [AMD/ATI] Navi 21"); + let (rgba, edge) = qr_rgba("https://example.com/x", 3, 1).unwrap(); + assert_eq!(rgba.len(), edge * edge * 4); + assert_eq!(&rgba[..4], &[255, 255, 255, 255]); // quiet zone is light + assert_eq!(&rgba[(3 * edge + 3) * 4..(3 * edge + 3) * 4 + 3], &[0, 0, 0]); // finder corner is dark + } +} diff --git a/src/login_ui.rs b/src/login_ui.rs new file mode 100644 index 0000000..d493b26 --- /dev/null +++ b/src/login_ui.rs @@ -0,0 +1,78 @@ +//! Optional GTK3 window for `uuremote-server login` (c_engine/login_window.c). Built only when +//! gtk+-3.0 is available (cfg uu_gtk); otherwise, and with `--no-gui` or no display, every call +//! is a no-op and the terminal QR remains the only UI. + +#[cfg(uu_gtk)] +extern "C" { + fn uu_login_ui_start(name: *const libc::c_char, os: *const libc::c_char, cpu: *const libc::c_char, gpu: *const libc::c_char) -> libc::c_int; + fn uu_login_ui_set_qr(rgba: *const u8, edge: libc::c_int); + fn uu_login_ui_set_status(text: *const libc::c_char, kind: libc::c_int); + fn uu_login_ui_set_done(text: *const libc::c_char); + fn uu_login_ui_closed() -> libc::c_int; + fn uu_login_ui_close(); +} + +#[derive(Clone, Copy)] +pub enum Tone { Info = 0, Ok = 1, Error = 2 } + +pub struct LoginUi { shown: bool } + +#[cfg(uu_gtk)] +fn cstr(s: &str) -> std::ffi::CString { std::ffi::CString::new(s.replace('\0', "")).unwrap_or_default() } + +impl LoginUi { + pub fn none() -> Self { LoginUi { shown: false } } + + /// Opens the window when built with GTK and a display is present; falls back silently otherwise. + #[allow(unused_variables)] + pub fn open(name: &str, os: &str, cpu: &str, gpu: &str) -> Self { + #[cfg(uu_gtk)] + if std::env::var_os("DISPLAY").is_some() || std::env::var_os("WAYLAND_DISPLAY").is_some() { + let (n, o, c, g) = (cstr(name), cstr(os), cstr(cpu), cstr(gpu)); + if unsafe { uu_login_ui_start(n.as_ptr(), o.as_ptr(), c.as_ptr(), g.as_ptr()) } == 0 { + return LoginUi { shown: true }; + } + eprintln!("Login window unavailable; using the terminal QR code"); + } + LoginUi::none() + } + + pub fn shown(&self) -> bool { self.shown } + + #[allow(unused_variables)] + pub fn qr(&self, rgba: &[u8], edge: usize) { + #[cfg(uu_gtk)] + if self.shown && rgba.len() == edge * edge * 4 { unsafe { uu_login_ui_set_qr(rgba.as_ptr(), edge as libc::c_int) } } + } + + #[allow(unused_variables)] + pub fn status(&self, text: &str, tone: Tone) { + #[cfg(uu_gtk)] + if self.shown { let t = cstr(text); unsafe { uu_login_ui_set_status(t.as_ptr(), tone as libc::c_int) } } + } + + #[allow(unused_variables)] + pub fn done(&self, text: &str) { + #[cfg(uu_gtk)] + if self.shown { let t = cstr(text); unsafe { uu_login_ui_set_done(t.as_ptr()) } } + } + + pub fn closed(&self) -> bool { + #[cfg(uu_gtk)] + if self.shown { return unsafe { uu_login_ui_closed() } != 0; } + false + } + + /// Resolves when the user closes the window; never resolves without a window. + pub async fn wait_closed(&self) { + if !self.shown { return std::future::pending().await; } + while !self.closed() { tokio::time::sleep(std::time::Duration::from_millis(200)).await; } + } +} + +impl Drop for LoginUi { + fn drop(&mut self) { + #[cfg(uu_gtk)] + if self.shown { unsafe { uu_login_ui_close() } } + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9b489e2 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,345 @@ +//! UU Remote Pure Native Linux Server (Rust Edition) +//! Zero-Wine, Zero-Python, Single-Binary, 5 Native Tools Integrated + +mod desktop_backend; +mod portal; +mod network_diagnostics; +mod session_ice; +mod wayland; +mod auth; +mod config; +mod login; +mod login_ui; +mod session_lock; +mod capture; +mod file_trans; +mod input; +mod input_mapping; +mod port_forward; +mod power; +mod signaling; +mod terminal; +mod webrtc; +mod video; +mod capture_setting; +mod audio; +mod system_actions; +mod capability; +mod protocol; +mod control_protocol; +mod rtp_metadata; +mod initialization; +mod system_metrics; +mod clipboard; +mod clipboard_protocol; +mod clipboard_rich; +mod viewer_metrics; +mod cursor; + +use auth::{Credentials, UUAuthClient}; +mod clipboard_probe; +use capture::ScreenCapture; +use input::InputInjector; +use signaling::{SignalingClient, SignalingEvent, SoacMessage}; +use std::collections::HashMap; +use std::sync::Arc; +use tokio::sync::{mpsc, Mutex}; +use webrtc::WebRtcSession; + +#[tokio::main] +async fn main() -> Result<(), Box> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); + if std::env::args().nth(1).as_deref() == Some("clipboard-acceptance") { + return tokio::task::spawn_blocking(clipboard_probe::run).await?.map_err(Into::into); + } + if std::env::args().nth(1).as_deref() == Some("portal-acceptance") { + if std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default().trim()!="uu-hyprland-test" { + return Err("Portal input acceptance is restricted to the isolated test VM".into()); + } + let screen=ScreenCapture::new()?; + if screen.portal.is_none() { return Err("Portal acceptance requires the Portal backend".into()); } + // Give the consent dialog time to release focus before fixed lab events. + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + let input=InputInjector::new(); + input.bind_portal(screen.portal.clone()); + input.mouse_absolute_normalized(0.25,0.25,(screen.width,screen.height));input.flush_pointer(); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + input.mouse_absolute_normalized(0.5,0.5,(screen.width,screen.height));input.flush_pointer(); + input.mouse_button(1,true);input.mouse_button(1,false); + tokio::time::sleep(std::time::Duration::from_millis(100)).await; + input.mouse_relative(32,0);input.flush_pointer(); + for key in b"UUWAYLAND" { input.windows_key_event(i32::from(*key),true);input.windows_key_event(i32::from(*key),false); } + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + input.release_held(); + let report:serde_json::Value=serde_json::from_slice(&std::fs::read("/tmp/uuremote-input-acceptance.json")?)?; + for key in ["native_wayland","window_active","motion","click","keyboard","text_input"] { + if report.get(key).and_then(serde_json::Value::as_bool)!=Some(true) { return Err(format!("Portal native GTK acceptance failed: {key}").into()); } + } + println!("Portal native GTK input acceptance passed: motion/click/keyboard/text"); + let path=std::env::args().nth(2); + return video::probe((screen.width,screen.height),screen.display.clone(),screen.portal.clone(),path).await.map_err(|e|e.into()); + } + if std::env::args().nth(1).as_deref() == Some("wayland-input-probe") { + return wayland::input_probe().map_err(|e|e.into()); + } + if std::env::args().nth(1).as_deref() == Some("wayland-capture") { + return wayland::capture_stdout().map_err(|e| e.into()); + } + if std::env::args().nth(1).as_deref() == Some("desktop-probe") { + let screen=ScreenCapture::new()?; + capture::keep_display_awake()?; + let frame=screen.capture_frame()?; + if let Some(path)=std::env::args().nth(2) { + use std::io::Write; + let mut rgba=frame.clone(); + for pixel in rgba.chunks_exact_mut(4) { pixel.swap(0,2); pixel[3]=255; } + let png=cursor::encode_png(screen.width,screen.height,&rgba); + let mut file=std::fs::OpenOptions::new().write(true).create_new(true).open(path)?; + file.write_all(&png)?; + } + println!("backend={:?} width={} height={} frame_bytes={}",screen.backend,screen.width,screen.height,frame.len()); + return Ok(()); + } + if std::env::args().nth(1).as_deref() == Some("desktop-video-probe") { + let screen=ScreenCapture::new()?; + capture::keep_display_awake()?; + return video::probe((screen.width,screen.height),screen.display.clone(),screen.portal.clone(),std::env::args().nth(2)).await.map_err(|e|e.into()); + } + if std::env::args().nth(1).as_deref() == Some("unlock-check") { + return session_lock::check_from_stdin().map_err(|e| e.into()); + } + if std::env::args().nth(1).as_deref() == Some("login") { + // Interactive: register this host and bind it to an account via QR scan + // (GTK window when available; `login --no-gui` keeps it terminal-only). + let gui = !std::env::args().skip(2).any(|a| a == "--no-gui"); + if login::run(gui).await.is_err() { std::process::exit(1); } // error already shown + return Ok(()); + } + log::info!("Starting UU Remote Pure Native Rust Server v1.0.0..."); + + let mut capture = Arc::new((if desktop_backend::detect()?==desktop_backend::DesktopBackend::Portal + && std::env::var("UU_PORTAL_PREAUTHORIZE").ok().as_deref()!=Some("1") { + Err("Portal screen access requires a desktop connection and local consent".to_owned()) + } else { ScreenCapture::new() }).unwrap_or_else(|error| { + log::warn!("Desktop unavailable; terminal and file tools remain available: {error}"); + ScreenCapture::unavailable(error) + })); + let input = Arc::new(InputInjector::new()); + let _pointer_worker = input.start_pointer_worker(); + #[cfg(target_os="linux")] + { + let shutdown_input=input.clone(); + tokio::spawn(async move { + if let Ok(mut term)=tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + term.recv().await; shutdown_input.release_held(); terminal::shutdown_all(); std::process::exit(0); + } + }); + } + let creds = match config::file().and_then(Credentials::load) { + Ok(creds) => creds, + Err(e) => { + log::warn!("Not logged in: {e} ({} or UU_* environment variables)", config::path().display()); + login::wait_for_credentials(None).await + } + }; + let mut auth = Arc::new(UUAuthClient::new(creds)); + + // One peer per viewer connection (desktop, file transfer, terminal...), keyed by ice_id. + let webrtc_sessions: Arc>> = Arc::new(Mutex::new(HashMap::new())); + let mut next_capture_type: Option<(u64,crate::session_ice::SessionIce)> = None; + let mut capture_types: HashMap = HashMap::new(); + + loop { + log::info!("Requesting fresh room credentials from NetEase cloud..."); + let room_data = match auth.create_room().await { + Ok(data) => data, + Err(auth::RoomError::LoginExpired) => { + // Like the official client: an expired token needs a new QR login, not retries. + log::error!("UU login is invalid or expired; a new QR login is required"); + let stale = config::read_fresh().ok().flatten().and_then(|f| f.get("token").and_then(|t| t.as_str()).map(str::to_owned)); + auth = Arc::new(UUAuthClient::new(login::wait_for_credentials(stale).await)); + continue; + } + Err(e) => { + log::error!("Failed to create room: {}. Retrying in 5s...", e); + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + continue; + } + }; + + log::info!( + "Acquired room signaling target: {}", + room_data.signaling_server + ); + + let (tx_event, mut rx_event) = mpsc::channel::(64); + let tx_timer = tx_event.clone(); + let signaling_client = match SignalingClient::connect( + &room_data.signaling_server, + &room_data.token, + tx_event, + ) + .await + { + Ok(cli) => { + let renewal_peers=webrtc_sessions.clone(); + tokio::spawn(async move { + tokio::time::sleep(tokio::time::Duration::from_secs(900)).await; + loop { + if tx_timer.is_closed() { return; } + let active=renewal_peers.lock().await.values().any(|session| { + use ::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState; + session.pc.connection_state()==RTCPeerConnectionState::Connected + }); + if !active { + log::info!("Idle room renewal timer elapsed; refreshing signaling room"); + let _=tx_timer.send(SignalingEvent::Disconnected).await; return; + } + log::info!("Room renewal deferred while remote connection is active"); + tokio::time::sleep(tokio::time::Duration::from_secs(60)).await; + } + }); + Arc::new(cli) + } + Err(e) => { + log::error!("Failed to connect signaling: {}. Retrying in 5s...", e); + tokio::time::sleep(tokio::time::Duration::from_secs(5)).await; + continue; + } + }; + + // 事件处理主循环 + while let Some(evt) = rx_event.recv().await { + match evt { + SignalingEvent::Connected => { + log::info!("Signaling handshake established."); + } + SignalingEvent::RoomInfoAck(val) => { + log::info!( + "RoomInfo acknowledged by NetEase server: room_id={}", + val.get("room_id") + .and_then(|v| v.as_str()) + .unwrap_or("unknown") + ); + } + SignalingEvent::DeviceInfoChanged(val) => { + log::info!( + "Device status synchronized: status={:?}, availability={:?}", + val.get("data") + .and_then(|d| d.get("status")) + .and_then(|s| s.as_str()), + val.get("data") + .and_then(|d| d.get("publisher_availability_status")) + .and_then(|s| s.as_str()) + ); + } + SignalingEvent::ConnectRequest { capture_type, ice_id, transport } => { + // Pending cloud credentials live only within this room; cap + // requests that never receive an offer rather than retain them. + if capture_types.len()>=32 { capture_types.clear(); } + match ice_id { Some(id) => { capture_types.insert(id, (capture_type,transport)); } None => next_capture_type = Some((capture_type,transport)) } + } + SignalingEvent::BeControlled(val) => { + let _ = val; + log::info!("Incoming remote control session request; awaiting offer"); + } + + SignalingEvent::Soac(soac) => { + log::info!( + "SOAC signaling received: type={}, ice_id={:?}", + soac.msg_type, + soac.ice_id + ); + let ice = soac.ice_id.as_ref().map(|v| v.as_str().map(str::to_owned).unwrap_or_else(|| v.to_string())).unwrap_or_default(); + let mut sessions = webrtc_sessions.lock().await; + // Drop peers that already ended. + let ended: Vec = sessions.iter().filter(|(_, s)| matches!(s.pc.connection_state(), + ::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Closed | + ::webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState::Failed)).map(|(k, _)| k.clone()).collect(); + for k in ended { if let Some(old) = sessions.remove(&k) { let _ = old.pc.close().await; } } + + if soac.msg_type == "offer" { + let (capture_type,transport) = capture_types.remove(&ice).or_else(|| next_capture_type.take()).unwrap_or((1,crate::session_ice::SessionIce::default())); + // CaptureType: 0 unknown, 1 desktop, 2 window; 5 file transfer, 8 terminal, 9 port mapping. + let desktop = capture_type <= 2; + log::info!("Offer for connection: capture_type={} desktop={} active_peers={}", capture_type, desktop, sessions.len()); + if let Some(old) = sessions.remove(&ice) { let _ = old.pc.close().await; } + if desktop { + // One desktop stream at a time: a new desktop offer replaces stale ones. + let stale: Vec = sessions.iter().filter(|(_, s)| s.desktop).map(|(k, _)| k.clone()).collect(); + for k in stale { if let Some(old) = sessions.remove(&k) { let _ = old.pc.close().await; } } + } + let stale_portal=capture.portal.as_ref().is_some_and(|session|!session.is_alive()) + && crate::session_lock::locked_now() == Some(false); + let session_capture=if desktop && (capture.init_error.is_some() || stale_portal) { + if stale_portal { + input.release_held();input.bind_portal(None); + capture=Arc::new(ScreenCapture::unavailable("Portal authorization expired".into())); + } + match tokio::task::spawn_blocking(ScreenCapture::new).await { + Ok(Ok(screen))=>{ capture=Arc::new(screen);capture.clone() }, + Ok(Err(error))=>{ log::warn!("Desktop connection unavailable: {error}"); continue; }, + Err(_)=>{log::warn!("Desktop initialization worker failed");continue;}, + } + } else { capture.clone() }; + // Independent file/terminal peers must not detach the + // current desktop's authorized Portal input session. + if desktop { input.bind_portal(session_capture.portal.clone()); } + match WebRtcSession::new(session_capture, input.clone(), signaling_client.clone(), desktop, transport).await { + Ok(sess) => match sess.handle_offer(&soac).await { + Ok(answer_sdp) => { + log::info!("Local SDP Answer generated, emitting soac response..."); + let resp = SoacMessage { + msg_type: "answer".into(), + sdp: Some(answer_sdp), + gzip_sdp: None, + candidate: None, + ice_id: soac.ice_id.clone(), + sdp_mid: None, + sdp_mline_index: None, + client_id: soac.client_id.clone(), + app_control_id: soac.app_control_id.clone(), + }; + if let Err(e) = signaling_client.emit_soac(resp).await { log::error!("Answer signaling send failed: {}", e); } + sessions.insert(ice, sess); + } + Err(e) => { log::error!("Failed to handle offer: {}", e); let _ = sess.pc.close().await; } + }, + Err(e) => log::error!("Create peer failed: {}", e), + } + } else if soac.msg_type == "candidate" { + if let Some(sess) = sessions.get(&ice) { + if let Err(e) = sess.add_candidate(&soac).await { log::error!("Remote ICE candidate failed: {}", e); } + } else { + log::warn!("Remote ICE candidate for unknown connection"); + } + } + } + SignalingEvent::Released(val) | SignalingEvent::Left(val) => { + let ice = ["ice_id", "iceId"].iter().find_map(|k| val.get(*k).or_else(|| val.get("data").and_then(|d| d.get(*k)))) + .and_then(|v| v.as_str()).map(str::to_owned); + let keys: Vec = val.as_object().map(|o| o.keys().take(16).cloned().collect()).unwrap_or_default(); + let mut sessions = webrtc_sessions.lock().await; + let targets: Vec = match &ice { + Some(id) if sessions.contains_key(id) => vec![id.clone()], + _ => sessions.keys().cloned().collect(), + }; + log::info!("Remote controller disconnected: keys={:?} ice_matched={} closing={}", keys, ice.as_ref().is_some_and(|i| sessions.contains_key(i)), targets.len()); + for k in targets { + if let Some(old) = sessions.remove(&k) { + if let Err(e) = old.pc.close().await { log::warn!("Close released peer failed: {}", e); } + } + } + } + SignalingEvent::Disconnected => { + capture_types.clear(); + next_capture_type=None; + log::warn!("Signaling connection lost. Initiating reconnect loop..."); + break; + } + } + } + + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; + } +} diff --git a/src/network_diagnostics.rs b/src/network_diagnostics.rs new file mode 100644 index 0000000..5299717 --- /dev/null +++ b/src/network_diagnostics.rs @@ -0,0 +1,227 @@ +//! Address-free ICE path diagnostics. A host pair may still traverse a VPN; +//! `direct` means no ICE relay candidate, not proof of a shared LAN. +use std::sync::{atomic::{AtomicU64, Ordering}, Weak}; +use std::time::Instant; +use webrtc::peer_connection::{RTCPeerConnection, peer_connection_state::RTCPeerConnectionState}; +use webrtc::stats::StatsReportType; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CandidateSummary { + pub protocol: &'static str, + pub kind: &'static str, +} + +fn protocol(value: &str) -> &'static str { + if value.eq_ignore_ascii_case("udp") { "udp" } + else if value.eq_ignore_ascii_case("tcp") { "tcp" } + else { "unknown" } +} +fn kind(value: &str) -> &'static str { + match value { "host" => "host", "srflx" => "srflx", "prflx" => "prflx", "relay" => "relay", _ => "unknown" } +} + +/// Parse only protocol/type from an SDP candidate. Never return arbitrary input. +pub fn candidate_summary(sdp: &str) -> CandidateSummary { + let fields: Vec<_> = sdp.split_whitespace().collect(); + CandidateSummary { + protocol: fields.get(2).map_or("unknown", |v| protocol(v)), + kind: if fields.get(6) == Some(&"typ") { fields.get(7).map_or("unknown", |v| kind(v)) } else { "unknown" }, + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PathSummary { + pub local: CandidateSummary, + pub remote: CandidateSummary, + pub route: &'static str, +} + +/// webrtc 0.10 keeps RTCIceCandidatePair fields private. Its Display is +/// `(local) <-> (remote) ...`. Restrict output to +/// allowlisted enums; fail closed if upstream changes this representation. +fn selected_pair_summary(display: &str) -> Option { + let (local, remote) = display.strip_prefix("(local) ")?.split_once(" <-> (remote) ")?; + fn side(value: &str) -> CandidateSummary { + let mut fields = value.split_whitespace(); + CandidateSummary { protocol: protocol(fields.next().unwrap_or("")), kind: kind(fields.next().unwrap_or("")) } + } + let local = side(local); + let remote = side(remote); + let route = if local.kind == "relay" || remote.kind == "relay" { "relay" } + else if local.kind == "unknown" || remote.kind == "unknown" || local.protocol == "unknown" || remote.protocol == "unknown" { "unknown" } + else { "direct" }; + Some(PathSummary { local, remote, route }) +} + +pub async fn selected_path(pc: &RTCPeerConnection) -> Option { + let transport = pc.dtls_transport(); + let pair = transport.ice_transport().get_selected_candidate_pair().await?; + Some(selected_pair_summary(&pair.to_string()).unwrap_or(PathSummary { + local: CandidateSummary { protocol: "unknown", kind: "unknown" }, + remote: CandidateSummary { protocol: "unknown", kind: "unknown" }, + route: "unknown", + })) +} + +#[derive(Default)] +struct RateCounter { previous: Option<(Instant, u64, u64)> } +impl RateCounter { + fn sample(&mut self, now: Instant, sent: u64, received: u64) -> Option<(u64, u64)> { + let old = self.previous.replace((now, sent, received))?; + let seconds = now.checked_duration_since(old.0)?.as_secs_f64(); + if seconds <= 0.0 || sent < old.1 || received < old.2 { return None; } + Some((((sent - old.1) as f64 * 8.0 / seconds) as u64, ((received - old.2) as f64 * 8.0 / seconds) as u64)) + } +} + +static SESSION_SEQUENCE: AtomicU64 = AtomicU64::new(1); + +/// Spawn once per peer. Weak ownership and closed-state exit prevent leaked +/// peer sessions. Reconnects reset counters. No IP, candidate ID or SDP is logged. +pub fn start(peer: Weak) { + let session = SESSION_SEQUENCE.fetch_add(1, Ordering::Relaxed); + tokio::spawn(async move { + let mut interval = tokio::time::interval(std::time::Duration::from_secs(5)); + interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut rate = RateCounter::default(); + let mut last_path = None; + let mut ticks = 0; + loop { + interval.tick().await; + let Some(pc) = peer.upgrade() else { break }; + let state = pc.connection_state(); + if state == RTCPeerConnectionState::Closed { break; } + if state != RTCPeerConnectionState::Connected { + rate = RateCounter::default(); + last_path = None; + continue; + } + let Some(path) = selected_path(&pc).await else { continue }; + let report = pc.get_stats().await; + let (mut sent, mut received) = (0u64, 0u64); + for stats in report.reports.values() { + // SCTPTransport repeats the same ICE totals; count Transport only. + if let StatsReportType::Transport(stats) = stats { + sent = sent.saturating_add(stats.bytes_sent as u64); + received = received.saturating_add(stats.bytes_received as u64); + } + } + let rates = rate.sample(Instant::now(), sent, received); + ticks += 1; + if last_path != Some(path) || ticks % 6 == 0 { + log::info!("ICE path: session={} route={} local={}/{} remote={}/{} tx_bps={:?} rx_bps={:?} rtt=unavailable", + session, path.route, path.local.protocol, path.local.kind, path.remote.protocol, path.remote.kind, + rates.map(|r| r.0), rates.map(|r| r.1)); + // webrtc-ice 0.10 candidate-pair RTT/packet/byte fields are zero + // placeholders, not measured metrics. Do not publish them. + last_path = Some(path); + } + } + }); +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn parses_real_pair_format_and_both_relay_sides() { + use webrtc::ice_transport::{ice_candidate::RTCIceCandidate, ice_candidate_pair::RTCIceCandidatePair, ice_candidate_type::RTCIceCandidateType, ice_protocol::RTCIceProtocol}; + for (local, remote, expected) in [ + (RTCIceCandidateType::Host, RTCIceCandidateType::Srflx, "direct"), + (RTCIceCandidateType::Relay, RTCIceCandidateType::Host, "relay"), + (RTCIceCandidateType::Host, RTCIceCandidateType::Relay, "relay"), + (RTCIceCandidateType::Unspecified, RTCIceCandidateType::Host, "unknown"), + ] { + let candidate = |typ| RTCIceCandidate { typ, protocol: RTCIceProtocol::Udp, address: "192.0.2.42".into(), port: 1234, ..Default::default() }; + let summary = selected_pair_summary(&RTCIceCandidatePair::new(candidate(local), candidate(remote)).to_string()).unwrap(); + assert_eq!(summary.route, expected); + assert!(!format!("{summary:?}").contains("192.0.2.42")); + } + } + #[test] + fn candidate_log_is_allowlisted() { + let summary = candidate_summary("candidate:x 1 UDP 123 192.0.2.5 4444 typ relay raddr 10.0.0.1 rport 123 ufrag secret"); + assert_eq!(summary, CandidateSummary { protocol: "udp", kind: "relay" }); + assert_eq!(candidate_summary("malformed secret"), CandidateSummary { protocol: "unknown", kind: "unknown" }); + assert!(selected_pair_summary("unexpected secret").is_none()); + } + #[test] + fn rates_reset_on_counter_restart() { + let mut rates = RateCounter::default(); + let now = Instant::now(); + assert_eq!(rates.sample(now, 100, 200), None); + assert_eq!(rates.sample(now + std::time::Duration::from_secs(2), 300, 300), Some((800, 400))); + assert_eq!(rates.sample(now + std::time::Duration::from_secs(3), 0, 0), None); + } + + /// Exercises actual ICE nomination and SCTP delivery between local peers, without + /// login, public STUN, external endpoints or production configuration. + #[tokio::test] + #[ignore = "opens local UDP sockets; run explicitly for network acceptance"] + async fn local_selected_pair_and_payload() { + use std::sync::Arc; + use webrtc::api::{APIBuilder, setting_engine::SettingEngine}; + use webrtc::peer_connection::configuration::RTCConfiguration; + let mut settings = SettingEngine::default(); + // This crate excludes loopback addresses during ICE gathering. Both + // peers still run in this process and use only gathered local addresses. + settings.set_ice_multicast_dns_mode(webrtc::ice::mdns::MulticastDnsMode::Disabled); + let mut media = webrtc::api::media_engine::MediaEngine::default(); + media.register_default_codecs().unwrap(); + let api = APIBuilder::new().with_media_engine(media).with_setting_engine(settings).build(); + let left = Arc::new(api.new_peer_connection(RTCConfiguration::default()).await.unwrap()); + let right = Arc::new(api.new_peer_connection(RTCConfiguration::default()).await.unwrap()); + for (label, peer) in [("left", &left), ("right", &right)] { + peer.on_peer_connection_state_change(Box::new(move |state| { + eprintln!("isolated ICE probe {label}: {state}"); + Box::pin(async {}) + })); + } + let (received_tx, mut received_rx) = tokio::sync::mpsc::channel(1); + right.on_data_channel(Box::new(move |channel| { + let tx = received_tx.clone(); + Box::pin(async move { + channel.on_message(Box::new(move |message| { + let tx = tx.clone(); + Box::pin(async move { let _ = tx.send(message.data).await; }) + })); + }) + })); + let channel = left.create_data_channel("network-acceptance", None).await.unwrap(); + let sender = Arc::downgrade(&channel); + channel.on_open(Box::new(move || { + let sender = sender.clone(); + Box::pin(async move { + if let Some(channel) = sender.upgrade() { + channel.send(&bytes::Bytes::from_static(b"isolated-ice-probe")).await.unwrap(); + } + }) + })); + let acceptance = async { + let mut gathered = left.gathering_complete_promise().await; + left.set_local_description(left.create_offer(None).await.unwrap()).await.unwrap(); + let _ = gathered.recv().await; + eprintln!("left SDP candidate count={}", left.local_description().await.unwrap().sdp.lines().filter(|s| s.starts_with("a=candidate:")).count()); + right.set_remote_description(left.local_description().await.unwrap()).await.unwrap(); + let mut gathered = right.gathering_complete_promise().await; + right.set_local_description(right.create_answer(None).await.unwrap()).await.unwrap(); + let _ = gathered.recv().await; + eprintln!("right SDP candidate count={}", right.local_description().await.unwrap().sdp.lines().filter(|s| s.starts_with("a=candidate:")).count()); + left.set_remote_description(right.local_description().await.unwrap()).await.unwrap(); + eprintln!("isolated ICE probe: descriptions exchanged"); + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + eprintln!("isolated ICE probe: left_ice={} right_ice={} selected={:?}", left.ice_connection_state(), right.ice_connection_state(), selected_path(&left).await); + assert_eq!(received_rx.recv().await.unwrap().as_ref(), b"isolated-ice-probe"); + let path = selected_path(&left).await.unwrap(); + assert_eq!(path.route, "direct"); + assert_eq!(path.local.kind, "host"); + assert_eq!(path.remote.kind, "host"); + let stats = left.get_stats().await; + assert!(stats.reports.values().any(|v| matches!(v, StatsReportType::Transport(t) if t.bytes_sent > 0 && t.bytes_received > 0))); + }; + let outcome = tokio::time::timeout(std::time::Duration::from_secs(15), acceptance).await; + left.close().await.unwrap(); + right.close().await.unwrap(); + outcome.expect("isolated local ICE/SCTP did not connect within 15 seconds"); + } +} diff --git a/src/port_forward.rs b/src/port_forward.rs new file mode 100644 index 0000000..74ebfff --- /dev/null +++ b/src/port_forward.rs @@ -0,0 +1,61 @@ +//! Native TCP Port Forwarding & SSH Tunneling via DataChannel + +use std::sync::Arc; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; +use tokio::sync::Mutex; +use webrtc::data_channel::data_channel_message::DataChannelMessage; +use webrtc::data_channel::RTCDataChannel; + +pub struct PortForwarder; + +impl PortForwarder { + /// 将 DataChannel 桥接到本地指定 TCP 端口(默认 127.0.0.1:22 SSH) + pub async fn bridge_tcp( + target_addr: &str, + channel: Arc, + ) -> Result<(), String> { + let stream = TcpStream::connect(target_addr) + .await + .map_err(|e| format!("Failed to connect to {}: {}", target_addr, e))?; + + log::info!("Connected to local service {}", target_addr); + let (mut tcp_read, mut tcp_write) = stream.into_split(); + let channel_for_write = channel.clone(); + + // 协程 1: 从本地 TCP (如 SSH) 读取数据并写入 DataChannel + tokio::spawn(async move { + let mut buf = [0u8; 4096]; + loop { + match tcp_read.read(&mut buf).await { + Ok(0) => break, + Ok(n) => { + let bytes = bytes::Bytes::copy_from_slice(&buf[..n]); + if let Err(e) = channel_for_write.send(&bytes).await { + log::warn!("DataChannel send failed: {}", e); + break; + } + } + Err(e) => { + log::warn!("TCP read error: {}", e); + break; + } + } + } + }); + + // 协程 2: 绑定 DataChannel on_message 写入本地 TCP + let tcp_write = Arc::new(Mutex::new(tcp_write)); + let tcp_write_clone = tcp_write.clone(); + + channel.on_message(Box::new(move |msg: DataChannelMessage| { + let tcp = tcp_write_clone.clone(); + Box::pin(async move { + let mut lock = tcp.lock().await; + let _ = lock.write_all(&msg.data).await; + }) + })); + + Ok(()) + } +} diff --git a/src/portal.rs b/src/portal.rs new file mode 100644 index 0000000..0b8c595 --- /dev/null +++ b/src/portal.rs @@ -0,0 +1,182 @@ +//! GNOME/KDE portal session. Capture and input must share this Arc; do not +//! recreate it in an encoder subprocess (that would request consent again). +use std::sync::Arc; +#[cfg(unix)] +#[path = "portal_permissions.rs"] +mod permissions; + +#[cfg(all(target_os = "linux", feature = "portal"))] +mod native { + use std::{ffi::c_void, ptr::NonNull, sync::Mutex}; + extern "C" { + fn uu_portal_open_persist(restore: *const libc::c_char, save: extern "C" fn(*const libc::c_char, *mut c_void), data: *mut c_void, error: *mut i32, width: *mut u32, height: *mut u32) -> *mut c_void; + fn uu_portal_clipboard_ready(portal: *mut c_void) -> i32; + fn uu_portal_clipboard_set(portal: *mut c_void, text: *const u8, length: usize) -> i32; + fn uu_portal_clipboard_poll(portal: *mut c_void, text: *mut u8, capacity: usize) -> i32; + fn uu_portal_close(portal: *mut c_void); + fn uu_portal_alive(portal: *mut c_void) -> i32; + fn uu_portal_reset_frame(portal: *mut c_void); + fn uu_portal_capture(portal: *mut c_void, bgra: *mut u8, length: usize) -> i32; + fn uu_portal_move(portal: *mut c_void, x: f64, y: f64, relative: i32) -> i32; + fn uu_portal_button(portal: *mut c_void, button: i32, pressed: i32) -> i32; + fn uu_portal_key(portal: *mut c_void, keysym: u32, pressed: i32) -> i32; + } + struct Handle(NonNull); + // The engine owns callback threads; public calls are serialized by Mutex. + unsafe impl Send for Handle {} + impl Drop for Handle { fn drop(&mut self) { unsafe { uu_portal_close(self.0.as_ptr()) } } } + pub struct Session { handle: Mutex, locked: tokio::sync::watch::Receiver>, was_locked: std::sync::atomic::AtomicBool, retry_at: Mutex>, pub width: u32, pub height: u32 } + impl Session { + pub fn is_alive(&self) -> bool { + self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_alive(handle.0.as_ptr()) != 0 }) + } + pub fn open() -> Result { + let (mut error, mut width, mut height) = (0, 0, 0); + let directory = super::permissions::directory(); + let key = super::permissions::desktop_key(); + let token = directory.as_deref().and_then(|dir| super::permissions::take(dir, key)) + .and_then(|value| std::ffi::CString::new(value).ok()); + let mut cache = (directory, key); + extern "C" fn save_token(token: *const libc::c_char, data: *mut c_void) { + // Callback is synchronous during open; cache lives through the call. + let result = std::panic::catch_unwind(|| unsafe { + let cache = &*(data as *const (Option, &'static str)); + if let (Some(dir), Ok(value)) = (cache.0.as_deref(), std::ffi::CStr::from_ptr(token).to_str()) { + if super::permissions::save(dir, cache.1, value).is_err() { log::warn!("Portal permission cache could not be saved"); } + } + }); + if result.is_err() { log::warn!("Portal permission cache callback failed"); } + } + let pointer = unsafe { uu_portal_open_persist(token.as_ref().map_or(std::ptr::null(), |v| v.as_ptr()), save_token, &mut cache as *mut _ as *mut c_void, &mut error, &mut width, &mut height) }; + let handle = NonNull::new(pointer).ok_or_else(|| super::error(error))?; + Ok(Self { handle: Mutex::new(Handle(handle)), locked: crate::session_lock::watch_locked(), was_locked: std::sync::atomic::AtomicBool::new(true), retry_at: Mutex::new(None), width, height }) + } + pub fn capture(&self, frame: &mut [u8]) -> Result<(), String> { + let mut handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?; + let locked = *self.locked.borrow() != Some(false); + if locked || self.was_locked.swap(locked, std::sync::atomic::Ordering::AcqRel) { + self.was_locked.store(locked, std::sync::atomic::Ordering::Release); + unsafe { uu_portal_reset_frame(handle.0.as_ptr()) }; + super::blank(frame); return Ok(()); + } + if unsafe { uu_portal_alive(handle.0.as_ptr()) } == 0 { + // GNOME can close the stream before the periodic lock watcher updates. + if crate::session_lock::locked_now() != Some(false) { + self.was_locked.store(true, std::sync::atomic::Ordering::Release); + super::blank(frame); return Ok(()); + } + // logind's LockedHint can lag compositor stream closure. Give it a + // full watcher interval before attempting another permission session. + let mut retry = self.retry_at.lock().map_err(|_| "Portal recovery lock poisoned")?; + let deadline = retry.get_or_insert_with(|| std::time::Instant::now() + std::time::Duration::from_secs(1)); + if std::time::Instant::now() < *deadline { super::blank(frame); return Ok(()); } + let replacement = match Self::open() { + Ok(value) => value, + Err(error) => { + log::warn!("Portal capture recovery deferred: {error}"); + *retry = Some(std::time::Instant::now() + std::time::Duration::from_secs(5)); + super::blank(frame); return Ok(()); + } + }; + *retry = None; + if replacement.width != self.width || replacement.height != self.height { + return Err("Portal dimensions changed; reconnect required".into()); + } + *handle = replacement.handle.into_inner().map_err(|_| "Portal session lock poisoned")?; + log::info!("Portal capture session restored after closure"); + } + let code = unsafe { uu_portal_capture(handle.0.as_ptr(), frame.as_mut_ptr(), frame.len()) }; + if code == 10 || code == 9 { super::blank(frame); Ok(()) } else { super::check(code) } + } + + pub fn clipboard_ready(&self) -> bool { + self.handle.lock().is_ok_and(|handle| unsafe { uu_portal_clipboard_ready(handle.0.as_ptr()) != 0 }) + } + pub fn clipboard_set(&self, text: &str) -> Result<(), String> { + if text.len()>crate::clipboard::MAX_TEXT || *self.locked.borrow()!=Some(false) { return Err("Portal clipboard unavailable".into()); } + let handle=self.handle.lock().map_err(|_| "Portal session lock poisoned")?; + if unsafe { uu_portal_clipboard_set(handle.0.as_ptr(),text.as_ptr(),text.len()) }==0 {Ok(())} else {Err("Portal clipboard ownership failed".into())} + } + pub fn clipboard_poll(&self) -> Option { + if *self.locked.borrow()!=Some(false) { return None; } + let handle=self.handle.lock().ok()?; + let mut bytes=vec![0;crate::clipboard::MAX_TEXT]; + let length=unsafe { uu_portal_clipboard_poll(handle.0.as_ptr(),bytes.as_mut_ptr(),bytes.len()) }; + if length<0 { return None; } + bytes.truncate(length as usize); String::from_utf8(bytes).ok() + } + pub fn move_pointer(&self, x: f64, y: f64, relative: bool) -> Result<(), String> { + if *self.locked.borrow() != Some(false) { return Err("Portal input blocked while locked".into()); } + let handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?; + super::check(unsafe { uu_portal_move(handle.0.as_ptr(), x, y, i32::from(relative)) }) + } + pub fn button(&self, button: i32, pressed: bool) -> Result<(), String> { + if pressed && *self.locked.borrow() != Some(false) { return Err("Portal input blocked while locked".into()); } + let handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?; + super::check(unsafe { uu_portal_button(handle.0.as_ptr(), button, i32::from(pressed)) }) + } + pub fn key(&self, symbol: u64, pressed: bool) -> Result<(), String> { + if pressed && *self.locked.borrow() != Some(false) { return Err("Portal input blocked while locked".into()); } + let symbol = u32::try_from(symbol).map_err(|_| "Invalid Portal keysym")?; + let handle = self.handle.lock().map_err(|_| "Portal session lock poisoned")?; + super::check(unsafe { uu_portal_key(handle.0.as_ptr(), symbol, i32::from(pressed)) }) + } + } +} + +fn blank(frame: &mut [u8]) { for pixel in frame.chunks_exact_mut(4) { pixel.copy_from_slice(&[0, 0, 0, 255]); } } + +fn error(code: i32) -> String { + let reason = match code { + 1 => "session bus unavailable", 2 => "RemoteDesktop/ScreenCast portal unavailable", + 3 => "request failed", 4 => "permission cancelled or denied", 5 => "permission request timed out", + 6 => "single monitor and keyboard/pointer permission required", 7 => "PipeWire connection failed", + 8 => "unsupported frame format or size", 9 => "session closed or stream lost", + 10 => "frame unavailable", 11 => "invalid input or frame buffer", _ => "operation failed", + }; + format!("Portal {reason} (code {code})") +} +fn check(code: i32) -> Result<(), String> { if code == 0 { Ok(()) } else { Err(error(code)) } } + +#[cfg(all(target_os = "linux", feature = "portal"))] +pub use native::Session as PortalSession; +#[cfg(not(all(target_os = "linux", feature = "portal")))] +pub struct PortalSession { pub width: u32, pub height: u32 } +#[cfg(not(all(target_os = "linux", feature = "portal")))] +impl PortalSession { + pub fn clipboard_ready(&self) -> bool { false } + pub fn clipboard_set(&self, _: &str) -> Result<(), String> { Err(error(2)) } + pub fn clipboard_poll(&self) -> Option { None } + pub fn is_alive(&self) -> bool { false } + pub fn open() -> Result { Err("Portal backend requires Linux and --features portal".into()) } + pub fn capture(&self, _: &mut [u8]) -> Result<(), String> { Err(error(2)) } + pub fn move_pointer(&self, _: f64, _: f64, _: bool) -> Result<(), String> { Err(error(2)) } + pub fn button(&self, _: i32, _: bool) -> Result<(), String> { Err(error(2)) } + pub fn key(&self, _: u64, _: bool) -> Result<(), String> { Err(error(2)) } +} + +/// Forward frames in-process into encoder stdin. Cancellation drops the Arc; +/// the caller keeps one owning Arc for all subsequent desktop reconnects. +pub fn write_frames(session: Arc, mut output: impl std::io::Write, cancelled: &std::sync::atomic::AtomicBool) -> Result<(), String> { + let length = (session.width as usize).checked_mul(session.height as usize).and_then(|n| n.checked_mul(4)).ok_or("Portal frame too large")?; + let mut frame = vec![0; length]; + let interval = std::time::Duration::from_nanos(1_000_000_000 / crate::video::FPS); + while !cancelled.load(std::sync::atomic::Ordering::Acquire) { + let started = std::time::Instant::now(); + session.capture(&mut frame)?; + output.write_all(&frame).map_err(|_| "Portal encoder input closed")?; + if let Some(left) = interval.checked_sub(started.elapsed()) { std::thread::sleep(left); } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + #[test] + fn locked_frames_hide_old_content() { let mut frame = [42; 8]; super::blank(&mut frame); assert_eq!(frame, [0,0,0,255,0,0,0,255]); } + #[test] + fn errors_never_include_remote_messages_or_identifiers() { + assert!(super::check(4).unwrap_err().contains("cancelled or denied")); + assert!(super::check(9).unwrap_err().contains("closed or stream lost")); + } +} diff --git a/src/portal_permissions.rs b/src/portal_permissions.rs new file mode 100644 index 0000000..00351bc --- /dev/null +++ b/src/portal_permissions.rs @@ -0,0 +1,71 @@ +//! Single-use Portal permissions. Never log the token or reuse it after an attempt. +use std::{fs::{self, OpenOptions}, io::{Read, Write}, path::{Path, PathBuf}}; +use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; + +pub fn directory() -> Option { + let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from) + .filter(|p| p.is_absolute()).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?; + let dir = base.join("uuremote/portal-permissions"); + // Reject symlinks in the parent chain; do not redirect credential storage. + for parent in dir.ancestors() { + if let Ok(meta) = fs::symlink_metadata(parent) { + if meta.file_type().is_symlink() { return None; } + } + } + fs::create_dir_all(&dir).ok()?; + fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).ok()?; + let meta = fs::symlink_metadata(&dir).ok()?; + (meta.is_dir() && meta.uid() == unsafe { libc::getuid() }).then_some(dir) +} + +pub fn desktop_key() -> &'static str { + let desktop = std::env::var("XDG_CURRENT_DESKTOP").unwrap_or_default().to_lowercase(); + if desktop.split(':').any(|v| v == "kde") { "kde" } else { "gnome" } +} + +pub fn take(dir: &Path, key: &str) -> Option { + let path = dir.join(key); + let mut file = OpenOptions::new().read(true).custom_flags(libc::O_NOFOLLOW).open(&path).ok()?; + let meta = file.metadata().ok()?; + if !meta.is_file() || meta.uid() != unsafe { libc::getuid() } || meta.mode() & 0o077 != 0 || meta.len() > 4096 { return None; } + let mut token = String::new(); + file.read_to_string(&mut token).ok()?; + // Consume before contacting the Portal: a timeout may still consume the upstream token. + fs::remove_file(path).ok()?; + (!token.is_empty() && !token.contains('\0')).then_some(token) +} + +pub fn save(dir: &Path, key: &str, token: &str) -> std::io::Result<()> { + if token.is_empty() || token.len() > 4096 || token.contains('\0') { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)); + } + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let temp = dir.join(format!(".{}.{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed))); + let result = (|| { + let mut file = OpenOptions::new().write(true).create_new(true).mode(0o600).open(&temp)?; + file.write_all(token.as_bytes())?; file.sync_all()?; + fs::rename(&temp, dir.join(key))?; + std::fs::File::open(dir)?.sync_all() + })(); + if result.is_err() { let _ = fs::remove_file(temp); } + result +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn permissions_are_private_single_use_and_reject_symlinks() { + let dir = std::env::temp_dir().join(format!("uu-portal-cache-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + save(&dir, "kde", "test-token").unwrap(); + assert_eq!(fs::metadata(dir.join("kde")).unwrap().mode() & 0o777, 0o600); + assert_eq!(take(&dir, "kde").as_deref(), Some("test-token")); + assert!(take(&dir, "kde").is_none()); + save(&dir, "gnome", "second-token").unwrap(); + std::os::unix::fs::symlink(dir.join("gnome"), dir.join("kde")).unwrap(); + assert!(take(&dir, "kde").is_none()); + assert!(save(&dir, "gnome", &"x".repeat(4097)).is_err()); + fs::remove_dir_all(dir).unwrap(); + } +} diff --git a/src/power.rs b/src/power.rs new file mode 100644 index 0000000..61d1893 --- /dev/null +++ b/src/power.rs @@ -0,0 +1,35 @@ +//! Native System Power Management (Reboot & Shutdown) + +use std::process::Command; + +pub struct PowerManager; + +impl PowerManager { + pub fn reboot() -> Result<(), String> { + log::info!("Executing system reboot command..."); + let status = Command::new("systemctl") + .arg("reboot") + .status() + .map_err(|e| format!("Failed to invoke systemctl reboot: {}", e))?; + + if status.success() { + Ok(()) + } else { + Err(format!("systemctl reboot exited with status {}", status)) + } + } + + pub fn shutdown() -> Result<(), String> { + log::info!("Executing system poweroff command..."); + let status = Command::new("systemctl") + .arg("poweroff") + .status() + .map_err(|e| format!("Failed to invoke systemctl poweroff: {}", e))?; + + if status.success() { + Ok(()) + } else { + Err(format!("systemctl poweroff exited with status {}", status)) + } + } +} diff --git a/src/protocol.rs b/src/protocol.rs new file mode 100644 index 0000000..301b7c1 --- /dev/null +++ b/src/protocol.rs @@ -0,0 +1,108 @@ +//! Dependency-free protobuf wire inspection for the official binary control channel. +//! This decodes fields only. It intentionally assigns no heartbeat/input semantics +//! and sends no acknowledgements: those require evidence from the application +//! callback above libstreamer::ControlledControlDataHandler::OnReceiveData. + +#[derive(Debug, PartialEq, Eq)] +pub enum WireValue<'a> { + Varint(u64), + Fixed64([u8; 8]), + Bytes(&'a [u8]), + Fixed32([u8; 4]), +} + +#[derive(Debug, PartialEq, Eq)] +pub struct WireField<'a> { + pub number: u32, + pub value: WireValue<'a>, +} + +#[derive(Debug, PartialEq, Eq)] +pub enum WireError { + Truncated, + VarintOverflow, + InvalidField, + UnsupportedWireType(u8), +} + +fn varint(input: &[u8], offset: &mut usize) -> Result { + let mut result = 0; + for shift in (0..70).step_by(7) { + let byte = *input.get(*offset).ok_or(WireError::Truncated)?; + *offset += 1; + if shift == 63 && byte > 1 { + return Err(WireError::VarintOverflow); + } + result |= u64::from(byte & 127) << shift; + if byte & 128 == 0 { + return Ok(result); + } + } + Err(WireError::VarintOverflow) +} + +fn take<'a>(input: &'a [u8], offset: &mut usize, length: usize) -> Result<&'a [u8], WireError> { + let end = offset.checked_add(length).ok_or(WireError::Truncated)?; + let value = input.get(*offset..end).ok_or(WireError::Truncated)?; + *offset = end; + Ok(value) +} + +/// Inspect a complete protobuf message, preserving opaque nested payloads. +/// Deprecated groups are rejected. No payload contents should be logged. +pub fn decode_wire(input: &[u8]) -> Result>, WireError> { + let mut offset = 0; + let mut fields = Vec::new(); + while offset < input.len() { + let key = varint(input, &mut offset)?; + let number = key >> 3; + if number == 0 || number > 0x1fff_ffff { + return Err(WireError::InvalidField); + } + let value = match (key & 7) as u8 { + 0 => WireValue::Varint(varint(input, &mut offset)?), + 1 => WireValue::Fixed64(take(input, &mut offset, 8)?.try_into().unwrap()), + 2 => { + let length = usize::try_from(varint(input, &mut offset)?) + .map_err(|_| WireError::Truncated)?; + WireValue::Bytes(take(input, &mut offset, length)?) + } + 5 => WireValue::Fixed32(take(input, &mut offset, 4)?.try_into().unwrap()), + wire => return Err(WireError::UnsupportedWireType(wire)), + }; + fields.push(WireField { number: number as u32, value }); + } + Ok(fields) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preserves_mixed_unknown_fields_and_nested_bytes() { + let bytes = [8, 150, 1, 18, 2, 8, 3, 29, 1, 2, 3, 4]; + assert_eq!(decode_wire(&bytes), Ok(vec![ + WireField { number: 1, value: WireValue::Varint(150) }, + WireField { number: 2, value: WireValue::Bytes(&[8, 3]) }, + WireField { number: 3, value: WireValue::Fixed32([1, 2, 3, 4]) }, + ])); + } + + #[test] + fn rejects_truncation_and_u64_overflow() { + assert_eq!(decode_wire(&[18, 4, 1]), Err(WireError::Truncated)); + assert_eq!(decode_wire(&[8, 128]), Err(WireError::Truncated)); + let mut bytes = vec![8]; + bytes.extend_from_slice(&[255; 9]); + bytes.push(2); + assert_eq!(decode_wire(&bytes), Err(WireError::VarintOverflow)); + } + + #[test] + fn rejects_invalid_fields_and_groups() { + assert_eq!(decode_wire(&[0]), Err(WireError::InvalidField)); + assert_eq!(decode_wire(&[11]), Err(WireError::UnsupportedWireType(3))); + assert_eq!(decode_wire(&[255, 255, 255, 255, 31]), Err(WireError::InvalidField)); + } +} diff --git a/src/rtp_metadata.rs b/src/rtp_metadata.rs new file mode 100644 index 0000000..2852514 --- /dev/null +++ b/src/rtp_metadata.rs @@ -0,0 +1,65 @@ +//! UU capture-source metadata used by the official streaming core. +//! URI and big-endian uint16 layout are verified in the official ARM64 library. +//! Source index 0 is this implementation's sole primary capture source. +use webrtc::rtp::extension::HeaderExtension; +use webrtc::util::{Marshal, MarshalSize}; + +pub const CAPTURE_INDEX_URI: &str = + "http://www.webrtc.org/experiments/rtp-hdrext/video-capture-index"; +pub const NEW_FRAME_URI: &str = + "http://www.webrtc.org/experiments/rtp-hdrext/video-frame-is-new-frame"; + +pub struct NewFrame(pub bool); +impl MarshalSize for NewFrame { fn marshal_size(&self) -> usize { 1 } } +impl Marshal for NewFrame { + fn marshal_to(&self, buffer: &mut [u8]) -> webrtc::util::Result { + let byte = buffer.first_mut().ok_or_else(|| webrtc::util::Error::Other("New frame buffer too short".into()))?; + *byte = u8::from(self.0); + Ok(1) + } +} +pub fn new_frame() -> HeaderExtension { + HeaderExtension::Custom { uri: NEW_FRAME_URI.into(), extension: Box::new(NewFrame(true)) } +} + +#[derive(Debug)] +pub struct CaptureIndex(pub u16); + +impl MarshalSize for CaptureIndex { + fn marshal_size(&self) -> usize { 2 } +} + +impl Marshal for CaptureIndex { + fn marshal_to(&self, buffer: &mut [u8]) -> webrtc::util::Result { + let target = buffer.get_mut(..2) + .ok_or_else(|| webrtc::util::Error::Other("Capture index buffer too short".into()))?; + target.copy_from_slice(&self.0.to_be_bytes()); + Ok(2) + } +} + +pub fn capture_index(index: u16) -> HeaderExtension { + HeaderExtension::Custom { + uri: CAPTURE_INDEX_URI.into(), extension: Box::new(CaptureIndex(index)), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn encodes_network_order_without_truncation() { + let mut bytes = [0u8; 2]; + assert_eq!(CaptureIndex(0x1234).marshal_to(&mut bytes).unwrap(), 2); + assert_eq!(bytes, [0x12, 0x34]); + assert!(CaptureIndex(1).marshal_to(&mut [0u8; 1]).is_err()); + } + #[test] + fn new_frame_is_one_byte_boolean() { + let mut bytes = [0]; + NewFrame(true).marshal_to(&mut bytes).unwrap(); + assert_eq!(bytes, [1]); + NewFrame(false).marshal_to(&mut bytes).unwrap(); + assert_eq!(bytes, [0]); + } +} diff --git a/src/session_ice.rs b/src/session_ice.rs new file mode 100644 index 0000000..8e26a1e --- /dev/null +++ b/src/session_ice.rs @@ -0,0 +1,64 @@ +//! Per-connection cloud ICE configuration. Never derive Debug or log credentials. +use serde_json::Value; +use webrtc::ice_transport::ice_server::RTCIceServer; +use webrtc::peer_connection::{configuration::RTCConfiguration,policy::ice_transport_policy::RTCIceTransportPolicy}; + +#[derive(Clone, Default)] +pub struct SessionIce { + servers: Vec, + relay_only: bool, +} + +impl SessionIce { + pub fn from_header(header:&Value)->Self { + let data=header.get("data").unwrap_or(header); + let field=|name:&str|header.get(name).or_else(||data.get(name)); + let mut result=Self { relay_only:field("force_relay").and_then(Value::as_bool).unwrap_or(false),..Default::default() }; + if let Some(servers)=field("iceServers").and_then(Value::as_array) { + for server in servers.iter().take(16) { + let urls=server.get("urls").or_else(||server.get("url")); + let urls:Vec=match urls { + Some(Value::String(url))=>vec![url.clone()], + Some(Value::Array(urls))=>urls.iter().filter_map(Value::as_str).take(16).map(str::to_owned).collect(), + _=>Vec::new(), + }.into_iter().filter(|url|url.len()<=2048 && ["stun:","stuns:","turn:","turns:"].iter().any(|prefix|url.starts_with(prefix))).collect(); + if urls.is_empty() { continue; } + let string=|name|server.get(name).and_then(Value::as_str).filter(|s|s.len()<=4096).unwrap_or("").to_owned(); + result.servers.push(RTCIceServer { urls,username:string("username"),credential:string("credential"), + credential_type:webrtc::ice_transport::ice_credential_type::RTCIceCredentialType::Password }); + } + } + result + } + pub fn configuration(self)->Result { + let has_turn=self.servers.iter().any(|server|server.urls.iter().any(|url|url.starts_with("turn:")||url.starts_with("turns:"))); + if self.relay_only && !has_turn { return Err("Relay-only session requested without usable TURN configuration".into()); } + let supplied=!self.servers.is_empty(); + let servers=if supplied { self.servers } else { vec![RTCIceServer { + urls:vec!["stun:stun.l.google.com:19302".into(),"stun:stun1.l.google.com:19302".into(),"stun:stun.miwifi.com:3478".into()],..Default::default() + }] }; + log::info!("Session ICE configuration: cloud_supplied={} server_count={} turn_available={} relay_only={}",supplied,servers.len(),has_turn,self.relay_only); + Ok(RTCConfiguration { ice_servers:servers, + ice_transport_policy:if self.relay_only { RTCIceTransportPolicy::Relay } else { RTCIceTransportPolicy::All },..Default::default() }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn cloud_credentials_are_scoped_to_peer_and_relay_policy_is_honored() { + let config=SessionIce::from_header(&serde_json::json!({"data":{"iceServers":[{"urls":["turn:example.invalid:3478?transport=udp"],"username":"test-user","credential":"test-secret"}],"force_relay":true}})).configuration().unwrap(); + assert_eq!(config.ice_transport_policy,RTCIceTransportPolicy::Relay); + assert_eq!(config.ice_servers[0].username,"test-user"); + assert_eq!(config.ice_servers[0].credential,"test-secret"); + } + #[test] + fn unsupported_server_urls_are_rejected_and_relay_never_silently_falls_back() { + assert!(SessionIce::from_header(&serde_json::json!({"force_relay":true,"iceServers":[{"urls":"https://example.invalid"}]})).configuration().is_err()); + let config=SessionIce::default().configuration().unwrap(); + assert_eq!(config.ice_transport_policy,RTCIceTransportPolicy::All); + assert_eq!(config.ice_servers.len(),1); + assert!(config.ice_servers[0].urls.iter().all(|s|s.starts_with("stun:"))); + } +} diff --git a/src/session_lock.rs b/src/session_lock.rs new file mode 100644 index 0000000..61fffbb --- /dev/null +++ b/src/session_lock.rs @@ -0,0 +1,207 @@ +//! Lock-screen state and remote auto-unlock for the desktop session. +//! +//! Official protocol (UURemoteServer LockScreenManager / SimpleActionHandler, see +//! analysis/protocol-fix-20261013/control): the host reports Message 15 SystemStateChange +//! { 1: SecureDesktopState { 1 is_locked, 2 is_sas_shown, 5 is_support_auto_logon } } and the +//! viewer's saved password arrives as SimpleAction { 1: 15 AUTO_UNLOCK_SYSTEM, 2: {"key": ...} }. +//! A failed unlock is answered with Message 12 ReportError { 2: -5, 3: "... auto unlock failed" }. +//! +//! The Mac host types the password into loginwindow through Accessibility and waits for the +//! unlock. Here the password is verified with PAM and the session is unlocked through logind +//! (`loginctl unlock-session`, allowed for the session owner), which avoids remote keystrokes +//! and gives an exact wrong-password result. The password is never logged or stored. + +use std::process::Command; +use std::sync::OnceLock; +use std::time::Duration; +use tokio::sync::watch; + +/// Official UnlockResult cases (LockScreenManager). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum UnlockResult { Success, WrongPassword, NoLoggedInUser, NoPermission, Failed } + +/// Official ReportError.error_code for a failed auto unlock. +pub const UNLOCK_FAILED_CODE: i32 = -5; + +#[cfg(target_os = "linux")] +extern "C" { + fn uu_pam_available() -> libc::c_int; + fn uu_pam_check(service: *const libc::c_char, user: *const libc::c_char, password: *const libc::c_char) -> libc::c_int; +} + +fn loginctl(args: &[&str]) -> Option { + let out = Command::new("loginctl").args(args).output().ok()?; + if !out.status.success() { return None; } + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()).filter(|s| !s.is_empty()) +} + +/// The logind session that owns this user's graphical display. +fn display_session() -> Option { + let uid = unsafe { libc::getuid() }.to_string(); + loginctl(&["show-user", &uid, "-p", "Display", "--value"]) +} + +pub fn locked_now() -> Option { display_session().as_deref().and_then(session_locked) } + +fn session_locked(session: &str) -> Option { + loginctl(&["show-session", session, "-p", "LockedHint", "--value"]).map(|v| v == "yes") +} + +fn user_name() -> Option { + let pw = unsafe { libc::getpwuid(libc::getuid()) }; + if pw.is_null() { return None; } + unsafe { std::ffi::CStr::from_ptr((*pw).pw_name) }.to_str().ok().map(str::to_owned) +} + +fn pam_available() -> bool { + #[cfg(target_os = "linux")] + { unsafe { uu_pam_available() != 0 } } + #[cfg(not(target_os = "linux"))] + { false } +} + +/// PAM "login" service check of the user's own password: 0 ok, 1 wrong, -1 unavailable. +#[cfg(target_os = "linux")] +fn pam_check(user: &str, password: &str) -> i32 { + let (Ok(service), Ok(user), Ok(pass)) = (std::ffi::CString::new("login"), std::ffi::CString::new(user), + std::ffi::CString::new(password)) else { return -1 }; + let verdict = unsafe { uu_pam_check(service.as_ptr(), user.as_ptr(), pass.as_ptr()) }; + pass.into_bytes_with_nul().fill(0); + verdict +} +#[cfg(not(target_os = "linux"))] +fn pam_check(_user: &str, _password: &str) -> i32 { -1 } + +/// Auto unlock is offered when there is a graphical logind session and PAM can be loaded. +pub fn supported() -> bool { + static SUPPORTED: OnceLock = OnceLock::new(); + *SUPPORTED.get_or_init(|| pam_available() && display_session().is_some()) +} + +/// Current lock state (None = unknown), refreshed every second by one background thread. +pub fn watch_locked() -> watch::Receiver> { + static STATE: OnceLock>> = OnceLock::new(); + STATE.get_or_init(|| { + let (tx, _) = watch::channel(None); + let sender = tx.clone(); + std::thread::Builder::new().name("uu-lock-state".into()).spawn(move || { + let mut session = None; + loop { + if session.is_none() { session = display_session(); } + let locked = session.as_deref().and_then(session_locked); + if locked.is_none() { session = None; } // session ended or changed: look it up again + sender.send_if_modified(|current| if *current != locked { + log::info!("Desktop lock state: {}", match locked { Some(true) => "locked", Some(false) => "unlocked", None => "unknown" }); + *current = locked; true + } else { false }); + std::thread::sleep(Duration::from_secs(1)); + } + }).expect("spawn lock state thread"); + tx + }).subscribe() +} + +/// Verifies the session user's password and unlocks the display session. Blocking (PAM may +/// delay a failure by seconds); call from spawn_blocking. Consumes and wipes the password. +pub fn unlock(password: String) -> UnlockResult { + let mut password = password; + let result = unlock_with(&password); + unsafe { password.as_bytes_mut().fill(0); } + result +} + +fn unlock_with(password: &str) -> UnlockResult { + let Some(session) = display_session() else { return UnlockResult::NoLoggedInUser }; + if session_locked(&session) == Some(false) { return UnlockResult::Success; } + let Some(user) = user_name() else { return UnlockResult::NoLoggedInUser }; + if password.is_empty() || password.contains('\0') { return UnlockResult::WrongPassword; } + match pam_check(&user, password) { 0 => {}, 1 => return UnlockResult::WrongPassword, _ => return UnlockResult::Failed } + if Command::new("loginctl").args(["unlock-session", &session]).status().map(|s| !s.success()).unwrap_or(true) { + return UnlockResult::NoPermission; + } + let _ = crate::capture::keep_display_awake(); // a blanked monitor would keep the stream black + // Post-unlock confirmation like the official host: the lock screen must actually go away. + for _ in 0..100 { // GNOME takes ~3 s to drop the shield after logind's Unlock + if session_locked(&session) == Some(false) { return UnlockResult::Success; } + std::thread::sleep(Duration::from_millis(100)); + } + UnlockResult::Failed +} + +type Channel = std::sync::Arc; +type Sequence = std::sync::Arc; + +fn now() -> u64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs() } + +/// Message 15 SystemStateChange { 1: SecureDesktopState } on CONTROL. +pub async fn send_state(channel: &Channel, sequence: &Sequence, locked: bool) { + let seq = sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let message = crate::initialization::encode_secure_desktop(seq, now(), locked, false, supported()); + if let Err(e) = channel.send(&bytes::Bytes::from(message)).await { log::warn!("Secure desktop state send failed: {e}"); } +} + +/// Reports the lock state to one desktop viewer: now, then on every change, until it closes. +pub async fn report_states(channel: Channel, sequence: Sequence) { + use webrtc::data_channel::data_channel_state::RTCDataChannelState; + let mut state = watch_locked(); + let mut sent = None; + loop { + let locked = *state.borrow_and_update(); + if let Some(locked) = locked.filter(|l| sent != Some(*l)) { + send_state(&channel, &sequence, locked).await; + log::info!("Secure desktop state sent: locked={} auto_unlock={}", locked, supported()); + sent = Some(locked); + } + tokio::select! { + changed = state.changed() => if changed.is_err() { return; }, + _ = tokio::time::sleep(Duration::from_secs(2)) => {}, + } + if channel.ready_state() != RTCDataChannelState::Open { return; } + } +} + +/// SimpleAction AUTO_UNLOCK_SYSTEM: unlock, log only the outcome, report failure like the Mac host. +pub async fn handle_auto_unlock(password: Option, channel: Channel, sequence: Sequence) { + let result = match password { + Some(password) => tokio::task::spawn_blocking(move || unlock(password)).await.unwrap_or(UnlockResult::Failed), + None => UnlockResult::WrongPassword, + }; + log::info!("Auto unlock result: {:?}", result); + if result != UnlockResult::Success { + let seq = sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let message = crate::initialization::encode_report_error(seq, now(), UNLOCK_FAILED_CODE, "linux auto unlock failed"); + if let Err(e) = channel.send(&bytes::Bytes::from(message)).await { log::warn!("Auto unlock failure report failed: {e}"); } + } +} + +/// `uuremote-server unlock-check`: diagnostics for auto unlock; password from stdin, never echoed. +pub fn check_from_stdin() -> Result<(), String> { + let session = display_session(); + println!("display_session={} locked={:?} pam={} auto_unlock_supported={}", session.as_deref().unwrap_or("-"), + session.as_deref().and_then(session_locked), pam_available(), supported()); + let mut password = String::new(); + std::io::stdin().read_line(&mut password).map_err(|e| e.to_string())?; + let mut password = password.trim_end_matches(['\r', '\n']).to_string(); + let user = user_name().ok_or("no user name")?; + let verdict = pam_check(&user, &password); + unsafe { password.as_bytes_mut().fill(0); } + println!("password={}", match verdict { 0 => "accepted", 1 => "rejected", _ => "unverifiable (PAM unavailable/error)" }); + Ok(()) +} + +/// The `key` (password) from SimpleAction.args JSON. +pub fn password_from_args(args: &[u8]) -> Option { + let value: serde_json::Value = serde_json::from_slice(args).ok()?; + value.get("key")?.as_str().map(str::to_owned) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn password_comes_from_the_official_key_field() { + assert_eq!(password_from_args(br#"{"key":"p@ss word"}"#).as_deref(), Some("p@ss word")); + assert_eq!(password_from_args(br#"{"password":"x"}"#), None); + assert_eq!(password_from_args(b"not json"), None); + } +} diff --git a/src/signaling.rs b/src/signaling.rs new file mode 100644 index 0000000..3929baf --- /dev/null +++ b/src/signaling.rs @@ -0,0 +1,250 @@ +//! Lightweight Native Engine.IO v4 / Socket.IO Signaling Client + +use futures_util::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::sync::Arc; +use tokio::sync::mpsc; +use tokio_tungstenite::connect_async; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::Message; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SoacMessage { + #[serde(rename = "type")] + pub msg_type: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub sdp: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub gzip_sdp: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub candidate: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ice_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sdp_mid: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub sdp_mline_index: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub client_id: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub app_control_id: Option, +} + +pub enum SignalingEvent { + Connected, + RoomInfoAck(Value), + DeviceInfoChanged(Value), + BeControlled(Value), + /// be-controlled with its binary app_data (ConnectOptions): capture type and the + /// ice_id it announces, when present. + ConnectRequest { capture_type: u64, ice_id: Option, transport:crate::session_ice::SessionIce }, + Soac(SoacMessage), + Released(Value), + Left(Value), + Disconnected, +} + +pub struct SignalingClient { + tx_outgoing: mpsc::Sender, +} + +impl SignalingClient { + pub async fn connect( + url: &str, + room_token: &str, + event_sender: mpsc::Sender, + ) -> Result { + let ws_url = format!( + "{}/socket.io/?transport=websocket&EIO=4", + url.trim_end_matches('/') + ); + + let mut req = ws_url + .clone() + .into_client_request() + .map_err(|e| format!("Invalid WS request: {}", e))?; + + req.headers_mut().insert( + "X-NRD-AUTH", + room_token.parse().map_err(|_| "Invalid token header")?, + ); + + let (ws_stream, _) = connect_async(req) + .await + .map_err(|e| format!("WS connect failed: {}", e))?; + + log::info!("Connected to Engine.IO / Socket.IO at {}", ws_url); + let (mut write, mut read) = ws_stream.split(); + let (tx_outgoing, mut rx_outgoing) = mpsc::channel::(32); + + // 发送协程 + tokio::spawn(async move { + while let Some(msg) = rx_outgoing.recv().await { + if let Err(e) = write.send(Message::Text(msg)).await { + log::warn!("WS send error: {}", e); + break; + } + } + }); + + let tx_out_clone = tx_outgoing.clone(); + + // 接收与状态机协程 + tokio::spawn(async move { + let mut req_counter = 10; + // Socket.IO binary event awaiting attachments: (event name, header JSON). + let mut pending_binary: Option<(String, Value)> = None; + while let Some(msg_res) = read.next().await { + match msg_res { + Ok(Message::Text(txt)) => { + // Engine.IO 报文处理 + if txt.starts_with('0') { + // Open packet -> 发送 Socket.IO connect + let _ = tx_out_clone.send("40".into()).await; + } else if txt == "2" { + // Ping -> 回复 Pong + let _ = tx_out_clone.send("3".into()).await; + } else if txt.starts_with("40") { + // Socket.IO connected -> 发送 room_info 请求 + req_counter += 1; + let room_req = format!("42{}[\"room_info\"]", req_counter); + let _ = tx_out_clone.send(room_req).await; + let _ = event_sender.send(SignalingEvent::Connected).await; + } else if txt.starts_with("43") { + // Socket.IO ack 回调 + let payload = &txt[txt.find('[').unwrap_or(2)..]; + if let Ok(v) = serde_json::from_str::(payload) { + let _ = event_sender.send(SignalingEvent::RoomInfoAck(v)).await; + } + } else if txt.starts_with("45") || txt.starts_with("46") { + // Socket.IO binary event/ack: header text, attachments follow as binary frames. + let body = txt.trim_start_matches(|c: char| c.is_ascii_digit() || c == '-'); + let name = serde_json::from_str::(body).ok() + .and_then(|v| v.get(0).and_then(|n| n.as_str()).map(str::to_owned)) + .unwrap_or_default(); + let name: String = name.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-').take(48).collect(); + log::info!("Socket.IO binary packet: kind={} event={} header_bytes={}", &txt[..2], name, txt.len()); + let header = serde_json::from_str::(body).ok().and_then(|v| v.get(1).cloned()).unwrap_or(Value::Null); + pending_binary = Some((name, header)); + } else if txt.starts_with("42") { + // Socket.IO event + let payload = &txt[2..]; + log::debug!("Socket.IO event received ({} bytes)", payload.len()); + if let Ok(Value::Array(arr)) = serde_json::from_str::(payload) { + if arr.len() >= 2 { + let event_name = arr[0].as_str().unwrap_or_default(); + let data = &arr[1]; + log::info!("Socket.IO event dispatch: name={}", event_name); + + match event_name { + "bmsg_push" => { + let _ = event_sender + .send(SignalingEvent::DeviceInfoChanged(data.clone())) + .await; + } + "be-controlled" => { + let _ = event_sender + .send(SignalingEvent::BeControlled(data.clone())) + .await; + } + "soac" => { + let (target_val, client_id_opt) = if let Some(inner) = data.get("data") { + (inner.clone(), data.get("client_id").and_then(|v| v.as_str()).map(|s| s.to_string())) + } else { + (data.clone(), None) + }; + + match serde_json::from_value::(target_val.clone()) { + Ok(mut soac) => { + if soac.client_id.is_none() { + soac.client_id = client_id_opt; + } + let _ = event_sender + .send(SignalingEvent::Soac(soac)) + .await; + } + Err(e) => { + log::error!("Failed to deserialize SoacMessage: error={}, raw={}", e, data); + } + } + } + "released" => { + let _ = event_sender + .send(SignalingEvent::Released(data.clone())) + .await; + } + "left" | "leave" => { + let ice_id = data.get("ice_id").and_then(|v| v.as_str()).unwrap_or(""); + if ice_id.is_empty() { + log::warn!("Room expired from NetEase cloud (leave event). Triggering room renewal..."); + let _ = event_sender.send(SignalingEvent::Disconnected).await; + } else { + let _ = event_sender + .send(SignalingEvent::Left(data.clone())) + .await; + } + } + _ => { + let keys: Vec = data.as_object().map(|o| o.keys().take(16).cloned().collect()).unwrap_or_default(); + log::info!("Unhandled Socket.IO event: {} keys={:?}", event_name, keys); + } + } + } + } + } + } + Ok(Message::Binary(data)) => { + // Engine.IO v4 sends attachments raw; tolerate a legacy 0x04 prefix. + let data: &[u8] = if data.first() == Some(&4) && crate::protocol::decode_wire(&data).is_err() { &data[1..] } else { &data }; + let fields = crate::protocol::decode_wire(data).ok(); + let shape: Vec<(u32, Option)> = fields.as_ref().map(|f| f.iter().map(|x| (x.number, match x.value { + crate::protocol::WireValue::Varint(v) => Some(v), _ => None })).collect()).unwrap_or_default(); + log::info!("Socket.IO binary attachment: bytes={} protobuf_fields={:?}", data.len(), shape); + if let Some((name, header)) = pending_binary.take() { + if name == "be-controlled" { + let capture_type = shape.iter().find(|(n, _)| *n == 1).and_then(|(_, v)| *v).unwrap_or(0); + let keys: Vec = header.as_object().map(|o| o.keys().take(24).cloned().collect()).unwrap_or_default(); + let ice_id = ["ice_id", "iceId"].iter().find_map(|k| header.get(*k).or_else(|| header.get("data").and_then(|d| d.get(*k)))) + .and_then(|v| v.as_str()).map(str::to_owned); + log::info!("be-controlled connect request: capture_type={} header_keys={:?} ice_id_present={}", capture_type, keys, ice_id.is_some()); + let _ = event_sender.send(SignalingEvent::ConnectRequest { capture_type, ice_id, transport:crate::session_ice::SessionIce::from_header(&header) }).await; + } + } + } + Ok(Message::Close(_)) | Err(_) => { + let _ = event_sender.send(SignalingEvent::Disconnected).await; + break; + } + _ => {} + } + } + }); + + Ok(Self { tx_outgoing }) + } + + pub async fn emit_event(&self, event: &str, payload: serde_json::Value) -> Result<(), String> { + let packet = format!("42{}", serde_json::json!([event, payload])); + log::info!("Emitting signaling event: {}", event); + self.tx_outgoing.send(packet).await.map_err(|e| e.to_string()) + } + + /// 发送 SOAC 消息(Answer 或 Candidate) + pub async fn emit_soac(&self, soac: SoacMessage) -> Result<(), String> { + let payload = if let Some(cid) = &soac.client_id { + serde_json::json!({ + "client_id": cid, + "data": soac + }).to_string() + } else { + serde_json::to_string(&soac).map_err(|e| e.to_string())? + }; + let msg = format!("42[\"soac\",{}]", payload); + log::info!("Emitting soac packet: type={}", soac.msg_type); + self.tx_outgoing + .send(msg) + .await + .map_err(|e| format!("Send soac error: {}", e)) + } +} diff --git a/src/system_actions.rs b/src/system_actions.rs new file mode 100644 index 0000000..62cd13e --- /dev/null +++ b/src/system_actions.rs @@ -0,0 +1,274 @@ +//! Official SimpleAction system commands from the viewer's 安全 / 更多 menus, mapped to the +//! Linux desktop session: lock (logind), show desktop, system monitor, reboot/power-off +//! (systemctl through logind/polkit), host mute (wpctl / pactl) and lock-after-session. +//! Declared through FeatureFlag ff_simple_action = FF_SIMPLE_ACTION_AUTO_LOCK (2, includes +//! MUTING) and ff_system_metrics = FF_SYSTEM_METRICS_SETTING_AUTO_LOCK (2). + +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Mutex; + +pub const FF_SIMPLE_ACTION: u8 = 2; +pub const FF_SYSTEM_METRICS: u8 = 2; + +pub const SHOW_DESKTOP: u64 = 2; +pub const REBOOT_SYSTEM: u64 = 9; +pub const LOCK_SYSTEM: u64 = 10; +pub const SHUTDOWN_SYSTEM: u64 = 12; +pub const SHOW_TASKMGR: u64 = 13; +pub const MUTE_SYSTEM: u64 = 14; +pub const MUTE_RESTORE: u64 = 16; +pub const MUTE_PERMANENT: u64 = 17; +pub const MUTE_TEMPORARY: u64 = 18; +pub const SET_AUTO_LOCK: u64 = 19; + +/// Host settings from the viewer's 安全 menu. The viewer sends them only when a switch is toggled +/// and shows what SystemMetrics reports, so they are host-wide and persisted (like the official +/// host), not per connection: a reconnect must still lock / mute. +#[derive(Debug, Default, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)] +struct Settings { + #[serde(default)] auto_lock: bool, + #[serde(default)] keep_mute: bool, + #[serde(default)] mute_permanent: bool, +} + +struct HostState { + settings: Settings, + /// Host mute state before remote control muted it (restored by MUTE_RESTORE / last session end). + restore: Option, + desktop_sessions: usize, +} + +fn settings_path() -> std::path::PathBuf { crate::config::path().with_file_name("host_settings.json") } + +fn state() -> &'static Mutex { + static STATE: std::sync::OnceLock> = std::sync::OnceLock::new(); + STATE.get_or_init(|| { + let settings = std::fs::read(settings_path()).ok() + .and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); + Mutex::new(HostState { settings, restore: None, desktop_sessions: 0 }) + }) +} + +fn save(settings: &Settings) { + let path = settings_path(); + let result = serde_json::to_vec_pretty(settings).map_err(|e| e.to_string()) + .and_then(|json| std::fs::write(&path, json).map_err(|e| e.to_string())); + if let Err(e) = result { log::warn!("Host settings not saved: {}", e); } +} + +/// Handle for one desktop connection (system actions are host-wide). +#[derive(Default)] +pub struct PeerActions { started: AtomicBool } + +fn quiet(program: &str, args: &[&str]) -> bool { + Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()) + .status().map(|s| s.success()).unwrap_or(false) +} + +fn detached(program: &str, args: &[&str]) -> bool { + Command::new(program).args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()) + .spawn().map(|mut child| { std::thread::spawn(move || child.wait()); true }).unwrap_or(false) +} + +/// Current mute state of the default output (None = no audio control available). +pub fn host_muted() -> Option { + if let Ok(out) = Command::new("wpctl").args(["get-volume", "@DEFAULT_AUDIO_SINK@"]).output() { + if out.status.success() { return Some(String::from_utf8_lossy(&out.stdout).contains("MUTED")); } + } + let out = Command::new("pactl").args(["get-sink-mute", "@DEFAULT_SINK@"]).output().ok()?; + out.status.success().then(|| String::from_utf8_lossy(&out.stdout).contains("yes")) +} + +pub fn set_host_muted(muted: bool) -> bool { + let flag = if muted { "1" } else { "0" }; + quiet("wpctl", &["set-mute", "@DEFAULT_AUDIO_SINK@", flag]) || quiet("pactl", &["set-sink-mute", "@DEFAULT_SINK@", flag]) +} + +pub fn lock_session() -> bool { quiet("loginctl", &["lock-session"]) } + +/// The on/off value of a toggle action: SimpleAction.value (field 5), else args JSON/text; default on. +pub fn toggle_value(value: Option, args: &[u8]) -> bool { + if let Some(v) = value { return v != 0; } + let text = String::from_utf8_lossy(args); + let text = text.trim(); + if let Ok(json) = serde_json::from_str::(text) { + let scalar = |v: &serde_json::Value| v.as_bool().or_else(|| v.as_i64().map(|n| n != 0)) + .or_else(|| v.as_str().map(|s| matches!(s, "1" | "true" | "on"))); + if let Some(b) = scalar(&json) { return b; } + if let Some(b) = json.as_object().and_then(|o| o.values().find_map(scalar)) { return b; } + } + !matches!(text, "0" | "false" | "off") +} + +/// Shape of action args for diagnostics: JSON keys and scalar types, never values. +pub fn args_shape(args: &[u8]) -> String { + match serde_json::from_slice::(args) { + Ok(serde_json::Value::Object(o)) => format!("{:?}", o.iter().map(|(k, v)| (k.chars().take(32).collect::(), match v { + serde_json::Value::Bool(_) => "bool", serde_json::Value::Number(_) => "number", + serde_json::Value::String(_) => "string", _ => "other" })).collect::>()), + Ok(_) => "json scalar".into(), + Err(_) => format!("{} bytes non-json", args.len()), + } +} + +fn mute_for_session(state: &mut HostState) { + if state.restore.is_none() { state.restore = host_muted(); } + set_host_muted(true); +} +fn restore_mute(state: &mut HostState) { + if let Some(previous) = state.restore.take() { set_host_muted(previous); } +} + +impl PeerActions { + /// Runs one system action; returns true when the settings report should be resent. + /// Blocking (spawns system tools); call from spawn_blocking. + pub fn handle(&self, action: u64, value: Option, args: &[u8], show_desktop: impl FnOnce()) -> bool { + match action { + SHOW_DESKTOP => { show_desktop(); log::info!("System action show_desktop"); return false } + LOCK_SYSTEM => { log::info!("System action lock_system: ok={}", lock_session()); return false } + SHOW_TASKMGR => { + let ok = detached("gnome-system-monitor", &[]) || detached("plasma-systemmonitor", &[]) || detached("xfce4-taskmanager", &[]); + log::info!("System action show_taskmgr: ok={}", ok); return false + } + REBOOT_SYSTEM => { log::warn!("System action reboot_system requested by viewer"); log::info!("reboot ok={}", quiet("systemctl", &["reboot"])); return false } + SHUTDOWN_SYSTEM => { log::warn!("System action shutdown_system requested by viewer"); log::info!("poweroff ok={}", quiet("systemctl", &["poweroff"])); return false } + _ => {} + } + let mut state = state().lock().unwrap(); + let before = state.settings; + match action { + // 静音运行 on: the viewer sends MUTE_SYSTEM + MUTE_TEMPORARY (observed), off: MUTE_RESTORE. + MUTE_SYSTEM | MUTE_TEMPORARY => { + let on = toggle_value(value, args); + state.settings.keep_mute = on; + if on { mute_for_session(&mut state); } else { restore_mute(&mut state); } + log::info!("System action mute (action {}): on={} muted={:?}", action, on, host_muted()); + } + // Keep the host muted after the session (远程结束后,恢复被控端声音设置 unchecked). + MUTE_PERMANENT => { + let on = toggle_value(value, args); + state.settings.mute_permanent = on; + if on { state.settings.keep_mute = true; mute_for_session(&mut state); } + log::info!("System action mute_permanent: on={} muted={:?}", on, host_muted()); + } + MUTE_RESTORE => { + state.settings.keep_mute = false; + state.settings.mute_permanent = false; + restore_mute(&mut state); + log::info!("System action mute_restore: muted={:?}", host_muted()); + } + SET_AUTO_LOCK => { + // Observed: enabling 远程结束后自动锁屏 sends value 2 and disabling value 1. + let on = match value { Some(v) => v == 2, None => toggle_value(None, args) }; + state.settings.auto_lock = on; + log::info!("System action set_auto_lock: on={}", on); + } + _ => return false, + } + if state.settings != before { save(&state.settings); } + true + } + + /// Desktop connection started: re-apply 静音运行 for the first remote session. + pub fn session_started(&self) { + if self.started.swap(true, Ordering::Relaxed) { return; } + let mut state = state().lock().unwrap(); + state.desktop_sessions += 1; + if state.desktop_sessions == 1 && state.settings.keep_mute { + mute_for_session(&mut state); + log::info!("Host muted for remote session (静音运行)"); + } + } + + /// Desktop connection ended. After the last one: undo a session-only mute and lock if the + /// viewer asked for it. + pub fn session_ended(&self) { + if !self.started.swap(false, Ordering::Relaxed) { return; } + let mut state = state().lock().unwrap(); + state.desktop_sessions = state.desktop_sessions.saturating_sub(1); + if state.desktop_sessions > 0 { return; } + if !state.settings.mute_permanent { restore_mute(&mut state); } + if state.settings.auto_lock { + log::info!("Auto lock after remote session: ok={}", lock_session()); + } + } + + /// Message 13 SystemMetrics: permissions, file-transfer folder and the current settings. + pub fn metrics_payload(&self, sound: bool, desktop: crate::system_metrics::Permission) -> Vec { + use crate::system_metrics::payload_with_settings; + let home = std::env::var("HOME").unwrap_or_else(|_| "/".into()); + let current = state().lock().unwrap().settings; + payload_with_settings(desktop, desktop, desktop, &home, &crate::system_metrics::Settings { + sound, keep_mute: current.keep_mute, mute_permanent: current.mute_permanent, auto_lock: current.auto_lock, + }) + } +} + +/// Session RPCs answered with success: 15 send_video_track_req -> 11 (the single desktop track +/// 0 is always sent), 21 virtual_audio_driver_policy_req -> 17 (no virtual driver needed: the +/// sink monitor is captured directly). Responses carry error_code 0 (default). +pub fn session_rpc_response(rpc: &[crate::protocol::WireField]) -> Option> { + use crate::protocol::{decode_wire, WireValue}; + let body = |n: u32| rpc.iter().find_map(|f| match (f.number, &f.value) { (x, WireValue::Bytes(b)) if x == n => Some(*b), _ => None }); + let (request, response_field) = [(15u32, 11u8), (21, 17)].into_iter().find_map(|(req, resp)| body(req).map(|b| (b, resp)))?; + let value = decode_wire(request).ok().and_then(|f| f.iter().find_map(|f| match (f.number, &f.value) { (1, WireValue::Varint(v)) => Some(*v), _ => None })); + log::info!("Session RPC answered: response_field={} value={:?}", response_field, value); + let header = body(1).unwrap_or(&[]); + let mut out = vec![10, header.len() as u8]; + out.extend_from_slice(header); + out.extend_from_slice(&[response_field << 3 | 2, 0]); + Some(out) +} + +/// Plugin RPCs (魔兽世界排队提醒工具): no plugins exist on Linux. Query answers "disabled" +/// (QueryPluginSettingResponse field 12); enable/install/notification requests answer error_code 1. +pub fn plugin_response(rpc: &[crate::protocol::WireField]) -> Option> { + use crate::protocol::{decode_wire, WireValue}; + fn varint(mut v: u64, out: &mut Vec) { while v >= 128 { out.push((v as u8 & 127) | 128); v >>= 7; } out.push(v as u8); } + fn bytes(field: u64, v: &[u8], out: &mut Vec) { varint(field << 3 | 2, out); varint(v.len() as u64, out); out.extend_from_slice(v); } + let body = |n: u32| rpc.iter().find_map(|f| match (f.number, &f.value) { (x, WireValue::Bytes(b)) if x == n => Some(*b), _ => None }); + // (request field, response field, plugin_id field in the response) + let (request, response_field, id_field): (&[u8], u64, u64) = [(16u32, 12u64, 3u64), (17, 13, 3), (18, 14, 2), (19, 15, 2), (20, 16, 2)] + .into_iter().find_map(|(req, resp, id)| body(req).map(|b| (b, resp, id)))?; + let plugin_id = decode_wire(request).ok()?.iter().find_map(|f| match (f.number, &f.value) { (1, WireValue::Bytes(b)) => Some(b.to_vec()), _ => None }).unwrap_or_default(); + let mut payload = Vec::new(); + if response_field != 12 { payload.extend_from_slice(&[8, 1]); } // error_code 1: unsupported + bytes(id_field, &plugin_id, &mut payload); // query: error_code 0, enable false (defaults) + let mut out = Vec::new(); + bytes(1, body(1).unwrap_or(&[]), &mut out); + bytes(response_field, &payload, &mut out); + log::info!("Plugin RPC answered: response_field={} (no Linux plugins)", response_field); + Some(out) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn toggle_values_from_value_field_json_and_text() { + assert!(!toggle_value(Some(0), b"1")); + assert!(toggle_value(Some(1), b"")); + assert!(!toggle_value(None, br#"{"enable":false}"#)); + assert!(toggle_value(None, br#"{"value":1}"#)); + assert!(!toggle_value(None, b"0")); + assert!(toggle_value(None, b"")); + } + #[test] + fn plugin_query_answers_disabled_with_same_request_and_plugin_id() { + use crate::protocol::{decode_wire, WireValue}; + // RpcRequest { 1 header{1:9}, 16 query{1:"wow"} } + let request = [10, 2, 8, 9, 130, 1, 5, 10, 3, b'w', b'o', b'w']; + let response = plugin_response(&decode_wire(&request).unwrap()).unwrap(); + let fields = decode_wire(&response).unwrap(); + assert_eq!(fields[0].value, WireValue::Bytes(&[8, 9])); + assert_eq!(fields[1].number, 12); + assert_eq!(fields[1].value, WireValue::Bytes(&[26, 3, b'w', b'o', b'w'])); + assert!(plugin_response(&decode_wire(&[10, 2, 8, 9]).unwrap()).is_none()); + } + #[test] + fn args_shape_never_contains_values() { + let shape = args_shape(br#"{"enable":true,"secret":"abc"}"#); + assert!(shape.contains("enable") && !shape.contains("abc")); + } +} diff --git a/src/system_metrics.rs b/src/system_metrics.rs new file mode 100644 index 0000000..5648d65 --- /dev/null +++ b/src/system_metrics.rs @@ -0,0 +1,118 @@ +//! Verified SystemMetrics protobuf shape for ordinary Linux X11 control. +//! Official maps/types: analysis/protocol-fix-20261013/control/system-metrics-*.json. +//! This reports observations supplied by the caller; it never unlocks a session, +//! sends SAS, enables audio, advertises Windows, or changes desktop settings. + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(u64)] +pub enum Permission { + Unknown = 0, + Reject = 1, + Allow = 2, +} + +/// Payload for Message.which field 13 SystemMetrics. Use initialization::envelope +/// with fresh local sequence/current UNIX seconds. Current locked state belongs +/// to a separate SystemStateChange notification, not this capability message. +pub fn payload(capture: Permission, operation: Permission, control: Permission) -> Vec { + payload_with_location(capture, operation, control, "") +} + +/// Same, plus SettingMetric field 5 file_transfer_save_location: the host directory the +/// viewer's file-transfer window opens on (the official Mac host reports its receive folder). +pub fn payload_with_location(capture: Permission, operation: Permission, control: Permission, location: &str) -> Vec { + payload_with_settings(capture, operation, control, location, &Settings::default()) +} + +/// Optional host settings the viewer shows in 声音 / 安全 (SettingMetric 1 keep_mute, +/// 2 mute_permanent, 3 auto_lock; GeneralMetric 2 system_sound_support). +#[derive(Debug, Default, Clone, Copy)] +pub struct Settings { pub sound: bool, pub keep_mute: bool, pub mute_permanent: bool, pub auto_lock: bool } + +pub fn payload_with_settings(capture: Permission, operation: Permission, control: Permission, location: &str, settings: &Settings) -> Vec { + let mut setting = Vec::new(); + for (field, on) in [(1u8, settings.keep_mute), (2, settings.mute_permanent), (3, settings.auto_lock)] { + if on { setting.push(field << 3); setting.push(1); } + } + if !location.is_empty() { + setting.push(5 << 3 | 2); + varint(location.len() as u64, &mut setting); + setting.extend_from_slice(location.as_bytes()); + } + for (field, state) in [(8u8, capture), (9u8, operation), (10u8, control)] { + if state != Permission::Unknown { + setting.push(field << 3); + setting.push(state as u8); + } + } + // SystemMetrics.general: system_sound_support = SS_SUPPORT (2) when desktop audio is streamed + // (GvPb_SystemSoundSupport: 0 unknown, 1 nonsupport, 2 support). + let mut out = if settings.sound { vec![26, 2, 16, 2] } else { vec![26, 0] }; + // No support_touch, sound capability, win_os_ver, private-screen, virtual + // mouse, auto-lock, file path or optional feature claims are fabricated. + out.push(34); // SystemMetrics.setting field 4 + varint(setting.len() as u64, &mut out); + out.extend_from_slice(&setting); + out +} + +fn varint(mut v: u64, out: &mut Vec) { + while v >= 128 { out.push((v as u8 & 127) | 128); v >>= 7; } + out.push(v as u8); +} + +/// Message field 26 RemoteDownloadPath{1 download_path}. +pub fn remote_download_path(path: &str) -> Vec { + let mut out = vec![10]; + varint(path.len() as u64, &mut out); + out.extend_from_slice(path.as_bytes()); + out +} + +#[cfg(test)] +#[path = "protocol.rs"] +mod wire_test_support; + +#[cfg(test)] +mod tests { + use super::*; + use super::wire_test_support::{decode_wire, WireValue}; + #[test] + fn measured_allow_capabilities_use_official_enum_values() { + let p = payload(Permission::Allow, Permission::Allow, Permission::Allow); + let fields = decode_wire(&p).unwrap(); + assert_eq!(fields.len(), 2); + assert_eq!(fields[0].number, 3); + assert_eq!(fields[0].value, WireValue::Bytes(&[])); + let WireValue::Bytes(setting) = fields[1].value else { panic!("setting not a message") }; + assert_eq!(fields[1].number, 4); + let s = decode_wire(setting).unwrap(); + assert_eq!(s.iter().map(|f| f.number).collect::>(), vec![8, 9, 10]); + assert!(s.iter().all(|f| f.value == WireValue::Varint(2))); + } + #[test] + fn rejected_and_unknown_observations_are_not_promoted_to_allow() { + assert_eq!(payload(Permission::Unknown, Permission::Unknown, Permission::Unknown), vec![26, 0, 34, 0]); + assert_eq!(payload(Permission::Allow, Permission::Reject, Permission::Reject), vec![26, 0, 34, 6, 64, 2, 72, 1, 80, 1]); + } + #[test] + fn emits_no_audio_touch_windows_or_auto_unlock_capability() { + let p = payload(Permission::Allow, Permission::Allow, Permission::Allow); + let fields = decode_wire(&p).unwrap(); + let WireValue::Bytes(general) = fields[0].value else { panic!() }; + assert!(general.is_empty()); + let WireValue::Bytes(setting) = fields[1].value else { panic!() }; + assert!(decode_wire(setting).unwrap().iter().all(|f| (8..=10).contains(&f.number))); + } + #[test] + fn reports_file_transfer_save_location_as_setting_field_5() { + let home = "/home/user/".repeat(12); + let p = payload_with_location(Permission::Allow, Permission::Allow, Permission::Allow, &home); + let fields = decode_wire(&p).unwrap(); + let WireValue::Bytes(setting) = fields[1].value else { panic!() }; + let s = decode_wire(setting).unwrap(); + assert_eq!(s[0].number, 5); + assert_eq!(s[0].value, WireValue::Bytes(home.as_bytes())); + assert_eq!(decode_wire(&remote_download_path("/home/x")).unwrap()[0].value, WireValue::Bytes(b"/home/x")); + } +} diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..2304eda --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,321 @@ +//! UU remote terminal (CT_TERMINAL) over BINARY_DATA_CHANNEL. +//! Frame layout recovered from the official Mac host codec (UURemoteServer 0x1001a7834 decode, +//! 0x1001a7480 encode): "TERM", version u8 = 1, type u8, two flag bytes, session_id u32 LE, +//! payload_len u32 LE (<= 1 MiB), payload. Type values are TerminalFrameType case index + 1. +//! Control payloads are JSON (cols/rows/shell/option, code/message, exit_code, password). +//! Sessions outlive a viewer connection (like the official tmux-backed sessions) and replay +//! a bounded scrollback on reattach. Terminal input/output bytes are never logged. + +use std::collections::{HashMap, VecDeque}; +use std::io::Read; +use std::os::fd::{AsRawFd, OwnedFd}; +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, OnceLock}; +use tokio::sync::mpsc::UnboundedSender; + +pub const OPEN: u8 = 1; +pub const STDIN: u8 = 2; +pub const RESIZE: u8 = 3; +pub const CLOSE: u8 = 4; +pub const STDOUT: u8 = 5; +pub const EXIT: u8 = 6; +pub const SIGNAL: u8 = 7; +pub const ERROR: u8 = 8; +pub const LIST_REQ: u8 = 9; +pub const LIST_RESP: u8 = 10; +pub const KILL_REQ: u8 = 11; +pub const KILL_RESP: u8 = 12; +pub const OPEN_RESP: u8 = 13; +pub const UNLOCK_REQ: u8 = 14; +pub const UNLOCK_RESP: u8 = 15; +pub const DETACH: u8 = 16; + +const MAGIC: &[u8; 4] = b"TERM"; +const HEADER: usize = 16; +const MAX_PAYLOAD: usize = 0x10_0000; +const SCROLLBACK: usize = 256 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Frame { pub kind: u8, pub flags: [u8; 2], pub session: u32, pub payload: Vec } + +pub fn encode(kind: u8, session: u32, payload: &[u8]) -> Vec { + let mut out = Vec::with_capacity(HEADER + payload.len()); + out.extend_from_slice(MAGIC); + out.push(1); + out.push(kind); + out.extend_from_slice(&[0, 0]); + out.extend_from_slice(&session.to_le_bytes()); + out.extend_from_slice(&(payload.len() as u32).to_le_bytes()); + out.extend_from_slice(payload); + out +} + +pub fn decode(data: &[u8]) -> Option { + if data.len() < HEADER || &data[..4] != MAGIC { return None; } + let kind = data[5]; + if !(1..=16).contains(&kind) { return None; } + let session = u32::from_le_bytes(data[8..12].try_into().ok()?); + let len = u32::from_le_bytes(data[12..16].try_into().ok()?) as usize; + if len > MAX_PAYLOAD || data.len() != HEADER + len { return None; } + Some(Frame { kind, flags: [data[6], data[7]], session, payload: data[HEADER..].to_vec() }) +} + +pub fn is_frame(data: &[u8]) -> bool { data.len() >= 4 && &data[..4] == MAGIC } + +struct Session { + id: u32, + shell: String, + created_ms: u64, + master: OwnedFd, + pid: i32, + sink: Mutex>>>, + scrollback: Mutex>, +} + +impl Session { + fn emit(&self, kind: u8, payload: &[u8]) -> bool { + let mut sink = self.sink.lock().unwrap(); + if let Some(tx) = sink.as_ref() { + if tx.send(encode(kind, self.id, payload)).is_ok() { return true; } + *sink = None; + } + false + } + fn resize(&self, cols: u16, rows: u16) { + let win = libc::winsize { ws_row: rows, ws_col: cols, ws_xpixel: 0, ws_ypixel: 0 }; + unsafe { libc::ioctl(self.master.as_raw_fd(), libc::TIOCSWINSZ as _, &win); } + } + fn write(&self, data: &[u8]) { + let mut off = 0; + while off < data.len() { + let n = unsafe { libc::write(self.master.as_raw_fd(), data[off..].as_ptr().cast(), data.len() - off) }; + if n <= 0 { break; } + off += n as usize; + } + } + fn signal(&self, sig: i32) { unsafe { libc::kill(-self.pid, sig); } } +} + +fn registry() -> &'static Mutex>> { + static REG: OnceLock>>> = OnceLock::new(); + REG.get_or_init(Default::default) +} +static NEXT_ID: AtomicU32 = AtomicU32::new(1); + +fn now_ms() -> u64 { std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_millis() as u64 } + +fn spawn(cols: u16, rows: u16, shell: Option<&str>) -> Result, String> { + use std::os::unix::process::CommandExt; + let win = nix::pty::Winsize { ws_row: rows.max(1), ws_col: cols.max(1), ws_xpixel: 0, ws_ypixel: 0 }; + let pty = nix::pty::openpty(Some(&win), None).map_err(|e| format!("openpty failed: {e}"))?; + let shell = shell.filter(|s| s.starts_with('/') && std::path::Path::new(s).exists()).map(str::to_owned) + .or_else(|| std::env::var("SHELL").ok().filter(|s| std::path::Path::new(s).exists())) + .unwrap_or_else(|| "/bin/bash".into()); + let home = std::env::var("HOME").unwrap_or_else(|_| "/".into()); + let slave = pty.slave; + let io = |fd: &OwnedFd| fd.try_clone().map(std::process::Stdio::from).map_err(|e| format!("pty dup failed: {e}")); + let mut cmd = std::process::Command::new(&shell); + cmd.arg("-l").current_dir(&home) + .env("TERM", "xterm-256color").env("COLORTERM", "truecolor") + .env("LANG", std::env::var("LANG").unwrap_or_else(|_| "C.UTF-8".into())) + .stdin(io(&slave)?).stdout(io(&slave)?).stderr(io(&slave)?); + unsafe { + cmd.pre_exec(|| { + if libc::setsid() < 0 { return Err(std::io::Error::last_os_error()); } + if libc::ioctl(0, libc::TIOCSCTTY as _, 0) < 0 { return Err(std::io::Error::last_os_error()); } + Ok(()) + }); + } + let mut child = cmd.spawn().map_err(|e| format!("shell spawn failed: {e}"))?; + drop(slave); + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + let session = Arc::new(Session { id, shell: shell.clone(), created_ms: now_ms(), pid: child.id() as i32, + master: pty.master, sink: Mutex::new(None), scrollback: Mutex::new(VecDeque::new()) }); + let mut reader = std::fs::File::from(session.master.try_clone().map_err(|e| format!("pty dup failed: {e}"))?); + let worker = session.clone(); + std::thread::Builder::new().name(format!("uu-term-{id}")).spawn(move || { + let mut buf = vec![0u8; 16 * 1024]; + loop { + match reader.read(&mut buf) { + Ok(0) | Err(_) => break, + Ok(n) => { + { + let mut sb = worker.scrollback.lock().unwrap(); + sb.extend(&buf[..n]); + let excess = sb.len().saturating_sub(SCROLLBACK); + sb.drain(..excess); + } + worker.emit(STDOUT, &buf[..n]); + } + } + } + let code = child.wait().ok().and_then(|s| s.code()).unwrap_or(-1); + log::info!("Terminal session exited: id={} exit_code={}", worker.id, code); + worker.emit(EXIT, serde_json::json!({"exit_code": code}).to_string().as_bytes()); + registry().lock().unwrap().remove(&worker.id); + }).map_err(|e| format!("reader thread failed: {e}"))?; + registry().lock().unwrap().insert(id, session.clone()); + log::info!("Terminal session spawned: id={} cols={} rows={}", id, cols, rows); + Ok(session) +} + +/// Ends every terminal session (interactive shells ignore SIGTERM, which otherwise +/// makes systemd wait for its stop timeout). Called when the server shuts down. +pub fn shutdown_all() { + let sessions: Vec> = registry().lock().unwrap().values().cloned().collect(); + for s in &sessions { s.signal(libc::SIGHUP); } + if !sessions.is_empty() { + std::thread::sleep(std::time::Duration::from_millis(300)); + for s in &sessions { s.signal(libc::SIGKILL); } + log::info!("Terminal sessions closed on shutdown: count={}", sessions.len()); + } +} + +fn json(payload: &[u8]) -> serde_json::Value { serde_json::from_slice(payload).unwrap_or(serde_json::Value::Null) } +fn dims(v: &serde_json::Value) -> (u16, u16) { + let get = |k: &str, d: u64| v.get(k).and_then(|x| x.as_u64().or_else(|| x.as_f64().map(|f| f as u64))).unwrap_or(d).clamp(1, 1000) as u16; + (get("cols", 80), get("rows", 24)) +} +fn signal_number(payload: &[u8]) -> i32 { + let text = String::from_utf8_lossy(payload); + let v = json(payload); + let name = v.as_str().map(str::to_owned).or_else(|| v.as_object().and_then(|o| o.values().find_map(|x| x.as_str().map(str::to_owned)))) + .unwrap_or_else(|| text.into_owned()); + if let Some(n) = v.as_object().and_then(|o| o.values().find_map(|x| x.as_i64())) { return n as i32; } + match name.trim().trim_start_matches("SIG") { + "TERM" => libc::SIGTERM, "KILL" => libc::SIGKILL, "HUP" => libc::SIGHUP, "QUIT" => libc::SIGQUIT, + "ABRT" => libc::SIGABRT, "PIPE" => libc::SIGPIPE, "FPE" => libc::SIGFPE, "SEGV" => libc::SIGSEGV, "ILL" => libc::SIGILL, + _ => libc::SIGINT, + } +} +fn reply(code: i64, message: &str) -> Vec { serde_json::json!({"code": code, "message": message}).to_string().into_bytes() } + +/// One viewer connection's terminal endpoint; `out` sends complete frames on BINARY_DATA_CHANNEL. +pub struct TerminalConn { out: UnboundedSender> } + +impl TerminalConn { + pub fn new(out: UnboundedSender>) -> Self { Self { out } } + fn send(&self, kind: u8, session: u32, payload: &[u8]) { let _ = self.out.send(encode(kind, session, payload)); } + + pub fn handle(&self, data: &[u8]) { + let Some(frame) = decode(data) else { log::warn!("Terminal frame rejected: bytes={}", data.len()); return; }; + if frame.kind != STDIN { log::info!("Terminal frame: type={} session={} payload_bytes={}", frame.kind, frame.session, frame.payload.len()); } + let existing = registry().lock().unwrap().get(&frame.session).cloned(); + match frame.kind { + OPEN => { + let v = json(&frame.payload); + let (cols, rows) = dims(&v); + let session = match existing { + Some(s) => { s.resize(cols, rows); Ok(s) } + None => spawn(cols, rows, v.get("shell").and_then(|s| s.as_str())), + }; + match session { + Ok(s) => { + *s.sink.lock().unwrap() = Some(self.out.clone()); + self.send(OPEN_RESP, s.id, &reply(0, "ok")); + let replay: Vec = s.scrollback.lock().unwrap().iter().copied().collect(); + if !replay.is_empty() { self.send(STDOUT, s.id, &replay); } + } + Err(e) => { log::warn!("Terminal open failed: {}", e); self.send(OPEN_RESP, frame.session, &reply(1, &e)); } + } + } + STDIN => if let Some(s) = existing { s.write(&frame.payload) }, + RESIZE => if let Some(s) = existing { let (c, r) = dims(&json(&frame.payload)); s.resize(c, r) }, + SIGNAL => if let Some(s) = existing { s.signal(signal_number(&frame.payload)) }, + CLOSE => if let Some(s) = existing { *s.sink.lock().unwrap() = None; s.signal(libc::SIGHUP); }, + DETACH => if let Some(s) = existing { *s.sink.lock().unwrap() = None }, + KILL_REQ => { + let id = if frame.session != 0 { frame.session } else { + json(&frame.payload).get("session_id").and_then(|x| x.as_u64()).unwrap_or(0) as u32 + }; + let target = registry().lock().unwrap().get(&id).cloned(); + match target { + Some(s) => { *s.sink.lock().unwrap() = None; s.signal(libc::SIGHUP); s.signal(libc::SIGKILL); self.send(KILL_RESP, id, &reply(0, "ok")); } + None => self.send(KILL_RESP, id, &reply(1, "Session not found")), + } + } + LIST_REQ => { + let sessions: Vec = registry().lock().unwrap().values().map(|s| { + let attached = s.sink.lock().unwrap().is_some(); + serde_json::json!({"session_id": s.id, "name": format!("bash-{}", s.id), "shell": s.shell, + "state": if attached { "running" } else { "detached" }, "created_at_ms": s.created_ms}) + }).collect(); + log::info!("Terminal list sessions: count={}", sessions.len()); + self.send(LIST_RESP, 0, serde_json::json!({"code": 0, "message": "ok", "sessions": sessions}).to_string().as_bytes()); + } + UNLOCK_REQ => self.send(UNLOCK_RESP, frame.session, &reply(0, "ok")), + _ => self.send(ERROR, frame.session, &reply(1, "unsupported frame")), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn frame_round_trip_matches_official_layout() { + let f = encode(OPEN_RESP, 7, b"{}"); + assert_eq!(&f[..8], &[b'T', b'E', b'R', b'M', 1, 13, 0, 0]); + assert_eq!(&f[8..16], &[7, 0, 0, 0, 2, 0, 0, 0]); + assert_eq!(decode(&f), Some(Frame { kind: 13, flags: [0, 0], session: 7, payload: b"{}".to_vec() })); + assert_eq!(decode(&f[..17]), None); + let mut bad = f.clone(); bad[5] = 17; assert_eq!(decode(&bad), None); + } + #[test] + fn signal_names_map_to_posix_numbers() { + assert_eq!(signal_number(b"SIGTERM"), libc::SIGTERM); + assert_eq!(signal_number(br#"{"signal":"SIGKILL"}"#), libc::SIGKILL); + assert_eq!(signal_number(b"whatever"), libc::SIGINT); + } + #[test] + fn open_spawns_shell_and_streams_output() { + let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); + let conn = TerminalConn::new(tx); + conn.handle(&encode(OPEN, 0, br#"{"cols":100,"rows":30,"shell":"/bin/sh"}"#)); + let resp = decode(&rx.blocking_recv().unwrap()).unwrap(); + assert_eq!(resp.kind, OPEN_RESP); + assert_eq!(json(&resp.payload)["code"], 0); + conn.handle(&encode(STDIN, resp.session, b"echo uu-term-ok; exit 3\n")); + let mut seen = Vec::new(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10); + let mut exit = None; + while std::time::Instant::now() < deadline && exit.is_none() { + if let Ok(m) = rx.try_recv() { + let f = decode(&m).unwrap(); + if f.kind == STDOUT { seen.extend(f.payload) } else if f.kind == EXIT { exit = Some(json(&f.payload)["exit_code"].clone()) } + } else { std::thread::sleep(std::time::Duration::from_millis(20)); } + } + assert!(String::from_utf8_lossy(&seen).contains("uu-term-ok")); + assert_eq!(exit, Some(serde_json::json!(3))); + } +} + +/// Terminal RPCs carried in Message 21 RpcRequest: 28 terminal_check_env_req (CheckEnvReq, empty) +/// -> RpcResponse 24 CheckEnvResp{1 code, 2 message}; 29 RenameSessionReq{1 session_id, 2 name} +/// -> RpcResponse 26 RenameSessionResp{1 session_id, 2 code, 3 message}. Returns the RpcResponse body. +pub fn rpc_response(rpc: &[crate::protocol::WireField]) -> Option> { + use crate::protocol::WireValue; + fn varint(mut v: u64, out: &mut Vec) { while v >= 128 { out.push((v as u8 & 127) | 128); v >>= 7; } out.push(v as u8); } + fn bytes(field: u64, v: &[u8], out: &mut Vec) { varint(field << 3 | 2, out); varint(v.len() as u64, out); out.extend_from_slice(v); } + let header = rpc.iter().find_map(|f| match (f.number, &f.value) { (1, WireValue::Bytes(b)) => Some(*b), _ => None }).unwrap_or(&[]); + let mut out = Vec::new(); + bytes(1, header, &mut out); + if rpc.iter().any(|f| f.number == 28) { + let mut body = Vec::new(); + bytes(2, b"ok", &mut body); // code 0 (default) = available + bytes(24, &body, &mut out); + log::info!("Terminal check_env answered: available"); + return Some(out); + } + if let Some(WireValue::Bytes(req)) = rpc.iter().find(|f| f.number == 29).map(|f| &f.value) { + let fields = crate::protocol::decode_wire(req).ok()?; + let session = fields.iter().find_map(|f| match (f.number, &f.value) { (1, WireValue::Varint(v)) => Some(*v), _ => None }).unwrap_or(0); + let mut body = Vec::new(); + if session != 0 { varint(1 << 3, &mut body); varint(session, &mut body); } + bytes(3, b"ok", &mut body); + bytes(26, &body, &mut out); + log::info!("Terminal rename answered: session={}", session); + return Some(out); + } + None +} diff --git a/src/video.rs b/src/video.rs new file mode 100644 index 0000000..4dcdf61 --- /dev/null +++ b/src/video.rs @@ -0,0 +1,410 @@ +use std::sync::Arc; +use std::time::{Duration, Instant}; +use tokio::io::AsyncReadExt; +use tokio::process::Command; +use tokio::sync::mpsc; +use webrtc::media::Sample; +use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState; +use webrtc::peer_connection::RTCPeerConnection; +use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample; +use crate::capture_setting::VideoSettings; + +/// Default frame rate; the viewer's 帧率 setting overrides it per connection. +pub const FPS: u64 = 60; +/// IDR every 0.5s. All-intra 60fps measured 30 Mbit/s on the real desktop (saturating +/// the viewer's Wi-Fi: 3-6 fps received); GOP 30 measured 2.7 Mbit/s at the same CQ18. +/// A broken prediction chain therefore freezes at most this long. +const GOP: u64 = 30; +const MAX_ACCESS_UNIT: usize = 8 * 1024 * 1024; + +fn nal_offsets(bytes: &[u8], kind: u8) -> Vec { + let mut result = Vec::new(); + let mut i = 0; + while i + 3 < bytes.len() { + let prefix = if bytes[i..].starts_with(&[0, 0, 0, 1]) { 4 } + else if bytes[i..].starts_with(&[0, 0, 1]) { 3 } else { i += 1; continue }; + if i + prefix < bytes.len() && bytes[i + prefix] & 31 == kind { result.push(i); } + i += prefix; + } + result +} +fn aud_offsets(bytes: &[u8]) -> Vec { nal_offsets(bytes, 9) } +fn is_independent_frame(bytes: &[u8]) -> bool { + !nal_offsets(bytes, 5).is_empty() && nal_offsets(bytes, 1).is_empty() +} + +#[derive(Debug)] +struct CompleteFrame { + sequence: u64, + completed_at: Instant, + data: Vec, +} + +const RTP_CLOCK: u64 = 90_000; + +/// `UU_VIDEO_ENCODER=cpu` keeps the virtual CPU display entirely off the GPU. +pub fn gpu_encoder_requested() -> bool { + std::env::var("UU_VIDEO_ENCODER").map_or(true, |v| v != "cpu") +} + +/// Round UP (+1ns float guard) so webrtc's floor(duration*90000) yields exactly `ticks`. +fn ticks_to_duration(ticks: u64) -> Duration { + Duration::from_nanos((ticks * 1_000_000_000 + RTP_CLOCK - 1) / RTP_CLOCK + 1) +} + +/// RTP timestamps follow when frames actually leave the encoder, not a nominal +/// 60fps count: a starved X11 capture would otherwise stamp 5fps as 60fps. +/// webrtc-rs stamps a sample with the running timestamp and only then advances it +/// by the sample duration, so each duration predicts the gap to the NEXT frame +/// (one nominal frame after this one). A stall costs one frame of timing error +/// and is corrected on the following frame instead of accumulating. +struct RtpTimeline { origin: Option, stamp: u64, fps: u64 } +impl Default for RtpTimeline { fn default() -> Self { Self { origin: None, stamp: 0, fps: FPS } } } +impl RtpTimeline { + fn duration_after(&mut self, completed_at: Instant) -> Duration { + let origin = *self.origin.get_or_insert(completed_at); + let real = ((completed_at.saturating_duration_since(origin).as_nanos() * u128::from(RTP_CLOCK) + 500_000_000) / 1_000_000_000) as u64; + let advance = (real + RTP_CLOCK / self.fps).saturating_sub(self.stamp).max(1); + self.stamp += advance; + ticks_to_duration(advance) + } +} + +/// Frames travel through a short queue so P-frames are never silently replaced. +/// After an overflow, dependent frames are skipped until the next IDR, so the +/// viewer never receives a broken prediction chain and no backlog can build up. +struct DependencyGate {needs_idr:bool} +impl Default for DependencyGate {fn default()->Self{Self{needs_idr:true}}} +impl DependencyGate{ + fn submit(&mut self,tx:&mpsc::Sender>,frame:Arc){ + if self.needs_idr&&!is_independent_frame(&frame.data){return;} + match tx.try_send(frame){ + Ok(())=>self.needs_idr=false, + Err(mpsc::error::TrySendError::Full(_))=>self.needs_idr=true, + Err(mpsc::error::TrySendError::Closed(_))=>{}, + } + } +} + +// Aborting the owner task drops Child, whose kill_on_drop kills only this encoder. +struct EncoderTask(tokio::task::JoinHandle>); +impl Drop for EncoderTask { fn drop(&mut self) { self.0.abort(); } } + +async fn read_encoder( + size: (u32, u32), display: String, portal:Option>, + latest: mpsc::Sender>, + settings: VideoSettings, sequence: Arc, +) -> Result<(), String> { + // The sequence is shared so a CPU fallback or settings restart continues it (skip statistics stay correct). + if !gpu_encoder_requested() { return read_encoder_with(size,display,portal,latest,false,sequence,settings).await; } + match read_encoder_with(size,display.clone(),portal.clone(),latest.clone(),true,sequence.clone(),settings).await { + Ok(())=>Ok(()), + Err(error) if !latest.is_closed()=>{ + log::warn!("NVENC stream unavailable; switching scoped encoder to CPU: {}",error); + read_encoder_with(size,display,portal,latest,false,sequence,settings).await + }, + Err(error)=>Err(error), + } +} + +/// Rate-control arguments: constant quality capped at 30M (自动), or capped at the viewer's +/// chosen bitrate. The VBV buffer stays at most 500k so a cap never adds queueing latency. +fn rate_args(settings: &VideoSettings) -> (String, String) { + let max_kbps = settings.max_kbps().unwrap_or(30_000); + let buffer_kbits = (max_kbps / 8).clamp(100, 500); + (format!("{max_kbps}k"), format!("{buffer_kbits}k")) +} + +async fn read_encoder_with( + size: (u32,u32),display:String,portal:Option>,latest:mpsc::Sender>,gpu:bool,sequence:Arc, + mut settings: VideoSettings, +)->Result<(),String>{ + let size = format!("{}x{}", size.0, size.1); + let wayland=display.starts_with("wayland:"); + // The separate wayland-capture process produces frames at its own fixed rate. + if wayland && portal.is_none() { settings.fps = FPS as u32; } + let fps = settings.fps.to_string(); + // Keep the IDR interval at 0.5 s whatever the frame rate. + let gop = (u64::from(settings.fps) * GOP / FPS).max(1).to_string(); + let (maxrate, bufsize) = rate_args(&settings); + let cq = settings.cq().to_string(); + let target = settings.max_kbps().map_or("16M".to_string(), |k| format!("{}k", k * 3 / 4)); + log::info!("Desktop encoder: display={} source={} output={:?} fps={} cq={} maxrate={} encoder={} low_latency=true",display,size,settings.output,settings.fps,cq,maxrate,if gpu{"h264_nvenc"}else{"libx264"}); + // A bundled FFmpeg prefix (config ffmpeg_root / UU_FFMPEG_ROOT) or `ffmpeg` on PATH. + let mut command=match crate::config::ffmpeg_root() { + Some(root) => { let mut c=Command::new(root.join("bin/ffmpeg")); c.env("LD_LIBRARY_PATH",root.join("lib/x86_64-linux-gnu")); c } + None => Command::new("ffmpeg"), + }; + command.args(["-hide_banner","-loglevel","error","-nostdin"]); + if wayland { + command.args(["-f","rawvideo","-pixel_format","bgra","-video_size",&size, + "-framerate",&fps,"-i","pipe:0","-an"]); + } else { + // The viewer draws its local pointer; do not bake a second into video. + command.args(["-f","x11grab","-draw_mouse","0","-framerate",&fps, + "-video_size",&size,"-i",&display,"-an"]); + } + // 其他分辨率: scale the captured desktop (the host display mode is left untouched). + if let Some((width, height)) = settings.output { + command.args(["-vf", &format!("scale={width}:{height}:flags=bilinear")]); + } + if gpu{ + command.args(["-c:v","h264_nvenc","-preset","p4","-tune","ull", + "-profile:v","baseline","-pix_fmt","yuv420p","-g",&gop,"-bf","0", + "-rc","vbr","-cq",&cq,"-b:v",&target,"-maxrate",&maxrate,"-bufsize",&bufsize, + "-rc-lookahead","0","-zerolatency","1","-delay","0","-aud","1"]); + }else{ + let x264 = format!("aud=1:repeat-headers=1:scenecut=0:keyint={gop}:min-keyint={gop}"); + command.args([ + "-c:v", "libx264", "-preset", "superfast", "-tune", "zerolatency", + "-profile:v", "baseline", "-pix_fmt", "yuv420p", "-g", &gop, "-threads", "4", + "-crf", &cq, "-maxrate", &maxrate, "-bufsize", &bufsize, + "-x264-params", &x264]); + } + // x11grab paces against an absolute schedule; after a capture stall it grabs + // back-to-back to "catch up" (measured 69 frames in 200ms). vfr on a 1/FPS + // timebase drops those same-slot frames instead of encoding a burst. + let time_base = format!("1/{fps}"); + if wayland { command.stdin(std::process::Stdio::piped()); } + let mut child=command.args(["-fps_mode","vfr","-enc_time_base",&time_base,"-f","h264","pipe:1"]) + .kill_on_drop(true) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::inherit()) + .spawn().map_err(|e| format!("Start scoped encoder: {e}"))?; + // Scope capture to this encoder. Dropping either task kills its child. + let _capture=if let Some(session)=portal { + let mut sink=child.stdin.take().ok_or("Encoder stdin missing")?; + Some(EncoderTask(tokio::spawn(async move { + use tokio::io::AsyncWriteExt; + let interval=Duration::from_nanos(1_000_000_000/u64::from(settings.fps)); + let mut tick=tokio::time::interval(interval); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + loop { + tick.tick().await; + let session=session.clone(); + let frame=tokio::task::spawn_blocking(move || { + let mut frame=vec![0;(session.width as usize)*(session.height as usize)*4]; + session.capture(&mut frame)?; + Ok::<_,String>(frame) + }).await.map_err(|e|format!("Portal capture worker: {e}"))??; + sink.write_all(&frame).await.map_err(|e|format!("Portal encoder pipe: {e}"))?; + } + }))) + } else if wayland { + // Linux keeps the running executable inode accessible after a scoped + // development/release replacement; current_exe may name a deleted path. + #[cfg(target_os="linux")] + let executable=std::path::PathBuf::from("/proc/self/exe"); + #[cfg(not(target_os="linux"))] + let executable=std::env::current_exe().map_err(|e|format!("Capture executable: {e}"))?; + let mut capture=Command::new(executable).arg("wayland-capture") + .kill_on_drop(true).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::inherit()) + .spawn().map_err(|e|format!("Start Wayland capture: {e}"))?; + let mut source=capture.stdout.take().ok_or("Capture stdout missing")?; + let mut sink=child.stdin.take().ok_or("Encoder stdin missing")?; + Some(EncoderTask(tokio::spawn(async move { + let result=tokio::io::copy(&mut source,&mut sink).await; + drop(capture); + result.map(|_|()).map_err(|e|format!("Wayland frame pipe: {e}")) + }))) + } else { None }; + let mut stdout = child.stdout.take().ok_or("Encoder stdout missing")?; + let mut pending = Vec::new(); + let mut chunk = [0u8; 16384]; + let mut gate = DependencyGate::default(); + loop { + let count = stdout.read(&mut chunk).await.map_err(|e| format!("Encoder read: {e}"))?; + if count == 0 { return Err("Encoder output ended".into()); } + pending.extend_from_slice(&chunk[..count]); + // A chunk can include the next AUD, so split before enforcing the bound. + loop { + let aud = aud_offsets(&pending); + if aud.len() < 2 { break; } + let next = aud[1]; + if next > MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); } + let frame: Vec = pending.drain(..next).collect(); + let sequence = sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + gate.submit(&latest, Arc::new(CompleteFrame { + sequence, completed_at: Instant::now(), data: frame, + })); + if latest.is_closed() { return Ok(()); } + } + if pending.len() > MAX_ACCESS_UNIT { return Err("Encoder access unit exceeds limit".into()); } + } +} + +fn transport_closed(pc: &RTCPeerConnection) -> bool { + matches!(pc.connection_state(), RTCPeerConnectionState::Closed | RTCPeerConnectionState::Failed) + || pc.sctp().state() == webrtc::sctp_transport::sctp_transport_state::RTCSctpTransportState::Closed +} + +/// Exercise the real capture/encoder chain without UU auth or a network peer. +pub async fn probe(size:(u32,u32),display:String,portal:Option>,path:Option)->Result<(),String> { + use std::io::Write; + let mut file=match path { + Some(path)=>Some(std::fs::OpenOptions::new().write(true).create_new(true).open(path).map_err(|e|format!("Video probe file: {e}"))?), + None=>None, + }; + let (tx,mut rx)=mpsc::channel(4); + let sequence=Arc::new(std::sync::atomic::AtomicU64::new(0)); + let _reader=EncoderTask(tokio::spawn(read_encoder(size,display,portal,tx,VideoSettings::default(),sequence))); + let mut count=0; + let mut bytes=0; + tokio::time::timeout(Duration::from_secs(15),async { + while count<5 { + let frame=rx.recv().await.ok_or("Video probe encoder ended")?; + if count==0 && !is_independent_frame(&frame.data) { return Err("Video probe did not begin with IDR".to_owned()); } + if let Some(file)=file.as_mut() { file.write_all(&frame.data).map_err(|e|e.to_string())?; } + bytes+=frame.data.len(); count+=1; + } + Ok::<(),String>(()) + }).await.map_err(|_|"Video probe timed out".to_owned())??; + println!("Encoded capture probe: frames={count} h264_bytes={bytes} first_frame_idr=true"); + Ok(()) +} + +pub async fn stream_desktop(pc: Arc, track: Arc, size: (u32, u32), display: String, portal:Option>, + mut settings: tokio::sync::watch::Receiver) -> Result<(), String> { + loop { + if transport_closed(&pc) { return Ok(()); } + if pc.connection_state() == RTCPeerConnectionState::Connected + && pc.sctp().state() == webrtc::sctp_transport::sctp_transport_state::RTCSctpTransportState::Connected { break; } + tokio::time::sleep(Duration::from_millis(100)).await; + } + crate::capture::keep_display_awake()?; + let (latest, mut receiver) = mpsc::channel(4); + let sequence = Arc::new(std::sync::atomic::AtomicU64::new(0)); + let current = *settings.borrow_and_update(); + let mut reader = EncoderTask(tokio::spawn(read_encoder(size, display.clone(), portal.clone(), latest.clone(), current, sequence.clone()))); + let mut previous = None; + let mut timeline = RtpTimeline { fps: u64::from(current.fps), ..Default::default() }; + let mut settings_open = true; + let mut frames = 0u64; + let mut skipped = 0u64; + let mut max_age_ms = 0u128; + let mut max_send_ms = 0u128; + let mut health = tokio::time::interval(Duration::from_millis(200)); + health.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); + let mut stats = Instant::now(); + loop { + tokio::select! { + result = &mut reader.0 => return result.map_err(|e| format!("Encoder reader task: {e}"))?, + _ = health.tick() => { if transport_closed(&pc) { return Ok(()); } }, + changed = settings.changed(), if settings_open => { + if changed.is_err() { settings_open = false; continue; } + // Restart the encoder with the viewer's new 帧率/画质; it begins with an IDR, and frames + // still queued from the old encoder remain a valid chain before it. + let next = *settings.borrow_and_update(); + timeline.fps = u64::from(next.fps); + reader = EncoderTask(tokio::spawn(read_encoder(size, display.clone(), portal.clone(), latest.clone(), next, sequence.clone()))); + }, + frame = receiver.recv() => { + // A closed queue means the reader ended; its JoinHandle carries the reason. + let Some(frame) = frame else { return (&mut reader.0).await.map_err(|e| format!("Encoder reader task: {e}"))?; }; + let duration = timeline.duration_after(frame.completed_at); + if let Some(last) = previous { skipped += frame.sequence.saturating_sub(last + 1); } + max_age_ms = max_age_ms.max(frame.completed_at.elapsed().as_millis()); + // Continue monitoring close even if the network send stalls. + let sample = Sample { + data: frame.data.clone().into(), duration, ..Default::default() + }; + let extensions = [crate::rtp_metadata::capture_index(0), crate::rtp_metadata::new_frame()]; + let send = track.write_sample_with_extensions(&sample, &extensions); + let send_started=Instant::now(); + tokio::pin!(send); + loop { + tokio::select! { + result = &mut send => { result.map_err(|e| format!("Video send: {e}"))?; break; }, + _ = health.tick() => { if transport_closed(&pc) { return Ok(()); } }, + } + } + previous = Some(frame.sequence); + max_send_ms=max_send_ms.max(send_started.elapsed().as_millis()); + frames += 1; + if stats.elapsed() >= Duration::from_secs(30) { + crate::capture::keep_display_awake()?; + log::info!("Desktop latest-frame stats: sent={} skipped={} latest_seq={} max_slot_age_ms={} max_send_ms={}", frames, skipped, frame.sequence, max_age_ms,max_send_ms); + stats = Instant::now(); + max_age_ms = 0; + max_send_ms = 0; + } + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn boundaries_accept_complete_idr_and_reject_dependent_frames() { + let bytes = [0,0,0,1,9,240,0,0,1,7,1,0,0,1,5,42,0,0,1,9,240]; + assert_eq!(aud_offsets(&bytes), vec![0,16]); + assert!(is_independent_frame(&bytes[..16])); + assert!(!is_independent_frame(&[0,0,1,9,240,0,0,1,1,42])); + assert!(!is_independent_frame(&[0,0,1,7,1,0,0,0,1])); + } + #[test] + fn rtp_ticks_survive_webrtc_floor_conversion(){ + for ticks in (1..=200_000).chain([90_000*60, 90_000*3600]) { + assert_eq!((ticks_to_duration(ticks).as_secs_f64()*90000.) as u64,ticks); + } + } + fn stamps(offsets_ms:&[u64])->Vec{ + let start=Instant::now(); + let mut timeline=RtpTimeline::default(); + let mut stamp=0; + offsets_ms.iter().map(|ms|{ + let current=stamp; + stamp+=(timeline.duration_after(start+Duration::from_millis(*ms)).as_secs_f64()*90000.) as u64; + current + }).collect() + } + #[test] + fn steady_60fps_keeps_exact_1500_tick_spacing_for_an_hour(){ + let start=Instant::now(); + let mut timeline=RtpTimeline::default(); + let mut stamp=0u64; + for frame in 0..216_000u64 { + let at=start+Duration::from_nanos(frame*1_000_000_000/FPS); + assert_eq!(stamp,frame*1500); + stamp+=(timeline.duration_after(at).as_secs_f64()*90000.) as u64; + } + } + #[test] + fn starved_capture_is_stamped_at_real_time_not_nominal_60fps(){ + // 5fps capture: frames 200ms apart must be ~18000 ticks apart, not 1500. + let s=stamps(&[0,200,400,600,800]); + assert_eq!(s[0],0); + for pair in s.windows(2).skip(1) { assert_eq!(pair[1]-pair[0],18_000); } + } + #[test] + fn stall_costs_one_frame_then_timeline_matches_real_time(){ + let s=stamps(&[0,17,517,534,551]); + assert_eq!(s[2],17*90+1500); // predicted before the stall was visible + assert_eq!(s[3],517*90+1500); // realigned: one nominal frame after real stall end + assert_eq!(s[4],534*90+1500); // no residual offset accumulates + assert!(s.windows(2).all(|p|p[1]>p[0])); + } + #[tokio::test] + async fn bounded_queue_never_sends_broken_prediction_chain_after_overload(){ + let(tx,mut rx)=mpsc::channel(1); + let mut gate=DependencyGate::default(); + let frame=|sequence,idr|Arc::new(CompleteFrame{sequence,completed_at:Instant::now(),data:vec![0,0,1,9,240,0,0,1,if idr{5}else{1},42]}); + gate.submit(&tx,frame(1,false));assert!(rx.try_recv().is_err()); // no IDR yet + gate.submit(&tx,frame(2,true)); + gate.submit(&tx,frame(3,false)); // queue full: P3 lost + assert_eq!(rx.recv().await.unwrap().sequence,2); + gate.submit(&tx,frame(4,false)); // P4 references lost P3 + assert!(rx.try_recv().is_err()); + gate.submit(&tx,frame(31,true));assert_eq!(rx.recv().await.unwrap().sequence,31); + gate.submit(&tx,frame(32,false));assert_eq!(rx.recv().await.unwrap().sequence,32); + } + #[test] + fn nvenc_idr_with_parameter_sets_is_independent(){ + // AUD, SPS, PPS, IDR slice as h264_nvenc emits every GOP (verified on the 3090). + let idr=[0,0,0,1,9,16,0,0,0,1,7,66,0,0,0,1,8,206,0,0,1,5,136]; + assert!(is_independent_frame(&idr)); + assert!(!is_independent_frame(&[0,0,0,1,9,48,0,0,1,1,154])); + } +} diff --git a/src/viewer_metrics.rs b/src/viewer_metrics.rs new file mode 100644 index 0000000..e409d0a --- /dev/null +++ b/src/viewer_metrics.rs @@ -0,0 +1,72 @@ +//! Bounded viewer telemetry extraction. Payloads and nonnumeric values never log. +use base64::Engine; +use std::io::Read; +use serde_json::Value; +const LIMIT:usize=256*1024; +fn permitted(key:&str)->bool{ + ["avg_received_fps","avg_decode_fps","avg_render_fps","avg_assembly_ms_interval","avg_current_delay_ms_interval","avg_decode_ms_interval","avg_delay_ms_interval","avg_jitter_buffer_ms_interval","avg_processing_delay_interval","avg_render_delay_ms_interval","avg_target_delay_ms_interval","received_framerate","actual_received_framerate","decode_framerate","render_framerate","actual_framerate", + "current_delay","average_delay","max_delay","current_delay_ms_interval","target_delay_ms_interval", + "jitter_buffer_ms_interval","render_delay_ms_interval","assembly_ms_interval","decode_ms_interval", + "processing_delay_interval","sending_delay_interval","frames_received","frames_decoded","frames_actual_rendered", + "packets_received","packets_lost","packet_loss_rate","current_packet_loss_rate", + "frame_capture_delay_ms_interval","frame_encode_delay_ms_interval","frame_pacer_delay_ms_interval", + "frame_transport_delay_ms_interval","frame_decode_delay_ms_interval","frame_e2e_delay_ms_interval"].contains(&key) +} +fn unpack(text:&str)->Option{ + if text.len()>LIMIT{return None;} + if let Ok(value)=serde_json::from_str(text){return Some(value);} + let bytes=base64::engine::general_purpose::STANDARD.decode(text).ok()?; + let mut output=Vec::new(); + if bytes.starts_with(&[31,139]){ + flate2::read::GzDecoder::new(&bytes[..]).take(LIMIT as u64+1).read_to_end(&mut output).ok()?; + }else if bytes.first()==Some(&0x78){ + flate2::read::ZlibDecoder::new(&bytes[..]).take(LIMIT as u64+1).read_to_end(&mut output).ok()?; + }else{output=bytes;} + if output.len()>LIMIT{return None;}serde_json::from_slice(&output).ok() +} +pub fn collect(event:&Value)->Vec<(String,f64)>{ + fn walk(v:&Value,path:&str,selected:bool,depth:usize,budget:&mut usize,out:&mut Vec<(String,f64)>){ + if depth>12||*budget==0||out.len()>=128{return;}*budget-=1; + match v{ + Value::Number(n) if selected=>{if let Some(n)=n.as_f64(){out.push((path.into(),n));}}, + Value::Object(map)=>for(k,v)in map{ + let allowed=permitted(k); + // After selecting a metric, only numeric aggregation keys are retained. + let aggregation=selected&&["min","max","avg","mean","sum","count","value","current","total"].contains(&k.as_str()); + let next=if allowed||aggregation{format!("{path}.{k}")}else{path.into()}; + walk(v,&next,allowed||aggregation,depth+1,budget,out); + }, + Value::Array(a)=>for v in a{walk(v,path,selected,depth+1,budget,out);}, + Value::String(text)=>{ + if selected{if let Ok(number)=text.parse::(){if number.is_finite(){out.push((path.into(),number));return;}}} + if let Some(unpacked)=unpack(text){walk(&unpacked,path,selected,depth+1,budget,out);} + },_=>{} + } + } + let mut output=Vec::new();walk(event,"stats",false,0,&mut 8192,&mut output);output +} +pub fn safe_shape(event:&Value)->Vec<(String,&'static str)>{ + fn walk(v:&Value,path:&str,depth:usize,out:&mut Vec<(String,&'static str)>){ + if depth>3||out.len()>=24{return;} + let kind=match v{Value::Object(_)=>"object",Value::Array(_)=>"array",Value::String(_)=>"string",Value::Number(_)=>"number",Value::Bool(_)=>"bool",Value::Null=>"null"}; + out.push((path.into(),kind)); + if let Value::Object(map)=v{for(k,v)in map{ + if k.len()<=48&&k.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_'){walk(v,&format!("{path}.{k}"),depth+1,out);} + }} + } + let mut output=Vec::new();walk(event,"event",0,&mut output);output +} +#[cfg(test)]mod tests{ + use super::*; + #[test]fn extracts_compressed_metrics_but_no_private_values(){ + use std::io::Write; + let text=r#"{"token":"secret","current_delay_ms_interval":{"avg":17},"render_framerate":60}"#; + let mut z=flate2::write::GzEncoder::new(Vec::new(),flate2::Compression::default());z.write_all(text.as_bytes()).unwrap(); + let encoded=base64::engine::general_purpose::STANDARD.encode(z.finish().unwrap()); + assert_eq!(collect(&serde_json::json!({"data":encoded})),vec![("stats.current_delay_ms_interval.avg".into(),17.),("stats.render_framerate".into(),60.)]); + } + #[test]fn limits_depth_and_preserves_numeric_strings(){ + assert_eq!(collect(&serde_json::json!({"render_framerate":"59.9","cookie":12})),vec![("stats.render_framerate".into(),59.9)]); + assert!(unpack(&"A".repeat(LIMIT+1)).is_none()); + } +} diff --git a/src/wayland.rs b/src/wayland.rs new file mode 100644 index 0000000..df11e85 --- /dev/null +++ b/src/wayland.rs @@ -0,0 +1,90 @@ +//! Hyprland/wlroots native backend. No XWayland fallback and no input logging. +#[cfg(all(target_os="linux", feature="wayland"))] +extern "C" { + fn uu_wl_init(out_w: *mut i32, out_h: *mut i32) -> i32; + fn uu_wl_capture(buffer: *mut u8, length: usize) -> i32; + fn uu_wl_move(x: i32, y: i32, relative: i32) -> i32; + fn uu_wl_button(button: i32, pressed: i32) -> i32; + fn uu_wl_key(symbol: u64, pressed: i32) -> i32; + fn uu_wl_wake() -> i32; +} +pub fn init() -> Result<(u32,u32),String> { + #[cfg(all(target_os="linux", feature="wayland"))] + { + let (mut w,mut h)=(0,0); + let result=unsafe { uu_wl_init(&mut w,&mut h) }; + if result != 0 || w <= 0 || h <= 0 { + return Err(format!("Wayland initialization failed ({result}); requires screencopy, virtual keyboard and virtual pointer. Check UU_WAYLAND_OUTPUT and session environment.")); + } + return Ok((w as u32,h as u32)); + } + #[cfg(not(all(target_os="linux", feature="wayland")))] + Err("Wayland backend requires Linux and a build with --features wayland".into()) +} +pub fn capture(buffer:&mut [u8]) -> Result<(),String> { + #[cfg(all(target_os="linux", feature="wayland"))] + { let result=unsafe { uu_wl_capture(buffer.as_mut_ptr(),buffer.len()) }; if result==0 { return Ok(()) } return Err(format!("Wayland capture failed ({result})")); } + #[cfg(not(all(target_os="linux", feature="wayland")))] + { let _=buffer; Err("Wayland capture unavailable".into()) } +} +pub fn wake()->Result<(),String> { + #[cfg(all(target_os="linux", feature="wayland"))] + { let result=unsafe { uu_wl_wake() }; if result==0 { return Ok(()); } return Err("Wayland output power control unavailable".into()); } + #[cfg(not(all(target_os="linux", feature="wayland")))] + Err("Wayland output power control unavailable".into()) +} +pub fn move_pointer(x:i32,y:i32,relative:bool)->i32 { + #[cfg(all(target_os="linux", feature="wayland"))] + { return unsafe { uu_wl_move(x,y,i32::from(relative)) }; } + #[cfg(not(all(target_os="linux", feature="wayland")))] + { let _=(x,y,relative); -1 } +} +pub fn button(button:i32,pressed:bool)->i32 { + #[cfg(all(target_os="linux", feature="wayland"))] + { return unsafe { uu_wl_button(button,i32::from(pressed)) }; } + #[cfg(not(all(target_os="linux", feature="wayland")))] + { let _=(button,pressed); -1 } +} +pub fn key(symbol:u64,pressed:bool)->i32 { + #[cfg(all(target_os="linux", feature="wayland"))] + { return unsafe { uu_wl_key(symbol,i32::from(pressed)) }; } + #[cfg(not(all(target_os="linux", feature="wayland")))] + { let _=(symbol,pressed); -1 } +} + +/// A separate process owns capture; encoder cancellation closes its pipe. +pub fn capture_stdout() -> Result<(),String> { + use std::io::Write; + let (w,h)=init()?; + let mut frame=vec![0u8;(w as usize)*(h as usize)*4]; + let mut stdout=std::io::stdout().lock(); + let interval=std::time::Duration::from_nanos(1_000_000_000/crate::video::FPS); + loop { + let start=std::time::Instant::now(); + capture(&mut frame)?; + stdout.write_all(&frame).map_err(|e|format!("Capture pipe: {e}"))?; + if let Some(left)=interval.checked_sub(start.elapsed()) { std::thread::sleep(left); } + } +} + +/// Use only in an isolated acceptance desktop; emits fixed test events, no logs. +pub fn input_probe()->Result<(),String> { + let (w,h)=init()?; + wake()?; + if move_pointer((w/4) as i32,(h/4) as i32,false)!=0 { return Err("Pointer probe failed".into()); } + std::thread::sleep(std::time::Duration::from_millis(50)); + if move_pointer((w/2) as i32,(h/2) as i32,false)!=0 { return Err("Pointer probe failed".into()); } + std::thread::sleep(std::time::Duration::from_millis(100)); + if button(1,true)!=0 || button(1,false)!=0 { return Err("Button probe failed".into()); } + std::thread::sleep(std::time::Duration::from_millis(100)); + if move_pointer(32,0,true)!=0 { return Err("Relative pointer probe failed".into()); } + std::thread::sleep(std::time::Duration::from_millis(100)); + for symbol in b"uuwayland" { + if key(u64::from(*symbol),true)!=0 || key(u64::from(*symbol),false)!=0 { + return Err("Keyboard probe failed".into()); + } + } + std::thread::sleep(std::time::Duration::from_millis(250)); + println!("Wayland test events sent; verify the native GTK acceptance report."); + Ok(()) +} diff --git a/src/webrtc.rs b/src/webrtc.rs new file mode 100644 index 0000000..fd2c711 --- /dev/null +++ b/src/webrtc.rs @@ -0,0 +1,942 @@ +//! Native Rust WebRTC Engine (PeerConnection, DataChannels, Input & Video) + +use crate::capture::ScreenCapture; +use crate::input::InputInjector; +use crate::signaling::SoacMessage; + +use base64::Engine; +use flate2::read::GzDecoder; +use std::io::Read; +use std::sync::Arc; +use tokio::sync::Mutex; +use webrtc::api::media_engine::MediaEngine; +use webrtc::api::APIBuilder; +use webrtc::data_channel::data_channel_message::DataChannelMessage; +use webrtc::data_channel::RTCDataChannel; +use webrtc::ice_transport::ice_candidate::RTCIceCandidateInit; +use webrtc::ice_transport::ice_server::RTCIceServer; +use webrtc::peer_connection::configuration::RTCConfiguration; +use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState; +use webrtc::peer_connection::sdp::session_description::RTCSessionDescription; +use webrtc::peer_connection::RTCPeerConnection; +use webrtc::media::Sample; +use webrtc::rtp_transceiver::rtp_codec::RTCRtpCodecCapability; +use webrtc::dtls_transport::dtls_role::DTLSRole; +use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample; +use webrtc::track::track_local::TrackLocalWriter; + +#[derive(Debug, Default, Clone)] +pub struct SessionContext { + pub client_id: Option, + pub ice_id: Option, + pub app_control_id: Option, + pub bundle_media: Option<(String, u16)>, +} + +pub struct WebRtcSession { + pub pc: Arc, + pub capture: Arc, + pub input: Arc, + pub desktop: bool, + pub context: Arc>, +} + +impl WebRtcSession { + pub async fn new( + capture: Arc, + input: Arc, + signaling_client: Arc, + desktop: bool, + transport:crate::session_ice::SessionIce, + ) -> Result { + let mut m = MediaEngine::default(); + m.register_default_codecs() + .map_err(|e| format!("Register standard codecs failed: {}", e))?; + + m.register_header_extension( + webrtc::rtp_transceiver::rtp_codec::RTCRtpHeaderExtensionCapability { uri: crate::rtp_metadata::CAPTURE_INDEX_URI.into() }, + webrtc::rtp_transceiver::rtp_codec::RTPCodecType::Video, None, + ).map_err(|e| format!("Register UU capture metadata failed: {}", e))?; + m.register_header_extension( + webrtc::rtp_transceiver::rtp_codec::RTCRtpHeaderExtensionCapability { uri: crate::rtp_metadata::NEW_FRAME_URI.into() }, + webrtc::rtp_transceiver::rtp_codec::RTPCodecType::Video, None, + ).map_err(|e| format!("Register UU fresh-frame metadata failed: {}", e))?; + let registry = webrtc::api::interceptor_registry::register_default_interceptors( + webrtc::interceptor::registry::Registry::new(), &mut m, + ).map_err(|e| format!("Register RTP/RTCP interceptors failed: {}", e))?; + let mut se = webrtc::api::setting_engine::SettingEngine::default(); + se.set_answering_dtls_role(DTLSRole::Server) + .map_err(|e| format!("Configure DTLS answer role failed: {}", e))?; + se.set_ice_multicast_dns_mode(webrtc::ice::mdns::MulticastDnsMode::Disabled); + // The viewer picked a ZeroTier pair even on the same LAN (36-81 ms, Wi-Fi + overlay); + // offering only physical interfaces keeps LAN direct, else srflx/relay like official hosts. + se.set_interface_filter(Box::new(|name: &str| ice_interface_allowed(name))); + + let api = APIBuilder::new() + .with_media_engine(m) + .with_setting_engine(se) + .with_interceptor_registry(registry) + .build(); + + let config = transport.configuration()?; + + let pc = Arc::new( + api.new_peer_connection(config) + .await + .map_err(|e| format!("Create PeerConnection failed: {}", e))?, + ); + + let context = Arc::new(Mutex::new(SessionContext::default())); + crate::network_diagnostics::start(Arc::downgrade(&pc)); + + // 监听本地 ICE Candidate 并自动发回信令服务器与客户端 + let context_ice = context.clone(); + let sig_ice = signaling_client.clone(); + pc.on_ice_candidate(Box::new(move |c: Option| { + let ctx = context_ice.clone(); + let sig = sig_ice.clone(); + Box::pin(async move { + if let Some(cand) = c { + if let Ok(init) = cand.to_json() { + let summary=crate::network_diagnostics::candidate_summary(&init.candidate); + log::info!("Local ICE candidate gathered: protocol={} type={}",summary.protocol,summary.kind); + let lock = ctx.lock().await; + if let Some(cid) = &lock.client_id { + let Some((mid, mline)) = lock.bundle_media.clone() else { + log::warn!("Local ICE candidate has no negotiated media section"); + return; + }; + + let cand_msg = SoacMessage { + msg_type: "candidate".into(), + sdp: None, + gzip_sdp: None, + candidate: Some(serde_json::json!({ + "candidate": init.candidate, + "sdpMid": mid, + "sdpMLineIndex": mline, + })), + ice_id: lock.ice_id.clone(), + sdp_mid: None, + sdp_mline_index: None, + client_id: Some(cid.clone()), + app_control_id: lock.app_control_id.clone(), + }; + if let Err(e) = sig.emit_soac(cand_msg).await { + log::error!("ICE signaling send failed: {}", e); + } + + + } else { + log::warn!("Local ICE candidate gathered but client_id not set yet"); + } + } + } else { + log::info!("Local ICE candidate gathering completed."); + } + }) + })); + + pc.on_ice_connection_state_change(Box::new(|state| { + log::info!("ICE Connection State changed: {:?}", state); + Box::pin(async move {}) + })); + + let connected_context = context.clone(); + let connection_input=input.clone(); + let connected_signal = signaling_client.clone(); + let notified = Arc::new(std::sync::atomic::AtomicBool::new(false)); + pc.on_peer_connection_state_change(Box::new(move |state| { + let ctx = connected_context.clone(); + let input=connection_input.clone(); + let sig = connected_signal.clone(); + let notified = notified.clone(); + Box::pin(async move { + log::info!("PeerConnection State changed: {:?}", state); + if matches!(state,RTCPeerConnectionState::Closed|RTCPeerConnectionState::Failed|RTCPeerConnectionState::Disconnected) {input.release_held();} + if state == RTCPeerConnectionState::Connected && !notified.swap(true, std::sync::atomic::Ordering::AcqRel) { + tokio::spawn(async move { + let ctx = ctx.lock().await.clone(); + if let (Some(client), Some(ice)) = (&ctx.client_id, ctx.ice_id.as_ref().and_then(|v| v.as_str())) { + let payload = crate::capability::h264_device_capability(client, ice, 0, crate::video::FPS as i32, 5); + if let Err(e) = sig.emit_event(crate::capability::FORWARD_SETTING_EVENT, payload).await { + log::error!("Device capability notification failed: {}", e); + } + if let Some(control) = ctx.app_control_id.as_ref().and_then(|v| v.as_str()) { + if let Err(e) = sig.emit_event(crate::capability::ICE_FINISHED_EVENT, + crate::capability::ice_finished(ice, control)).await { + log::error!("Connection completion notification failed: {}", e); + } + } + } + }); + } + }) + })); + + // 注册视频轨 + let video_track = Arc::new(TrackLocalStaticSample::new( + RTCRtpCodecCapability { + mime_type: "video/H264".to_owned(), + ..Default::default() + }, + "video_0".to_owned(), + "video_0".to_owned(), + )); + + let sender = pc.add_track(video_track.clone()).await + .map_err(|e| format!("Add video track failed: {}", e))?; + tokio::spawn(async move { + let mut feedback = [0u8; 1500]; + let mut reports = 0usize; + let mut feedback_counts = FeedbackCounts::default(); + while let Ok((packets, _)) = sender.read(&mut feedback).await { + for packet in packets { + feedback_counts.observe(packet.as_any()); + if let Some(report) = packet.as_any().downcast_ref::() { + reports += 1; + if reports == 1 || reports % 10 == 0 { + for r in &report.reports { + let now=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default(); + let ntp=(((now.as_secs()+2_208_988_800)&0xffff)<<16) as u32 | ((u64::from(now.subsec_nanos())*65536/1_000_000_000) as u32); + let elapsed=ntp.wrapping_sub(r.last_sender_report).wrapping_sub(r.delay); + let rtt=if r.last_sender_report!=0&&elapsed<65536*30 {Some(f64::from(elapsed)*1000./65536.)}else{None}; + log::info!("Video receiver report: ssrc={} last_sequence={} lost={} fraction_lost={} rtcp_rtt_ms={:?}",r.ssrc,r.last_sequence_number,r.total_lost,r.fraction_lost,rtt); + } + log::info!("Video feedback totals: nack_packets={} pli={} fir={}",feedback_counts.nack_packets,feedback_counts.pli,feedback_counts.fir); + } + } + } + } + }); + + // Desktop sound on the viewer's audio m-line (it always offers Opus). + if desktop && crate::audio::enabled() { + let audio_track = Arc::new(TrackLocalStaticSample::new( + RTCRtpCodecCapability { mime_type: "audio/opus".to_owned(), clock_rate: 48000, channels: 2, ..Default::default() }, + "audio_0".to_owned(), "audio_0".to_owned(), + )); + match pc.add_track(audio_track.clone()).await { + Ok(audio_sender) => { + // Drain RTCP so the interceptors keep running. + tokio::spawn(async move { let mut rtcp = [0u8; 1500]; while audio_sender.read(&mut rtcp).await.is_ok() {} }); + tokio::spawn(crate::audio::stream_audio(pc.clone(), audio_track)); + } + Err(e) => log::warn!("Add audio track failed: {}", e), + } + } + + // Encode current X11 frames only while a peer is connected. + let streaming_pc = pc.clone(); + let capture_size = (capture.width, capture.height); + let capture_display = capture.display.clone(); + // Per-connection 画质/帧率, changed by the viewer's capture-setting RPCs. + let (video_settings, video_settings_rx) = tokio::sync::watch::channel(crate::capture_setting::VideoSettings::default()); + let video_settings = Arc::new(video_settings); + // Per-connection mute / lock-after-session settings (安全 menu). + let peer_actions = Arc::new(crate::system_actions::PeerActions::default()); + let desktop_sound = desktop && crate::audio::enabled(); + if desktop { + let (end_pc, actions) = (pc.clone(), peer_actions.clone()); + tokio::spawn(async move { + { + use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState as State; + // Count the session once it is actually connected (a failed offer is not a session). + while end_pc.connection_state() != State::Connected { + if matches!(end_pc.connection_state(), State::Closed | State::Failed) { return; } + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + let starting = actions.clone(); + let _ = tokio::task::spawn_blocking(move || starting.session_started()).await; + } + use webrtc::peer_connection::peer_connection_state::RTCPeerConnectionState as State; + while !matches!(end_pc.connection_state(), State::Closed | State::Failed) { + tokio::time::sleep(std::time::Duration::from_secs(1)).await; + } + drop(end_pc); + let _ = tokio::task::spawn_blocking(move || actions.session_ended()).await; + }); + } + let portal=capture.portal.clone(); + // File/terminal/port-mapping connections carry no desktop video. + if desktop { + tokio::spawn(async move { + if let Err(e) = crate::video::stream_desktop(streaming_pc, video_track, capture_size, capture_display, portal, video_settings_rx).await { + log::error!("Live desktop stream stopped: {}", e); + } + }); + } else { + drop((streaming_pc, video_track, capture_size, capture_display, video_settings_rx)); + } + let input_clone = input.clone(); + let control_capture = capture.clone(); + let control_sequence = Arc::new(std::sync::atomic::AtomicU64::new(1)); + let text_clipboard_ready = Arc::new(std::sync::atomic::AtomicBool::new(false)); + // One file-transfer session per peer. The viewer may send FileTransferFtp RPCs on CONTROL, + // but it receives file traffic only through streamerDidReceiveFileData, so every reply and + // host-initiated request goes out on FILE_DATA_CHANNEL. + let file_channel: Arc>>> = Arc::new(std::sync::Mutex::new(None)); + let (file_tx, mut file_rx) = tokio::sync::mpsc::unbounded_channel::>(); + let peer_files = crate::file_trans::FileSession::new(file_tx, control_sequence.clone()); + { + let slot = file_channel.clone(); + tokio::spawn(async move { + while let Some(message) = file_rx.recv().await { + let mut channel = slot.lock().unwrap().clone(); + for _ in 0..100 { + if channel.is_some() { break; } + tokio::time::sleep(std::time::Duration::from_millis(50)).await; + channel = slot.lock().unwrap().clone(); + } + let Some(channel) = channel else { log::warn!("File transfer reply dropped: no FILE_DATA_CHANNEL"); continue; }; + if let Err(e) = channel.send(&bytes::Bytes::from(message)).await { log::warn!("FILE_DATA_CHANNEL send failed: {}", e); } + } + }); + } + + // 监听 DataChannel + pc.on_data_channel(Box::new(move |d: Arc| { + let label = d.label().to_string(); + log::info!("New DataChannel received: {}", label); + + let input_inst = input_clone.clone(); + let screen = control_capture.clone(); + let out_sequence = control_sequence.clone(); + let shared_clipboard_ready = text_clipboard_ready.clone(); + let peer_files = peer_files.clone(); + let peer_video_settings = video_settings.clone(); + let peer_actions = peer_actions.clone(); + if label == "FILE_DATA_CHANNEL" { *file_channel.lock().unwrap() = Some(d.clone()); } + + Box::pin(async move { + let lbl = label.clone(); + let inp = input_inst.clone(); + let d_reply = d.clone(); + let input_size = (screen.width, screen.height); + let reply_sequence = out_sequence.clone(); + let channel_video_settings = peer_video_settings.clone(); + let channel_actions = peer_actions.clone(); + let clipboard_input = Arc::new(std::sync::Mutex::new(None::>>)); + let clipboard_assembly = Arc::new(std::sync::Mutex::new(crate::clipboard_protocol::Assembly::default())); + let rich_state=Arc::new(std::sync::Mutex::new(crate::clipboard_rich::State::default())); + let clipboard_enabled = shared_clipboard_ready.clone(); + // Ordered outbound queue for protocol replies produced outside this callback. + let (outbound, mut outbound_rx) = tokio::sync::mpsc::unbounded_channel::>(); + { + let out_channel = d.clone(); + let out_label = label.clone(); + tokio::spawn(async move { + while let Some(message) = outbound_rx.recv().await { + if let Err(e) = out_channel.send(&bytes::Bytes::from(message)).await { + log::warn!("{} send failed: {}", out_label, e); break; + } + } + }); + } + // The viewer sends FileTransferFtp RPCs (Message 21/22) on CONTROL; accept them on TEXT/FILE too. + let file_session = if matches!(label.as_str(), "CONTROL_DATA_CHANNEL" | "TEXT_DATA_CHANNEL" | "FILE_DATA_CHANNEL") { + Some(peer_files.clone()) + } else { None }; + // CT_TERMINAL: TERM frames and terminal RPCs (check_env/rename) on BINARY. + let terminal_conn = if label == "BINARY_DATA_CHANNEL" { + Some(Arc::new(crate::terminal::TerminalConn::new(outbound.clone()))) + } else { None }; + if label == "CONTROL_DATA_CHANNEL" || label == "TEXT_DATA_CHANNEL" { + let channel = d.clone(); + let initial_sequence = out_sequence.clone(); + let clipboard_sink = clipboard_input.clone(); + let clipboard_ready = clipboard_enabled.clone(); + let rich_outgoing=rich_state.clone(); + let open_actions = channel_actions.clone(); + let open_video = channel_video_settings.clone(); + d.on_open(Box::new(move || { + let init_actions = open_actions.clone(); + let init_video = open_video.clone(); + let channel = channel.clone(); + let sequence = initial_sequence.clone(); + let screen = screen.clone(); + let clipboard_sink = clipboard_sink.clone(); + let clipboard_ready = clipboard_ready.clone(); + let rich_outgoing=rich_outgoing.clone(); + Box::pin(async move { + if channel.label() == "TEXT_DATA_CHANNEL" { + if !desktop { return; } + let bridge = if let Some(session)=screen.portal.clone() { crate::clipboard::start_portal(session) } else { crate::clipboard::start(screen.display.clone()) }; + *clipboard_sink.lock().unwrap() = Some(bridge.incoming); + let clipboard_channel = channel.clone(); + let clipboard_sequence = sequence.clone(); + let clipboard_cleanup = clipboard_sink.clone(); + let ready = bridge.ready.await.unwrap_or(false); + clipboard_ready.store(ready,std::sync::atomic::Ordering::Relaxed); + tokio::spawn(async move { + if !ready { + *clipboard_cleanup.lock().unwrap() = None; + log::warn!("Native text clipboard unavailable"); return; + } + log::info!("Native text clipboard bridge ready"); + let mut updates = bridge.outgoing; + let mut health = tokio::time::interval(std::time::Duration::from_millis(200)); + loop { + tokio::select! { + _ = health.tick() => { + if clipboard_channel.ready_state() != webrtc::data_channel::data_channel_state::RTCDataChannelState::Open { break; } + }, + changed = updates.changed() => { + if changed.is_err() { break; } + let text = updates.borrow_and_update().clone(); + let Some(text) = text else { continue; }; + { + let request_id=clipboard_sequence.fetch_add(1,std::sync::atomic::Ordering::Relaxed); + let payload = match rich_outgoing.lock().unwrap().offer(request_id,text.clone()) { + Ok(payload)=>payload,Err(reason)=>{log::warn!("Clipboard offer rejected: {}",reason);continue;} + }; + let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let message = crate::initialization::envelope(clipboard_sequence.fetch_add(1,std::sync::atomic::Ordering::Relaxed),timestamp,21,&payload); + if !matches!(tokio::time::timeout(std::time::Duration::from_secs(2),clipboard_channel.send(&bytes::Bytes::from(message))).await,Ok(Ok(_))) { + log::warn!("Native clipboard RPC send failed"); break; + } + } + log::info!("Native clipboard text format offered: bytes={}",text.len()); + } + } + } + *clipboard_cleanup.lock().unwrap() = None; + clipboard_ready.store(false,std::sync::atomic::Ordering::Relaxed); + }); + return; + } + let timestamp = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let next_seq = || sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + // Default file-transfer folder: the desktop user's home directory. + let home = std::env::var("HOME").unwrap_or_else(|_| "/".into()); + let desktop_permission=if screen.init_error.is_none() { + crate::system_metrics::Permission::Allow + } else { crate::system_metrics::Permission::Reject }; + let messages = [ + (8, crate::initialization::encode_capture_change(next_seq(), timestamp, 0, 0, "Linux desktop")), + (13, Ok(crate::initialization::envelope(next_seq(), timestamp, 13, &init_actions.metrics_payload(desktop_sound, desktop_permission)))), + (26, Ok(crate::initialization::envelope(next_seq(), timestamp, 26, + &crate::system_metrics::remote_download_path(&home)))), + (7, crate::capture_setting::screen_sources(next_seq(), timestamp, (screen.width, screen.height), init_video.borrow().output, "Linux desktop")), + ]; + for (field, message) in messages { + if screen.init_error.is_some() && matches!(field,7|8) { continue; } + let message = match message { + Ok(message) => message, + Err(e) => { log::error!("CONTROL initialization encode failed: {}", e); return; } + }; + if let Err(e) = channel.send(&bytes::Bytes::from(message)).await { + log::error!("CONTROL initialization field {} failed: {}", field, e); + return; + } + log::info!("CONTROL initialization field {} sent", field); + } + // Mirror the Linux pointer shape; the video itself carries no pointer. + if !desktop { return; } + tokio::spawn(crate::session_lock::report_states(channel.clone(), sequence.clone())); + let mut shapes = crate::cursor::monitor(&screen.display); + let mut health = tokio::time::interval(std::time::Duration::from_millis(200)); + let mut sent = 0usize; + loop { + let current = shapes.borrow_and_update().clone(); + if let Some(cursor) = current { + let timestamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let message = crate::cursor::encode_cursor_shape(next_seq(), timestamp, &cursor); + if channel.send(&bytes::Bytes::from(message)).await.is_err() { break; } + sent += 1; + if sent <= 3 || sent % 100 == 0 { + log::info!("Cursor shape sent: count={} size={}x{} hotspot={},{} png_bytes={}", sent, cursor.width, cursor.height, cursor.hot_x, cursor.hot_y, cursor.png.len()); + } + } + loop { + tokio::select! { + changed = shapes.changed() => { if changed.is_err() { return; } break; }, + _ = health.tick() => { + if channel.ready_state() != webrtc::data_channel::data_channel_state::RTCDataChannelState::Open { return; } + }, + } + } + } + }) + })); + } + + + d.on_message(Box::new(move |msg: DataChannelMessage| { + let channel_name = lbl.clone(); + let input_worker = inp.clone(); + let terminal_worker = terminal_conn.clone(); + let rpc_out = outbound.clone(); + let reply_chan = d_reply.clone(); + let out_sequence = reply_sequence.clone(); + let clipboard_sink = clipboard_input.clone(); + let clipboard_assembly = clipboard_assembly.clone(); + let clipboard_ready = clipboard_enabled.clone(); + let rich_incoming=rich_state.clone(); + let file_worker = file_session.clone(); + let video_settings = channel_video_settings.clone(); + let actions = channel_actions.clone(); + + Box::pin(async move { + if let Some(term) = &terminal_worker { + if crate::terminal::is_frame(&msg.data) { term.handle(&msg.data); return; } + } + if let Ok(fields) = crate::protocol::decode_wire(&msg.data) { + use crate::protocol::WireValue; + let rpc = fields.iter().find_map(|f| match (f.number, &f.value) { (21, WireValue::Bytes(b)) => Some(*b), _ => None }); + let rpc_fields = rpc.and_then(|r| crate::protocol::decode_wire(r).ok()); + let output_before = video_settings.borrow().output; + if let Some(response) = rpc_fields.as_deref().and_then(|r| crate::capture_setting::handle_rpc(r, &video_settings, input_size)) { + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let next = || out_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let _ = rpc_out.send(crate::initialization::envelope(next(), ts, 22, &response)); + let current = *video_settings.borrow(); + if current.output != output_before { + match crate::capture_setting::screen_sources(next(), ts, input_size, current.output, "Linux desktop") { + Ok(screens) => { let _ = rpc_out.send(screens); }, + Err(e) => log::warn!("Screen sources update failed: {}", e), + } + } + let sync = crate::capture_setting::sync_payload(¤t, input_size); + let _ = rpc_out.send(crate::initialization::envelope(next(), ts, 25, &sync)); + return; + } + if let Some(response) = rpc_fields.as_deref().and_then(|r| crate::system_actions::plugin_response(r).or_else(|| crate::system_actions::session_rpc_response(r))) { + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let _ = rpc_out.send(crate::initialization::envelope(out_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed), ts, 22, &response)); + return; + } + if let Some(response) = rpc.and_then(|r| crate::protocol::decode_wire(r).ok()).and_then(|r| crate::terminal::rpc_response(&r)) { + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let _ = rpc_out.send(crate::initialization::envelope(out_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed), ts, 22, &response)); + return; + } + } + if let Some(files) = &file_worker { + if let Ok(fields) = crate::protocol::decode_wire(&msg.data) { + if files.handle(&fields) { + static ROUTE: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if ROUTE.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 20 { + log::info!("File transfer RPC received on {}", channel_name); + } + return; + } + } + } + // Temporary bounded clipboard routing diagnostics: schema only, + // never text values, payload bytes, key values or clipboard content. + if channel_name == "TEXT_DATA_CHANNEL" || channel_name == "BINARY_DATA_CHANNEL" || channel_name == "FILE_DATA_CHANNEL" { + static CLIPBOARD_SHAPES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + static TOOL_SHAPES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + let counter = if channel_name == "TEXT_DATA_CHANNEL" { &CLIPBOARD_SHAPES } else { &TOOL_SHAPES }; + if counter.fetch_add(1,std::sync::atomic::Ordering::Relaxed) < 40 { + let shape = if let Ok(value) = serde_json::from_slice::(&msg.data) { + fn shape(v:&serde_json::Value,depth:usize)->serde_json::Value { + use serde_json::{Value,json}; + match v { + Value::Object(o) if depth<2 => Value::Object(o.iter().take(24).filter(|(k,_)|k.len()<=48&&k.bytes().all(|b|b.is_ascii_alphanumeric()||b==b'_')).map(|(k,v)|(k.clone(),shape(v,depth+1))).collect()), + Value::String(_)=>json!("string"), Value::Number(_)=>json!("number"), Value::Bool(_)=>json!("bool"), + Value::Array(_)=>json!("array"),Value::Object(_)=>json!("object"),Value::Null=>json!("null"), + } + } + shape(&value,0).to_string() + } else if let Ok(fields) = crate::protocol::decode_wire(&msg.data) { + format!("protobuf fields={:?}",fields.iter().map(|f|f.number).collect::>()) + } else { "opaque".to_string() }; + log::info!("Clipboard channel schema: channel={} bytes={} schema={}",channel_name,msg.data.len(),shape); + } + } + if channel_name == "CONTROL_DATA_CHANNEL" || channel_name == "TEXT_DATA_CHANNEL" { + if let Ok(fields) = crate::protocol::decode_wire(&msg.data) { + use crate::protocol::WireValue; + for field in &fields { + if let (22,WireValue::Bytes(payload))=(field.number,&field.value) { + let update=rich_incoming.lock().unwrap().response(payload); + match update { + Ok(Some(text))=>{if let Some(sink)=clipboard_sink.lock().unwrap().as_ref(){log::info!("Native desktop clipboard text received: bytes={}",text.len());sink.send_replace(Some(text));}}, + Err(reason)=>log::warn!("Clipboard desktop response rejected: {}",reason), + _=>{}, + } + if let Ok(response)=crate::protocol::decode_wire(payload) { + if let Some(WireValue::Bytes(status))=response.iter().find(|f|f.number==6).map(|f|&f.value) { + if let Ok(status)=crate::protocol::decode_wire(status) { + let success=status.iter().any(|f|f.number==1&&f.value==WireValue::Varint(1)); + log::info!("Native clipboard RPC text acknowledged: success={}",success); + } + } + } + } + } + for field in &fields { + if let (21, WireValue::Bytes(payload)) = (field.number,&field.value) { + let ids=crate::clipboard_rich::format_ids(payload); + if !ids.is_empty(){log::info!("Clipboard offered format IDs: {:?}",ids);} + let rich_result={ + let mut next=||out_sequence.fetch_add(1,std::sync::atomic::Ordering::Relaxed); + rich_incoming.lock().unwrap().request(payload,&mut next) + }; + match rich_result { + Ok(result)=>{ + if let Some(text)=result.text {if let Some(sink)=clipboard_sink.lock().unwrap().as_ref(){log::info!("Native desktop clipboard text received: bytes={}",text.len());sink.send_replace(Some(text));}} + let count=result.messages.len(); + for (kind,payload) in result.messages { + let timestamp=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let message=crate::initialization::envelope(out_sequence.fetch_add(1,std::sync::atomic::Ordering::Relaxed),timestamp,kind,&payload); + if !matches!(tokio::time::timeout(std::time::Duration::from_secs(2),reply_chan.send(&bytes::Bytes::from(message))).await,Ok(Ok(_))){log::warn!("Clipboard desktop reply failed");break;} + } + if count>0{log::info!("Clipboard desktop protocol replies: count={}",count);} + } + Err(reason)=>log::warn!("Clipboard desktop request rejected: {}",reason), + } + let received=crate::clipboard_protocol::read_text_request(payload); + match received { + Ok(Some((header,text))) => { + let sink=clipboard_sink.lock().unwrap().clone(); + if let Some(sink)=sink { + log::info!("Native clipboard RPC text received: bytes={}",text.len()); + sink.send_replace(Some(text)); + let payload=crate::clipboard_protocol::text_response(&header); + let timestamp=std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let message=crate::initialization::envelope(out_sequence.fetch_add(1,std::sync::atomic::Ordering::Relaxed),timestamp,22,&payload); + let _=reply_chan.send(&bytes::Bytes::from(message)).await; + } + } + Ok(None)=> {if let Ok(nested)=crate::protocol::decode_wire(payload){log::info!("Clipboard RPC request schema: fields={:?}",nested.iter().map(|f|f.number).collect::>());}}, + Err(reason)=>log::warn!("Clipboard RPC rejected: {}",reason), + } + } + } + for field in &fields { + if let (17, WireValue::Bytes(payload)) = (field.number, &field.value) { + match clipboard_assembly.lock().unwrap().accept(payload) { + Ok(Some(text)) => { + if let Some(sink) = clipboard_sink.lock().unwrap().as_ref() { + log::info!("Native clipboard text received: bytes={}",text.len()); + sink.send_replace(Some(text)); + } + } + Ok(None) => {}, + Err(reason) => log::warn!("Native clipboard message rejected: {}",reason), + } + } + } + if fields.iter().any(|f|f.number==20) { + static INPUT_SHAPE:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); + if INPUT_SHAPE.fetch_add(1,std::sync::atomic::Ordering::Relaxed)<12 { + let shape:Vec<(u32,&str,usize)>=fields.iter().map(|f|match &f.value { + WireValue::Bytes(b)=>(f.number,"bytes",b.len()), + _=>(f.number,"number",0) + }).collect(); + log::info!("CONTROL protobuf input field shape: {:?}",shape); + } + } + + let seq = fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 1) => Some(*v), _ => None }); + let _timestamp = fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 2) => Some(*v), _ => None }); + let simple = fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Bytes(v), 3) => Some(*v), _ => None }); + // Diagnostics: which non-input CONTROL messages the viewer sends (numbers only, no contents). + if !fields.iter().any(|f| f.number == 20) { + static SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if SEEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed) < 300 { + let numbers: Vec = fields.iter().map(|f| f.number).collect(); + let action = simple.and_then(|b| crate::protocol::decode_wire(b).ok()).and_then(|a| a.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 1) => Some(*v), _ => None })); + log::info!("CONTROL message: fields={:?} simple_action={:?}", numbers, action); + } + } + // QuerySystemState { 1: SS_ID_SECURE_DESKTOP_STATE = 1 } asks for the lock state now. + let query = fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Bytes(v), 16) => Some(*v), _ => None }); + if let Some(query) = query { + let id = crate::protocol::decode_wire(query).ok().and_then(|q| q.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 1) => Some(*v), _ => None })); + if id == Some(1) { + let locked = *crate::session_lock::watch_locked().borrow(); + crate::session_lock::send_state(&reply_chan, &out_sequence, locked.unwrap_or(false)).await; + } + } + if let Some(simple) = simple { + let seq = seq.unwrap_or(0); + if let Ok(action_fields) = crate::protocol::decode_wire(simple) { + let action = action_fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 1) => Some(*v), _ => None }).unwrap_or(0); + if action == 15 { + // AUTO_UNLOCK_SYSTEM: args JSON {"key": saved password}; never logged. + let args = action_fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Bytes(v), 2) => Some(*v), _ => None }).unwrap_or(&[]); + let password = crate::session_lock::password_from_args(args); + let (chan, seq_out) = (reply_chan.clone(), out_sequence.clone()); + tokio::spawn(crate::session_lock::handle_auto_unlock(password, chan, seq_out)); + } + use crate::system_actions as sa; + if matches!(action, sa::SHOW_DESKTOP | sa::REBOOT_SYSTEM | sa::LOCK_SYSTEM | sa::SHUTDOWN_SYSTEM | sa::SHOW_TASKMGR + | sa::MUTE_SYSTEM | sa::MUTE_RESTORE | sa::MUTE_PERMANENT | sa::MUTE_TEMPORARY | sa::SET_AUTO_LOCK) { + let value = action_fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Varint(v), 5) => Some(*v), _ => None }); + let args = action_fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Bytes(v), 2) => Some(v.to_vec()), _ => None }).unwrap_or_default(); + log::info!("SimpleAction {} ({}) received: value={:?} args={}", action, + crate::control_protocol::simple_action_name(action).unwrap_or("?"), value, sa::args_shape(&args)); + let (actions, input, chan, seq_out) = (actions.clone(), input_worker.clone(), reply_chan.clone(), out_sequence.clone()); + tokio::spawn(async move { + let worker = actions.clone(); + let report = tokio::task::spawn_blocking(move || worker.handle(action, value, &args, || { + // GNOME/KDE "show desktop" shortcut (Super+D) through the desktop's own input path. + input.windows_key_event(0x5B, true); input.windows_key_event(0x44, true); + input.windows_key_event(0x44, false); input.windows_key_event(0x5B, false); + })).await.unwrap_or(false); + if report { + let ts = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); + let message = crate::initialization::envelope(seq_out.fetch_add(1, std::sync::atomic::Ordering::Relaxed), ts, 13, &actions.metrics_payload(desktop_sound, crate::system_metrics::Permission::Allow)); + if let Err(e) = chan.send(&bytes::Bytes::from(message)).await { log::warn!("Settings report failed: {}", e); } + } + }); + } else if action > 1 && action != 15 { + let args = action_fields.iter().find_map(|f| match (&f.value, f.number) { (WireValue::Bytes(v), 2) => Some(*v), _ => None }).unwrap_or(&[]); + log::info!("SimpleAction {} ({}) not handled: args={}", action, crate::control_protocol::simple_action_name(action).unwrap_or("?"), sa::args_shape(args)); + } + if action == 0 { + let response = crate::control_protocol::encode_echo_response_with_clipboard( + out_sequence.fetch_add(1, std::sync::atomic::Ordering::Relaxed), + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(), seq, + clipboard_ready.load(std::sync::atomic::Ordering::Relaxed)); + if let Err(e) = reply_chan.send(&bytes::Bytes::from(response)).await { + log::error!("CONTROL echo response failed: {}", e); + } else { + static RESPONSES: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + if RESPONSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed) == 0 { + log::info!("CONTROL protobuf echo request answered"); + } + } + } + } + } + } + } + if let Ok(txt) = std::str::from_utf8(&msg.data) { + log::debug!("DataChannel [{}] received UTF-8 data: {} bytes", channel_name, txt.len()); + if let Ok(val) = serde_json::from_str::(txt) { + if channel_name.contains("CONTROL") { + match crate::control_protocol::decode_control(&msg.data) { + Ok(crate::control_protocol::ControlMessage::Input(event)) => { + use crate::control_protocol::ControlInput; + match &event { + ControlInput::MouseAbsolute {x,y} => input_worker.mouse_absolute_normalized(*x,*y,input_size), + ControlInput::MouseRelative {dx,dy} => input_worker.mouse_relative(*dx,*dy), + ControlInput::MouseScroll {dx,dy} => input_worker.mouse_scroll(*dx,*dy), + ControlInput::Keyboard {key, pressed} => input_worker.windows_key_event(*key, *pressed), + ControlInput::KeyboardClick {key} => {input_worker.windows_key_event(*key, true);input_worker.windows_key_event(*key, false);}, + ControlInput::MouseButton {button,pressed} => input_worker.wire_mouse_button(*button,*pressed), + ControlInput::MouseClick {button} => {input_worker.wire_mouse_button(*button,true);input_worker.wire_mouse_button(*button,false);}, + _ => {} + } + + }, + _ => {} + } + } else if channel_name.contains("STREAMER") { + log::debug!("STREAMER channel JSON received"); + if let Some(event)=val.get("connection_period_stats_event") { + let nums=crate::viewer_metrics::collect(event); + if nums.is_empty(){ + static SHAPE:std::sync::atomic::AtomicUsize=std::sync::atomic::AtomicUsize::new(0); + if SHAPE.fetch_add(1,std::sync::atomic::Ordering::Relaxed)<3 { + log::info!("Viewer telemetry schema: {:?}",crate::viewer_metrics::safe_shape(event)); + } + } + log::info!("Viewer delay/frame numeric metrics: {:?}",nums); + } + + // 检查是否有 ping 或握手请求并回应 + if val.get("type").and_then(|t| t.as_str()) == Some("ping") { + let _ = reply_chan.send(&bytes::Bytes::from_static(b"{\"type\":\"pong\"}")).await; + } + } else if channel_name.contains("TEXT") { + log::debug!("TEXT channel JSON received"); + } + } + } else { + log::debug!("DataChannel [{}] received binary data: len={}", channel_name, msg.data.len()); + + + } + + }) + })); + + }) + })); + + Ok(Self { + pc, + capture, + input, + desktop, + context, + }) + } + + /// 应用远端 Offer,生成并返回 Answer + pub async fn handle_offer(&self, soac: &SoacMessage) -> Result { + // 同步当前的客户端与房间会话上下文 + { + let mut ctx = self.context.lock().await; + ctx.client_id = soac.client_id.clone(); + ctx.ice_id = soac.ice_id.clone(); + ctx.app_control_id = soac.app_control_id.clone(); + log::info!("Updated WebRTC session context: client_id={:?}, ice_id={:?}", ctx.client_id, ctx.ice_id); + } + let mut sdp_str = soac.sdp.clone().unwrap_or_default(); + if sdp_str.is_empty() { + if let Some(gzip_sdp) = &soac.gzip_sdp { + if let Ok(compressed) = base64::engine::general_purpose::STANDARD.decode(gzip_sdp) { + let mut decoder = GzDecoder::new(&compressed[..]); + let mut decompressed = String::new(); + if decoder.read_to_string(&mut decompressed).is_ok() { + sdp_str = decompressed; + } + } + } + } + + if sdp_str.is_empty() { + return Err("Offer SDP is empty".into()); + } + + let quic_value = sdp_str.lines().find_map(|line| line.strip_prefix("a=x-uuremote-quic")); + let quic_summary = match quic_value.map(str::trim) { + None => "absent", Some("") => "present", Some(":0") => "0", Some(":1") => "1", + Some(":false") => "false", Some(":true") => "true", _ => "present non-boolean value (not logged)", + }; + log::info!("Offer x-uuremote-quic: {}", quic_summary); + log::info!("Offer includes UU capture-index extension: {}", sdp_str.lines().any(|l| l.starts_with("a=extmap:") && l.contains(crate::rtp_metadata::CAPTURE_INDEX_URI))); + let offer = RTCSessionDescription::offer(sdp_str) + .map_err(|e| format!("Invalid offer: {}", e))?; + + self.pc + .set_remote_description(offer) + .await + .map_err(|e| format!("Set remote desc failed: {}", e))?; + + let answer = self + .pc + .create_answer(None) + .await + .map_err(|e| format!("Create answer failed: {}", e))?; + + log::info!("Answer includes x-uuremote-quic: {}", answer.sdp.lines().any(|l| l == "a=x-uuremote-quic")); + log::info!("Answer media sections: {:?}", answer.sdp.lines().filter(|l| l.starts_with("m=")).collect::>()); + let bundle_media = negotiated_bundle_media(&answer.sdp) + .ok_or("Answer has no active BUNDLE transport")?; + self.context.lock().await.bundle_media = Some(bundle_media); + self.pc + .set_local_description(answer.clone()) + .await + .map_err(|e| format!("Set local desc failed: {}", e))?; + Ok(answer.sdp) + } + + /// 接收远端 ICE Candidate + pub async fn add_candidate(&self, soac: &SoacMessage) -> Result<(), String> { + if let Some(cand_val) = &soac.candidate { + let (cand_str, sdp_mid, sdp_mline) = if let Some(s) = cand_val.as_str() { + (s.to_string(), soac.sdp_mid.clone().or_else(|| Some("0".to_string())), soac.sdp_mline_index.map(|i| i as u16).or(Some(0))) + } else { + let cs = cand_val.get("candidate").and_then(|v| v.as_str()).unwrap_or("").to_string(); + let mid = cand_val.get("sdpMid").and_then(|v| v.as_str()).map(|s| s.to_string()) + .or_else(|| soac.sdp_mid.clone()) + .or_else(|| Some("0".to_string())); + let mline = cand_val.get("sdpMLineIndex").and_then(|v| v.as_u64()).map(|i| i as u16) + .or_else(|| soac.sdp_mline_index.map(|i| i as u16)) + .or(Some(0)); + (cs, mid, mline) + }; + + if !cand_str.is_empty() { + let init = RTCIceCandidateInit { + candidate: cand_str.clone(), + sdp_mid, + sdp_mline_index: sdp_mline, + ..Default::default() + }; + + let summary=crate::network_diagnostics::candidate_summary(&cand_str); + log::info!("Injecting Remote ICE Candidate: protocol={} type={}",summary.protocol,summary.kind); + + self.pc + .add_ice_candidate(init) + .await + .map_err(|e| format!("Add candidate error: {}", e))?; + } + } + Ok(()) + } +} + + +fn negotiated_bundle_media(sdp: &str) -> Option<(String, u16)> { + let preferred: Vec<&str> = sdp.lines().find_map(|l| l.strip_prefix("a=group:BUNDLE "))? + .split_whitespace().collect(); + let mut sections: Vec<(bool, Option)> = Vec::new(); + for line in sdp.lines() { + if let Some(media) = line.strip_prefix("m=") { + let port = media.split_whitespace().nth(1)?; + sections.push((port != "0", None)); + } else if let Some(mid) = line.strip_prefix("a=mid:") { + if let Some(section) = sections.last_mut() { section.1 = Some(mid.to_string()); } + } + } + for mid in preferred { + for (index, (active, section_mid)) in sections.iter().enumerate() { + if *active && section_mid.as_deref() == Some(mid) { + return Some((mid.to_string(), index.try_into().ok()?)); + } + } + } + None +} + +#[cfg(test)] +mod tests { + use super::negotiated_bundle_media; + #[test] + fn skips_rejected_audio_for_ice_transport() { + let sdp = "a=group:BUNDLE 1 2\r\nm=audio 0 RTP 0\r\na=mid:0\r\nm=video 9 RTP 98\r\na=mid:1\r\nm=application 9 SCTP 0\r\na=mid:2\r\n"; + assert_eq!(negotiated_bundle_media(sdp), Some(("1".into(), 1))); + } + #[test] + fn follows_bundle_order_not_first_media() { + let sdp = "a=group:BUNDLE data video\nm=video 9 RTP 98\na=mid:video\nm=application 9 SCTP 0\na=mid:data\n"; + assert_eq!(negotiated_bundle_media(sdp), Some(("data".into(), 1))); + } +} + +/// Virtual/overlay interfaces never carry the UU video path (ZeroTier, containers). +fn ice_interface_allowed(name: &str) -> bool { + !["zt", "docker", "br-", "veth", "virbr", "lo"].iter().any(|prefix| name.starts_with(prefix)) +} + +/// Viewer feedback seen on the video sender: retransmission and keyframe requests. +#[derive(Default)] +pub(crate) struct FeedbackCounts { pub nack_packets: u64, pub pli: u64, pub fir: u64 } +impl FeedbackCounts { + pub(crate) fn observe(&mut self, packet: &dyn std::any::Any) { + use webrtc::rtcp::{payload_feedbacks::{full_intra_request::FullIntraRequest, picture_loss_indication::PictureLossIndication}, transport_feedbacks::transport_layer_nack::TransportLayerNack}; + if let Some(nack) = packet.downcast_ref::() { + self.nack_packets += nack.nacks.iter().map(|pair| 1 + u64::from(pair.lost_packets.count_ones())).sum::(); + } else if packet.is::() { self.pli += 1; } + else if packet.is::() { self.fir += 1; } + } +} + +#[cfg(test)] +mod network_tests { + use super::*; + #[test] + fn ice_skips_overlay_and_container_interfaces_only() { + for name in ["ztfp6jdvog", "docker0", "br-1a2b", "veth12", "virbr0", "lo"] { assert!(!ice_interface_allowed(name), "{name}"); } + for name in ["eno1", "enp5s0", "wlp3s0", "eth0"] { assert!(ice_interface_allowed(name), "{name}"); } + } + #[test] + fn feedback_counts_nacked_packets_and_keyframe_requests() { + use webrtc::rtcp::{payload_feedbacks::picture_loss_indication::PictureLossIndication, transport_feedbacks::transport_layer_nack::{NackPair, TransportLayerNack}}; + let mut counts = FeedbackCounts::default(); + counts.observe(&TransportLayerNack { nacks: vec![NackPair { packet_id: 10, lost_packets: 0b101 }], ..Default::default() }); + counts.observe(&PictureLossIndication::default()); + assert_eq!((counts.nack_packets, counts.pli, counts.fir), (3, 1, 0)); + } +} diff --git a/vendor/webrtc-dtls/.cargo-ok b/vendor/webrtc-dtls/.cargo-ok new file mode 100644 index 0000000..5f8b795 --- /dev/null +++ b/vendor/webrtc-dtls/.cargo-ok @@ -0,0 +1 @@ +{"v":1} \ No newline at end of file diff --git a/vendor/webrtc-dtls/.cargo_vcs_info.json b/vendor/webrtc-dtls/.cargo_vcs_info.json new file mode 100644 index 0000000..a35632f --- /dev/null +++ b/vendor/webrtc-dtls/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "5b05bb0cce3861011db10be5f286e03f7a40d94d" + }, + "path_in_vcs": "dtls" +} \ No newline at end of file diff --git a/vendor/webrtc-dtls/.gitignore b/vendor/webrtc-dtls/.gitignore new file mode 100644 index 0000000..9db22ce --- /dev/null +++ b/vendor/webrtc-dtls/.gitignore @@ -0,0 +1,12 @@ +# Generated by Cargo +# will have compiled files and executables +/target/ +/examples/hub/target +/.idea/ + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/vendor/webrtc-dtls/CHANGELOG.md b/vendor/webrtc-dtls/CHANGELOG.md new file mode 100644 index 0000000..0718977 --- /dev/null +++ b/vendor/webrtc-dtls/CHANGELOG.md @@ -0,0 +1,26 @@ +# webrtc-dtls changelog + +## Unreleased + +## v0.7.1 + +* Added support for insecure/deprecated signature verification algorithms [#342](https://github.com/webrtc-rs/webrtc/pull/342) by [@chuigda](https://github.com/chuigda). + +## v0.7.0 + +* Increased minimum support rust version to `1.60.0`. +* Add `RTCCertificate::from_pem` and `RTCCertificate::serialize_pem` (only work with `pem` feature enabled) [#333](https://github.com/webrtc-rs/webrtc/pull/333) + +### Breaking + +* Increased required `webrtc-util` version to `0.7.0`, with this change some methods in `DTLSConn` that implement `webrtc_util::Conn` have changed from async to sync. + +## v0.6.0 + +* [#254 [DTLS] Add NamedCurve::P384](https://github.com/webrtc-rs/webrtc/pull/254) contributed by [neonphog](https://github.com/neonphog) +* Increased min version of `log` dependency to `0.4.16`. [#250 Fix log at ^0.4.16 to make tests compile](https://github.com/webrtc-rs/webrtc/pull/250) by [@k0nserv](https://github.com/k0nserv). +* Increased serde's minimum version to 1.0.110 [#243 Fixes for cargo minimal-versions](https://github.com/webrtc-rs/webrtc/pull/243) contributed by [algesten](https://github.com/algesten) + +## Prior to 0.6.0 + +Before 0.6.0 there was no changelog, previous changes are sometimes, but not always, available in the [GitHub Releases](https://github.com/webrtc-rs/dtls/releases). diff --git a/vendor/webrtc-dtls/Cargo.toml b/vendor/webrtc-dtls/Cargo.toml new file mode 100644 index 0000000..554be90 --- /dev/null +++ b/vendor/webrtc-dtls/Cargo.toml @@ -0,0 +1,172 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2021" +name = "webrtc-dtls" +version = "0.9.0" +authors = ["Rain Liu "] +description = "A pure Rust implementation of DTLS" +homepage = "https://webrtc.rs" +documentation = "https://docs.rs/webrtc-dtls" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/webrtc-rs/dtls" + +[[example]] +name = "dial_psk" +path = "examples/dial/psk/dial_psk.rs" +bench = false + +[[example]] +name = "dial_selfsign" +path = "examples/dial/selfsign/dial_selfsign.rs" +bench = false + +[[example]] +name = "dial_verify" +path = "examples/dial/verify/dial_verify.rs" +bench = false + +[[example]] +name = "listen_psk" +path = "examples/listen/psk/listen_psk.rs" +bench = false + +[[example]] +name = "listen_selfsign" +path = "examples/listen/selfsign/listen_selfsign.rs" +bench = false + +[[example]] +name = "listen_verify" +path = "examples/listen/verify/listen_verify.rs" +bench = false + +[dependencies.aes] +version = "0.8" + +[dependencies.aes-gcm] +version = "0.10" + +[dependencies.async-trait] +version = "0.1" + +[dependencies.bincode] +version = "1" + +[dependencies.byteorder] +version = "1" + +[dependencies.cbc] +version = "0.1" +features = [ + "block-padding", + "alloc", +] + +[dependencies.ccm] +version = "0.5" + +[dependencies.der-parser] +version = "8.1" + +[dependencies.hkdf] +version = "0.12" + +[dependencies.hmac] +version = "0.12" + +[dependencies.log] +version = "0.4" + +[dependencies.p256] +version = "0.13" +features = [ + "default", + "ecdh", + "ecdsa", +] + +[dependencies.p384] +version = "0.13" + +[dependencies.pem] +version = "3" +optional = true + +[dependencies.rand] +version = "0.8" + +[dependencies.rand_core] +version = "0.6" + +[dependencies.rcgen] +version = "0.11" + +[dependencies.ring] +version = "0.17" + +[dependencies.rustls] +version = "0.21" +features = ["dangerous_configuration"] + +[dependencies.sec1] +version = "0.7" +features = ["std"] + +[dependencies.serde] +version = "1" +features = ["derive"] + +[dependencies.sha1] +version = "0.10" + +[dependencies.sha2] +version = "0.10" + +[dependencies.subtle] +version = "2" + +[dependencies.thiserror] +version = "1" + +[dependencies.tokio] +version = "1.32.0" +features = ["full"] + +[dependencies.util] +version = "0.8.1" +features = ["conn"] +default-features = false +package = "webrtc-util" + +[dependencies.x25519-dalek] +version = "2" +features = ["static_secrets"] + +[dependencies.x509-parser] +version = "0.15" + +[dev-dependencies.chrono] +version = "0.4.28" + +[dev-dependencies.clap] +version = "3" + +[dev-dependencies.env_logger] +version = "0.10" + +[dev-dependencies.tokio-test] +version = "0.4" + +[features] +pem = ["dep:pem"] diff --git a/vendor/webrtc-dtls/Cargo.toml.orig b/vendor/webrtc-dtls/Cargo.toml.orig new file mode 100644 index 0000000..38c5d7c --- /dev/null +++ b/vendor/webrtc-dtls/Cargo.toml.orig @@ -0,0 +1,82 @@ +[package] +name = "webrtc-dtls" +version = "0.9.0" +authors = ["Rain Liu "] +edition = "2021" +description = "A pure Rust implementation of DTLS" +license = "MIT OR Apache-2.0" +documentation = "https://docs.rs/webrtc-dtls" +homepage = "https://webrtc.rs" +repository = "https://github.com/webrtc-rs/dtls" + +[dependencies] +util = { version = "0.8.1", path = "../util", package = "webrtc-util", default-features = false, features = ["conn"] } + +byteorder = "1" +rand_core = "0.6" +hkdf = "0.12" +p256 = { version = "0.13", features = ["default", "ecdh", "ecdsa"] } +p384 = "0.13" +rand = "0.8" +hmac = "0.12" +sec1 = { version = "0.7", features = [ "std" ] } +sha1 = "0.10" +sha2 = "0.10" +aes = "0.8" +cbc = { version = "0.1", features = [ "block-padding", "alloc"] } +aes-gcm = "0.10" +ccm = "0.5" +tokio = { version = "1.32.0", features = ["full"] } +async-trait = "0.1" +x25519-dalek = { version = "2", features = ["static_secrets"] } +x509-parser = "0.15" +der-parser = "8.1" +rcgen = "0.11" +ring = "0.17" +rustls = { version = "0.21", features = ["dangerous_configuration"]} +bincode = "1" +serde = { version = "1", features = ["derive"] } +subtle = "2" +log = "0.4" +thiserror = "1" +pem = { version = "3", optional = true } + +[dev-dependencies] +tokio-test = "0.4" +env_logger = "0.10" +chrono = "0.4.28" +clap = "3" +hub = {path = "examples/hub"} + +[features] +pem = ["dep:pem"] + +[[example]] +name = "dial_psk" +path = "examples/dial/psk/dial_psk.rs" +bench = false + +[[example]] +name = "dial_selfsign" +path = "examples/dial/selfsign/dial_selfsign.rs" +bench = false + +[[example]] +name = "dial_verify" +path = "examples/dial/verify/dial_verify.rs" +bench = false + +[[example]] +name = "listen_psk" +path = "examples/listen/psk/listen_psk.rs" +bench = false + +[[example]] +name = "listen_selfsign" +path = "examples/listen/selfsign/listen_selfsign.rs" +bench = false + +[[example]] +name = "listen_verify" +path = "examples/listen/verify/listen_verify.rs" +bench = false diff --git a/vendor/webrtc-dtls/LICENSE-APACHE b/vendor/webrtc-dtls/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/vendor/webrtc-dtls/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/vendor/webrtc-dtls/LICENSE-MIT b/vendor/webrtc-dtls/LICENSE-MIT new file mode 100644 index 0000000..e11d93b --- /dev/null +++ b/vendor/webrtc-dtls/LICENSE-MIT @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 WebRTC.rs + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/webrtc-dtls/README.md b/vendor/webrtc-dtls/README.md new file mode 100644 index 0000000..1ef5cb9 --- /dev/null +++ b/vendor/webrtc-dtls/README.md @@ -0,0 +1,30 @@ +

+ WebRTC.rs +
+

+

+ + + + + + + + + + + + + + + + + License: MIT/Apache 2.0 + + + Discord + +

+

+ A pure Rust implementation of DTLS. Rewrite Pion DTLS in Rust +

diff --git a/vendor/webrtc-dtls/codecov.yml b/vendor/webrtc-dtls/codecov.yml new file mode 100644 index 0000000..a405022 --- /dev/null +++ b/vendor/webrtc-dtls/codecov.yml @@ -0,0 +1,23 @@ +codecov: + require_ci_to_pass: yes + max_report_age: off + token: 14bc9fb7-bdcf-4355-8e0e-ebec14066ae5 + +coverage: + precision: 2 + round: down + range: 50..90 + status: + project: + default: + enabled: no + threshold: 0.2 + if_not_found: success + patch: + default: + enabled: no + if_not_found: success + changes: + default: + enabled: no + if_not_found: success diff --git a/vendor/webrtc-dtls/doc/webrtc.rs.png b/vendor/webrtc-dtls/doc/webrtc.rs.png new file mode 100644 index 0000000000000000000000000000000000000000..7bf0dda2a869e19f110bc581a3d20f9609982824 GIT binary patch literal 33276 zcmb4qgL7ri^Y*>Tjm?d1I~&`!ZQHhO+t}FV#!hyV?8dg8{pItmdjEj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>AOBpy*d+>os+i3AhnWAUe zcevplB;(J{xjyRHTPSEZcx1S-W4XXK5XKi1m_jP<^AEVpj*4oVbvvq;CB;jWphotv z@w&g6r{4Ye0?OBiM}@B?A5pgEyN6btb+7e5?np`iJ#|goV!vDt`v4YLhh41h_P&JbBjLN5z7BLu27bp-a`D;V833f zT;%*3>-~Rut4bUA=tBaKwP+v%iYW{xp*s@>EG=+*|NeP@Xw-3qNK-b2Br{)>P!FFG z48_?=JS2pmvz{xOji69)(aehgw;b_nrvc0V=11)4GmNO}92rE1nh#ud3z3mf6fYMw G`0_t~Oa}h| literal 0 HcmV?d00001 diff --git a/vendor/webrtc-dtls/examples/certificates/README.md b/vendor/webrtc-dtls/examples/certificates/README.md new file mode 100644 index 0000000..cd498e0 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/README.md @@ -0,0 +1,60 @@ +# Certificates + +The certificates in for the examples are generated using the commands shown below. + +Note that this was run on OpenSSL 1.1.1d, of which the arguments can be found in the [OpenSSL Manpages](https://www.openssl.org/docs/man1.1.1/man1), and is not guaranteed to work on different OpenSSL versions. + +```shell +# Extensions required for certificate validation. +$ EXTFILE='extfile.conf' +$ echo 'subjectAltName = DNS:webrtc.rs' > "${EXTFILE}" + +# Server. +$ SERVER_NAME='server' +$ openssl ecparam -name prime256v1 -genkey -noout -out "${SERVER_NAME}.pem" +$ openssl req -key "${SERVER_NAME}.pem" -new -sha256 -subj '/C=NL' -out "${SERVER_NAME}.csr" +$ openssl x509 -req -in "${SERVER_NAME}.csr" -extfile "${EXTFILE}" -days 365 -signkey "${SERVER_NAME}.pem" -sha256 -out "${SERVER_NAME}.pub.pem" + +# Client. +$ CLIENT_NAME='client' +$ openssl ecparam -name prime256v1 -genkey -noout -out "${CLIENT_NAME}.pem" +$ openssl req -key "${CLIENT_NAME}.pem" -new -sha256 -subj '/C=NL' -out "${CLIENT_NAME}.csr" +$ openssl x509 -req -in "${CLIENT_NAME}.csr" -extfile "${EXTFILE}" -days 365 -CA "${SERVER_NAME}.pub.pem" -CAkey "${SERVER_NAME}.pem" -set_serial '0xabcd' -sha256 -out "${CLIENT_NAME}.pub.pem" + +# Cleanup. +$ rm "${EXTFILE}" "${SERVER_NAME}.csr" "${CLIENT_NAME}.csr" +``` + +## Converting EC private key to PKCS#8 in Rust + +`Cargo.toml`: + +```toml +[dependencies] +topk8 = "0.0.1" +``` + +`main.rs`: + +```rust +fn main() { + let ec_pem = " +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIAL4r6d9lPq3XEDSZTL9l0D6thrPM7RiAhl3Fjuw9Ji2oAoGCCqGSM49 +AwEHoUQDQgAE4U64dviQRMujGK0g80dwzgjV7fnwLkj6RfvINMHvD6eiCsphWIlq +cddTAoOjXVQDu3qMAS1Ghfyk1F377EW1Sw== +-----END EC PRIVATE KEY----- +"; + + let pkcs8_pem = topk8::from_sec1_pem(ec_pem).unwrap(); + + println!("{}", pkcs8_pem); + + // -----BEGIN PRIVATE KEY----- + // MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgAvivp32U+rdcQNJl + // Mv2XQPq2Gs8ztGICGXcWO7D0mLagCgYIKoZIzj0DAQehRANCAAThTrh2+JBEy6MY + // rSDzR3DOCNXt+fAuSPpF+8g0we8Pp6IKymFYiWpx11MCg6NdVAO7eowBLUaF/KTU + // XfvsRbVL + // -----END PRIVATE KEY----- +} +``` diff --git a/vendor/webrtc-dtls/examples/certificates/client.csr b/vendor/webrtc-dtls/examples/certificates/client.csr new file mode 100644 index 0000000..3a41d57 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/client.csr @@ -0,0 +1,7 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHHMG8CAQAwDTELMAkGA1UEBhMCTkwwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC +AAQhwOK0F+5DQy5FG0dRdN0GF20p3MsTaBk73IpNzrlK+WtgxdVxmRm55LWCTgkA +RhnOcmzXW+raCEWQgTadaLd5oAAwCgYIKoZIzj0EAwIDSAAwRQIhANDZpyL2lr50 +Xr5DrD19SOa7LXpXz3DcM8RDLcBQvx05AiB7mbtcY6I18diHU0jSxHAGcUn5nAeD +EP4tqFOz7QRzgQ== +-----END CERTIFICATE REQUEST----- diff --git a/vendor/webrtc-dtls/examples/certificates/client.pem b/vendor/webrtc-dtls/examples/certificates/client.pem new file mode 100644 index 0000000..aa73a43 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/client.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEIO7fb5dmM2P0F71o/Clo0ElO29ud+JbtA3fhDIL15AgioAoGCCqGSM49 +AwEHoUQDQgAEIcDitBfuQ0MuRRtHUXTdBhdtKdzLE2gZO9yKTc65SvlrYMXVcZkZ +ueS1gk4JAEYZznJs11vq2ghFkIE2nWi3eQ== +-----END EC PRIVATE KEY----- diff --git a/vendor/webrtc-dtls/examples/certificates/client.pem.private_key.pem b/vendor/webrtc-dtls/examples/certificates/client.pem.private_key.pem new file mode 100644 index 0000000..fbcbd47 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/client.pem.private_key.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg7t9vl2YzY/QXvWj8 +KWjQSU7b2534lu0Dd+EMgvXkCCKhRANCAAQhwOK0F+5DQy5FG0dRdN0GF20p3MsT +aBk73IpNzrlK+WtgxdVxmRm55LWCTgkARhnOcmzXW+raCEWQgTadaLd5 +-----END PRIVATE KEY----- diff --git a/vendor/webrtc-dtls/examples/certificates/client.pub.pem b/vendor/webrtc-dtls/examples/certificates/client.pub.pem new file mode 100644 index 0000000..688c9f0 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/client.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN CERTIFICATE----- +MIIBITCByaADAgECAgMAq80wCgYIKoZIzj0EAwIwDTELMAkGA1UEBhMCTkwwHhcN +MjEwOTE4MjAzNzE1WhcNMjIwOTE4MjAzNzE1WjANMQswCQYDVQQGEwJOTDBZMBMG +ByqGSM49AgEGCCqGSM49AwEHA0IABCHA4rQX7kNDLkUbR1F03QYXbSncyxNoGTvc +ik3OuUr5a2DF1XGZGbnktYJOCQBGGc5ybNdb6toIRZCBNp1ot3mjGDAWMBQGA1Ud +EQQNMAuCCXdlYnJ0Yy5yczAKBggqhkjOPQQDAgNHADBEAiA8mpJVfaCw+RwALmxN +XD28Ze3DUPomlfXhx+NGuePt5QIgAcRxvuDctyL07f8pQ5n22NOioNHdjwOjxww+ +ZekD+Lg= +-----END CERTIFICATE----- diff --git a/vendor/webrtc-dtls/examples/certificates/extfile.conf b/vendor/webrtc-dtls/examples/certificates/extfile.conf new file mode 100644 index 0000000..c4b7cce --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/extfile.conf @@ -0,0 +1 @@ +subjectAltName = DNS:webrtc.rs diff --git a/vendor/webrtc-dtls/examples/certificates/server.csr b/vendor/webrtc-dtls/examples/certificates/server.csr new file mode 100644 index 0000000..cf9a983 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/server.csr @@ -0,0 +1,7 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIHHMG8CAQAwDTELMAkGA1UEBhMCTkwwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC +AASRyJbgbcieCbC1/HbiqmADkPxfk5Bmwjei2YXhPE+oYS3F5+df4BKNBgs7py7H +sxc768+6X8HmvYlfvk2kHXAVoAAwCgYIKoZIzj0EAwIDSAAwRQIhAKR9rI22Xk/U +L3xp2dzn7q3nyWqgDvp5uTflP4t0MBpJAiAJDKmcOCXNMhhgg4T2lhdfz/pZVfu5 +lxLcZm2ELiYImQ== +-----END CERTIFICATE REQUEST----- diff --git a/vendor/webrtc-dtls/examples/certificates/server.pem b/vendor/webrtc-dtls/examples/certificates/server.pem new file mode 100644 index 0000000..c6dd913 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/server.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEID358pSfZXZqwqURqBLvLYcqhOdZVVNR2toCMER39YHboAoGCCqGSM49 +AwEHoUQDQgAEkciW4G3Ingmwtfx24qpgA5D8X5OQZsI3otmF4TxPqGEtxefnX+AS +jQYLO6cux7MXO+vPul/B5r2JX75NpB1wFQ== +-----END EC PRIVATE KEY----- diff --git a/vendor/webrtc-dtls/examples/certificates/server.pem.private_key.pem b/vendor/webrtc-dtls/examples/certificates/server.pem.private_key.pem new file mode 100644 index 0000000..b5088e5 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/server.pem.private_key.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgPfnylJ9ldmrCpRGo +Eu8thyqE51lVU1Ha2gIwRHf1gduhRANCAASRyJbgbcieCbC1/HbiqmADkPxfk5Bm +wjei2YXhPE+oYS3F5+df4BKNBgs7py7Hsxc768+6X8HmvYlfvk2kHXAV +-----END PRIVATE KEY----- diff --git a/vendor/webrtc-dtls/examples/certificates/server.pub.pem b/vendor/webrtc-dtls/examples/certificates/server.pub.pem new file mode 100644 index 0000000..bfdd542 --- /dev/null +++ b/vendor/webrtc-dtls/examples/certificates/server.pub.pem @@ -0,0 +1,9 @@ +-----BEGIN CERTIFICATE----- +MIIBMjCB2qADAgECAhQzsfVoH1cRfcxCY/drp/cKdjvBDDAKBggqhkjOPQQDAjAN +MQswCQYDVQQGEwJOTDAeFw0yMTA5MTgyMDM2NTVaFw0yMjA5MTgyMDM2NTVaMA0x +CzAJBgNVBAYTAk5MMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEkciW4G3Ingmw +tfx24qpgA5D8X5OQZsI3otmF4TxPqGEtxefnX+ASjQYLO6cux7MXO+vPul/B5r2J +X75NpB1wFaMYMBYwFAYDVR0RBA0wC4IJd2VicnRjLnJzMAoGCCqGSM49BAMCA0cA +MEQCIBZBGmNM3qig7OTMZLL4PYj4JrGMjIj/jZFHEhqeQn6HAiBpRte9WzCjJzZX +vzRkUKfCs1NMa/XR0hfdaa8KJAdKyQ== +-----END CERTIFICATE----- diff --git a/vendor/webrtc-dtls/examples/dial/psk/dial_psk.rs b/vendor/webrtc-dtls/examples/dial/psk/dial_psk.rs new file mode 100644 index 0000000..9f73de9 --- /dev/null +++ b/vendor/webrtc-dtls/examples/dial/psk/dial_psk.rs @@ -0,0 +1,83 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use tokio::net::UdpSocket; +use util::Conn; +use webrtc_dtls::cipher_suite::CipherSuiteId; +use webrtc_dtls::config::*; +use webrtc_dtls::conn::DTLSConn; +use webrtc_dtls::Error; + +// cargo run --example dial_psk -- --server 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Client") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Client") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("server") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("server") + .help("DTLS Server name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let server = matches.value_of("server").unwrap(); + + let conn = Arc::new(UdpSocket::bind("0.0.0.0:0").await?); + conn.connect(server).await?; + println!("connecting {server}.."); + + let config = Config { + psk: Some(Arc::new(|hint: &[u8]| -> Result, Error> { + println!("Server's hint: {}", String::from_utf8(hint.to_vec())?); + Ok(vec![0xAB, 0xC1, 0x23]) + })), + psk_identity_hint: Some("webrtc-rs DTLS Server".as_bytes().to_vec()), + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }; + let dtls_conn: Arc = + Arc::new(DTLSConn::new(conn, config, true, None).await?); + + println!("Connected; type 'exit' to shutdown gracefully"); + let _ = hub::utilities::chat(Arc::clone(&dtls_conn)).await; + + dtls_conn.close().await?; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/examples/dial/selfsign/dial_selfsign.rs b/vendor/webrtc-dtls/examples/dial/selfsign/dial_selfsign.rs new file mode 100644 index 0000000..340a463 --- /dev/null +++ b/vendor/webrtc-dtls/examples/dial/selfsign/dial_selfsign.rs @@ -0,0 +1,82 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use tokio::net::UdpSocket; +use util::Conn; +use webrtc_dtls::config::*; +use webrtc_dtls::conn::DTLSConn; +use webrtc_dtls::crypto::Certificate; +use webrtc_dtls::Error; + +// cargo run --example dial_selfsign -- --server 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Client") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Client") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("server") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("server") + .help("DTLS Server name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let server = matches.value_of("server").unwrap(); + + let conn = Arc::new(UdpSocket::bind("0.0.0.0:0").await?); + conn.connect(server).await?; + println!("connecting {server}.."); + + // Generate a certificate and private key to secure the connection + let certificate = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + + let config = Config { + certificates: vec![certificate], + insecure_skip_verify: true, + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }; + let dtls_conn: Arc = + Arc::new(DTLSConn::new(conn, config, true, None).await?); + + println!("Connected; type 'exit' to shutdown gracefully"); + let _ = hub::utilities::chat(Arc::clone(&dtls_conn)).await; + + dtls_conn.close().await?; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/examples/dial/verify/dial_verify.rs b/vendor/webrtc-dtls/examples/dial/verify/dial_verify.rs new file mode 100644 index 0000000..f8aba22 --- /dev/null +++ b/vendor/webrtc-dtls/examples/dial/verify/dial_verify.rs @@ -0,0 +1,93 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use hub::utilities::load_certificate; +use tokio::net::UdpSocket; +use util::Conn; +use webrtc_dtls::config::*; +use webrtc_dtls::conn::DTLSConn; +use webrtc_dtls::Error; + +// cargo run --example dial_verify -- --server 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Client") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Client") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("server") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("server") + .help("DTLS Server name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let server = matches.value_of("server").unwrap(); + + let conn = Arc::new(UdpSocket::bind("0.0.0.0:0").await?); + conn.connect(server).await?; + println!("connecting {server}.."); + + let certificate = hub::utilities::load_key_and_certificate( + "dtls/examples/certificates/client.pem.private_key.pem".into(), + "dtls/examples/certificates/client.pub.pem".into(), + )?; + + let mut cert_pool = rustls::RootCertStore::empty(); + let certs = load_certificate("dtls/examples/certificates/server.pub.pem".into())?; + for cert in &certs { + if cert_pool.add(cert).is_err() { + return Err(Error::Other("cert_pool add_pem_file failed".to_owned())); + } + } + + let config = Config { + certificates: vec![certificate], + extended_master_secret: ExtendedMasterSecretType::Require, + roots_cas: cert_pool, + server_name: "webrtc.rs".to_owned(), + ..Default::default() + }; + let dtls_conn: Arc = + Arc::new(DTLSConn::new(conn, config, true, None).await?); + + println!("Connected; type 'exit' to shutdown gracefully"); + let _ = hub::utilities::chat(Arc::clone(&dtls_conn)).await; + + dtls_conn.close().await?; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/examples/listen/psk/listen_psk.rs b/vendor/webrtc-dtls/examples/listen/psk/listen_psk.rs new file mode 100644 index 0000000..fc536bb --- /dev/null +++ b/vendor/webrtc-dtls/examples/listen/psk/listen_psk.rs @@ -0,0 +1,89 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use util::conn::*; +use webrtc_dtls::cipher_suite::CipherSuiteId; +use webrtc_dtls::config::{Config, ExtendedMasterSecretType}; +use webrtc_dtls::listener::listen; +use webrtc_dtls::Error; + +// cargo run --example listen_psk -- --host 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Server") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Server") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("host") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("host") + .help("DTLS host name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let host = matches.value_of("host").unwrap().to_owned(); + + let cfg = Config { + psk: Some(Arc::new(|hint: &[u8]| -> Result, Error> { + println!("Client's hint: {}", String::from_utf8(hint.to_vec())?); + Ok(vec![0xAB, 0xC1, 0x23]) + })), + psk_identity_hint: Some("webrtc-rs DTLS Client".as_bytes().to_vec()), + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }; + + println!("listening {host}...\ntype 'exit' to shutdown gracefully"); + + let listener = Arc::new(listen(host, cfg).await?); + + // Simulate a chat session + let h = Arc::new(hub::Hub::new()); + + let listener2 = Arc::clone(&listener); + let h2 = Arc::clone(&h); + tokio::spawn(async move { + while let Ok((dtls_conn, _remote_addr)) = listener2.accept().await { + // Register the connection with the chat hub + h2.register(dtls_conn).await; + } + }); + + h.chat().await; + + Ok(listener.close().await?) +} diff --git a/vendor/webrtc-dtls/examples/listen/selfsign/listen_selfsign.rs b/vendor/webrtc-dtls/examples/listen/selfsign/listen_selfsign.rs new file mode 100644 index 0000000..19a54fd --- /dev/null +++ b/vendor/webrtc-dtls/examples/listen/selfsign/listen_selfsign.rs @@ -0,0 +1,87 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use util::conn::*; +use webrtc_dtls::config::{Config, ExtendedMasterSecretType}; +use webrtc_dtls::crypto::Certificate; +use webrtc_dtls::listener::listen; +use webrtc_dtls::Error; + +// cargo run --example listen_selfsign -- --host 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Server") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Server") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("host") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("host") + .help("DTLS host name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let host = matches.value_of("host").unwrap().to_owned(); + + // Generate a certificate and private key to secure the connection + let certificate = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + + let cfg = Config { + certificates: vec![certificate], + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }; + + println!("listening {host}...\ntype 'exit' to shutdown gracefully"); + + let listener = Arc::new(listen(host, cfg).await?); + + // Simulate a chat session + let h = Arc::new(hub::Hub::new()); + + let listener2 = Arc::clone(&listener); + let h2 = Arc::clone(&h); + tokio::spawn(async move { + while let Ok((dtls_conn, _remote_addr)) = listener2.accept().await { + // Register the connection with the chat hub + h2.register(dtls_conn).await; + } + }); + + h.chat().await; + + Ok(listener.close().await?) +} diff --git a/vendor/webrtc-dtls/examples/listen/verify/listen_verify.rs b/vendor/webrtc-dtls/examples/listen/verify/listen_verify.rs new file mode 100644 index 0000000..78bb492 --- /dev/null +++ b/vendor/webrtc-dtls/examples/listen/verify/listen_verify.rs @@ -0,0 +1,118 @@ +use std::io::Write; +use std::sync::Arc; + +use clap::{App, AppSettings, Arg}; +use hub::utilities::load_certificate; +use util::conn::*; +use webrtc_dtls::config::{ClientAuthType, Config, ExtendedMasterSecretType}; +use webrtc_dtls::listener::listen; +use webrtc_dtls::Error; + +// cargo run --example listen_verify -- --host 127.0.0.1:4444 + +#[tokio::main] +async fn main() -> Result<(), Error> { + env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, log::LevelFilter::Trace) + .init(); + + let mut app = App::new("DTLS Server") + .version("0.1.0") + .author("Rain Liu ") + .about("An example of DTLS Server") + .setting(AppSettings::DeriveDisplayOrder) + .setting(AppSettings::SubcommandsNegateReqs) + .arg( + Arg::with_name("FULLHELP") + .help("Prints more detailed help information") + .long("fullhelp"), + ) + .arg( + Arg::with_name("host") + .required_unless("FULLHELP") + .takes_value(true) + .default_value("127.0.0.1:4444") + .long("host") + .help("DTLS host name."), + ); + + let matches = app.clone().get_matches(); + + if matches.is_present("FULLHELP") { + app.print_long_help().unwrap(); + std::process::exit(0); + } + + let host = matches.value_of("host").unwrap().to_owned(); + + let certificate = hub::utilities::load_key_and_certificate( + "dtls/examples/certificates/server.pem.private_key.pem".into(), + "dtls/examples/certificates/server.pub.pem".into(), + )?; + + let mut cert_pool = rustls::RootCertStore::empty(); + let certs = load_certificate("dtls/examples/certificates/server.pub.pem".into())?; + for cert in &certs { + if cert_pool.add(cert).is_err() { + return Err(Error::Other("cert_pool add_pem_file failed".to_owned())); + } + } + + let cfg = Config { + certificates: vec![certificate], + extended_master_secret: ExtendedMasterSecretType::Require, + client_auth: ClientAuthType::RequireAndVerifyClientCert, //RequireAnyClientCert, // + client_cas: cert_pool, + ..Default::default() + }; + + println!("listening {host}...\ntype 'exit' to shutdown gracefully"); + + let listener = Arc::new(listen(host, cfg).await?); + + // Simulate a chat session + let h = Arc::new(hub::Hub::new()); + + let (done_tx, mut done_rx) = tokio::sync::mpsc::channel::<()>(1); + let mut done_tx = Some(done_tx); + + let listener2 = Arc::clone(&listener); + let h2 = Arc::clone(&h); + tokio::spawn(async move { + loop { + tokio::select! { + _ = done_rx.recv() => { + break; + } + result = listener2.accept() => { + match result{ + Ok((dtls_conn, _)) => { + // Register the connection with the chat hub + h2.register(dtls_conn).await; + } + Err(err) => { + println!("connecting failed with error: {err}"); + } + } + } + } + } + }); + + h.chat().await; + + done_tx.take(); + + Ok(listener.close().await?) +} diff --git a/vendor/webrtc-dtls/src/alert/alert_test.rs b/vendor/webrtc-dtls/src/alert/alert_test.rs new file mode 100644 index 0000000..ad9fff9 --- /dev/null +++ b/vendor/webrtc-dtls/src/alert/alert_test.rs @@ -0,0 +1,50 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; +use crate::error::Error; + +#[test] +fn test_alert() -> Result<()> { + let tests = vec![ + ( + "Valid Alert", + vec![0x02, 0x0A], + Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnexpectedMessage, + }, + None, + ), + ( + "Invalid alert length", + vec![0x00], + Alert { + alert_level: AlertLevel::Invalid, + alert_description: AlertDescription::Invalid, + }, + Some(Error::Other("io".to_owned())), + ), + ]; + + for (name, data, wanted, unmarshal_error) in tests { + let mut reader = BufReader::new(data.as_slice()); + let result = Alert::unmarshal(&mut reader); + + if let Some(err) = unmarshal_error { + assert!(result.is_err(), "{name} expected error: {err}"); + } else if let Ok(alert) = result { + assert_eq!(wanted, alert, "{name} expected {wanted}, but got {alert}"); + + let mut data2: Vec = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(data2.as_mut()); + alert.marshal(&mut writer)?; + } + assert_eq!(data, data2, "{name} expected {data:?}, but got {data2:?}"); + } else { + assert!(result.is_ok(), "{name} expected Ok, but has error"); + } + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/alert/mod.rs b/vendor/webrtc-dtls/src/alert/mod.rs new file mode 100644 index 0000000..197aec2 --- /dev/null +++ b/vendor/webrtc-dtls/src/alert/mod.rs @@ -0,0 +1,185 @@ +#[cfg(test)] +mod alert_test; + +use std::fmt; +use std::io::{Read, Write}; + +use byteorder::{ReadBytesExt, WriteBytesExt}; + +use super::content::*; +use crate::error::Result; + +#[derive(Copy, Clone, PartialEq, Debug)] +pub(crate) enum AlertLevel { + Warning = 1, + Fatal = 2, + Invalid, +} + +impl fmt::Display for AlertLevel { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + AlertLevel::Warning => write!(f, "LevelWarning"), + AlertLevel::Fatal => write!(f, "LevelFatal"), + _ => write!(f, "Invalid alert level"), + } + } +} + +impl From for AlertLevel { + fn from(val: u8) -> Self { + match val { + 1 => AlertLevel::Warning, + 2 => AlertLevel::Fatal, + _ => AlertLevel::Invalid, + } + } +} + +#[derive(Copy, Clone, PartialEq, Debug)] +pub(crate) enum AlertDescription { + CloseNotify = 0, + UnexpectedMessage = 10, + BadRecordMac = 20, + DecryptionFailed = 21, + RecordOverflow = 22, + DecompressionFailure = 30, + HandshakeFailure = 40, + NoCertificate = 41, + BadCertificate = 42, + UnsupportedCertificate = 43, + CertificateRevoked = 44, + CertificateExpired = 45, + CertificateUnknown = 46, + IllegalParameter = 47, + UnknownCa = 48, + AccessDenied = 49, + DecodeError = 50, + DecryptError = 51, + ExportRestriction = 60, + ProtocolVersion = 70, + InsufficientSecurity = 71, + InternalError = 80, + UserCanceled = 90, + NoRenegotiation = 100, + UnsupportedExtension = 110, + UnknownPskIdentity = 115, + Invalid, +} + +impl fmt::Display for AlertDescription { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + AlertDescription::CloseNotify => write!(f, "CloseNotify"), + AlertDescription::UnexpectedMessage => write!(f, "UnexpectedMessage"), + AlertDescription::BadRecordMac => write!(f, "BadRecordMac"), + AlertDescription::DecryptionFailed => write!(f, "DecryptionFailed"), + AlertDescription::RecordOverflow => write!(f, "RecordOverflow"), + AlertDescription::DecompressionFailure => write!(f, "DecompressionFailure"), + AlertDescription::HandshakeFailure => write!(f, "HandshakeFailure"), + AlertDescription::NoCertificate => write!(f, "NoCertificate"), + AlertDescription::BadCertificate => write!(f, "BadCertificate"), + AlertDescription::UnsupportedCertificate => write!(f, "UnsupportedCertificate"), + AlertDescription::CertificateRevoked => write!(f, "CertificateRevoked"), + AlertDescription::CertificateExpired => write!(f, "CertificateExpired"), + AlertDescription::CertificateUnknown => write!(f, "CertificateUnknown"), + AlertDescription::IllegalParameter => write!(f, "IllegalParameter"), + AlertDescription::UnknownCa => write!(f, "UnknownCA"), + AlertDescription::AccessDenied => write!(f, "AccessDenied"), + AlertDescription::DecodeError => write!(f, "DecodeError"), + AlertDescription::DecryptError => write!(f, "DecryptError"), + AlertDescription::ExportRestriction => write!(f, "ExportRestriction"), + AlertDescription::ProtocolVersion => write!(f, "ProtocolVersion"), + AlertDescription::InsufficientSecurity => write!(f, "InsufficientSecurity"), + AlertDescription::InternalError => write!(f, "InternalError"), + AlertDescription::UserCanceled => write!(f, "UserCanceled"), + AlertDescription::NoRenegotiation => write!(f, "NoRenegotiation"), + AlertDescription::UnsupportedExtension => write!(f, "UnsupportedExtension"), + AlertDescription::UnknownPskIdentity => write!(f, "UnknownPskIdentity"), + _ => write!(f, "Invalid alert description"), + } + } +} + +impl From for AlertDescription { + fn from(val: u8) -> Self { + match val { + 0 => AlertDescription::CloseNotify, + 10 => AlertDescription::UnexpectedMessage, + 20 => AlertDescription::BadRecordMac, + 21 => AlertDescription::DecryptionFailed, + 22 => AlertDescription::RecordOverflow, + 30 => AlertDescription::DecompressionFailure, + 40 => AlertDescription::HandshakeFailure, + 41 => AlertDescription::NoCertificate, + 42 => AlertDescription::BadCertificate, + 43 => AlertDescription::UnsupportedCertificate, + 44 => AlertDescription::CertificateRevoked, + 45 => AlertDescription::CertificateExpired, + 46 => AlertDescription::CertificateUnknown, + 47 => AlertDescription::IllegalParameter, + 48 => AlertDescription::UnknownCa, + 49 => AlertDescription::AccessDenied, + 50 => AlertDescription::DecodeError, + 51 => AlertDescription::DecryptError, + 60 => AlertDescription::ExportRestriction, + 70 => AlertDescription::ProtocolVersion, + 71 => AlertDescription::InsufficientSecurity, + 80 => AlertDescription::InternalError, + 90 => AlertDescription::UserCanceled, + 100 => AlertDescription::NoRenegotiation, + 110 => AlertDescription::UnsupportedExtension, + 115 => AlertDescription::UnknownPskIdentity, + _ => AlertDescription::Invalid, + } + } +} + +// One of the content types supported by the TLS record layer is the +// alert type. Alert messages convey the severity of the message +// (warning or fatal) and a description of the alert. Alert messages +// with a level of fatal result in the immediate termination of the +// connection. In this case, other connections corresponding to the +// session may continue, but the session identifier MUST be invalidated, +// preventing the failed session from being used to establish new +// connections. Like other messages, alert messages are encrypted and +// compressed, as specified by the current connection state. +// https://tools.ietf.org/html/rfc5246#section-7.2 +#[derive(Copy, Clone, PartialEq, Debug)] +pub struct Alert { + pub(crate) alert_level: AlertLevel, + pub(crate) alert_description: AlertDescription, +} + +impl fmt::Display for Alert { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Alert {}: {}", self.alert_level, self.alert_description) + } +} + +impl Alert { + pub fn content_type(&self) -> ContentType { + ContentType::Alert + } + + pub fn size(&self) -> usize { + 2 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.alert_level as u8)?; + writer.write_u8(self.alert_description as u8)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let alert_level = reader.read_u8()?.into(); + let alert_description = reader.read_u8()?.into(); + + Ok(Alert { + alert_level, + alert_description, + }) + } +} diff --git a/vendor/webrtc-dtls/src/application_data.rs b/vendor/webrtc-dtls/src/application_data.rs new file mode 100644 index 0000000..4897430 --- /dev/null +++ b/vendor/webrtc-dtls/src/application_data.rs @@ -0,0 +1,37 @@ +use std::io::{Read, Write}; + +use super::content::*; +use crate::error::Result; + +// Application data messages are carried by the record layer and are +// fragmented, compressed, and encrypted based on the current connection +// state. The messages are treated as transparent data to the record +// layer. +// https://tools.ietf.org/html/rfc5246#section-10 +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct ApplicationData { + pub data: Vec, +} + +impl ApplicationData { + pub fn content_type(&self) -> ContentType { + ContentType::ApplicationData + } + + pub fn size(&self) -> usize { + self.data.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_all(&self.data)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let mut data: Vec = vec![]; + reader.read_to_end(&mut data)?; + + Ok(ApplicationData { data }) + } +} diff --git a/vendor/webrtc-dtls/src/change_cipher_spec/change_cipher_spec_test.rs b/vendor/webrtc-dtls/src/change_cipher_spec/change_cipher_spec_test.rs new file mode 100644 index 0000000..868d96d --- /dev/null +++ b/vendor/webrtc-dtls/src/change_cipher_spec/change_cipher_spec_test.rs @@ -0,0 +1,37 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_change_cipher_spec_round_trip() -> Result<()> { + let c = ChangeCipherSpec {}; + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + + let mut reader = BufReader::new(raw.as_slice()); + let cnew = ChangeCipherSpec::unmarshal(&mut reader)?; + assert_eq!( + c, cnew, + "ChangeCipherSpec round trip: got {cnew:?}, want {c:?}" + ); + + Ok(()) +} + +#[test] +fn test_change_cipher_spec_invalid() -> Result<()> { + let data = vec![0x00]; + + let mut reader = BufReader::new(data.as_slice()); + let result = ChangeCipherSpec::unmarshal(&mut reader); + + match result { + Ok(_) => panic!("must be error"), + Err(err) => assert_eq!(err.to_string(), Error::ErrInvalidCipherSpec.to_string()), + }; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/change_cipher_spec/mod.rs b/vendor/webrtc-dtls/src/change_cipher_spec/mod.rs new file mode 100644 index 0000000..51c08b0 --- /dev/null +++ b/vendor/webrtc-dtls/src/change_cipher_spec/mod.rs @@ -0,0 +1,42 @@ +#[cfg(test)] +mod change_cipher_spec_test; + +use std::io::{Read, Write}; + +use byteorder::{ReadBytesExt, WriteBytesExt}; + +use super::content::*; +use super::error::*; + +// The change cipher spec protocol exists to signal transitions in +// ciphering strategies. The protocol consists of a single message, +// which is encrypted and compressed under the current (not the pending) +// connection state. The message consists of a single byte of value 1. +// https://tools.ietf.org/html/rfc5246#section-7.1 +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct ChangeCipherSpec; + +impl ChangeCipherSpec { + pub fn content_type(&self) -> ContentType { + ContentType::ChangeCipherSpec + } + + pub fn size(&self) -> usize { + 1 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(0x01)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let data = reader.read_u8()?; + if data != 0x01 { + return Err(Error::ErrInvalidCipherSpec); + } + + Ok(ChangeCipherSpec {}) + } +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_ccm.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_ccm.rs new file mode 100644 index 0000000..a28ee0f --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_ccm.rs @@ -0,0 +1,118 @@ +use super::*; +use crate::client_certificate_type::ClientCertificateType; +use crate::crypto::crypto_ccm::{CryptoCcm, CryptoCcmTagLen}; +use crate::prf::*; + +#[derive(Clone)] +pub struct CipherSuiteAes128Ccm { + ccm: Option, + client_certificate_type: ClientCertificateType, + id: CipherSuiteId, + psk: bool, + crypto_ccm_tag_len: CryptoCcmTagLen, +} + +impl CipherSuiteAes128Ccm { + const PRF_MAC_LEN: usize = 0; + const PRF_KEY_LEN: usize = 16; + const PRF_IV_LEN: usize = 4; + + pub fn new( + client_certificate_type: ClientCertificateType, + id: CipherSuiteId, + psk: bool, + crypto_ccm_tag_len: CryptoCcmTagLen, + ) -> Self { + CipherSuiteAes128Ccm { + ccm: None, + client_certificate_type, + id, + psk, + crypto_ccm_tag_len, + } + } +} + +impl CipherSuite for CipherSuiteAes128Ccm { + fn to_string(&self) -> String { + format!("{}", self.id) + } + + fn id(&self) -> CipherSuiteId { + self.id + } + + fn certificate_type(&self) -> ClientCertificateType { + self.client_certificate_type + } + + fn hash_func(&self) -> CipherSuiteHash { + CipherSuiteHash::Sha256 + } + + fn is_psk(&self) -> bool { + self.psk + } + + fn is_initialized(&self) -> bool { + self.ccm.is_some() + } + + fn init( + &mut self, + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + is_client: bool, + ) -> Result<()> { + let keys = prf_encryption_keys( + master_secret, + client_random, + server_random, + CipherSuiteAes128Ccm::PRF_MAC_LEN, + CipherSuiteAes128Ccm::PRF_KEY_LEN, + CipherSuiteAes128Ccm::PRF_IV_LEN, + self.hash_func(), + )?; + + if is_client { + self.ccm = Some(CryptoCcm::new( + &self.crypto_ccm_tag_len, + &keys.client_write_key, + &keys.client_write_iv, + &keys.server_write_key, + &keys.server_write_iv, + )); + } else { + self.ccm = Some(CryptoCcm::new( + &self.crypto_ccm_tag_len, + &keys.server_write_key, + &keys.server_write_iv, + &keys.client_write_key, + &keys.client_write_iv, + )); + } + + Ok(()) + } + + fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + if let Some(ccm) = &self.ccm { + ccm.encrypt(pkt_rlh, raw) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to encrypt".to_owned(), + )) + } + } + + fn decrypt(&self, input: &[u8]) -> Result> { + if let Some(ccm) = &self.ccm { + ccm.decrypt(input) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to decrypt".to_owned(), + )) + } + } +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_gcm_sha256.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_gcm_sha256.rs new file mode 100644 index 0000000..fe7fd9a --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_128_gcm_sha256.rs @@ -0,0 +1,113 @@ +use super::*; +use crate::crypto::crypto_gcm::*; +use crate::prf::*; + +#[derive(Clone)] +pub struct CipherSuiteAes128GcmSha256 { + gcm: Option, + rsa: bool, +} + +impl CipherSuiteAes128GcmSha256 { + const PRF_MAC_LEN: usize = 0; + const PRF_KEY_LEN: usize = 16; + const PRF_IV_LEN: usize = 4; + + pub fn new(rsa: bool) -> Self { + CipherSuiteAes128GcmSha256 { gcm: None, rsa } + } +} + +impl CipherSuite for CipherSuiteAes128GcmSha256 { + fn to_string(&self) -> String { + if self.rsa { + "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256".to_owned() + } else { + "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256".to_owned() + } + } + + fn id(&self) -> CipherSuiteId { + if self.rsa { + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256 + } else { + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256 + } + } + + fn certificate_type(&self) -> ClientCertificateType { + if self.rsa { + ClientCertificateType::RsaSign + } else { + ClientCertificateType::EcdsaSign + } + } + + fn hash_func(&self) -> CipherSuiteHash { + CipherSuiteHash::Sha256 + } + + fn is_psk(&self) -> bool { + false + } + + fn is_initialized(&self) -> bool { + self.gcm.is_some() + } + + fn init( + &mut self, + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + is_client: bool, + ) -> Result<()> { + let keys = prf_encryption_keys( + master_secret, + client_random, + server_random, + CipherSuiteAes128GcmSha256::PRF_MAC_LEN, + CipherSuiteAes128GcmSha256::PRF_KEY_LEN, + CipherSuiteAes128GcmSha256::PRF_IV_LEN, + self.hash_func(), + )?; + + if is_client { + self.gcm = Some(CryptoGcm::new( + &keys.client_write_key, + &keys.client_write_iv, + &keys.server_write_key, + &keys.server_write_iv, + )); + } else { + self.gcm = Some(CryptoGcm::new( + &keys.server_write_key, + &keys.server_write_iv, + &keys.client_write_key, + &keys.client_write_iv, + )); + } + + Ok(()) + } + + fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + if let Some(cg) = &self.gcm { + cg.encrypt(pkt_rlh, raw) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to encrypt".to_owned(), + )) + } + } + + fn decrypt(&self, input: &[u8]) -> Result> { + if let Some(cg) = &self.gcm { + cg.decrypt(input) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to decrypt".to_owned(), + )) + } + } +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_256_cbc_sha.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_256_cbc_sha.rs new file mode 100644 index 0000000..e358279 --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_aes_256_cbc_sha.rs @@ -0,0 +1,113 @@ +use super::*; +use crate::crypto::crypto_cbc::*; +use crate::prf::*; + +#[derive(Clone)] +pub struct CipherSuiteAes256CbcSha { + cbc: Option, + rsa: bool, +} + +impl CipherSuiteAes256CbcSha { + const PRF_MAC_LEN: usize = 20; + const PRF_KEY_LEN: usize = 32; + const PRF_IV_LEN: usize = 16; + + pub fn new(rsa: bool) -> Self { + CipherSuiteAes256CbcSha { cbc: None, rsa } + } +} + +impl CipherSuite for CipherSuiteAes256CbcSha { + fn to_string(&self) -> String { + if self.rsa { + "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA".to_owned() + } else { + "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA".to_owned() + } + } + + fn id(&self) -> CipherSuiteId { + if self.rsa { + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha + } else { + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha + } + } + + fn certificate_type(&self) -> ClientCertificateType { + if self.rsa { + ClientCertificateType::RsaSign + } else { + ClientCertificateType::EcdsaSign + } + } + + fn hash_func(&self) -> CipherSuiteHash { + CipherSuiteHash::Sha256 + } + + fn is_psk(&self) -> bool { + false + } + + fn is_initialized(&self) -> bool { + self.cbc.is_some() + } + + fn init( + &mut self, + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + is_client: bool, + ) -> Result<()> { + let keys = prf_encryption_keys( + master_secret, + client_random, + server_random, + CipherSuiteAes256CbcSha::PRF_MAC_LEN, + CipherSuiteAes256CbcSha::PRF_KEY_LEN, + CipherSuiteAes256CbcSha::PRF_IV_LEN, + self.hash_func(), + )?; + + if is_client { + self.cbc = Some(CryptoCbc::new( + &keys.client_write_key, + &keys.client_mac_key, + &keys.server_write_key, + &keys.server_mac_key, + )?); + } else { + self.cbc = Some(CryptoCbc::new( + &keys.server_write_key, + &keys.server_mac_key, + &keys.client_write_key, + &keys.client_mac_key, + )?); + } + + Ok(()) + } + + fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + if let Some(cg) = &self.cbc { + cg.encrypt(pkt_rlh, raw) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to encrypt".to_owned(), + )) + } + } + + fn decrypt(&self, input: &[u8]) -> Result> { + if let Some(cg) = &self.cbc { + cg.decrypt(input) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to decrypt".to_owned(), + )) + } + } +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm.rs new file mode 100644 index 0000000..c5bf2df --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm.rs @@ -0,0 +1,12 @@ +use super::*; +use crate::cipher_suite::cipher_suite_aes_128_ccm::CipherSuiteAes128Ccm; +use crate::crypto::crypto_ccm::CryptoCcmTagLen; + +pub fn new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm() -> CipherSuiteAes128Ccm { + CipherSuiteAes128Ccm::new( + ClientCertificateType::EcdsaSign, + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm, + false, + CryptoCcmTagLen::CryptoCcmTagLength, + ) +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8.rs new file mode 100644 index 0000000..aa9a92c --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8.rs @@ -0,0 +1,12 @@ +use super::*; +use crate::cipher_suite::cipher_suite_aes_128_ccm::CipherSuiteAes128Ccm; +use crate::crypto::crypto_ccm::CryptoCcmTagLen; + +pub fn new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8() -> CipherSuiteAes128Ccm { + CipherSuiteAes128Ccm::new( + ClientCertificateType::EcdsaSign, + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8, + false, + CryptoCcmTagLen::CryptoCcm8TagLength, + ) +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm.rs new file mode 100644 index 0000000..6f506e0 --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm.rs @@ -0,0 +1,12 @@ +use super::*; +use crate::cipher_suite::cipher_suite_aes_128_ccm::CipherSuiteAes128Ccm; +use crate::crypto::crypto_ccm::CryptoCcmTagLen; + +pub fn new_cipher_suite_tls_psk_with_aes_128_ccm() -> CipherSuiteAes128Ccm { + CipherSuiteAes128Ccm::new( + ClientCertificateType::Unsupported, + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm, + true, + CryptoCcmTagLen::CryptoCcmTagLength, + ) +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm8.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm8.rs new file mode 100644 index 0000000..64b9f1a --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_ccm8.rs @@ -0,0 +1,12 @@ +use super::*; +use crate::cipher_suite::cipher_suite_aes_128_ccm::CipherSuiteAes128Ccm; +use crate::crypto::crypto_ccm::CryptoCcmTagLen; + +pub fn new_cipher_suite_tls_psk_with_aes_128_ccm8() -> CipherSuiteAes128Ccm { + CipherSuiteAes128Ccm::new( + ClientCertificateType::Unsupported, + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8, + true, + CryptoCcmTagLen::CryptoCcm8TagLength, + ) +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_gcm_sha256.rs b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_gcm_sha256.rs new file mode 100644 index 0000000..2204ace --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/cipher_suite_tls_psk_with_aes_128_gcm_sha256.rs @@ -0,0 +1,96 @@ +use super::*; +use crate::crypto::crypto_gcm::*; +use crate::prf::*; + +#[derive(Clone, Default)] +pub struct CipherSuiteTlsPskWithAes128GcmSha256 { + gcm: Option, +} + +impl CipherSuiteTlsPskWithAes128GcmSha256 { + const PRF_MAC_LEN: usize = 0; + const PRF_KEY_LEN: usize = 16; + const PRF_IV_LEN: usize = 4; +} + +impl CipherSuite for CipherSuiteTlsPskWithAes128GcmSha256 { + fn to_string(&self) -> String { + "TLS_PSK_WITH_AES_128_GCM_SHA256".to_owned() + } + + fn id(&self) -> CipherSuiteId { + CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256 + } + + fn certificate_type(&self) -> ClientCertificateType { + ClientCertificateType::Unsupported + } + + fn hash_func(&self) -> CipherSuiteHash { + CipherSuiteHash::Sha256 + } + + fn is_psk(&self) -> bool { + true + } + + fn is_initialized(&self) -> bool { + self.gcm.is_some() + } + + fn init( + &mut self, + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + is_client: bool, + ) -> Result<()> { + let keys = prf_encryption_keys( + master_secret, + client_random, + server_random, + CipherSuiteTlsPskWithAes128GcmSha256::PRF_MAC_LEN, + CipherSuiteTlsPskWithAes128GcmSha256::PRF_KEY_LEN, + CipherSuiteTlsPskWithAes128GcmSha256::PRF_IV_LEN, + self.hash_func(), + )?; + + if is_client { + self.gcm = Some(CryptoGcm::new( + &keys.client_write_key, + &keys.client_write_iv, + &keys.server_write_key, + &keys.server_write_iv, + )); + } else { + self.gcm = Some(CryptoGcm::new( + &keys.server_write_key, + &keys.server_write_iv, + &keys.client_write_key, + &keys.client_write_iv, + )); + } + + Ok(()) + } + + fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + if let Some(cg) = &self.gcm { + cg.encrypt(pkt_rlh, raw) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to encrypt".to_owned(), + )) + } + } + + fn decrypt(&self, input: &[u8]) -> Result> { + if let Some(cg) = &self.gcm { + cg.decrypt(input) + } else { + Err(Error::Other( + "CipherSuite has not been initialized, unable to decrypt".to_owned(), + )) + } + } +} diff --git a/vendor/webrtc-dtls/src/cipher_suite/mod.rs b/vendor/webrtc-dtls/src/cipher_suite/mod.rs new file mode 100644 index 0000000..195492c --- /dev/null +++ b/vendor/webrtc-dtls/src/cipher_suite/mod.rs @@ -0,0 +1,227 @@ +pub mod cipher_suite_aes_128_ccm; +pub mod cipher_suite_aes_128_gcm_sha256; +pub mod cipher_suite_aes_256_cbc_sha; +pub mod cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm; +pub mod cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8; +pub mod cipher_suite_tls_psk_with_aes_128_ccm; +pub mod cipher_suite_tls_psk_with_aes_128_ccm8; +pub mod cipher_suite_tls_psk_with_aes_128_gcm_sha256; + +use std::fmt; +use std::marker::{Send, Sync}; + +use cipher_suite_aes_128_gcm_sha256::*; +use cipher_suite_aes_256_cbc_sha::*; +use cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm::*; +use cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8::*; +use cipher_suite_tls_psk_with_aes_128_ccm::*; +use cipher_suite_tls_psk_with_aes_128_ccm8::*; +use cipher_suite_tls_psk_with_aes_128_gcm_sha256::*; + +use super::client_certificate_type::*; +use super::error::*; +use super::record_layer::record_layer_header::*; + +// CipherSuiteID is an ID for our supported CipherSuites +// Supported Cipher Suites +#[allow(non_camel_case_types)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum CipherSuiteId { + // AES-128-CCM + Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm = 0xc0ac, + Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8 = 0xc0ae, + + // AES-128-GCM-SHA256 + Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256 = 0xc02b, + Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256 = 0xc02f, + + // AES-256-CBC-SHA + Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha = 0xc00a, + Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha = 0xc014, + + Tls_Psk_With_Aes_128_Ccm = 0xc0a4, + Tls_Psk_With_Aes_128_Ccm_8 = 0xc0a8, + Tls_Psk_With_Aes_128_Gcm_Sha256 = 0x00a8, + + Unsupported, +} + +impl fmt::Display for CipherSuiteId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm => { + write!(f, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM") + } + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8 => { + write!(f, "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8") + } + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256 => { + write!(f, "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256") + } + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256 => { + write!(f, "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256") + } + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha => { + write!(f, "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA") + } + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha => { + write!(f, "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA") + } + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm => write!(f, "TLS_PSK_WITH_AES_128_CCM"), + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8 => write!(f, "TLS_PSK_WITH_AES_128_CCM_8"), + CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256 => { + write!(f, "TLS_PSK_WITH_AES_128_GCM_SHA256") + } + _ => write!(f, "Unsupported CipherSuiteID"), + } + } +} + +impl From for CipherSuiteId { + fn from(val: u16) -> Self { + match val { + // AES-128-CCM + 0xc0ac => CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm, + 0xc0ae => CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8, + + // AES-128-GCM-SHA256 + 0xc02b => CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + 0xc02f => CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256, + + // AES-256-CBC-SHA + 0xc00a => CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha, + 0xc014 => CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha, + + 0xc0a4 => CipherSuiteId::Tls_Psk_With_Aes_128_Ccm, + 0xc0a8 => CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8, + 0x00a8 => CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256, + + _ => CipherSuiteId::Unsupported, + } + } +} + +#[derive(Copy, Clone, Debug)] +pub enum CipherSuiteHash { + Sha256, +} + +impl CipherSuiteHash { + pub(crate) fn size(&self) -> usize { + match *self { + CipherSuiteHash::Sha256 => 32, + } + } +} + +pub trait CipherSuite { + fn to_string(&self) -> String; + fn id(&self) -> CipherSuiteId; + fn certificate_type(&self) -> ClientCertificateType; + fn hash_func(&self) -> CipherSuiteHash; + fn is_psk(&self) -> bool; + fn is_initialized(&self) -> bool; + + // Generate the internal encryption state + fn init( + &mut self, + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + is_client: bool, + ) -> Result<()>; + + fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result>; + fn decrypt(&self, input: &[u8]) -> Result>; +} + +// Taken from https://www.iana.org/assignments/tls-parameters/tls-parameters.xml +// A cipher_suite is a specific combination of key agreement, cipher and MAC +// function. +pub fn cipher_suite_for_id(id: CipherSuiteId) -> Result> { + match id { + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm => { + Ok(Box::new(new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm())) + } + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8 => Ok(Box::new( + new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8(), + )), + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256 => { + Ok(Box::new(CipherSuiteAes128GcmSha256::new(false))) + } + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256 => { + Ok(Box::new(CipherSuiteAes128GcmSha256::new(true))) + } + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_256_Cbc_Sha => { + Ok(Box::new(CipherSuiteAes256CbcSha::new(true))) + } + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha => { + Ok(Box::new(CipherSuiteAes256CbcSha::new(false))) + } + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm => { + Ok(Box::new(new_cipher_suite_tls_psk_with_aes_128_ccm())) + } + CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8 => { + Ok(Box::new(new_cipher_suite_tls_psk_with_aes_128_ccm8())) + } + CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256 => { + Ok(Box::::default()) + } + _ => Err(Error::ErrInvalidCipherSuite), + } +} + +// CipherSuites we support in order of preference +pub(crate) fn default_cipher_suites() -> Vec> { + vec![ + Box::new(CipherSuiteAes128GcmSha256::new(false)), + Box::new(CipherSuiteAes256CbcSha::new(false)), + Box::new(CipherSuiteAes128GcmSha256::new(true)), + Box::new(CipherSuiteAes256CbcSha::new(true)), + ] +} + +fn all_cipher_suites() -> Vec> { + vec![ + Box::new(new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm()), + Box::new(new_cipher_suite_tls_ecdhe_ecdsa_with_aes_128_ccm8()), + Box::new(CipherSuiteAes128GcmSha256::new(false)), + Box::new(CipherSuiteAes128GcmSha256::new(true)), + Box::new(CipherSuiteAes256CbcSha::new(false)), + Box::new(CipherSuiteAes256CbcSha::new(true)), + Box::new(new_cipher_suite_tls_psk_with_aes_128_ccm()), + Box::new(new_cipher_suite_tls_psk_with_aes_128_ccm8()), + Box::::default(), + ] +} + +fn cipher_suites_for_ids(ids: &[CipherSuiteId]) -> Result>> { + let mut cipher_suites = vec![]; + for id in ids { + cipher_suites.push(cipher_suite_for_id(*id)?); + } + Ok(cipher_suites) +} + +pub(crate) fn parse_cipher_suites( + user_selected_suites: &[CipherSuiteId], + exclude_psk: bool, + exclude_non_psk: bool, +) -> Result>> { + let cipher_suites = if !user_selected_suites.is_empty() { + cipher_suites_for_ids(user_selected_suites)? + } else { + default_cipher_suites() + }; + + let filtered_cipher_suites: Vec> = cipher_suites + .into_iter() + .filter(|c| !((exclude_psk && c.is_psk()) || (exclude_non_psk && !c.is_psk()))) + .collect(); + + if filtered_cipher_suites.is_empty() { + Err(Error::ErrNoAvailableCipherSuites) + } else { + Ok(filtered_cipher_suites) + } +} diff --git a/vendor/webrtc-dtls/src/client_certificate_type.rs b/vendor/webrtc-dtls/src/client_certificate_type.rs new file mode 100644 index 0000000..d87aacb --- /dev/null +++ b/vendor/webrtc-dtls/src/client_certificate_type.rs @@ -0,0 +1,16 @@ +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum ClientCertificateType { + RsaSign = 1, + EcdsaSign = 64, + Unsupported, +} + +impl From for ClientCertificateType { + fn from(val: u8) -> Self { + match val { + 1 => ClientCertificateType::RsaSign, + 64 => ClientCertificateType::EcdsaSign, + _ => ClientCertificateType::Unsupported, + } + } +} diff --git a/vendor/webrtc-dtls/src/compression_methods.rs b/vendor/webrtc-dtls/src/compression_methods.rs new file mode 100644 index 0000000..a03195e --- /dev/null +++ b/vendor/webrtc-dtls/src/compression_methods.rs @@ -0,0 +1,60 @@ +use std::io::{Read, Write}; + +use byteorder::{ReadBytesExt, WriteBytesExt}; + +use crate::error::Result; + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum CompressionMethodId { + Null = 0, + Unsupported, +} + +impl From for CompressionMethodId { + fn from(val: u8) -> Self { + match val { + 0 => CompressionMethodId::Null, + _ => CompressionMethodId::Unsupported, + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct CompressionMethods { + pub ids: Vec, +} + +impl CompressionMethods { + pub fn size(&self) -> usize { + 1 + self.ids.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.ids.len() as u8)?; + + for id in &self.ids { + writer.write_u8(*id as u8)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let compression_methods_count = reader.read_u8()? as usize; + let mut ids = vec![]; + for _ in 0..compression_methods_count { + let id = reader.read_u8()?.into(); + if id != CompressionMethodId::Unsupported { + ids.push(id); + } + } + + Ok(CompressionMethods { ids }) + } +} + +pub fn default_compression_methods() -> CompressionMethods { + CompressionMethods { + ids: vec![CompressionMethodId::Null], + } +} diff --git a/vendor/webrtc-dtls/src/config.rs b/vendor/webrtc-dtls/src/config.rs new file mode 100644 index 0000000..0e1e23c --- /dev/null +++ b/vendor/webrtc-dtls/src/config.rs @@ -0,0 +1,190 @@ +use std::sync::Arc; + +use tokio::time::Duration; + +use crate::cipher_suite::*; +use crate::crypto::*; +use crate::error::*; +use crate::extension::extension_use_srtp::SrtpProtectionProfile; +use crate::handshaker::VerifyPeerCertificateFn; +use crate::signature_hash_algorithm::SignatureScheme; + +/// Config is used to configure a DTLS client or server. +/// After a Config is passed to a DTLS function it must not be modified. +#[derive(Clone)] +pub struct Config { + /// certificates contains certificate chain to present to the other side of the connection. + /// Server MUST set this if psk is non-nil + /// client SHOULD sets this so CertificateRequests can be handled if psk is non-nil + pub certificates: Vec, + + /// cipher_suites is a list of supported cipher suites. + /// If cipher_suites is nil, a default list is used + pub cipher_suites: Vec, + + /// signature_schemes contains the signature and hash schemes that the peer requests to verify. + pub signature_schemes: Vec, + + /// srtp_protection_profiles are the supported protection profiles + /// Clients will send this via use_srtp and assert that the server properly responds + /// Servers will assert that clients send one of these profiles and will respond as needed + pub srtp_protection_profiles: Vec, + + /// client_auth determines the server's policy for + /// TLS Client Authentication. The default is NoClientCert. + pub client_auth: ClientAuthType, + + /// extended_master_secret determines if the "Extended Master Secret" extension + /// should be disabled, requested, or required (default requested). + pub extended_master_secret: ExtendedMasterSecretType, + + /// flight_interval controls how often we send outbound handshake messages + /// defaults to time.Second + pub flight_interval: Duration, + + /// psk sets the pre-shared key used by this DTLS connection + /// If psk is non-nil only psk cipher_suites will be used + pub psk: Option, + pub psk_identity_hint: Option>, + + /// insecure_skip_verify controls whether a client verifies the + /// server's certificate chain and host name. + /// If insecure_skip_verify is true, TLS accepts any certificate + /// presented by the server and any host name in that certificate. + /// In this mode, TLS is susceptible to man-in-the-middle attacks. + /// This should be used only for testing. + pub insecure_skip_verify: bool, + + /// insecure_hashes allows the use of hashing algorithms that are known + /// to be vulnerable. + pub insecure_hashes: bool, + + /// insecure_verification allows the use of verification algorithms that are + /// known to be vulnerable or deprecated + pub insecure_verification: bool, + /// VerifyPeerCertificate, if not nil, is called after normal + /// certificate verification by either a client or server. It + /// receives the certificate provided by the peer and also a flag + /// that tells if normal verification has succeeded. If it returns a + /// non-nil error, the handshake is aborted and that error results. + /// + /// If normal verification fails then the handshake will abort before + /// considering this callback. If normal verification is disabled by + /// setting insecure_skip_verify, or (for a server) when client_auth is + /// RequestClientCert or RequireAnyClientCert, then this callback will + /// be considered but the verifiedChains will always be nil. + pub verify_peer_certificate: Option, + + /// roots_cas defines the set of root certificate authorities + /// that one peer uses when verifying the other peer's certificates. + /// If RootCAs is nil, TLS uses the host's root CA set. + /// Used by Client to verify server's certificate + pub roots_cas: rustls::RootCertStore, + + /// client_cas defines the set of root certificate authorities + /// that servers use if required to verify a client certificate + /// by the policy in client_auth. + /// Used by Server to verify client's certificate + pub client_cas: rustls::RootCertStore, + + /// server_name is used to verify the hostname on the returned + /// certificates unless insecure_skip_verify is given. + pub server_name: String, + + /// mtu is the length at which handshake messages will be fragmented to + /// fit within the maximum transmission unit (default is 1200 bytes) + pub mtu: usize, + + /// replay_protection_window is the size of the replay attack protection window. + /// Duplication of the sequence number is checked in this window size. + /// Packet with sequence number older than this value compared to the latest + /// accepted packet will be discarded. (default is 64) + pub replay_protection_window: usize, +} + +impl Default for Config { + fn default() -> Self { + Config { + certificates: vec![], + cipher_suites: vec![], + signature_schemes: vec![], + srtp_protection_profiles: vec![], + client_auth: ClientAuthType::default(), + extended_master_secret: ExtendedMasterSecretType::default(), + flight_interval: Duration::default(), + psk: None, + psk_identity_hint: None, + insecure_skip_verify: false, + insecure_hashes: false, + insecure_verification: false, + verify_peer_certificate: None, + roots_cas: rustls::RootCertStore::empty(), + client_cas: rustls::RootCertStore::empty(), + server_name: String::default(), + mtu: 0, + replay_protection_window: 0, + } + } +} + +pub(crate) const DEFAULT_MTU: usize = 1200; // bytes + +// PSKCallback is called once we have the remote's psk_identity_hint. +// If the remote provided none it will be nil +pub(crate) type PskCallback = Arc Result>) + Send + Sync>; + +// ClientAuthType declares the policy the server will follow for +// TLS Client Authentication. +#[derive(Default, Copy, Clone, PartialEq, Eq)] +pub enum ClientAuthType { + #[default] + NoClientCert = 0, + RequestClientCert = 1, + RequireAnyClientCert = 2, + VerifyClientCertIfGiven = 3, + RequireAndVerifyClientCert = 4, +} + +// ExtendedMasterSecretType declares the policy the client and server +// will follow for the Extended Master Secret extension +#[derive(Default, PartialEq, Eq, Copy, Clone)] +pub enum ExtendedMasterSecretType { + #[default] + Request = 0, + Require = 1, + Disable = 2, +} + +pub(crate) fn validate_config(is_client: bool, config: &Config) -> Result<()> { + if is_client && config.psk.is_some() && config.psk_identity_hint.is_none() { + return Err(Error::ErrPskAndIdentityMustBeSetForClient); + } + + if !is_client && config.psk.is_none() && config.certificates.is_empty() { + return Err(Error::ErrServerMustHaveCertificate); + } + + if !config.certificates.is_empty() && config.psk.is_some() { + return Err(Error::ErrPskAndCertificate); + } + + if config.psk_identity_hint.is_some() && config.psk.is_none() { + return Err(Error::ErrIdentityNoPsk); + } + + for cert in &config.certificates { + match cert.private_key.kind { + CryptoPrivateKeyKind::Ed25519(_) => {} + CryptoPrivateKeyKind::Ecdsa256(_) => {} + _ => return Err(Error::ErrInvalidPrivateKey), + } + } + + parse_cipher_suites( + &config.cipher_suites, + config.psk.is_none(), + config.psk.is_some(), + )?; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/conn/conn_test.rs b/vendor/webrtc-dtls/src/conn/conn_test.rs new file mode 100644 index 0000000..3043d2a --- /dev/null +++ b/vendor/webrtc-dtls/src/conn/conn_test.rs @@ -0,0 +1,2457 @@ +use std::time::SystemTime; + +use rand::Rng; +use util::conn::conn_pipe::*; +use util::KeyingMaterialExporter; + +use super::*; +use crate::cipher_suite::cipher_suite_aes_128_gcm_sha256::*; +use crate::cipher_suite::*; +use crate::compression_methods::*; +use crate::crypto::*; +use crate::curve::*; +use crate::error::*; +use crate::extension::extension_supported_elliptic_curves::*; +use crate::extension::extension_supported_point_formats::*; +use crate::extension::extension_supported_signature_algorithms::*; +use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; +use crate::extension::*; +use crate::handshake::handshake_message_certificate::*; +use crate::handshake::handshake_message_client_hello::*; +use crate::handshake::handshake_message_hello_verify_request::*; +use crate::handshake::handshake_message_server_hello::*; +use crate::handshake::handshake_message_server_hello_done::*; +use crate::handshake::handshake_message_server_key_exchange::*; +use crate::handshake::handshake_random::*; +use crate::signature_hash_algorithm::*; + +const ERR_TEST_PSK_INVALID_IDENTITY: &str = "TestPSK: Server got invalid identity"; +const ERR_PSK_REJECTED: &str = "PSK Rejected"; +const ERR_NOT_EXPECTED_CHAIN: &str = "not expected chain"; +const ERR_EXPECTED_CHAIN: &str = "expected chain"; +const ERR_WRONG_CERT: &str = "wrong cert"; + +async fn build_pipe() -> Result<(DTLSConn, DTLSConn)> { + let (ua, ub) = pipe(); + + pipe_conn(Arc::new(ua), Arc::new(ub)).await +} + +async fn pipe_conn( + ca: Arc, + cb: Arc, +) -> Result<(DTLSConn, DTLSConn)> { + let (c_tx, mut c_rx) = mpsc::channel(1); + + // Setup client + tokio::spawn(async move { + let client = create_test_client( + ca, + Config { + srtp_protection_profiles: vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + ..Default::default() + }, + true, + ) + .await; + + let _ = c_tx.send(client).await; + }); + + // Setup server + let sever = create_test_server( + cb, + Config { + srtp_protection_profiles: vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + ..Default::default() + }, + true, + ) + .await?; + + // Receive client + let client = match c_rx.recv().await.unwrap() { + Ok(client) => client, + Err(err) => return Err(err), + }; + + Ok((client, sever)) +} + +fn psk_callback_client(hint: &[u8]) -> Result> { + trace!( + "Server's hint: {}", + String::from_utf8(hint.to_vec()).unwrap() + ); + Ok(vec![0xAB, 0xC1, 0x23]) +} + +fn psk_callback_server(hint: &[u8]) -> Result> { + trace!( + "Client's hint: {}", + String::from_utf8(hint.to_vec()).unwrap() + ); + Ok(vec![0xAB, 0xC1, 0x23]) +} + +fn psk_callback_hint_fail(_hint: &[u8]) -> Result> { + Err(Error::Other(ERR_PSK_REJECTED.to_owned())) +} + +async fn create_test_client( + ca: Arc, + mut cfg: Config, + generate_certificate: bool, +) -> Result { + if generate_certificate { + let client_cert = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + cfg.certificates = vec![client_cert]; + } + + cfg.insecure_skip_verify = true; + DTLSConn::new(ca, cfg, true, None).await +} + +async fn create_test_server( + cb: Arc, + mut cfg: Config, + generate_certificate: bool, +) -> Result { + if generate_certificate { + let server_cert = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + cfg.certificates = vec![server_cert]; + } + + DTLSConn::new(cb, cfg, false, None).await +} + +#[tokio::test] +async fn test_routine_leak_on_close() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let (ca, cb) = build_pipe().await?; + + let buf_a = vec![0xFA; 100]; + let n_a = ca.write(&buf_a, Some(Duration::from_secs(5))).await?; + assert_eq!(n_a, 100); + + let mut buf_b = vec![0; 1024]; + let n_b = cb.read(&mut buf_b, Some(Duration::from_secs(5))).await?; + assert_eq!(n_a, 100); + assert_eq!(&buf_a[..], &buf_b[0..n_b]); + + cb.close().await?; + ca.close().await?; + + { + drop(ca); + drop(cb); + } + + tokio::time::sleep(Duration::from_millis(1)).await; + + Ok(()) +} + +#[tokio::test] +async fn test_sequence_number_overflow_on_application_data() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let (ca, cb) = build_pipe().await?; + + { + let mut lsn = ca.state.local_sequence_number.lock().await; + lsn[1] = MAX_SEQUENCE_NUMBER; + } + + let buf_a = vec![0xFA; 100]; + let n_a = ca.write(&buf_a, Some(Duration::from_secs(5))).await?; + assert_eq!(n_a, 100); + + let mut buf_b = vec![0; 1024]; + let n_b = cb.read(&mut buf_b, Some(Duration::from_secs(5))).await?; + assert_eq!(n_a, 100); + assert_eq!(&buf_a[..], &buf_b[0..n_b]); + + let result = ca.write(&buf_a, Some(Duration::from_secs(5))).await; + if let Err(err) = result { + assert_eq!( + err.to_string(), + Error::ErrSequenceNumberOverflow.to_string() + ); + } else { + panic!("Expected error but it is OK"); + } + + cb.close().await?; + + if let Err(err) = ca.close().await { + assert_eq!( + err.to_string(), + Error::ErrSequenceNumberOverflow.to_string() + ); + } else { + panic!("Expected error but it is OK"); + } + + { + drop(ca); + drop(cb); + } + + tokio::time::sleep(Duration::from_millis(1)).await; + + Ok(()) +} + +#[tokio::test] +async fn test_sequence_number_overflow_on_handshake() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let (ca, cb) = build_pipe().await?; + + { + let mut lsn = ca.state.local_sequence_number.lock().await; + lsn[0] = MAX_SEQUENCE_NUMBER + 1; + } + + // Try to send handshake packet. + if let Err(err) = ca + .write_packets(vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + random: HandshakeRandom::default(), + cookie: vec![0; 64], + + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Gcm_Sha256], + compression_methods: default_compression_methods(), + extensions: vec![], + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]) + .await + { + assert_eq!( + err.to_string(), + Error::ErrSequenceNumberOverflow.to_string() + ); + } else { + panic!("Expected error but it is OK"); + } + + cb.close().await?; + ca.close().await?; + + { + drop(ca); + drop(cb); + } + + tokio::time::sleep(Duration::from_millis(1)).await; + + Ok(()) +} + +#[tokio::test] +async fn test_handshake_with_alert() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let cases = vec![ + ( + "CipherSuiteNoIntersection", + Config { + // Server + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + ..Default::default() + }, + Config { + // Client + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256], + ..Default::default() + }, + Error::ErrCipherSuiteNoIntersection, + Error::ErrAlertFatalOrClose, //errClient: &errAlert{&alert{alertLevelFatal, alertInsufficientSecurity}}, + ), + ( + "SignatureSchemesNoIntersection", + Config { + // Server + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + signature_schemes: vec![SignatureScheme::EcdsaWithP256AndSha256], + ..Default::default() + }, + Config { + // Client + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + signature_schemes: vec![SignatureScheme::EcdsaWithP521AndSha512], + ..Default::default() + }, + Error::ErrAlertFatalOrClose, //errServer: &errAlert{&alert{alertLevelFatal, alertInsufficientSecurity}}, + Error::ErrNoAvailableSignatureSchemes, //NoAvailableSignatureSchemes, + ), + ]; + + for (name, config_server, config_client, err_server, err_client) in cases { + let (client_err_tx, mut client_err_rx) = mpsc::channel(1); + + let (ca, cb) = pipe(); + tokio::spawn(async move { + let result = create_test_client(Arc::new(ca), config_client, true).await; + let _ = client_err_tx.send(result).await; + }); + + let result_server = create_test_server(Arc::new(cb), config_server, true).await; + if let Err(err) = result_server { + assert_eq!( + err.to_string(), + err_server.to_string(), + "{name} Server error exp({err_server}) failed({err})" + ); + } else { + panic!("{name} expected error but create_test_server return OK"); + } + + let result_client = client_err_rx.recv().await; + if let Some(result_client) = result_client { + if let Err(err) = result_client { + assert_eq!( + err.to_string(), + err_client.to_string(), + "{name} Client error exp({err_client}) failed({err})" + ); + } else { + panic!("{name} expected error but create_test_client return OK"); + } + } + } + + Ok(()) +} + +#[tokio::test] +async fn test_export_keying_material() -> Result<()> { + let export_label = "EXTRACTOR-dtls_srtp"; + let expected_server_key = vec![0x61, 0x09, 0x9d, 0x7d, 0xcb, 0x08, 0x52, 0x2c, 0xe7, 0x7b]; + let expected_client_key = vec![0x87, 0xf0, 0x40, 0x02, 0xf6, 0x1c, 0xf1, 0xfe, 0x8c, 0x77]; + + let (_decrypted_tx, decrypted_rx) = mpsc::channel(1); + let (_handshake_tx, handshake_rx) = mpsc::channel(1); + let (packet_tx, _packet_rx) = mpsc::channel(1); + let (handle_queue_tx, _handle_queue_rx) = mpsc::channel(1); + let (ca, _cb) = pipe(); + + let mut c = DTLSConn { + conn: Arc::new(ca), + state: State { + local_random: HandshakeRandom { + gmt_unix_time: SystemTime::UNIX_EPOCH + .checked_add(Duration::new(500, 0)) + .unwrap(), + ..Default::default() + }, + remote_random: HandshakeRandom { + gmt_unix_time: SystemTime::UNIX_EPOCH + .checked_add(Duration::new(1000, 0)) + .unwrap(), + ..Default::default() + }, + local_sequence_number: Arc::new(Mutex::new(vec![0, 0])), + cipher_suite: Arc::new(Mutex::new(Some(Box::new(CipherSuiteAes128GcmSha256::new( + false, + ))))), + ..Default::default() + }, + cache: HandshakeCache::new(), + decrypted_rx: Mutex::new(decrypted_rx), + handshake_completed_successfully: Arc::new(AtomicBool::new(false)), + connection_closed_by_user: false, + closed: AtomicBool::new(false), + current_flight: Box::new(Flight0 {}) as Box, + flights: None, + cfg: HandshakeConfig::default(), + retransmit: false, + handshake_rx, + + packet_tx: Arc::new(packet_tx), + handle_queue_tx, + handshake_done_tx: None, + + reader_close_tx: Mutex::new(None), + }; + + c.set_local_epoch(0); + let state = c.connection_state().await; + if let Err(err) = state.export_keying_material(export_label, &[], 0).await { + assert!( + err.to_string() + .contains(&Error::ErrHandshakeInProgress.to_string()), + "ExportKeyingMaterial when epoch == 0: expected '{}' actual '{}'", + Error::ErrHandshakeInProgress, + err, + ); + } else { + panic!("expect error but export_keying_material returns OK"); + } + + c.set_local_epoch(1); + let state = c.connection_state().await; + if let Err(err) = state.export_keying_material(export_label, &[0x00], 0).await { + assert!( + err.to_string() + .contains(&Error::ErrContextUnsupported.to_string()), + "ExportKeyingMaterial with context: expected '{}' actual '{}'", + Error::ErrContextUnsupported, + err + ); + } else { + panic!("expect error but export_keying_material returns OK"); + } + + for k in INVALID_KEYING_LABELS.iter() { + let state = c.connection_state().await; + if let Err(err) = state.export_keying_material(k, &[], 0).await { + assert!( + err.to_string() + .contains(&Error::ErrReservedExportKeyingMaterial.to_string()), + "ExportKeyingMaterial reserved label: expected '{}' actual '{}'", + Error::ErrReservedExportKeyingMaterial, + err, + ); + } else { + panic!("expect error but export_keying_material returns OK"); + } + } + + let state = c.connection_state().await; + let keying_material = state.export_keying_material(export_label, &[], 10).await?; + assert_eq!( + &keying_material, &expected_server_key, + "ExportKeyingMaterial client export: expected ({:?}) actual ({:?})", + &expected_server_key, &keying_material, + ); + + c.state.is_client = true; + let state = c.connection_state().await; + let keying_material = state.export_keying_material(export_label, &[], 10).await?; + assert_eq!( + &keying_material, &expected_client_key, + "ExportKeyingMaterial client export: expected ({:?}) actual ({:?})", + &expected_client_key, &keying_material, + ); + + Ok(()) +} + +#[tokio::test] +async fn test_psk() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let tests = vec![ + ( + "Server identity specified", + Some("Test Identity".as_bytes().to_vec()), + ), + ("Server identity nil", None), + ]; + + for (name, server_identity) in tests { + let client_identity = "Client Identity".as_bytes(); + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + + let (ca, cb) = pipe(); + tokio::spawn(async move { + let conf = Config { + psk: Some(Arc::new(psk_callback_client)), + psk_identity_hint: Some(client_identity.to_vec()), + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + ..Default::default() + }; + + let result = create_test_client(Arc::new(ca), conf, false).await; + let _ = client_res_tx.send(result).await; + }); + + let config = Config { + psk: Some(Arc::new(psk_callback_server)), + psk_identity_hint: server_identity, + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + ..Default::default() + }; + + let server = create_test_server(Arc::new(cb), config, false).await?; + + let actual_psk_identity_hint = &server.connection_state().await.identity_hint; + assert_eq!( + actual_psk_identity_hint, client_identity, + "TestPSK: Server ClientPSKIdentity Mismatch '{name}': expected({client_identity:?}) actual({actual_psk_identity_hint:?})", + ); + + if let Some(result) = client_res_rx.recv().await { + if let Ok(client) = result { + client.close().await?; + } else { + panic!("{name}: Expected create_test_client successfully, but got error",); + } + } + + let _ = server.close().await; + } + + Ok(()) +} + +#[tokio::test] +async fn test_psk_hint_fail() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + + let (ca, cb) = pipe(); + tokio::spawn(async move { + let conf = Config { + psk: Some(Arc::new(psk_callback_hint_fail)), + psk_identity_hint: Some(vec![]), + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + ..Default::default() + }; + + let result = create_test_client(Arc::new(ca), conf, false).await; + let _ = client_res_tx.send(result).await; + }); + + let config = Config { + psk: Some(Arc::new(psk_callback_hint_fail)), + psk_identity_hint: Some(vec![]), + cipher_suites: vec![CipherSuiteId::Tls_Psk_With_Aes_128_Ccm_8], + ..Default::default() + }; + + if let Err(server_err) = create_test_server(Arc::new(cb), config, false).await { + assert_eq!( + server_err.to_string(), + Error::ErrAlertFatalOrClose.to_string(), + "TestPSK: Server error exp({}) failed({})", + Error::ErrAlertFatalOrClose, + server_err, + ); + } else { + panic!("Expected server error, but got OK"); + } + + let result = client_res_rx.recv().await; + if let Some(client) = result { + if let Err(client_err) = client { + assert!( + client_err.to_string().contains(ERR_PSK_REJECTED), + "TestPSK: Client error exp({ERR_PSK_REJECTED}) failed({client_err})", + ); + } else { + panic!("Expected client error, but got OK"); + } + } + + Ok(()) +} + +#[tokio::test] +async fn test_client_timeout() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + + let (ca, _cb) = pipe(); + tokio::spawn(async move { + let conf = Config::default(); + let result = tokio::time::timeout( + Duration::from_millis(100), + create_test_client(Arc::new(ca), conf, true), + ) + .await; + let _ = client_res_tx.send(result).await; + }); + + // no server! + let result = client_res_rx.recv().await; + if let Some(client_timeout_result) = result { + assert!(client_timeout_result.is_err(), "Expected Error but got Ok"); + } + + Ok(()) +} + +//use std::io::Write; + +#[tokio::test] +async fn test_srtp_configuration() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + #[allow(clippy::type_complexity)] + let tests: Vec<( + &str, + Vec, + Vec, + SrtpProtectionProfile, + Option, + Option, + )> = vec![ + ( + "No SRTP in use", + vec![], + vec![], + SrtpProtectionProfile::Unsupported, + None, + None, + ), + ( + "SRTP both ends", + vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + None, + None, + ), + ( + "SRTP client only", + vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + vec![], + SrtpProtectionProfile::Unsupported, + Some(Error::ErrAlertFatalOrClose), + Some(Error::ErrServerNoMatchingSrtpProfile), + ), + ( + "SRTP server only", + vec![], + vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + SrtpProtectionProfile::Unsupported, + None, + None, + ), + ( + "Multiple Suites", + vec![ + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32, + ], + vec![ + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32, + ], + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + None, + None, + ), + ( + "Multiple Suites, Client Chooses", + vec![ + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32, + ], + vec![ + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32, + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + ], + SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + None, + None, + ), + ]; + + for (name, client_srtp, server_srtp, expected_profile, want_client_err, want_server_err) in + tests + { + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + tokio::spawn(async move { + let conf = Config { + srtp_protection_profiles: client_srtp, + ..Default::default() + }; + + let result = create_test_client(Arc::new(ca), conf, true).await; + let _ = client_res_tx.send(result).await; + }); + + let config = Config { + srtp_protection_profiles: server_srtp, + ..Default::default() + }; + + let result = create_test_server(Arc::new(cb), config, true).await; + if let Some(expected_err) = want_server_err { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "{name} TestPSK: Server error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else { + match result { + Ok(server) => { + let actual_server_srtp = server.selected_srtpprotection_profile(); + assert_eq!(actual_server_srtp, expected_profile, + "test_srtp_configuration: Server SRTPProtectionProfile Mismatch '{name}': expected({expected_profile:?}) actual({actual_server_srtp:?})"); + } + Err(err) => { + panic!("{name} expected no error: {err}"); + } + }; + } + + let client_result = client_res_rx.recv().await; + if let Some(result) = client_result { + if let Some(expected_err) = want_client_err { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "TestPSK: Client error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else if let Ok(client) = result { + let actual_client_srtp = client.selected_srtpprotection_profile(); + assert_eq!(actual_client_srtp, expected_profile, + "test_srtp_configuration: Client SRTPProtectionProfile Mismatch '{name}': expected({expected_profile:?}) actual({actual_client_srtp:?})"); + } else { + panic!("{name} expected no error"); + } + } else { + panic!("{name} expected client, but got none"); + } + } + + Ok(()) +} + +#[tokio::test] +async fn test_client_certificate() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let server_name = "localhost".to_owned(); + + let srv_cert = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + let mut srv_ca_pool = rustls::RootCertStore::empty(); + srv_ca_pool + .add(&srv_cert.certificate[0]) + .map_err(|_err| Error::Other("add srv_cert error".to_owned()))?; + + let cert = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + let mut ca_pool = rustls::RootCertStore::empty(); + ca_pool + .add(&cert.certificate[0]) + .map_err(|_err| Error::Other("add cert error".to_owned()))?; + + let tests = vec![ + ( + "NoClientCert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + false, + ), + ( + "NoClientCert_cert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequireAnyClientCert, + ..Default::default() + }, + false, + ), + ( + "RequestClientCert_cert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequestClientCert, + ..Default::default() + }, + false, + ), + ( + "RequestClientCert_no_cert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequestClientCert, + ..Default::default() + }, + false, + ), + ( + "RequireAnyClientCert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequireAnyClientCert, + ..Default::default() + }, + false, + ), + ( + "RequireAnyClientCert_error", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequireAnyClientCert, + ..Default::default() + }, + true, + ), + ( + "VerifyClientCertIfGiven_no_cert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::VerifyClientCertIfGiven, + client_cas: ca_pool.clone(), + ..Default::default() + }, + false, + ), + ( + "VerifyClientCertIfGiven_cert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::VerifyClientCertIfGiven, + client_cas: ca_pool.clone(), + ..Default::default() + }, + false, + ), + ( + "VerifyClientCertIfGiven_error", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::VerifyClientCertIfGiven, + ..Default::default() + }, + true, + ), + ( + "RequireAndVerifyClientCert", + Config { + roots_cas: srv_ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![srv_cert.clone()], + client_auth: ClientAuthType::RequireAndVerifyClientCert, + client_cas: ca_pool.clone(), + ..Default::default() + }, + false, + ), + ]; + + for (name, client_cfg, server_cfg, want_err) in tests { + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + let client_cfg_clone = client_cfg.clone(); + tokio::spawn(async move { + let result = DTLSConn::new(Arc::new(ca), client_cfg_clone, true, None).await; + let _ = client_res_tx.send(result).await; + }); + + let result = DTLSConn::new(Arc::new(cb), server_cfg.clone(), false, None).await; + let client_result = client_res_rx.recv().await; + + if want_err { + if result.is_err() { + continue; + } + panic!("{name} Error expected"); + } + + assert!( + result.is_ok(), + "{} Server failed({:?})", + name, + result.err().unwrap() + ); + assert!(client_result.is_some(), "{name}, expected client conn"); + + let res = client_result.unwrap(); + assert!( + res.is_ok(), + "{} Client failed({:?})", + name, + res.err().unwrap() + ); + + let server = result.unwrap(); + let client = res.unwrap(); + + let actual_client_cert = &server.connection_state().await.peer_certificates; + if server_cfg.client_auth == ClientAuthType::RequireAnyClientCert + || server_cfg.client_auth == ClientAuthType::RequireAndVerifyClientCert + { + assert!( + !actual_client_cert.is_empty(), + "{name} Client did not provide a certificate", + ); + //if actual_client_cert.len() != len(tt.clientCfg.Certificates[0].Certificate) || !bytes.Equal(tt.clientCfg.Certificates[0].Certificate[0], actual_client_cert[0]) { + assert_eq!( + actual_client_cert[0], + client_cfg.certificates[0].certificate[0].as_ref(), + "{name} Client certificate was not communicated correctly", + ); + } + + if server_cfg.client_auth == ClientAuthType::NoClientCert { + assert!( + actual_client_cert.is_empty(), + "{name} Client certificate wasn't expected", + ); + } + + let actual_server_cert = &client.connection_state().await.peer_certificates; + assert!( + !actual_server_cert.is_empty(), + "{name} Server did not provide a certificate", + ); + + /*if len(actual_server_cert) != len(tt.serverCfg.Certificates[0].Certificate) + || !bytes.Equal( + tt.serverCfg.Certificates[0].Certificate[0], + actual_server_cert[0], + )*/ + assert_eq!( + actual_server_cert[0].len(), + server_cfg.certificates[0].certificate[0].as_ref().len(), + "{name} Server certificate was not communicated correctly", + ); + assert_eq!( + actual_server_cert[0], + server_cfg.certificates[0].certificate[0].as_ref(), + "{name} Server certificate was not communicated correctly", + ); + } + + Ok(()) +} + +#[tokio::test] +async fn test_extended_master_secret() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let tests = vec![ + ( + "Request_Request_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + None, + None, + ), + ( + "Request_Require_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + None, + None, + ), + ( + "Request_Disable_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + None, + None, + ), + ( + "Require_Request_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + None, + None, + ), + ( + "Require_Require_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + None, + None, + ), + ( + "Require_Disable_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + Some(Error::ErrClientRequiredButNoServerEms), + Some(Error::ErrAlertFatalOrClose), + ), + ( + "Disable_Request_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Request, + ..Default::default() + }, + None, + None, + ), + ( + "Disable_Require_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Require, + ..Default::default() + }, + Some(Error::ErrAlertFatalOrClose), + Some(Error::ErrServerRequiredButNoClientEms), + ), + ( + "Disable_Disable_ExtendedMasterSecret", + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + Config { + extended_master_secret: ExtendedMasterSecretType::Disable, + ..Default::default() + }, + None, + None, + ), + ]; + + for (name, client_cfg, server_cfg, expected_client_err, expected_server_err) in tests { + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + let client_cfg_clone = client_cfg.clone(); + tokio::spawn(async move { + let result = create_test_client(Arc::new(ca), client_cfg_clone, true).await; + let _ = client_res_tx.send(result).await; + }); + + let result = create_test_server(Arc::new(cb), server_cfg.clone(), true).await; + let client_result = client_res_rx.recv().await; + assert!(client_result.is_some(), "{name}, expected client conn"); + let res = client_result.unwrap(); + + if let Some(client_err) = expected_client_err { + if let Err(err) = res { + assert_eq!( + err.to_string(), + client_err.to_string(), + "Client error expected: \"{client_err}\" but got \"{err}\"", + ); + } else { + panic!("{name} expected err, but got ok"); + } + } else { + assert!(res.is_ok(), "{name} expected ok, but got err"); + } + + if let Some(server_err) = expected_server_err { + if let Err(err) = result { + assert_eq!( + err.to_string(), + server_err.to_string(), + "Server error expected: \"{server_err}\" but got \"{err}\"", + ); + } else { + panic!("{name} expected err, but got ok"); + } + } else { + assert!(result.is_ok(), "{name} expected ok, but got err"); + } + } + + Ok(()) +} + +fn fn_not_expected_chain(_cert: &[Vec], chain: &[rustls::Certificate]) -> Result<()> { + if !chain.is_empty() { + return Err(Error::Other(ERR_NOT_EXPECTED_CHAIN.to_owned())); + } + Ok(()) +} + +fn fn_expected_chain(_cert: &[Vec], chain: &[rustls::Certificate]) -> Result<()> { + if chain.is_empty() { + return Err(Error::Other(ERR_EXPECTED_CHAIN.to_owned())); + } + Ok(()) +} + +fn fn_wrong_cert(_cert: &[Vec], _chain: &[rustls::Certificate]) -> Result<()> { + Err(Error::Other(ERR_WRONG_CERT.to_owned())) +} + +#[tokio::test] +async fn test_server_certificate() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let server_name = "localhost".to_owned(); + let cert = Certificate::generate_self_signed(vec![server_name.clone()])?; + let mut ca_pool = rustls::RootCertStore::empty(); + ca_pool + .add(&cert.certificate[0]) + .map_err(|_err| Error::Other("add cert error".to_owned()))?; + + let tests = vec![ + ( + "no_ca", + Config { + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + true, + ), + ( + "good_ca", + Config { + roots_cas: ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + false, + ), + ( + "no_ca_skip_verify", + Config { + insecure_skip_verify: true, + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + false, + ), + ( + "good_ca_skip_verify_custom_verify_peer", + Config { + roots_cas: ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::RequireAnyClientCert, + verify_peer_certificate: Some(Arc::new(fn_not_expected_chain)), + ..Default::default() + }, + false, + ), + ( + "good_ca_verify_custom_verify_peer", + Config { + roots_cas: ca_pool.clone(), + server_name: server_name.clone(), + certificates: vec![cert.clone()], + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::RequireAndVerifyClientCert, + client_cas: ca_pool.clone(), + verify_peer_certificate: Some(Arc::new(fn_expected_chain)), + ..Default::default() + }, + false, + ), + ( + "good_ca_custom_verify_peer", + Config { + roots_cas: ca_pool.clone(), + server_name: server_name.clone(), + verify_peer_certificate: Some(Arc::new(fn_wrong_cert)), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + true, + ), + ( + "server_name", + Config { + roots_cas: ca_pool.clone(), + server_name: server_name.clone(), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + false, + ), + ( + "server_name_error", + Config { + roots_cas: ca_pool.clone(), + server_name: "barfoo".to_owned(), + ..Default::default() + }, + Config { + certificates: vec![cert.clone()], + client_auth: ClientAuthType::NoClientCert, + ..Default::default() + }, + true, + ), + ]; + + for (name, client_cfg, server_cfg, want_err) in tests { + let (res_tx, mut res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + + tokio::spawn(async move { + let result = DTLSConn::new(Arc::new(cb), server_cfg, false, None).await; + let _ = res_tx.send(result).await; + }); + + let cli_result = DTLSConn::new(Arc::new(ca), client_cfg, true, None).await; + + if !want_err && cli_result.is_err() { + panic!("{}: Client failed({})", name, cli_result.err().unwrap()); + } + if want_err && cli_result.is_ok() { + panic!("{name}: Error expected"); + } + + let _ = res_rx.recv().await; + } + Ok(()) +} + +#[tokio::test] +async fn test_cipher_suite_configuration() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let tests = vec![ + ( + "No CipherSuites specified", + vec![], + vec![], + None, + None, + None, + ), + ( + "Invalid CipherSuite", + vec![CipherSuiteId::Unsupported], + vec![CipherSuiteId::Unsupported], + Some(Error::ErrInvalidCipherSuite), + Some(Error::ErrInvalidCipherSuite), + None, + ), + ( + "Valid CipherSuites specified", + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + None, + None, + Some(CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256), + ), + ( + "CipherSuites mismatch", + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha], + Some(Error::ErrAlertFatalOrClose), + Some(Error::ErrCipherSuiteNoIntersection), + None, + ), + ( + "Valid CipherSuites CCM specified", + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm], + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm], + None, + None, + Some(CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm), + ), + ( + "Valid CipherSuites CCM-8 specified", + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8], + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8], + None, + None, + Some(CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Ccm_8), + ), + ( + "Server supports subset of client suites", + vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha, + ], + vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha], + None, + None, + Some(CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha), + ), + ]; + + for ( + name, + client_cipher_suites, + server_cipher_suites, + want_client_error, + want_server_error, + want_selected_cipher_suite, + ) in tests + { + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + tokio::spawn(async move { + let conf = Config { + cipher_suites: client_cipher_suites, + ..Default::default() + }; + + let result = create_test_client(Arc::new(ca), conf, true).await; + let _ = client_res_tx.send(result).await; + }); + + let config = Config { + cipher_suites: server_cipher_suites, + ..Default::default() + }; + + let result = create_test_server(Arc::new(cb), config, true).await; + if let Some(expected_err) = want_server_error { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "{name} test_cipher_suite_configuration: Server error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else { + assert!(result.is_ok(), "{name} expected ok, but got error") + } + + let client_result = client_res_rx.recv().await; + if let Some(result) = client_result { + if let Some(expected_err) = want_client_error { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "{name} test_cipher_suite_configuration: Client error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else { + assert!(result.is_ok(), "{name} expected ok, but got error"); + let client = result.unwrap(); + if let Some(want_cs) = want_selected_cipher_suite { + let cipher_suite = client.state.cipher_suite.lock().await; + assert!(cipher_suite.is_some(), "{name} expected some, but got none"); + if let Some(cs) = &*cipher_suite { + assert_eq!(cs.id(), want_cs, + "test_cipher_suite_configuration: Server Selected Bad Cipher Suite '{}': expected({}) actual({})", + name, want_cs, cs.id()); + } + } + } + } else { + panic!("{name} expected Some, but got None"); + } + } + + Ok(()) +} + +fn psk_callback(_b: &[u8]) -> Result> { + Ok(vec![0x00, 0x01, 0x02]) +} + +#[tokio::test] +async fn test_psk_configuration() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let tests = vec![ + ( + "PSK specified", + false, + false, + true, //Some(psk_callback), + true, //Some(psk_callback), + Some(vec![0x00]), + Some(vec![0x00]), + Some(Error::ErrNoAvailableCipherSuites), + Some(Error::ErrNoAvailableCipherSuites), + ), + ( + "PSK and certificate specified", + true, + true, + true, //Some(psk_callback), + true, //Some(psk_callback), + Some(vec![0x00]), + Some(vec![0x00]), + Some(Error::ErrPskAndCertificate), + Some(Error::ErrPskAndCertificate), + ), + ( + "PSK and no identity specified", + false, + false, + true, //Some(psk_callback), + true, //Some(psk_callback), + None, + None, + Some(Error::ErrPskAndIdentityMustBeSetForClient), + Some(Error::ErrNoAvailableCipherSuites), + ), + ( + "No PSK and identity specified", + false, + false, + false, + false, + Some(vec![0x00]), + Some(vec![0x00]), + Some(Error::ErrIdentityNoPsk), + Some(Error::ErrServerMustHaveCertificate), + ), + ]; + + for ( + name, + client_has_certificate, + server_has_certificate, + client_psk, + server_psk, + client_psk_identity, + server_psk_identity, + want_client_error, + want_server_error, + ) in tests + { + let (client_res_tx, mut client_res_rx) = mpsc::channel(1); + let (ca, cb) = pipe(); + tokio::spawn(async move { + let conf = Config { + psk: if client_psk { + Some(Arc::new(psk_callback)) + } else { + None + }, + psk_identity_hint: client_psk_identity, + ..Default::default() + }; + + let result = create_test_client(Arc::new(ca), conf, client_has_certificate).await; + let _ = client_res_tx.send(result).await; + }); + + let config = Config { + psk: if server_psk { + Some(Arc::new(psk_callback)) + } else { + None + }, + psk_identity_hint: server_psk_identity, + ..Default::default() + }; + + let result = create_test_server(Arc::new(cb), config, server_has_certificate).await; + if let Some(expected_err) = want_server_error { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "{name} test_psk_configuration: Server error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else { + assert!(result.is_ok(), "{name} expected ok, but got error") + } + + let client_result = client_res_rx.recv().await; + if let Some(result) = client_result { + if let Some(expected_err) = want_client_error { + if let Err(err) = result { + assert_eq!( + err.to_string(), + expected_err.to_string(), + "{name} test_psk_configuration: Client error exp({expected_err}) failed({err})", + ); + } else { + panic!("{name} expected error, but got ok"); + } + } else { + assert!(result.is_ok(), "{name} expected ok, but got error"); + } + } else { + panic!("{name} expected Some, but got None"); + } + } + + Ok(()) +} + +#[tokio::test] +async fn test_server_timeout() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let mut cookie = vec![0u8; 20]; + rand::thread_rng().fill(cookie.as_mut_slice()); + + let random_bytes = [0u8; RANDOM_BYTES_LENGTH]; + let gmt_unix_time = SystemTime::UNIX_EPOCH + .checked_add(Duration::new(500, 0)) + .unwrap(); + let random = HandshakeRandom { + gmt_unix_time, + random_bytes, + }; + + let cipher_suites = vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, //&cipherSuiteTLSEcdheEcdsaWithAes128GcmSha256{}, + CipherSuiteId::Tls_Ecdhe_Rsa_With_Aes_128_Gcm_Sha256, //&cipherSuiteTLSEcdheRsaWithAes128GcmSha256{}, + ]; + + let extensions = vec![ + Extension::SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms { + signature_hash_algorithms: vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Rsa, + }, + ], + }), + Extension::SupportedEllipticCurves(ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::X25519, NamedCurve::P256, NamedCurve::P384], + }), + Extension::SupportedPointFormats(ExtensionSupportedPointFormats { + point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED], + }), + ]; + + let record = RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + cookie, + random, + cipher_suites, + compression_methods: default_compression_methods(), + extensions, + }, + ))), + ); + + let mut packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(packet.as_mut()); + record.marshal(&mut writer)?; + } + + use util::Conn; + let (ca, cb) = pipe(); + + // Client reader + let (ca_read_chan_tx, mut ca_read_chan_rx) = mpsc::channel(1000); + + let ca_rx = Arc::new(ca); + let ca_tx = Arc::clone(&ca_rx); + + tokio::spawn(async move { + let mut data = vec![0; 8192]; + loop { + if let Ok(n) = ca_rx.recv(&mut data).await { + let result = ca_read_chan_tx.send(data[..n].to_vec()).await; + if result.is_ok() { + return; + } + } else { + return; + } + } + }); + + // Start sending ClientHello packets until server responds with first packet + tokio::spawn(async move { + loop { + let timer = tokio::time::sleep(Duration::from_millis(10)); + tokio::pin!(timer); + + tokio::select! { + _ = timer.as_mut() => { + let result = ca_tx.send(&packet).await; + if result.is_err() { + return; + } + } + _ = ca_read_chan_rx.recv() => return, + } + } + }); + + let config = Config { + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + flight_interval: Duration::from_millis(100), + ..Default::default() + }; + + let result = tokio::time::timeout( + Duration::from_millis(50), + create_test_server(Arc::new(cb), config, true), + ) + .await; + assert!(result.is_err(), "Expected Error but got Ok"); + + // Wait a little longer to ensure no additional messages have been sent by the server + //tokio::time::sleep(Duration::from_millis(300)).await; + + /*tokio::select! { + case msg := <-caReadChan: + t.Fatalf("Expected no additional messages from server, got: %+v", msg) + default: + }*/ + + Ok(()) +} + +#[tokio::test] +async fn test_protocol_version_validation() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let mut cookie = vec![0; 20]; + rand::thread_rng().fill(cookie.as_mut_slice()); + + let random_bytes = [0u8; RANDOM_BYTES_LENGTH]; + let gmt_unix_time = SystemTime::UNIX_EPOCH + .checked_add(Duration::new(500, 0)) + .unwrap(); + let random = HandshakeRandom { + gmt_unix_time, + random_bytes, + }; + + let local_keypair = NamedCurve::X25519.generate_keypair()?; + + //|"Server"| + { + let server_cases = vec![ + ( + "ClientHelloVersion", + vec![RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: ProtocolVersion { + major: 0xfe, + minor: 0xff, + }, // try to downgrade + cookie: cookie.clone(), + random: random.clone(), + cipher_suites: vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + ], + compression_methods: default_compression_methods(), + extensions: vec![], + }, + ))), + )], + ), + ( + "SecondsClientHelloVersion", + vec![ + RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + cookie: cookie.clone(), + random: random.clone(), + cipher_suites: vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + ], + compression_methods: default_compression_methods(), + extensions: vec![], + }, + ))), + ), + { + let mut handshake = Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: ProtocolVersion { + major: 0xfe, + minor: 0xff, + }, // try to downgrade + cookie: cookie.clone(), + random: random.clone(), + cipher_suites: vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + ], + compression_methods: default_compression_methods(), + extensions: vec![], + }, + )); + handshake.handshake_header.message_sequence = 1; + let mut record_layer = + RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record_layer.record_layer_header.sequence_number = 1; + + record_layer + }, + ], + ), + ]; + + use util::Conn; + for (name, records) in server_cases { + let (ca, cb) = pipe(); + + tokio::spawn(async move { + let config = Config { + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + flight_interval: Duration::from_millis(100), + ..Default::default() + }; + let timeout_result = tokio::time::timeout( + Duration::from_millis(1000), + create_test_server(Arc::new(cb), config, true), + ) + .await; + match timeout_result { + Ok(result) => { + if let Err(err) = result { + assert_eq!( + err.to_string(), + Error::ErrUnsupportedProtocolVersion.to_string(), + "{} Client error exp({}) failed({})", + name, + Error::ErrUnsupportedProtocolVersion, + err, + ); + } else { + panic!("{name} expected error, but got ok"); + } + } + Err(err) => { + panic!("server timeout {err}"); + } + }; + }); + + tokio::time::sleep(Duration::from_millis(50)).await; + + let mut resp = vec![0; 1024]; + let mut n = 0; + for record in records { + let mut packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(packet.as_mut()); + record.marshal(&mut writer)?; + } + + let _ = ca.send(&packet).await; + n = ca.recv(&mut resp).await?; + } + + let mut reader = BufReader::new(&resp[..n]); + let h = RecordLayerHeader::unmarshal(&mut reader)?; + assert_eq!( + h.content_type, + ContentType::Alert, + "Peer must return alert to unsupported protocol version" + ); + } + } + + //"Client" + { + let client_cases = vec![( + "ServerHelloVersion", + vec![ + RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::HelloVerifyRequest( + HandshakeMessageHelloVerifyRequest { + version: PROTOCOL_VERSION1_2, + cookie: cookie.clone(), + }, + ))), + ), + { + let mut handshake = Handshake::new(HandshakeMessage::ServerHello( + HandshakeMessageServerHello { + version: ProtocolVersion { + major: 0xfe, + minor: 0xff, + }, // try to downgrade + random: random.clone(), + cipher_suite: CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + compression_method: default_compression_methods().ids[0], + extensions: vec![], + }, + )); + handshake.handshake_header.message_sequence = 1; + let mut record = + RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record.record_layer_header.sequence_number = 1; + record + }, + { + let mut handshake = Handshake::new(HandshakeMessage::Certificate( + HandshakeMessageCertificate { + certificate: vec![], + }, + )); + handshake.handshake_header.message_sequence = 2; + let mut record = + RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record.record_layer_header.sequence_number = 2; + record + }, + { + let mut handshake = Handshake::new(HandshakeMessage::ServerKeyExchange( + HandshakeMessageServerKeyExchange { + identity_hint: vec![], + elliptic_curve_type: EllipticCurveType::NamedCurve, + named_curve: NamedCurve::X25519, + public_key: local_keypair.public_key.clone(), + algorithm: SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + signature: vec![0; 64], + }, + )); + handshake.handshake_header.message_sequence = 3; + let mut record = + RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record.record_layer_header.sequence_number = 3; + record + }, + { + let mut handshake = Handshake::new(HandshakeMessage::ServerHelloDone( + HandshakeMessageServerHelloDone {}, + )); + handshake.handshake_header.message_sequence = 4; + let mut record = + RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record.record_layer_header.sequence_number = 4; + record + }, + ], + )]; + + use util::Conn; + for (name, records) in client_cases { + let (ca, cb) = pipe(); + + tokio::spawn(async move { + let config = Config { + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + flight_interval: Duration::from_millis(100), + ..Default::default() + }; + let timeout_result = tokio::time::timeout( + Duration::from_millis(1000), + create_test_client(Arc::new(cb), config, true), + ) + .await; + match timeout_result { + Ok(result) => { + if let Err(err) = result { + assert_eq!( + err.to_string(), + Error::ErrUnsupportedProtocolVersion.to_string(), + "{} Server error exp({}) failed({})", + name, + Error::ErrUnsupportedProtocolVersion, + err, + ); + } else { + panic!("{name} expected error, but got ok"); + } + } + Err(err) => { + panic!("server timeout {err}"); + } + }; + }); + + tokio::time::sleep(Duration::from_millis(50)).await; + + let mut resp = vec![0; 1024]; + for record in records { + let _ = ca.recv(&mut resp).await?; + + let mut packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(packet.as_mut()); + record.marshal(&mut writer)?; + } + let _ = ca.send(&packet).await; + } + + let n = ca.recv(&mut resp).await?; + + let mut reader = BufReader::new(&resp[..n]); + let h = RecordLayerHeader::unmarshal(&mut reader)?; + + assert_eq!( + h.content_type, + ContentType::Alert, + "Peer must return alert to unsupported protocol version" + ); + } + } + + Ok(()) +} + +#[tokio::test] +async fn test_multiple_hello_verify_request() -> Result<()> { + /*env_logger::Builder::new() + .format(|buf, record| { + writeln!( + buf, + "{}:{} [{}] {} - {}", + record.file().unwrap_or("unknown"), + record.line().unwrap_or(0), + record.level(), + chrono::Local::now().format("%H:%M:%S.%6f"), + record.args() + ) + }) + .filter(None, LevelFilter::Trace) + .init();*/ + + let mut cookies = vec![ + // first clientHello contains an empty cookie + vec![], + ]; + + let mut packets = vec![]; + for i in 0..2 { + let mut cookie = vec![0; 20]; + rand::thread_rng().fill(cookie.as_mut_slice()); + cookies.push(cookie.clone()); + + let mut handshake = Handshake::new(HandshakeMessage::HelloVerifyRequest( + HandshakeMessageHelloVerifyRequest { + version: PROTOCOL_VERSION1_2, + cookie, + }, + )); + handshake.handshake_header.message_sequence = i as u16; + + let mut record = RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(handshake)); + record.record_layer_header.sequence_number = i as u64; + + let mut packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(packet.as_mut()); + record.marshal(&mut writer)?; + } + + packets.push(packet); + } + + let (ca, cb) = pipe(); + + tokio::spawn(async move { + let conf = Config::default(); + let _ = tokio::time::timeout( + Duration::from_millis(100), + create_test_client(Arc::new(ca), conf, true), + ) + .await; + }); + + for i in 0..cookies.len() { + let cookie = &cookies[i]; + trace!("cookie {}: {:?}", i, cookie); + + // read client hello + let mut resp = vec![0; 1024]; + let n = cb.recv(&mut resp).await?; + let mut reader = BufReader::new(&resp[..n]); + let record = RecordLayer::unmarshal(&mut reader)?; + match record.content { + Content::Handshake(h) => match h.handshake_message { + HandshakeMessage::ClientHello(client_hello) => { + assert_eq!( + &client_hello.cookie, cookie, + "Wrong cookie {}, expected: {:?}, got: {:?}", + i, &client_hello.cookie, cookie + ); + } + _ => panic!("unexpected handshake message"), + }, + _ => panic!("unexpected content"), + }; + + if packets.len() <= i { + break; + } + // write hello verify request + cb.send(&packets[i]).await?; + } + + Ok(()) +} + +async fn send_client_hello( + cookie: Vec, + ca: &Arc, + sequence_number: u64, + send_renegotiation_info: bool, +) -> Result<()> { + let mut extensions = vec![]; + if send_renegotiation_info { + extensions.push(Extension::RenegotiationInfo(ExtensionRenegotiationInfo { + renegotiated_connection: 0, + })); + } + + let mut h = Handshake::new(HandshakeMessage::ClientHello(HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + random: HandshakeRandom::default(), + cookie, + + cipher_suites: vec![CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256], + compression_methods: default_compression_methods(), + extensions, + })); + h.handshake_header.message_sequence = sequence_number as u16; + + let mut record = RecordLayer::new(PROTOCOL_VERSION1_2, 0, Content::Handshake(h)); + record.record_layer_header.sequence_number = sequence_number; + + let mut packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(packet.as_mut()); + record.marshal(&mut writer)?; + } + + ca.send(&packet).await?; + + Ok(()) +} + +// Assert that a DTLS Server always responds with RenegotiationInfo if +// a ClientHello contained that extension or not +#[cfg(not(target_os = "windows"))] // this times out in CI on windows. +#[tokio::test] +async fn test_renegotiation_info() -> Result<()> { + let mut resp = vec![0u8; 1024]; + + let tests = vec![ + ("Include RenegotiationInfo", true), + ("No RenegotiationInfo", false), + ]; + + for (name, send_renegotiation_info) in tests { + let (ca, cb) = pipe(); + + tokio::spawn(async move { + let conf = Config::default(); + let _ = tokio::time::timeout( + Duration::from_millis(100), + create_test_server(Arc::new(cb), conf, true), + ) + .await; + }); + + tokio::time::sleep(Duration::from_millis(5)).await; + + let ca: Arc = Arc::new(ca); + send_client_hello(vec![], &ca, 0, send_renegotiation_info).await?; + + let n = ca.recv(&mut resp).await?; + let mut reader = BufReader::new(&resp[..n]); + let record = RecordLayer::unmarshal(&mut reader)?; + + let hello_verify_request = match record.content { + Content::Handshake(h) => match h.handshake_message { + HandshakeMessage::HelloVerifyRequest(hvr) => hvr, + _ => { + panic!("unexpected handshake message"); + } + }, + _ => { + panic!("unexpected content"); + } + }; + + send_client_hello( + hello_verify_request.cookie.clone(), + &ca, + 1, + send_renegotiation_info, + ) + .await?; + let n = ca.recv(&mut resp).await?; + let messages = unpack_datagram(&resp[..n])?; + + let mut reader = BufReader::new(&messages[0][..]); + let record = RecordLayer::unmarshal(&mut reader)?; + + let server_hello = match record.content { + Content::Handshake(h) => match h.handshake_message { + HandshakeMessage::ServerHello(sh) => sh, + _ => { + panic!("unexpected handshake message"); + } + }, + _ => { + panic!("unexpected content"); + } + }; + + let got_negotiation_info = server_hello + .extensions + .iter() + .any(|v| matches!(v, Extension::RenegotiationInfo(_))); + + assert!( + got_negotiation_info, + "{name}: Received ServerHello without RenegotiationInfo" + ); + + ca.close().await?; + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/conn/mod.rs b/vendor/webrtc-dtls/src/conn/mod.rs new file mode 100644 index 0000000..f9165fe --- /dev/null +++ b/vendor/webrtc-dtls/src/conn/mod.rs @@ -0,0 +1,1206 @@ +#[cfg(test)] +mod conn_test; + +use std::io::{BufReader, BufWriter}; +use std::marker::{Send, Sync}; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicBool, AtomicU16, Ordering}; +use std::sync::Arc; + +use async_trait::async_trait; +use log::*; +use tokio::sync::{mpsc, Mutex}; +use tokio::time::Duration; +use util::replay_detector::*; +use util::Conn; + +use crate::alert::*; +use crate::application_data::*; +use crate::cipher_suite::*; +use crate::config::*; +use crate::content::*; +use crate::curve::named_curve::NamedCurve; +use crate::error::*; +use crate::extension::extension_use_srtp::*; +use crate::flight::flight0::*; +use crate::flight::flight1::*; +use crate::flight::flight5::*; +use crate::flight::flight6::*; +use crate::flight::*; +use crate::fragment_buffer::*; +use crate::handshake::handshake_cache::*; +use crate::handshake::handshake_header::HandshakeHeader; +use crate::handshake::*; +use crate::handshaker::*; +use crate::record_layer::record_layer_header::*; +use crate::record_layer::*; +use crate::signature_hash_algorithm::parse_signature_schemes; +use crate::state::*; + +pub(crate) const INITIAL_TICKER_INTERVAL: Duration = Duration::from_secs(1); +pub(crate) const COOKIE_LENGTH: usize = 20; +pub(crate) const DEFAULT_NAMED_CURVE: NamedCurve = NamedCurve::X25519; +pub(crate) const INBOUND_BUFFER_SIZE: usize = 8192; +// Default replay protection window is specified by RFC 6347 Section 4.1.2.6 +pub(crate) const DEFAULT_REPLAY_PROTECTION_WINDOW: usize = 64; + +pub static INVALID_KEYING_LABELS: &[&str] = &[ + "client finished", + "server finished", + "master secret", + "key expansion", +]; + +type PacketSendRequest = (Vec, Option>>); + +struct ConnReaderContext { + is_client: bool, + replay_protection_window: usize, + replay_detector: Vec>, + decrypted_tx: mpsc::Sender>>, + encrypted_packets: Vec>, + fragment_buffer: FragmentBuffer, + cache: HandshakeCache, + cipher_suite: Arc>>>, + remote_epoch: Arc, + handshake_tx: mpsc::Sender>, + handshake_done_rx: mpsc::Receiver<()>, + packet_tx: Arc>, +} + +// Conn represents a DTLS connection +pub struct DTLSConn { + conn: Arc, + pub(crate) cache: HandshakeCache, // caching of handshake messages for verifyData generation + decrypted_rx: Mutex>>>, // Decrypted Application Data or error, pull by calling `Read` + pub(crate) state: State, // Internal state + + handshake_completed_successfully: Arc, + connection_closed_by_user: bool, + // closeLock sync.Mutex + closed: AtomicBool, // *closer.Closer + //handshakeLoopsFinished sync.WaitGroup + + //readDeadline :deadline.Deadline, + //writeDeadline :deadline.Deadline, + + //log logging.LeveledLogger + /* + reading chan struct{} + handshakeRecv chan chan struct{} + cancelHandshaker func() + cancelHandshakeReader func() + */ + pub(crate) current_flight: Box, + pub(crate) flights: Option>, + pub(crate) cfg: HandshakeConfig, + pub(crate) retransmit: bool, + pub(crate) handshake_rx: mpsc::Receiver>, + + pub(crate) packet_tx: Arc>, + pub(crate) handle_queue_tx: mpsc::Sender>, + pub(crate) handshake_done_tx: Option>, + + reader_close_tx: Mutex>>, +} + +type UtilResult = std::result::Result; + +#[async_trait] +impl Conn for DTLSConn { + async fn connect(&self, _addr: SocketAddr) -> UtilResult<()> { + Err(util::Error::Other("Not applicable".to_owned())) + } + async fn recv(&self, buf: &mut [u8]) -> UtilResult { + self.read(buf, None).await.map_err(util::Error::from_std) + } + async fn recv_from(&self, buf: &mut [u8]) -> UtilResult<(usize, SocketAddr)> { + if let Some(raddr) = self.conn.remote_addr() { + let n = self.read(buf, None).await.map_err(util::Error::from_std)?; + Ok((n, raddr)) + } else { + Err(util::Error::Other( + "No remote address is provided by underlying Conn".to_owned(), + )) + } + } + async fn send(&self, buf: &[u8]) -> UtilResult { + self.write(buf, None).await.map_err(util::Error::from_std) + } + async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> UtilResult { + Err(util::Error::Other("Not applicable".to_owned())) + } + fn local_addr(&self) -> UtilResult { + self.conn.local_addr() + } + fn remote_addr(&self) -> Option { + self.conn.remote_addr() + } + async fn close(&self) -> UtilResult<()> { + self.close().await.map_err(util::Error::from_std) + } +} + +impl DTLSConn { + pub async fn new( + conn: Arc, + mut config: Config, + is_client: bool, + initial_state: Option, + ) -> Result { + validate_config(is_client, &config)?; + + let local_cipher_suites: Vec = parse_cipher_suites( + &config.cipher_suites, + config.psk.is_none(), + config.psk.is_some(), + )? + .iter() + .map(|cs| cs.id()) + .collect(); + + let sigs: Vec = config.signature_schemes.iter().map(|x| *x as u16).collect(); + let local_signature_schemes = parse_signature_schemes(&sigs, config.insecure_hashes)?; + + let retransmit_interval = if config.flight_interval != Duration::from_secs(0) { + config.flight_interval + } else { + INITIAL_TICKER_INTERVAL + }; + + /* + loggerFactory := config.LoggerFactory + if loggerFactory == nil { + loggerFactory = logging.NewDefaultLoggerFactory() + } + + logger := loggerFactory.NewLogger("dtls") + */ + let maximum_transmission_unit = if config.mtu == 0 { + DEFAULT_MTU + } else { + config.mtu + }; + + let replay_protection_window = if config.replay_protection_window == 0 { + DEFAULT_REPLAY_PROTECTION_WINDOW + } else { + config.replay_protection_window + }; + + let mut server_name = config.server_name.clone(); + + // Use host from conn address when server_name is not provided + if is_client && server_name.is_empty() { + if let Some(remote_addr) = conn.remote_addr() { + server_name = remote_addr.ip().to_string(); + } else { + log::warn!("conn.remote_addr is empty, please set explicitly server_name in Config! Use default \"localhost\" as server_name now"); + server_name = "localhost".to_owned(); + } + } + + let cfg = HandshakeConfig { + local_psk_callback: config.psk.take(), + local_psk_identity_hint: config.psk_identity_hint.take(), + local_cipher_suites, + local_signature_schemes, + extended_master_secret: config.extended_master_secret, + local_srtp_protection_profiles: config.srtp_protection_profiles.clone(), + server_name, + client_auth: config.client_auth, + local_certificates: config.certificates.clone(), + insecure_skip_verify: config.insecure_skip_verify, + insecure_verification: config.insecure_verification, + verify_peer_certificate: config.verify_peer_certificate.take(), + client_cert_verifier: if config.client_auth as u8 + >= ClientAuthType::VerifyClientCertIfGiven as u8 + { + Some(Arc::new(rustls::server::AllowAnyAuthenticatedClient::new( + config.client_cas, + ))) + } else { + None + }, + server_cert_verifier: Arc::new(rustls::client::WebPkiVerifier::new( + config.roots_cas, + None, + )), + retransmit_interval, + //log: logger, + initial_epoch: 0, + ..Default::default() + }; + + let (state, flight, initial_fsm_state) = if let Some(state) = initial_state { + let flight = if is_client { + Box::new(Flight5 {}) as Box + } else { + Box::new(Flight6 {}) as Box + }; + + (state, flight, HandshakeState::Finished) + } else { + let flight = if is_client { + Box::new(Flight1 {}) as Box + } else { + Box::new(Flight0 {}) as Box + }; + + ( + State { + is_client, + ..Default::default() + }, + flight, + HandshakeState::Preparing, + ) + }; + + let (decrypted_tx, decrypted_rx) = mpsc::channel(1); + let (handshake_tx, handshake_rx) = mpsc::channel(1); + let (handshake_done_tx, handshake_done_rx) = mpsc::channel(1); + let (packet_tx, mut packet_rx) = mpsc::channel(1); + let (handle_queue_tx, mut handle_queue_rx) = mpsc::channel(1); + let (reader_close_tx, mut reader_close_rx) = mpsc::channel(1); + + let packet_tx = Arc::new(packet_tx); + let packet_tx2 = Arc::clone(&packet_tx); + let next_conn_rx = Arc::clone(&conn); + let next_conn_tx = Arc::clone(&conn); + let cache = HandshakeCache::new(); + let mut cache1 = cache.clone(); + let cache2 = cache.clone(); + let handshake_completed_successfully = Arc::new(AtomicBool::new(false)); + let handshake_completed_successfully2 = Arc::clone(&handshake_completed_successfully); + + let mut c = DTLSConn { + conn: Arc::clone(&conn), + cache, + decrypted_rx: Mutex::new(decrypted_rx), + state, + handshake_completed_successfully, + connection_closed_by_user: false, + closed: AtomicBool::new(false), + + current_flight: flight, + flights: None, + cfg, + retransmit: false, + handshake_rx, + packet_tx, + handle_queue_tx, + handshake_done_tx: Some(handshake_done_tx), + reader_close_tx: Mutex::new(Some(reader_close_tx)), + }; + + let cipher_suite1 = Arc::clone(&c.state.cipher_suite); + let sequence_number = Arc::clone(&c.state.local_sequence_number); + + tokio::spawn(async move { + loop { + let rx = packet_rx.recv().await; + if let Some(r) = rx { + let (pkt, result_tx) = r; + + let result = DTLSConn::handle_outgoing_packets( + &next_conn_tx, + pkt, + &mut cache1, + is_client, + &sequence_number, + &cipher_suite1, + maximum_transmission_unit, + ) + .await; + + if let Some(tx) = result_tx { + let _ = tx.send(result).await; + } + } else { + trace!("{}: handle_outgoing_packets exit", srv_cli_str(is_client)); + break; + } + } + }); + + let local_epoch = Arc::clone(&c.state.local_epoch); + let remote_epoch = Arc::clone(&c.state.remote_epoch); + let cipher_suite2 = Arc::clone(&c.state.cipher_suite); + + tokio::spawn(async move { + let mut buf = vec![0u8; INBOUND_BUFFER_SIZE]; + let mut ctx = ConnReaderContext { + is_client, + replay_protection_window, + replay_detector: vec![], + decrypted_tx, + encrypted_packets: vec![], + fragment_buffer: FragmentBuffer::new(), + cache: cache2, + cipher_suite: cipher_suite2, + remote_epoch, + handshake_tx, + handshake_done_rx, + packet_tx: packet_tx2, + }; + + //trace!("before enter read_and_buffer: {}] ", srv_cli_str(is_client)); + loop { + tokio::select! { + _ = reader_close_rx.recv() => { + trace!( + "{}: read_and_buffer exit", + srv_cli_str(ctx.is_client), + ); + break; + } + result = DTLSConn::read_and_buffer( + &mut ctx, + &next_conn_rx, + &mut handle_queue_rx, + &mut buf, + &local_epoch, + &handshake_completed_successfully2, + ) => { + if let Err(err) = result { + trace!( + "{}: read_and_buffer return err: {}", + srv_cli_str(is_client), + err + ); + if Error::ErrAlertFatalOrClose == err { + trace!( + "{}: read_and_buffer exit with {}", + srv_cli_str(ctx.is_client), + err + ); + + break; + } + } + } + } + } + }); + + // Do handshake + c.handshake(initial_fsm_state).await?; + + trace!("Handshake Completed"); + + Ok(c) + } + + // Read reads data from the connection. + pub async fn read(&self, p: &mut [u8], duration: Option) -> Result { + if !self.is_handshake_completed_successfully() { + return Err(Error::ErrHandshakeInProgress); + } + + let rx = { + let mut decrypted_rx = self.decrypted_rx.lock().await; + if let Some(d) = duration { + let timer = tokio::time::sleep(d); + tokio::pin!(timer); + + tokio::select! { + r = decrypted_rx.recv() => r, + _ = timer.as_mut() => return Err(Error::ErrDeadlineExceeded), + } + } else { + decrypted_rx.recv().await + } + }; + + if let Some(out) = rx { + match out { + Ok(val) => { + let n = val.len(); + if p.len() < n { + return Err(Error::ErrBufferTooSmall); + } + p[..n].copy_from_slice(&val); + Ok(n) + } + Err(err) => Err(err), + } + } else { + Err(Error::ErrAlertFatalOrClose) + } + } + + // Write writes len(p) bytes from p to the DTLS connection + pub async fn write(&self, p: &[u8], duration: Option) -> Result { + if self.is_connection_closed() { + return Err(Error::ErrConnClosed); + } + + if !self.is_handshake_completed_successfully() { + return Err(Error::ErrHandshakeInProgress); + } + + let pkts = vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + self.get_local_epoch(), + Content::ApplicationData(ApplicationData { data: p.to_vec() }), + ), + should_encrypt: true, + reset_local_sequence_number: false, + }]; + + if let Some(d) = duration { + let timer = tokio::time::sleep(d); + tokio::pin!(timer); + + tokio::select! { + result = self.write_packets(pkts) => { + result?; + } + _ = timer.as_mut() => return Err(Error::ErrDeadlineExceeded), + } + } else { + self.write_packets(pkts).await?; + } + + Ok(p.len()) + } + + // Close closes the connection. + pub async fn close(&self) -> Result<()> { + if !self.closed.load(Ordering::SeqCst) { + self.closed.store(true, Ordering::SeqCst); + + // Discard error from notify() to return non-error on the first user call of Close() + // even if the underlying connection is already closed. + self.notify(AlertLevel::Warning, AlertDescription::CloseNotify) + .await?; + + { + let mut reader_close_tx = self.reader_close_tx.lock().await; + reader_close_tx.take(); + } + self.conn.close().await?; + } + + Ok(()) + } + + /// connection_state returns basic DTLS details about the connection. + /// Note that this replaced the `Export` function of v1. + pub async fn connection_state(&self) -> State { + self.state.clone().await + } + + /// selected_srtpprotection_profile returns the selected SRTPProtectionProfile + pub fn selected_srtpprotection_profile(&self) -> SrtpProtectionProfile { + self.state.srtp_protection_profile + } + + pub(crate) async fn notify(&self, level: AlertLevel, desc: AlertDescription) -> Result<()> { + self.write_packets(vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + self.get_local_epoch(), + Content::Alert(Alert { + alert_level: level, + alert_description: desc, + }), + ), + should_encrypt: self.is_handshake_completed_successfully(), + reset_local_sequence_number: false, + }]) + .await + } + + pub(crate) async fn write_packets(&self, pkts: Vec) -> Result<()> { + let (tx, mut rx) = mpsc::channel(1); + + self.packet_tx.send((pkts, Some(tx))).await?; + + if let Some(result) = rx.recv().await { + result + } else { + Ok(()) + } + } + + async fn handle_outgoing_packets( + next_conn: &Arc, + mut pkts: Vec, + cache: &mut HandshakeCache, + is_client: bool, + local_sequence_number: &Arc>>, + cipher_suite: &Arc>>>, + maximum_transmission_unit: usize, + ) -> Result<()> { + let mut raw_packets = vec![]; + for p in &mut pkts { + if let Content::Handshake(h) = &p.record.content { + let mut handshake_raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(handshake_raw.as_mut()); + p.record.marshal(&mut writer)?; + } + trace!( + "Send [handshake:{}] -> {} (epoch: {}, seq: {})", + srv_cli_str(is_client), + h.handshake_header.handshake_type.to_string(), + p.record.record_layer_header.epoch, + h.handshake_header.message_sequence + ); + cache + .push( + handshake_raw[RECORD_LAYER_HEADER_SIZE..].to_vec(), + p.record.record_layer_header.epoch, + h.handshake_header.message_sequence, + h.handshake_header.handshake_type, + is_client, + ) + .await; + + let raw_handshake_packets = DTLSConn::process_handshake_packet( + local_sequence_number, + cipher_suite, + maximum_transmission_unit, + p, + h, + ) + .await?; + raw_packets.extend_from_slice(&raw_handshake_packets); + } else { + /*if let Content::Alert(a) = &p.record.content { + if a.alert_description == AlertDescription::CloseNotify { + closed = true; + } + }*/ + + let raw_packet = + DTLSConn::process_packet(local_sequence_number, cipher_suite, p).await?; + raw_packets.push(raw_packet); + } + } + + if !raw_packets.is_empty() { + let compacted_raw_packets = + compact_raw_packets(&raw_packets, maximum_transmission_unit); + + for compacted_raw_packets in &compacted_raw_packets { + next_conn.send(compacted_raw_packets).await?; + } + } + + Ok(()) + } + + async fn process_packet( + local_sequence_number: &Arc>>, + cipher_suite: &Arc>>>, + p: &mut Packet, + ) -> Result> { + let epoch = p.record.record_layer_header.epoch as usize; + let seq = { + let mut lsn = local_sequence_number.lock().await; + while lsn.len() <= epoch { + lsn.push(0); + } + + lsn[epoch] += 1; + lsn[epoch] - 1 + }; + //trace!("{}: seq = {}", srv_cli_str(is_client), seq); + + if seq > MAX_SEQUENCE_NUMBER { + // RFC 6347 Section 4.1.0 + // The implementation must either abandon an association or rehandshake + // prior to allowing the sequence number to wrap. + return Err(Error::ErrSequenceNumberOverflow); + } + p.record.record_layer_header.sequence_number = seq; + + let mut raw_packet = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw_packet.as_mut()); + p.record.marshal(&mut writer)?; + } + + if p.should_encrypt { + let cipher_suite = cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + raw_packet = cipher_suite.encrypt(&p.record.record_layer_header, &raw_packet)?; + } + } + + Ok(raw_packet) + } + + async fn process_handshake_packet( + local_sequence_number: &Arc>>, + cipher_suite: &Arc>>>, + maximum_transmission_unit: usize, + p: &Packet, + h: &Handshake, + ) -> Result>> { + let mut raw_packets = vec![]; + + let handshake_fragments = DTLSConn::fragment_handshake(maximum_transmission_unit, h)?; + + let epoch = p.record.record_layer_header.epoch as usize; + + let mut lsn = local_sequence_number.lock().await; + while lsn.len() <= epoch { + lsn.push(0); + } + + for handshake_fragment in &handshake_fragments { + let seq = { + lsn[epoch] += 1; + lsn[epoch] - 1 + }; + //trace!("seq = {}", seq); + if seq > MAX_SEQUENCE_NUMBER { + return Err(Error::ErrSequenceNumberOverflow); + } + + let record_layer_header = RecordLayerHeader { + protocol_version: p.record.record_layer_header.protocol_version, + content_type: p.record.record_layer_header.content_type, + content_len: handshake_fragment.len() as u16, + epoch: p.record.record_layer_header.epoch, + sequence_number: seq, + }; + + let mut record_layer_header_bytes = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(record_layer_header_bytes.as_mut()); + record_layer_header.marshal(&mut writer)?; + } + + //p.record.record_layer_header = record_layer_header; + + let mut raw_packet = vec![]; + raw_packet.extend_from_slice(&record_layer_header_bytes); + raw_packet.extend_from_slice(handshake_fragment); + if p.should_encrypt { + let cipher_suite = cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + raw_packet = cipher_suite.encrypt(&record_layer_header, &raw_packet)?; + } + } + + raw_packets.push(raw_packet); + } + + Ok(raw_packets) + } + + fn fragment_handshake(maximum_transmission_unit: usize, h: &Handshake) -> Result>> { + let mut content = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(content.as_mut()); + h.handshake_message.marshal(&mut writer)?; + } + + let mut fragmented_handshakes = vec![]; + + let mut content_fragments = split_bytes(&content, maximum_transmission_unit); + if content_fragments.is_empty() { + content_fragments = vec![vec![]]; + } + + let mut offset = 0; + for content_fragment in &content_fragments { + let content_fragment_len = content_fragment.len(); + + let handshake_header_fragment = HandshakeHeader { + handshake_type: h.handshake_header.handshake_type, + length: h.handshake_header.length, + message_sequence: h.handshake_header.message_sequence, + fragment_offset: offset as u32, + fragment_length: content_fragment_len as u32, + }; + + offset += content_fragment_len; + + let mut handshake_header_fragment_raw = vec![]; + { + let mut writer = + BufWriter::<&mut Vec>::new(handshake_header_fragment_raw.as_mut()); + handshake_header_fragment.marshal(&mut writer)?; + } + + let mut fragmented_handshake = vec![]; + fragmented_handshake.extend_from_slice(&handshake_header_fragment_raw); + fragmented_handshake.extend_from_slice(content_fragment); + + fragmented_handshakes.push(fragmented_handshake); + } + + Ok(fragmented_handshakes) + } + + pub(crate) fn set_handshake_completed_successfully(&mut self) { + self.handshake_completed_successfully + .store(true, Ordering::SeqCst); + } + + pub(crate) fn is_handshake_completed_successfully(&self) -> bool { + self.handshake_completed_successfully.load(Ordering::SeqCst) + } + + async fn read_and_buffer( + ctx: &mut ConnReaderContext, + next_conn: &Arc, + handle_queue_rx: &mut mpsc::Receiver>, + buf: &mut [u8], + local_epoch: &Arc, + handshake_completed_successfully: &Arc, + ) -> Result<()> { + let network_result = next_conn.recv(buf).await; + let n = network_result?; + let pkts = unpack_datagram(&buf[..n])?; + let mut has_handshake = false; + for pkt in pkts { + let (hs, alert, mut err) = DTLSConn::handle_incoming_packet(ctx, pkt, true).await; + if let Some(alert) = alert { + let alert_err = ctx + .packet_tx + .send(( + vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + local_epoch.load(Ordering::SeqCst), + Content::Alert(Alert { + alert_level: alert.alert_level, + alert_description: alert.alert_description, + }), + ), + should_encrypt: handshake_completed_successfully.load(Ordering::SeqCst), + reset_local_sequence_number: false, + }], + None, + )) + .await; + + if let Err(alert_err) = alert_err { + if err.is_none() { + err = Some(Error::Other(alert_err.to_string())); + } + } + + if alert.alert_level == AlertLevel::Fatal + || alert.alert_description == AlertDescription::CloseNotify + { + return Err(Error::ErrAlertFatalOrClose); + } + } + + if let Some(err) = err { + return Err(err); + } + + if hs { + has_handshake = true + } + } + + if has_handshake { + let (done_tx, mut done_rx) = mpsc::channel(1); + + tokio::select! { + _ = ctx.handshake_tx.send(done_tx) => { + let mut wait_done_rx = true; + while wait_done_rx{ + tokio::select!{ + _ = done_rx.recv() => { + // If the other party may retransmit the flight, + // we should respond even if it not a new message. + wait_done_rx = false; + } + _ = ctx.handshake_done_rx.recv() => { + // The handshake FSM may have finished after the + // outer select chose its notification send arm. + // Its retained receiver no longer consumes done_tx. + wait_done_rx = false; + } + done = handle_queue_rx.recv() => { + //trace!("recv handle_queue: {} ", srv_cli_str(ctx.is_client)); + + let pkts = ctx.encrypted_packets.drain(..).collect(); + DTLSConn::handle_queued_packets(ctx, local_epoch, handshake_completed_successfully, pkts).await?; + + drop(done); + } + } + } + } + _ = ctx.handshake_done_rx.recv() => { + } + } + } + + Ok(()) + } + + async fn handle_queued_packets( + ctx: &mut ConnReaderContext, + local_epoch: &Arc, + handshake_completed_successfully: &Arc, + pkts: Vec>, + ) -> Result<()> { + for p in pkts { + let (_, alert, mut err) = DTLSConn::handle_incoming_packet(ctx, p, false).await; // don't re-enqueue + if let Some(alert) = alert { + let alert_err = ctx + .packet_tx + .send(( + vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + local_epoch.load(Ordering::SeqCst), + Content::Alert(Alert { + alert_level: alert.alert_level, + alert_description: alert.alert_description, + }), + ), + should_encrypt: handshake_completed_successfully.load(Ordering::SeqCst), + reset_local_sequence_number: false, + }], + None, + )) + .await; + + if let Err(alert_err) = alert_err { + if err.is_none() { + err = Some(Error::Other(alert_err.to_string())); + } + } + if alert.alert_level == AlertLevel::Fatal + || alert.alert_description == AlertDescription::CloseNotify + { + return Err(Error::ErrAlertFatalOrClose); + } + } + + if let Some(err) = err { + return Err(err); + } + } + + Ok(()) + } + + async fn handle_incoming_packet( + ctx: &mut ConnReaderContext, + mut pkt: Vec, + enqueue: bool, + ) -> (bool, Option, Option) { + let mut reader = BufReader::new(pkt.as_slice()); + let h = match RecordLayerHeader::unmarshal(&mut reader) { + Ok(h) => h, + Err(err) => { + // Decode error must be silently discarded + // [RFC6347 Section-4.1.2.7] + debug!( + "{}: discarded broken packet: {}", + srv_cli_str(ctx.is_client), + err + ); + return (false, None, None); + } + }; + + // Validate epoch + let epoch = ctx.remote_epoch.load(Ordering::SeqCst); + if h.epoch > epoch { + if h.epoch > epoch + 1 { + debug!( + "{}: discarded future packet (epoch: {}, seq: {})", + srv_cli_str(ctx.is_client), + h.epoch, + h.sequence_number, + ); + return (false, None, None); + } + if enqueue { + debug!( + "{}: received packet of next epoch, queuing packet", + srv_cli_str(ctx.is_client) + ); + ctx.encrypted_packets.push(pkt); + } + return (false, None, None); + } + + // Anti-replay protection + while ctx.replay_detector.len() <= h.epoch as usize { + ctx.replay_detector + .push(Box::new(SlidingWindowDetector::new( + ctx.replay_protection_window, + MAX_SEQUENCE_NUMBER, + ))); + } + + let ok = ctx.replay_detector[h.epoch as usize].check(h.sequence_number); + if !ok { + debug!( + "{}: discarded duplicated packet (epoch: {}, seq: {})", + srv_cli_str(ctx.is_client), + h.epoch, + h.sequence_number, + ); + return (false, None, None); + } + + // Decrypt + if h.epoch != 0 { + let invalid_cipher_suite = { + let cipher_suite = ctx.cipher_suite.lock().await; + if cipher_suite.is_none() { + true + } else if let Some(cipher_suite) = &*cipher_suite { + !cipher_suite.is_initialized() + } else { + false + } + }; + if invalid_cipher_suite { + if enqueue { + debug!( + "{}: handshake not finished, queuing packet", + srv_cli_str(ctx.is_client) + ); + ctx.encrypted_packets.push(pkt); + } + return (false, None, None); + } + + let cipher_suite = ctx.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + pkt = match cipher_suite.decrypt(&pkt) { + Ok(pkt) => pkt, + Err(err) => { + debug!("{}: decrypt failed: {}", srv_cli_str(ctx.is_client), err); + + // If we get an error for PSK we need to return an error. + if cipher_suite.is_psk() { + return ( + false, + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnknownPskIdentity, + }), + None, + ); + } else { + return (false, None, None); + } + } + }; + } + } + + let is_handshake = match ctx.fragment_buffer.push(&pkt) { + Ok(is_handshake) => is_handshake, + Err(err) => { + // Decode error must be silently discarded + // [RFC6347 Section-4.1.2.7] + debug!("{}: defragment failed: {}", srv_cli_str(ctx.is_client), err); + return (false, None, None); + } + }; + if is_handshake { + ctx.replay_detector[h.epoch as usize].accept(); + while let Ok((out, epoch)) = ctx.fragment_buffer.pop() { + //log::debug!("Extension Debug: out.len()={}", out.len()); + let mut reader = BufReader::new(out.as_slice()); + let raw_handshake = match Handshake::unmarshal(&mut reader) { + Ok(rh) => { + trace!( + "Recv [handshake:{}] -> {} (epoch: {}, seq: {})", + srv_cli_str(ctx.is_client), + rh.handshake_header.handshake_type.to_string(), + h.epoch, + rh.handshake_header.message_sequence + ); + rh + } + Err(err) => { + debug!( + "{}: handshake parse failed: {}", + srv_cli_str(ctx.is_client), + err + ); + continue; + } + }; + + ctx.cache + .push( + out, + epoch, + raw_handshake.handshake_header.message_sequence, + raw_handshake.handshake_header.handshake_type, + !ctx.is_client, + ) + .await; + } + + return (true, None, None); + } + + let mut reader = BufReader::new(pkt.as_slice()); + let r = match RecordLayer::unmarshal(&mut reader) { + Ok(r) => r, + Err(err) => { + return ( + false, + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::DecodeError, + }), + Some(err), + ); + } + }; + + match r.content { + Content::Alert(mut a) => { + trace!("{}: <- {}", srv_cli_str(ctx.is_client), a.to_string()); + if a.alert_description == AlertDescription::CloseNotify { + // Respond with a close_notify [RFC5246 Section 7.2.1] + a = Alert { + alert_level: AlertLevel::Warning, + alert_description: AlertDescription::CloseNotify, + }; + } + ctx.replay_detector[h.epoch as usize].accept(); + return ( + false, + Some(a), + Some(Error::Other(format!("Error of Alert {a}"))), + ); + } + Content::ChangeCipherSpec(_) => { + let invalid_cipher_suite = { + let cipher_suite = ctx.cipher_suite.lock().await; + if cipher_suite.is_none() { + true + } else if let Some(cipher_suite) = &*cipher_suite { + !cipher_suite.is_initialized() + } else { + false + } + }; + + if invalid_cipher_suite { + if enqueue { + debug!( + "{}: CipherSuite not initialized, queuing packet", + srv_cli_str(ctx.is_client) + ); + ctx.encrypted_packets.push(pkt); + } + return (false, None, None); + } + + let new_remote_epoch = h.epoch + 1; + trace!( + "{}: <- ChangeCipherSpec (epoch: {})", + srv_cli_str(ctx.is_client), + new_remote_epoch + ); + + if epoch + 1 == new_remote_epoch { + ctx.remote_epoch.store(new_remote_epoch, Ordering::SeqCst); + ctx.replay_detector[h.epoch as usize].accept(); + } + } + Content::ApplicationData(a) => { + if h.epoch == 0 { + return ( + false, + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnexpectedMessage, + }), + Some(Error::ErrApplicationDataEpochZero), + ); + } + + ctx.replay_detector[h.epoch as usize].accept(); + + let application_len = a.data.len(); + let delivery_result = ctx.decrypted_tx.send(Ok(a.data)).await; + //TODO + /*select { + case self.decrypted < - content.data: + case < -c.closed.Done(): + }*/ + } + _ => { + return ( + false, + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnexpectedMessage, + }), + Some(Error::ErrUnhandledContextType), + ); + } + }; + + (false, None, None) + } + + fn is_connection_closed(&self) -> bool { + self.closed.load(Ordering::SeqCst) + } + + pub(crate) fn set_local_epoch(&mut self, epoch: u16) { + self.state.local_epoch.store(epoch, Ordering::SeqCst); + } + + pub(crate) fn get_local_epoch(&self) -> u16 { + self.state.local_epoch.load(Ordering::SeqCst) + } +} + +fn compact_raw_packets(raw_packets: &[Vec], maximum_transmission_unit: usize) -> Vec> { + let mut combined_raw_packets = vec![]; + let mut current_combined_raw_packet = vec![]; + + for raw_packet in raw_packets { + if !current_combined_raw_packet.is_empty() + && current_combined_raw_packet.len() + raw_packet.len() >= maximum_transmission_unit + { + combined_raw_packets.push(current_combined_raw_packet); + current_combined_raw_packet = vec![]; + } + current_combined_raw_packet.extend_from_slice(raw_packet); + } + + combined_raw_packets.push(current_combined_raw_packet); + + combined_raw_packets +} + +fn split_bytes(bytes: &[u8], split_len: usize) -> Vec> { + let mut splits = vec![]; + let num_bytes = bytes.len(); + for i in (0..num_bytes).step_by(split_len) { + let mut j = i + split_len; + if j > num_bytes { + j = num_bytes; + } + + splits.push(bytes[i..j].to_vec()); + } + + splits +} + +#[cfg(test)] +#[path = "post_handshake_regression.rs"] +mod post_handshake_regression; diff --git a/vendor/webrtc-dtls/src/conn/post_handshake_regression.rs b/vendor/webrtc-dtls/src/conn/post_handshake_regression.rs new file mode 100644 index 0000000..159e0d4 --- /dev/null +++ b/vendor/webrtc-dtls/src/conn/post_handshake_regression.rs @@ -0,0 +1,78 @@ +//! Reader regression using the actual DTLS record parser and read_and_buffer. +//! No live capture, peer identity, private keys or cryptographic fixtures. +use super::*; +use crate::handshake::handshake_message_server_hello_done::HandshakeMessageServerHelloDone; +use crate::handshake::{Handshake, HandshakeMessage}; +use util::conn::conn_pipe::pipe; + +#[tokio::test] +async fn post_handshake_completion_unblocks_inactive_fsm_wait() { + let (reader_pipe, writer_pipe) = pipe(); + let next_conn: Arc = Arc::new(reader_pipe); + let (decrypted_tx, _decrypted_rx) = mpsc::channel(1); + // Keep this receiver alive but deliberately do not consume it: the FSM + // returned Finished, while DTLSConn still owns its handshake_rx receiver. + let (handshake_tx, handshake_rx) = mpsc::channel(1); + let (completion_tx, completion_rx) = mpsc::channel(1); + let (packet_tx, _packet_rx) = mpsc::channel(1); + let (_handle_queue_tx, mut handle_queue_rx) = mpsc::channel(1); + let mut ctx = ConnReaderContext { + is_client: false, + replay_protection_window: DEFAULT_REPLAY_PROTECTION_WINDOW, + replay_detector: vec![], + decrypted_tx, + encrypted_packets: vec![], + fragment_buffer: FragmentBuffer::new(), + cache: HandshakeCache::new(), + cipher_suite: Arc::new(Mutex::new(None)), + remote_epoch: Arc::new(AtomicU16::new(0)), + handshake_tx, + handshake_done_rx: completion_rx, + packet_tx: Arc::new(packet_tx), + }; + let local_epoch = Arc::new(AtomicU16::new(0)); + let handshake_done = Arc::new(AtomicBool::new(true)); + let mut worker = tokio::spawn(async move { + let mut buf = vec![0; INBOUND_BUFFER_SIZE]; + DTLSConn::read_and_buffer( + &mut ctx, &next_conn, &mut handle_queue_rx, &mut buf, + &local_epoch, &handshake_done, + ).await + }); + + // A valid plaintext epoch0 handshake record exercises the real fragment + // buffer/parser and has_handshake path. TLS authentication is outside this + // reader-wait regression; the inactive FSM never inspects this fixture. + let record = RecordLayer::new( + PROTOCOL_VERSION1_2, 0, + Content::Handshake(Handshake::new(HandshakeMessage::ServerHelloDone( + HandshakeMessageServerHelloDone {}, + ))), + ); + let mut packet = Vec::new(); + record.marshal(&mut packet).unwrap(); + writer_pipe.send(&packet).await.unwrap(); + + // Holding completion_tx open makes outer select choose the ready send + // branch deterministically, rather than relying on select's random order. + let notification_ready = tokio::time::timeout(Duration::from_secs(1), async { + while handshake_rx.len() != 1 { + tokio::task::yield_now().await; + } + }).await; + if notification_ready.is_err() { + worker.abort(); + panic!("actual reader did not enqueue inactive-FSM notification"); + } + assert!(!worker.is_finished()); + drop(completion_tx); + + // Original inner select has no completion arm, so this times out. + // Fixed reader observes completion and releases its packet-read loop. + let completed = tokio::time::timeout(Duration::from_millis(500), &mut worker).await; + if completed.is_err() { + worker.abort(); + panic!("post-handshake reader remained blocked on inactive FSM"); + } + completed.unwrap().unwrap().unwrap(); +} diff --git a/vendor/webrtc-dtls/src/content.rs b/vendor/webrtc-dtls/src/content.rs new file mode 100644 index 0000000..f1b0f62 --- /dev/null +++ b/vendor/webrtc-dtls/src/content.rs @@ -0,0 +1,81 @@ +use std::io::{Read, Write}; + +use super::alert::*; +use super::application_data::*; +use super::change_cipher_spec::*; +use super::handshake::*; +use crate::error::*; + +// https://tools.ietf.org/html/rfc4346#section-6.2.1 +#[derive(Default, Copy, Clone, PartialEq, Eq, Debug)] +pub enum ContentType { + ChangeCipherSpec = 20, + Alert = 21, + Handshake = 22, + ApplicationData = 23, + #[default] + Invalid, +} + +impl From for ContentType { + fn from(val: u8) -> Self { + match val { + 20 => ContentType::ChangeCipherSpec, + 21 => ContentType::Alert, + 22 => ContentType::Handshake, + 23 => ContentType::ApplicationData, + _ => ContentType::Invalid, + } + } +} + +#[derive(PartialEq, Debug, Clone)] +pub enum Content { + ChangeCipherSpec(ChangeCipherSpec), + Alert(Alert), + Handshake(Handshake), + ApplicationData(ApplicationData), +} + +impl Content { + pub fn content_type(&self) -> ContentType { + match self { + Content::ChangeCipherSpec(c) => c.content_type(), + Content::Alert(c) => c.content_type(), + Content::Handshake(c) => c.content_type(), + Content::ApplicationData(c) => c.content_type(), + } + } + + pub fn size(&self) -> usize { + match self { + Content::ChangeCipherSpec(c) => c.size(), + Content::Alert(c) => c.size(), + Content::Handshake(c) => c.size(), + Content::ApplicationData(c) => c.size(), + } + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + match self { + Content::ChangeCipherSpec(c) => c.marshal(writer), + Content::Alert(c) => c.marshal(writer), + Content::Handshake(c) => c.marshal(writer), + Content::ApplicationData(c) => c.marshal(writer), + } + } + + pub fn unmarshal(content_type: ContentType, reader: &mut R) -> Result { + match content_type { + ContentType::ChangeCipherSpec => Ok(Content::ChangeCipherSpec( + ChangeCipherSpec::unmarshal(reader)?, + )), + ContentType::Alert => Ok(Content::Alert(Alert::unmarshal(reader)?)), + ContentType::Handshake => Ok(Content::Handshake(Handshake::unmarshal(reader)?)), + ContentType::ApplicationData => Ok(Content::ApplicationData( + ApplicationData::unmarshal(reader)?, + )), + _ => Err(Error::ErrInvalidContentType), + } + } +} diff --git a/vendor/webrtc-dtls/src/crypto/crypto_cbc.rs b/vendor/webrtc-dtls/src/crypto/crypto_cbc.rs new file mode 100644 index 0000000..3a6bce8 --- /dev/null +++ b/vendor/webrtc-dtls/src/crypto/crypto_cbc.rs @@ -0,0 +1,128 @@ +// AES-CBC (Cipher Block Chaining) +// First historic block cipher for AES. +// CBC mode is insecure and must not be used. It’s been progressively deprecated and +// removed from SSL libraries. +// Introduced with TLS 1.0 year 2002. Superseded by GCM in TLS 1.2 year 2008. +// Removed in TLS 1.3 year 2018. +// RFC 3268 year 2002 https://tools.ietf.org/html/rfc3268 + +// https://github.com/RustCrypto/block-ciphers + +use aes::cipher::{block_padding::Pkcs7, BlockDecryptMut, BlockEncryptMut, KeyIvInit}; +use p256::elliptic_curve::subtle::ConstantTimeEq; +use rand::Rng; +use std::io::Cursor; +use std::ops::Not; + +use crate::content::*; +use crate::error::*; +use crate::prf::*; +use crate::record_layer::record_layer_header::*; +type Aes256CbcEnc = cbc::Encryptor; +type Aes256CbcDec = cbc::Decryptor; + +// State needed to handle encrypted input/output +#[derive(Clone)] +pub struct CryptoCbc { + local_key: Vec, + remote_key: Vec, + write_mac: Vec, + read_mac: Vec, +} + +impl CryptoCbc { + const BLOCK_SIZE: usize = 16; + const MAC_SIZE: usize = 20; + + pub fn new( + local_key: &[u8], + local_mac: &[u8], + remote_key: &[u8], + remote_mac: &[u8], + ) -> Result { + Ok(CryptoCbc { + local_key: local_key.to_vec(), + write_mac: local_mac.to_vec(), + + remote_key: remote_key.to_vec(), + read_mac: remote_mac.to_vec(), + }) + } + + pub fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + let mut payload = raw[RECORD_LAYER_HEADER_SIZE..].to_vec(); + let raw = &raw[..RECORD_LAYER_HEADER_SIZE]; + + // Generate + Append MAC + let h = pkt_rlh; + + let mac = prf_mac( + h.epoch, + h.sequence_number, + h.content_type, + h.protocol_version, + &payload, + &self.write_mac, + )?; + payload.extend_from_slice(&mac); + + let mut iv: Vec = vec![0; Self::BLOCK_SIZE]; + rand::thread_rng().fill(iv.as_mut_slice()); + + let write_cbc = Aes256CbcEnc::new_from_slices(&self.local_key, &iv)?; + let encrypted = write_cbc.encrypt_padded_vec_mut::(&payload); + + // Prepend unencrypte header with encrypted payload + let mut r = vec![]; + r.extend_from_slice(raw); + r.extend_from_slice(&iv); + r.extend_from_slice(&encrypted); + + let r_len = (r.len() - RECORD_LAYER_HEADER_SIZE) as u16; + r[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE] + .copy_from_slice(&r_len.to_be_bytes()); + + Ok(r) + } + + pub fn decrypt(&self, r: &[u8]) -> Result> { + let mut reader = Cursor::new(r); + let h = RecordLayerHeader::unmarshal(&mut reader)?; + if h.content_type == ContentType::ChangeCipherSpec { + // Nothing to encrypt with ChangeCipherSpec + return Ok(r.to_vec()); + } + + let body = &r[RECORD_LAYER_HEADER_SIZE..]; + let iv = &body[0..Self::BLOCK_SIZE]; + let body = &body[Self::BLOCK_SIZE..]; + //TODO: add body.len() check + + let read_cbc = Aes256CbcDec::new_from_slices(&self.remote_key, iv)?; + + let decrypted = read_cbc + .decrypt_padded_vec_mut::(body) + .map_err(|_| Error::ErrInvalidPacketLength)?; + + let recv_mac = &decrypted[decrypted.len() - Self::MAC_SIZE..]; + let decrypted = &decrypted[0..decrypted.len() - Self::MAC_SIZE]; + let mac = prf_mac( + h.epoch, + h.sequence_number, + h.content_type, + h.protocol_version, + decrypted, + &self.read_mac, + )?; + + if recv_mac.ct_eq(&mac).not().into() { + return Err(Error::ErrInvalidMac); + } + + let mut d = Vec::with_capacity(RECORD_LAYER_HEADER_SIZE + decrypted.len()); + d.extend_from_slice(&r[..RECORD_LAYER_HEADER_SIZE]); + d.extend_from_slice(decrypted); + + Ok(d) + } +} diff --git a/vendor/webrtc-dtls/src/crypto/crypto_ccm.rs b/vendor/webrtc-dtls/src/crypto/crypto_ccm.rs new file mode 100644 index 0000000..a932e54 --- /dev/null +++ b/vendor/webrtc-dtls/src/crypto/crypto_ccm.rs @@ -0,0 +1,188 @@ +// AES-CCM (Counter with CBC-MAC) +// Alternative to GCM mode. +// Available in OpenSSL as of TLS 1.3 (2018), but disabled by default. +// Two AES computations per block, thus expected to be somewhat slower than AES-GCM. +// RFC 6655 year 2012 https://tools.ietf.org/html/rfc6655 +// Much lower adoption, probably because it came after GCM and offer no significant benefit. + +// https://github.com/RustCrypto/AEADs +// https://docs.rs/ccm/0.3.0/ccm/ Or https://crates.io/crates/aes-ccm? + +use std::io::Cursor; + +use aes::Aes128; +use ccm::aead::generic_array::GenericArray; +use ccm::aead::AeadInPlace; +use ccm::consts::{U12, U16, U8}; +use ccm::Ccm; +use ccm::KeyInit; +use rand::Rng; + +use super::*; +use crate::content::*; +use crate::error::*; +use crate::record_layer::record_layer_header::*; + +const CRYPTO_CCM_8_TAG_LENGTH: usize = 8; +const CRYPTO_CCM_TAG_LENGTH: usize = 16; +const CRYPTO_CCM_NONCE_LENGTH: usize = 12; + +type AesCcm8 = Ccm; +type AesCcm = Ccm; + +#[derive(Clone)] +pub enum CryptoCcmTagLen { + CryptoCcm8TagLength, + CryptoCcmTagLength, +} + +enum CryptoCcmType { + CryptoCcm8(AesCcm8), + CryptoCcm(AesCcm), +} + +// State needed to handle encrypted input/output +pub struct CryptoCcm { + local_ccm: CryptoCcmType, + remote_ccm: CryptoCcmType, + local_write_iv: Vec, + remote_write_iv: Vec, + // used by clone() + local_write_key: Vec, + remote_write_key: Vec, +} + +impl Clone for CryptoCcm { + fn clone(&self) -> Self { + match self.local_ccm { + CryptoCcmType::CryptoCcm(_) => Self::new( + &CryptoCcmTagLen::CryptoCcmTagLength, + &self.local_write_key, + &self.local_write_iv, + &self.remote_write_key, + &self.remote_write_iv, + ), + CryptoCcmType::CryptoCcm8(_) => Self::new( + &CryptoCcmTagLen::CryptoCcm8TagLength, + &self.local_write_key, + &self.local_write_iv, + &self.remote_write_key, + &self.remote_write_iv, + ), + } + } +} + +impl CryptoCcm { + pub fn new( + tag_len: &CryptoCcmTagLen, + local_key: &[u8], + local_write_iv: &[u8], + remote_key: &[u8], + remote_write_iv: &[u8], + ) -> Self { + let key = GenericArray::from_slice(local_key); + let local_ccm = match tag_len { + CryptoCcmTagLen::CryptoCcmTagLength => CryptoCcmType::CryptoCcm(AesCcm::new(key)), + CryptoCcmTagLen::CryptoCcm8TagLength => CryptoCcmType::CryptoCcm8(AesCcm8::new(key)), + }; + + let key = GenericArray::from_slice(remote_key); + let remote_ccm = match tag_len { + CryptoCcmTagLen::CryptoCcmTagLength => CryptoCcmType::CryptoCcm(AesCcm::new(key)), + CryptoCcmTagLen::CryptoCcm8TagLength => CryptoCcmType::CryptoCcm8(AesCcm8::new(key)), + }; + + CryptoCcm { + local_ccm, + local_write_key: local_key.to_vec(), + local_write_iv: local_write_iv.to_vec(), + remote_ccm, + remote_write_key: remote_key.to_vec(), + remote_write_iv: remote_write_iv.to_vec(), + } + } + + pub fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + let payload = &raw[RECORD_LAYER_HEADER_SIZE..]; + let raw = &raw[..RECORD_LAYER_HEADER_SIZE]; + + let mut nonce = vec![0u8; CRYPTO_CCM_NONCE_LENGTH]; + nonce[..4].copy_from_slice(&self.local_write_iv[..4]); + rand::thread_rng().fill(&mut nonce[4..]); + let nonce = GenericArray::from_slice(&nonce); + + let additional_data = generate_aead_additional_data(pkt_rlh, payload.len()); + + let mut buffer: Vec = Vec::new(); + buffer.extend_from_slice(payload); + + match &self.local_ccm { + CryptoCcmType::CryptoCcm(ccm) => { + ccm.encrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + } + CryptoCcmType::CryptoCcm8(ccm8) => { + ccm8.encrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + } + } + + let mut r = Vec::with_capacity(raw.len() + nonce.len() + buffer.len()); + + r.extend_from_slice(raw); + r.extend_from_slice(&nonce[4..]); + r.extend_from_slice(&buffer); + + // Update recordLayer size to include explicit nonce + let r_len = (r.len() - RECORD_LAYER_HEADER_SIZE) as u16; + r[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE] + .copy_from_slice(&r_len.to_be_bytes()); + + Ok(r) + } + + pub fn decrypt(&self, r: &[u8]) -> Result> { + let mut reader = Cursor::new(r); + let h = RecordLayerHeader::unmarshal(&mut reader)?; + if h.content_type == ContentType::ChangeCipherSpec { + // Nothing to encrypt with ChangeCipherSpec + return Ok(r.to_vec()); + } + + if r.len() <= (RECORD_LAYER_HEADER_SIZE + 8) { + return Err(Error::ErrNotEnoughRoomForNonce); + } + + let mut nonce = vec![]; + nonce.extend_from_slice(&self.remote_write_iv[..4]); + nonce.extend_from_slice(&r[RECORD_LAYER_HEADER_SIZE..RECORD_LAYER_HEADER_SIZE + 8]); + let nonce = GenericArray::from_slice(&nonce); + + let out = &r[RECORD_LAYER_HEADER_SIZE + 8..]; + + let mut buffer: Vec = Vec::new(); + buffer.extend_from_slice(out); + + match &self.remote_ccm { + CryptoCcmType::CryptoCcm(ccm) => { + let additional_data = + generate_aead_additional_data(&h, out.len() - CRYPTO_CCM_TAG_LENGTH); + ccm.decrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + } + CryptoCcmType::CryptoCcm8(ccm8) => { + let additional_data = + generate_aead_additional_data(&h, out.len() - CRYPTO_CCM_8_TAG_LENGTH); + ccm8.decrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + } + } + + let mut d = Vec::with_capacity(RECORD_LAYER_HEADER_SIZE + buffer.len()); + d.extend_from_slice(&r[..RECORD_LAYER_HEADER_SIZE]); + d.extend_from_slice(&buffer); + + Ok(d) + } +} diff --git a/vendor/webrtc-dtls/src/crypto/crypto_gcm.rs b/vendor/webrtc-dtls/src/crypto/crypto_gcm.rs new file mode 100644 index 0000000..9928cca --- /dev/null +++ b/vendor/webrtc-dtls/src/crypto/crypto_gcm.rs @@ -0,0 +1,119 @@ +// AES-GCM (Galois Counter Mode) +// The most widely used block cipher worldwide. +// Mandatory as of TLS 1.2 (2008) and used by default by most clients. +// RFC 5288 year 2008 https://tools.ietf.org/html/rfc5288 + +// https://github.com/RustCrypto/AEADs +// https://docs.rs/aes-gcm/0.8.0/aes_gcm/ + +use std::io::Cursor; + +use aes_gcm::aead::generic_array::GenericArray; +use aes_gcm::aead::AeadInPlace; +use aes_gcm::{Aes128Gcm, KeyInit}; +use rand::Rng; + +use super::*; +use crate::content::*; +use crate::error::*; +use crate::record_layer::record_layer_header::*; // what about Aes256Gcm? + +const CRYPTO_GCM_TAG_LENGTH: usize = 16; +const CRYPTO_GCM_NONCE_LENGTH: usize = 12; + +// State needed to handle encrypted input/output +#[derive(Clone)] +pub struct CryptoGcm { + local_gcm: Aes128Gcm, + remote_gcm: Aes128Gcm, + local_write_iv: Vec, + remote_write_iv: Vec, +} + +impl CryptoGcm { + pub fn new( + local_key: &[u8], + local_write_iv: &[u8], + remote_key: &[u8], + remote_write_iv: &[u8], + ) -> Self { + let key = GenericArray::from_slice(local_key); + let local_gcm = Aes128Gcm::new(key); + + let key = GenericArray::from_slice(remote_key); + let remote_gcm = Aes128Gcm::new(key); + + CryptoGcm { + local_gcm, + local_write_iv: local_write_iv.to_vec(), + remote_gcm, + remote_write_iv: remote_write_iv.to_vec(), + } + } + + pub fn encrypt(&self, pkt_rlh: &RecordLayerHeader, raw: &[u8]) -> Result> { + let payload = &raw[RECORD_LAYER_HEADER_SIZE..]; + let raw = &raw[..RECORD_LAYER_HEADER_SIZE]; + + let mut nonce = vec![0u8; CRYPTO_GCM_NONCE_LENGTH]; + nonce[..4].copy_from_slice(&self.local_write_iv[..4]); + rand::thread_rng().fill(&mut nonce[4..]); + let nonce = GenericArray::from_slice(&nonce); + + let additional_data = generate_aead_additional_data(pkt_rlh, payload.len()); + + let mut buffer: Vec = Vec::new(); + buffer.extend_from_slice(payload); + + self.local_gcm + .encrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + + let mut r = Vec::with_capacity(raw.len() + nonce.len() + buffer.len()); + r.extend_from_slice(raw); + r.extend_from_slice(&nonce[4..]); + r.extend_from_slice(&buffer); + + // Update recordLayer size to include explicit nonce + let r_len = (r.len() - RECORD_LAYER_HEADER_SIZE) as u16; + r[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE] + .copy_from_slice(&r_len.to_be_bytes()); + + Ok(r) + } + + pub fn decrypt(&self, r: &[u8]) -> Result> { + let mut reader = Cursor::new(r); + let h = RecordLayerHeader::unmarshal(&mut reader)?; + if h.content_type == ContentType::ChangeCipherSpec { + // Nothing to encrypt with ChangeCipherSpec + return Ok(r.to_vec()); + } + + if r.len() <= (RECORD_LAYER_HEADER_SIZE + 8) { + return Err(Error::ErrNotEnoughRoomForNonce); + } + + let mut nonce = vec![]; + nonce.extend_from_slice(&self.remote_write_iv[..4]); + nonce.extend_from_slice(&r[RECORD_LAYER_HEADER_SIZE..RECORD_LAYER_HEADER_SIZE + 8]); + let nonce = GenericArray::from_slice(&nonce); + + let out = &r[RECORD_LAYER_HEADER_SIZE + 8..]; + + let additional_data = generate_aead_additional_data(&h, out.len() - CRYPTO_GCM_TAG_LENGTH); + + let mut buffer: Vec = Vec::new(); + buffer.extend_from_slice(out); + + self.remote_gcm + .decrypt_in_place(nonce, &additional_data, &mut buffer) + .map_err(|e| Error::Other(e.to_string()))?; + + let mut d = Vec::with_capacity(RECORD_LAYER_HEADER_SIZE + buffer.len()); + d.extend_from_slice(&r[..RECORD_LAYER_HEADER_SIZE]); + d.extend_from_slice(&buffer); + + Ok(d) + } +} diff --git a/vendor/webrtc-dtls/src/crypto/crypto_test.rs b/vendor/webrtc-dtls/src/crypto/crypto_test.rs new file mode 100644 index 0000000..b47c4dc --- /dev/null +++ b/vendor/webrtc-dtls/src/crypto/crypto_test.rs @@ -0,0 +1,221 @@ +use std::io::Cursor; + +use x509_parser::pem::Pem; + +use super::crypto_ccm::*; +use super::*; +use crate::content::ContentType; +use crate::record_layer::record_layer_header::{ProtocolVersion, RECORD_LAYER_HEADER_SIZE}; + +const RAW_PRIVATE_KEY: &str = " +-----BEGIN RSA PRIVATE KEY----- +MIIEowIBAAKCAQEAxIA2BrrnR2sIlATsp7aRBD/3krwZ7vt9dNeoDQAee0s6SuYP +6MBx/HPnAkwNvPS90R05a7pwRkoT6Ur4PfPhCVlUe8lV+0Eto3ZSEeHz3HdsqlM3 +bso67L7Dqrc7MdVstlKcgJi8yeAoGOIL9/igOv0XBFCeznm9nznx6mnsR5cugw+1 +ypXelaHmBCLV7r5SeVSh57+KhvZGbQ2fFpUaTPegRpJZXBNS8lSeWvtOv9d6N5UB +ROTAJodMZT5AfX0jB0QB9IT/0I96H6BSENH08NXOeXApMuLKvnAf361rS7cRAfRL +rWZqERMP4u6Cnk0Cnckc3WcW27kGGIbtwbqUIQIDAQABAoIBAGF7OVIdZp8Hejn0 +N3L8HvT8xtUEe9kS6ioM0lGgvX5s035Uo4/T6LhUx0VcdXRH9eLHnLTUyN4V4cra +ZkxVsE3zAvZl60G6E+oDyLMWZOP6Wu4kWlub9597A5atT7BpMIVCdmFVZFLB4SJ3 +AXkC3nplFAYP+Lh1rJxRIrIn2g+pEeBboWbYA++oDNuMQffDZaokTkJ8Bn1JZYh0 +xEXKY8Bi2Egd5NMeZa1UFO6y8tUbZfwgVs6Enq5uOgtfayq79vZwyjj1kd29MBUD +8g8byV053ZKxbUOiOuUts97eb+fN3DIDRTcT2c+lXt/4C54M1FclJAbtYRK/qwsl +pYWKQAECgYEA4ZUbqQnTo1ICvj81ifGrz+H4LKQqe92Hbf/W51D/Umk2kP702W22 +HP4CvrJRtALThJIG9m2TwUjl/WAuZIBrhSAbIvc3Fcoa2HjdRp+sO5U1ueDq7d/S +Z+PxRI8cbLbRpEdIaoR46qr/2uWZ943PHMv9h4VHPYn1w8b94hwD6vkCgYEA3v87 +mFLzyM9ercnEv9zHMRlMZFQhlcUGQZvfb8BuJYl/WogyT6vRrUuM0QXULNEPlrin +mBQTqc1nCYbgkFFsD2VVt1qIyiAJsB9MD1LNV6YuvE7T2KOSadmsA4fa9PUqbr71 +hf3lTTq+LeR09LebO7WgSGYY+5YKVOEGpYMR1GkCgYEAxPVQmk3HKHEhjgRYdaG5 +lp9A9ZE8uruYVJWtiHgzBTxx9TV2iST+fd/We7PsHFTfY3+wbpcMDBXfIVRKDVwH +BMwchXH9+Ztlxx34bYJaegd0SmA0Hw9ugWEHNgoSEmWpM1s9wir5/ELjc7dGsFtz +uzvsl9fpdLSxDYgAAdzeGtkCgYBAzKIgrVox7DBzB8KojhtD5ToRnXD0+H/M6OKQ +srZPKhlb0V/tTtxrIx0UUEFLlKSXA6mPw6XDHfDnD86JoV9pSeUSlrhRI+Ysy6tq +eIE7CwthpPZiaYXORHZ7wCqcK/HcpJjsCs9rFbrV0yE5S3FMdIbTAvgXg44VBB7O +UbwIoQKBgDuY8gSrA5/A747wjjmsdRWK4DMTMEV4eCW1BEP7Tg7Cxd5n3xPJiYhr +nhLGN+mMnVIcv2zEMS0/eNZr1j/0BtEdx+3IC6Eq+ONY0anZ4Irt57/5QeKgKn/L +JPhfPySIPG4UmwE4gW8t79vfOKxnUu2fDD1ZXUYopan6EckACNH/ +-----END RSA PRIVATE KEY----- +"; + +#[test] +fn test_generate_key_signature() -> Result<()> { + let reader = Cursor::new(RAW_PRIVATE_KEY.as_bytes()); + let pem = match Pem::read(reader) { + Ok((pem, _)) => pem, + Err(_) => return Err(Error::Other("Pem::read error".to_owned())), + }; + //let private_key = rsa::RSAPrivateKey::from_pkcs1(&pem.contents)?; + + let client_random = vec![ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, + ]; + let server_random = vec![ + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, + 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, + 0x8e, 0x8f, + ]; + let public_key = vec![ + 0x20, 0x9f, 0xd7, 0xad, 0x6d, 0xcf, 0xf4, 0x29, 0x8d, 0xd3, 0xf9, 0x6d, 0x5b, 0x1b, 0x2a, + 0xf9, 0x10, 0xa0, 0x53, 0x5b, 0x14, 0x88, 0xd7, 0xf8, 0xfa, 0xbb, 0x34, 0x9a, 0x98, 0x28, + 0x80, 0xb6, 0x15, + ]; + let expected_signature = vec![ + 0x6f, 0x47, 0x97, 0x85, 0xcc, 0x76, 0x50, 0x93, 0xbd, 0xe2, 0x6a, 0x69, 0x0b, 0xc3, 0x03, + 0xd1, 0xb7, 0xe4, 0xab, 0x88, 0x7b, 0xa6, 0x52, 0x80, 0xdf, 0xaa, 0x25, 0x7a, 0xdb, 0x29, + 0x32, 0xe4, 0xd8, 0x28, 0x28, 0xb3, 0xe8, 0x04, 0x3c, 0x38, 0x16, 0xfc, 0x78, 0xe9, 0x15, + 0x7b, 0xc5, 0xbd, 0x7d, 0xfc, 0xcd, 0x83, 0x00, 0x57, 0x4a, 0x3c, 0x23, 0x85, 0x75, 0x6b, + 0x37, 0xd5, 0x89, 0x72, 0x73, 0xf0, 0x44, 0x8c, 0x00, 0x70, 0x1f, 0x6e, 0xa2, 0x81, 0xd0, + 0x09, 0xc5, 0x20, 0x36, 0xab, 0x23, 0x09, 0x40, 0x1f, 0x4d, 0x45, 0x96, 0x62, 0xbb, 0x81, + 0xb0, 0x30, 0x72, 0xad, 0x3a, 0x0a, 0xac, 0x31, 0x63, 0x40, 0x52, 0x0a, 0x27, 0xf3, 0x34, + 0xde, 0x27, 0x7d, 0xb7, 0x54, 0xff, 0x0f, 0x9f, 0x5a, 0xfe, 0x07, 0x0f, 0x4e, 0x9f, 0x53, + 0x04, 0x34, 0x62, 0xf4, 0x30, 0x74, 0x83, 0x35, 0xfc, 0xe4, 0x7e, 0xbf, 0x5a, 0xc4, 0x52, + 0xd0, 0xea, 0xf9, 0x61, 0x4e, 0xf5, 0x1c, 0x0e, 0x58, 0x02, 0x71, 0xfb, 0x1f, 0x34, 0x55, + 0xe8, 0x36, 0x70, 0x3c, 0xc1, 0xcb, 0xc9, 0xb7, 0xbb, 0xb5, 0x1c, 0x44, 0x9a, 0x6d, 0x88, + 0x78, 0x98, 0xd4, 0x91, 0x2e, 0xeb, 0x98, 0x81, 0x23, 0x30, 0x73, 0x39, 0x43, 0xd5, 0xbb, + 0x70, 0x39, 0xba, 0x1f, 0xdb, 0x70, 0x9f, 0x91, 0x83, 0x56, 0xc2, 0xde, 0xed, 0x17, 0x6d, + 0x2c, 0x3e, 0x21, 0xea, 0x36, 0xb4, 0x91, 0xd8, 0x31, 0x05, 0x60, 0x90, 0xfd, 0xc6, 0x74, + 0xa9, 0x7b, 0x18, 0xfc, 0x1c, 0x6a, 0x1c, 0x6e, 0xec, 0xd3, 0xc1, 0xc0, 0x0d, 0x11, 0x25, + 0x48, 0x37, 0x3d, 0x45, 0x11, 0xa2, 0x31, 0x14, 0x0a, 0x66, 0x9f, 0xd8, 0xac, 0x74, 0xa2, + 0xcd, 0xc8, 0x79, 0xb3, 0x9e, 0xc6, 0x66, 0x25, 0xcf, 0x2c, 0x87, 0x5e, 0x5c, 0x36, 0x75, + 0x86, + ]; + + let signature = generate_key_signature( + &client_random, + &server_random, + &public_key, + NamedCurve::X25519, + &CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Rsa256( + ring::rsa::KeyPair::from_der(&pem.contents) + .map_err(|e| Error::Other(e.to_string()))?, + ), + serialized_der: pem.contents.clone(), + }, //hashAlgorithmSHA256, + )?; + + assert_eq!( + signature, expected_signature, + "Signature generation failed \nexp {expected_signature:?} \nactual {signature:?} " + ); + + Ok(()) +} + +#[test] +fn test_ccm_encryption_and_decryption() -> Result<()> { + let key = vec![ + 0x18, 0x78, 0xac, 0xc2, 0x2a, 0xd8, 0xbd, 0xd8, 0xc6, 0x01, 0xa6, 0x17, 0x12, 0x6f, 0x63, + 0x54, + ]; + let iv = vec![0x0e, 0xb2, 0x09, 0x06]; + + let ccm = CryptoCcm::new(&CryptoCcmTagLen::CryptoCcmTagLength, &key, &iv, &key, &iv); + + let rlh = RecordLayerHeader { + content_type: ContentType::ApplicationData, + protocol_version: ProtocolVersion { + major: 0xfe, + minor: 0xff, + }, + epoch: 0, + sequence_number: 18, + content_len: 3, + }; + + let raw = vec![ + 0x17, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x03, 0xff, 0xaa, + 0xbb, + ]; + + let cipher_text = ccm.encrypt(&rlh, &raw)?; + + assert_eq!( + &cipher_text[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE], + [0, 27], + "RecordLayer size updating failed \nexp: {:?} \nactual {:?} ", + [0, 27], + &cipher_text[RECORD_LAYER_HEADER_SIZE - 2..RECORD_LAYER_HEADER_SIZE] + ); + + let plain_text = ccm.decrypt(&cipher_text)?; + + assert_eq!( + raw[RECORD_LAYER_HEADER_SIZE..], + plain_text[RECORD_LAYER_HEADER_SIZE..], + "Decryption failed \nexp: {:?} \nactual {:?} ", + &raw[RECORD_LAYER_HEADER_SIZE..], + &plain_text[RECORD_LAYER_HEADER_SIZE..] + ); + + Ok(()) +} + +#[test] +fn test_certificate_verify() -> Result<()> { + let plain_text: Vec = vec![ + 0x6f, 0x47, 0x97, 0x85, 0xcc, 0x76, 0x50, 0x93, 0xbd, 0xe2, 0x6a, 0x69, 0x0b, 0xc3, 0x03, + 0xd1, 0xb7, 0xe4, 0xab, 0x88, 0x7b, 0xa6, 0x52, 0x80, 0xdf, 0xaa, 0x25, 0x7a, 0xdb, 0x29, + 0x32, 0xe4, 0xd8, 0x28, 0x28, 0xb3, 0xe8, 0x04, 0x3c, 0x38, 0x16, 0xfc, 0x78, 0xe9, 0x15, + 0x7b, 0xc5, 0xbd, 0x7d, 0xfc, 0xcd, 0x83, 0x00, 0x57, 0x4a, 0x3c, 0x23, 0x85, 0x75, 0x6b, + 0x37, 0xd5, 0x89, 0x72, 0x73, 0xf0, 0x44, 0x8c, 0x00, 0x70, 0x1f, 0x6e, 0xa2, 0x81, 0xd0, + 0x09, 0xc5, 0x20, 0x36, 0xab, 0x23, 0x09, 0x40, 0x1f, 0x4d, 0x45, 0x96, 0x62, 0xbb, 0x81, + 0xb0, 0x30, 0x72, 0xad, 0x3a, 0x0a, 0xac, 0x31, 0x63, 0x40, 0x52, 0x0a, 0x27, 0xf3, 0x34, + 0xde, 0x27, 0x7d, 0xb7, 0x54, 0xff, 0x0f, 0x9f, 0x5a, 0xfe, 0x07, 0x0f, 0x4e, 0x9f, 0x53, + 0x04, 0x34, 0x62, 0xf4, 0x30, 0x74, 0x83, 0x35, 0xfc, 0xe4, 0x7e, 0xbf, 0x5a, 0xc4, 0x52, + 0xd0, 0xea, 0xf9, 0x61, 0x4e, 0xf5, 0x1c, 0x0e, 0x58, 0x02, 0x71, 0xfb, 0x1f, 0x34, 0x55, + 0xe8, 0x36, 0x70, 0x3c, 0xc1, 0xcb, 0xc9, 0xb7, 0xbb, 0xb5, 0x1c, 0x44, 0x9a, 0x6d, 0x88, + 0x78, 0x98, 0xd4, 0x91, 0x2e, 0xeb, 0x98, 0x81, 0x23, 0x30, 0x73, 0x39, 0x43, 0xd5, 0xbb, + 0x70, 0x39, 0xba, 0x1f, 0xdb, 0x70, 0x9f, 0x91, 0x83, 0x56, 0xc2, 0xde, 0xed, 0x17, 0x6d, + 0x2c, 0x3e, 0x21, 0xea, 0x36, 0xb4, 0x91, 0xd8, 0x31, 0x05, 0x60, 0x90, 0xfd, 0xc6, 0x74, + 0xa9, 0x7b, 0x18, 0xfc, 0x1c, 0x6a, 0x1c, 0x6e, 0xec, 0xd3, 0xc1, 0xc0, 0x0d, 0x11, 0x25, + 0x48, 0x37, 0x3d, 0x45, 0x11, 0xa2, 0x31, 0x14, 0x0a, 0x66, 0x9f, 0xd8, 0xac, 0x74, 0xa2, + 0xcd, 0xc8, 0x79, 0xb3, 0x9e, 0xc6, 0x66, 0x25, 0xcf, 0x2c, 0x87, 0x5e, 0x5c, 0x36, 0x75, + 0x86, + ]; + + //test ECDSA256 + let certificate_ecdsa256 = Certificate::generate_self_signed(vec!["localhost".to_owned()])?; + let cert_verify_ecdsa256 = + generate_certificate_verify(&plain_text, &certificate_ecdsa256.private_key)?; + verify_certificate_verify( + &plain_text, + &SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + &cert_verify_ecdsa256, + &certificate_ecdsa256 + .certificate + .iter() + .map(|x| x.0.clone()) + .collect::>>(), + false, + )?; + + //test ED25519 + let certificate_ed25519 = Certificate::generate_self_signed_with_alg( + vec!["localhost".to_owned()], + &rcgen::PKCS_ED25519, + )?; + let cert_verify_ed25519 = + generate_certificate_verify(&plain_text, &certificate_ed25519.private_key)?; + verify_certificate_verify( + &plain_text, + &SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ed25519, + }, + &cert_verify_ed25519, + &certificate_ed25519 + .certificate + .iter() + .map(|x| x.0.clone()) + .collect::>>(), + false, + )?; + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/crypto/mod.rs b/vendor/webrtc-dtls/src/crypto/mod.rs new file mode 100644 index 0000000..4ae949b --- /dev/null +++ b/vendor/webrtc-dtls/src/crypto/mod.rs @@ -0,0 +1,522 @@ +#[cfg(test)] +mod crypto_test; + +pub mod crypto_cbc; +pub mod crypto_ccm; +pub mod crypto_gcm; + +use std::convert::TryFrom; +use std::sync::Arc; + +use der_parser::oid; +use der_parser::oid::Oid; +use rcgen::KeyPair; +use ring::rand::SystemRandom; +use ring::signature::{EcdsaKeyPair, Ed25519KeyPair}; + +use crate::curve::named_curve::*; +use crate::error::*; +use crate::record_layer::record_layer_header::*; +use crate::signature_hash_algorithm::{HashAlgorithm, SignatureAlgorithm, SignatureHashAlgorithm}; + +/// A X.509 certificate(s) used to authenticate a DTLS connection. +#[derive(Clone, PartialEq, Debug)] +pub struct Certificate { + /// DER-encoded certificates. + pub certificate: Vec, + /// Private key. + pub private_key: CryptoPrivateKey, +} + +impl Certificate { + /// Generate a self-signed certificate. + /// + /// See [`rcgen::generate_simple_self_signed`]. + pub fn generate_self_signed(subject_alt_names: impl Into>) -> Result { + let cert = rcgen::generate_simple_self_signed(subject_alt_names)?; + let key_pair = cert.get_key_pair(); + + Ok(Certificate { + certificate: vec![rustls::Certificate(cert.serialize_der()?)], + private_key: CryptoPrivateKey::try_from(key_pair)?, + }) + } + + /// Generate a self-signed certificate with the given algorithm. + /// + /// See [`rcgen::Certificate::from_params`]. + pub fn generate_self_signed_with_alg( + subject_alt_names: impl Into>, + alg: &'static rcgen::SignatureAlgorithm, + ) -> Result { + let mut params = rcgen::CertificateParams::new(subject_alt_names); + params.alg = alg; + let cert = rcgen::Certificate::from_params(params)?; + let key_pair = cert.get_key_pair(); + + Ok(Certificate { + certificate: vec![rustls::Certificate(cert.serialize_der()?)], + private_key: CryptoPrivateKey::try_from(key_pair)?, + }) + } + + /// Parses a certificate from the ASCII PEM format. + #[cfg(feature = "pem")] + pub fn from_pem(pem_str: &str) -> Result { + let mut pems = pem::parse_many(pem_str).map_err(|e| Error::InvalidPEM(e.to_string()))?; + if pems.len() < 2 { + return Err(Error::InvalidPEM(format!( + "expected at least two PEM blocks, got {}", + pems.len() + ))); + } + if pems[0].tag() != "PRIVATE_KEY" { + return Err(Error::InvalidPEM(format!( + "invalid tag (expected: 'PRIVATE_KEY', got: '{}')", + pems[0].tag() + ))); + } + + let keypair = rcgen::KeyPair::from_der(pems[0].contents()) + .map_err(|e| Error::InvalidPEM(format!("can't decode keypair: {e}")))?; + + let mut rustls_certs = Vec::new(); + for p in pems.drain(1..) { + if p.tag() != "CERTIFICATE" { + return Err(Error::InvalidPEM(format!( + "invalid tag (expected: 'CERTIFICATE', got: '{}')", + p.tag() + ))); + } + rustls_certs.push(rustls::Certificate(p.contents().to_vec())); + } + + Ok(Certificate { + certificate: rustls_certs, + private_key: CryptoPrivateKey::try_from(&keypair)?, + }) + } + + /// Serializes the certificate (including the private key) in PKCS#8 format in PEM. + #[cfg(feature = "pem")] + pub fn serialize_pem(&self) -> String { + let mut data = vec![pem::Pem::new( + "PRIVATE_KEY".to_string(), + self.private_key.serialized_der.clone(), + )]; + for rustls_cert in &self.certificate { + data.push(pem::Pem::new( + "CERTIFICATE".to_string(), + rustls_cert.0.clone(), + )); + } + pem::encode_many(&data) + } +} + +pub(crate) fn value_key_message( + client_random: &[u8], + server_random: &[u8], + public_key: &[u8], + named_curve: NamedCurve, +) -> Vec { + let mut server_ecdh_params = vec![0u8; 4]; + server_ecdh_params[0] = 3; // named curve + server_ecdh_params[1..3].copy_from_slice(&(named_curve as u16).to_be_bytes()); + server_ecdh_params[3] = public_key.len() as u8; + + let mut plaintext = vec![]; + plaintext.extend_from_slice(client_random); + plaintext.extend_from_slice(server_random); + plaintext.extend_from_slice(&server_ecdh_params); + plaintext.extend_from_slice(public_key); + + plaintext +} + +/// Either ED25519, ECDSA or RSA keypair. +#[derive(Debug)] +pub enum CryptoPrivateKeyKind { + Ed25519(Ed25519KeyPair), + Ecdsa256(EcdsaKeyPair), + Rsa256(ring::rsa::KeyPair), +} + +/// Private key. +#[derive(Debug)] +pub struct CryptoPrivateKey { + /// Keypair. + pub kind: CryptoPrivateKeyKind, + /// DER-encoded keypair. + pub serialized_der: Vec, +} + +impl PartialEq for CryptoPrivateKey { + fn eq(&self, other: &Self) -> bool { + if self.serialized_der != other.serialized_der { + return false; + } + + matches!( + (&self.kind, &other.kind), + ( + CryptoPrivateKeyKind::Rsa256(_), + CryptoPrivateKeyKind::Rsa256(_) + ) | ( + CryptoPrivateKeyKind::Ecdsa256(_), + CryptoPrivateKeyKind::Ecdsa256(_) + ) | ( + CryptoPrivateKeyKind::Ed25519(_), + CryptoPrivateKeyKind::Ed25519(_) + ) + ) + } +} + +impl Clone for CryptoPrivateKey { + fn clone(&self) -> Self { + match self.kind { + CryptoPrivateKeyKind::Ed25519(_) => CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Ed25519( + Ed25519KeyPair::from_pkcs8(&self.serialized_der).unwrap(), + ), + serialized_der: self.serialized_der.clone(), + }, + CryptoPrivateKeyKind::Ecdsa256(_) => CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Ecdsa256( + EcdsaKeyPair::from_pkcs8( + &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, + &self.serialized_der, + &SystemRandom::new(), + ) + .unwrap(), + ), + serialized_der: self.serialized_der.clone(), + }, + CryptoPrivateKeyKind::Rsa256(_) => CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Rsa256( + ring::rsa::KeyPair::from_pkcs8(&self.serialized_der).unwrap(), + ), + serialized_der: self.serialized_der.clone(), + }, + } + } +} + +impl TryFrom<&KeyPair> for CryptoPrivateKey { + type Error = Error; + + fn try_from(key_pair: &KeyPair) -> Result { + Self::from_key_pair(key_pair) + } +} + +impl CryptoPrivateKey { + pub fn from_key_pair(key_pair: &KeyPair) -> Result { + let serialized_der = key_pair.serialize_der(); + if key_pair.is_compatible(&rcgen::PKCS_ED25519) { + Ok(CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Ed25519( + Ed25519KeyPair::from_pkcs8(&serialized_der) + .map_err(|e| Error::Other(e.to_string()))?, + ), + serialized_der, + }) + } else if key_pair.is_compatible(&rcgen::PKCS_ECDSA_P256_SHA256) { + Ok(CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Ecdsa256( + EcdsaKeyPair::from_pkcs8( + &ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING, + &serialized_der, + &SystemRandom::new(), + ) + .map_err(|e| Error::Other(e.to_string()))?, + ), + serialized_der, + }) + } else if key_pair.is_compatible(&rcgen::PKCS_RSA_SHA256) { + Ok(CryptoPrivateKey { + kind: CryptoPrivateKeyKind::Rsa256( + ring::rsa::KeyPair::from_pkcs8(&serialized_der) + .map_err(|e| Error::Other(e.to_string()))?, + ), + serialized_der, + }) + } else { + Err(Error::Other("Unsupported key_pair".to_owned())) + } + } +} + +// If the client provided a "signature_algorithms" extension, then all +// certificates provided by the server MUST be signed by a +// hash/signature algorithm pair that appears in that extension +// +// https://tools.ietf.org/html/rfc5246#section-7.4.2 +pub(crate) fn generate_key_signature( + client_random: &[u8], + server_random: &[u8], + public_key: &[u8], + named_curve: NamedCurve, + private_key: &CryptoPrivateKey, /*, hash_algorithm: HashAlgorithm*/ +) -> Result> { + let msg = value_key_message(client_random, server_random, public_key, named_curve); + let signature = match &private_key.kind { + CryptoPrivateKeyKind::Ed25519(kp) => kp.sign(&msg).as_ref().to_vec(), + CryptoPrivateKeyKind::Ecdsa256(kp) => { + let system_random = SystemRandom::new(); + kp.sign(&system_random, &msg) + .map_err(|e| Error::Other(e.to_string()))? + .as_ref() + .to_vec() + } + CryptoPrivateKeyKind::Rsa256(kp) => { + let system_random = SystemRandom::new(); + let mut signature = vec![0; kp.public().modulus_len()]; + kp.sign( + &ring::signature::RSA_PKCS1_SHA256, + &system_random, + &msg, + &mut signature, + ) + .map_err(|e| Error::Other(e.to_string()))?; + + signature + } + }; + + Ok(signature) +} + +// add OID_ED25519 which is not defined in x509_parser +pub const OID_ED25519: Oid<'static> = oid!(1.3.101 .112); +pub const OID_ECDSA: Oid<'static> = oid!(1.2.840 .10045 .2 .1); + +fn verify_signature( + message: &[u8], + hash_algorithm: &SignatureHashAlgorithm, + remote_key_signature: &[u8], + raw_certificates: &[Vec], + insecure_verification: bool, +) -> Result<()> { + if raw_certificates.is_empty() { + return Err(Error::ErrLengthMismatch); + } + + let (_, certificate) = x509_parser::parse_x509_certificate(&raw_certificates[0]) + .map_err(|e| Error::Other(e.to_string()))?; + + let verify_alg: &dyn ring::signature::VerificationAlgorithm = match hash_algorithm.signature { + SignatureAlgorithm::Ed25519 => &ring::signature::ED25519, + SignatureAlgorithm::Ecdsa if hash_algorithm.hash == HashAlgorithm::Sha256 => { + &ring::signature::ECDSA_P256_SHA256_ASN1 + } + SignatureAlgorithm::Ecdsa if hash_algorithm.hash == HashAlgorithm::Sha384 => { + &ring::signature::ECDSA_P384_SHA384_ASN1 + } + SignatureAlgorithm::Rsa if hash_algorithm.hash == HashAlgorithm::Sha1 => { + &ring::signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY + } + SignatureAlgorithm::Rsa if (hash_algorithm.hash == HashAlgorithm::Sha256) => { + if remote_key_signature.len() < 256 && insecure_verification { + &ring::signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY + } else { + &ring::signature::RSA_PKCS1_2048_8192_SHA256 + } + } + SignatureAlgorithm::Rsa if hash_algorithm.hash == HashAlgorithm::Sha384 => { + &ring::signature::RSA_PKCS1_2048_8192_SHA384 + } + SignatureAlgorithm::Rsa if hash_algorithm.hash == HashAlgorithm::Sha512 => { + if remote_key_signature.len() < 256 && insecure_verification { + &ring::signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY + } else { + &ring::signature::RSA_PKCS1_2048_8192_SHA512 + } + } + _ => return Err(Error::ErrKeySignatureVerifyUnimplemented), + }; + + log::trace!("Picked an algorithm {:?}", verify_alg); + + let public_key = ring::signature::UnparsedPublicKey::new( + verify_alg, + certificate + .tbs_certificate + .subject_pki + .subject_public_key + .data, + ); + + public_key + .verify(message, remote_key_signature) + .map_err(|e| Error::Other(e.to_string()))?; + + Ok(()) +} + +pub(crate) fn verify_key_signature( + message: &[u8], + hash_algorithm: &SignatureHashAlgorithm, + remote_key_signature: &[u8], + raw_certificates: &[Vec], + insecure_verification: bool, +) -> Result<()> { + verify_signature( + message, + hash_algorithm, + remote_key_signature, + raw_certificates, + insecure_verification, + ) +} + +// If the server has sent a CertificateRequest message, the client MUST send the Certificate +// message. The ClientKeyExchange message is now sent, and the content +// of that message will depend on the public key algorithm selected +// between the ClientHello and the ServerHello. If the client has sent +// a certificate with signing ability, a digitally-signed +// CertificateVerify message is sent to explicitly verify possession of +// the private key in the certificate. +// https://tools.ietf.org/html/rfc5246#section-7.3 +pub(crate) fn generate_certificate_verify( + handshake_bodies: &[u8], + private_key: &CryptoPrivateKey, /*, hashAlgorithm hashAlgorithm*/ +) -> Result> { + let signature = match &private_key.kind { + CryptoPrivateKeyKind::Ed25519(kp) => kp.sign(handshake_bodies).as_ref().to_vec(), + CryptoPrivateKeyKind::Ecdsa256(kp) => { + let system_random = SystemRandom::new(); + kp.sign(&system_random, handshake_bodies) + .map_err(|e| Error::Other(e.to_string()))? + .as_ref() + .to_vec() + } + CryptoPrivateKeyKind::Rsa256(kp) => { + let system_random = SystemRandom::new(); + let mut signature = vec![0; kp.public().modulus_len()]; + kp.sign( + &ring::signature::RSA_PKCS1_SHA256, + &system_random, + handshake_bodies, + &mut signature, + ) + .map_err(|e| Error::Other(e.to_string()))?; + + signature + } + }; + + Ok(signature) +} + +pub(crate) fn verify_certificate_verify( + handshake_bodies: &[u8], + hash_algorithm: &SignatureHashAlgorithm, + remote_key_signature: &[u8], + raw_certificates: &[Vec], + insecure_verification: bool, +) -> Result<()> { + verify_signature( + handshake_bodies, + hash_algorithm, + remote_key_signature, + raw_certificates, + insecure_verification, + ) +} + +pub(crate) fn load_certs(raw_certificates: &[Vec]) -> Result> { + if raw_certificates.is_empty() { + return Err(Error::ErrLengthMismatch); + } + + let mut certs = vec![]; + for raw_cert in raw_certificates { + let cert = rustls::Certificate(raw_cert.to_vec()); + certs.push(cert); + } + + Ok(certs) +} + +pub(crate) fn verify_client_cert( + raw_certificates: &[Vec], + cert_verifier: &Arc, +) -> Result> { + let chains = load_certs(raw_certificates)?; + + let (end_entity, intermediates) = chains + .split_first() + .ok_or(Error::ErrClientCertificateRequired)?; + + match cert_verifier.verify_client_cert(end_entity, intermediates, std::time::SystemTime::now()) + { + Ok(_) => {} + Err(err) => return Err(Error::Other(err.to_string())), + }; + + Ok(chains) +} + +pub(crate) fn verify_server_cert( + raw_certificates: &[Vec], + cert_verifier: &Arc, + server_name: &str, +) -> Result> { + let chains = load_certs(raw_certificates)?; + let dns_name = match rustls::server::DnsName::try_from_ascii(server_name.as_ref()) { + Ok(dns_name) => dns_name, + Err(err) => return Err(Error::Other(err.to_string())), + }; + + let (end_entity, intermediates) = chains + .split_first() + .ok_or(Error::ErrServerMustHaveCertificate)?; + match cert_verifier.verify_server_cert( + end_entity, + intermediates, + &rustls::ServerName::DnsName(dns_name.to_owned()), + &mut [].into_iter(), + &[], + std::time::SystemTime::now(), + ) { + Ok(_) => {} + Err(err) => return Err(Error::Other(err.to_string())), + }; + + Ok(chains) +} + +pub(crate) fn generate_aead_additional_data(h: &RecordLayerHeader, payload_len: usize) -> Vec { + let mut additional_data = vec![0u8; 13]; + // SequenceNumber MUST be set first + // we only want uint48, clobbering an extra 2 (using uint64, rust doesn't have uint48) + additional_data[..8].copy_from_slice(&h.sequence_number.to_be_bytes()); + additional_data[..2].copy_from_slice(&h.epoch.to_be_bytes()); + additional_data[8] = h.content_type as u8; + additional_data[9] = h.protocol_version.major; + additional_data[10] = h.protocol_version.minor; + additional_data[11..].copy_from_slice(&(payload_len as u16).to_be_bytes()); + + additional_data +} + +#[cfg(test)] +mod test { + #[cfg(feature = "pem")] + use super::*; + + #[cfg(feature = "pem")] + #[test] + fn test_certificate_serialize_pem_and_from_pem() -> crate::error::Result<()> { + let cert = Certificate::generate_self_signed(vec!["webrtc.rs".to_owned()])?; + + let pem = cert.serialize_pem(); + let loaded_cert = Certificate::from_pem(&pem)?; + + assert_eq!(loaded_cert, cert); + + Ok(()) + } +} diff --git a/vendor/webrtc-dtls/src/curve/mod.rs b/vendor/webrtc-dtls/src/curve/mod.rs new file mode 100644 index 0000000..dd48d5f --- /dev/null +++ b/vendor/webrtc-dtls/src/curve/mod.rs @@ -0,0 +1,17 @@ +pub mod named_curve; + +// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-10 +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum EllipticCurveType { + NamedCurve = 0x03, + Unsupported, +} + +impl From for EllipticCurveType { + fn from(val: u8) -> Self { + match val { + 0x03 => EllipticCurveType::NamedCurve, + _ => EllipticCurveType::Unsupported, + } + } +} diff --git a/vendor/webrtc-dtls/src/curve/named_curve.rs b/vendor/webrtc-dtls/src/curve/named_curve.rs new file mode 100644 index 0000000..6d7d97f --- /dev/null +++ b/vendor/webrtc-dtls/src/curve/named_curve.rs @@ -0,0 +1,83 @@ +use rand_core::OsRng; // requires 'getrandom' feature + +use crate::error::*; + +// https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 +#[repr(u16)] +#[derive(Copy, Clone, PartialEq, Eq, Debug)] +pub enum NamedCurve { + Unsupported = 0x0000, + P256 = 0x0017, + P384 = 0x0018, + X25519 = 0x001d, +} + +impl From for NamedCurve { + fn from(val: u16) -> Self { + match val { + 0x0017 => NamedCurve::P256, + 0x0018 => NamedCurve::P384, + 0x001d => NamedCurve::X25519, + _ => NamedCurve::Unsupported, + } + } +} + +pub(crate) enum NamedCurvePrivateKey { + EphemeralSecretP256(p256::ecdh::EphemeralSecret), + EphemeralSecretP384(p384::ecdh::EphemeralSecret), + StaticSecretX25519(x25519_dalek::StaticSecret), +} + +pub struct NamedCurveKeypair { + pub(crate) curve: NamedCurve, + pub(crate) public_key: Vec, + pub(crate) private_key: NamedCurvePrivateKey, +} + +fn elliptic_curve_keypair(curve: NamedCurve) -> Result { + let (public_key, private_key) = match curve { + NamedCurve::P256 => { + let secret_key = p256::ecdh::EphemeralSecret::random(&mut OsRng); + let public_key = p256::EncodedPoint::from(secret_key.public_key()); + ( + public_key.as_bytes().to_vec(), + NamedCurvePrivateKey::EphemeralSecretP256(secret_key), + ) + } + NamedCurve::P384 => { + let secret_key = p384::ecdh::EphemeralSecret::random(&mut OsRng); + let public_key = p384::EncodedPoint::from(secret_key.public_key()); + ( + public_key.as_bytes().to_vec(), + NamedCurvePrivateKey::EphemeralSecretP384(secret_key), + ) + } + NamedCurve::X25519 => { + let secret_key = x25519_dalek::StaticSecret::random_from_rng(OsRng); + let public_key = x25519_dalek::PublicKey::from(&secret_key); + ( + public_key.as_bytes().to_vec(), + NamedCurvePrivateKey::StaticSecretX25519(secret_key), + ) + } + _ => return Err(Error::ErrInvalidNamedCurve), + }; + + Ok(NamedCurveKeypair { + curve, + public_key, + private_key, + }) +} + +impl NamedCurve { + pub fn generate_keypair(&self) -> Result { + match *self { + NamedCurve::X25519 => elliptic_curve_keypair(NamedCurve::X25519), + NamedCurve::P256 => elliptic_curve_keypair(NamedCurve::P256), + NamedCurve::P384 => elliptic_curve_keypair(NamedCurve::P384), + _ => Err(Error::ErrInvalidNamedCurve), + } + } +} diff --git a/vendor/webrtc-dtls/src/error.rs b/vendor/webrtc-dtls/src/error.rs new file mode 100644 index 0000000..de68a38 --- /dev/null +++ b/vendor/webrtc-dtls/src/error.rs @@ -0,0 +1,224 @@ +use std::io; +use std::string::FromUtf8Error; + +use rcgen::RcgenError; +use thiserror::Error; +use tokio::sync::mpsc::error::SendError as MpscSendError; +use util::KeyingMaterialExporterError; + +pub type Result = std::result::Result; + +#[derive(Debug, Error, PartialEq)] +#[non_exhaustive] +pub enum Error { + #[error("conn is closed")] + ErrConnClosed, + #[error("read/write timeout")] + ErrDeadlineExceeded, + #[error("buffer is too small")] + ErrBufferTooSmall, + #[error("context is not supported for export_keying_material")] + ErrContextUnsupported, + #[error("packet is too short")] + ErrDtlspacketInvalidLength, + #[error("handshake is in progress")] + ErrHandshakeInProgress, + #[error("invalid content type")] + ErrInvalidContentType, + #[error("invalid mac")] + ErrInvalidMac, + #[error("packet length and declared length do not match")] + ErrInvalidPacketLength, + #[error("export_keying_material can not be used with a reserved label")] + ErrReservedExportKeyingMaterial, + #[error("client sent certificate verify but we have no certificate to verify")] + ErrCertificateVerifyNoCertificate, + #[error("client+server do not support any shared cipher suites")] + ErrCipherSuiteNoIntersection, + #[error("server hello can not be created without a cipher suite")] + ErrCipherSuiteUnset, + #[error("client sent certificate but did not verify it")] + ErrClientCertificateNotVerified, + #[error("server required client verification, but got none")] + ErrClientCertificateRequired, + #[error("server responded with SRTP Profile we do not support")] + ErrClientNoMatchingSrtpProfile, + #[error("client required Extended Master Secret extension, but server does not support it")] + ErrClientRequiredButNoServerEms, + #[error("server hello can not be created without a compression method")] + ErrCompressionMethodUnset, + #[error("client+server cookie does not match")] + ErrCookieMismatch, + #[error("cookie must not be longer then 255 bytes")] + ErrCookieTooLong, + #[error("PSK Identity Hint provided but PSK is nil")] + ErrIdentityNoPsk, + #[error("no certificate provided")] + ErrInvalidCertificate, + #[error("cipher spec invalid")] + ErrInvalidCipherSpec, + #[error("invalid or unknown cipher suite")] + ErrInvalidCipherSuite, + #[error("unable to determine if ClientKeyExchange is a public key or PSK Identity")] + ErrInvalidClientKeyExchange, + #[error("invalid or unknown compression method")] + ErrInvalidCompressionMethod, + #[error("ECDSA signature contained zero or negative values")] + ErrInvalidEcdsasignature, + #[error("invalid or unknown elliptic curve type")] + ErrInvalidEllipticCurveType, + #[error("invalid extension type")] + ErrInvalidExtensionType, + #[error("invalid hash algorithm")] + ErrInvalidHashAlgorithm, + #[error("invalid named curve")] + ErrInvalidNamedCurve, + #[error("invalid private key type")] + ErrInvalidPrivateKey, + #[error("named curve and private key type does not match")] + ErrNamedCurveAndPrivateKeyMismatch, + #[error("invalid server name format")] + ErrInvalidSniFormat, + #[error("invalid signature algorithm")] + ErrInvalidSignatureAlgorithm, + #[error("expected and actual key signature do not match")] + ErrKeySignatureMismatch, + #[error("Conn can not be created with a nil nextConn")] + ErrNilNextConn, + #[error("connection can not be created, no CipherSuites satisfy this Config")] + ErrNoAvailableCipherSuites, + #[error("connection can not be created, no SignatureScheme satisfy this Config")] + ErrNoAvailableSignatureSchemes, + #[error("no certificates configured")] + ErrNoCertificates, + #[error("no config provided")] + ErrNoConfigProvided, + #[error("client requested zero or more elliptic curves that are not supported by the server")] + ErrNoSupportedEllipticCurves, + #[error("unsupported protocol version")] + ErrUnsupportedProtocolVersion, + #[error("Certificate and PSK provided")] + ErrPskAndCertificate, + #[error("PSK and PSK Identity Hint must both be set for client")] + ErrPskAndIdentityMustBeSetForClient, + #[error("SRTP support was requested but server did not respond with use_srtp extension")] + ErrRequestedButNoSrtpExtension, + #[error("Certificate is mandatory for server")] + ErrServerMustHaveCertificate, + #[error("client requested SRTP but we have no matching profiles")] + ErrServerNoMatchingSrtpProfile, + #[error( + "server requires the Extended Master Secret extension, but the client does not support it" + )] + ErrServerRequiredButNoClientEms, + #[error("expected and actual verify data does not match")] + ErrVerifyDataMismatch, + #[error("handshake message unset, unable to marshal")] + ErrHandshakeMessageUnset, + #[error("invalid flight number")] + ErrInvalidFlight, + #[error("unable to generate key signature, unimplemented")] + ErrKeySignatureGenerateUnimplemented, + #[error("unable to verify key signature, unimplemented")] + ErrKeySignatureVerifyUnimplemented, + #[error("data length and declared length do not match")] + ErrLengthMismatch, + #[error("buffer not long enough to contain nonce")] + ErrNotEnoughRoomForNonce, + #[error("feature has not been implemented yet")] + ErrNotImplemented, + #[error("sequence number overflow")] + ErrSequenceNumberOverflow, + #[error("unable to marshal fragmented handshakes")] + ErrUnableToMarshalFragmented, + #[error("invalid state machine transition")] + ErrInvalidFsmTransition, + #[error("ApplicationData with epoch of 0")] + ErrApplicationDataEpochZero, + #[error("unhandled contentType")] + ErrUnhandledContextType, + #[error("context canceled")] + ErrContextCanceled, + #[error("empty fragment")] + ErrEmptyFragment, + #[error("Alert is Fatal or Close Notify")] + ErrAlertFatalOrClose, + + #[error( + "Fragment buffer overflow. New size {new_size} is greater than specified max {max_size}" + )] + ErrFragmentBufferOverflow { new_size: usize, max_size: usize }, + + #[error("{0}")] + Io(#[source] IoError), + #[error("{0}")] + Util(#[from] util::Error), + #[error("utf8: {0}")] + Utf8(#[from] FromUtf8Error), + #[error("{0}")] + Sec1(#[source] sec1::Error), + #[error("{0}")] + Aes(#[from] aes::cipher::InvalidLength), + #[error("{0}")] + P256(#[source] P256Error), + #[error("{0}")] + RcGen(#[from] RcgenError), + #[error("mpsc send: {0}")] + MpscSend(String), + #[error("keying material: {0}")] + KeyingMaterial(#[from] KeyingMaterialExporterError), + + /// Error parsing a given PEM string. + #[error("invalid PEM: {0}")] + InvalidPEM(String), + + #[allow(non_camel_case_types)] + #[error("{0}")] + Other(String), +} + +#[derive(Debug, Error)] +#[error("io error: {0}")] +pub struct IoError(#[from] pub io::Error); + +// Workaround for wanting PartialEq for io::Error. +impl PartialEq for IoError { + fn eq(&self, other: &Self) -> bool { + self.0.kind() == other.0.kind() + } +} + +impl From for Error { + fn from(e: io::Error) -> Self { + Error::Io(IoError(e)) + } +} + +impl From for Error { + fn from(e: sec1::Error) -> Self { + Error::Sec1(e) + } +} + +#[derive(Debug, Error)] +#[error("{0}")] +pub struct P256Error(#[source] p256::elliptic_curve::Error); + +impl PartialEq for P256Error { + fn eq(&self, _: &Self) -> bool { + false + } +} + +impl From for Error { + fn from(e: p256::elliptic_curve::Error) -> Self { + Error::P256(P256Error(e)) + } +} + +// Because Tokio SendError is parameterized, we sadly lose the backtrace. +impl From> for Error { + fn from(e: MpscSendError) -> Self { + Error::MpscSend(e.to_string()) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_server_name.rs b/vendor/webrtc-dtls/src/extension/extension_server_name.rs new file mode 100644 index 0000000..dbe018e --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_server_name.rs @@ -0,0 +1,56 @@ +#[cfg(test)] +mod extension_server_name_test; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::*; + +const EXTENSION_SERVER_NAME_TYPE_DNSHOST_NAME: u8 = 0; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionServerName { + pub(crate) server_name: String, +} + +impl ExtensionServerName { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::ServerName + } + + pub fn size(&self) -> usize { + //TODO: check how to do cryptobyte? + 2 + 2 + 1 + 2 + self.server_name.as_bytes().len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + //TODO: check how to do cryptobyte? + writer.write_u16::(2 + 1 + 2 + self.server_name.len() as u16)?; + writer.write_u16::(1 + 2 + self.server_name.len() as u16)?; + writer.write_u8(EXTENSION_SERVER_NAME_TYPE_DNSHOST_NAME)?; + writer.write_u16::(self.server_name.len() as u16)?; + writer.write_all(self.server_name.as_bytes())?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + //TODO: check how to do cryptobyte? + let _ = reader.read_u16::()? as usize; + let _ = reader.read_u16::()? as usize; + + let name_type = reader.read_u8()?; + if name_type != EXTENSION_SERVER_NAME_TYPE_DNSHOST_NAME { + return Err(Error::ErrInvalidSniFormat); + } + + let buf_len = reader.read_u16::()? as usize; + let mut buf: Vec = vec![0u8; buf_len]; + reader.read_exact(&mut buf)?; + + let server_name = String::from_utf8(buf)?; + + Ok(ExtensionServerName { server_name }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_server_name/extension_server_name_test.rs b/vendor/webrtc-dtls/src/extension/extension_server_name/extension_server_name_test.rs new file mode 100644 index 0000000..4cfb7a1 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_server_name/extension_server_name_test.rs @@ -0,0 +1,26 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_server_name() -> Result<()> { + let extension = ExtensionServerName { + server_name: "test.domain".to_owned(), + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + extension.marshal(&mut writer)?; + } + + let mut reader = BufReader::new(raw.as_slice()); + let new_extension = ExtensionServerName::unmarshal(&mut reader)?; + + assert_eq!( + new_extension, extension, + "extensionServerName marshal: got {new_extension:?} expected {extension:?}", + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves.rs b/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves.rs new file mode 100644 index 0000000..88caf6f --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves.rs @@ -0,0 +1,46 @@ +#[cfg(test)] +mod extension_supported_elliptic_curves_test; + +use super::*; +use crate::curve::named_curve::*; + +const EXTENSION_SUPPORTED_GROUPS_HEADER_SIZE: usize = 6; + +// https://tools.ietf.org/html/rfc8422#section-5.1.1 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionSupportedEllipticCurves { + pub elliptic_curves: Vec, +} + +impl ExtensionSupportedEllipticCurves { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::SupportedEllipticCurves + } + + pub fn size(&self) -> usize { + 2 + 2 + self.elliptic_curves.len() * 2 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::(2 + 2 * self.elliptic_curves.len() as u16)?; + writer.write_u16::(2 * self.elliptic_curves.len() as u16)?; + for v in &self.elliptic_curves { + writer.write_u16::(*v as u16)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let _ = reader.read_u16::()?; + + let group_count = reader.read_u16::()? as usize / 2; + let mut elliptic_curves = vec![]; + for _ in 0..group_count { + let elliptic_curve = reader.read_u16::()?.into(); + elliptic_curves.push(elliptic_curve); + } + + Ok(ExtensionSupportedEllipticCurves { elliptic_curves }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves/extension_supported_elliptic_curves_test.rs b/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves/extension_supported_elliptic_curves_test.rs new file mode 100644 index 0000000..2bcf70c --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_elliptic_curves/extension_supported_elliptic_curves_test.rs @@ -0,0 +1,32 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_supported_groups() -> Result<()> { + let raw_supported_groups = vec![0x0, 0x4, 0x0, 0x2, 0x0, 0x1d]; // 0x0, 0xa, + let parsed_supported_groups = ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::X25519], + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + parsed_supported_groups.marshal(&mut writer)?; + } + + assert_eq!( + raw, raw_supported_groups, + "extensionSupportedGroups marshal: got {raw:?}, want {raw_supported_groups:?}" + ); + + let mut reader = BufReader::new(raw.as_slice()); + let new_supported_groups = ExtensionSupportedEllipticCurves::unmarshal(&mut reader)?; + + assert_eq!( + new_supported_groups, parsed_supported_groups, + "extensionSupportedGroups unmarshal: got {new_supported_groups:?}, want {parsed_supported_groups:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_point_formats.rs b/vendor/webrtc-dtls/src/extension/extension_supported_point_formats.rs new file mode 100644 index 0000000..17e2448 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_point_formats.rs @@ -0,0 +1,49 @@ +#[cfg(test)] +mod extension_supported_point_formats_test; + +use super::*; + +const EXTENSION_SUPPORTED_POINT_FORMATS_SIZE: usize = 5; + +pub type EllipticCurvePointFormat = u8; + +pub const ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED: EllipticCurvePointFormat = 0; + +// https://tools.ietf.org/html/rfc4492#section-5.1.2 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionSupportedPointFormats { + pub(crate) point_formats: Vec, +} + +impl ExtensionSupportedPointFormats { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::SupportedPointFormats + } + + pub fn size(&self) -> usize { + 2 + 1 + self.point_formats.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::(1 + self.point_formats.len() as u16)?; + writer.write_u8(self.point_formats.len() as u8)?; + for v in &self.point_formats { + writer.write_u8(*v)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let _ = reader.read_u16::()?; + + let point_format_count = reader.read_u8()? as usize; + let mut point_formats = vec![]; + for _ in 0..point_format_count { + let point_format = reader.read_u8()?; + point_formats.push(point_format); + } + + Ok(ExtensionSupportedPointFormats { point_formats }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_point_formats/extension_supported_point_formats_test.rs b/vendor/webrtc-dtls/src/extension/extension_supported_point_formats/extension_supported_point_formats_test.rs new file mode 100644 index 0000000..e624a98 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_point_formats/extension_supported_point_formats_test.rs @@ -0,0 +1,33 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_supported_point_formats() -> Result<()> { + let raw_extension_supported_point_formats = vec![0x00, 0x02, 0x01, 0x00]; // 0x00, 0x0b, + let parsed_extension_supported_point_formats = ExtensionSupportedPointFormats { + point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED], + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + parsed_extension_supported_point_formats.marshal(&mut writer)?; + } + + assert_eq!( + raw, raw_extension_supported_point_formats, + "extensionSupportedPointFormats marshal: got {raw:?}, want {raw_extension_supported_point_formats:?}" + ); + + let mut reader = BufReader::new(raw.as_slice()); + let new_extension_supported_point_formats = + ExtensionSupportedPointFormats::unmarshal(&mut reader)?; + + assert_eq!( + new_extension_supported_point_formats, parsed_extension_supported_point_formats, + "extensionSupportedPointFormats unmarshal: got {new_extension_supported_point_formats:?}, want {parsed_extension_supported_point_formats:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms.rs b/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms.rs new file mode 100644 index 0000000..e15210b --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms.rs @@ -0,0 +1,50 @@ +#[cfg(test)] +mod extension_supported_signature_algorithms_test; + +use super::*; +use crate::signature_hash_algorithm::*; + +const EXTENSION_SUPPORTED_SIGNATURE_ALGORITHMS_HEADER_SIZE: usize = 6; + +// https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionSupportedSignatureAlgorithms { + pub(crate) signature_hash_algorithms: Vec, +} + +impl ExtensionSupportedSignatureAlgorithms { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::SupportedSignatureAlgorithms + } + + pub fn size(&self) -> usize { + 2 + 2 + self.signature_hash_algorithms.len() * 2 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::(2 + 2 * self.signature_hash_algorithms.len() as u16)?; + writer.write_u16::(2 * self.signature_hash_algorithms.len() as u16)?; + for v in &self.signature_hash_algorithms { + writer.write_u8(v.hash as u8)?; + writer.write_u8(v.signature as u8)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let _ = reader.read_u16::()?; + + let algorithm_count = reader.read_u16::()? as usize / 2; + let mut signature_hash_algorithms = vec![]; + for _ in 0..algorithm_count { + let hash = reader.read_u8()?.into(); + let signature = reader.read_u8()?.into(); + signature_hash_algorithms.push(SignatureHashAlgorithm { hash, signature }); + } + + Ok(ExtensionSupportedSignatureAlgorithms { + signature_hash_algorithms, + }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms/extension_supported_signature_algorithms_test.rs b/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms/extension_supported_signature_algorithms_test.rs new file mode 100644 index 0000000..e531fee --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_supported_signature_algorithms/extension_supported_signature_algorithms_test.rs @@ -0,0 +1,48 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_supported_signature_algorithms() -> Result<()> { + let raw_extension_supported_signature_algorithms = + vec![0x00, 0x08, 0x00, 0x06, 0x04, 0x03, 0x05, 0x03, 0x06, 0x03]; //0x00, 0x0d, + let parsed_extension_supported_signature_algorithms = ExtensionSupportedSignatureAlgorithms { + signature_hash_algorithms: vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Ecdsa, + }, + ], + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + parsed_extension_supported_signature_algorithms.marshal(&mut writer)?; + } + + assert_eq!( + raw, raw_extension_supported_signature_algorithms, + "extensionSupportedSignatureAlgorithms marshal: got {raw:?}, want {raw_extension_supported_signature_algorithms:?}" + ); + + let mut reader = BufReader::new(raw.as_slice()); + let new_extension_supported_signature_algorithms = + ExtensionSupportedSignatureAlgorithms::unmarshal(&mut reader)?; + + assert_eq!( + new_extension_supported_signature_algorithms, + parsed_extension_supported_signature_algorithms, + "extensionSupportedSignatureAlgorithms unmarshal: got {new_extension_supported_signature_algorithms:?}, want {parsed_extension_supported_signature_algorithms:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret.rs b/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret.rs new file mode 100644 index 0000000..9d62c4e --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret.rs @@ -0,0 +1,35 @@ +#[cfg(test)] +mod extension_use_extended_master_secret_test; + +use super::*; + +const EXTENSION_USE_EXTENDED_MASTER_SECRET_HEADER_SIZE: usize = 4; + +// https://tools.ietf.org/html/rfc8422 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionUseExtendedMasterSecret { + pub(crate) supported: bool, +} + +impl ExtensionUseExtendedMasterSecret { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::UseExtendedMasterSecret + } + + pub fn size(&self) -> usize { + 2 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + // length + writer.write_u16::(0)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let _ = reader.read_u16::()?; + + Ok(ExtensionUseExtendedMasterSecret { supported: true }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret/extension_use_extended_master_secret_test.rs b/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret/extension_use_extended_master_secret_test.rs new file mode 100644 index 0000000..d2b0dd4 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_use_extended_master_secret/extension_use_extended_master_secret_test.rs @@ -0,0 +1,32 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_use_extended_master_secret() -> Result<()> { + let raw_extension_use_extended_master_secret = vec![0x00, 0x00]; + let parsed_extension_use_extended_master_secret = + ExtensionUseExtendedMasterSecret { supported: true }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + parsed_extension_use_extended_master_secret.marshal(&mut writer)?; + } + + assert_eq!( + raw, raw_extension_use_extended_master_secret, + "extension_use_extended_master_secret marshal: got {raw:?}, want {raw_extension_use_extended_master_secret:?}" + ); + + let mut reader = BufReader::new(raw.as_slice()); + let new_extension_use_extended_master_secret = + ExtensionUseExtendedMasterSecret::unmarshal(&mut reader)?; + + assert_eq!( + new_extension_use_extended_master_secret, parsed_extension_use_extended_master_secret, + "extension_use_extended_master_secret unmarshal: got {new_extension_use_extended_master_secret:?}, want {parsed_extension_use_extended_master_secret:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/extension_use_srtp.rs b/vendor/webrtc-dtls/src/extension/extension_use_srtp.rs new file mode 100644 index 0000000..b8620d7 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_use_srtp.rs @@ -0,0 +1,80 @@ +#[cfg(test)] +mod extension_use_srtp_test; + +use super::*; + +// SRTPProtectionProfile defines the parameters and options that are in effect for the SRTP processing +// https://tools.ietf.org/html/rfc5764#section-4.1.2 +#[allow(non_camel_case_types)] +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum SrtpProtectionProfile { + Srtp_Aes128_Cm_Hmac_Sha1_80 = 0x0001, + Srtp_Aes128_Cm_Hmac_Sha1_32 = 0x0002, + Srtp_Aead_Aes_128_Gcm = 0x0007, + Srtp_Aead_Aes_256_Gcm = 0x0008, + Unsupported, +} + +impl From for SrtpProtectionProfile { + fn from(val: u16) -> Self { + match val { + 0x0001 => SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80, + 0x0002 => SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_32, + 0x0007 => SrtpProtectionProfile::Srtp_Aead_Aes_128_Gcm, + 0x0008 => SrtpProtectionProfile::Srtp_Aead_Aes_256_Gcm, + _ => SrtpProtectionProfile::Unsupported, + } + } +} + +const EXTENSION_USE_SRTPHEADER_SIZE: usize = 6; + +// https://tools.ietf.org/html/rfc8422 +#[allow(non_camel_case_types)] +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionUseSrtp { + pub(crate) protection_profiles: Vec, +} + +impl ExtensionUseSrtp { + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::UseSrtp + } + + pub fn size(&self) -> usize { + 2 + 2 + self.protection_profiles.len() * 2 + 1 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::( + 2 + /* MKI Length */ 1 + 2 * self.protection_profiles.len() as u16, + )?; + writer.write_u16::(2 * self.protection_profiles.len() as u16)?; + for v in &self.protection_profiles { + writer.write_u16::(*v as u16)?; + } + + /* MKI Length */ + writer.write_u8(0x00)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let _ = reader.read_u16::()?; + + let profile_count = reader.read_u16::()? as usize / 2; + let mut protection_profiles = vec![]; + for _ in 0..profile_count { + let protection_profile = reader.read_u16::()?.into(); + protection_profiles.push(protection_profile); + } + + /* MKI Length */ + let _ = reader.read_u8()?; + + Ok(ExtensionUseSrtp { + protection_profiles, + }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/extension_use_srtp/extension_use_srtp_test.rs b/vendor/webrtc-dtls/src/extension/extension_use_srtp/extension_use_srtp_test.rs new file mode 100644 index 0000000..c58ba56 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/extension_use_srtp/extension_use_srtp_test.rs @@ -0,0 +1,32 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_extension_use_srtp() -> Result<()> { + let raw_use_srtp = vec![0x00, 0x05, 0x00, 0x02, 0x00, 0x01, 0x00]; //0x00, 0x0e, + let parsed_use_srtp = ExtensionUseSrtp { + protection_profiles: vec![SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80], + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + parsed_use_srtp.marshal(&mut writer)?; + } + + assert_eq!( + raw, raw_use_srtp, + "extensionUseSRTP marshal: got {raw:?}, want {raw_use_srtp:?}" + ); + + let mut reader = BufReader::new(raw.as_slice()); + let new_use_srtp = ExtensionUseSrtp::unmarshal(&mut reader)?; + + assert_eq!( + new_use_srtp, parsed_use_srtp, + "extensionUseSRTP unmarshal: got {new_use_srtp:?}, want {parsed_use_srtp:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/extension/mod.rs b/vendor/webrtc-dtls/src/extension/mod.rs new file mode 100644 index 0000000..2030038 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/mod.rs @@ -0,0 +1,130 @@ +pub mod extension_server_name; +pub mod extension_supported_elliptic_curves; +pub mod extension_supported_point_formats; +pub mod extension_supported_signature_algorithms; +pub mod extension_use_extended_master_secret; +pub mod extension_use_srtp; +pub mod renegotiation_info; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use extension_server_name::*; +use extension_supported_elliptic_curves::*; +use extension_supported_point_formats::*; +use extension_supported_signature_algorithms::*; +use extension_use_extended_master_secret::*; +use extension_use_srtp::*; + +use crate::error::*; +use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; + +// https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ExtensionValue { + ServerName = 0, + SupportedEllipticCurves = 10, + SupportedPointFormats = 11, + SupportedSignatureAlgorithms = 13, + UseSrtp = 14, + UseExtendedMasterSecret = 23, + RenegotiationInfo = 65281, + Unsupported, +} + +impl From for ExtensionValue { + fn from(val: u16) -> Self { + match val { + 0 => ExtensionValue::ServerName, + 10 => ExtensionValue::SupportedEllipticCurves, + 11 => ExtensionValue::SupportedPointFormats, + 13 => ExtensionValue::SupportedSignatureAlgorithms, + 14 => ExtensionValue::UseSrtp, + 23 => ExtensionValue::UseExtendedMasterSecret, + 65281 => ExtensionValue::RenegotiationInfo, + _ => ExtensionValue::Unsupported, + } + } +} + +#[derive(PartialEq, Eq, Debug, Clone)] +pub enum Extension { + ServerName(ExtensionServerName), + SupportedEllipticCurves(ExtensionSupportedEllipticCurves), + SupportedPointFormats(ExtensionSupportedPointFormats), + SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms), + UseSrtp(ExtensionUseSrtp), + UseExtendedMasterSecret(ExtensionUseExtendedMasterSecret), + RenegotiationInfo(ExtensionRenegotiationInfo), +} + +impl Extension { + pub fn extension_value(&self) -> ExtensionValue { + match self { + Extension::ServerName(ext) => ext.extension_value(), + Extension::SupportedEllipticCurves(ext) => ext.extension_value(), + Extension::SupportedPointFormats(ext) => ext.extension_value(), + Extension::SupportedSignatureAlgorithms(ext) => ext.extension_value(), + Extension::UseSrtp(ext) => ext.extension_value(), + Extension::UseExtendedMasterSecret(ext) => ext.extension_value(), + Extension::RenegotiationInfo(ext) => ext.extension_value(), + } + } + + pub fn size(&self) -> usize { + let mut len = 2; + + len += match self { + Extension::ServerName(ext) => ext.size(), + Extension::SupportedEllipticCurves(ext) => ext.size(), + Extension::SupportedPointFormats(ext) => ext.size(), + Extension::SupportedSignatureAlgorithms(ext) => ext.size(), + Extension::UseSrtp(ext) => ext.size(), + Extension::UseExtendedMasterSecret(ext) => ext.size(), + Extension::RenegotiationInfo(ext) => ext.size(), + }; + + len + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::(self.extension_value() as u16)?; + match self { + Extension::ServerName(ext) => ext.marshal(writer), + Extension::SupportedEllipticCurves(ext) => ext.marshal(writer), + Extension::SupportedPointFormats(ext) => ext.marshal(writer), + Extension::SupportedSignatureAlgorithms(ext) => ext.marshal(writer), + Extension::UseSrtp(ext) => ext.marshal(writer), + Extension::UseExtendedMasterSecret(ext) => ext.marshal(writer), + Extension::RenegotiationInfo(ext) => ext.marshal(writer), + } + } + + pub fn unmarshal(reader: &mut R) -> Result { + let extension_value: ExtensionValue = reader.read_u16::()?.into(); + match extension_value { + ExtensionValue::ServerName => Ok(Extension::ServerName( + ExtensionServerName::unmarshal(reader)?, + )), + ExtensionValue::SupportedEllipticCurves => Ok(Extension::SupportedEllipticCurves( + ExtensionSupportedEllipticCurves::unmarshal(reader)?, + )), + ExtensionValue::SupportedPointFormats => Ok(Extension::SupportedPointFormats( + ExtensionSupportedPointFormats::unmarshal(reader)?, + )), + ExtensionValue::SupportedSignatureAlgorithms => { + Ok(Extension::SupportedSignatureAlgorithms( + ExtensionSupportedSignatureAlgorithms::unmarshal(reader)?, + )) + } + ExtensionValue::UseSrtp => Ok(Extension::UseSrtp(ExtensionUseSrtp::unmarshal(reader)?)), + ExtensionValue::UseExtendedMasterSecret => Ok(Extension::UseExtendedMasterSecret( + ExtensionUseExtendedMasterSecret::unmarshal(reader)?, + )), + ExtensionValue::RenegotiationInfo => Ok(Extension::RenegotiationInfo( + ExtensionRenegotiationInfo::unmarshal(reader)?, + )), + _ => Err(Error::ErrInvalidExtensionType), + } + } +} diff --git a/vendor/webrtc-dtls/src/extension/renegotiation_info.rs b/vendor/webrtc-dtls/src/extension/renegotiation_info.rs new file mode 100644 index 0000000..ab3d29a --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/renegotiation_info.rs @@ -0,0 +1,48 @@ +#[cfg(test)] +mod renegotiation_info_test; + +use super::*; +use crate::error::Error::ErrInvalidPacketLength; + +const RENEGOTIATION_INFO_HEADER_SIZE: usize = 5; + +/// RenegotiationInfo allows a Client/Server to +/// communicate their renegotiation support +/// https://tools.ietf.org/html/rfc5746 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ExtensionRenegotiationInfo { + pub(crate) renegotiated_connection: u8, +} + +impl ExtensionRenegotiationInfo { + // TypeValue returns the extension TypeValue + pub fn extension_value(&self) -> ExtensionValue { + ExtensionValue::RenegotiationInfo + } + + pub fn size(&self) -> usize { + 3 + } + + /// marshal encodes the extension + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u16::(1)?; //length + writer.write_u8(self.renegotiated_connection)?; + + Ok(writer.flush()?) + } + + /// Unmarshal populates the extension from encoded data + pub fn unmarshal(reader: &mut R) -> Result { + let l = reader.read_u16::()?; //length + if l != 1 { + return Err(ErrInvalidPacketLength); + } + + let renegotiated_connection = reader.read_u8()?; + + Ok(ExtensionRenegotiationInfo { + renegotiated_connection, + }) + } +} diff --git a/vendor/webrtc-dtls/src/extension/renegotiation_info/renegotiation_info_test.rs b/vendor/webrtc-dtls/src/extension/renegotiation_info/renegotiation_info_test.rs new file mode 100644 index 0000000..5266a94 --- /dev/null +++ b/vendor/webrtc-dtls/src/extension/renegotiation_info/renegotiation_info_test.rs @@ -0,0 +1,26 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_renegotiation_info() -> Result<()> { + let extension = ExtensionRenegotiationInfo { + renegotiated_connection: 0, + }; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + extension.marshal(&mut writer)?; + } + + let mut reader = BufReader::new(raw.as_slice()); + let new_extension = ExtensionRenegotiationInfo::unmarshal(&mut reader)?; + + assert_eq!( + new_extension.renegotiated_connection, + extension.renegotiated_connection + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/flight/flight0.rs b/vendor/webrtc-dtls/src/flight/flight0.rs new file mode 100644 index 0000000..2b69dd7 --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight0.rs @@ -0,0 +1,203 @@ +use std::fmt; +use std::sync::atomic::Ordering; + +use async_trait::async_trait; +use rand::Rng; + +use super::flight2::*; +use super::*; +use crate::config::*; +use crate::conn::*; +use crate::error::Error; +use crate::extension::*; +use crate::handshake::*; +use crate::record_layer::record_layer_header::*; +use crate::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight0; + +impl fmt::Display for Flight0 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 0") + } +} + +#[async_trait] +impl Flight for Flight0 { + async fn parse( + &self, + _tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let (seq, msgs) = match cache + .full_pull_map( + 0, + &[HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }], + ) + .await + { + Ok((seq, msgs)) => (seq, msgs), + Err(_) => return Err((None, None)), + }; + + state.handshake_recv_sequence = seq; + + if let Some(message) = msgs.get(&HandshakeType::ClientHello) { + // Validate type + let client_hello = match message { + HandshakeMessage::ClientHello(client_hello) => client_hello, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if client_hello.version != PROTOCOL_VERSION1_2 { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::ProtocolVersion, + }), + Some(Error::ErrUnsupportedProtocolVersion), + )); + } + + state.remote_random = client_hello.random.clone(); + + if let Ok(id) = + find_matching_cipher_suite(&client_hello.cipher_suites, &cfg.local_cipher_suites) + { + if let Ok(cipher_suite) = cipher_suite_for_id(id) { + log::debug!( + "[handshake:{}] use cipher suite: {}", + srv_cli_str(state.is_client), + cipher_suite.to_string() + ); + let mut cs = state.cipher_suite.lock().await; + *cs = Some(cipher_suite); + } + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrCipherSuiteNoIntersection), + )); + } + + for extension in &client_hello.extensions { + match extension { + Extension::SupportedEllipticCurves(e) => { + if e.elliptic_curves.is_empty() { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrNoSupportedEllipticCurves), + )); + } + state.named_curve = e.elliptic_curves[0]; + } + Extension::UseSrtp(e) => { + if let Ok(profile) = find_matching_srtp_profile( + &e.protection_profiles, + &cfg.local_srtp_protection_profiles, + ) { + state.srtp_protection_profile = profile; + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrServerNoMatchingSrtpProfile), + )); + } + } + Extension::UseExtendedMasterSecret(_) => { + if cfg.extended_master_secret != ExtendedMasterSecretType::Disable { + state.extended_master_secret = true; + } + } + Extension::ServerName(e) => { + state.server_name = e.server_name.clone(); // remote server name + } + _ => {} + } + } + + if cfg.extended_master_secret == ExtendedMasterSecretType::Require + && !state.extended_master_secret + { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrServerRequiredButNoClientEms), + )); + } + + if state.local_keypair.is_none() { + state.local_keypair = match state.named_curve.generate_keypair() { + Ok(local_keypar) => Some(local_keypar), + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::IllegalParameter, + }), + Some(err), + )) + } + }; + } + + Ok(Box::new(Flight2 {})) + } else { + Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + } + + async fn generate( + &self, + state: &mut State, + _cache: &HandshakeCache, + _cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + // Initialize + state.cookie = vec![0; COOKIE_LENGTH]; + rand::thread_rng().fill(state.cookie.as_mut_slice()); + + //TODO: figure out difference between golang's atom store and rust atom store + let zero_epoch = 0; + state.local_epoch.store(zero_epoch, Ordering::SeqCst); + state.remote_epoch.store(zero_epoch, Ordering::SeqCst); + + state.named_curve = DEFAULT_NAMED_CURVE; + state.local_random.populate(); + + Ok(vec![]) + } +} diff --git a/vendor/webrtc-dtls/src/flight/flight1.rs b/vendor/webrtc-dtls/src/flight/flight1.rs new file mode 100644 index 0000000..d404571 --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight1.rs @@ -0,0 +1,193 @@ +use std::fmt; +use std::sync::atomic::Ordering; + +use async_trait::async_trait; + +use super::flight3::*; +use super::*; +use crate::compression_methods::*; +use crate::config::*; +use crate::conn::*; +use crate::content::*; +use crate::curve::named_curve::*; +use crate::error::Error; +use crate::extension::extension_server_name::*; +use crate::extension::extension_supported_elliptic_curves::*; +use crate::extension::extension_supported_point_formats::*; +use crate::extension::extension_supported_signature_algorithms::*; +use crate::extension::extension_use_extended_master_secret::*; +use crate::extension::extension_use_srtp::*; +use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; +use crate::extension::*; +use crate::handshake::handshake_message_client_hello::*; +use crate::handshake::*; +use crate::record_layer::record_layer_header::*; +use crate::record_layer::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight1; + +impl fmt::Display for Flight1 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 1") + } +} + +#[async_trait] +impl Flight for Flight1 { + async fn parse( + &self, + tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + // HelloVerifyRequest can be skipped by the server, + // so allow ServerHello during flight1 also + let (seq, msgs) = match cache + .full_pull_map( + state.handshake_recv_sequence, + &[ + HandshakeCachePullRule { + typ: HandshakeType::HelloVerifyRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }, + ], + ) + .await + { + // No valid message received. Keep reading + Ok((seq, msgs)) => (seq, msgs), + Err(_) => return Err((None, None)), + }; + + if msgs.contains_key(&HandshakeType::ServerHello) { + // Flight1 and flight2 were skipped. + // Parse as flight3. + let flight3 = Flight3 {}; + return flight3.parse(tx, state, cache, cfg).await; + } + + if let Some(message) = msgs.get(&HandshakeType::HelloVerifyRequest) { + // DTLS 1.2 clients must not assume that the server will use the protocol version + // specified in HelloVerifyRequest message. RFC 6347 Section 4.2.1 + let h = match message { + HandshakeMessage::HelloVerifyRequest(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if h.version != PROTOCOL_VERSION1_0 && h.version != PROTOCOL_VERSION1_2 { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::ProtocolVersion, + }), + Some(Error::ErrUnsupportedProtocolVersion), + )); + } + + state.cookie = h.cookie.clone(); + state.handshake_recv_sequence = seq; + Ok(Box::new(Flight3 {})) + } else { + Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + } + + async fn generate( + &self, + state: &mut State, + _cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let zero_epoch = 0; + state.local_epoch.store(zero_epoch, Ordering::SeqCst); + state.remote_epoch.store(zero_epoch, Ordering::SeqCst); + + state.named_curve = DEFAULT_NAMED_CURVE; + state.cookie = vec![]; + state.local_random.populate(); + + let mut extensions = vec![ + Extension::SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms { + signature_hash_algorithms: cfg.local_signature_schemes.clone(), + }), + Extension::RenegotiationInfo(ExtensionRenegotiationInfo { + renegotiated_connection: 0, + }), + ]; + + if cfg.local_psk_callback.is_none() { + extensions.extend_from_slice(&[ + Extension::SupportedEllipticCurves(ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::P256, NamedCurve::X25519, NamedCurve::P384], + }), + Extension::SupportedPointFormats(ExtensionSupportedPointFormats { + point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED], + }), + ]); + } + + if !cfg.local_srtp_protection_profiles.is_empty() { + extensions.push(Extension::UseSrtp(ExtensionUseSrtp { + protection_profiles: cfg.local_srtp_protection_profiles.clone(), + })); + } + + if cfg.extended_master_secret == ExtendedMasterSecretType::Request + || cfg.extended_master_secret == ExtendedMasterSecretType::Require + { + extensions.push(Extension::UseExtendedMasterSecret( + ExtensionUseExtendedMasterSecret { supported: true }, + )); + } + + if !cfg.server_name.is_empty() { + extensions.push(Extension::ServerName(ExtensionServerName { + server_name: cfg.server_name.clone(), + })); + } + + Ok(vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + random: state.local_random.clone(), + cookie: state.cookie.clone(), + + cipher_suites: cfg.local_cipher_suites.clone(), + compression_methods: default_compression_methods(), + extensions, + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]) + } +} diff --git a/vendor/webrtc-dtls/src/flight/flight2.rs b/vendor/webrtc-dtls/src/flight/flight2.rs new file mode 100644 index 0000000..9703c9a --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight2.rs @@ -0,0 +1,131 @@ +use std::fmt; + +use async_trait::async_trait; + +use super::flight0::*; +use super::flight4::*; +use super::*; +use crate::content::*; +use crate::error::Error; +use crate::handshake::handshake_message_hello_verify_request::*; +use crate::handshake::*; +use crate::record_layer::record_layer_header::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight2; + +impl fmt::Display for Flight2 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 2") + } +} + +#[async_trait] +impl Flight for Flight2 { + fn has_retransmit(&self) -> bool { + false + } + + async fn parse( + &self, + tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let (seq, msgs) = match cache + .full_pull_map( + state.handshake_recv_sequence, + &[HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }], + ) + .await + { + // No valid message received. Keep reading + Ok((seq, msgs)) => (seq, msgs), + + // Client may retransmit the first ClientHello when HelloVerifyRequest is dropped. + // Parse as flight 0 in this case. + Err(_) => return Flight0 {}.parse(tx, state, cache, cfg).await, + }; + + state.handshake_recv_sequence = seq; + + if let Some(message) = msgs.get(&HandshakeType::ClientHello) { + // Validate type + let client_hello = match message { + HandshakeMessage::ClientHello(client_hello) => client_hello, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if client_hello.version != PROTOCOL_VERSION1_2 { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::ProtocolVersion, + }), + Some(Error::ErrUnsupportedProtocolVersion), + )); + } + + if client_hello.cookie.is_empty() { + return Err((None, None)); + } + + if state.cookie != client_hello.cookie { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::AccessDenied, + }), + Some(Error::ErrCookieMismatch), + )); + } + + Ok(Box::new(Flight4 {})) + } else { + Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + } + + async fn generate( + &self, + state: &mut State, + _cache: &HandshakeCache, + _cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + state.handshake_send_sequence = 0; + Ok(vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::HelloVerifyRequest( + HandshakeMessageHelloVerifyRequest { + version: PROTOCOL_VERSION1_2, + cookie: state.cookie.clone(), + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]) + } +} diff --git a/vendor/webrtc-dtls/src/flight/flight3.rs b/vendor/webrtc-dtls/src/flight/flight3.rs new file mode 100644 index 0000000..511de66 --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight3.rs @@ -0,0 +1,470 @@ +use std::fmt; + +use async_trait::async_trait; +use log::*; + +use super::flight5::*; +use super::*; +use crate::cipher_suite::cipher_suite_for_id; +use crate::compression_methods::*; +use crate::config::*; +use crate::content::*; +use crate::curve::named_curve::*; +use crate::error::Error; +use crate::extension::extension_server_name::*; +use crate::extension::extension_supported_elliptic_curves::*; +use crate::extension::extension_supported_point_formats::*; +use crate::extension::extension_supported_signature_algorithms::*; +use crate::extension::extension_use_extended_master_secret::*; +use crate::extension::extension_use_srtp::*; +use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; +use crate::extension::*; +use crate::handshake::handshake_message_client_hello::*; +use crate::handshake::handshake_message_server_key_exchange::*; +use crate::handshake::*; +use crate::prf::{prf_pre_master_secret, prf_psk_pre_master_secret}; +use crate::record_layer::record_layer_header::*; +use crate::record_layer::*; +use crate::{find_matching_cipher_suite, find_matching_srtp_profile}; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight3; + +impl fmt::Display for Flight3 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 3") + } +} + +#[async_trait] +impl Flight for Flight3 { + async fn parse( + &self, + _tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + // Clients may receive multiple HelloVerifyRequest messages with different cookies. + // Clients SHOULD handle this by sending a new ClientHello with a cookie in response + // to the new HelloVerifyRequest. RFC 6347 Section 4.2.1 + if let Ok((seq, msgs)) = cache + .full_pull_map( + state.handshake_recv_sequence, + &[HandshakeCachePullRule { + typ: HandshakeType::HelloVerifyRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }], + ) + .await + { + if let Some(message) = msgs.get(&HandshakeType::HelloVerifyRequest) { + // DTLS 1.2 clients must not assume that the server will use the protocol version + // specified in HelloVerifyRequest message. RFC 6347 Section 4.2.1 + let h = match message { + HandshakeMessage::HelloVerifyRequest(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + // DTLS 1.2 clients must not assume that the server will use the protocol version + // specified in HelloVerifyRequest message. RFC 6347 Section 4.2.1 + if h.version != PROTOCOL_VERSION1_0 && h.version != PROTOCOL_VERSION1_2 { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::ProtocolVersion, + }), + Some(Error::ErrUnsupportedProtocolVersion), + )); + } + + state.cookie = h.cookie.clone(); + state.handshake_recv_sequence = seq; + return Ok(Box::new(Flight3 {}) as Box); + } + } + + let result = if cfg.local_psk_callback.is_some() { + cache + .full_pull_map( + state.handshake_recv_sequence, + &[ + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + ], + ) + .await + } else { + cache + .full_pull_map( + state.handshake_recv_sequence, + &[ + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: true, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + ], + ) + .await + }; + + let (seq, msgs) = match result { + Ok((seq, msgs)) => (seq, msgs), + Err(_) => return Err((None, None)), + }; + + state.handshake_recv_sequence = seq; + + if let Some(message) = msgs.get(&HandshakeType::ServerHello) { + let h = match message { + HandshakeMessage::ServerHello(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if h.version != PROTOCOL_VERSION1_2 { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::ProtocolVersion, + }), + Some(Error::ErrUnsupportedProtocolVersion), + )); + } + + for extension in &h.extensions { + match extension { + Extension::UseSrtp(e) => { + let profile = match find_matching_srtp_profile( + &e.protection_profiles, + &cfg.local_srtp_protection_profiles, + ) { + Ok(profile) => profile, + Err(_) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::IllegalParameter, + }), + Some(Error::ErrClientNoMatchingSrtpProfile), + )) + } + }; + state.srtp_protection_profile = profile; + } + Extension::UseExtendedMasterSecret(_) => { + if cfg.extended_master_secret != ExtendedMasterSecretType::Disable { + state.extended_master_secret = true; + } + } + _ => {} + }; + } + + if cfg.extended_master_secret == ExtendedMasterSecretType::Require + && !state.extended_master_secret + { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrClientRequiredButNoServerEms), + )); + } + if !cfg.local_srtp_protection_profiles.is_empty() + && state.srtp_protection_profile == SrtpProtectionProfile::Unsupported + { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrRequestedButNoSrtpExtension), + )); + } + if find_matching_cipher_suite(&[h.cipher_suite], &cfg.local_cipher_suites).is_err() { + debug!( + "[handshake:{}] use cipher suite: {}", + srv_cli_str(state.is_client), + h.cipher_suite + ); + + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrCipherSuiteNoIntersection), + )); + } + + let cipher_suite = match cipher_suite_for_id(h.cipher_suite) { + Ok(cipher_suite) => cipher_suite, + Err(_) => { + debug!( + "[handshake:{}] use cipher suite: {}", + srv_cli_str(state.is_client), + h.cipher_suite + ); + + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrInvalidCipherSuite), + )); + } + }; + + trace!( + "[handshake:{}] use cipher suite: {}", + srv_cli_str(state.is_client), + cipher_suite.to_string() + ); + { + let mut cs = state.cipher_suite.lock().await; + *cs = Some(cipher_suite); + } + state.remote_random = h.random.clone(); + } + + if let Some(message) = msgs.get(&HandshakeType::Certificate) { + let h = match message { + HandshakeMessage::Certificate(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + state.peer_certificates = h.certificate.clone(); + } + + if let Some(message) = msgs.get(&HandshakeType::ServerKeyExchange) { + let h = match message { + HandshakeMessage::ServerKeyExchange(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if let Err((alert, err)) = handle_server_key_exchange(state, cfg, h) { + return Err((alert, err)); + } + } + + if let Some(message) = msgs.get(&HandshakeType::CertificateRequest) { + match message { + HandshakeMessage::CertificateRequest(_) => {} + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + state.remote_requested_certificate = true; + } + + Ok(Box::new(Flight5 {}) as Box) + } + + async fn generate( + &self, + state: &mut State, + _cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let mut extensions = vec![ + Extension::SupportedSignatureAlgorithms(ExtensionSupportedSignatureAlgorithms { + signature_hash_algorithms: cfg.local_signature_schemes.clone(), + }), + Extension::RenegotiationInfo(ExtensionRenegotiationInfo { + renegotiated_connection: 0, + }), + ]; + + if cfg.local_psk_callback.is_none() { + extensions.extend_from_slice(&[ + Extension::SupportedEllipticCurves(ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::P256, NamedCurve::X25519, NamedCurve::P384], + }), + Extension::SupportedPointFormats(ExtensionSupportedPointFormats { + point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED], + }), + ]); + } + + if !cfg.local_srtp_protection_profiles.is_empty() { + extensions.push(Extension::UseSrtp(ExtensionUseSrtp { + protection_profiles: cfg.local_srtp_protection_profiles.clone(), + })); + } + + if cfg.extended_master_secret == ExtendedMasterSecretType::Request + || cfg.extended_master_secret == ExtendedMasterSecretType::Require + { + extensions.push(Extension::UseExtendedMasterSecret( + ExtensionUseExtendedMasterSecret { supported: true }, + )); + } + + if !cfg.server_name.is_empty() { + extensions.push(Extension::ServerName(ExtensionServerName { + server_name: cfg.server_name.clone(), + })); + } + + Ok(vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientHello( + HandshakeMessageClientHello { + version: PROTOCOL_VERSION1_2, + random: state.local_random.clone(), + cookie: state.cookie.clone(), + + cipher_suites: cfg.local_cipher_suites.clone(), + compression_methods: default_compression_methods(), + extensions, + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]) + } +} + +pub(crate) fn handle_server_key_exchange( + state: &mut State, + cfg: &HandshakeConfig, + h: &HandshakeMessageServerKeyExchange, +) -> Result<(), (Option, Option)> { + if let Some(local_psk_callback) = &cfg.local_psk_callback { + let psk = match local_psk_callback(&h.identity_hint) { + Ok(psk) => psk, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.identity_hint = h.identity_hint.clone(); + state.pre_master_secret = prf_psk_pre_master_secret(&psk); + } else { + let local_keypair = match h.named_curve.generate_keypair() { + Ok(local_keypair) => local_keypair, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.pre_master_secret = match prf_pre_master_secret( + &h.public_key, + &local_keypair.private_key, + local_keypair.curve, + ) { + Ok(pre_master_secret) => pre_master_secret, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.local_keypair = Some(local_keypair); + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/flight/flight4.rs b/vendor/webrtc-dtls/src/flight/flight4.rs new file mode 100644 index 0000000..b511dc4 --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight4.rs @@ -0,0 +1,850 @@ +use std::fmt; +use std::io::BufWriter; + +use async_trait::async_trait; +use log::*; + +use super::flight6::*; +use super::*; +use crate::cipher_suite::*; +use crate::client_certificate_type::*; +use crate::compression_methods::*; +use crate::config::*; +use crate::content::*; +use crate::crypto::*; +use crate::curve::named_curve::*; +use crate::curve::*; +use crate::error::Error; +use crate::extension::extension_supported_elliptic_curves::*; +use crate::extension::extension_supported_point_formats::*; +use crate::extension::extension_use_extended_master_secret::*; +use crate::extension::extension_use_srtp::*; +use crate::extension::renegotiation_info::ExtensionRenegotiationInfo; +use crate::extension::*; +use crate::handshake::handshake_message_certificate::*; +use crate::handshake::handshake_message_certificate_request::*; +use crate::handshake::handshake_message_server_hello::*; +use crate::handshake::handshake_message_server_hello_done::*; +use crate::handshake::handshake_message_server_key_exchange::*; +use crate::handshake::*; +use crate::prf::*; +use crate::record_layer::record_layer_header::*; +use crate::record_layer::*; +use crate::signature_hash_algorithm::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight4; + +impl fmt::Display for Flight4 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 4") + } +} + +#[async_trait] +impl Flight for Flight4 { + async fn parse( + &self, + tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let (seq, msgs) = match cache + .full_pull_map( + state.handshake_recv_sequence, + &[ + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: true, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateVerify, + epoch: cfg.initial_epoch, + is_client: true, + optional: true, + }, + ], + ) + .await + { + Ok((seq, msgs)) => (seq, msgs), + Err(_) => return Err((None, None)), + }; + + let client_key_exchange = if let Some(HandshakeMessage::ClientKeyExchange(h)) = + msgs.get(&HandshakeType::ClientKeyExchange) + { + h + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )); + }; + + if let Some(message) = msgs.get(&HandshakeType::Certificate) { + let h = match message { + HandshakeMessage::Certificate(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + state.peer_certificates = h.certificate.clone(); + trace!( + "[handshake] PeerCertificates4 {}", + state.peer_certificates.len() + ); + } + + if let Some(message) = msgs.get(&HandshakeType::CertificateVerify) { + let h = match message { + HandshakeMessage::CertificateVerify(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + + if state.peer_certificates.is_empty() { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::NoCertificate, + }), + Some(Error::ErrCertificateVerifyNoCertificate), + )); + } + + let plain_text = cache + .pull_and_merge(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + ]) + .await; + + // Verify that the pair of hash algorithm and signature is listed. + let mut valid_signature_scheme = false; + for ss in &cfg.local_signature_schemes { + if ss.hash == h.algorithm.hash && ss.signature == h.algorithm.signature { + valid_signature_scheme = true; + break; + } + } + if !valid_signature_scheme { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrNoAvailableSignatureSchemes), + )); + } + + if let Err(err) = verify_certificate_verify( + &plain_text, + &h.algorithm, + &h.signature, + &state.peer_certificates, + cfg.insecure_verification, + ) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )); + } + + let mut chains = vec![]; + let mut verified = false; + if cfg.client_auth as u8 >= ClientAuthType::VerifyClientCertIfGiven as u8 { + if let Some(client_cert_verifier) = &cfg.client_cert_verifier { + chains = + match verify_client_cert(&state.peer_certificates, client_cert_verifier) { + Ok(chains) => chains, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )) + } + }; + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(Error::ErrInvalidCertificate), + )); + } + + verified = true + } + if let Some(verify_peer_certificate) = &cfg.verify_peer_certificate { + if let Err(err) = verify_peer_certificate(&state.peer_certificates, &chains) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )); + } + } + state.peer_certificates_verified = verified + } else if !state.peer_certificates.is_empty() { + // A certificate was received, but we haven't seen a CertificateVerify + // keep reading until we receive one + return Err((None, None)); + } + + { + let mut cipher_suite = state.cipher_suite.lock().await; + if let Some(cipher_suite) = &mut *cipher_suite { + if !cipher_suite.is_initialized() { + let mut server_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(server_random.as_mut()); + let _ = state.local_random.marshal(&mut writer); + } + let mut client_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(client_random.as_mut()); + let _ = state.remote_random.marshal(&mut writer); + } + + let mut pre_master_secret = vec![]; + if let Some(local_psk_callback) = &cfg.local_psk_callback { + let psk = match local_psk_callback(&client_key_exchange.identity_hint) { + Ok(psk) => psk, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.identity_hint = client_key_exchange.identity_hint.clone(); + pre_master_secret = prf_psk_pre_master_secret(&psk); + } else if let Some(local_keypair) = &state.local_keypair { + pre_master_secret = match prf_pre_master_secret( + &client_key_exchange.public_key, + &local_keypair.private_key, + local_keypair.curve, + ) { + Ok(pre_master_secret) => pre_master_secret, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::IllegalParameter, + }), + Some(err), + )) + } + }; + } + + if state.extended_master_secret { + let hf = cipher_suite.hash_func(); + let session_hash = + match cache.session_hash(hf, cfg.initial_epoch, &[]).await { + Ok(s) => s, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.master_secret = match prf_extended_master_secret( + &pre_master_secret, + &session_hash, + cipher_suite.hash_func(), + ) { + Ok(ms) => ms, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + } else { + state.master_secret = match prf_master_secret( + &pre_master_secret, + &client_random, + &server_random, + cipher_suite.hash_func(), + ) { + Ok(ms) => ms, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + } + + if let Err(err) = cipher_suite.init( + &state.master_secret, + &client_random, + &server_random, + false, + ) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )); + } + } + } + } + + // Now, encrypted packets can be handled + let (done_tx, mut done_rx) = mpsc::channel(1); + if let Err(err) = tx.send(done_tx).await { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(Error::Other(err.to_string())), + )); + } + + done_rx.recv().await; + + let (seq, msgs) = match cache + .full_pull_map( + seq, + &[HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: true, + optional: false, + }], + ) + .await + { + Ok((seq, msgs)) => (seq, msgs), + // No valid message received. Keep reading + Err(_) => return Err((None, None)), + }; + + state.handshake_recv_sequence = seq; + + if let Some(HandshakeMessage::Finished(h)) = msgs.get(&HandshakeType::Finished) { + h + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )); + }; + + match cfg.client_auth { + ClientAuthType::RequireAnyClientCert => { + trace!( + "{} peer_certificates.len() {}", + srv_cli_str(state.is_client), + state.peer_certificates.len(), + ); + if state.peer_certificates.is_empty() { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::NoCertificate, + }), + Some(Error::ErrClientCertificateRequired), + )); + } + } + ClientAuthType::VerifyClientCertIfGiven => { + if !state.peer_certificates.is_empty() && !state.peer_certificates_verified { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(Error::ErrClientCertificateNotVerified), + )); + } + } + ClientAuthType::RequireAndVerifyClientCert => { + if state.peer_certificates.is_empty() { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::NoCertificate, + }), + Some(Error::ErrClientCertificateRequired), + )); + } + if !state.peer_certificates_verified { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(Error::ErrClientCertificateNotVerified), + )); + } + } + ClientAuthType::NoClientCert | ClientAuthType::RequestClientCert => { + return Ok(Box::new(Flight6 {}) as Box); + } + } + + Ok(Box::new(Flight6 {}) as Box) + } + + async fn generate( + &self, + state: &mut State, + _cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let mut extensions = vec![Extension::RenegotiationInfo(ExtensionRenegotiationInfo { + renegotiated_connection: 0, + })]; + if (cfg.extended_master_secret == ExtendedMasterSecretType::Request + || cfg.extended_master_secret == ExtendedMasterSecretType::Require) + && state.extended_master_secret + { + extensions.push(Extension::UseExtendedMasterSecret( + ExtensionUseExtendedMasterSecret { supported: true }, + )); + } + + if state.srtp_protection_profile != SrtpProtectionProfile::Unsupported { + extensions.push(Extension::UseSrtp(ExtensionUseSrtp { + protection_profiles: vec![state.srtp_protection_profile], + })); + } + + if cfg.local_psk_callback.is_none() { + extensions.extend_from_slice(&[ + Extension::SupportedEllipticCurves(ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::P256, NamedCurve::X25519, NamedCurve::P384], + }), + Extension::SupportedPointFormats(ExtensionSupportedPointFormats { + point_formats: vec![ELLIPTIC_CURVE_POINT_FORMAT_UNCOMPRESSED], + }), + ]); + } + + let mut pkts = vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ServerHello( + HandshakeMessageServerHello { + version: PROTOCOL_VERSION1_2, + random: state.local_random.clone(), + cipher_suite: { + let cipher_suite = state.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + cipher_suite.id() + } else { + CipherSuiteId::Unsupported + } + }, + compression_method: default_compression_methods().ids[0], + extensions, + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]; + + if cfg.local_psk_callback.is_none() { + let certificate = match cfg.get_certificate(&cfg.server_name) { + Ok(cert) => cert, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::HandshakeFailure, + }), + Some(err), + )) + } + }; + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::Certificate( + HandshakeMessageCertificate { + certificate: certificate + .certificate + .iter() + .map(|x| x.0.clone()) + .collect(), + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + + let mut server_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(server_random.as_mut()); + let _ = state.local_random.marshal(&mut writer); + } + let mut client_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(client_random.as_mut()); + let _ = state.remote_random.marshal(&mut writer); + } + + // Find compatible signature scheme + let signature_hash_algo = match select_signature_scheme( + &cfg.local_signature_schemes, + &certificate.private_key, + ) { + Ok(s) => s, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(err), + )) + } + }; + + if let Some(local_keypair) = &state.local_keypair { + let signature = match generate_key_signature( + &client_random, + &server_random, + &local_keypair.public_key, + state.named_curve, + &certificate.private_key, /*, signature_hash_algo.hash*/ + ) { + Ok(s) => s, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.local_key_signature = signature; + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ServerKeyExchange( + HandshakeMessageServerKeyExchange { + identity_hint: vec![], + elliptic_curve_type: EllipticCurveType::NamedCurve, + named_curve: state.named_curve, + public_key: local_keypair.public_key.clone(), + algorithm: SignatureHashAlgorithm { + hash: signature_hash_algo.hash, + signature: signature_hash_algo.signature, + }, + signature: state.local_key_signature.clone(), + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + } + + if cfg.client_auth as u8 > ClientAuthType::NoClientCert as u8 { + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::CertificateRequest( + HandshakeMessageCertificateRequest { + certificate_types: vec![ + ClientCertificateType::RsaSign, + ClientCertificateType::EcdsaSign, + ], + signature_hash_algorithms: cfg.local_signature_schemes.clone(), + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + } + } else if let Some(local_psk_identity_hint) = &cfg.local_psk_identity_hint { + // To help the client in selecting which identity to use, the server + // can provide a "PSK identity hint" in the ServerKeyExchange message. + // If no hint is provided, the ServerKeyExchange message is omitted. + // + // https://tools.ietf.org/html/rfc4279#section-2 + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ServerKeyExchange( + HandshakeMessageServerKeyExchange { + identity_hint: local_psk_identity_hint.clone(), + elliptic_curve_type: EllipticCurveType::Unsupported, + named_curve: NamedCurve::Unsupported, + public_key: vec![], + algorithm: SignatureHashAlgorithm { + hash: HashAlgorithm::Unsupported, + signature: SignatureAlgorithm::Unsupported, + }, + signature: vec![], + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + } + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ServerHelloDone( + HandshakeMessageServerHelloDone {}, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + + Ok(pkts) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use tokio::sync::Mutex; + + use super::*; + use crate::error::Result; + + struct MockCipherSuite {} + + impl CipherSuite for MockCipherSuite { + fn to_string(&self) -> String { + "MockCipherSuite".into() + } + fn id(&self) -> CipherSuiteId { + unimplemented!(); + } + fn certificate_type(&self) -> ClientCertificateType { + unimplemented!(); + } + fn hash_func(&self) -> CipherSuiteHash { + unimplemented!(); + } + fn is_psk(&self) -> bool { + false + } + fn is_initialized(&self) -> bool { + panic!("is_initialized called with Certificate but not CertificateVerify"); + } + + // Generate the internal encryption state + fn init( + &mut self, + _master_secret: &[u8], + _client_random: &[u8], + _server_random: &[u8], + _is_client: bool, + ) -> Result<()> { + unimplemented!(); + } + + fn encrypt(&self, _pkt_rlh: &RecordLayerHeader, _raw: &[u8]) -> Result> { + unimplemented!(); + } + fn decrypt(&self, _input: &[u8]) -> Result> { + unimplemented!(); + } + } + + // Assert that if a client sends a certificate they must also send a `CertificateVerify` + // message. The `Flight4` must not interact with the `cipher_suite` if the `CertificateVerify` + // is missing. + #[tokio::test] + async fn test_flight4_process_certificateverify() { + let mut state = State { + cipher_suite: Arc::new(Mutex::new(Some(Box::new(MockCipherSuite {})))), + ..Default::default() + }; + + let raw_certificate = vec![ + 0x0b, 0x00, 0x01, 0x9b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x9b, 0x00, 0x01, + 0x98, 0x00, 0x01, 0x95, 0x30, 0x82, 0x01, 0x91, 0x30, 0x82, 0x01, 0x38, 0xa0, 0x03, + 0x02, 0x01, 0x02, 0x02, 0x11, 0x01, 0x65, 0x03, 0x3f, 0x4d, 0x0b, 0x9a, 0x62, 0x91, + 0xdb, 0x4d, 0x28, 0x2c, 0x1f, 0xd6, 0x73, 0x32, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, + 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x30, 0x00, 0x30, 0x1e, 0x17, 0x0d, 0x32, 0x32, + 0x30, 0x35, 0x31, 0x35, 0x31, 0x38, 0x34, 0x33, 0x35, 0x35, 0x5a, 0x17, 0x0d, 0x32, + 0x32, 0x30, 0x36, 0x31, 0x35, 0x31, 0x38, 0x34, 0x33, 0x35, 0x35, 0x5a, 0x30, 0x00, + 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, + 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xc3, + 0xb7, 0x13, 0x1a, 0x0a, 0xfc, 0xd0, 0x82, 0xf8, 0x94, 0x5e, 0xc0, 0x77, 0x07, 0x81, + 0x28, 0xc9, 0xcb, 0x08, 0x84, 0x50, 0x6b, 0xf0, 0x22, 0xe8, 0x79, 0xb9, 0x15, 0x33, + 0xc4, 0x56, 0xa1, 0xd3, 0x1b, 0x24, 0xe3, 0x61, 0xbd, 0x4d, 0x65, 0x80, 0x6b, 0x5d, + 0x96, 0x48, 0xa2, 0x44, 0x9e, 0xce, 0xe8, 0x65, 0xd6, 0x3c, 0xe0, 0x9b, 0x6b, 0xa1, + 0x36, 0x34, 0xb2, 0x39, 0xe2, 0x03, 0x00, 0xa3, 0x81, 0x92, 0x30, 0x81, 0x8f, 0x30, + 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x02, + 0xa4, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, + 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, + 0x05, 0x07, 0x03, 0x01, 0x30, 0x0f, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x01, 0x01, 0xff, + 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, + 0x04, 0x16, 0x04, 0x14, 0xb1, 0x1a, 0xe3, 0xeb, 0x6f, 0x7c, 0xc3, 0x8f, 0xba, 0x6f, + 0x1c, 0xe8, 0xf0, 0x23, 0x08, 0x50, 0x8d, 0x3c, 0xea, 0x31, 0x30, 0x2e, 0x06, 0x03, + 0x55, 0x1d, 0x11, 0x01, 0x01, 0xff, 0x04, 0x24, 0x30, 0x22, 0x82, 0x20, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, + 0x30, 0x30, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, + 0x03, 0x47, 0x00, 0x30, 0x44, 0x02, 0x20, 0x06, 0x31, 0x43, 0xac, 0x03, 0x45, 0x79, + 0x3c, 0xd7, 0x5f, 0x6e, 0x6a, 0xf8, 0x0e, 0xfd, 0x35, 0x49, 0xee, 0x1b, 0xbc, 0x47, + 0xce, 0xe3, 0x39, 0xec, 0xe4, 0x62, 0xe1, 0x30, 0x1a, 0xa1, 0x89, 0x02, 0x20, 0x35, + 0xcd, 0x7a, 0x15, 0x68, 0x09, 0x50, 0x49, 0x9e, 0x3e, 0x05, 0xd7, 0xc2, 0x69, 0x3f, + 0x9c, 0x0c, 0x98, 0x92, 0x65, 0xec, 0xae, 0x44, 0xfe, 0xe5, 0x68, 0xb8, 0x09, 0x78, + 0x7f, 0x6b, 0x77, + ]; + + let raw_client_key_exchange = vec![ + 0x10, 0x00, 0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x20, 0x96, + 0xed, 0x0c, 0xee, 0xf3, 0x11, 0xb1, 0x9d, 0x8b, 0x1c, 0x02, 0x7f, 0x06, 0x7c, 0x57, + 0x7a, 0x14, 0xa6, 0x41, 0xde, 0x63, 0x57, 0x9e, 0xcd, 0x34, 0x54, 0xba, 0x37, 0x4d, + 0x34, 0x15, 0x18, + ]; + + let mut cache = HandshakeCache::new(); + cache + .push(raw_certificate, 0, 0, HandshakeType::Certificate, true) + .await; + cache + .push( + raw_client_key_exchange, + 0, + 1, + HandshakeType::ClientKeyExchange, + true, + ) + .await; + + let cfg = HandshakeConfig::default(); + + let (mut tx, _rx) = mpsc::channel::>(1); + + let f = Flight4 {}; + let res = f.parse(&mut tx, &mut state, &cache, &cfg).await; + assert!(res.is_err()); + } +} diff --git a/vendor/webrtc-dtls/src/flight/flight5.rs b/vendor/webrtc-dtls/src/flight/flight5.rs new file mode 100644 index 0000000..4743a1a --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight5.rs @@ -0,0 +1,771 @@ +use std::fmt; +use std::io::{BufReader, BufWriter}; + +use async_trait::async_trait; + +use super::flight3::*; +use super::*; +use crate::change_cipher_spec::ChangeCipherSpec; +use crate::content::*; +use crate::crypto::*; +use crate::curve::named_curve::*; +use crate::curve::*; +use crate::error::Error; +use crate::handshake::handshake_message_certificate::*; +use crate::handshake::handshake_message_certificate_verify::*; +use crate::handshake::handshake_message_client_key_exchange::*; +use crate::handshake::handshake_message_finished::*; +use crate::handshake::handshake_message_server_key_exchange::*; +use crate::handshake::*; +use crate::prf::*; +use crate::record_layer::record_layer_header::*; +use crate::record_layer::*; +use crate::signature_hash_algorithm::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight5; + +impl fmt::Display for Flight5 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 5") + } +} + +#[async_trait] +impl Flight for Flight5 { + fn is_last_recv_flight(&self) -> bool { + true + } + + async fn parse( + &self, + _tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let (_seq, msgs) = match cache + .full_pull_map( + state.handshake_recv_sequence, + &[HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: false, + optional: false, + }], + ) + .await + { + Ok((seq, msgs)) => (seq, msgs), + Err(_) => return Err((None, None)), + }; + + let finished = + if let Some(HandshakeMessage::Finished(h)) = msgs.get(&HandshakeType::Finished) { + h + } else { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )); + }; + + let plain_text = cache + .pull_and_merge(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateVerify, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: true, + optional: false, + }, + ]) + .await; + + { + let cipher_suite = state.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + let expected_verify_data = match prf_verify_data_server( + &state.master_secret, + &plain_text, + cipher_suite.hash_func(), + ) { + Ok(d) => d, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(err), + )) + } + }; + + if expected_verify_data != finished.verify_data { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::HandshakeFailure, + }), + Some(Error::ErrVerifyDataMismatch), + )); + } + } + } + + Ok(Box::new(Flight5 {})) + } + + async fn generate( + &self, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let certificate = if !cfg.local_certificates.is_empty() { + let cert = match cfg.get_certificate(&cfg.server_name) { + Ok(cert) => cert, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::HandshakeFailure, + }), + Some(err), + )) + } + }; + Some(cert) + } else { + None + }; + + let mut pkts = vec![]; + + if state.remote_requested_certificate { + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::Certificate( + HandshakeMessageCertificate { + certificate: if let Some(cert) = &certificate { + cert.certificate.iter().map(|x| x.0.clone()).collect() + } else { + vec![] + }, + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + } + + let mut client_key_exchange = HandshakeMessageClientKeyExchange { + identity_hint: vec![], + public_key: vec![], + }; + if cfg.local_psk_callback.is_none() { + if let Some(local_keypair) = &state.local_keypair { + client_key_exchange.public_key = local_keypair.public_key.clone(); + } + } else if let Some(local_psk_identity_hint) = &cfg.local_psk_identity_hint { + client_key_exchange.identity_hint = local_psk_identity_hint.clone(); + } + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::ClientKeyExchange( + client_key_exchange, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + + let server_key_exchange_data = cache + .pull_and_merge(&[HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }]) + .await; + + let mut server_key_exchange = HandshakeMessageServerKeyExchange { + identity_hint: vec![], + elliptic_curve_type: EllipticCurveType::Unsupported, + named_curve: NamedCurve::Unsupported, + public_key: vec![], + algorithm: SignatureHashAlgorithm { + hash: HashAlgorithm::Unsupported, + signature: SignatureAlgorithm::Unsupported, + }, + signature: vec![], + }; + + // handshakeMessageServerKeyExchange is optional for PSK + if server_key_exchange_data.is_empty() { + if let Err((alert, err)) = handle_server_key_exchange(state, cfg, &server_key_exchange) + { + return Err((alert, err)); + } + } else { + let mut reader = BufReader::new(server_key_exchange_data.as_slice()); + let raw_handshake = match Handshake::unmarshal(&mut reader) { + Ok(h) => h, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnexpectedMessage, + }), + Some(err), + )) + } + }; + + match raw_handshake.handshake_message { + HandshakeMessage::ServerKeyExchange(h) => server_key_exchange = h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::UnexpectedMessage, + }), + Some(Error::ErrInvalidContentType), + )) + } + }; + } + + // Append not-yet-sent packets + let mut merged = vec![]; + let mut seq_pred = state.handshake_send_sequence as u16; + for p in &mut pkts { + let h = match &mut p.record.content { + Content::Handshake(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(Error::ErrInvalidContentType), + )) + } + }; + h.handshake_header.message_sequence = seq_pred; + seq_pred += 1; + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + if let Err(err) = h.marshal(&mut writer) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )); + } + } + + merged.extend_from_slice(&raw); + } + + if let Err((alert, err)) = + initialize_cipher_suite(state, cache, cfg, &server_key_exchange, &merged).await + { + return Err((alert, err)); + } + + // If the client has sent a certificate with signing ability, a digitally-signed + // CertificateVerify message is sent to explicitly verify possession of the + // private key in the certificate. + if state.remote_requested_certificate && !cfg.local_certificates.is_empty() { + let mut plain_text = cache + .pull_and_merge(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + ]) + .await; + + plain_text.extend_from_slice(&merged); + + // Find compatible signature scheme + let signature_hash_algo = match select_signature_scheme( + &cfg.local_signature_schemes, + &certificate.as_ref().unwrap().private_key, + ) { + Ok(s) => s, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(err), + )) + } + }; + + let cert_verify = match generate_certificate_verify( + &plain_text, + &certificate.as_ref().unwrap().private_key, /*, signature_hash_algo.hash*/ + ) { + Ok(cert) => cert, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + state.local_certificates_verify = cert_verify; + + let mut p = Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::Handshake(Handshake::new(HandshakeMessage::CertificateVerify( + HandshakeMessageCertificateVerify { + algorithm: signature_hash_algo, + signature: state.local_certificates_verify.clone(), + }, + ))), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }; + + let h = match &mut p.record.content { + Content::Handshake(h) => h, + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(Error::ErrInvalidContentType), + )) + } + }; + h.handshake_header.message_sequence = seq_pred; + + // seqPred++ // this is the last use of seqPred + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + if let Err(err) = h.marshal(&mut writer) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )); + } + } + merged.extend_from_slice(&raw); + + pkts.push(p); + } + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::ChangeCipherSpec(ChangeCipherSpec {}), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }); + + if state.local_verify_data.is_empty() { + let mut plain_text = cache + .pull_and_merge(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateVerify, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: true, + optional: false, + }, + ]) + .await; + + plain_text.extend_from_slice(&merged); + + let cipher_suite = state.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + state.local_verify_data = match prf_verify_data_client( + &state.master_secret, + &plain_text, + cipher_suite.hash_func(), + ) { + Ok(data) => data, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + } + } + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 1, + Content::Handshake(Handshake::new(HandshakeMessage::Finished( + HandshakeMessageFinished { + verify_data: state.local_verify_data.clone(), + }, + ))), + ), + should_encrypt: true, + reset_local_sequence_number: true, + }); + + Ok(pkts) + } +} +async fn initialize_cipher_suite( + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + h: &HandshakeMessageServerKeyExchange, + sending_plain_text: &[u8], +) -> Result<(), (Option, Option)> { + let mut cipher_suite = state.cipher_suite.lock().await; + + if let Some(cipher_suite) = &*cipher_suite { + if cipher_suite.is_initialized() { + return Ok(()); + } + } + + let mut client_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(client_random.as_mut()); + let _ = state.local_random.marshal(&mut writer); + } + let mut server_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(server_random.as_mut()); + let _ = state.remote_random.marshal(&mut writer); + } + + if let Some(cipher_suite) = &*cipher_suite { + if state.extended_master_secret { + let session_hash = match cache + .session_hash( + cipher_suite.hash_func(), + cfg.initial_epoch, + sending_plain_text, + ) + .await + { + Ok(s) => s, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + + state.master_secret = match prf_extended_master_secret( + &state.pre_master_secret, + &session_hash, + cipher_suite.hash_func(), + ) { + Ok(m) => m, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::IllegalParameter, + }), + Some(err), + )) + } + }; + } else { + state.master_secret = match prf_master_secret( + &state.pre_master_secret, + &client_random, + &server_random, + cipher_suite.hash_func(), + ) { + Ok(m) => m, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + } + } + + if cfg.local_psk_callback.is_none() { + // Verify that the pair of hash algorithm and signiture is listed. + let mut valid_signature_scheme = false; + for ss in &cfg.local_signature_schemes { + if ss.hash == h.algorithm.hash && ss.signature == h.algorithm.signature { + valid_signature_scheme = true; + break; + } + } + if !valid_signature_scheme { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InsufficientSecurity, + }), + Some(Error::ErrNoAvailableSignatureSchemes), + )); + } + + let expected_msg = + value_key_message(&client_random, &server_random, &h.public_key, h.named_curve); + if let Err(err) = verify_key_signature( + &expected_msg, + &h.algorithm, + &h.signature, + &state.peer_certificates, + cfg.insecure_verification, + ) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )); + } + + let mut chains = vec![]; + if !cfg.insecure_skip_verify { + chains = match verify_server_cert( + &state.peer_certificates, + &cfg.server_cert_verifier, + &cfg.server_name, + ) { + Ok(chains) => chains, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )) + } + } + } + if let Some(verify_peer_certificate) = &cfg.verify_peer_certificate { + if let Err(err) = verify_peer_certificate(&state.peer_certificates, &chains) { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::BadCertificate, + }), + Some(err), + )); + } + } + } + + if let Some(cipher_suite) = &mut *cipher_suite { + if let Err(err) = + cipher_suite.init(&state.master_secret, &client_random, &server_random, true) + { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )); + } + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/flight/flight6.rs b/vendor/webrtc-dtls/src/flight/flight6.rs new file mode 100644 index 0000000..1e9b003 --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/flight6.rs @@ -0,0 +1,190 @@ +use std::fmt; + +use async_trait::async_trait; + +use super::*; +use crate::change_cipher_spec::*; +use crate::content::*; +use crate::handshake::handshake_message_finished::*; +use crate::handshake::*; +use crate::prf::*; +use crate::record_layer::record_layer_header::*; + +#[derive(Debug, PartialEq)] +pub(crate) struct Flight6; + +impl fmt::Display for Flight6 { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Flight 6") + } +} + +#[async_trait] +impl Flight for Flight6 { + fn is_last_send_flight(&self) -> bool { + true + } + + async fn parse( + &self, + _tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let (_, msgs) = match cache + .full_pull_map( + state.handshake_recv_sequence - 1, + &[HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: true, + optional: false, + }], + ) + .await + { + Ok((seq, msgs)) => (seq, msgs), + // No valid message received. Keep reading + Err(_) => return Err((None, None)), + }; + + if let Some(message) = msgs.get(&HandshakeType::Finished) { + match message { + HandshakeMessage::Finished(_) => {} + _ => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + None, + )) + } + }; + } + + // Other party retransmitted the last flight. + Ok(Box::new(Flight6 {})) + } + + async fn generate( + &self, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)> { + let mut pkts = vec![Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 0, + Content::ChangeCipherSpec(ChangeCipherSpec {}), + ), + should_encrypt: false, + reset_local_sequence_number: false, + }]; + + if state.local_verify_data.is_empty() { + let plain_text = cache + .pull_and_merge(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch: cfg.initial_epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateVerify, + epoch: cfg.initial_epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Finished, + epoch: cfg.initial_epoch + 1, + is_client: true, + optional: false, + }, + ]) + .await; + + let cipher_suite = state.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + state.local_verify_data = match prf_verify_data_server( + &state.master_secret, + &plain_text, + cipher_suite.hash_func(), + ) { + Ok(data) => data, + Err(err) => { + return Err(( + Some(Alert { + alert_level: AlertLevel::Fatal, + alert_description: AlertDescription::InternalError, + }), + Some(err), + )) + } + }; + } + } + + pkts.push(Packet { + record: RecordLayer::new( + PROTOCOL_VERSION1_2, + 1, + Content::Handshake(Handshake::new(HandshakeMessage::Finished( + HandshakeMessageFinished { + verify_data: state.local_verify_data.clone(), + }, + ))), + ), + should_encrypt: true, + reset_local_sequence_number: true, + }); + + Ok(pkts) + } +} diff --git a/vendor/webrtc-dtls/src/flight/mod.rs b/vendor/webrtc-dtls/src/flight/mod.rs new file mode 100644 index 0000000..8e6b41e --- /dev/null +++ b/vendor/webrtc-dtls/src/flight/mod.rs @@ -0,0 +1,87 @@ +pub(crate) mod flight0; +pub(crate) mod flight1; +pub(crate) mod flight2; +pub(crate) mod flight3; +pub(crate) mod flight4; +pub(crate) mod flight5; +pub(crate) mod flight6; + +use std::fmt; + +use async_trait::async_trait; +use tokio::sync::mpsc; + +use crate::alert::*; +use crate::error::Error; +use crate::handshake::handshake_cache::*; +use crate::handshaker::*; +use crate::record_layer::*; +use crate::state::*; + +/* + DTLS messages are grouped into a series of message flights, according + to the diagrams below. Although each Flight of messages may consist + of a number of messages, they should be viewed as monolithic for the + purpose of timeout and retransmission. + https://tools.ietf.org/html/rfc4347#section-4.2.4 + Client Server + ------ ------ + Waiting Flight 0 + + ClientHello --------> Flight 1 + + <------- HelloVerifyRequest Flight 2 + + ClientHello --------> Flight 3 + + ServerHello \ + Certificate* \ + ServerKeyExchange* Flight 4 + CertificateRequest* / + <-------- ServerHelloDone / + + Certificate* \ + ClientKeyExchange \ + CertificateVerify* Flight 5 + [ChangeCipherSpec] / + Finished --------> / + + [ChangeCipherSpec] \ Flight 6 + <-------- Finished / + +*/ + +#[derive(Clone, Debug)] +pub(crate) struct Packet { + pub(crate) record: RecordLayer, + pub(crate) should_encrypt: bool, + pub(crate) reset_local_sequence_number: bool, +} + +#[async_trait] +pub(crate) trait Flight: fmt::Display + fmt::Debug { + fn is_last_send_flight(&self) -> bool { + false + } + fn is_last_recv_flight(&self) -> bool { + false + } + fn has_retransmit(&self) -> bool { + true + } + + async fn parse( + &self, + tx: &mut mpsc::Sender>, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)>; + + async fn generate( + &self, + state: &mut State, + cache: &HandshakeCache, + cfg: &HandshakeConfig, + ) -> Result, (Option, Option)>; +} diff --git a/vendor/webrtc-dtls/src/fragment_buffer/fragment_buffer_test.rs b/vendor/webrtc-dtls/src/fragment_buffer/fragment_buffer_test.rs new file mode 100644 index 0000000..0e90908 --- /dev/null +++ b/vendor/webrtc-dtls/src/fragment_buffer/fragment_buffer_test.rs @@ -0,0 +1,174 @@ +use super::*; + +#[test] +fn test_fragment_buffer() -> Result<()> { + let tests = vec![ + ( + "Single Fragment", + vec![vec![ + 0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0x00, + ]], + vec![vec![ + 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, + 0x00, + ]], + 0, + ), + ( + "Single Fragment Epoch 3", + vec![vec![ + 0x16, 0xfe, 0xff, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x03, + 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0x00, + ]], + vec![vec![ + 0x03, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, + 0x00, + ]], + 3, + ), + ( + "Multiple Fragments", + vec![ + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, + 0x01, 0x02, 0x03, 0x04, + ], + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x05, 0x05, + 0x06, 0x07, 0x08, 0x09, + ], + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x05, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, + ], + ], + vec![vec![ + 0x0b, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + ]], + 0, + ), + ( + "Multiple Unordered Fragments", + vec![ + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, + 0x01, 0x02, 0x03, 0x04, + ], + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x05, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, + ], + vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x81, + 0x0b, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x05, 0x05, + 0x06, 0x07, 0x08, 0x09, + ], + ], + vec![vec![ + 0x0b, 0x00, 0x00, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x00, 0x01, + 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + ]], + 0, + ), + ( + "Multiple Handshakes in Single Fragment", + vec![vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, + 0x30, /* record header */ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, 0xff, + 0x01, 0x01, /*handshake msg 1*/ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, 0xff, + 0x01, 0x01, /*handshake msg 2*/ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, 0xff, + 0x01, 0x01, /*handshake msg 3*/ + ]], + vec![ + vec![ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, + 0xff, 0x01, 0x01, + ], + vec![ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, + 0xff, 0x01, 0x01, + ], + vec![ + 0x03, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0xfe, + 0xff, 0x01, 0x01, + ], + ], + 0, + ), + // Ensure zero length fragments don't cause an infinite recursive loop which in turn causes + // a stack overflow. + ( + "Zero length fragment", + vec![vec![ + 0x16, 0xfe, 0xfd, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x00, + 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]], + vec![vec![ + 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, + ]], + 0, + ), + ]; + + for (name, inputs, expects, expected_epoch) in tests { + let mut fragment_buffer = FragmentBuffer::new(); + for frag in inputs { + let status = fragment_buffer.push(&frag)?; + assert!( + status, + "fragment_buffer didn't accept fragments for '{name}'" + ); + } + + for expected in expects { + let (out, epoch) = fragment_buffer.pop()?; + assert_eq!( + out, expected, + "fragment_buffer '{name}' push/pop: got {out:?}, want {expected:?}" + ); + + assert_eq!( + epoch, expected_epoch, + "fragment_buffer returned wrong epoch: got {epoch}, want {expected_epoch}" + ); + } + + let result = fragment_buffer.pop(); + assert!( + result.is_err(), + "fragment_buffer popped single buffer multiple times for '{name}'" + ); + } + + Ok(()) +} + +#[test] +fn test_fragment_buffer_overflow() -> Result<()> { + let mut fragment_buffer = FragmentBuffer::new(); + + fragment_buffer.push(&[ + 0x16, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0F, 0x03, 0x00, + 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xfe, 0xff, 0x00, + ])?; + + let big_buffer = vec![0; 2_000_000]; + let result = fragment_buffer.push(&big_buffer); + + assert!( + result.is_err(), + "Pushing a buffer of size 2MB should have caused FragmentBuffer::push to return an error" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/fragment_buffer/mod.rs b/vendor/webrtc-dtls/src/fragment_buffer/mod.rs new file mode 100644 index 0000000..d375bc2 --- /dev/null +++ b/vendor/webrtc-dtls/src/fragment_buffer/mod.rs @@ -0,0 +1,160 @@ +#[cfg(test)] +mod fragment_buffer_test; + +use std::collections::HashMap; +use std::io::{BufWriter, Cursor}; + +use crate::content::*; +use crate::error::*; +use crate::handshake::handshake_header::*; +use crate::record_layer::record_layer_header::*; + +// 2 mb max buffer size +const FRAGMENT_BUFFER_MAX_SIZE: usize = 2_000_000; + +pub(crate) struct Fragment { + record_layer_header: RecordLayerHeader, + handshake_header: HandshakeHeader, + data: Vec, +} + +pub(crate) struct FragmentBuffer { + // map of MessageSequenceNumbers that hold slices of fragments + cache: HashMap>, + + current_message_sequence_number: u16, +} + +impl FragmentBuffer { + pub fn new() -> Self { + FragmentBuffer { + cache: HashMap::new(), + current_message_sequence_number: 0, + } + } + + // Attempts to push a DTLS packet to the FragmentBuffer + // when it returns true it means the FragmentBuffer has inserted and the buffer shouldn't be handled + // when an error returns it is fatal, and the DTLS connection should be stopped + pub fn push(&mut self, mut buf: &[u8]) -> Result { + let current_size = self.size(); + if current_size + buf.len() >= FRAGMENT_BUFFER_MAX_SIZE { + return Err(Error::ErrFragmentBufferOverflow { + new_size: current_size + buf.len(), + max_size: FRAGMENT_BUFFER_MAX_SIZE, + }); + } + + let mut reader = Cursor::new(buf); + let record_layer_header = RecordLayerHeader::unmarshal(&mut reader)?; + + // Fragment isn't a handshake, we don't need to handle it + if record_layer_header.content_type != ContentType::Handshake { + return Ok(false); + } + + buf = &buf[RECORD_LAYER_HEADER_SIZE..]; + while !buf.is_empty() { + let mut reader = Cursor::new(buf); + let handshake_header = HandshakeHeader::unmarshal(&mut reader)?; + + self.cache + .entry(handshake_header.message_sequence) + .or_default(); + + // end index should be the length of handshake header but if the handshake + // was fragmented, we should keep them all + let mut end = HANDSHAKE_HEADER_LENGTH + handshake_header.length as usize; + if end > buf.len() { + end = buf.len(); + } + + // Discard all headers, when rebuilding the packet we will re-build + let data = buf[HANDSHAKE_HEADER_LENGTH..end].to_vec(); + + if let Some(x) = self.cache.get_mut(&handshake_header.message_sequence) { + x.push(Fragment { + record_layer_header, + handshake_header, + data, + }); + } + buf = &buf[end..]; + } + + Ok(true) + } + + pub fn pop(&mut self) -> Result<(Vec, u16)> { + let seq_num = self.current_message_sequence_number; + if !self.cache.contains_key(&seq_num) { + return Err(Error::ErrEmptyFragment); + } + + let (content, epoch) = if let Some(frags) = self.cache.get_mut(&seq_num) { + let mut raw_message = vec![]; + // Recursively collect up + if !append_message(0, frags, &mut raw_message) { + return Err(Error::ErrEmptyFragment); + } + + let mut first_header = frags[0].handshake_header; + first_header.fragment_offset = 0; + first_header.fragment_length = first_header.length; + + let mut raw_header = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw_header.as_mut()); + if first_header.marshal(&mut writer).is_err() { + return Err(Error::ErrEmptyFragment); + } + } + + let message_epoch = frags[0].record_layer_header.epoch; + + raw_header.extend_from_slice(&raw_message); + + (raw_header, message_epoch) + } else { + return Err(Error::ErrEmptyFragment); + }; + + self.cache.remove(&seq_num); + self.current_message_sequence_number += 1; + + Ok((content, epoch)) + } + + fn size(&self) -> usize { + self.cache + .values() + .map(|fragment| fragment.iter().map(|f| f.data.len()).sum::()) + .sum() + } +} + +fn append_message(target_offset: u32, frags: &[Fragment], raw_message: &mut Vec) -> bool { + for f in frags { + if f.handshake_header.fragment_offset == target_offset { + let fragment_end = + f.handshake_header.fragment_offset + f.handshake_header.fragment_length; + + // NB: Order here is important, the `f.handshake_header.fragment_length != 0` + // MUST come before the recursive call. + if fragment_end != f.handshake_header.length + && f.handshake_header.fragment_length != 0 + && !append_message(fragment_end, frags, raw_message) + { + return false; + } + + let mut message = vec![]; + message.extend_from_slice(&f.data); + message.extend_from_slice(raw_message); + *raw_message = message; + return true; + } + } + + false +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_cache.rs b/vendor/webrtc-dtls/src/handshake/handshake_cache.rs new file mode 100644 index 0000000..38667bb --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_cache.rs @@ -0,0 +1,241 @@ +#[cfg(test)] +mod handshake_cache_test; + +use std::collections::HashMap; +use std::io::BufReader; +use std::sync::Arc; + +use sha2::{Digest, Sha256}; +use tokio::sync::Mutex; + +use crate::cipher_suite::*; +use crate::handshake::*; + +#[derive(Clone, Debug)] +pub(crate) struct HandshakeCacheItem { + typ: HandshakeType, + is_client: bool, + epoch: u16, + message_sequence: u16, + data: Vec, +} + +#[derive(Copy, Clone, Debug)] +pub(crate) struct HandshakeCachePullRule { + pub(crate) typ: HandshakeType, + pub(crate) epoch: u16, + pub(crate) is_client: bool, + pub(crate) optional: bool, +} + +#[derive(Clone)] +pub(crate) struct HandshakeCache { + cache: Arc>>, +} + +impl HandshakeCache { + pub(crate) fn new() -> Self { + HandshakeCache { + cache: Arc::new(Mutex::new(vec![])), + } + } + + pub(crate) async fn push( + &mut self, + data: Vec, + epoch: u16, + message_sequence: u16, + typ: HandshakeType, + is_client: bool, + ) -> bool { + let mut cache = self.cache.lock().await; + + for i in &*cache { + if i.message_sequence == message_sequence && i.is_client == is_client { + return false; + } + } + + cache.push(HandshakeCacheItem { + typ, + is_client, + epoch, + message_sequence, + data, + }); + + true + } + + // returns a list handshakes that match the requested rules + // the list will contain null entries for rules that can't be satisfied + // multiple entries may match a rule, but only the last match is returned (ie ClientHello with cookies) + pub(crate) async fn pull(&self, rules: &[HandshakeCachePullRule]) -> Vec { + let cache = self.cache.lock().await; + + let mut out = vec![]; + for r in rules { + let mut item: Option = None; + for c in &*cache { + if c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch { + if let Some(x) = &item { + if x.message_sequence < c.message_sequence { + item = Some(c.clone()); + } + } else { + item = Some(c.clone()); + } + } + } + + if let Some(c) = item { + out.push(c); + } + } + + out + } + + // full_pull_map pulls all handshakes between rules[0] to rules[len(rules)-1] as map. + pub(crate) async fn full_pull_map( + &self, + start_seq: isize, + rules: &[HandshakeCachePullRule], + ) -> Result<(isize, HashMap)> { + let cache = self.cache.lock().await; + + let mut ci = HashMap::new(); + for r in rules { + let mut item: Option = None; + for c in &*cache { + if c.typ == r.typ && c.is_client == r.is_client && c.epoch == r.epoch { + if let Some(x) = &item { + if x.message_sequence < c.message_sequence { + item = Some(c.clone()); + } + } else { + item = Some(c.clone()); + } + } + } + if !r.optional && item.is_none() { + // Missing mandatory message. + return Err(Error::Other("Missing mandatory message".to_owned())); + } + + if let Some(c) = item { + ci.insert(r.typ, c); + } + } + + let mut out = HashMap::new(); + let mut seq = start_seq; + for r in rules { + let t = r.typ; + if let Some(i) = ci.get(&t) { + let mut reader = BufReader::new(i.data.as_slice()); + let raw_handshake = Handshake::unmarshal(&mut reader)?; + if seq as u16 != raw_handshake.handshake_header.message_sequence { + // There is a gap. Some messages are not arrived. + return Err(Error::Other( + "There is a gap. Some messages are not arrived.".to_owned(), + )); + } + seq += 1; + out.insert(t, raw_handshake.handshake_message); + } + } + + Ok((seq, out)) + } + + // pull_and_merge calls pull and then merges the results, ignoring any null entries + pub(crate) async fn pull_and_merge(&self, rules: &[HandshakeCachePullRule]) -> Vec { + let mut merged = vec![]; + + for p in &self.pull(rules).await { + merged.extend_from_slice(&p.data); + } + + merged + } + + // session_hash returns the session hash for Extended Master Secret support + // https://tools.ietf.org/html/draft-ietf-tls-session-hash-06#section-4 + pub(crate) async fn session_hash( + &self, + hf: CipherSuiteHash, + epoch: u16, + additional: &[u8], + ) -> Result> { + let mut merged = vec![]; + + // Order defined by https://tools.ietf.org/html/rfc5246#section-7.3 + let handshake_buffer = self + .pull(&[ + HandshakeCachePullRule { + typ: HandshakeType::ClientHello, + epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHello, + epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerKeyExchange, + epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::CertificateRequest, + epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ServerHelloDone, + epoch, + is_client: false, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::Certificate, + epoch, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: HandshakeType::ClientKeyExchange, + epoch, + is_client: true, + optional: false, + }, + ]) + .await; + + for p in &handshake_buffer { + merged.extend_from_slice(&p.data); + } + + merged.extend_from_slice(additional); + + let mut hasher = match hf { + CipherSuiteHash::Sha256 => Sha256::new(), + }; + hasher.update(&merged); + let result = hasher.finalize(); + + Ok(result.as_slice().to_vec()) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_cache/handshake_cache_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_cache/handshake_cache_test.rs new file mode 100644 index 0000000..b17391b --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_cache/handshake_cache_test.rs @@ -0,0 +1,658 @@ +use super::*; + +#[tokio::test] +async fn test_handshake_cache_single_push() -> Result<()> { + let tests = vec![ + ( + "Single Push", + vec![HandshakeCacheItem { + typ: 0.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }], + vec![HandshakeCachePullRule { + typ: 0.into(), + epoch: 0, + is_client: true, + optional: false, + }], + vec![0x00], + ), + ( + "Multi Push", + vec![ + HandshakeCacheItem { + typ: 0.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: 2.into(), + is_client: true, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 0.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 2.into(), + epoch: 0, + is_client: true, + optional: false, + }, + ], + vec![0x00, 0x01, 0x02], + ), + ( + "Multi Push, Rules set order", + vec![ + HandshakeCacheItem { + typ: 2.into(), + is_client: true, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: 0.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 0.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 2.into(), + epoch: 0, + is_client: true, + optional: false, + }, + ], + vec![0x00, 0x01, 0x02], + ), + ( + "Multi Push, Dupe Seqnum", + vec![ + HandshakeCacheItem { + typ: 0.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 0.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + ], + vec![0x00, 0x01], + ), + ( + "Multi Push, Dupe Seqnum Client/Server", + vec![ + HandshakeCacheItem { + typ: 0.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: 1.into(), + is_client: false, + epoch: 0, + message_sequence: 1, + data: vec![0x02], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 0.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: false, + optional: false, + }, + ], + vec![0x00, 0x01, 0x02], + ), + ( + "Multi Push, Dupe Seqnum with Unique HandshakeType", + vec![ + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 2.into(), + is_client: true, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: 3.into(), + is_client: false, + epoch: 0, + message_sequence: 0, + data: vec![0x02], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 2.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 3.into(), + epoch: 0, + is_client: false, + optional: false, + }, + ], + vec![0x00, 0x01, 0x02], + ), + ( + "Multi Push, Wrong epoch", + vec![ + HandshakeCacheItem { + typ: 1.into(), + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: 2.into(), + is_client: true, + epoch: 1, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: 2.into(), + is_client: true, + epoch: 0, + message_sequence: 2, + data: vec![0x11], + }, + HandshakeCacheItem { + typ: 3.into(), + is_client: false, + epoch: 0, + message_sequence: 0, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: 3.into(), + is_client: false, + epoch: 1, + message_sequence: 0, + data: vec![0x12], + }, + HandshakeCacheItem { + typ: 3.into(), + is_client: false, + epoch: 2, + message_sequence: 0, + data: vec![0x12], + }, + ], + vec![ + HandshakeCachePullRule { + typ: 1.into(), + epoch: 0, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 2.into(), + epoch: 1, + is_client: true, + optional: false, + }, + HandshakeCachePullRule { + typ: 3.into(), + epoch: 0, + is_client: false, + optional: false, + }, + ], + vec![0x00, 0x01, 0x02], + ), + ]; + + for (name, inputs, rules, expected) in tests { + let mut h = HandshakeCache::new(); + for i in inputs { + h.push(i.data, i.epoch, i.message_sequence, i.typ, i.is_client) + .await; + } + let verify_data = h.pull_and_merge(&rules).await; + assert_eq!( + verify_data, expected, + "handshakeCache '{name}' exp:{expected:?} actual {verify_data:?}", + ); + } + + Ok(()) +} + +#[tokio::test] +async fn test_handshake_cache_session_hash() -> Result<()> { + let tests = vec![ + ( + "Standard Handshake", + vec![ + HandshakeCacheItem { + typ: HandshakeType::ClientHello, + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHello, + is_client: false, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: HandshakeType::Certificate, + is_client: false, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerKeyExchange, + is_client: false, + epoch: 0, + message_sequence: 3, + data: vec![0x03], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHelloDone, + is_client: false, + epoch: 0, + message_sequence: 4, + data: vec![0x04], + }, + HandshakeCacheItem { + typ: HandshakeType::ClientKeyExchange, + is_client: true, + epoch: 0, + message_sequence: 5, + data: vec![0x05], + }, + ], + vec![ + 0x17, 0xe8, 0x8d, 0xb1, 0x87, 0xaf, 0xd6, 0x2c, 0x16, 0xe5, 0xde, 0xbf, 0x3e, 0x65, + 0x27, 0xcd, 0x00, 0x6b, 0xc0, 0x12, 0xbc, 0x90, 0xb5, 0x1a, 0x81, 0x0c, 0xd8, 0x0c, + 0x2d, 0x51, 0x1f, 0x43, + ], + ), + ( + "Handshake With Client Cert Request", + vec![ + HandshakeCacheItem { + typ: HandshakeType::ClientHello, + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHello, + is_client: false, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: HandshakeType::Certificate, + is_client: false, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerKeyExchange, + is_client: false, + epoch: 0, + message_sequence: 3, + data: vec![0x03], + }, + HandshakeCacheItem { + typ: HandshakeType::CertificateRequest, + is_client: false, + epoch: 0, + message_sequence: 4, + data: vec![0x04], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHelloDone, + is_client: false, + epoch: 0, + message_sequence: 5, + data: vec![0x05], + }, + HandshakeCacheItem { + typ: HandshakeType::ClientKeyExchange, + is_client: true, + epoch: 0, + message_sequence: 6, + data: vec![0x06], + }, + ], + vec![ + 0x57, 0x35, 0x5a, 0xc3, 0x30, 0x3c, 0x14, 0x8f, 0x11, 0xae, 0xf7, 0xcb, 0x17, 0x94, + 0x56, 0xb9, 0x23, 0x2c, 0xde, 0x33, 0xa8, 0x18, 0xdf, 0xda, 0x2c, 0x2f, 0xcb, 0x93, + 0x25, 0x74, 0x9a, 0x6b, + ], + ), + ( + "Handshake Ignores after ClientKeyExchange", + vec![ + HandshakeCacheItem { + typ: HandshakeType::ClientHello, + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHello, + is_client: false, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: HandshakeType::Certificate, + is_client: false, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerKeyExchange, + is_client: false, + epoch: 0, + message_sequence: 3, + data: vec![0x03], + }, + HandshakeCacheItem { + typ: HandshakeType::CertificateRequest, + is_client: false, + epoch: 0, + message_sequence: 4, + data: vec![0x04], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHelloDone, + is_client: false, + epoch: 0, + message_sequence: 5, + data: vec![0x05], + }, + HandshakeCacheItem { + typ: HandshakeType::ClientKeyExchange, + is_client: true, + epoch: 0, + message_sequence: 6, + data: vec![0x06], + }, + HandshakeCacheItem { + typ: HandshakeType::CertificateVerify, + is_client: true, + epoch: 0, + message_sequence: 7, + data: vec![0x07], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: true, + epoch: 1, + message_sequence: 7, + data: vec![0x08], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: false, + epoch: 1, + message_sequence: 7, + data: vec![0x09], + }, + ], + vec![ + 0x57, 0x35, 0x5a, 0xc3, 0x30, 0x3c, 0x14, 0x8f, 0x11, 0xae, 0xf7, 0xcb, 0x17, 0x94, + 0x56, 0xb9, 0x23, 0x2c, 0xde, 0x33, 0xa8, 0x18, 0xdf, 0xda, 0x2c, 0x2f, 0xcb, 0x93, + 0x25, 0x74, 0x9a, 0x6b, + ], + ), + ( + "Handshake Ignores wrong epoch", + vec![ + HandshakeCacheItem { + typ: HandshakeType::ClientHello, + is_client: true, + epoch: 0, + message_sequence: 0, + data: vec![0x00], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHello, + is_client: false, + epoch: 0, + message_sequence: 1, + data: vec![0x01], + }, + HandshakeCacheItem { + typ: HandshakeType::Certificate, + is_client: false, + epoch: 0, + message_sequence: 2, + data: vec![0x02], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerKeyExchange, + is_client: false, + epoch: 0, + message_sequence: 3, + data: vec![0x03], + }, + HandshakeCacheItem { + typ: HandshakeType::CertificateRequest, + is_client: false, + epoch: 0, + message_sequence: 4, + data: vec![0x04], + }, + HandshakeCacheItem { + typ: HandshakeType::ServerHelloDone, + is_client: false, + epoch: 0, + message_sequence: 5, + data: vec![0x05], + }, + HandshakeCacheItem { + typ: HandshakeType::ClientKeyExchange, + is_client: true, + epoch: 0, + message_sequence: 6, + data: vec![0x06], + }, + HandshakeCacheItem { + typ: HandshakeType::CertificateVerify, + is_client: true, + epoch: 0, + message_sequence: 7, + data: vec![0x07], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: true, + epoch: 0, + message_sequence: 7, + data: vec![0xf0], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: false, + epoch: 0, + message_sequence: 7, + data: vec![0xf1], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: true, + epoch: 1, + message_sequence: 7, + data: vec![0x08], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: false, + epoch: 1, + message_sequence: 7, + data: vec![0x09], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: true, + epoch: 0, + message_sequence: 7, + data: vec![0xf0], + }, + HandshakeCacheItem { + typ: HandshakeType::Finished, + is_client: false, + epoch: 0, + message_sequence: 7, + data: vec![0xf1], + }, + ], + vec![ + 0x57, 0x35, 0x5a, 0xc3, 0x30, 0x3c, 0x14, 0x8f, 0x11, 0xae, 0xf7, 0xcb, 0x17, 0x94, + 0x56, 0xb9, 0x23, 0x2c, 0xde, 0x33, 0xa8, 0x18, 0xdf, 0xda, 0x2c, 0x2f, 0xcb, 0x93, + 0x25, 0x74, 0x9a, 0x6b, + ], + ), + ]; + + for (name, inputs, expected) in tests { + let mut h = HandshakeCache::new(); + for i in inputs { + h.push(i.data, i.epoch, i.message_sequence, i.typ, i.is_client) + .await; + } + + let verify_data = h.session_hash(CipherSuiteHash::Sha256, 0, &[]).await?; + + assert_eq!( + verify_data, expected, + "handshakeCacheSessionHassh '{name}' exp: {expected:?} actual {verify_data:?}" + ); + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_header.rs b/vendor/webrtc-dtls/src/handshake/handshake_header.rs new file mode 100644 index 0000000..70c7610 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_header.rs @@ -0,0 +1,50 @@ +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::*; + +// msg_len for Handshake messages assumes an extra 12 bytes for +// sequence, Fragment and version information +pub(crate) const HANDSHAKE_HEADER_LENGTH: usize = 12; + +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] +pub struct HandshakeHeader { + pub(crate) handshake_type: HandshakeType, + pub(crate) length: u32, // uint24 in spec + pub(crate) message_sequence: u16, + pub(crate) fragment_offset: u32, // uint24 in spec + pub(crate) fragment_length: u32, // uint24 in spec +} + +impl HandshakeHeader { + pub fn size(&self) -> usize { + 1 + 3 + 2 + 3 + 3 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.handshake_type as u8)?; + writer.write_u24::(self.length)?; + writer.write_u16::(self.message_sequence)?; + writer.write_u24::(self.fragment_offset)?; + writer.write_u24::(self.fragment_length)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let handshake_type = reader.read_u8()?.into(); + let length = reader.read_u24::()?; + let message_sequence = reader.read_u16::()?; + let fragment_offset = reader.read_u24::()?; + let fragment_length = reader.read_u24::()?; + + Ok(HandshakeHeader { + handshake_type, + length, + message_sequence, + fragment_offset, + fragment_length, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate.rs new file mode 100644 index 0000000..c4e0034 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate.rs @@ -0,0 +1,70 @@ +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::*; + +#[cfg(test)] +mod handshake_message_certificate_test; + +const HANDSHAKE_MESSAGE_CERTIFICATE_LENGTH_FIELD_SIZE: usize = 3; + +#[derive(PartialEq, Eq, Debug, Clone)] +pub struct HandshakeMessageCertificate { + pub(crate) certificate: Vec>, +} + +impl HandshakeMessageCertificate { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::Certificate + } + + pub fn size(&self) -> usize { + let mut len = 3; + + for r in &self.certificate { + len += HANDSHAKE_MESSAGE_CERTIFICATE_LENGTH_FIELD_SIZE + r.len(); + } + + len + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + let mut payload_size = 0; + for r in &self.certificate { + payload_size += HANDSHAKE_MESSAGE_CERTIFICATE_LENGTH_FIELD_SIZE + r.len(); + } + + // Total Payload Size + writer.write_u24::(payload_size as u32)?; + + for r in &self.certificate { + // Certificate Length + writer.write_u24::(r.len() as u32)?; + + // Certificate body + writer.write_all(r)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let mut certificate: Vec> = vec![]; + + let payload_size = reader.read_u24::()? as usize; + let mut offset = 0; + while offset < payload_size { + let certificate_len = reader.read_u24::()? as usize; + offset += HANDSHAKE_MESSAGE_CERTIFICATE_LENGTH_FIELD_SIZE; + + let mut buf = vec![0; certificate_len]; + reader.read_exact(&mut buf)?; + offset += certificate_len; + + certificate.push(buf); + } + + Ok(HandshakeMessageCertificate { certificate }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate/handshake_message_certificate_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate/handshake_message_certificate_test.rs new file mode 100644 index 0000000..582d16d --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate/handshake_message_certificate_test.rs @@ -0,0 +1,79 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_certificate() -> Result<()> { + let raw_certificate = vec![ + 0x00, 0x01, 0x8c, 0x00, 0x01, 0x89, 0x30, 0x82, 0x01, 0x85, 0x30, 0x82, 0x01, 0x2b, 0x02, + 0x14, 0x7d, 0x00, 0xcf, 0x07, 0xfc, 0xe2, 0xb6, 0xb8, 0x3f, 0x72, 0xeb, 0x11, 0x36, 0x1b, + 0xf6, 0x39, 0xf1, 0x3c, 0x33, 0x41, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, + 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, + 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, + 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, + 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, + 0x1e, 0x17, 0x0d, 0x31, 0x38, 0x31, 0x30, 0x32, 0x35, 0x30, 0x38, 0x35, 0x31, 0x31, 0x32, + 0x5a, 0x17, 0x0d, 0x31, 0x39, 0x31, 0x30, 0x32, 0x35, 0x30, 0x38, 0x35, 0x31, 0x31, 0x32, + 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, + 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, + 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, + 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, + 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x59, 0x30, + 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, + 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0xf9, 0xb1, 0x62, 0xd6, 0x07, 0xae, + 0xc3, 0x36, 0x34, 0xf5, 0xa3, 0x09, 0x39, 0x86, 0xe7, 0x3b, 0x59, 0xf7, 0x4a, 0x1d, 0xf4, + 0x97, 0x4f, 0x91, 0x40, 0x56, 0x1b, 0x3d, 0x6c, 0x5a, 0x38, 0x10, 0x15, 0x58, 0xf5, 0xa4, + 0xcc, 0xdf, 0xd5, 0xf5, 0x4a, 0x35, 0x40, 0x0f, 0x9f, 0x54, 0xb7, 0xe9, 0xe2, 0xae, 0x63, + 0x83, 0x6a, 0x4c, 0xfc, 0xc2, 0x5f, 0x78, 0xa0, 0xbb, 0x46, 0x54, 0xa4, 0xda, 0x30, 0x0a, + 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45, + 0x02, 0x20, 0x47, 0x1a, 0x5f, 0x58, 0x2a, 0x74, 0x33, 0x6d, 0xed, 0xac, 0x37, 0x21, 0xfa, + 0x76, 0x5a, 0x4d, 0x78, 0x68, 0x1a, 0xdd, 0x80, 0xa4, 0xd4, 0xb7, 0x7f, 0x7d, 0x78, 0xb3, + 0xfb, 0xf3, 0x95, 0xfb, 0x02, 0x21, 0x00, 0xc0, 0x73, 0x30, 0xda, 0x2b, 0xc0, 0x0c, 0x9e, + 0xb2, 0x25, 0x0d, 0x46, 0xb0, 0xbc, 0x66, 0x7f, 0x71, 0x66, 0xbf, 0x16, 0xb3, 0x80, 0x78, + 0xd0, 0x0c, 0xef, 0xcc, 0xf5, 0xc1, 0x15, 0x0f, 0x58, + ]; + + let mut reader = BufReader::new(raw_certificate.as_slice()); + let c = HandshakeMessageCertificate::unmarshal(&mut reader)?; + //TODO: add x509 parse + // certificate, err := x509.ParseCertificate(c.certificate[0]) + // if err != nil { + // t.Error(err) + // } + // copyCertificatePrivateMembers(certificate, parsedCertificate) + // if !reflect.DeepEqual(certificate, parsedCertificate) { + // t.Errorf("handshakeMessageCertificate unmarshal: got %#v, want %#v", c, parsedCertificate) + // } + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_certificate, + "handshakeMessageCertificate marshal: got {raw:?}, want {raw_certificate:?}" + ); + + Ok(()) +} + +#[test] +fn test_empty_handshake_message_certificate() -> Result<()> { + let raw_certificate = vec![0x00, 0x00, 0x00]; + + let expected_certificate = HandshakeMessageCertificate { + certificate: vec![], + }; + + let mut reader = BufReader::new(raw_certificate.as_slice()); + let c = HandshakeMessageCertificate::unmarshal(&mut reader)?; + + assert_eq!( + c, expected_certificate, + "handshakeMessageCertificate unmarshal: got {c:?}, want {expected_certificate:?}", + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request.rs new file mode 100644 index 0000000..f48cecb --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request.rs @@ -0,0 +1,77 @@ +#[cfg(test)] +mod handshake_message_certificate_request_test; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::*; +use crate::client_certificate_type::*; +use crate::signature_hash_algorithm::*; + +/* +A non-anonymous server can optionally request a certificate from +the client, if appropriate for the selected cipher suite. This +message, if sent, will immediately follow the ServerKeyExchange +message (if it is sent; otherwise, this message follows the +server's Certificate message). +*/ +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageCertificateRequest { + pub(crate) certificate_types: Vec, + pub(crate) signature_hash_algorithms: Vec, +} + +const HANDSHAKE_MESSAGE_CERTIFICATE_REQUEST_MIN_LENGTH: usize = 5; + +impl HandshakeMessageCertificateRequest { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::CertificateRequest + } + + pub fn size(&self) -> usize { + 1 + self.certificate_types.len() + 2 + self.signature_hash_algorithms.len() * 2 + 2 + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.certificate_types.len() as u8)?; + for v in &self.certificate_types { + writer.write_u8(*v as u8)?; + } + + writer.write_u16::(2 * self.signature_hash_algorithms.len() as u16)?; + for v in &self.signature_hash_algorithms { + writer.write_u8(v.hash as u8)?; + writer.write_u8(v.signature as u8)?; + } + + writer.write_all(&[0x00, 0x00])?; // Distinguished Names Length + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let certificate_types_length = reader.read_u8()?; + + let mut certificate_types = vec![]; + for _ in 0..certificate_types_length { + let cert_type = reader.read_u8()?.into(); + certificate_types.push(cert_type); + } + + let signature_hash_algorithms_length = reader.read_u16::()?; + + let mut signature_hash_algorithms = vec![]; + for _ in (0..signature_hash_algorithms_length).step_by(2) { + let hash = reader.read_u8()?.into(); + let signature = reader.read_u8()?.into(); + + signature_hash_algorithms.push(SignatureHashAlgorithm { hash, signature }); + } + + Ok(HandshakeMessageCertificateRequest { + certificate_types, + signature_hash_algorithms, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request/handshake_message_certificate_request_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request/handshake_message_certificate_request_test.rs new file mode 100644 index 0000000..f261cde --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_request/handshake_message_certificate_request_test.rs @@ -0,0 +1,64 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; +use crate::signature_hash_algorithm::*; + +#[test] +fn test_handshake_message_certificate_request() -> Result<()> { + let raw_certificate_request = vec![ + 0x02, 0x01, 0x40, 0x00, 0x0C, 0x04, 0x03, 0x04, 0x01, 0x05, 0x03, 0x05, 0x01, 0x06, 0x01, + 0x02, 0x01, 0x00, 0x00, + ]; + + let parsed_certificate_request = HandshakeMessageCertificateRequest { + certificate_types: vec![ + ClientCertificateType::RsaSign, + ClientCertificateType::EcdsaSign, + ], + signature_hash_algorithms: vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha1, + signature: SignatureAlgorithm::Rsa, + }, + ], + }; + + let mut reader = BufReader::new(raw_certificate_request.as_slice()); + let c = HandshakeMessageCertificateRequest::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_certificate_request, + "parsedCertificateRequest unmarshal: got {c:?}, want {parsed_certificate_request:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_certificate_request, + "parsedCertificateRequest marshal: got {raw:?}, want {raw_certificate_request:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify.rs new file mode 100644 index 0000000..4b535ce --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify.rs @@ -0,0 +1,52 @@ +#[cfg(test)] +mod handshake_message_certificate_verify_test; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::*; +use crate::signature_hash_algorithm::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageCertificateVerify { + pub(crate) algorithm: SignatureHashAlgorithm, + pub(crate) signature: Vec, +} + +const HANDSHAKE_MESSAGE_CERTIFICATE_VERIFY_MIN_LENGTH: usize = 4; + +impl HandshakeMessageCertificateVerify { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::CertificateVerify + } + + pub fn size(&self) -> usize { + 1 + 1 + 2 + self.signature.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.algorithm.hash as u8)?; + writer.write_u8(self.algorithm.signature as u8)?; + writer.write_u16::(self.signature.len() as u16)?; + writer.write_all(&self.signature)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let hash_algorithm = reader.read_u8()?.into(); + let signature_algorithm = reader.read_u8()?.into(); + let signature_length = reader.read_u16::()? as usize; + let mut signature = vec![0; signature_length]; + reader.read_exact(&mut signature)?; + + Ok(HandshakeMessageCertificateVerify { + algorithm: SignatureHashAlgorithm { + hash: hash_algorithm, + signature: signature_algorithm, + }, + signature, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify/handshake_message_certificate_verify_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify/handshake_message_certificate_verify_test.rs new file mode 100644 index 0000000..b52cebc --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_certificate_verify/handshake_message_certificate_verify_test.rs @@ -0,0 +1,40 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_certificate_request() -> Result<()> { + let raw_certificate_verify = vec![ + 0x04, 0x03, 0x00, 0x47, 0x30, 0x45, 0x02, 0x20, 0x6b, 0x63, 0x17, 0xad, 0xbe, 0xb7, 0x7b, + 0x0f, 0x86, 0x73, 0x39, 0x1e, 0xba, 0xb3, 0x50, 0x9c, 0xce, 0x9c, 0xe4, 0x8b, 0xe5, 0x13, + 0x07, 0x59, 0x18, 0x1f, 0xe5, 0xa0, 0x2b, 0xca, 0xa6, 0xad, 0x02, 0x21, 0x00, 0xd3, 0xb5, + 0x01, 0xbe, 0x87, 0x6c, 0x04, 0xa1, 0xdc, 0x28, 0xaa, 0x5f, 0xf7, 0x1e, 0x9c, 0xc0, 0x1e, + 0x00, 0x2c, 0xe5, 0x94, 0xbb, 0x03, 0x0e, 0xf1, 0xcb, 0x28, 0x22, 0x33, 0x23, 0x88, 0xad, + ]; + let parsed_certificate_verify = HandshakeMessageCertificateVerify { + algorithm: SignatureHashAlgorithm { + hash: raw_certificate_verify[0].into(), + signature: raw_certificate_verify[1].into(), + }, + signature: raw_certificate_verify[4..].to_vec(), + }; + + let mut reader = BufReader::new(raw_certificate_verify.as_slice()); + let c = HandshakeMessageCertificateVerify::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_certificate_verify, + "handshakeMessageCertificate unmarshal: got {c:?}, want {parsed_certificate_verify:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_certificate_verify, + "handshakeMessageCertificateVerify marshal: got {raw:?}, want {raw_certificate_verify:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello.rs new file mode 100644 index 0000000..ad4ca6f --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello.rs @@ -0,0 +1,196 @@ +#[cfg(test)] +mod handshake_message_client_hello_test; + +use std::fmt; +use std::io::{BufReader, BufWriter}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::handshake_random::*; +use super::*; +use crate::cipher_suite::*; +use crate::compression_methods::*; +use crate::extension::*; +use crate::record_layer::record_layer_header::*; + +/* +When a client first connects to a server it is required to send +the client hello as its first message. The client can also send a +client hello in response to a hello request or on its own +initiative in order to renegotiate the security parameters in an +existing connection. +*/ +#[derive(Clone)] +pub struct HandshakeMessageClientHello { + pub(crate) version: ProtocolVersion, + pub(crate) random: HandshakeRandom, + pub(crate) cookie: Vec, + + pub(crate) cipher_suites: Vec, + pub(crate) compression_methods: CompressionMethods, + pub(crate) extensions: Vec, +} + +impl PartialEq for HandshakeMessageClientHello { + fn eq(&self, other: &Self) -> bool { + if !(self.version == other.version + && self.random == other.random + && self.cookie == other.cookie + && self.compression_methods == other.compression_methods + && self.extensions == other.extensions + && self.cipher_suites.len() == other.cipher_suites.len()) + { + return false; + } + + for i in 0..self.cipher_suites.len() { + if self.cipher_suites[i] != other.cipher_suites[i] { + return false; + } + } + + true + } +} + +impl fmt::Debug for HandshakeMessageClientHello { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut cipher_suites_str = String::new(); + for cipher_suite in &self.cipher_suites { + cipher_suites_str += &cipher_suite.to_string(); + cipher_suites_str += " "; + } + let s = vec![ + format!("version: {:?} random: {:?}", self.version, self.random), + format!("cookie: {:?}", self.cookie), + format!("cipher_suites: {cipher_suites_str:?}"), + format!("compression_methods: {:?}", self.compression_methods), + format!("extensions: {:?}", self.extensions), + ]; + write!(f, "{}", s.join(" ")) + } +} + +const HANDSHAKE_MESSAGE_CLIENT_HELLO_VARIABLE_WIDTH_START: usize = 34; + +impl HandshakeMessageClientHello { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::ClientHello + } + + pub fn size(&self) -> usize { + let mut len = 0; + + len += 2; // version.major+minor + len += self.random.size(); + + // SessionID + len += 1; + + len += 1 + self.cookie.len(); + + len += 2 + 2 * self.cipher_suites.len(); + + len += self.compression_methods.size(); + + len += 2; + for extension in &self.extensions { + len += extension.size(); + } + + len + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + if self.cookie.len() > 255 { + return Err(Error::ErrCookieTooLong); + } + + writer.write_u8(self.version.major)?; + writer.write_u8(self.version.minor)?; + self.random.marshal(writer)?; + + // SessionID + writer.write_u8(0x00)?; + + writer.write_u8(self.cookie.len() as u8)?; + writer.write_all(&self.cookie)?; + + writer.write_u16::(2 * self.cipher_suites.len() as u16)?; + for cipher_suite in &self.cipher_suites { + writer.write_u16::(*cipher_suite as u16)?; + } + + self.compression_methods.marshal(writer)?; + + let mut extension_buffer = vec![]; + { + let mut extension_writer = BufWriter::<&mut Vec>::new(extension_buffer.as_mut()); + for extension in &self.extensions { + extension.marshal(&mut extension_writer)?; + } + } + + writer.write_u16::(extension_buffer.len() as u16)?; + writer.write_all(&extension_buffer)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let major = reader.read_u8()?; + let minor = reader.read_u8()?; + let random = HandshakeRandom::unmarshal(reader)?; + + // Session ID + reader.read_u8()?; + + let cookie_len = reader.read_u8()? as usize; + let mut cookie = vec![0; cookie_len]; + reader.read_exact(&mut cookie)?; + + let cipher_suites_len = reader.read_u16::()? as usize / 2; + let mut cipher_suites = vec![]; + for _ in 0..cipher_suites_len { + let id: CipherSuiteId = reader.read_u16::()?.into(); + //let cipher_suite = cipher_suite_for_id(id)?; + cipher_suites.push(id); + } + + let compression_methods = CompressionMethods::unmarshal(reader)?; + let mut extensions = vec![]; + + let extension_buffer_len = reader.read_u16::()? as usize; + let mut extension_buffer = vec![0u8; extension_buffer_len]; + reader.read_exact(&mut extension_buffer)?; + + let mut offset = 0; + while offset < extension_buffer_len { + let mut extension_reader = BufReader::new(&extension_buffer[offset..]); + if let Ok(extension) = Extension::unmarshal(&mut extension_reader) { + extensions.push(extension); + } else { + log::warn!( + "Unsupported Extension Type {} {}", + extension_buffer[offset], + extension_buffer[offset + 1] + ); + } + + let extension_len = + u16::from_be_bytes([extension_buffer[offset + 2], extension_buffer[offset + 3]]) + as usize; + offset += 4 + extension_len; + } + + Ok(HandshakeMessageClientHello { + version: ProtocolVersion { major, minor }, + random, + cookie, + + cipher_suites, + compression_methods, + extensions, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello/handshake_message_client_hello_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello/handshake_message_client_hello_test.rs new file mode 100644 index 0000000..ba42603 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_client_hello/handshake_message_client_hello_test.rs @@ -0,0 +1,75 @@ +use std::io::{BufReader, BufWriter}; +use std::time::{Duration, SystemTime}; + +use super::*; +use crate::curve::named_curve::*; +use crate::extension::extension_supported_elliptic_curves::*; + +#[test] +fn test_handshake_message_client_hello() -> Result<()> { + let raw_client_hello = vec![ + 0xfe, 0xfd, 0xb6, 0x2f, 0xce, 0x5c, 0x42, 0x54, 0xff, 0x86, 0xe1, 0x24, 0x41, 0x91, 0x42, + 0x62, 0x15, 0xad, 0x16, 0xc9, 0x15, 0x8d, 0x95, 0x71, 0x8a, 0xbb, 0x22, 0xd7, 0x47, 0xec, + 0xd8, 0x3d, 0xdc, 0x4b, 0x00, 0x14, 0xe6, 0x14, 0x3a, 0x1b, 0x04, 0xea, 0x9e, 0x7a, 0x14, + 0xd6, 0x6c, 0x57, 0xd0, 0x0e, 0x32, 0x85, 0x76, 0x18, 0xde, 0xd8, 0x00, 0x04, 0xc0, 0x2b, + 0xc0, 0x0a, 0x01, 0x00, 0x00, 0x08, 0x00, 0x0a, 0x00, 0x04, 0x00, 0x02, 0x00, 0x1d, + ]; + + let gmt_unix_time = if let Some(unix_time) = + SystemTime::UNIX_EPOCH.checked_add(Duration::new(3056586332u64, 0)) + { + unix_time + } else { + SystemTime::UNIX_EPOCH + }; + let parsed_client_hello = HandshakeMessageClientHello { + version: ProtocolVersion { + major: 0xFE, + minor: 0xFD, + }, + random: HandshakeRandom { + gmt_unix_time, + random_bytes: [ + 0x42, 0x54, 0xff, 0x86, 0xe1, 0x24, 0x41, 0x91, 0x42, 0x62, 0x15, 0xad, 0x16, 0xc9, + 0x15, 0x8d, 0x95, 0x71, 0x8a, 0xbb, 0x22, 0xd7, 0x47, 0xec, 0xd8, 0x3d, 0xdc, 0x4b, + ], + }, + cookie: vec![ + 0xe6, 0x14, 0x3a, 0x1b, 0x04, 0xea, 0x9e, 0x7a, 0x14, 0xd6, 0x6c, 0x57, 0xd0, 0x0e, + 0x32, 0x85, 0x76, 0x18, 0xde, 0xd8, + ], + cipher_suites: vec![ + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_256_Cbc_Sha, + //Box::::default(), + //Box::::default(), + ], + compression_methods: CompressionMethods { + ids: vec![CompressionMethodId::Null], + }, + extensions: vec![Extension::SupportedEllipticCurves( + ExtensionSupportedEllipticCurves { + elliptic_curves: vec![NamedCurve::X25519], + }, + )], + }; + + let mut reader = BufReader::new(raw_client_hello.as_slice()); + let c = HandshakeMessageClientHello::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_client_hello, + "handshakeMessageClientHello unmarshal: got {c:?}, want {parsed_client_hello:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_client_hello, + "handshakeMessageClientHello marshal: got {raw:?}, want {raw_client_hello:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange.rs new file mode 100644 index 0000000..4c027ff --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange.rs @@ -0,0 +1,70 @@ +#[cfg(test)] +mod handshake_message_client_key_exchange_test; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, WriteBytesExt}; + +use super::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageClientKeyExchange { + pub(crate) identity_hint: Vec, + pub(crate) public_key: Vec, +} + +impl HandshakeMessageClientKeyExchange { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::ClientKeyExchange + } + + pub fn size(&self) -> usize { + if !self.public_key.is_empty() { + 1 + self.public_key.len() + } else { + 2 + self.identity_hint.len() + } + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + if (!self.identity_hint.is_empty() && !self.public_key.is_empty()) + || (self.identity_hint.is_empty() && self.public_key.is_empty()) + { + return Err(Error::ErrInvalidClientKeyExchange); + } + + if !self.public_key.is_empty() { + writer.write_u8(self.public_key.len() as u8)?; + writer.write_all(&self.public_key)?; + } else { + writer.write_u16::(self.identity_hint.len() as u16)?; + writer.write_all(&self.identity_hint)?; + } + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let mut data = vec![]; + reader.read_to_end(&mut data)?; + + // If parsed as PSK return early and only populate PSK Identity Hint + let psk_length = ((data[0] as u16) << 8) | data[1] as u16; + if data.len() == psk_length as usize + 2 { + return Ok(HandshakeMessageClientKeyExchange { + identity_hint: data[2..].to_vec(), + public_key: vec![], + }); + } + + let public_key_length = data[0] as usize; + if data.len() != public_key_length + 1 { + return Err(Error::ErrBufferTooSmall); + } + + Ok(HandshakeMessageClientKeyExchange { + identity_hint: vec![], + public_key: data[1..].to_vec(), + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange/handshake_message_client_key_exchange_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange/handshake_message_client_key_exchange_test.rs new file mode 100644 index 0000000..0b9d6c1 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_client_key_exchange/handshake_message_client_key_exchange_test.rs @@ -0,0 +1,35 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_client_key_exchange() -> Result<()> { + let raw_client_key_exchange = vec![ + 0x20, 0x26, 0x78, 0x4a, 0x78, 0x70, 0xc1, 0xf9, 0x71, 0xea, 0x50, 0x4a, 0xb5, 0xbb, 0x00, + 0x76, 0x02, 0x05, 0xda, 0xf7, 0xd0, 0x3f, 0xe3, 0xf7, 0x4e, 0x8a, 0x14, 0x6f, 0xb7, 0xe0, + 0xc0, 0xff, 0x54, + ]; + let parsed_client_key_exchange = HandshakeMessageClientKeyExchange { + identity_hint: vec![], + public_key: raw_client_key_exchange[1..].to_vec(), + }; + + let mut reader = BufReader::new(raw_client_key_exchange.as_slice()); + let c = HandshakeMessageClientKeyExchange::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_client_key_exchange, + "parsedCertificateRequest unmarshal: got {c:?}, want {parsed_client_key_exchange:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_client_key_exchange, + "handshakeMessageClientKeyExchange marshal: got {raw:?}, want {raw_client_key_exchange:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_finished.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_finished.rs new file mode 100644 index 0000000..d20feb6 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_finished.rs @@ -0,0 +1,34 @@ +#[cfg(test)] +mod handshake_message_finished_test; + +use std::io::{Read, Write}; + +use super::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageFinished { + pub(crate) verify_data: Vec, +} + +impl HandshakeMessageFinished { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::Finished + } + + pub fn size(&self) -> usize { + self.verify_data.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_all(&self.verify_data)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let mut verify_data: Vec = vec![]; + reader.read_to_end(&mut verify_data)?; + + Ok(HandshakeMessageFinished { verify_data }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_finished/handshake_message_finished_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_finished/handshake_message_finished_test.rs new file mode 100644 index 0000000..7980ee9 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_finished/handshake_message_finished_test.rs @@ -0,0 +1,32 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_finished() -> Result<()> { + let raw_finished = vec![ + 0x01, 0x01, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, + ]; + let parsed_finished = HandshakeMessageFinished { + verify_data: raw_finished.clone(), + }; + + let mut reader = BufReader::new(raw_finished.as_slice()); + let c = HandshakeMessageFinished::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_finished, + "handshakeMessageFinished unmarshal: got {c:?}, want {parsed_finished:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_finished, + "handshakeMessageFinished marshal: got {raw:?}, want {raw_finished:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request.rs new file mode 100644 index 0000000..1d738d9 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request.rs @@ -0,0 +1,72 @@ +#[cfg(test)] +mod handshake_message_hello_verify_request_test; + +use std::io::{Read, Write}; + +use byteorder::{ReadBytesExt, WriteBytesExt}; + +use super::*; +use crate::record_layer::record_layer_header::*; + +/* + The definition of HelloVerifyRequest is as follows: + + struct { + ProtocolVersion server_version; + opaque cookie<0..2^8-1>; + } HelloVerifyRequest; + + The HelloVerifyRequest message type is hello_verify_request(3). + + When the client sends its ClientHello message to the server, the server + MAY respond with a HelloVerifyRequest message. This message contains + a stateless cookie generated using the technique of [PHOTURIS]. The + client MUST retransmit the ClientHello with the cookie added. + + https://tools.ietf.org/html/rfc6347#section-4.2.1 +*/ +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageHelloVerifyRequest { + pub(crate) version: ProtocolVersion, + pub(crate) cookie: Vec, +} + +impl HandshakeMessageHelloVerifyRequest { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::HelloVerifyRequest + } + + pub fn size(&self) -> usize { + 1 + 1 + 1 + self.cookie.len() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + if self.cookie.len() > 255 { + return Err(Error::ErrCookieTooLong); + } + + writer.write_u8(self.version.major)?; + writer.write_u8(self.version.minor)?; + writer.write_u8(self.cookie.len() as u8)?; + writer.write_all(&self.cookie)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let major = reader.read_u8()?; + let minor = reader.read_u8()?; + let cookie_length = reader.read_u8()?; + let mut cookie = vec![]; + reader.read_to_end(&mut cookie)?; + + if cookie.len() < cookie_length as usize { + return Err(Error::ErrBufferTooSmall); + } + + Ok(HandshakeMessageHelloVerifyRequest { + version: ProtocolVersion { major, minor }, + cookie, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request/handshake_message_hello_verify_request_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request/handshake_message_hello_verify_request_test.rs new file mode 100644 index 0000000..5a25ce0 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_hello_verify_request/handshake_message_hello_verify_request_test.rs @@ -0,0 +1,40 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_hello_verify_request() -> Result<()> { + let raw_hello_verify_request = vec![ + 0xfe, 0xff, 0x14, 0x25, 0xfb, 0xee, 0xb3, 0x7c, 0x95, 0xcf, 0x00, 0xeb, 0xad, 0xe2, 0xef, + 0xc7, 0xfd, 0xbb, 0xed, 0xf7, 0x1f, 0x6c, 0xcd, + ]; + let parsed_hello_verify_request = HandshakeMessageHelloVerifyRequest { + version: ProtocolVersion { + major: 0xFE, + minor: 0xFF, + }, + cookie: vec![ + 0x25, 0xfb, 0xee, 0xb3, 0x7c, 0x95, 0xcf, 0x00, 0xeb, 0xad, 0xe2, 0xef, 0xc7, 0xfd, + 0xbb, 0xed, 0xf7, 0x1f, 0x6c, 0xcd, + ], + }; + + let mut reader = BufReader::new(raw_hello_verify_request.as_slice()); + let c = HandshakeMessageHelloVerifyRequest::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_hello_verify_request, + "parsed_hello_verify_request unmarshal: got {c:?}, want {parsed_hello_verify_request:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_hello_verify_request, + "parsed_hello_verify_request marshal: got {raw:?}, want {raw_hello_verify_request:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello.rs new file mode 100644 index 0000000..fd38b24 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello.rs @@ -0,0 +1,151 @@ +#[cfg(test)] +mod handshake_message_server_hello_test; + +use std::fmt; +use std::io::{BufReader, BufWriter}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use super::handshake_random::*; +use super::*; +use crate::cipher_suite::*; +use crate::compression_methods::*; +use crate::extension::*; +use crate::record_layer::record_layer_header::*; + +/* +The server will send this message in response to a ClientHello +message when it was able to find an acceptable set of algorithms. +If it cannot find such a match, it will respond with a handshake +failure alert. +https://tools.ietf.org/html/rfc5246#section-7.4.1.3 +*/ +#[derive(Clone)] +pub struct HandshakeMessageServerHello { + pub(crate) version: ProtocolVersion, + pub(crate) random: HandshakeRandom, + + pub(crate) cipher_suite: CipherSuiteId, + pub(crate) compression_method: CompressionMethodId, + pub(crate) extensions: Vec, +} + +impl PartialEq for HandshakeMessageServerHello { + fn eq(&self, other: &Self) -> bool { + self.version == other.version + && self.random == other.random + && self.compression_method == other.compression_method + && self.extensions == other.extensions + && self.cipher_suite == other.cipher_suite + } +} + +impl fmt::Debug for HandshakeMessageServerHello { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let s = vec![ + format!("version: {:?} random: {:?}", self.version, self.random), + format!("cipher_suites: {:?}", self.cipher_suite), + format!("compression_method: {:?}", self.compression_method), + format!("extensions: {:?}", self.extensions), + ]; + write!(f, "{}", s.join(" ")) + } +} + +impl HandshakeMessageServerHello { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::ServerHello + } + + pub fn size(&self) -> usize { + let mut len = 2 + self.random.size(); + + // SessionID + len += 1; + + len += 2; + + len += 1; + + len += 2; + for extension in &self.extensions { + len += extension.size(); + } + + len + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + writer.write_u8(self.version.major)?; + writer.write_u8(self.version.minor)?; + self.random.marshal(writer)?; + + // SessionID + writer.write_u8(0x00)?; + + writer.write_u16::(self.cipher_suite as u16)?; + + writer.write_u8(self.compression_method as u8)?; + + let mut extension_buffer = vec![]; + { + let mut extension_writer = BufWriter::<&mut Vec>::new(extension_buffer.as_mut()); + for extension in &self.extensions { + extension.marshal(&mut extension_writer)?; + } + } + + writer.write_u16::(extension_buffer.len() as u16)?; + writer.write_all(&extension_buffer)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let major = reader.read_u8()?; + let minor = reader.read_u8()?; + let random = HandshakeRandom::unmarshal(reader)?; + + // Session ID + let session_id_len = reader.read_u8()? as usize; + let mut session_id_buffer = vec![0u8; session_id_len]; + reader.read_exact(&mut session_id_buffer)?; + + let cipher_suite: CipherSuiteId = reader.read_u16::()?.into(); + + let compression_method = reader.read_u8()?.into(); + let mut extensions = vec![]; + + let extension_buffer_len = reader.read_u16::()? as usize; + let mut extension_buffer = vec![0u8; extension_buffer_len]; + reader.read_exact(&mut extension_buffer)?; + + let mut offset = 0; + while offset < extension_buffer_len { + let mut extension_reader = BufReader::new(&extension_buffer[offset..]); + if let Ok(extension) = Extension::unmarshal(&mut extension_reader) { + extensions.push(extension); + } else { + log::warn!( + "Unsupported Extension Type {} {}", + extension_buffer[offset], + extension_buffer[offset + 1] + ); + } + + let extension_len = + u16::from_be_bytes([extension_buffer[offset + 2], extension_buffer[offset + 3]]) + as usize; + offset += 4 + extension_len; + } + + Ok(HandshakeMessageServerHello { + version: ProtocolVersion { major, minor }, + random, + + cipher_suite, + compression_method, + extensions, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello/handshake_message_server_hello_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello/handshake_message_server_hello_test.rs new file mode 100644 index 0000000..ba906e0 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello/handshake_message_server_hello_test.rs @@ -0,0 +1,56 @@ +use std::io::{BufReader, BufWriter}; +use std::time::{Duration, SystemTime}; + +use super::*; + +#[test] +fn test_handshake_message_server_hello() -> Result<()> { + let raw_server_hello = vec![ + 0xfe, 0xfd, 0x21, 0x63, 0x32, 0x21, 0x81, 0x0e, 0x98, 0x6c, 0x85, 0x3d, 0xa4, 0x39, 0xaf, + 0x5f, 0xd6, 0x5c, 0xcc, 0x20, 0x7f, 0x7c, 0x78, 0xf1, 0x5f, 0x7e, 0x1c, 0xb7, 0xa1, 0x1e, + 0xcf, 0x63, 0x84, 0x28, 0x00, 0xc0, 0x2b, 0x00, 0x00, 0x00, + ]; + + let gmt_unix_time = if let Some(unix_time) = + SystemTime::UNIX_EPOCH.checked_add(Duration::new(560149025u64, 0)) + { + unix_time + } else { + SystemTime::UNIX_EPOCH + }; + let parsed_server_hello = HandshakeMessageServerHello { + version: ProtocolVersion { + major: 0xFE, + minor: 0xFD, + }, + random: HandshakeRandom { + gmt_unix_time, + random_bytes: [ + 0x81, 0x0e, 0x98, 0x6c, 0x85, 0x3d, 0xa4, 0x39, 0xaf, 0x5f, 0xd6, 0x5c, 0xcc, 0x20, + 0x7f, 0x7c, 0x78, 0xf1, 0x5f, 0x7e, 0x1c, 0xb7, 0xa1, 0x1e, 0xcf, 0x63, 0x84, 0x28, + ], + }, + cipher_suite: CipherSuiteId::Tls_Ecdhe_Ecdsa_With_Aes_128_Gcm_Sha256, + compression_method: CompressionMethodId::Null, + extensions: vec![], + }; + + let mut reader = BufReader::new(raw_server_hello.as_slice()); + let c = HandshakeMessageServerHello::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_server_hello, + "handshakeMessageServerHello unmarshal: got {c:?}, want {parsed_server_hello:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_server_hello, + "handshakeMessageServerHello marshal: got {raw:?}, want {raw_server_hello:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done.rs new file mode 100644 index 0000000..bae58f2 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done.rs @@ -0,0 +1,27 @@ +#[cfg(test)] +mod handshake_message_server_hello_done_test; + +use std::io::{Read, Write}; + +use super::*; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageServerHelloDone; + +impl HandshakeMessageServerHelloDone { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::ServerHelloDone + } + + pub fn size(&self) -> usize { + 0 + } + + pub fn marshal(&self, _writer: &mut W) -> Result<()> { + Ok(()) + } + + pub fn unmarshal(_reader: &mut R) -> Result { + Ok(HandshakeMessageServerHelloDone {}) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done/handshake_message_server_hello_done_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done/handshake_message_server_hello_done_test.rs new file mode 100644 index 0000000..b9d3b83 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_hello_done/handshake_message_server_hello_done_test.rs @@ -0,0 +1,28 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_server_hello_done() -> Result<()> { + let raw_server_hello_done = vec![]; + let parsed_server_hello_done = HandshakeMessageServerHelloDone {}; + + let mut reader = BufReader::new(raw_server_hello_done.as_slice()); + let c = HandshakeMessageServerHelloDone::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_server_hello_done, + "handshakeMessageServerHelloDone unmarshal: got {c:?}, want {parsed_server_hello_done:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_server_hello_done, + "handshakeMessageServerHelloDone marshal: got {raw:?}, want {raw_server_hello_done:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange.rs new file mode 100644 index 0000000..e843842 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange.rs @@ -0,0 +1,133 @@ +#[cfg(test)] +mod handshake_message_server_key_exchange_test; + +use std::io::{Read, Write}; + +use byteorder::{BigEndian, WriteBytesExt}; + +use super::*; +use crate::curve::named_curve::*; +use crate::curve::*; +use crate::signature_hash_algorithm::*; + +// Structure supports ECDH and PSK +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeMessageServerKeyExchange { + pub(crate) identity_hint: Vec, + + pub(crate) elliptic_curve_type: EllipticCurveType, + pub(crate) named_curve: NamedCurve, + pub(crate) public_key: Vec, + pub(crate) algorithm: SignatureHashAlgorithm, + pub(crate) signature: Vec, +} + +impl HandshakeMessageServerKeyExchange { + pub fn handshake_type(&self) -> HandshakeType { + HandshakeType::ServerKeyExchange + } + + pub fn size(&self) -> usize { + if !self.identity_hint.is_empty() { + 2 + self.identity_hint.len() + } else { + 1 + 2 + 1 + self.public_key.len() + 2 + 2 + self.signature.len() + } + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + if !self.identity_hint.is_empty() { + writer.write_u16::(self.identity_hint.len() as u16)?; + writer.write_all(&self.identity_hint)?; + return Ok(writer.flush()?); + } + + writer.write_u8(self.elliptic_curve_type as u8)?; + writer.write_u16::(self.named_curve as u16)?; + + writer.write_u8(self.public_key.len() as u8)?; + writer.write_all(&self.public_key)?; + + writer.write_u8(self.algorithm.hash as u8)?; + writer.write_u8(self.algorithm.signature as u8)?; + + writer.write_u16::(self.signature.len() as u16)?; + writer.write_all(&self.signature)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let mut data = vec![]; + reader.read_to_end(&mut data)?; + + // If parsed as PSK return early and only populate PSK Identity Hint + let psk_length = ((data[0] as u16) << 8) | data[1] as u16; + if data.len() == psk_length as usize + 2 { + return Ok(HandshakeMessageServerKeyExchange { + identity_hint: data[2..].to_vec(), + + elliptic_curve_type: EllipticCurveType::Unsupported, + named_curve: NamedCurve::Unsupported, + public_key: vec![], + algorithm: SignatureHashAlgorithm { + hash: HashAlgorithm::Unsupported, + signature: SignatureAlgorithm::Unsupported, + }, + signature: vec![], + }); + } + + let elliptic_curve_type = data[0].into(); + if data[1..].len() < 2 { + return Err(Error::ErrBufferTooSmall); + } + + let named_curve = (((data[1] as u16) << 8) | data[2] as u16).into(); + if data.len() < 4 { + return Err(Error::ErrBufferTooSmall); + } + + let public_key_length = data[3] as usize; + let mut offset = 4 + public_key_length; + if data.len() < offset { + return Err(Error::ErrBufferTooSmall); + } + let public_key = data[4..offset].to_vec(); + if data.len() <= offset { + return Err(Error::ErrBufferTooSmall); + } + + let hash_algorithm = data[offset].into(); + offset += 1; + if data.len() <= offset { + return Err(Error::ErrBufferTooSmall); + } + + let signature_algorithm = data[offset].into(); + offset += 1; + if data.len() < offset + 2 { + return Err(Error::ErrBufferTooSmall); + } + + let signature_length = (((data[offset] as u16) << 8) | data[offset + 1] as u16) as usize; + offset += 2; + if data.len() < offset + signature_length { + return Err(Error::ErrBufferTooSmall); + } + let signature = data[offset..offset + signature_length].to_vec(); + + Ok(HandshakeMessageServerKeyExchange { + identity_hint: vec![], + + elliptic_curve_type, + named_curve, + public_key, + algorithm: SignatureHashAlgorithm { + hash: hash_algorithm, + signature: signature_algorithm, + }, + signature, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange/handshake_message_server_key_exchange_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange/handshake_message_server_key_exchange_test.rs new file mode 100644 index 0000000..4fd7adf --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_message_server_key_exchange/handshake_message_server_key_exchange_test.rs @@ -0,0 +1,50 @@ +use std::io::{BufReader, BufWriter}; + +use super::*; + +#[test] +fn test_handshake_message_server_key_exchange() -> Result<()> { + let raw_server_key_exchange = vec![ + 0x03, 0x00, 0x1d, 0x41, 0x04, 0x0c, 0xb9, 0xa3, 0xb9, 0x90, 0x71, 0x35, 0x4a, 0x08, 0x66, + 0xaf, 0xd6, 0x88, 0x58, 0x29, 0x69, 0x98, 0xf1, 0x87, 0x0f, 0xb5, 0xa8, 0xcd, 0x92, 0xf6, + 0x2b, 0x08, 0x0c, 0xd4, 0x16, 0x5b, 0xcc, 0x81, 0xf2, 0x58, 0x91, 0x8e, 0x62, 0xdf, 0xc1, + 0xec, 0x72, 0xe8, 0x47, 0x24, 0x42, 0x96, 0xb8, 0x7b, 0xee, 0xe7, 0x0d, 0xdc, 0x44, 0xec, + 0xf3, 0x97, 0x6b, 0x1b, 0x45, 0x28, 0xac, 0x3f, 0x35, 0x02, 0x03, 0x00, 0x47, 0x30, 0x45, + 0x02, 0x21, 0x00, 0xb2, 0x0b, 0x22, 0x95, 0x3d, 0x56, 0x57, 0x6a, 0x3f, 0x85, 0x30, 0x6f, + 0x55, 0xc3, 0xf4, 0x24, 0x1b, 0x21, 0x07, 0xe5, 0xdf, 0xba, 0x24, 0x02, 0x68, 0x95, 0x1f, + 0x6e, 0x13, 0xbd, 0x9f, 0xaa, 0x02, 0x20, 0x49, 0x9c, 0x9d, 0xdf, 0x84, 0x60, 0x33, 0x27, + 0x96, 0x9e, 0x58, 0x6d, 0x72, 0x13, 0xe7, 0x3a, 0xe8, 0xdf, 0x43, 0x75, 0xc7, 0xb9, 0x37, + 0x6e, 0x90, 0xe5, 0x3b, 0x81, 0xd4, 0xda, 0x68, 0xcd, + ]; + let parsed_server_key_exchange = HandshakeMessageServerKeyExchange { + identity_hint: vec![], + elliptic_curve_type: EllipticCurveType::NamedCurve, + named_curve: NamedCurve::X25519, + public_key: raw_server_key_exchange[4..69].to_vec(), + algorithm: SignatureHashAlgorithm { + hash: HashAlgorithm::Sha1, + signature: SignatureAlgorithm::Ecdsa, + }, + + signature: raw_server_key_exchange[73..144].to_vec(), + }; + + let mut reader = BufReader::new(raw_server_key_exchange.as_slice()); + let c = HandshakeMessageServerKeyExchange::unmarshal(&mut reader)?; + assert_eq!( + c, parsed_server_key_exchange, + "handshakeMessageServerKeyExchange unmarshal: got {c:?}, want {parsed_server_key_exchange:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + c.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_server_key_exchange, + "handshakeMessageServerKeyExchange marshal: got {raw:?}, want {raw_server_key_exchange:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_random.rs b/vendor/webrtc-dtls/src/handshake/handshake_random.rs new file mode 100644 index 0000000..4ff468a --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_random.rs @@ -0,0 +1,67 @@ +use std::io::{self, Read, Write}; +use std::time::{Duration, SystemTime}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; +use rand::Rng; + +pub const RANDOM_BYTES_LENGTH: usize = 28; +pub const HANDSHAKE_RANDOM_LENGTH: usize = RANDOM_BYTES_LENGTH + 4; + +// https://tools.ietf.org/html/rfc4346#section-7.4.1.2 +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HandshakeRandom { + pub gmt_unix_time: SystemTime, + pub random_bytes: [u8; RANDOM_BYTES_LENGTH], +} + +impl Default for HandshakeRandom { + fn default() -> Self { + HandshakeRandom { + gmt_unix_time: SystemTime::UNIX_EPOCH, + random_bytes: [0u8; RANDOM_BYTES_LENGTH], + } + } +} + +impl HandshakeRandom { + pub fn size(&self) -> usize { + 4 + RANDOM_BYTES_LENGTH + } + + pub fn marshal(&self, writer: &mut W) -> io::Result<()> { + let secs = match self.gmt_unix_time.duration_since(SystemTime::UNIX_EPOCH) { + Ok(d) => d.as_secs() as u32, + Err(_) => 0, + }; + writer.write_u32::(secs)?; + writer.write_all(&self.random_bytes)?; + + writer.flush() + } + + pub fn unmarshal(reader: &mut R) -> io::Result { + let secs = reader.read_u32::()?; + let gmt_unix_time = if let Some(unix_time) = + SystemTime::UNIX_EPOCH.checked_add(Duration::new(secs as u64, 0)) + { + unix_time + } else { + SystemTime::UNIX_EPOCH + }; + + let mut random_bytes = [0u8; RANDOM_BYTES_LENGTH]; + reader.read_exact(&mut random_bytes)?; + + Ok(HandshakeRandom { + gmt_unix_time, + random_bytes, + }) + } + + // populate fills the HandshakeRandom with random values + // may be called multiple times + pub fn populate(&mut self) { + self.gmt_unix_time = SystemTime::now(); + rand::thread_rng().fill(&mut self.random_bytes); + } +} diff --git a/vendor/webrtc-dtls/src/handshake/handshake_test.rs b/vendor/webrtc-dtls/src/handshake/handshake_test.rs new file mode 100644 index 0000000..a61da45 --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/handshake_test.rs @@ -0,0 +1,70 @@ +use std::io::{BufReader, BufWriter}; +use std::time::{Duration, SystemTime}; + +use super::*; +use crate::compression_methods::*; +use crate::handshake::handshake_message_client_hello::*; +use crate::handshake::handshake_random::HandshakeRandom; +use crate::record_layer::record_layer_header::ProtocolVersion; + +#[test] +fn test_handshake_message() -> Result<()> { + let raw_handshake_message = vec![ + 0x01, 0x00, 0x00, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0xfe, 0xfd, 0xb6, + 0x2f, 0xce, 0x5c, 0x42, 0x54, 0xff, 0x86, 0xe1, 0x24, 0x41, 0x91, 0x42, 0x62, 0x15, 0xad, + 0x16, 0xc9, 0x15, 0x8d, 0x95, 0x71, 0x8a, 0xbb, 0x22, 0xd7, 0x47, 0xec, 0xd8, 0x3d, 0xdc, + 0x4b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]; + let parsed_handshake = Handshake { + handshake_header: HandshakeHeader { + handshake_type: HandshakeType::ClientHello, + length: 0x29, + message_sequence: 0, + fragment_offset: 0, + fragment_length: 0x29, + }, + handshake_message: HandshakeMessage::ClientHello(HandshakeMessageClientHello { + version: ProtocolVersion { + major: 0xFE, + minor: 0xFD, + }, + random: HandshakeRandom { + gmt_unix_time: if let Some(unix_time) = + SystemTime::UNIX_EPOCH.checked_add(Duration::new(3056586332u64, 0)) + { + unix_time + } else { + SystemTime::UNIX_EPOCH + }, + random_bytes: [ + 0x42, 0x54, 0xff, 0x86, 0xe1, 0x24, 0x41, 0x91, 0x42, 0x62, 0x15, 0xad, 0x16, + 0xc9, 0x15, 0x8d, 0x95, 0x71, 0x8a, 0xbb, 0x22, 0xd7, 0x47, 0xec, 0xd8, 0x3d, + 0xdc, 0x4b, + ], + }, + cookie: vec![], + cipher_suites: vec![], + compression_methods: CompressionMethods { ids: vec![] }, + extensions: vec![], + }), + }; + + let mut reader = BufReader::new(raw_handshake_message.as_slice()); + let h = Handshake::unmarshal(&mut reader)?; + assert_eq!( + h, parsed_handshake, + "handshakeMessageClientHello unmarshal: got {h:?}, want {parsed_handshake:?}" + ); + + let mut raw = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(raw.as_mut()); + h.marshal(&mut writer)?; + } + assert_eq!( + raw, raw_handshake_message, + "handshakeMessageClientHello marshal: got {raw:?}, want {raw_handshake_message:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/handshake/mod.rs b/vendor/webrtc-dtls/src/handshake/mod.rs new file mode 100644 index 0000000..a71f44f --- /dev/null +++ b/vendor/webrtc-dtls/src/handshake/mod.rs @@ -0,0 +1,238 @@ +pub mod handshake_cache; +pub mod handshake_header; +pub mod handshake_message_certificate; +pub mod handshake_message_certificate_request; +pub mod handshake_message_certificate_verify; +pub mod handshake_message_client_hello; +pub mod handshake_message_client_key_exchange; +pub mod handshake_message_finished; +pub mod handshake_message_hello_verify_request; +pub mod handshake_message_server_hello; +pub mod handshake_message_server_hello_done; +pub mod handshake_message_server_key_exchange; +pub mod handshake_random; + +#[cfg(test)] +mod handshake_test; + +use std::fmt; +use std::io::{Read, Write}; + +use handshake_header::*; +use handshake_message_certificate::*; +use handshake_message_certificate_request::*; +use handshake_message_certificate_verify::*; +use handshake_message_client_hello::*; +use handshake_message_client_key_exchange::*; +use handshake_message_finished::*; +use handshake_message_hello_verify_request::*; +use handshake_message_server_hello::*; +use handshake_message_server_hello_done::*; +use handshake_message_server_key_exchange::*; + +use super::content::*; +use super::error::*; + +// https://tools.ietf.org/html/rfc5246#section-7.4 +#[derive(Default, Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub enum HandshakeType { + HelloRequest = 0, + ClientHello = 1, + ServerHello = 2, + HelloVerifyRequest = 3, + Certificate = 11, + ServerKeyExchange = 12, + CertificateRequest = 13, + ServerHelloDone = 14, + CertificateVerify = 15, + ClientKeyExchange = 16, + Finished = 20, + #[default] + Invalid, +} + +impl fmt::Display for HandshakeType { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + HandshakeType::HelloRequest => write!(f, "HelloRequest"), + HandshakeType::ClientHello => write!(f, "ClientHello"), + HandshakeType::ServerHello => write!(f, "ServerHello"), + HandshakeType::HelloVerifyRequest => write!(f, "HelloVerifyRequest"), + HandshakeType::Certificate => write!(f, "Certificate"), + HandshakeType::ServerKeyExchange => write!(f, "ServerKeyExchange"), + HandshakeType::CertificateRequest => write!(f, "CertificateRequest"), + HandshakeType::ServerHelloDone => write!(f, "ServerHelloDone"), + HandshakeType::CertificateVerify => write!(f, "CertificateVerify"), + HandshakeType::ClientKeyExchange => write!(f, "ClientKeyExchange"), + HandshakeType::Finished => write!(f, "Finished"), + HandshakeType::Invalid => write!(f, "Invalid"), + } + } +} + +impl From for HandshakeType { + fn from(val: u8) -> Self { + match val { + 0 => HandshakeType::HelloRequest, + 1 => HandshakeType::ClientHello, + 2 => HandshakeType::ServerHello, + 3 => HandshakeType::HelloVerifyRequest, + 11 => HandshakeType::Certificate, + 12 => HandshakeType::ServerKeyExchange, + 13 => HandshakeType::CertificateRequest, + 14 => HandshakeType::ServerHelloDone, + 15 => HandshakeType::CertificateVerify, + 16 => HandshakeType::ClientKeyExchange, + 20 => HandshakeType::Finished, + _ => HandshakeType::Invalid, + } + } +} + +#[derive(PartialEq, Debug, Clone)] +pub enum HandshakeMessage { + //HelloRequest(errNotImplemented), + ClientHello(HandshakeMessageClientHello), + ServerHello(HandshakeMessageServerHello), + HelloVerifyRequest(HandshakeMessageHelloVerifyRequest), + Certificate(HandshakeMessageCertificate), + ServerKeyExchange(HandshakeMessageServerKeyExchange), + CertificateRequest(HandshakeMessageCertificateRequest), + ServerHelloDone(HandshakeMessageServerHelloDone), + CertificateVerify(HandshakeMessageCertificateVerify), + ClientKeyExchange(HandshakeMessageClientKeyExchange), + Finished(HandshakeMessageFinished), +} + +impl HandshakeMessage { + pub fn handshake_type(&self) -> HandshakeType { + match self { + HandshakeMessage::ClientHello(msg) => msg.handshake_type(), + HandshakeMessage::ServerHello(msg) => msg.handshake_type(), + HandshakeMessage::HelloVerifyRequest(msg) => msg.handshake_type(), + HandshakeMessage::Certificate(msg) => msg.handshake_type(), + HandshakeMessage::ServerKeyExchange(msg) => msg.handshake_type(), + HandshakeMessage::CertificateRequest(msg) => msg.handshake_type(), + HandshakeMessage::ServerHelloDone(msg) => msg.handshake_type(), + HandshakeMessage::CertificateVerify(msg) => msg.handshake_type(), + HandshakeMessage::ClientKeyExchange(msg) => msg.handshake_type(), + HandshakeMessage::Finished(msg) => msg.handshake_type(), + } + } + + pub fn size(&self) -> usize { + match self { + HandshakeMessage::ClientHello(msg) => msg.size(), + HandshakeMessage::ServerHello(msg) => msg.size(), + HandshakeMessage::HelloVerifyRequest(msg) => msg.size(), + HandshakeMessage::Certificate(msg) => msg.size(), + HandshakeMessage::ServerKeyExchange(msg) => msg.size(), + HandshakeMessage::CertificateRequest(msg) => msg.size(), + HandshakeMessage::ServerHelloDone(msg) => msg.size(), + HandshakeMessage::CertificateVerify(msg) => msg.size(), + HandshakeMessage::ClientKeyExchange(msg) => msg.size(), + HandshakeMessage::Finished(msg) => msg.size(), + } + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + match self { + HandshakeMessage::ClientHello(msg) => msg.marshal(writer)?, + HandshakeMessage::ServerHello(msg) => msg.marshal(writer)?, + HandshakeMessage::HelloVerifyRequest(msg) => msg.marshal(writer)?, + HandshakeMessage::Certificate(msg) => msg.marshal(writer)?, + HandshakeMessage::ServerKeyExchange(msg) => msg.marshal(writer)?, + HandshakeMessage::CertificateRequest(msg) => msg.marshal(writer)?, + HandshakeMessage::ServerHelloDone(msg) => msg.marshal(writer)?, + HandshakeMessage::CertificateVerify(msg) => msg.marshal(writer)?, + HandshakeMessage::ClientKeyExchange(msg) => msg.marshal(writer)?, + HandshakeMessage::Finished(msg) => msg.marshal(writer)?, + } + + Ok(()) + } +} + +// The handshake protocol is responsible for selecting a cipher spec and +// generating a master secret, which together comprise the primary +// cryptographic parameters associated with a secure session. The +// handshake protocol can also optionally authenticate parties who have +// certificates signed by a trusted certificate authority. +// https://tools.ietf.org/html/rfc5246#section-7.3 +#[derive(PartialEq, Debug, Clone)] +pub struct Handshake { + pub(crate) handshake_header: HandshakeHeader, + pub(crate) handshake_message: HandshakeMessage, +} + +impl Handshake { + pub fn new(handshake_message: HandshakeMessage) -> Self { + Handshake { + handshake_header: HandshakeHeader { + handshake_type: handshake_message.handshake_type(), + length: handshake_message.size() as u32, + message_sequence: 0, + fragment_offset: 0, + fragment_length: handshake_message.size() as u32, + }, + handshake_message, + } + } + + pub fn content_type(&self) -> ContentType { + ContentType::Handshake + } + + pub fn size(&self) -> usize { + self.handshake_header.size() + self.handshake_message.size() + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + self.handshake_header.marshal(writer)?; + self.handshake_message.marshal(writer)?; + Ok(()) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let handshake_header = HandshakeHeader::unmarshal(reader)?; + + let handshake_message = match handshake_header.handshake_type { + HandshakeType::ClientHello => { + HandshakeMessage::ClientHello(HandshakeMessageClientHello::unmarshal(reader)?) + } + HandshakeType::ServerHello => { + HandshakeMessage::ServerHello(HandshakeMessageServerHello::unmarshal(reader)?) + } + HandshakeType::HelloVerifyRequest => HandshakeMessage::HelloVerifyRequest( + HandshakeMessageHelloVerifyRequest::unmarshal(reader)?, + ), + HandshakeType::Certificate => { + HandshakeMessage::Certificate(HandshakeMessageCertificate::unmarshal(reader)?) + } + HandshakeType::ServerKeyExchange => HandshakeMessage::ServerKeyExchange( + HandshakeMessageServerKeyExchange::unmarshal(reader)?, + ), + HandshakeType::CertificateRequest => HandshakeMessage::CertificateRequest( + HandshakeMessageCertificateRequest::unmarshal(reader)?, + ), + HandshakeType::ServerHelloDone => HandshakeMessage::ServerHelloDone( + HandshakeMessageServerHelloDone::unmarshal(reader)?, + ), + HandshakeType::CertificateVerify => HandshakeMessage::CertificateVerify( + HandshakeMessageCertificateVerify::unmarshal(reader)?, + ), + HandshakeType::ClientKeyExchange => HandshakeMessage::ClientKeyExchange( + HandshakeMessageClientKeyExchange::unmarshal(reader)?, + ), + HandshakeType::Finished => { + HandshakeMessage::Finished(HandshakeMessageFinished::unmarshal(reader)?) + } + _ => return Err(Error::ErrNotImplemented), + }; + + Ok(Handshake { + handshake_header, + handshake_message, + }) + } +} diff --git a/vendor/webrtc-dtls/src/handshaker.rs b/vendor/webrtc-dtls/src/handshaker.rs new file mode 100644 index 0000000..1598f6e --- /dev/null +++ b/vendor/webrtc-dtls/src/handshaker.rs @@ -0,0 +1,410 @@ +use std::collections::HashMap; +use std::fmt; +use std::sync::Arc; + +use log::*; + +use crate::cipher_suite::*; +use crate::config::*; +use crate::conn::*; +use crate::content::*; +use crate::crypto::*; +use crate::error::*; +use crate::extension::extension_use_srtp::*; +use crate::signature_hash_algorithm::*; + +//use std::io::BufWriter; + +// [RFC6347 Section-4.2.4] +// +-----------+ +// +---> | PREPARING | <--------------------+ +// | +-----------+ | +// | | | +// | | Buffer next flight | +// | | | +// | \|/ | +// | +-----------+ | +// | | SENDING |<------------------+ | Send +// | +-----------+ | | HelloRequest +// Receive | | | | +// next | | Send flight | | or +// flight | +--------+ | | +// | | | Set retransmit timer | | Receive +// | | \|/ | | HelloRequest +// | | +-----------+ | | Send +// +--)--| WAITING |-------------------+ | ClientHello +// | | +-----------+ Timer expires | | +// | | | | | +// | | +------------------------+ | +// Receive | | Send Read retransmit | +// last | | last | +// flight | | flight | +// | | | +// \|/\|/ | +// +-----------+ | +// | FINISHED | -------------------------------+ +// +-----------+ +// | /|\ +// | | +// +---+ +// Read retransmit +// Retransmit last flight + +#[derive(Copy, Clone, PartialEq)] +pub(crate) enum HandshakeState { + Errored, + Preparing, + Sending, + Waiting, + Finished, +} + +impl fmt::Display for HandshakeState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + HandshakeState::Errored => write!(f, "Errored"), + HandshakeState::Preparing => write!(f, "Preparing"), + HandshakeState::Sending => write!(f, "Sending"), + HandshakeState::Waiting => write!(f, "Waiting"), + HandshakeState::Finished => write!(f, "Finished"), + } + } +} + +pub(crate) type VerifyPeerCertificateFn = + Arc], &[rustls::Certificate]) -> Result<()>) + Send + Sync>; + +pub(crate) struct HandshakeConfig { + pub(crate) local_psk_callback: Option, + pub(crate) local_psk_identity_hint: Option>, + pub(crate) local_cipher_suites: Vec, // Available CipherSuites + pub(crate) local_signature_schemes: Vec, // Available signature schemes + pub(crate) extended_master_secret: ExtendedMasterSecretType, // Policy for the Extended Master Support extension + pub(crate) local_srtp_protection_profiles: Vec, // Available SRTPProtectionProfiles, if empty no SRTP support + pub(crate) server_name: String, + pub(crate) client_auth: ClientAuthType, // If we are a client should we request a client certificate + pub(crate) local_certificates: Vec, + pub(crate) name_to_certificate: HashMap, + pub(crate) insecure_skip_verify: bool, + pub(crate) insecure_verification: bool, + pub(crate) verify_peer_certificate: Option, + pub(crate) server_cert_verifier: Arc, + pub(crate) client_cert_verifier: Option>, + pub(crate) retransmit_interval: tokio::time::Duration, + pub(crate) initial_epoch: u16, + //log logging.LeveledLogger + //mu sync.Mutex +} + +impl Default for HandshakeConfig { + fn default() -> Self { + HandshakeConfig { + local_psk_callback: None, + local_psk_identity_hint: None, + local_cipher_suites: vec![], + local_signature_schemes: vec![], + extended_master_secret: ExtendedMasterSecretType::Disable, + local_srtp_protection_profiles: vec![], + server_name: String::new(), + client_auth: ClientAuthType::NoClientCert, + local_certificates: vec![], + name_to_certificate: HashMap::new(), + insecure_skip_verify: false, + insecure_verification: false, + verify_peer_certificate: None, + server_cert_verifier: Arc::new(rustls::client::WebPkiVerifier::new( + rustls::RootCertStore::empty(), + None, + )), + client_cert_verifier: None, + retransmit_interval: tokio::time::Duration::from_secs(0), + initial_epoch: 0, + } + } +} + +impl HandshakeConfig { + pub(crate) fn get_certificate(&self, server_name: &str) -> Result { + //TODO + /*if self.name_to_certificate.is_empty() { + let mut name_to_certificate = HashMap::new(); + for cert in &self.local_certificates { + if let Ok((_rem, x509_cert)) = x509_parser::parse_x509_der(&cert.certificate) { + if let Some(a) = x509_cert.tbs_certificate.subject.iter_common_name().next() { + let common_name = match a.attr_value.as_str() { + Ok(cn) => cn.to_lowercase(), + Err(err) => return Err(Error::new(err.to_string())), + }; + name_to_certificate.insert(common_name, cert.clone()); + } + if let Some((_, sans)) = x509_cert.tbs_certificate.subject_alternative_name() { + for gn in &sans.general_names { + match gn { + x509_parser::extensions::GeneralName::DNSName(san) => { + let san = san.to_lowercase(); + name_to_certificate.insert(san, cert.clone()); + } + _ => {} + } + } + } + } else { + continue; + } + } + self.name_to_certificate = name_to_certificate; + }*/ + + if self.local_certificates.is_empty() { + return Err(Error::ErrNoCertificates); + } + + if self.local_certificates.len() == 1 { + // There's only one choice, so no point doing any work. + return Ok(self.local_certificates[0].clone()); + } + + if server_name.is_empty() { + return Ok(self.local_certificates[0].clone()); + } + + let lower = server_name.to_lowercase(); + let name = lower.trim_end_matches('.'); + + if let Some(cert) = self.name_to_certificate.get(name) { + return Ok(cert.clone()); + } + + // try replacing labels in the name with wildcards until we get a + // match. + let mut labels: Vec<&str> = name.split_terminator('.').collect(); + for i in 0..labels.len() { + labels[i] = "*"; + let candidate = labels.join("."); + if let Some(cert) = self.name_to_certificate.get(&candidate) { + return Ok(cert.clone()); + } + } + + // If nothing matches, return the first certificate. + Ok(self.local_certificates[0].clone()) + } +} + +pub(crate) fn srv_cli_str(is_client: bool) -> String { + if is_client { + return "client".to_owned(); + } + "server".to_owned() +} + +impl DTLSConn { + pub(crate) async fn handshake(&mut self, mut state: HandshakeState) -> Result<()> { + loop { + trace!( + "[handshake:{}] {}: {}", + srv_cli_str(self.state.is_client), + self.current_flight.to_string(), + state.to_string() + ); + + if state == HandshakeState::Finished && !self.is_handshake_completed_successfully() { + self.set_handshake_completed_successfully(); + self.handshake_done_tx.take(); // drop it by take + return Ok(()); + } + + state = match state { + HandshakeState::Preparing => self.prepare().await?, + HandshakeState::Sending => self.send().await?, + HandshakeState::Waiting => self.wait().await?, + HandshakeState::Finished => self.finish().await?, + _ => return Err(Error::ErrInvalidFsmTransition), + }; + } + } + + async fn prepare(&mut self) -> Result { + self.flights = None; + + // Prepare flights + self.retransmit = self.current_flight.has_retransmit(); + + let result = self + .current_flight + .generate(&mut self.state, &self.cache, &self.cfg) + .await; + + match result { + Err((a, mut err)) => { + if let Some(a) = a { + let alert_err = self.notify(a.alert_level, a.alert_description).await; + + if let Err(alert_err) = alert_err { + if err.is_some() { + err = Some(alert_err); + } + } + } + if let Some(err) = err { + return Err(err); + } + } + Ok(pkts) => { + /*if !pkts.is_empty() { + let mut s = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(s.as_mut()); + pkts[0].record.content.marshal(&mut writer)?; + } + trace!( + "[handshake:{}] {}: {:?}", + srv_cli_str(self.state.is_client), + self.current_flight.to_string(), + s, + ); + }*/ + self.flights = Some(pkts) + } + }; + + let epoch = self.cfg.initial_epoch; + let mut next_epoch = epoch; + if let Some(pkts) = &mut self.flights { + for p in pkts { + p.record.record_layer_header.epoch += epoch; + if p.record.record_layer_header.epoch > next_epoch { + next_epoch = p.record.record_layer_header.epoch; + } + if let Content::Handshake(h) = &mut p.record.content { + h.handshake_header.message_sequence = self.state.handshake_send_sequence as u16; + self.state.handshake_send_sequence += 1; + } + } + } + if epoch != next_epoch { + trace!( + "[handshake:{}] -> changeCipherSpec (epoch: {})", + srv_cli_str(self.state.is_client), + next_epoch + ); + self.set_local_epoch(next_epoch); + } + + Ok(HandshakeState::Sending) + } + async fn send(&mut self) -> Result { + // Send flights + if let Some(pkts) = self.flights.clone() { + self.write_packets(pkts).await?; + } + + if self.current_flight.is_last_send_flight() { + Ok(HandshakeState::Finished) + } else { + Ok(HandshakeState::Waiting) + } + } + async fn wait(&mut self) -> Result { + let retransmit_timer = tokio::time::sleep(self.cfg.retransmit_interval); + tokio::pin!(retransmit_timer); + + loop { + tokio::select! { + done = self.handshake_rx.recv() =>{ + if done.is_none() { + trace!("[handshake:{}] {} handshake_tx is dropped", srv_cli_str(self.state.is_client), self.current_flight.to_string()); + return Err(Error::ErrAlertFatalOrClose); + } + + //trace!("[handshake:{}] {} received handshake_rx", srv_cli_str(self.state.is_client), self.current_flight.to_string()); + let result = self.current_flight.parse(&mut self.handle_queue_tx, &mut self.state, &self.cache, &self.cfg).await; + drop(done); + match result { + Err((alert, mut err)) => { + trace!("[handshake:{}] {} result alert:{:?}, err:{:?}", + srv_cli_str(self.state.is_client), + self.current_flight.to_string(), + alert, + err); + + if let Some(alert) = alert { + let alert_err = self.notify(alert.alert_level, alert.alert_description).await; + + if let Err(alert_err) = alert_err { + if err.is_some() { + err = Some(alert_err); + } + } + } + if let Some(err) = err { + return Err(err); + } + } + Ok(next_flight) => { + trace!("[handshake:{}] {} -> {}", srv_cli_str(self.state.is_client), self.current_flight.to_string(), next_flight.to_string()); + if next_flight.is_last_recv_flight() && self.current_flight.to_string() == next_flight.to_string() { + return Ok(HandshakeState::Finished); + } + self.current_flight = next_flight; + return Ok(HandshakeState::Preparing); + } + }; + } + + _ = retransmit_timer.as_mut() =>{ + trace!("[handshake:{}] {} retransmit_timer", srv_cli_str(self.state.is_client), self.current_flight.to_string()); + + if !self.retransmit { + return Ok(HandshakeState::Waiting); + } + return Ok(HandshakeState::Sending); + } + + /*_ = self.done_rx.recv() => { + return Err(Error::new("done_rx recv".to_owned())); + }*/ + } + } + } + async fn finish(&mut self) -> Result { + let retransmit_timer = tokio::time::sleep(self.cfg.retransmit_interval); + + tokio::select! { + done = self.handshake_rx.recv() =>{ + if done.is_none() { + trace!("[handshake:{}] {} handshake_tx is dropped", srv_cli_str(self.state.is_client), self.current_flight.to_string()); + return Err(Error::ErrAlertFatalOrClose); + } + let result = self.current_flight.parse(&mut self.handle_queue_tx, &mut self.state, &self.cache, &self.cfg).await; + drop(done); + match result { + Err((alert, mut err)) => { + if let Some(alert) = alert { + let alert_err = self.notify(alert.alert_level, alert.alert_description).await; + if let Err(alert_err) = alert_err { + if err.is_some() { + err = Some(alert_err); + } + } + } + if let Some(err) = err { + return Err(err); + } + } + Ok(_) => { + retransmit_timer.await; + // Retransmit last flight + return Ok(HandshakeState::Sending); + } + }; + } + + /*_ = self.done_rx.recv() => { + return Err(Error::new("done_rx recv".to_owned())); + }*/ + } + + Ok(HandshakeState::Finished) + } +} diff --git a/vendor/webrtc-dtls/src/lib.rs b/vendor/webrtc-dtls/src/lib.rs new file mode 100644 index 0000000..fd75b6b --- /dev/null +++ b/vendor/webrtc-dtls/src/lib.rs @@ -0,0 +1,57 @@ +#![warn(rust_2018_idioms)] +#![allow(dead_code)] + +pub mod alert; +pub mod application_data; +pub mod change_cipher_spec; +pub mod cipher_suite; +pub mod client_certificate_type; +pub mod compression_methods; +pub mod config; +pub mod conn; +pub mod content; +pub mod crypto; +pub mod curve; +mod error; +pub mod extension; +pub mod flight; +pub mod fragment_buffer; +pub mod handshake; +pub mod handshaker; +pub mod listener; +pub mod prf; +pub mod record_layer; +pub mod signature_hash_algorithm; +pub mod state; + +use cipher_suite::*; +pub use error::Error; +use extension::extension_use_srtp::SrtpProtectionProfile; + +pub(crate) fn find_matching_srtp_profile( + a: &[SrtpProtectionProfile], + b: &[SrtpProtectionProfile], +) -> Result { + for a_profile in a { + for b_profile in b { + if a_profile == b_profile { + return Ok(*a_profile); + } + } + } + Err(()) +} + +pub(crate) fn find_matching_cipher_suite( + a: &[CipherSuiteId], + b: &[CipherSuiteId], +) -> Result { + for a_suite in a { + for b_suite in b { + if a_suite == b_suite { + return Ok(*a_suite); + } + } + } + Err(()) +} diff --git a/vendor/webrtc-dtls/src/listener.rs b/vendor/webrtc-dtls/src/listener.rs new file mode 100644 index 0000000..0dc6257 --- /dev/null +++ b/vendor/webrtc-dtls/src/listener.rs @@ -0,0 +1,95 @@ +use std::future::Future; +use std::io::BufReader; +use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::Arc; + +use async_trait::async_trait; +use tokio::net::ToSocketAddrs; +use util::conn::conn_udp_listener::*; +use util::conn::*; + +use crate::config::*; +use crate::conn::DTLSConn; +use crate::content::ContentType; +use crate::error::Result; +use crate::record_layer::record_layer_header::RecordLayerHeader; +use crate::record_layer::unpack_datagram; + +/// Listen creates a DTLS listener +pub async fn listen(laddr: A, config: Config) -> Result { + validate_config(false, &config)?; + + let mut lc = ListenConfig { + accept_filter: Some(Box::new( + |packet: &[u8]| -> Pin + Send + 'static>> { + let pkts = match unpack_datagram(packet) { + Ok(pkts) => { + if pkts.is_empty() { + return Box::pin(async { false }); + } + pkts + } + Err(_) => return Box::pin(async { false }), + }; + + let mut reader = BufReader::new(pkts[0].as_slice()); + match RecordLayerHeader::unmarshal(&mut reader) { + Ok(h) => { + let content_type = h.content_type; + Box::pin(async move { content_type == ContentType::Handshake }) + } + Err(_) => Box::pin(async { false }), + } + }, + )), + ..Default::default() + }; + + let parent = Arc::new(lc.listen(laddr).await?); + Ok(DTLSListener { parent, config }) +} + +/// DTLSListener represents a DTLS listener +pub struct DTLSListener { + parent: Arc, + config: Config, +} + +impl DTLSListener { + /// creates a DTLS listener which accepts connections from an inner Listener. + pub fn new(parent: Arc, config: Config) -> Result { + validate_config(false, &config)?; + + Ok(DTLSListener { parent, config }) + } +} + +type UtilResult = std::result::Result; + +#[async_trait] +impl Listener for DTLSListener { + /// Accept waits for and returns the next connection to the listener. + /// You have to either close or read on all connection that are created. + /// Connection handshake will timeout using ConnectContextMaker in the Config. + /// If you want to specify the timeout duration, set ConnectContextMaker. + async fn accept(&self) -> UtilResult<(Arc, SocketAddr)> { + let (conn, raddr) = self.parent.accept().await?; + let dtls_conn = DTLSConn::new(conn, self.config.clone(), false, None) + .await + .map_err(util::Error::from_std)?; + Ok((Arc::new(dtls_conn), raddr)) + } + + /// Close closes the listener. + /// Any blocked Accept operations will be unblocked and return errors. + /// Already Accepted connections are not closed. + async fn close(&self) -> UtilResult<()> { + self.parent.close().await + } + + /// Addr returns the listener's network address. + async fn addr(&self) -> UtilResult { + self.parent.addr().await + } +} diff --git a/vendor/webrtc-dtls/src/prf/mod.rs b/vendor/webrtc-dtls/src/prf/mod.rs new file mode 100644 index 0000000..e38cd45 --- /dev/null +++ b/vendor/webrtc-dtls/src/prf/mod.rs @@ -0,0 +1,315 @@ +#[cfg(test)] +mod prf_test; + +use std::convert::TryInto; +use std::fmt; + +use hmac::{Hmac, Mac}; +use sha1::Sha1; +use sha2::{Digest, Sha256}; + +type HmacSha256 = Hmac; +type HmacSha1 = Hmac; + +use crate::cipher_suite::CipherSuiteHash; +use crate::content::ContentType; +use crate::curve::named_curve::*; +use crate::error::*; +use crate::record_layer::record_layer_header::ProtocolVersion; + +pub(crate) const PRF_MASTER_SECRET_LABEL: &str = "master secret"; +pub(crate) const PRF_EXTENDED_MASTER_SECRET_LABEL: &str = "extended master secret"; +pub(crate) const PRF_KEY_EXPANSION_LABEL: &str = "key expansion"; +pub(crate) const PRF_VERIFY_DATA_CLIENT_LABEL: &str = "client finished"; +pub(crate) const PRF_VERIFY_DATA_SERVER_LABEL: &str = "server finished"; + +#[derive(PartialEq, Debug, Clone)] +pub(crate) struct EncryptionKeys { + pub(crate) master_secret: Vec, + pub(crate) client_mac_key: Vec, + pub(crate) server_mac_key: Vec, + pub(crate) client_write_key: Vec, + pub(crate) server_write_key: Vec, + pub(crate) client_write_iv: Vec, + pub(crate) server_write_iv: Vec, +} + +impl fmt::Display for EncryptionKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut out = "EncryptionKeys:\n".to_string(); + + out += format!("- master_secret: {:?}\n", self.master_secret).as_str(); + out += format!("- client_mackey: {:?}\n", self.client_mac_key).as_str(); + out += format!("- server_mackey: {:?}\n", self.server_mac_key).as_str(); + out += format!("- client_write_key: {:?}\n", self.client_write_key).as_str(); + out += format!("- server_write_key: {:?}\n", self.server_write_key).as_str(); + out += format!("- client_write_iv: {:?}\n", self.client_write_iv).as_str(); + out += format!("- server_write_iv: {:?}\n", self.server_write_iv).as_str(); + + write!(f, "{out}") + } +} + +// The premaster secret is formed as follows: if the PSK is N octets +// long, concatenate a uint16 with the value N, N zero octets, a second +// uint16 with the value N, and the PSK itself. +// +// https://tools.ietf.org/html/rfc4279#section-2 +pub(crate) fn prf_psk_pre_master_secret(psk: &[u8]) -> Vec { + let psk_len = psk.len(); + + let mut out = vec![0u8; 2 + psk_len + 2]; + + out.extend_from_slice(psk); + let be = (psk_len as u16).to_be_bytes(); + out[..2].copy_from_slice(&be); + out[2 + psk_len..2 + psk_len + 2].copy_from_slice(&be); + + out +} + +pub(crate) fn prf_pre_master_secret( + public_key: &[u8], + private_key: &NamedCurvePrivateKey, + curve: NamedCurve, +) -> Result> { + match curve { + NamedCurve::P256 => elliptic_curve_pre_master_secret(public_key, private_key, curve), + NamedCurve::P384 => elliptic_curve_pre_master_secret(public_key, private_key, curve), + NamedCurve::X25519 => elliptic_curve_pre_master_secret(public_key, private_key, curve), + _ => Err(Error::ErrInvalidNamedCurve), + } +} + +fn elliptic_curve_pre_master_secret( + public_key: &[u8], + private_key: &NamedCurvePrivateKey, + curve: NamedCurve, +) -> Result> { + match curve { + NamedCurve::P256 => { + let pub_key = p256::EncodedPoint::from_bytes(public_key)?; + let public = p256::PublicKey::from_sec1_bytes(pub_key.as_ref())?; + if let NamedCurvePrivateKey::EphemeralSecretP256(secret) = private_key { + return Ok(secret.diffie_hellman(&public).raw_secret_bytes().to_vec()); + } + } + NamedCurve::P384 => { + let pub_key = p384::EncodedPoint::from_bytes(public_key)?; + let public = p384::PublicKey::from_sec1_bytes(pub_key.as_ref())?; + if let NamedCurvePrivateKey::EphemeralSecretP384(secret) = private_key { + return Ok(secret.diffie_hellman(&public).raw_secret_bytes().to_vec()); + } + } + NamedCurve::X25519 => { + if public_key.len() != 32 { + return Err(Error::Other("Public key is not 32 len".into())); + } + let pub_key: [u8; 32] = public_key.try_into().unwrap(); + let public = x25519_dalek::PublicKey::from(pub_key); + if let NamedCurvePrivateKey::StaticSecretX25519(secret) = private_key { + return Ok(secret.diffie_hellman(&public).as_bytes().to_vec()); + } + } + _ => return Err(Error::ErrInvalidNamedCurve), + } + Err(Error::ErrNamedCurveAndPrivateKeyMismatch) +} + +// This PRF with the SHA-256 hash function is used for all cipher suites +// defined in this document and in TLS documents published prior to this +// document when TLS 1.2 is negotiated. New cipher suites MUST explicitly +// specify a PRF and, in general, SHOULD use the TLS PRF with SHA-256 or a +// stronger standard hash function. +// +// P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + +// HMAC_hash(secret, A(2) + seed) + +// HMAC_hash(secret, A(3) + seed) + ... +// +// A() is defined as: +// +// A(0) = seed +// A(i) = HMAC_hash(secret, A(i-1)) +// +// P_hash can be iterated as many times as necessary to produce the +// required quantity of data. For example, if P_SHA256 is being used to +// create 80 bytes of data, it will have to be iterated three times +// (through A(3)), creating 96 bytes of output data; the last 16 bytes +// of the final iteration will then be discarded, leaving 80 bytes of +// output data. +// +// https://tools.ietf.org/html/rfc4346w +fn hmac_sha(h: CipherSuiteHash, key: &[u8], data: &[u8]) -> Result> { + let mut mac = match h { + CipherSuiteHash::Sha256 => { + HmacSha256::new_from_slice(key).map_err(|e| Error::Other(e.to_string()))? + } + }; + mac.update(data); + let result = mac.finalize(); + let code_bytes = result.into_bytes(); + Ok(code_bytes.to_vec()) +} + +pub(crate) fn prf_p_hash( + secret: &[u8], + seed: &[u8], + requested_length: usize, + h: CipherSuiteHash, +) -> Result> { + let mut last_round = seed.to_vec(); + let mut out = vec![]; + + let iterations = ((requested_length as f64) / (h.size() as f64)).ceil() as usize; + for _ in 0..iterations { + last_round = hmac_sha(h, secret, &last_round)?; + + let mut last_round_seed = last_round.clone(); + last_round_seed.extend_from_slice(seed); + let with_secret = hmac_sha(h, secret, &last_round_seed)?; + + out.extend_from_slice(&with_secret); + } + + Ok(out[..requested_length].to_vec()) +} + +pub(crate) fn prf_extended_master_secret( + pre_master_secret: &[u8], + session_hash: &[u8], + h: CipherSuiteHash, +) -> Result> { + let mut seed = PRF_EXTENDED_MASTER_SECRET_LABEL.as_bytes().to_vec(); + seed.extend_from_slice(session_hash); + prf_p_hash(pre_master_secret, &seed, 48, h) +} + +pub(crate) fn prf_master_secret( + pre_master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + h: CipherSuiteHash, +) -> Result> { + let mut seed = PRF_MASTER_SECRET_LABEL.as_bytes().to_vec(); + seed.extend_from_slice(client_random); + seed.extend_from_slice(server_random); + prf_p_hash(pre_master_secret, &seed, 48, h) +} + +pub(crate) fn prf_encryption_keys( + master_secret: &[u8], + client_random: &[u8], + server_random: &[u8], + prf_mac_len: usize, + prf_key_len: usize, + prf_iv_len: usize, + h: CipherSuiteHash, +) -> Result { + let mut seed = PRF_KEY_EXPANSION_LABEL.as_bytes().to_vec(); + seed.extend_from_slice(server_random); + seed.extend_from_slice(client_random); + + let material = prf_p_hash( + master_secret, + &seed, + (2 * prf_mac_len) + (2 * prf_key_len) + (2 * prf_iv_len), + h, + )?; + let mut key_material = &material[..]; + + let client_mac_key = key_material[..prf_mac_len].to_vec(); + key_material = &key_material[prf_mac_len..]; + + let server_mac_key = key_material[..prf_mac_len].to_vec(); + key_material = &key_material[prf_mac_len..]; + + let client_write_key = key_material[..prf_key_len].to_vec(); + key_material = &key_material[prf_key_len..]; + + let server_write_key = key_material[..prf_key_len].to_vec(); + key_material = &key_material[prf_key_len..]; + + let client_write_iv = key_material[..prf_iv_len].to_vec(); + key_material = &key_material[prf_iv_len..]; + + let server_write_iv = key_material[..prf_iv_len].to_vec(); + + Ok(EncryptionKeys { + master_secret: master_secret.to_vec(), + client_mac_key, + server_mac_key, + client_write_key, + server_write_key, + client_write_iv, + server_write_iv, + }) +} + +pub(crate) fn prf_verify_data( + master_secret: &[u8], + handshake_bodies: &[u8], + label: &str, + h: CipherSuiteHash, +) -> Result> { + let mut hasher = match h { + CipherSuiteHash::Sha256 => Sha256::new(), + }; + hasher.update(handshake_bodies); + let result = hasher.finalize(); + let mut seed = label.as_bytes().to_vec(); + seed.extend_from_slice(&result); + + prf_p_hash(master_secret, &seed, 12, h) +} + +pub(crate) fn prf_verify_data_client( + master_secret: &[u8], + handshake_bodies: &[u8], + h: CipherSuiteHash, +) -> Result> { + prf_verify_data( + master_secret, + handshake_bodies, + PRF_VERIFY_DATA_CLIENT_LABEL, + h, + ) +} + +pub(crate) fn prf_verify_data_server( + master_secret: &[u8], + handshake_bodies: &[u8], + h: CipherSuiteHash, +) -> Result> { + prf_verify_data( + master_secret, + handshake_bodies, + PRF_VERIFY_DATA_SERVER_LABEL, + h, + ) +} + +// compute the MAC using HMAC-SHA1 +pub(crate) fn prf_mac( + epoch: u16, + sequence_number: u64, + content_type: ContentType, + protocol_version: ProtocolVersion, + payload: &[u8], + key: &[u8], +) -> Result> { + let mut hmac = HmacSha1::new_from_slice(key).map_err(|e| Error::Other(e.to_string()))?; + + let mut msg = vec![0u8; 13]; + msg[..2].copy_from_slice(&epoch.to_be_bytes()); + msg[2..8].copy_from_slice(&sequence_number.to_be_bytes()[2..]); + msg[8] = content_type as u8; + msg[9] = protocol_version.major; + msg[10] = protocol_version.minor; + msg[11..].copy_from_slice(&(payload.len() as u16).to_be_bytes()); + + hmac.update(&msg); + hmac.update(payload); + let result = hmac.finalize(); + + Ok(result.into_bytes().to_vec()) +} diff --git a/vendor/webrtc-dtls/src/prf/prf_test.rs b/vendor/webrtc-dtls/src/prf/prf_test.rs new file mode 100644 index 0000000..33d5241 --- /dev/null +++ b/vendor/webrtc-dtls/src/prf/prf_test.rs @@ -0,0 +1,261 @@ +use super::*; +use crate::cipher_suite::CipherSuiteHash; + +#[test] +fn test_pre_master_secret() -> Result<()> { + let private_key: [u8; 32] = [ + 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, + 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, + 0x3e, 0x3f, + ]; + let private_key = + NamedCurvePrivateKey::StaticSecretX25519(x25519_dalek::StaticSecret::from(private_key)); + let public_key = [ + 0x9f, 0xd7, 0xad, 0x6d, 0xcf, 0xf4, 0x29, 0x8d, 0xd3, 0xf9, 0x6d, 0x5b, 0x1b, 0x2a, 0xf9, + 0x10, 0xa0, 0x53, 0x5b, 0x14, 0x88, 0xd7, 0xf8, 0xfa, 0xbb, 0x34, 0x9a, 0x98, 0x28, 0x80, + 0xb6, 0x15, + ]; + + let expected_pre_master_secret = vec![ + 0xdf, 0x4a, 0x29, 0x1b, 0xaa, 0x1e, 0xb7, 0xcf, 0xa6, 0x93, 0x4b, 0x29, 0xb4, 0x74, 0xba, + 0xad, 0x26, 0x97, 0xe2, 0x9f, 0x1f, 0x92, 0x0d, 0xcc, 0x77, 0xc8, 0xa0, 0xa0, 0x88, 0x44, + 0x76, 0x24, + ]; + + let pre_master_secret = prf_pre_master_secret(&public_key, &private_key, NamedCurve::X25519)?; + + assert_eq!( + expected_pre_master_secret, pre_master_secret, + "PremasterSecret exp: {expected_pre_master_secret:?} actual: {pre_master_secret:?}" + ); + + Ok(()) +} + +#[test] +fn test_master_secret() -> Result<()> { + let pre_master_secret = vec![ + 0xdf, 0x4a, 0x29, 0x1b, 0xaa, 0x1e, 0xb7, 0xcf, 0xa6, 0x93, 0x4b, 0x29, 0xb4, 0x74, 0xba, + 0xad, 0x26, 0x97, 0xe2, 0x9f, 0x1f, 0x92, 0x0d, 0xcc, 0x77, 0xc8, 0xa0, 0xa0, 0x88, 0x44, + 0x76, 0x24, + ]; + let client_random = vec![ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, + ]; + let server_random = vec![ + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, + 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, + 0x8e, 0x8f, + ]; + let expected_master_secret = vec![ + 0x91, 0x6a, 0xbf, 0x9d, 0xa5, 0x59, 0x73, 0xe1, 0x36, 0x14, 0xae, 0x0a, 0x3f, 0x5d, 0x3f, + 0x37, 0xb0, 0x23, 0xba, 0x12, 0x9a, 0xee, 0x02, 0xcc, 0x91, 0x34, 0x33, 0x81, 0x27, 0xcd, + 0x70, 0x49, 0x78, 0x1c, 0x8e, 0x19, 0xfc, 0x1e, 0xb2, 0xa7, 0x38, 0x7a, 0xc0, 0x6a, 0xe2, + 0x37, 0x34, 0x4c, + ]; + + let master_secret = prf_master_secret( + &pre_master_secret, + &client_random, + &server_random, + CipherSuiteHash::Sha256, + )?; + + assert_eq!( + expected_master_secret, master_secret, + "master_secret exp: {expected_master_secret:?} actual: {master_secret:?}" + ); + + Ok(()) +} + +#[test] +fn test_encryption_keys() -> Result<()> { + let client_random = vec![ + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, + 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, + 0x1e, 0x1f, + ]; + let server_random = vec![ + 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, + 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, + 0x8e, 0x8f, + ]; + let master_secret = vec![ + 0x91, 0x6a, 0xbf, 0x9d, 0xa5, 0x59, 0x73, 0xe1, 0x36, 0x14, 0xae, 0x0a, 0x3f, 0x5d, 0x3f, + 0x37, 0xb0, 0x23, 0xba, 0x12, 0x9a, 0xee, 0x02, 0xcc, 0x91, 0x34, 0x33, 0x81, 0x27, 0xcd, + 0x70, 0x49, 0x78, 0x1c, 0x8e, 0x19, 0xfc, 0x1e, 0xb2, 0xa7, 0x38, 0x7a, 0xc0, 0x6a, 0xe2, + 0x37, 0x34, 0x4c, + ]; + + let expected_encryption_keys = EncryptionKeys { + master_secret: master_secret.clone(), + client_mac_key: vec![], + server_mac_key: vec![], + client_write_key: vec![ + 0x1b, 0x7d, 0x11, 0x7c, 0x7d, 0x5f, 0x69, 0x0b, 0xc2, 0x63, 0xca, 0xe8, 0xef, 0x60, + 0xaf, 0x0f, + ], + server_write_key: vec![ + 0x18, 0x78, 0xac, 0xc2, 0x2a, 0xd8, 0xbd, 0xd8, 0xc6, 0x01, 0xa6, 0x17, 0x12, 0x6f, + 0x63, 0x54, + ], + client_write_iv: vec![0x0e, 0xb2, 0x09, 0x06], + server_write_iv: vec![0xf7, 0x81, 0xfa, 0xd2], + }; + + let keys = prf_encryption_keys( + &master_secret, + &client_random, + &server_random, + 0, + 16, + 4, + CipherSuiteHash::Sha256, + )?; + + assert_eq!( + expected_encryption_keys, keys, + "master_secret exp: {expected_encryption_keys:?} actual: {keys:?}", + ); + + Ok(()) +} + +#[test] +fn test_verify_data() -> Result<()> { + let client_hello = vec![ + 0x01, 0x00, 0x00, 0xa1, 0x03, 0x03, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, + 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x00, 0x00, 0x20, 0xcc, 0xa8, 0xcc, 0xa9, + 0xc0, 0x2f, 0xc0, 0x30, 0xc0, 0x2b, 0xc0, 0x2c, 0xc0, 0x13, 0xc0, 0x09, 0xc0, 0x14, 0xc0, + 0x0a, 0x00, 0x9c, 0x00, 0x9d, 0x00, 0x2f, 0x00, 0x35, 0xc0, 0x12, 0x00, 0x0a, 0x01, 0x00, + 0x00, 0x58, 0x00, 0x00, 0x00, 0x18, 0x00, 0x16, 0x00, 0x00, 0x13, 0x65, 0x78, 0x61, 0x6d, + 0x70, 0x6c, 0x65, 0x2e, 0x75, 0x6c, 0x66, 0x68, 0x65, 0x69, 0x6d, 0x2e, 0x6e, 0x65, 0x74, + 0x00, 0x05, 0x00, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x0a, 0x00, 0x08, + 0x00, 0x1d, 0x00, 0x17, 0x00, 0x18, 0x00, 0x19, 0x00, 0x0b, 0x00, 0x02, 0x01, 0x00, 0x00, + 0x0d, 0x00, 0x12, 0x00, 0x10, 0x04, 0x01, 0x04, 0x03, 0x05, 0x01, 0x05, 0x03, 0x06, 0x01, + 0x06, 0x03, 0x02, 0x01, 0x02, 0x03, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x12, 0x00, 0x00, + ]; + let server_hello = vec![ + 0x02, 0x00, 0x00, 0x2d, 0x03, 0x03, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, + 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, + 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x00, 0xc0, 0x13, 0x00, 0x00, 0x05, 0xff, + 0x01, 0x00, 0x01, 0x00, + ]; + let server_certificate = vec![ + 0x0b, 0x00, 0x03, 0x2b, 0x00, 0x03, 0x28, 0x00, 0x03, 0x25, 0x30, 0x82, 0x03, 0x21, 0x30, + 0x82, 0x02, 0x09, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x08, 0x15, 0x5a, 0x92, 0xad, 0xc2, + 0x04, 0x8f, 0x90, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, + 0x0b, 0x05, 0x00, 0x30, 0x22, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, + 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0a, 0x45, + 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x43, 0x41, 0x30, 0x1e, 0x17, 0x0d, 0x31, 0x38, + 0x31, 0x30, 0x30, 0x35, 0x30, 0x31, 0x33, 0x38, 0x31, 0x37, 0x5a, 0x17, 0x0d, 0x31, 0x39, + 0x31, 0x30, 0x30, 0x35, 0x30, 0x31, 0x33, 0x38, 0x31, 0x37, 0x5a, 0x30, 0x2b, 0x31, 0x0b, + 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x55, 0x53, 0x31, 0x1c, 0x30, 0x1a, + 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x13, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, + 0x75, 0x6c, 0x66, 0x68, 0x65, 0x69, 0x6d, 0x2e, 0x6e, 0x65, 0x74, 0x30, 0x82, 0x01, 0x22, + 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, + 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, 0x00, 0xc4, + 0x80, 0x36, 0x06, 0xba, 0xe7, 0x47, 0x6b, 0x08, 0x94, 0x04, 0xec, 0xa7, 0xb6, 0x91, 0x04, + 0x3f, 0xf7, 0x92, 0xbc, 0x19, 0xee, 0xfb, 0x7d, 0x74, 0xd7, 0xa8, 0x0d, 0x00, 0x1e, 0x7b, + 0x4b, 0x3a, 0x4a, 0xe6, 0x0f, 0xe8, 0xc0, 0x71, 0xfc, 0x73, 0xe7, 0x02, 0x4c, 0x0d, 0xbc, + 0xf4, 0xbd, 0xd1, 0x1d, 0x39, 0x6b, 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 0xee, 0x82, 0x9e, 0x4d, 0x02, 0x9d, + 0xc9, 0x1c, 0xdd, 0x67, 0x16, 0xdb, 0xb9, 0x06, 0x18, 0x86, 0xed, 0xc1, 0xba, 0x94, 0x21, + 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x52, 0x30, 0x50, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, + 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, 0x03, 0x02, 0x05, 0xa0, 0x30, 0x1d, 0x06, 0x03, 0x55, + 0x1d, 0x25, 0x04, 0x16, 0x30, 0x14, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, + 0x02, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x1f, 0x06, 0x03, + 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x89, 0x4f, 0xde, 0x5b, 0xcc, 0x69, + 0xe2, 0x52, 0xcf, 0x3e, 0xa3, 0x00, 0xdf, 0xb1, 0x97, 0xb8, 0x1d, 0xe1, 0xc1, 0x46, 0x30, + 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, + 0x82, 0x01, 0x01, 0x00, 0x59, 0x16, 0x45, 0xa6, 0x9a, 0x2e, 0x37, 0x79, 0xe4, 0xf6, 0xdd, + 0x27, 0x1a, 0xba, 0x1c, 0x0b, 0xfd, 0x6c, 0xd7, 0x55, 0x99, 0xb5, 0xe7, 0xc3, 0x6e, 0x53, + 0x3e, 0xff, 0x36, 0x59, 0x08, 0x43, 0x24, 0xc9, 0xe7, 0xa5, 0x04, 0x07, 0x9d, 0x39, 0xe0, + 0xd4, 0x29, 0x87, 0xff, 0xe3, 0xeb, 0xdd, 0x09, 0xc1, 0xcf, 0x1d, 0x91, 0x44, 0x55, 0x87, + 0x0b, 0x57, 0x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, 0x69, 0xa1, 0x59, 0x41, 0xe8, 0xe2, 0xcc, 0xa8, 0x4b, + 0xb6, 0x08, 0x46, 0x36, 0xa0, + ]; + let server_key_exchange = vec![ + 0x0c, 0x00, 0x01, 0x28, 0x03, 0x00, 0x1d, 0x20, 0x9f, 0xd7, 0xad, 0x6d, 0xcf, 0xf4, 0x29, + 0x8d, 0xd3, 0xf9, 0x6d, 0x5b, 0x1b, 0x2a, 0xf9, 0x10, 0xa0, 0x53, 0x5b, 0x14, 0x88, 0xd7, + 0xf8, 0xfa, 0xbb, 0x34, 0x9a, 0x98, 0x28, 0x80, 0xb6, 0x15, 0x04, 0x01, 0x01, 0x00, 0x04, + 0x02, 0xb6, 0x61, 0xf7, 0xc1, 0x91, 0xee, 0x59, 0xbe, 0x45, 0x37, 0x66, 0x39, 0xbd, 0xc3, + 0xd4, 0xbb, 0x81, 0xe1, 0x15, 0xca, 0x73, 0xc8, 0x34, 0x8b, 0x52, 0x5b, 0x0d, 0x23, 0x38, + 0xaa, 0x14, 0x46, 0x67, 0xed, 0x94, 0x31, 0x02, 0x14, 0x12, 0xcd, 0x9b, 0x84, 0x4c, 0xba, + 0x29, 0x93, 0x4a, 0xaa, 0xcc, 0xe8, 0x73, 0x41, 0x4e, 0xc1, 0x1c, 0xb0, 0x2e, 0x27, 0x2d, + 0x0a, 0xd8, 0x1f, 0x76, 0x7d, 0x33, 0x07, 0x67, 0x21, 0xf1, 0x3b, 0xf3, 0x60, 0x20, 0xcf, + 0x0b, 0x1f, 0xd0, 0xec, 0xb0, 0x78, 0xde, 0x11, 0x28, 0xbe, 0xba, 0x09, 0x49, 0xeb, 0xec, + 0xe1, 0xa1, 0xf9, 0x6e, 0x20, 0x9d, 0xc3, 0x6e, 0x4f, 0xff, 0xd3, 0x6b, 0x67, 0x3a, 0x7d, + 0xdc, 0x15, 0x97, 0xad, 0x44, 0x08, 0xe4, 0x85, 0xc4, 0xad, 0xb2, 0xc8, 0x73, 0x84, 0x12, + 0x49, 0x37, 0x25, 0x23, 0x80, 0x9e, 0x43, 0x12, 0xd0, 0xc7, 0xb3, 0x52, 0x2e, 0xf9, 0x83, + 0xca, 0xc1, 0xe0, 0x39, 0x35, 0xff, 0x13, 0xa8, 0xe9, 0x6b, 0xa6, 0x81, 0xa6, 0x2e, 0x40, + 0xd3, 0xe7, 0x0a, 0x7f, 0xf3, 0x58, 0x66, 0xd3, 0xd9, 0x99, 0x3f, 0x9e, 0x26, 0xa6, 0x34, + 0xc8, 0x1b, 0x4e, 0x71, 0x38, 0x0f, 0xcd, 0xd6, 0xf4, 0xe8, 0x35, 0xf7, 0x5a, 0x64, 0x09, + 0xc7, 0xdc, 0x2c, 0x07, 0x41, 0x0e, 0x6f, 0x87, 0x85, 0x8c, 0x7b, 0x94, 0xc0, 0x1c, 0x2e, + 0x32, 0xf2, 0x91, 0x76, 0x9e, 0xac, 0xca, 0x71, 0x64, 0x3b, 0x8b, 0x98, 0xa9, 0x63, 0xdf, + 0x0a, 0x32, 0x9b, 0xea, 0x4e, 0xd6, 0x39, 0x7e, 0x8c, 0xd0, 0x1a, 0x11, 0x0a, 0xb3, 0x61, + 0xac, 0x5b, 0xad, 0x1c, 0xcd, 0x84, 0x0a, 0x6c, 0x8a, 0x6e, 0xaa, 0x00, 0x1a, 0x9d, 0x7d, + 0x87, 0xdc, 0x33, 0x18, 0x64, 0x35, 0x71, 0x22, 0x6c, 0x4d, 0xd2, 0xc2, 0xac, 0x41, 0xfb, + ]; + let server_hello_done = vec![0x0e, 0x00, 0x00, 0x00]; + let client_key_exchange = vec![ + 0x10, 0x00, 0x00, 0x21, 0x20, 0x35, 0x80, 0x72, 0xd6, 0x36, 0x58, 0x80, 0xd1, 0xae, 0xea, + 0x32, 0x9a, 0xdf, 0x91, 0x21, 0x38, 0x38, 0x51, 0xed, 0x21, 0xa2, 0x8e, 0x3b, 0x75, 0xe9, + 0x65, 0xd0, 0xd2, 0xcd, 0x16, 0x62, 0x54, + ]; + + let mut final_msg = vec![]; + final_msg.extend_from_slice(&client_hello); + final_msg.extend_from_slice(&server_hello); + final_msg.extend_from_slice(&server_certificate); + final_msg.extend_from_slice(&server_key_exchange); + final_msg.extend_from_slice(&server_hello_done); + final_msg.extend_from_slice(&client_key_exchange); + + let master_secret = vec![ + 0x91, 0x6a, 0xbf, 0x9d, 0xa5, 0x59, 0x73, 0xe1, 0x36, 0x14, 0xae, 0x0a, 0x3f, 0x5d, 0x3f, + 0x37, 0xb0, 0x23, 0xba, 0x12, 0x9a, 0xee, 0x02, 0xcc, 0x91, 0x34, 0x33, 0x81, 0x27, 0xcd, + 0x70, 0x49, 0x78, 0x1c, 0x8e, 0x19, 0xfc, 0x1e, 0xb2, 0xa7, 0x38, 0x7a, 0xc0, 0x6a, 0xe2, + 0x37, 0x34, 0x4c, + ]; + + let expected_verify_data = vec![ + 0xcf, 0x91, 0x96, 0x26, 0xf1, 0x36, 0x0c, 0x53, 0x6a, 0xaa, 0xd7, 0x3a, + ]; + + let verify_data = prf_verify_data_client(&master_secret, &final_msg, CipherSuiteHash::Sha256)?; + + assert_eq!( + expected_verify_data, verify_data, + "verify_data exp: {expected_verify_data:?} actual: {verify_data:?}" + ); + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/record_layer/mod.rs b/vendor/webrtc-dtls/src/record_layer/mod.rs new file mode 100644 index 0000000..8be337d --- /dev/null +++ b/vendor/webrtc-dtls/src/record_layer/mod.rs @@ -0,0 +1,107 @@ +pub mod record_layer_header; + +#[cfg(test)] +mod record_layer_test; + +use std::io::{Read, Write}; + +use record_layer_header::*; + +use super::content::*; +use super::error::*; +use crate::alert::Alert; +use crate::application_data::ApplicationData; +use crate::change_cipher_spec::ChangeCipherSpec; +use crate::handshake::Handshake; + +/* + The TLS Record Layer which handles all data transport. + The record layer is assumed to sit directly on top of some + reliable transport such as TCP. The record layer can carry four types of content: + + 1. Handshake messages—used for algorithm negotiation and key establishment. + 2. ChangeCipherSpec messages—really part of the handshake but technically a separate kind of message. + 3. Alert messages—used to signal that errors have occurred + 4. Application layer data + + The DTLS record layer is extremely similar to that of TLS 1.1. The + only change is the inclusion of an explicit sequence number in the + record. This sequence number allows the recipient to correctly + verify the TLS MAC. + https://tools.ietf.org/html/rfc4347#section-4.1 +*/ +#[derive(Debug, Clone, PartialEq)] +pub struct RecordLayer { + pub record_layer_header: RecordLayerHeader, + pub content: Content, +} + +impl RecordLayer { + pub fn new(protocol_version: ProtocolVersion, epoch: u16, content: Content) -> Self { + RecordLayer { + record_layer_header: RecordLayerHeader { + content_type: content.content_type(), + protocol_version, + epoch, + sequence_number: 0, + content_len: content.size() as u16, + }, + content, + } + } + + pub fn marshal(&self, writer: &mut W) -> Result<()> { + self.record_layer_header.marshal(writer)?; + self.content.marshal(writer)?; + Ok(()) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let record_layer_header = RecordLayerHeader::unmarshal(reader)?; + let content = match record_layer_header.content_type { + ContentType::Alert => Content::Alert(Alert::unmarshal(reader)?), + ContentType::ApplicationData => { + Content::ApplicationData(ApplicationData::unmarshal(reader)?) + } + ContentType::ChangeCipherSpec => { + Content::ChangeCipherSpec(ChangeCipherSpec::unmarshal(reader)?) + } + ContentType::Handshake => Content::Handshake(Handshake::unmarshal(reader)?), + _ => return Err(Error::Other("Invalid Content Type".to_owned())), + }; + + Ok(RecordLayer { + record_layer_header, + content, + }) + } +} + +// Note that as with TLS, multiple handshake messages may be placed in +// the same DTLS record, provided that there is room and that they are +// part of the same flight. Thus, there are two acceptable ways to pack +// two DTLS messages into the same datagram: in the same record or in +// separate records. +// https://tools.ietf.org/html/rfc6347#section-4.2.3 +pub(crate) fn unpack_datagram(buf: &[u8]) -> Result>> { + let mut out = vec![]; + + let mut offset = 0; + while buf.len() != offset { + if buf.len() - offset <= RECORD_LAYER_HEADER_SIZE { + return Err(Error::ErrInvalidPacketLength); + } + + let pkt_len = RECORD_LAYER_HEADER_SIZE + + (((buf[offset + RECORD_LAYER_HEADER_SIZE - 2] as usize) << 8) + | buf[offset + RECORD_LAYER_HEADER_SIZE - 1] as usize); + if offset + pkt_len > buf.len() { + return Err(Error::ErrInvalidPacketLength); + } + + out.push(buf[offset..offset + pkt_len].to_vec()); + offset += pkt_len + } + + Ok(out) +} diff --git a/vendor/webrtc-dtls/src/record_layer/record_layer_header.rs b/vendor/webrtc-dtls/src/record_layer/record_layer_header.rs new file mode 100644 index 0000000..5711682 --- /dev/null +++ b/vendor/webrtc-dtls/src/record_layer/record_layer_header.rs @@ -0,0 +1,90 @@ +use std::io::{Read, Write}; + +use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; + +use crate::content::*; +use crate::error::*; + +pub const RECORD_LAYER_HEADER_SIZE: usize = 13; +pub const MAX_SEQUENCE_NUMBER: u64 = 0x0000FFFFFFFFFFFF; + +pub const DTLS1_2MAJOR: u8 = 0xfe; +pub const DTLS1_2MINOR: u8 = 0xfd; + +pub const DTLS1_0MAJOR: u8 = 0xfe; +pub const DTLS1_0MINOR: u8 = 0xff; + +// VERSION_DTLS12 is the DTLS version in the same style as +// VersionTLSXX from crypto/tls +pub const VERSION_DTLS12: u16 = 0xfefd; + +pub const PROTOCOL_VERSION1_0: ProtocolVersion = ProtocolVersion { + major: DTLS1_0MAJOR, + minor: DTLS1_0MINOR, +}; +pub const PROTOCOL_VERSION1_2: ProtocolVersion = ProtocolVersion { + major: DTLS1_2MAJOR, + minor: DTLS1_2MINOR, +}; + +// https://tools.ietf.org/html/rfc4346#section-6.2.1 +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] +pub struct ProtocolVersion { + pub major: u8, + pub minor: u8, +} + +#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)] +pub struct RecordLayerHeader { + pub content_type: ContentType, + pub protocol_version: ProtocolVersion, + pub epoch: u16, + pub sequence_number: u64, // uint48 in spec + pub content_len: u16, +} + +impl RecordLayerHeader { + pub fn marshal(&self, writer: &mut W) -> Result<()> { + if self.sequence_number > MAX_SEQUENCE_NUMBER { + return Err(Error::ErrSequenceNumberOverflow); + } + + writer.write_u8(self.content_type as u8)?; + writer.write_u8(self.protocol_version.major)?; + writer.write_u8(self.protocol_version.minor)?; + writer.write_u16::(self.epoch)?; + + let be: [u8; 8] = self.sequence_number.to_be_bytes(); + writer.write_all(&be[2..])?; // uint48 in spec + + writer.write_u16::(self.content_len)?; + + Ok(writer.flush()?) + } + + pub fn unmarshal(reader: &mut R) -> Result { + let content_type = reader.read_u8()?.into(); + let major = reader.read_u8()?; + let minor = reader.read_u8()?; + let epoch = reader.read_u16::()?; + + // SequenceNumber is stored as uint48, make into uint64 + let mut be: [u8; 8] = [0u8; 8]; + reader.read_exact(&mut be[2..])?; + let sequence_number = u64::from_be_bytes(be); + + let protocol_version = ProtocolVersion { major, minor }; + if protocol_version != PROTOCOL_VERSION1_0 && protocol_version != PROTOCOL_VERSION1_2 { + return Err(Error::ErrUnsupportedProtocolVersion); + } + let content_len = reader.read_u16::()?; + + Ok(RecordLayerHeader { + content_type, + protocol_version, + epoch, + sequence_number, + content_len, + }) + } +} diff --git a/vendor/webrtc-dtls/src/record_layer/record_layer_test.rs b/vendor/webrtc-dtls/src/record_layer/record_layer_test.rs new file mode 100644 index 0000000..3e644e5 --- /dev/null +++ b/vendor/webrtc-dtls/src/record_layer/record_layer_test.rs @@ -0,0 +1,118 @@ +use std::io::{BufReader, BufWriter}; + +use super::record_layer_header::*; +use super::*; +use crate::change_cipher_spec::ChangeCipherSpec; + +#[test] +fn test_udp_decode() -> Result<()> { + let tests = vec![ + ( + "Change Cipher Spec, single packet", + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x01, + ], + vec![vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x01, + ]], + None, + ), + ( + "Change Cipher Spec, multi packet", + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x01, + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x01, 0x01, + ], + vec![ + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, + 0x01, + ], + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0x00, 0x01, + 0x01, + ], + ], + None, + ), + ( + "Invalid packet length", + vec![0x14, 0xfe], + vec![], + Some(Error::ErrInvalidPacketLength), + ), + ( + "Packet declared invalid length", + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0xFF, 0x01, + ], + vec![], + Some(Error::ErrInvalidPacketLength), + ), + ]; + + for (name, data, wanted, wanted_err) in tests { + let dtls_pkts = unpack_datagram(&data); + if let Some(err) = wanted_err { + if let Err(dtls) = dtls_pkts { + assert_eq!(err.to_string(), dtls.to_string()); + } else { + panic!("something wrong for {name} when wanted_err is Some"); + } + } else if let Ok(pkts) = dtls_pkts { + assert_eq!( + wanted, pkts, + "{name} UDP decode: got {pkts:?}, want {wanted:?}", + ); + } else { + panic!("something wrong for {name} when wanted_err is None"); + } + } + + Ok(()) +} + +#[test] +fn test_record_layer_round_trip() -> Result<()> { + let tests = vec![( + "Change Cipher Spec, single packet", + vec![ + 0x14, 0xfe, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12, 0x00, 0x01, 0x01, + ], + RecordLayer { + record_layer_header: RecordLayerHeader { + content_type: ContentType::ChangeCipherSpec, + protocol_version: ProtocolVersion { + major: 0xfe, + minor: 0xff, + }, + epoch: 0, + sequence_number: 18, + content_len: 1, + }, + content: Content::ChangeCipherSpec(ChangeCipherSpec {}), + }, + )]; + + for (name, data, want) in tests { + let mut reader = BufReader::new(data.as_slice()); + let r = RecordLayer::unmarshal(&mut reader)?; + + assert_eq!( + want, r, + "{name} recordLayer.unmarshal: got {r:?}, want {want:?}" + ); + + let mut data2 = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(data2.as_mut()); + r.marshal(&mut writer)?; + } + assert_eq!( + data, data2, + "{name} recordLayer.marshal: got {data2:?}, want {data:?}" + ); + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/signature_hash_algorithm/mod.rs b/vendor/webrtc-dtls/src/signature_hash_algorithm/mod.rs new file mode 100644 index 0000000..41e5dab --- /dev/null +++ b/vendor/webrtc-dtls/src/signature_hash_algorithm/mod.rs @@ -0,0 +1,215 @@ +#[cfg(test)] +mod signature_hash_algorithm_test; + +use std::fmt; + +use crate::crypto::*; +use crate::error::*; + +// HashAlgorithm is used to indicate the hash algorithm used +// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-18 +// Supported hash hash algorithms +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum HashAlgorithm { + Md2 = 0, // Blacklisted + Md5 = 1, // Blacklisted + Sha1 = 2, // Blacklisted + Sha224 = 3, + Sha256 = 4, + Sha384 = 5, + Sha512 = 6, + Ed25519 = 8, + Unsupported, +} + +impl From for HashAlgorithm { + fn from(val: u8) -> Self { + match val { + 0 => HashAlgorithm::Md2, + 1 => HashAlgorithm::Md5, + 2 => HashAlgorithm::Sha1, + 3 => HashAlgorithm::Sha224, + 4 => HashAlgorithm::Sha256, + 5 => HashAlgorithm::Sha384, + 6 => HashAlgorithm::Sha512, + 8 => HashAlgorithm::Ed25519, + _ => HashAlgorithm::Unsupported, + } + } +} + +impl fmt::Display for HashAlgorithm { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match *self { + HashAlgorithm::Md2 => write!(f, "md2"), + HashAlgorithm::Md5 => write!(f, "md5"), // [RFC3279] + HashAlgorithm::Sha1 => write!(f, "sha-1"), // [RFC3279] + HashAlgorithm::Sha224 => write!(f, "sha-224"), // [RFC4055] + HashAlgorithm::Sha256 => write!(f, "sha-256"), // [RFC4055] + HashAlgorithm::Sha384 => write!(f, "sha-384"), // [RFC4055] + HashAlgorithm::Sha512 => write!(f, "sha-512"), // [RFC4055] + HashAlgorithm::Ed25519 => write!(f, "null"), // [RFC4055] + _ => write!(f, "unknown or unsupported hash algorithm"), + } + } +} + +impl HashAlgorithm { + pub(crate) fn insecure(&self) -> bool { + matches!( + *self, + HashAlgorithm::Md2 | HashAlgorithm::Md5 | HashAlgorithm::Sha1 + ) + } + + pub(crate) fn invalid(&self) -> bool { + matches!(*self, HashAlgorithm::Md2) + } +} + +// https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-16 +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum SignatureAlgorithm { + Rsa = 1, + Ecdsa = 3, + Ed25519 = 7, + Unsupported, +} + +impl From for SignatureAlgorithm { + fn from(val: u8) -> Self { + match val { + 1 => SignatureAlgorithm::Rsa, + 3 => SignatureAlgorithm::Ecdsa, + 7 => SignatureAlgorithm::Ed25519, + _ => SignatureAlgorithm::Unsupported, + } + } +} + +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub struct SignatureHashAlgorithm { + pub hash: HashAlgorithm, + pub signature: SignatureAlgorithm, +} + +impl SignatureHashAlgorithm { + // is_compatible checks that given private key is compatible with the signature scheme. + pub(crate) fn is_compatible(&self, private_key: &CryptoPrivateKey) -> bool { + match &private_key.kind { + CryptoPrivateKeyKind::Ed25519(_) => self.signature == SignatureAlgorithm::Ed25519, + CryptoPrivateKeyKind::Ecdsa256(_) => self.signature == SignatureAlgorithm::Ecdsa, + CryptoPrivateKeyKind::Rsa256(_) => self.signature == SignatureAlgorithm::Rsa, + } + } +} + +pub(crate) fn default_signature_schemes() -> Vec { + vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Ed25519, + signature: SignatureAlgorithm::Ed25519, + }, + ] +} + +// select Signature Scheme returns most preferred and compatible scheme. +pub(crate) fn select_signature_scheme( + sigs: &[SignatureHashAlgorithm], + private_key: &CryptoPrivateKey, +) -> Result { + for ss in sigs { + if ss.is_compatible(private_key) { + return Ok(*ss); + } + } + + Err(Error::ErrNoAvailableSignatureSchemes) +} + +// SignatureScheme identifies a signature algorithm supported by TLS. See +// RFC 8446, Section 4.2.3. +#[derive(Copy, Clone, Debug, PartialEq, Eq)] +pub enum SignatureScheme { + // RSASSA-PKCS1-v1_5 algorithms. + Pkcs1WithSha256 = 0x0401, + Pkcs1WithSha384 = 0x0501, + Pkcs1WithSha512 = 0x0601, + + // RSASSA-PSS algorithms with public key OID rsaEncryption. + PssWithSha256 = 0x0804, + PssWithSha384 = 0x0805, + PssWithSha512 = 0x0806, + + // ECDSA algorithms. Only constrained to a specific curve in TLS 1.3. + EcdsaWithP256AndSha256 = 0x0403, + EcdsaWithP384AndSha384 = 0x0503, + EcdsaWithP521AndSha512 = 0x0603, + + // EdDSA algorithms. + Ed25519 = 0x0807, + + // Legacy signature and hash algorithms for TLS 1.2. + Pkcs1WithSha1 = 0x0201, + EcdsaWithSha1 = 0x0203, +} + +// parse_signature_schemes translates []tls.SignatureScheme to []signatureHashAlgorithm. +// It returns default signature scheme list if no SignatureScheme is passed. +pub(crate) fn parse_signature_schemes( + sigs: &[u16], + insecure_hashes: bool, +) -> Result> { + if sigs.is_empty() { + return Ok(default_signature_schemes()); + } + + let mut out = vec![]; + for ss in sigs { + let sig: SignatureAlgorithm = ((*ss & 0xFF) as u8).into(); + if sig == SignatureAlgorithm::Unsupported { + return Err(Error::ErrInvalidSignatureAlgorithm); + } + let h: HashAlgorithm = (((*ss >> 8) & 0xFF) as u8).into(); + if h == HashAlgorithm::Unsupported || h.invalid() { + return Err(Error::ErrInvalidHashAlgorithm); + } + if h.insecure() && !insecure_hashes { + continue; + } + out.push(SignatureHashAlgorithm { + hash: h, + signature: sig, + }) + } + + if out.is_empty() { + Err(Error::ErrNoAvailableSignatureSchemes) + } else { + Ok(out) + } +} diff --git a/vendor/webrtc-dtls/src/signature_hash_algorithm/signature_hash_algorithm_test.rs b/vendor/webrtc-dtls/src/signature_hash_algorithm/signature_hash_algorithm_test.rs new file mode 100644 index 0000000..775ef32 --- /dev/null +++ b/vendor/webrtc-dtls/src/signature_hash_algorithm/signature_hash_algorithm_test.rs @@ -0,0 +1,141 @@ +use super::*; + +#[test] +fn test_parse_signature_schemes() -> Result<()> { + let tests = vec![ + ( + "Translate", + vec![ + SignatureScheme::EcdsaWithP256AndSha256 as u16, + SignatureScheme::EcdsaWithP384AndSha384 as u16, + SignatureScheme::EcdsaWithP521AndSha512 as u16, + SignatureScheme::Pkcs1WithSha256 as u16, + SignatureScheme::Pkcs1WithSha384 as u16, + SignatureScheme::Pkcs1WithSha512 as u16, + ], + vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha384, + signature: SignatureAlgorithm::Rsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha512, + signature: SignatureAlgorithm::Rsa, + }, + ], + false, + None, + ), + ( + "InvalidSignatureAlgorithm", + vec![ + SignatureScheme::EcdsaWithP256AndSha256 as u16, // Valid + 0x04FF, // Invalid: unknown signature with SHA-256 + ], + vec![], + false, + Some(Error::ErrInvalidSignatureAlgorithm), + ), + ( + "InvalidHashAlgorithm", + vec![ + SignatureScheme::EcdsaWithP256AndSha256 as u16, // Valid + 0x0003, // Invalid: ECDSA with MD2 + ], + vec![], + false, + Some(Error::ErrInvalidHashAlgorithm), + ), + ( + "InsecureHashAlgorithmDenied", + vec![ + SignatureScheme::EcdsaWithP256AndSha256 as u16, // Valid + SignatureScheme::EcdsaWithSha1 as u16, // Insecure + ], + vec![SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }], + false, + None, + ), + ( + "InsecureHashAlgorithmAllowed", + vec![ + SignatureScheme::EcdsaWithP256AndSha256 as u16, // Valid + SignatureScheme::EcdsaWithSha1 as u16, // Insecure + ], + vec![ + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha256, + signature: SignatureAlgorithm::Ecdsa, + }, + SignatureHashAlgorithm { + hash: HashAlgorithm::Sha1, + signature: SignatureAlgorithm::Ecdsa, + }, + ], + true, + None, + ), + ( + "OnlyInsecureHashAlgorithm", + vec![ + SignatureScheme::EcdsaWithSha1 as u16, // Insecure + ], + vec![], + false, + Some(Error::ErrNoAvailableSignatureSchemes), + ), + ( + "Translate", + vec![SignatureScheme::Ed25519 as u16], + vec![SignatureHashAlgorithm { + hash: HashAlgorithm::Ed25519, + signature: SignatureAlgorithm::Ed25519, + }], + false, + None, + ), + ]; + + for (name, inputs, expected, insecure_hashes, want_err) in tests { + let output = parse_signature_schemes(&inputs, insecure_hashes); + if let Some(err) = want_err { + if let Err(output_err) = output { + assert_eq!( + err.to_string(), + output_err.to_string(), + "Expected error: {err:?}, got: {output_err:?}" + ); + } else { + panic!("expect err, but got non-err for {name}"); + } + } else if let Ok(output_val) = output { + assert_eq!( + expected, output_val, + "Expected signatureHashAlgorithm:\n{expected:?}\ngot:\n{output_val:?}", + ); + } else { + panic!("expect non-err, but got err for {name}"); + } + } + + Ok(()) +} diff --git a/vendor/webrtc-dtls/src/state.rs b/vendor/webrtc-dtls/src/state.rs new file mode 100644 index 0000000..d195fba --- /dev/null +++ b/vendor/webrtc-dtls/src/state.rs @@ -0,0 +1,304 @@ +use std::io::{BufWriter, Cursor}; +use std::marker::{Send, Sync}; +use std::sync::atomic::{AtomicU16, Ordering}; +use std::sync::Arc; + +use async_trait::async_trait; +use serde::{Deserialize, Serialize}; +use tokio::sync::Mutex; +use util::{KeyingMaterialExporter, KeyingMaterialExporterError}; + +use super::cipher_suite::*; +use super::conn::*; +use super::curve::named_curve::*; +use super::extension::extension_use_srtp::SrtpProtectionProfile; +use super::handshake::handshake_random::*; +use super::prf::*; +use crate::error::*; + +// State holds the dtls connection state and implements both encoding.BinaryMarshaler and encoding.BinaryUnmarshaler +pub struct State { + pub(crate) local_epoch: Arc, + pub(crate) remote_epoch: Arc, + pub(crate) local_sequence_number: Arc>>, // uint48 + pub(crate) local_random: HandshakeRandom, + pub(crate) remote_random: HandshakeRandom, + pub(crate) master_secret: Vec, + pub(crate) cipher_suite: Arc>>>, // nil if a cipher_suite hasn't been chosen + + pub(crate) srtp_protection_profile: SrtpProtectionProfile, // Negotiated srtp_protection_profile + pub peer_certificates: Vec>, + pub identity_hint: Vec, + + pub(crate) is_client: bool, + + pub(crate) pre_master_secret: Vec, + pub(crate) extended_master_secret: bool, + + pub(crate) named_curve: NamedCurve, + pub(crate) local_keypair: Option, + pub(crate) cookie: Vec, + pub(crate) handshake_send_sequence: isize, + pub(crate) handshake_recv_sequence: isize, + pub(crate) server_name: String, + pub(crate) remote_requested_certificate: bool, // Did we get a CertificateRequest + pub(crate) local_certificates_verify: Vec, // cache CertificateVerify + pub(crate) local_verify_data: Vec, // cached VerifyData + pub(crate) local_key_signature: Vec, // cached keySignature + pub(crate) peer_certificates_verified: bool, + //pub(crate) replay_detector: Vec>, +} + +#[derive(Serialize, Deserialize, PartialEq, Debug)] +struct SerializedState { + local_epoch: u16, + remote_epoch: u16, + local_random: [u8; HANDSHAKE_RANDOM_LENGTH], + remote_random: [u8; HANDSHAKE_RANDOM_LENGTH], + cipher_suite_id: u16, + master_secret: Vec, + sequence_number: u64, + srtp_protection_profile: u16, + peer_certificates: Vec>, + identity_hint: Vec, + is_client: bool, +} + +impl Default for State { + fn default() -> Self { + State { + local_epoch: Arc::new(AtomicU16::new(0)), + remote_epoch: Arc::new(AtomicU16::new(0)), + local_sequence_number: Arc::new(Mutex::new(vec![])), + local_random: HandshakeRandom::default(), + remote_random: HandshakeRandom::default(), + master_secret: vec![], + cipher_suite: Arc::new(Mutex::new(None)), // nil if a cipher_suite hasn't been chosen + + srtp_protection_profile: SrtpProtectionProfile::Unsupported, // Negotiated srtp_protection_profile + peer_certificates: vec![], + identity_hint: vec![], + + is_client: false, + + pre_master_secret: vec![], + extended_master_secret: false, + + named_curve: NamedCurve::Unsupported, + local_keypair: None, + cookie: vec![], + handshake_send_sequence: 0, + handshake_recv_sequence: 0, + server_name: "".to_string(), + remote_requested_certificate: false, // Did we get a CertificateRequest + local_certificates_verify: vec![], // cache CertificateVerify + local_verify_data: vec![], // cached VerifyData + local_key_signature: vec![], // cached keySignature + peer_certificates_verified: false, + //replay_detector: vec![], + } + } +} + +impl State { + pub(crate) async fn clone(&self) -> Self { + let mut state = State::default(); + + if let Ok(serialized) = self.serialize().await { + let _ = state.deserialize(&serialized).await; + } + + state + } + + async fn serialize(&self) -> Result { + let mut local_rand = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(local_rand.as_mut()); + self.local_random.marshal(&mut writer)?; + } + let mut remote_rand = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(remote_rand.as_mut()); + self.remote_random.marshal(&mut writer)?; + } + + let mut local_random = [0u8; HANDSHAKE_RANDOM_LENGTH]; + let mut remote_random = [0u8; HANDSHAKE_RANDOM_LENGTH]; + + local_random.copy_from_slice(&local_rand); + remote_random.copy_from_slice(&remote_rand); + + let local_epoch = self.local_epoch.load(Ordering::SeqCst); + let remote_epoch = self.remote_epoch.load(Ordering::SeqCst); + let sequence_number = { + let lsn = self.local_sequence_number.lock().await; + lsn[local_epoch as usize] + }; + let cipher_suite_id = { + let cipher_suite = self.cipher_suite.lock().await; + match &*cipher_suite { + Some(cipher_suite) => cipher_suite.id() as u16, + None => return Err(Error::ErrCipherSuiteUnset), + } + }; + + Ok(SerializedState { + local_epoch, + remote_epoch, + local_random, + remote_random, + cipher_suite_id, + master_secret: self.master_secret.clone(), + sequence_number, + srtp_protection_profile: self.srtp_protection_profile as u16, + peer_certificates: self.peer_certificates.clone(), + identity_hint: self.identity_hint.clone(), + is_client: self.is_client, + }) + } + + async fn deserialize(&mut self, serialized: &SerializedState) -> Result<()> { + // Set epoch values + self.local_epoch + .store(serialized.local_epoch, Ordering::SeqCst); + self.remote_epoch + .store(serialized.remote_epoch, Ordering::SeqCst); + { + let mut lsn = self.local_sequence_number.lock().await; + while lsn.len() <= serialized.local_epoch as usize { + lsn.push(0); + } + lsn[serialized.local_epoch as usize] = serialized.sequence_number; + } + + // Set random values + let mut reader = Cursor::new(&serialized.local_random); + self.local_random = HandshakeRandom::unmarshal(&mut reader)?; + + let mut reader = Cursor::new(&serialized.remote_random); + self.remote_random = HandshakeRandom::unmarshal(&mut reader)?; + + self.is_client = serialized.is_client; + + // Set master secret + self.master_secret = serialized.master_secret.clone(); + + // Set cipher suite + self.cipher_suite = Arc::new(Mutex::new(Some(cipher_suite_for_id( + serialized.cipher_suite_id.into(), + )?))); + + self.srtp_protection_profile = serialized.srtp_protection_profile.into(); + + // Set remote certificate + self.peer_certificates = serialized.peer_certificates.clone(); + self.identity_hint = serialized.identity_hint.clone(); + + Ok(()) + } + + pub async fn init_cipher_suite(&mut self) -> Result<()> { + let mut cipher_suite = self.cipher_suite.lock().await; + if let Some(cipher_suite) = &mut *cipher_suite { + if cipher_suite.is_initialized() { + return Ok(()); + } + + let mut local_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(local_random.as_mut()); + self.local_random.marshal(&mut writer)?; + } + let mut remote_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(remote_random.as_mut()); + self.remote_random.marshal(&mut writer)?; + } + + if self.is_client { + cipher_suite.init(&self.master_secret, &local_random, &remote_random, true) + } else { + cipher_suite.init(&self.master_secret, &remote_random, &local_random, false) + } + } else { + Err(Error::ErrCipherSuiteUnset) + } + } + + // marshal_binary is a binary.BinaryMarshaler.marshal_binary implementation + pub async fn marshal_binary(&self) -> Result> { + let serialized = self.serialize().await?; + + match bincode::serialize(&serialized) { + Ok(enc) => Ok(enc), + Err(err) => Err(Error::Other(err.to_string())), + } + } + + // unmarshal_binary is a binary.BinaryUnmarshaler.unmarshal_binary implementation + pub async fn unmarshal_binary(&mut self, data: &[u8]) -> Result<()> { + let serialized: SerializedState = match bincode::deserialize(data) { + Ok(dec) => dec, + Err(err) => return Err(Error::Other(err.to_string())), + }; + self.deserialize(&serialized).await?; + self.init_cipher_suite().await?; + + Ok(()) + } +} + +#[async_trait] +impl KeyingMaterialExporter for State { + /// export_keying_material returns length bytes of exported key material in a new + /// slice as defined in RFC 5705. + /// This allows protocols to use DTLS for key establishment, but + /// then use some of the keying material for their own purposes + async fn export_keying_material( + &self, + label: &str, + context: &[u8], + length: usize, + ) -> std::result::Result, KeyingMaterialExporterError> { + use KeyingMaterialExporterError::*; + + if self.local_epoch.load(Ordering::SeqCst) == 0 { + return Err(HandshakeInProgress); + } else if !context.is_empty() { + return Err(ContextUnsupported); + } else if INVALID_KEYING_LABELS.contains(&label) { + return Err(ReservedExportKeyingMaterial); + } + + let mut local_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(local_random.as_mut()); + self.local_random.marshal(&mut writer)?; + } + let mut remote_random = vec![]; + { + let mut writer = BufWriter::<&mut Vec>::new(remote_random.as_mut()); + self.remote_random.marshal(&mut writer)?; + } + + let mut seed = label.as_bytes().to_vec(); + if self.is_client { + seed.extend_from_slice(&local_random); + seed.extend_from_slice(&remote_random); + } else { + seed.extend_from_slice(&remote_random); + seed.extend_from_slice(&local_random); + } + + let cipher_suite = self.cipher_suite.lock().await; + if let Some(cipher_suite) = &*cipher_suite { + match prf_p_hash(&self.master_secret, &seed, length, cipher_suite.hash_func()) { + Ok(v) => Ok(v), + Err(err) => Err(Hash(err.to_string())), + } + } else { + Err(CipherSuiteUnset) + } + } +}