diff --git a/crates/voelin-core/src/link/session_link.rs b/crates/voelin-core/src/link/session_link.rs index 8cd1541..a4e351d 100644 --- a/crates/voelin-core/src/link/session_link.rs +++ b/crates/voelin-core/src/link/session_link.rs @@ -207,7 +207,10 @@ async fn drive( ) -> Option { let (media_tx, media_rx) = mpsc::unbounded_channel(); let sink: Arc = Arc::new(MediaQueue(media_tx)); - let params = crate::ts_session::connect_params(options, sink, backends); + let params = match crate::ts_session::connect_params(options, sink, backends) { + Ok(params) => params, + Err(e) => return connect_failure(&e), + }; let local = LocalCtx::new(ctx.clone(), options.audio, options.stream_peer.clone()); let mut early: VecDeque = VecDeque::new(); diff --git a/crates/voelin-core/src/link/tests.rs b/crates/voelin-core/src/link/tests.rs index b9714ed..e7f5526 100644 --- a/crates/voelin-core/src/link/tests.rs +++ b/crates/voelin-core/src/link/tests.rs @@ -2253,3 +2253,25 @@ async fn the_features_of_a_server_are_the_hosts_narrowed_by_the_servers_list() { }) .await; } + +/// A port that is no port is refused in words, not dropped: the connection +/// would go to another port than the one the bookmark names. +#[tokio::test(flavor = "multi_thread")] +async fn a_bookmark_with_a_port_that_is_no_port_does_not_connect() { + let mut backends = Backends::empty(); + let (conns, mut seen) = mpsc::unbounded_channel(); + backends.register_local(Arc::new(LinkConnector::any(Arc::new(Recorder(conns))))); + let link = SessionLink::new(backends); + let ctx = LocalCtx::standalone().link; + let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel(); + let (event_tx, mut events) = mpsc::unbounded_channel(); + link.spawn(ConnectOptions::new("ts.example.com:99999", "tester"), ctx, cmd_rx, event_tx); + let reason = event_of(&mut events, |e| match e { + LinkEvent::Disconnected(reason) => Some(reason), + _ => None, + }) + .await; + let reason = reason.expect("a reason"); + assert!(reason.contains("65535") && reason.contains("ts.example.com:99999"), "{reason}"); + assert!(seen.try_recv().is_err(), "a link was asked to connect anyway"); +} diff --git a/crates/voelin-core/src/ts_session/mod.rs b/crates/voelin-core/src/ts_session/mod.rs index bc6ec3b..da67c7f 100644 --- a/crates/voelin-core/src/ts_session/mod.rs +++ b/crates/voelin-core/src/ts_session/mod.rs @@ -75,11 +75,13 @@ fn now_ms() -> i64 { /// v1 has fields for them), the server password is `Hello.password` and the /// privilege key `Hello.invite_code`. The identity goes as /// `Credential::Foreign`; no account is used yet. +/// +/// An address a link cannot carry is refused here ([`bookmark`]). pub(crate) fn connect_params( options: &ConnectOptions, media: Arc, backends: &Backends, -) -> ConnectParams { +) -> Result { let credential = Credential::Foreign { kind: IDENTITY_KIND, blob: options @@ -102,8 +104,8 @@ pub(crate) fn connect_params( invite_code: options.token.clone().unwrap_or_default(), ..Default::default() }; - ConnectParams { - address: address_link(options), + Ok(ConnectParams { + address: address_link(options)?, credential, linked: Vec::new(), account: backends.account(), @@ -114,18 +116,18 @@ pub(crate) fn connect_params( media, push_capacity: 1024, timeout: Duration::from_secs(35), - } + }) } /// The `ts3server://` link of the options' address, with the channel to join /// and the client version to claim. -fn address_link(options: &ConnectOptions) -> String { +fn address_link(options: &ConnectOptions) -> Result { let mut link = match Link::parse(&options.address) { Some(Link::Server(link)) => link, // Not a TeamSpeak link, or none: a bookmark's `host[:port]`. - _ if !options.address.contains("://") => voelin_model::ServerLink::new(&options.address), + _ if !options.address.contains("://") => bookmark(&options.address)?, // Some other scheme: as given, for the connector of that scheme. - _ => return options.address.clone(), + _ => return Ok(options.address.clone()), }; link.channel = options.channel.clone().filter(|c| !c.is_empty()).or(link.channel); link.channel_password = @@ -138,7 +140,45 @@ fn address_link(options: &ConnectOptions) -> String { url.push('='); url.push_str(&URL_SAFE_NO_PAD.encode(version)); } - url + Ok(url) +} + +/// The link to a bookmark's `host[:port]`. +/// +/// A link cannot say everything an address can: it drops a port that is no +/// port (`ServerLink::new` takes `host:99999` for the host `host` and joins +/// the default port), and it ends the host at a `?`, `#` or `/` and decodes a +/// `%` (so that a `?` in the host would hide the channel behind the next +/// one). The TeamSpeak library refuses such an address when it resolves it; +/// so does this, in words, instead of connecting to something else. +fn bookmark(address: &str) -> Result { + let address = address.trim(); + // Without the query: a link keeps secrets in it. + let shown = crate::link::without_query(address); + let not_an_address = || SessionError::Protocol(format!("not a server address: {shown}")); + if address.is_empty() + || address + .chars() + .any(|c| matches!(c, '?' | '#' | '/' | '%') || c.is_whitespace() || c.is_control()) + { + return Err(not_an_address()); + } + // The text after the port's colon: `[v6]:port`, or `host:port` with the one + // colon (more colons are an IPv6 address without a port). + let port = if let Some(rest) = address.strip_prefix('[') { + let (_, after) = rest.split_once(']').ok_or_else(not_an_address)?; + (!after.is_empty()).then(|| after.strip_prefix(':').unwrap_or(after)) + } else { + address.rsplit_once(':').filter(|(host, _)| !host.contains(':')).map(|(_, port)| port) + }; + if let Some(port) = port + && !port.parse::().is_ok_and(|port| port != 0) + { + return Err(SessionError::Protocol(format!( + "the port in {shown} is not a number from 1 to 65535" + ))); + } + Ok(voelin_model::ServerLink::new(address)) } /// The options a TeamSpeak link is connected with: the reverse of @@ -681,7 +721,7 @@ mod tests { fn params(options: &ConnectOptions) -> ConnectParams { let (media, _rx) = voelin_proto::test_util::media_channel(); - connect_params(options, media, &Backends::empty()) + connect_params(options, media, &Backends::empty()).unwrap() } fn back(options: &ConnectOptions) -> ConnectOptions { @@ -787,4 +827,91 @@ mod tests { assert_eq!(client.name, "Voelin"); assert_eq!(sent.hello.version, 1); } + + /// Why `connect_params` refused an address, if it did. + fn refused(address: &str) -> Option { + let (media, _rx) = voelin_proto::test_util::media_channel(); + match connect_params(&ConnectOptions::new(address, "nick"), media, &Backends::empty()) { + Ok(_) => None, + Err(SessionError::Protocol(text)) => Some(text), + Err(other) => panic!("{address}: {other}"), + } + } + + #[test] + fn a_bookmark_the_link_would_change_is_refused() { + // A port that is no port, in any shape: the link would drop it and the + // connection would go to the default port. + for address in [ + "ts.example.com:99999", + "ts.example.com:65536", + "ts.example.com:0", + "ts.example.com:abc", + "ts.example.com:", + "[::1]:70000", + "[::1]:", + "[::1]x", + ] { + let text = refused(address).unwrap_or_else(|| panic!("{address} was accepted")); + assert!(text.contains("65535") && text.contains(address), "{text}"); + } + // A host the link would cut or decode: a `?` hides the channel behind the + // next one, a `/` or `#` ends the host, a `%` is decoded. + for address in [ + "", + " ", + "ts.example.com?x", + "ts.example.com#x", + "ts.example.com/x", + "a b", + "h%41", + "[::1", + ] { + let text = refused(address).unwrap_or_else(|| panic!("{address:?} was accepted")); + assert!(text.starts_with("not a server address"), "{text}"); + } + // The text names no query: a link keeps secrets in it. + let text = refused("ts.example.com?password=hunter2").unwrap(); + assert!(!text.contains("hunter2"), "{text}"); + } + + #[test] + fn the_bookmarks_a_server_has_come_back_with_their_channel() { + for (address, host) in [ + ("ts.example.com", "ts.example.com"), + ("ts.example.com:9987", "ts.example.com:9987"), + (" ts.example.com:1 ", "ts.example.com:1"), + ("127.0.0.1:65535", "127.0.0.1:65535"), + ("[::1]:9987", "[::1]:9987"), + // The brackets of a v6 address without a port are the link's to drop; + // the TeamSpeak library reads both forms. + ("[::1]", "::1"), + ("::1", "::1"), + ("2001:db8::1", "2001:db8::1"), + ] { + let mut options = ConnectOptions::new(address, "nick"); + options.channel = Some("Games/Raid".into()); + let got = back(&options); + assert_eq!((got.address.as_str(), got.channel.as_deref()), (host, Some("Games/Raid"))); + } + } + + /// The normalisations of the round trip, listed in `docs/session-seam.md` + /// (13): an empty option is none, and an empty nickname stays empty. + #[test] + fn empty_options_come_back_as_none() { + let mut options = ConnectOptions::new("ts.example.com", ""); + options.server_password = Some(String::new()); + options.channel = Some(String::new()); + options.channel_password = Some(String::new()); + options.token = Some(String::new()); + let got = back(&options); + assert!(got.nickname.is_empty()); + assert!( + got.server_password.is_none() + && got.channel.is_none() + && got.channel_password.is_none() + && got.token.is_none() + ); + } }