libp2p_webrtc_websys/
sdp.rs

1use std::net::SocketAddr;
2
3use libp2p_webrtc_utils::Fingerprint;
4use web_sys::{RtcSdpType, RtcSessionDescriptionInit};
5
6/// Creates the SDP answer used by the client.
7pub(crate) fn answer(
8    addr: SocketAddr,
9    server_fingerprint: Fingerprint,
10    client_ufrag: &str,
11) -> RtcSessionDescriptionInit {
12    let answer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Answer);
13    answer_obj.set_sdp(&libp2p_webrtc_utils::sdp::answer(
14        addr,
15        server_fingerprint,
16        client_ufrag,
17    ));
18    answer_obj
19}
20
21/// Creates the munged SDP offer from the Browser's given SDP offer
22///
23/// Certificate verification is disabled which is why we hardcode a dummy fingerprint here.
24pub(crate) fn offer(offer: String, client_ufrag: &str) -> RtcSessionDescriptionInit {
25    // find line and replace a=ice-ufrag: with "\r\na=ice-ufrag:{client_ufrag}\r\n"
26    // find line and replace a=ice-pwd: with "\r\na=ice-ufrag:{client_ufrag}\r\n"
27
28    let mut munged_sdp_offer = String::new();
29
30    for line in offer.split("\r\n") {
31        if line.starts_with("a=ice-ufrag:") {
32            munged_sdp_offer.push_str(&format!("a=ice-ufrag:{client_ufrag}\r\n"));
33            continue;
34        }
35
36        if line.starts_with("a=ice-pwd:") {
37            munged_sdp_offer.push_str(&format!("a=ice-pwd:{client_ufrag}\r\n"));
38            continue;
39        }
40
41        if !line.is_empty() {
42            munged_sdp_offer.push_str(&format!("{}\r\n", line));
43            continue;
44        }
45    }
46
47    // remove any double \r\n
48    let munged_sdp_offer = munged_sdp_offer.replace("\r\n\r\n", "\r\n");
49
50    tracing::trace!(offer=%munged_sdp_offer, "Created SDP offer");
51
52    let offer_obj = RtcSessionDescriptionInit::new(RtcSdpType::Offer);
53    offer_obj.set_sdp(&munged_sdp_offer);
54
55    offer_obj
56}