| 1 | use crate::sdp::{self, Attribute}; |
| 2 | |
| 3 | pub fn teams_candidate(browser: &str) -> Option<String> { |
| 4 | let line = browser.trim().trim_start_matches("a=").trim_start_matches("candidate:"); |
| 5 | let tokens: Vec<&str> = line.split_whitespace().collect(); |
| 6 | let [foundation, component, transport, priority, address, port, "typ", kind, rest @ ..] = tokens.as_slice() else { |
| 7 | return None; |
| 8 | }; |
| 9 | if address.ends_with(".local") { |
| 10 | return None; |
| 11 | } |
| 12 | let mut related = Vec::new(); |
| 13 | let mut tcp_type = None; |
| 14 | for pair in rest.chunks(2) { |
| 15 | match pair { |
| 16 | ["raddr", value] | ["rport", value] => related.push(format!("{} {value}", pair[0])), |
| 17 | ["tcptype", value] => tcp_type = Some(*value), |
| 18 | _ => {} |
| 19 | } |
| 20 | } |
| 21 | let transport = match (transport.to_ascii_lowercase().as_str(), tcp_type) { |
| 22 | ("udp", _) => "UDP", |
| 23 | ("tcp", Some("active")) => "TCP-ACT", |
| 24 | ("tcp", Some("passive")) => "TCP-PASS", |
| 25 | ("tcp", Some("so")) => "TCP-SO", |
| 26 | _ => return None, |
| 27 | }; |
| 28 | let mut text = format!("{foundation} {component} {transport} {priority} {address} {port} typ {kind}"); |
| 29 | for part in related { |
| 30 | text.push(' '); |
| 31 | text.push_str(&part); |
| 32 | } |
| 33 | Some(text) |
| 34 | } |
| 35 | |
| 36 | fn candidate_ufrag(browser: &str) -> Option<&str> { |
| 37 | let tokens: Vec<&str> = browser.split_whitespace().collect(); |
| 38 | tokens.windows(2).find(|pair| pair[0] == "ufrag").map(|pair| pair[1]) |
| 39 | } |
| 40 | |
| 41 | pub fn is_udp_relay(browser: &str) -> bool { |
| 42 | let lower = browser.to_ascii_lowercase(); |
| 43 | lower.contains(" udp ") && lower.contains(" typ relay") |
| 44 | } |
| 45 | |
| 46 | struct DefaultAddress { |
| 47 | address: String, |
| 48 | port: String, |
| 49 | } |
| 50 | |
| 51 | fn default_address(candidates: &[String]) -> Option<DefaultAddress> { |
| 52 | let rank = |kind: &str| match kind { |
| 53 | "relay" => 0, |
| 54 | "srflx" => 1, |
| 55 | _ => 2, |
| 56 | }; |
| 57 | candidates |
| 58 | .iter() |
| 59 | .filter_map(|candidate| { |
| 60 | let tokens: Vec<&str> = candidate.split_whitespace().collect(); |
| 61 | (tokens.get(1) == Some(&"1")).then_some(())?; |
| 62 | let transport_rank = if tokens.get(2) == Some(&"UDP") { 0 } else { 1 }; |
| 63 | Some(((transport_rank, rank(tokens.get(7)?)), tokens.get(4)?.to_string(), tokens.get(5)?.to_string())) |
| 64 | }) |
| 65 | .min_by_key(|(rank, _, _)| *rank) |
| 66 | .map(|(_, address, port)| DefaultAddress { address, port }) |
| 67 | } |
| 68 | |
| 69 | fn connection_for(address: &str) -> String { |
| 70 | if address.contains(':') { format!("IN IP6 {address}") } else { format!("IN IP4 {address}") } |
| 71 | } |
| 72 | |
| 73 | /// Replaces the placeholder transport of a signaled SDP with the gathered candidates, for a peer that is not the mixer. |
| 74 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 75 | pub enum SdpKind { |
| 76 | Offer, |
| 77 | Answer, |
| 78 | } |
| 79 | |
| 80 | fn settled_role(sdp: &str) -> Option<&str> { |
| 81 | sdp.lines() |
| 82 | .filter_map(|line| line.trim_end_matches('\r').strip_prefix("a=setup:")) |
| 83 | .find(|role| matches!(*role, "active" | "passive")) |
| 84 | } |
| 85 | |
| 86 | /// The DTLS role this side took in the last negotiation; Teams keeps it in re-offers instead of `actpass`. |
| 87 | pub fn negotiated_setup(local_sdp: Option<&str>, remote_sdp: Option<&str>) -> Option<String> { |
| 88 | if let Some(role) = local_sdp.and_then(settled_role) { |
| 89 | return Some(role.to_owned()); |
| 90 | } |
| 91 | match remote_sdp.and_then(settled_role)? { |
| 92 | "active" => Some("passive".to_owned()), |
| 93 | _ => Some("active".to_owned()), |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub fn with_candidates(teams_sdp: &str, browser_candidates: &[String], kind: SdpKind) -> crate::error::Result<String> { |
| 98 | let mut description = sdp::parse(teams_sdp)?; |
| 99 | let ufrag = description.media.first().and_then(|media| media.value("ice-ufrag")).map(str::to_owned); |
| 100 | let candidates: Vec<String> = browser_candidates |
| 101 | .iter() |
| 102 | .filter(|candidate| ufrag.as_deref().is_none_or(|ufrag| candidate_ufrag(candidate).is_none_or(|own| own == ufrag))) |
| 103 | .filter_map(|candidate| teams_candidate(candidate)) |
| 104 | .collect(); |
| 105 | let Some(default) = default_address(&candidates) else { |
| 106 | return Ok(teams_sdp.to_owned()); |
| 107 | }; |
| 108 | let connection = connection_for(&default.address); |
| 109 | if description.session.connection.is_some() { |
| 110 | description.session.connection = Some(connection.clone()); |
| 111 | } |
| 112 | for media in &mut description.media { |
| 113 | if media.port == "0" { |
| 114 | continue; |
| 115 | } |
| 116 | media.port = default.port.clone(); |
| 117 | media.connection = Some(connection.clone()); |
| 118 | let carried_candidates = media.attributes.iter().any(|attribute| attribute.name == "candidate"); |
| 119 | let mut attributes = Vec::with_capacity(media.attributes.len() + candidates.len()); |
| 120 | for attribute in media.attributes.drain(..) { |
| 121 | match attribute.name.as_str() { |
| 122 | "candidate" => {} |
| 123 | "rtcp" if kind == SdpKind::Offer => attributes.push(Attribute::with_value("rtcp", &default.port)), |
| 124 | "rtcp" => {} |
| 125 | _ => attributes.push(attribute), |
| 126 | } |
| 127 | } |
| 128 | if carried_candidates { |
| 129 | let position = attributes.iter().position(|attribute| attribute.name == "ssrc" || attribute.name == "label").unwrap_or(attributes.len()); |
| 130 | for (offset, candidate) in candidates.iter().enumerate() { |
| 131 | attributes.insert(position + offset, Attribute::with_value("candidate", candidate)); |
| 132 | } |
| 133 | } |
| 134 | media.attributes = attributes; |
| 135 | } |
| 136 | Ok(sdp::write(&description)) |
| 137 | } |
| 138 | |
| 139 | #[cfg(test)] |
| 140 | mod tests { |
| 141 | use super::*; |
| 142 | |
| 143 | #[test] |
| 144 | fn browser_candidates_take_the_teams_form() { |
| 145 | assert_eq!( |
| 146 | teams_candidate("candidate:842163049 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001 generation 0 ufrag abc network-id 1 network-cost 10").as_deref(), |
| 147 | Some("842163049 1 UDP 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001") |
| 148 | ); |
| 149 | assert_eq!( |
| 150 | teams_candidate("a=candidate:1 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0").as_deref(), |
| 151 | Some("1 1 TCP-ACT 1518280447 10.0.0.2 9 typ host") |
| 152 | ); |
| 153 | assert_eq!(teams_candidate("candidate:2 1 udp 2122260223 abcd-1234.local 50000 typ host generation 0"), None); |
| 154 | } |
| 155 | |
| 156 | #[test] |
| 157 | fn the_relay_candidate_becomes_the_default_transport() { |
| 158 | let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nc=IN IP4 10.10.10.10\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=rtpmap:111 opus/48000/2\r\na=label:main-audio\r\na=mid:0\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=rtpmap:102 H264/90000\r\na=label:main-video\r\na=mid:1\r\nm=video 0 RTP/SAVP 102\r\na=mid:2\r\n"; |
| 159 | let gathered = vec![ |
| 160 | "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0".to_owned(), |
| 161 | "candidate:2 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 50000".to_owned(), |
| 162 | "candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001".to_owned(), |
| 163 | ]; |
| 164 | let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap(); |
| 165 | assert!(text.contains("m=audio 3480 RTP/SAVP 111")); |
| 166 | assert!(text.contains("m=video 3480 RTP/SAVP 102")); |
| 167 | assert!(text.contains("m=video 0 RTP/SAVP 102")); |
| 168 | assert!(text.contains("c=IN IP4 52.114.0.9")); |
| 169 | assert!(text.contains("a=rtcp:3480")); |
| 170 | assert!(!text.contains("10.10.10.10")); |
| 171 | assert_eq!(text.matches("a=candidate:").count(), 3); |
| 172 | assert!(text.contains("a=candidate:3 1 UDP 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001")); |
| 173 | } |
| 174 | |
| 175 | #[test] |
| 176 | fn old_ice_generations_and_tcp_only_gathering_are_handled() { |
| 177 | let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=ice-ufrag:new\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=mid:0\r\n"; |
| 178 | let gathered = vec![ |
| 179 | "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0 ufrag old".to_owned(), |
| 180 | "candidate:2 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0 ufrag new".to_owned(), |
| 181 | ]; |
| 182 | let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap(); |
| 183 | assert!(!text.contains("50000")); |
| 184 | assert!(text.contains("m=audio 9 RTP/SAVP 111")); |
| 185 | assert!(text.contains("a=candidate:2 1 TCP-ACT 1518280447 10.0.0.2 9 typ host")); |
| 186 | assert!(is_udp_relay("candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 1.2.3.4 rport 5")); |
| 187 | assert!(!is_udp_relay("candidate:3 1 tcp 41885439 52.114.0.9 443 typ relay tcptype passive")); |
| 188 | } |
| 189 | |
| 190 | #[test] |
| 191 | fn without_candidates_the_sdp_stays_as_it_is() { |
| 192 | assert_eq!(with_candidates("v=0\r\n", &[], SdpKind::Offer).unwrap(), "v=0\r\n"); |
| 193 | assert_eq!(negotiated_setup(Some("v=0\r\na=setup:actpass\r\na=setup:active\r\n"), None).as_deref(), Some("active")); |
| 194 | assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), Some("a=setup:active\r\n")).as_deref(), Some("passive")); |
| 195 | assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), None), None); |
| 196 | } |
| 197 | } |