Skip to main content

rtci_host/
args.rs

1// Copyright 2026 Brainwires. MIT OR Apache-2.0.
2
3//! The arguments and results the front ends pass across their boundary
4//! (`serde` types, camelCase as the W3C dictionaries are), with the parsing
5//! both front ends share.
6
7use rtci::data_channel::RTCDataChannelInit;
8use rtci::peer_connection::configuration::RTCBundlePolicy;
9use serde::Deserialize;
10use serde::Serialize;
11
12use crate::error::Error;
13use crate::error::ErrorKind;
14use crate::gate::GateExt;
15use crate::gate::NetGate;
16use crate::gate::Proto;
17use crate::gate::Reach;
18use crate::peer::IceServerSpec;
19use crate::peer::ServerTransport;
20
21/// One `RTCIceServer`.
22#[derive(Clone, Debug, Deserialize)]
23#[serde(rename_all = "camelCase")]
24pub struct IceServerArg {
25  pub urls: Vec<String>,
26  pub username: Option<String>,
27  pub credential: Option<String>,
28}
29
30/// `RTCConfiguration`, as the front end's JavaScript passes it.
31#[derive(Clone, Debug, Deserialize)]
32#[serde(rename_all = "camelCase")]
33pub struct ConfigArg {
34  pub ice_servers: Vec<IceServerArg>,
35  pub ice_transport_policy: String,
36  #[serde(default)]
37  pub bundle_policy: Option<String>,
38  /// `RTCCertificate` ids (the front end's certificate store's).
39  #[serde(default)]
40  pub certificates: Vec<u32>,
41  /// `RTCConfiguration.denoNetwork`: the front end's handle for a
42  /// [`Network`](crate::Network).
43  #[serde(default)]
44  pub network: Option<u32>,
45}
46
47impl ConfigArg {
48  /// `iceTransportPolicy: "relay"`.
49  pub fn relay_only(&self) -> bool {
50    self.ice_transport_policy == "relay"
51  }
52
53  /// `bundlePolicy` (`balanced` for anything but `max-bundle` and
54  /// `max-compat`).
55  pub fn bundle_policy(&self) -> RTCBundlePolicy {
56    match self.bundle_policy.as_deref() {
57      Some("max-bundle") => RTCBundlePolicy::MaxBundle,
58      Some("max-compat") => RTCBundlePolicy::MaxCompat,
59      _ => RTCBundlePolicy::Balanced,
60    }
61  }
62}
63
64/// Parses every URL of `RTCConfiguration.iceServers` (the W3C
65/// `SyntaxError` / `InvalidAccessError` checks); no gate is asked.
66pub fn parse_ice_servers(
67  servers: &[IceServerArg],
68) -> Result<Vec<IceServerSpec>, Error> {
69  let mut specs = Vec::new();
70  for server in servers {
71    for url in &server.urls {
72      specs.push(IceServerSpec::parse(
73        url,
74        server.username.as_deref(),
75        server.credential.as_deref(),
76      )?);
77    }
78  }
79  Ok(specs)
80}
81
82/// Asks `gate` for each server's host and port before DNS
83/// ([`ReachKind::IceServer`](crate::ReachKind::IceServer)); the first
84/// refusal is a [`ErrorKind::NotCapable`] error.
85pub fn check_ice_servers(
86  gate: &dyn NetGate,
87  specs: &[IceServerSpec],
88) -> Result<(), Error> {
89  for spec in specs {
90    let proto = match spec.transport {
91      ServerTransport::Udp => Proto::Udp,
92      ServerTransport::Tcp => Proto::Tcp,
93      ServerTransport::Tls => Proto::Tls,
94    };
95    gate
96      .check(&Reach::ice_server(proto, &spec.host, spec.port))
97      .map_err(Error::not_capable)?;
98  }
99  Ok(())
100}
101
102/// Whether any server needs TLS (`turns:` / `stuns:`): the front end then
103/// builds [`PeerOptions::tls`](crate::PeerOptions::tls).
104pub fn needs_tls(specs: &[IceServerSpec]) -> bool {
105  specs.iter().any(|s| s.transport == ServerTransport::Tls)
106}
107
108/// `RTCIceCandidateInit`.
109#[derive(Clone, Debug, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct CandidateArg {
112  pub candidate: String,
113  pub sdp_mid: Option<String>,
114  #[serde(rename = "sdpMLineIndex")]
115  pub sdp_m_line_index: Option<u16>,
116  pub username_fragment: Option<String>,
117}
118
119/// `createDataChannel(label, init)`.
120#[derive(Clone, Debug, Deserialize)]
121#[serde(rename_all = "camelCase")]
122pub struct DataChannelArg {
123  pub label: String,
124  pub ordered: bool,
125  pub max_packet_life_time: Option<u16>,
126  pub max_retransmits: Option<u16>,
127  pub protocol: String,
128  pub negotiated: bool,
129  pub id: Option<u16>,
130  // wpt100:S2 the DCEP priority (webrtc-priority 4.3), 256 when absent.
131  #[serde(default = "default_channel_priority")]
132  pub priority: u16,
133}
134
135fn default_channel_priority() -> u16 {
136  256
137}
138
139impl DataChannelArg {
140  /// The engine's channel options; a negotiated channel without an id is a
141  /// `TypeError`.
142  pub fn to_init(&self) -> Result<RTCDataChannelInit, Error> {
143    let negotiated = if self.negotiated {
144      Some(self.id.ok_or_else(|| {
145        Error::new(ErrorKind::Type, "A negotiated RTCDataChannel needs an id")
146      })?)
147    } else {
148      None
149    };
150    Ok(RTCDataChannelInit {
151      ordered: self.ordered,
152      max_packet_life_time: self.max_packet_life_time,
153      max_retransmits: self.max_retransmits,
154      protocol: self.protocol.clone(),
155      negotiated,
156      priority: self.priority,
157    })
158  }
159}
160
161/// A created data channel: its engine handle and its stream id, when
162/// assigned.
163#[derive(Clone, Copy, Debug, Serialize)]
164pub struct CreatedChannel {
165  pub channel: u32,
166  pub id: Option<u16>,
167}
168
169/// `generateCertificate`'s algorithm (WebCrypto's dictionaries).
170#[derive(Clone, Debug, Deserialize)]
171#[serde(rename_all = "camelCase")]
172pub struct KeygenArg {
173  pub name: String,
174  pub named_curve: Option<String>,
175  pub modulus_length: Option<u32>,
176  pub public_exponent: Option<Vec<u8>>,
177  pub hash: Option<String>,
178}
179
180/// An `RTCCertificate` for the front end's JavaScript.
181#[derive(Clone, Debug, Serialize)]
182#[serde(rename_all = "camelCase")]
183pub struct CertificateInfo {
184  pub id: u32,
185  /// Milliseconds since the epoch.
186  pub expires: f64,
187  pub fingerprints: Vec<FingerprintInfo>,
188}
189
190/// One `RTCDtlsFingerprint`.
191#[derive(Clone, Debug, Serialize)]
192pub struct FingerprintInfo {
193  pub algorithm: String,
194  pub value: String,
195}