diff --git a/Cargo.lock b/Cargo.lock
index b0d139a746d..2ebb23dfb8b 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3533,6 +3533,7 @@ dependencies = [
"v8",
"v_xmlescape",
"wasm_dep_analyzer",
+ "webrtc-sdp",
"widestring",
"wuff",
"xml5ever 0.39.0",
@@ -3831,6 +3832,7 @@ dependencies = [
"strum",
"url",
"v8",
+ "webrtc-sdp",
]
[[package]]
@@ -6783,6 +6785,16 @@ dependencies = [
"string_cache_codegen 0.11.2",
]
+[[package]]
+name = "webrtc-sdp"
+version = "0.3.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e66e22e6327595a7b7612460f8106fdf936cba0abdb99aa1581a388787797a1"
+dependencies = [
+ "log",
+ "url",
+]
+
[[package]]
name = "weezl"
version = "0.1.12"
diff --git a/moli-renderer-v8/Cargo.toml b/moli-renderer-v8/Cargo.toml
index 76bbfc051d8..7c1cadcc905 100644
--- a/moli-renderer-v8/Cargo.toml
+++ b/moli-renderer-v8/Cargo.toml
@@ -132,6 +132,7 @@ idna = "1.0"
uuid = { version = "1.23.1", default-features = false }
v_xmlescape = { git = "https://github.com/lexmount/v_escape", rev = "d30e780f4d498ffae80e836bc046501f6dfde47a", default-features = false, features = ["std", "string", "fmt"] }
widestring = "1.2.1"
+webrtc-sdp = "0.3.15"
style_traits = { package = "stylo_traits", version = "0.22" }
xmlparser = "0.13.6"
typed-num = { version = "0.3.0", default-features = false, features = ["serde"] }
diff --git a/moli-renderer-v8/src/context_bootstrap.rs b/moli-renderer-v8/src/context_bootstrap.rs
index 31e0f6794d3..540f1aef2e3 100644
--- a/moli-renderer-v8/src/context_bootstrap.rs
+++ b/moli-renderer-v8/src/context_bootstrap.rs
@@ -342,9 +342,10 @@ pub(crate) use self::canvas::{
use self::constructors::illegal_constructor_callback;
pub(crate) use self::constructors::{
WebTransportErrorClonePayload, WebTransportErrorSource, build_dom_exception_object,
- build_quota_exceeded_error_object, build_web_transport_error_from_clone_payload,
- dom_exception_clone_fields, ensure_dom_implementation_singleton, new_dom_error_value,
- new_dom_exception_value, new_most_derived_dom_exception_value, new_quota_exceeded_error_value,
+ build_quota_exceeded_error_object, build_rtc_sdp_error,
+ build_web_transport_error_from_clone_payload, dom_exception_clone_fields,
+ ensure_dom_implementation_singleton, new_dom_error_value, new_dom_exception_value,
+ new_most_derived_dom_exception_value, new_quota_exceeded_error_value,
quota_exceeded_error_clone_fields, throw_dom_exception_value,
web_transport_error_clone_payload_from_object,
};
diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp.rs
index 330924939bb..6507af2cd33 100644
--- a/moli-renderer-v8/src/context_bootstrap/rtc_rtp.rs
+++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp.rs
@@ -8,6 +8,7 @@ use moli_webapi::rtc::peer_connection::{
mod operations;
mod rtp_sender;
mod rtp_offer;
+mod sdp;
mod rtp_parameters;
pub(crate) mod rtp_transceivers;
diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/rtp_offer.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/rtp_offer.rs
index c3844a55913..27a6ce083bb 100644
--- a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/rtp_offer.rs
+++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/rtp_offer.rs
@@ -113,10 +113,8 @@ fn media_section(kind: &str, direction: &str, codecs: &[Codec], mid: usize) -> S
pub(super) fn build(sections: &[Section], data: bool) -> String {
let count = sections.len() + usize::from(data);
let mids: Vec<_> = (0..count).map(|mid| mid.to_string()).collect();
- let mut sdp = format!(
- "v=0\r\no=- 0 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE {}\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\n",
- mids.join(" ")
- );
+ let mids: Vec<_> = mids.iter().map(String::as_str).collect();
+ let mut sdp = super::sdp::session_header(&mids);
for (mid, section) in sections.iter().enumerate() {
sdp.push_str(&media_section(
§ion.kind,
diff --git a/moli-renderer-v8/src/context_bootstrap/rtc_rtp/sdp.rs b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/sdp.rs
new file mode 100644
index 00000000000..cba99d4b7ab
--- /dev/null
+++ b/moli-renderer-v8/src/context_bootstrap/rtc_rtp/sdp.rs
@@ -0,0 +1,23 @@
+pub(super) use moli_webapi::rtc::peer_connection::sdp::session_header;
+
+#[cfg(test)]
+mod tests {
+ use moli_webapi::rtc::peer_connection::sdp::parse;
+
+ #[test]
+ fn sdp_all_compatibility_offers_parse_and_empty_bundle_is_omitted() {
+ for bits in 0..8 {
+ let text = moli_webapi::rtc::peer_connection::build_signaling_only_offer(
+ bits & 1 != 0,
+ bits & 2 != 0,
+ bits & 4 != 0,
+ );
+ let parsed = parse(&text).unwrap();
+ assert_eq!(parsed.media.len(), (bits as u32).count_ones() as usize);
+ assert_eq!(text.contains("a=group:BUNDLE"), bits != 0);
+ }
+ let text = super::super::rtp_offer::build(&[], false);
+ assert!(parse(&text).unwrap().media.is_empty());
+ assert!(!text.contains("a=group:BUNDLE"));
+ }
+}
diff --git a/moli-renderer-v8/src/script_vm/tests/mod.rs b/moli-renderer-v8/src/script_vm/tests/mod.rs
index 6f5551b617a..caf9fdc66f3 100644
--- a/moli-renderer-v8/src/script_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/script_vm/tests/mod.rs
@@ -2551,6 +2551,7 @@ mod idb_object_store_native_receivers;
mod webidl_receivers;
mod webidl_trusted_types;
mod webrtc_event_init;
+mod webrtc_local_description;
mod websocket;
mod websocket_close_info_numbers;
diff --git a/moli-renderer-v8/src/script_vm/tests/webrtc_local_description.rs b/moli-renderer-v8/src/script_vm/tests/webrtc_local_description.rs
new file mode 100644
index 00000000000..e667d682a03
--- /dev/null
+++ b/moli-renderer-v8/src/script_vm/tests/webrtc_local_description.rs
@@ -0,0 +1,56 @@
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn webrtc_local_description_validates_offer_provenance_through_operations_chain() {
+ let loader = ResourceRequestClient::new(&moli_fetch::FetchConfig::default()).unwrap();
+ for url in [
+ "https://local-sdp.test/",
+ "http://local-sdp.test/",
+ "data:text/html,
",
+ ] {
+ let mut vm = new_storage_page_task_executor_test_vm_with_loader(url, &loader);
+ vm.eval("document.body.innerHTML=''")
+ .unwrap();
+ vm.eval(include_str!(
+ "../../../tests/fixtures/webrtc-local-description.js"
+ ))
+ .unwrap();
+ advance_page_task_executor_until_eval_equals(
+ &mut vm, &loader, "String(globalThis.__uiEventResults?.complete)", "true",
+ "local description operations must finish through the production selected Page dispatcher",
+ ).await;
+ assert_eq!(
+ vm.eval("JSON.stringify(__uiEventResults.checks.filter(row=>!row.passed))")
+ .unwrap(),
+ "[]",
+ "{url}"
+ );
+ assert_eq!(vm.eval("__uiEventResults.total===32 && new Set(__uiEventResults.checks.map(row=>row.name)).size===32").unwrap(), "true");
+ }
+}
+
+#[test]
+fn webrtc_sdp_error_uses_intrinsic_rtc_brand_and_original_line_number() {
+ let mut vm = new_parsed_test_vm("https://sdp-error.test/", "");
+ vm.eval("globalThis.originalRTCError=RTCError;globalThis.originalDOMException=DOMException;RTCError=function(){throw Error('author constructor')};DOMException=function(){throw Error('author constructor')}").unwrap();
+ let context_ptr = &vm.current_main_world().unwrap().context as *const _;
+ vm.with_context_scope_by_ptr_and_checkpoint_for_test(context_ptr, |scope, _| {
+ let error = moli_webapi::dom_exception::build_rtc_sdp_error(scope, "Invalid media port", 6)
+ .unwrap();
+ assert!(crate::web_api_interfaces::RTCError::is_instance(
+ scope, error
+ ));
+ assert!(crate::web_api_interfaces::DOMException::is_instance(
+ scope, error
+ ));
+ let global = scope.get_current_context().global(scope);
+ let key = crate::util::v8_string(scope, "nativeSdpError").unwrap();
+ assert_eq!(
+ global.create_data_property(scope, key.into(), error.into()),
+ Some(true)
+ );
+ Ok(())
+ })
+ .unwrap();
+ assert_eq!(vm.eval("nativeSdpError instanceof originalRTCError && nativeSdpError instanceof originalDOMException && nativeSdpError.name==='OperationError' && nativeSdpError.code===0 && nativeSdpError.message==='Invalid media port' && nativeSdpError.errorDetail==='sdp-syntax-error' && nativeSdpError.sdpLineNumber===6 && nativeSdpError.sctpCauseCode===null && nativeSdpError.receivedAlert===null && nativeSdpError.sentAlert===null && typeof nativeSdpError.stack==='string'").unwrap(), "true");
+}
diff --git a/moli-renderer-v8/tests/fixtures/webrtc-local-description.js b/moli-renderer-v8/tests/fixtures/webrtc-local-description.js
new file mode 100644
index 00000000000..fe787ef11c8
--- /dev/null
+++ b/moli-renderer-v8/tests/fixtures/webrtc-local-description.js
@@ -0,0 +1,132 @@
+(async () => {
+ const checks = [];
+ const assert = (value, message = 'assertion failed') => { if (!value) throw Error(message); };
+ const check = async (name, callback) => {
+ try { await callback(); checks.push({name, passed: true}); }
+ catch (error) { checks.push({name, passed: false, error: String(error), stack: error.stack}); }
+ };
+ for (const [realm, w] of [['main', window], ['iframe', document.querySelector('iframe').contentWindow]]) {
+ const run = (name, body) => check(`${realm}: ${name}`, async () => {
+ const pc = new w.RTCPeerConnection();
+ try { await body(pc); } finally { pc.close(); }
+ });
+ const rejects = async (promise, name) => {
+ let error;
+ try { await promise; } catch (caught) { error = caught; }
+ assert(error instanceof w.DOMException && error.name === name, `expected ${name}, got ${error}`);
+ return error;
+ };
+ const pristine = pc => assert(pc.signalingState === 'stable' && pc.localDescription === null && pc.pendingLocalDescription === null && pc.currentLocalDescription === null);
+ await run('uncached explicit SDP rejects without state changes', async pc => {
+ await rejects(pc.setLocalDescription({type: 'offer', sdp: 'not SDP'}), 'InvalidModificationError');
+ pristine(pc);
+ });
+ await run('modified latest offer rejects before applying state', async pc => {
+ pc.addTransceiver('audio');
+ const offer = await pc.createOffer();
+ await rejects(pc.setLocalDescription({...offer, sdp: offer.sdp + 'a=x-extension:yes\r\n'}), 'InvalidModificationError');
+ pristine(pc);
+ });
+ await run('explicit empty offer generates valid session', async pc => {
+ await pc.setLocalDescription({type: 'offer', sdp: ''});
+ assert(pc.signalingState === 'have-local-offer');
+ assert(pc.localDescription instanceof w.RTCSessionDescription && pc.localDescription.sdp.startsWith('v=0\r\n'));
+ assert(!pc.localDescription.sdp.includes('a=group:BUNDLE \r\n'));
+ });
+ await run('generated empty session omits empty BUNDLE', async pc => {
+ const offer = await pc.createOffer();
+ assert(!offer.sdp.includes('a=group:BUNDLE'));
+ await pc.setLocalDescription(offer);
+ assert(pc.pendingLocalDescription.sdp === offer.sdp);
+ });
+ await run('latest offer is preserved verbatim in native description', async pc => {
+ pc.addTransceiver('audio'); pc.addTransceiver('video');
+ const offer = await pc.createOffer();
+ await pc.setLocalDescription(offer);
+ assert(pc.localDescription instanceof w.RTCSessionDescription);
+ assert(pc.localDescription.sdp === offer.sdp && pc.pendingLocalDescription.sdp === offer.sdp);
+ assert(pc.currentLocalDescription === null);
+ });
+ await run('older offer rejects after topology changes', async pc => {
+ pc.addTransceiver('audio');
+ const old = await pc.createOffer();
+ pc.addTransceiver('video');
+ const latest = await pc.createOffer();
+ assert(latest.sdp !== old.sdp);
+ await rejects(pc.setLocalDescription(old), 'InvalidModificationError');
+ pristine(pc);
+ await pc.setLocalDescription(latest);
+ assert(pc.localDescription.sdp === latest.sdp);
+ });
+ await run('offer comparison runs when operation reaches chain head', async pc => {
+ pc.addTransceiver('audio');
+ const old = await pc.createOffer();
+ pc.addTransceiver('video');
+ const creating = pc.createOffer();
+ const applying = rejects(pc.setLocalDescription(old), 'InvalidModificationError');
+ await creating; await applying;
+ pristine(pc);
+ });
+ await run('implicit local offer retains legacy receive options', async pc => {
+ const offer = await pc.createOffer({offerToReceiveAudio: true});
+ await pc.setLocalDescription();
+ assert(offer.sdp.includes('m=audio') && pc.localDescription.sdp.includes('m=audio'));
+ });
+ await run('implicit local offer reflects current transceivers', async pc => {
+ await pc.createOffer();
+ pc.addTransceiver('video');
+ await pc.setLocalDescription();
+ assert(pc.localDescription.sdp.includes('m=video'));
+ });
+ await run('rollback ignores invalid SDP and clears pending description', async pc => {
+ pc.addTransceiver('audio');
+ await pc.setLocalDescription();
+ await pc.setLocalDescription({type: 'rollback', sdp: '!;'});
+ pristine(pc);
+ });
+ await run('rollback in stable rejects without parsing SDP', async pc => {
+ await rejects(pc.setLocalDescription({type: 'rollback', sdp: '!invalid'}), 'InvalidStateError');
+ pristine(pc);
+ });
+ await run('answer SDP provenance precedes signaling state checks', async pc => {
+ await rejects(pc.setLocalDescription({type: 'answer', sdp: 'not SDP'}), 'InvalidModificationError');
+ await rejects(pc.setLocalDescription({type: 'pranswer', sdp: 'not SDP'}), 'InvalidModificationError');
+ await rejects(pc.setLocalDescription({type: 'answer'}), 'InvalidStateError');
+ pristine(pc);
+ });
+ await run('dictionary reads once and preserves captured SDP', async pc => {
+ pc.addTransceiver('audio');
+ const offer = await pc.createOffer();
+ const reads = [];
+ const promise = pc.setLocalDescription({get sdp() { reads.push('sdp'); return offer.sdp; }, get type() { reads.push('type'); return 'offer'; }});
+ assert(reads.join(',') === 'sdp,type' && pc.localDescription === null);
+ await promise;
+ assert(reads.join(',') === 'sdp,type' && pc.localDescription.sdp === offer.sdp);
+ });
+ await run('failed update preserves pending description identity', async pc => {
+ const offer = await pc.createOffer(); await pc.setLocalDescription(offer);
+ const before = pc.localDescription;
+ await rejects(pc.setLocalDescription({type: 'offer', sdp: 'modified'}), 'InvalidModificationError');
+ assert(pc.localDescription === before && pc.pendingLocalDescription === before && pc.signalingState === 'have-local-offer');
+ });
+ await run('failed operation does not block next valid operation', async pc => {
+ pc.addTransceiver('audio'); const offer = await pc.createOffer();
+ const bad = rejects(pc.setLocalDescription({...offer, sdp: 'invalid'}), 'InvalidModificationError');
+ const good = pc.setLocalDescription(offer);
+ await bad; await good;
+ assert(pc.localDescription.sdp === offer.sdp);
+ });
+ await run('local description errors ignore replaced global constructors', async pc => {
+ const original = w.DOMException, originalRTC = w.RTCError;
+ try {
+ w.DOMException = function() { throw Error('author DOMException constructor'); };
+ w.RTCError = function() { throw Error('author RTCError constructor'); };
+ let error;
+ try { await pc.setLocalDescription({type: 'offer', sdp: 'invalid'}); } catch (caught) { error = caught; }
+ assert(error instanceof original && error.name === 'InvalidModificationError');
+ } finally { w.DOMException = original; w.RTCError = originalRTC; }
+ pristine(pc);
+ });
+ }
+ globalThis.__uiEventResults = {complete: true, total: checks.length, passed: checks.filter(row => row.passed).length, checks};
+})().catch(error => { globalThis.__uiEventResults = {complete: true, total: 1, passed: 0, checks: [{name: 'fixture', passed: false, error: String(error)}]}; });
diff --git a/moli-webapi/Cargo.toml b/moli-webapi/Cargo.toml
index c0d884de2e0..8a3d9e53a62 100644
--- a/moli-webapi/Cargo.toml
+++ b/moli-webapi/Cargo.toml
@@ -33,6 +33,7 @@ moli-webapi-declare = { path = "../moli-webapi-declare" }
moli-webidl = { path = "../moli-webidl" }
strum = { version = "0.28", features = ["derive"] }
v8 = "152.2.0"
+webrtc-sdp = "0.3.15"
url = "2.5.7"
[dev-dependencies]
diff --git a/moli-webapi/src/dom_exception.rs b/moli-webapi/src/dom_exception.rs
index e069f17ecc8..a6336a51092 100644
--- a/moli-webapi/src/dom_exception.rs
+++ b/moli-webapi/src/dom_exception.rs
@@ -11,7 +11,7 @@ mod overconstrained_error;
mod rtc_error;
mod web_transport_error;
pub use overconstrained_error::overconstrained_error_constructor_callback;
-pub use rtc_error::rtc_error_constructor_callback;
+pub use rtc_error::{build_rtc_sdp_error, rtc_error_constructor_callback};
pub use web_transport_error::{
WebTransportErrorClonePayload, WebTransportErrorSource,
build_web_transport_error_from_clone_payload, web_transport_error_clone_payload_from_object,
diff --git a/moli-webapi/src/dom_exception/rtc_error.rs b/moli-webapi/src/dom_exception/rtc_error.rs
index ab43e51b353..3ab8d0c7bc5 100644
--- a/moli-webapi/src/dom_exception/rtc_error.rs
+++ b/moli-webapi/src/dom_exception/rtc_error.rs
@@ -124,3 +124,23 @@ fn slot_getter<'s>(
rv.set(value);
}
}
+
+pub fn build_rtc_sdp_error<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ message: &str,
+ line_number: i32,
+) -> Option> {
+ let object = ObjectDeclaration::new(v8_string(scope, message)?)
+ .bind(scope)
+ .ok()?;
+ ErrorInit {
+ error_detail: ErrorDetail::SdpSyntaxError,
+ received_alert: None,
+ sctp_cause_code: None,
+ sdp_line_number: Some(line_number),
+ sent_alert: None,
+ }
+ .initialize_snapshot(scope, object)?;
+ capture_dom_exception_stack(scope, object);
+ Some(object)
+}
diff --git a/moli-webapi/src/rtc/peer_connection.rs b/moli-webapi/src/rtc/peer_connection.rs
index eee6e03f99d..9ed0f1e94a8 100644
--- a/moli-webapi/src/rtc/peer_connection.rs
+++ b/moli-webapi/src/rtc/peer_connection.rs
@@ -5,7 +5,7 @@ use crate::event_target::SIMPLE_EVENT_TARGET_LISTENERS_SLOT;
use crate::interfaces as web_api_interfaces;
use moli_v8_util::{
callback_data_index_value, callback_data_item, get_private_value, set_private_value,
- set_resolved_promise, throw_type_error, v8_string, v8str,
+ throw_type_error, v8_string, v8str,
};
use moli_webapi_declare::{WebApiFunctionTemplate, WebApiObject};
use moli_webidl::{self as webidl, WebIdlDictionarySerialize};
@@ -16,6 +16,7 @@ pub mod operations;
mod peer_options;
pub mod rtp_capabilities;
pub mod rtp_transceivers;
+pub mod sdp;
const RTC_PEER_CONNECTION_CONFIGURATION_SLOT: &str = "__moliRtcPeerConnectionConfiguration";
pub const RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT: &str = "__moliRtcPeerConnectionSignalingState";
@@ -30,6 +31,9 @@ const RTC_PEER_CONNECTION_CURRENT_LOCAL_DESCRIPTION_SLOT: &str =
const RTC_PEER_CONNECTION_PENDING_LOCAL_DESCRIPTION_SLOT: &str =
"__moliRtcPeerConnectionPendingLocalDescription";
const RTC_PEER_CONNECTION_HAS_DATA_CHANNEL_SLOT: &str = "__moliRtcPeerConnectionHasDataChannel";
+const LAST_CREATED_OFFER: &str = "__moliRtcLastCreatedOffer";
+const LAST_CREATED_ANSWER: &str = "__moliRtcLastCreatedAnswer";
+const LAST_OFFER_OPTIONS: &str = "__moliRtcLastOfferOptions";
const RTC_DATA_CHANNEL_LABEL_SLOT: &str = "__moliRtcDataChannelLabel";
const RTC_DATA_CHANNEL_ORDERED_SLOT: &str = "__moliRtcDataChannelOrdered";
@@ -87,6 +91,12 @@ struct RtcPeerConnectionObjectDeclaration<'scope> {
current_local_description: (),
#[webapi(slot = RTC_PEER_CONNECTION_PENDING_LOCAL_DESCRIPTION_SLOT, init = "null")]
pending_local_description: (),
+ #[webapi(slot = LAST_CREATED_OFFER, init = "")]
+ last_created_offer: (),
+ #[webapi(slot = LAST_CREATED_ANSWER, init = "")]
+ last_created_answer: (),
+ #[webapi(slot = LAST_OFFER_OPTIONS, init = 0)]
+ last_offer_options: (),
#[webapi(slot = RTC_PEER_CONNECTION_HAS_DATA_CHANNEL_SLOT, init = false)]
has_data_channel: (),
#[webapi(slot = rtp_transceivers::NEGOTIATION_HANDLER, init = "null")]
@@ -216,6 +226,9 @@ pub fn rtc_peer_connection_constructor_callback<'s>(
local_description: (),
current_local_description: (),
pending_local_description: (),
+ last_created_offer: (),
+ last_created_answer: (),
+ last_offer_options: (),
has_data_channel: (),
onnegotiationneeded: (),
event_listeners: (),
@@ -378,9 +391,15 @@ pub fn complete_create_offer<'s>(
.int32_value(scope)
.expect("native offer options");
let sdp = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0);
+ if let Err(error) = sdp::parse(&sdp) {
+ return reject_sdp_error(scope, request, &error);
+ }
let Some(sdp) = v8_string(scope, &sdp) else {
return false;
};
+ set_private_value(scope, pc, LAST_CREATED_OFFER, sdp.into());
+ let options = v8::Integer::new(scope, options);
+ set_private_value(scope, pc, LAST_OFFER_OPTIONS, options.into());
let offer = RtcSessionDescriptionInitDeclaration::new(v8str(scope, "offer").into(), sdp)
.bind(scope)
.expect("offer dictionary");
@@ -439,6 +458,26 @@ pub fn complete_set_local_description<'s>(
} else {
kind.as_str()
};
+ let last_slot = match kind {
+ "offer" => Some(LAST_CREATED_OFFER),
+ "answer" | "pranswer" => Some(LAST_CREATED_ANSWER),
+ _ => None,
+ };
+ if sdp.length() != 0
+ && let Some(last_slot) = last_slot
+ && !sdp.strict_equals(get_private_value(scope, pc, last_slot).expect("last SDP"))
+ {
+ v8::tc_scope!(let caught, scope);
+ crate::embedding::throw_dom_exception_value(
+ caught,
+ "The local SDP differs from the last created description.",
+ "InvalidModificationError",
+ );
+ let reason = caught.exception().expect("local SDP modification error");
+ caught.reset();
+ operations::reject(caught, request, reason);
+ return true;
+ }
let state = get_private_value(scope, pc, RTC_PEER_CONNECTION_SIGNALING_STATE_SLOT)
.expect("signaling state")
.to_rust_string_lossy(scope);
@@ -483,12 +522,20 @@ pub fn complete_set_local_description<'s>(
);
} else {
if sdp.length() == 0 {
- let text = offer_sdp(scope, pc, false, false);
+ let options = get_private_value(scope, pc, LAST_OFFER_OPTIONS)
+ .expect("last offer options")
+ .int32_value(scope)
+ .expect("offer option bits");
+ let text = offer_sdp(scope, pc, options & 1 != 0, options & 2 != 0);
let Some(value) = v8_string(scope, &text) else {
return false;
};
sdp = value;
}
+ if let Err(error) = sdp::parse(&sdp.to_rust_string_lossy(scope)) {
+ return reject_sdp_error(scope, request, &error);
+ }
+ set_private_value(scope, pc, LAST_CREATED_OFFER, sdp.into());
let Some(kind) = v8_string(scope, kind) else {
return false;
};
@@ -519,6 +566,18 @@ pub fn complete_set_local_description<'s>(
true
}
+fn reject_sdp_error<'s>(
+ scope: &mut v8::PinScope<'s, '_>,
+ request: v8::Local<'s, v8::Object>,
+ error: &sdp::SyntaxError,
+) -> bool {
+ let Some(reason) = crate::dom_exception::build_rtc_sdp_error(scope, &error.message, error.line_number) else {
+ return false;
+ };
+ operations::reject(scope, request, reason.into());
+ true
+}
+
fn rtc_peer_connection_close_callback<'s>(
scope: &mut v8::PinScope<'s, '_>,
args: v8::FunctionCallbackArguments<'s>,
@@ -601,7 +660,7 @@ fn set_string_slot<'s>(
set_private_value(scope, object, slot, v8str(scope, value).into());
}
-fn build_signaling_only_offer(audio: bool, video: bool, data: bool) -> String {
+pub fn build_signaling_only_offer(audio: bool, video: bool, data: bool) -> String {
let mut mids = Vec::new();
if audio {
mids.push("0");
@@ -612,10 +671,7 @@ fn build_signaling_only_offer(audio: bool, video: bool, data: bool) -> String {
if data {
mids.push("2");
}
- let mut sdp = format!(
- "v=0\r\no=- 0 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE {}\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS\r\n",
- mids.join(" ")
- );
+ let mut sdp = sdp::session_header(&mids);
if audio {
sdp.push_str(RTC_AUDIO_OFFER_SECTION);
}
diff --git a/moli-webapi/src/rtc/peer_connection/sdp.rs b/moli-webapi/src/rtc/peer_connection/sdp.rs
new file mode 100644
index 00000000000..1292dd12519
--- /dev/null
+++ b/moli-webapi/src/rtc/peer_connection/sdp.rs
@@ -0,0 +1,171 @@
+//! SDP syntax and structured session parsing. JSEP negotiation and semantic
+//! validation belong to the description application step, not this parser.
+
+use webrtc_sdp::{
+ SdpLine, SdpSession, SdpType, error::SdpParserError, media_type::parse_media_vector,
+ parse_sdp_line,
+};
+
+#[derive(Debug)]
+pub struct SyntaxError {
+ pub message: String,
+ pub line_number: i32,
+}
+
+impl SyntaxError {
+ fn at(message: impl Into, index: usize) -> Self {
+ Self {
+ message: message.into(),
+ line_number: i32::try_from(index.saturating_add(1)).unwrap_or(i32::MAX),
+ }
+ }
+}
+
+impl From for SyntaxError {
+ fn from(error: SdpParserError) -> Self {
+ let index = match &error {
+ SdpParserError::Line { line_number, .. }
+ | SdpParserError::Unsupported { line_number, .. }
+ | SdpParserError::Sequence { line_number, .. } => *line_number,
+ };
+ Self::at(error.to_string(), index)
+ }
+}
+
+pub fn parse(text: &str) -> Result {
+ let mut lines = Vec::new();
+ let mut warnings = Vec::new();
+ for (index, line) in text.lines().enumerate() {
+ if line.trim().is_empty() {
+ continue;
+ }
+ match parse_sdp_line(line, index) {
+ Ok(line) => lines.push(line),
+ // RFC 8866 requires receivers to ignore unrecognized attributes.
+ // Keep them as diagnostics; the original SDP is never serialized
+ // back from this representation or stripped of these attributes.
+ Err(error @ SdpParserError::Unsupported { .. }) if line.starts_with("a=") => {
+ warnings.push(error);
+ }
+ Err(error) => return Err(error.into()),
+ }
+ }
+ let eof = text.lines().count();
+ let mut lines = lines.into_iter();
+ let header = |lines: &mut std::vec::IntoIter| {
+ lines
+ .next()
+ .ok_or_else(|| SyntaxError::at("Missing required SDP session header.", eof))
+ };
+ let version = header(&mut lines)?;
+ let origin = header(&mut lines)?;
+ let session = header(&mut lines)?;
+ let SdpType::Version(version) = version.sdp_type else {
+ return Err(SyntaxError::at(
+ "Expected SDP version.",
+ version.line_number,
+ ));
+ };
+ let SdpType::Origin(origin) = origin.sdp_type else {
+ return Err(SyntaxError::at("Expected SDP origin.", origin.line_number));
+ };
+ let SdpType::Session(session) = session.sdp_type else {
+ return Err(SyntaxError::at(
+ "Expected SDP session name.",
+ session.line_number,
+ ));
+ };
+ let mut parsed = SdpSession::new(version, origin, session);
+ let mut lines: Vec<_> = lines.collect();
+ let media_start = lines
+ .iter()
+ .position(|line| matches!(line.sdp_type, SdpType::Media(_)))
+ .unwrap_or(lines.len());
+ let mut media = lines.split_off(media_start);
+ parsed.parse_session_vector(&mut lines)?;
+ if parsed.timing.is_none() {
+ let index = media.first().map_or(eof, |line| line.line_number);
+ return Err(SyntaxError::at("Missing SDP timing.", index));
+ }
+ if !media.is_empty() {
+ parsed.extend_media(parse_media_vector(&mut media)?);
+ }
+ parsed.warnings = warnings;
+ // Use the parser's public session/media APIs rather than parse_sdp(): its
+ // 51-byte minimum rejects valid short sessions, and its final sanity check
+ // mixes syntax with semantic constraints (e.g. RID payload references).
+ Ok(parsed)
+}
+
+pub fn session_header(mids: &[&str]) -> String {
+ let mut text = "v=0\r\no=- 0 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\n".to_owned();
+ // BUNDLE requires at least one identification-tag. A connection without
+ // media or a data channel has no group to advertise.
+ if !mids.is_empty() {
+ text.push_str(&format!("a=group:BUNDLE {}\r\n", mids.join(" ")));
+ }
+ text.push_str("a=extmap-allow-mixed\r\na=msid-semantic: WMS\r\n");
+ text
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use webrtc_sdp::attribute_type::{SdpAttribute, SdpAttributeType};
+
+ const SHORT: &str = "v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n";
+
+ #[test]
+ fn sdp_short_session_is_valid_without_padding_or_media() {
+ assert!(SHORT.len() < 51);
+ let parsed = parse(SHORT).unwrap();
+ assert_eq!(parsed.version, 0);
+ assert!(parsed.timing.is_some());
+ assert!(parsed.media.is_empty());
+ }
+
+ #[test]
+ fn sdp_parser_retains_unknown_attributes_as_warnings() {
+ let text = format!("{SHORT}a=x-vendor-extension:unchanged\r\n");
+ let parsed = parse(&text).unwrap();
+ assert_eq!(parsed.warnings.len(), 1);
+ assert!(matches!(
+ parsed.warnings[0],
+ SdpParserError::Unsupported { line_number: 4, .. }
+ ));
+ }
+
+ #[test]
+ fn sdp_syntax_errors_report_original_one_based_lines() {
+ for (text, line) in [
+ ("", 1),
+ ("v=0\r\n", 2),
+ ("s=-\r\no=- 0 0 IN IP4 0.0.0.0\r\nv=0\r\nt=0 0\r\n", 1),
+ ("v=0\r\no=- invalid 0 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n", 2),
+ ("v=0\r\no=- 0 0 IN IP4 0.0.0.0\r\ns=-\r\n", 4),
+ ] {
+ assert_eq!(parse(text).unwrap_err().line_number, line, "{text:?}");
+ }
+ let text = format!("{SHORT}\r\nm=audio invalid UDP/TLS/RTP/SAVPF 111\r\n");
+ assert_eq!(parse(&text).unwrap_err().line_number, 6);
+ }
+
+ #[test]
+ fn sdp_structured_media_is_separate_from_jsep_semantics() {
+ let text = format!(
+ "{SHORT}m=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:voice\r\na=sendonly\r\na=rtpmap:111 opus/48000/2\r\na=rid:high send pt=112\r\n"
+ );
+ let parsed = parse(&text).unwrap();
+ assert_eq!(parsed.media.len(), 1);
+ assert!(
+ matches!(parsed.media[0].get_attribute(SdpAttributeType::Mid), Some(SdpAttribute::Mid(mid)) if mid == "voice")
+ );
+ // A RID referring to an absent payload is a semantic failure, not a
+ // reason to classify an otherwise parsed description as syntax-error.
+ assert!(
+ parsed.media[0]
+ .get_attribute(SdpAttributeType::Rid)
+ .is_some()
+ );
+ }
+}