Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions scripts/check.sh
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
#!/usr/bin/env bash
# Static checks: Rust unit tests + clippy, TypeScript typecheck + unit tests
# Static checks: Rust formatting, unit tests + clippy, TypeScript typecheck + unit tests
# (vitest), and that THIRD_PARTY_NOTICES.md matches the current dependencies.
# (End-to-end: scripts/smoke.sh)
set -euo pipefail
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
[[ -f "$ROOT/.deps/env.sh" ]] && . "$ROOT/.deps/env.sh"
echo "==> cargo fmt"
(cd "$ROOT/src-tauri" && cargo fmt --check)
echo "==> cargo test"
(cd "$ROOT/src-tauri" && cargo test --lib --quiet)
echo "==> cargo clippy"
(cd "$ROOT/src-tauri" && cargo clippy --quiet --all-targets -- -D warnings)
(cd "$ROOT/src-tauri" && cargo clippy --quiet --all-targets -- -D warnings -D clippy::undocumented_unsafe_blocks)
echo "==> tsc"
(cd "$ROOT" && bunx tsc --noEmit -p .)
echo "==> vitest"
Expand Down
8 changes: 4 additions & 4 deletions src-tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ fn main() {
/// FFmpeg's headers. Built before the media engine is linked: static
/// archives must come after the code that uses them.
fn build_cast_remux() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo"));
let prefix = std::env::var("TP_MEDIA_PREFIX")
.map(PathBuf::from)
.unwrap_or_else(|_| manifest.join("../third_party/prefix"));
Expand All @@ -39,7 +39,7 @@ fn build_cast_remux() {
/// dynamic tail differs: no pkg-config probe (macOS's static archives reference
/// frameworks and libSystem), link the well-known set directly.
fn link_media_engine_macos() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo"));
let prefix = std::env::var("TP_MEDIA_PREFIX")
.map(PathBuf::from)
.unwrap_or_else(|_| manifest.join("../third_party/prefix"));
Expand Down Expand Up @@ -222,7 +222,7 @@ fn link_swift_surface(manifest: &std::path::Path) {
/// dynamically. The result is a single self-contained executable whose codec
/// support does not depend on the distro's FFmpeg build.
fn link_media_engine() {
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap());
let manifest = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").expect("set by cargo"));
let prefix = std::env::var("TP_MEDIA_PREFIX")
.map(PathBuf::from)
.unwrap_or_else(|_| manifest.join("../third_party/prefix"));
Expand Down Expand Up @@ -264,7 +264,7 @@ fn link_media_engine() {
);
}
String::from_utf8(out.stdout)
.unwrap()
.expect("pkg-config prints UTF-8")
.split_whitespace()
.map(str::to_owned)
.collect()
Expand Down
65 changes: 53 additions & 12 deletions src-tauri/src/cast/castv2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,14 @@ use std::time::Duration;

use tokio::io::{AsyncReadExt, AsyncWriteExt, ReadHalf, WriteHalf};
use tokio::net::TcpStream;
use tokio_rustls::TlsConnector;
use tokio_rustls::client::TlsStream;
use tokio_rustls::rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use tokio_rustls::rustls::client::danger::{
HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,
};
use tokio_rustls::rustls::crypto::{self, CryptoProvider};
use tokio_rustls::rustls::pki_types::{CertificateDer, ServerName, UnixTime};
use tokio_rustls::rustls::{self, ClientConfig, DigitallySignedStruct, SignatureScheme};
use tokio_rustls::TlsConnector;

pub const NS_CONNECTION: &str = "urn:x-cast:com.google.cast.tp.connection";
pub const NS_HEARTBEAT: &str = "urn:x-cast:com.google.cast.tp.heartbeat";
Expand All @@ -42,7 +44,12 @@ pub struct Message {

impl Message {
pub fn new(destination: &str, namespace: &str, payload: String) -> Self {
Message { source: SENDER.into(), destination: destination.into(), namespace: namespace.into(), payload }
Message {
source: SENDER.into(),
destination: destination.into(),
namespace: namespace.into(),
payload,
}
}
}

Expand Down Expand Up @@ -92,7 +99,12 @@ fn get_varint(buf: &[u8], pos: &mut usize) -> Option<u64> {
/// Parses a `CastMessage`; `None` for malformed or binary-payload messages
/// (device authentication, which this sender doesn't use).
pub fn decode(buf: &[u8]) -> Option<Message> {
let mut m = Message { source: String::new(), destination: String::new(), namespace: String::new(), payload: String::new() };
let mut m = Message {
source: String::new(),
destination: String::new(),
namespace: String::new(),
payload: String::new(),
};
let mut has_payload = false;
let mut pos = 0;
while pos < buf.len() {
Expand Down Expand Up @@ -127,6 +139,12 @@ pub fn decode(buf: &[u8]) -> Option<Message> {

// --------------------------------------------------------------- TLS

/// Accepts any server certificate. Deliberate: Chromecasts present a
/// self-signed certificate (device authentication happens over the Cast
/// channel, which this sender skips), and the address comes from mDNS or the
/// user on the local network. Handshake signatures are still verified, so
/// the session is encrypted — just not authenticated. Never reuse this for
/// anything that talks to the internet.
#[derive(Debug)]
struct DeviceCert(Arc<CryptoProvider>);

Expand All @@ -148,7 +166,12 @@ impl ServerCertVerifier for DeviceCert {
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
crypto::verify_tls12_signature(message, cert, dss, &self.0.signature_verification_algorithms)
crypto::verify_tls12_signature(
message,
cert,
dss,
&self.0.signature_verification_algorithms,
)
}

fn verify_tls13_signature(
Expand All @@ -157,7 +180,12 @@ impl ServerCertVerifier for DeviceCert {
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
crypto::verify_tls13_signature(message, cert, dss, &self.0.signature_verification_algorithms)
crypto::verify_tls13_signature(
message,
cert,
dss,
&self.0.signature_verification_algorithms,
)
}

fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
Expand All @@ -167,6 +195,9 @@ impl ServerCertVerifier for DeviceCert {

type Tls = TlsStream<TcpStream>;

/// For each of the TCP connect and the TLS handshake.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(6);

pub struct Reader(ReadHalf<Tls>);
pub struct Writer(WriteHalf<Tls>);

Expand All @@ -180,15 +211,18 @@ pub async fn connect(addr: SocketAddr) -> io::Result<(Reader, Writer, IpAddr)> {
.dangerous()
.with_custom_certificate_verifier(Arc::new(DeviceCert(provider)))
.with_no_client_auth();
let tcp = tokio::time::timeout(Duration::from_secs(6), TcpStream::connect(addr))
let tcp = tokio::time::timeout(CONNECT_TIMEOUT, TcpStream::connect(addr))
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??;
tcp.set_nodelay(true)?;
let local = tcp.local_addr()?.ip();
let name = ServerName::IpAddress(addr.ip().into());
let tls = tokio::time::timeout(Duration::from_secs(6), TlsConnector::from(Arc::new(config)).connect(name, tcp))
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??;
let tls = tokio::time::timeout(
CONNECT_TIMEOUT,
TlsConnector::from(Arc::new(config)).connect(name, tcp),
)
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "the device did not answer"))??;
let (r, w) = tokio::io::split(tls);
Ok((Reader(r), Writer(w), local))
}
Expand All @@ -199,7 +233,10 @@ impl Reader {
loop {
let len = self.0.read_u32().await? as usize;
if len > MAX_FRAME {
return Err(io::Error::new(io::ErrorKind::InvalidData, "oversized cast frame"));
return Err(io::Error::new(
io::ErrorKind::InvalidData,
"oversized cast frame",
));
}
let mut buf = vec![0; len];
self.0.read_exact(&mut buf).await?;
Expand Down Expand Up @@ -227,7 +264,11 @@ mod tests {

#[test]
fn round_trips_messages() {
let m = Message::new(RECEIVER, NS_RECEIVER, r#"{"type":"LAUNCH","appId":"CC1AD845","requestId":1}"#.into());
let m = Message::new(
RECEIVER,
NS_RECEIVER,
r#"{"type":"LAUNCH","appId":"CC1AD845","requestId":1}"#.into(),
);
let bytes = encode(&m);
// protocol 0, then source "sender-0"
assert_eq!(&bytes[..4], &[0x08, 0x00, 0x12, 0x08]);
Expand Down
188 changes: 188 additions & 0 deletions src-tauri/src/cast/commands.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
//! The `cast_*` commands the UI drives casting with.

use super::*;

/// The cast devices found so far; the first call starts looking
/// (updates follow as `cast://devices`).
#[tauri::command]
pub fn cast_devices<R: Runtime>(app: AppHandle<R>, cast: State<'_, Cast>) -> Result<Devices> {
if cast.relay.is_none() {
return Err(Error::msg(
"Casting is unavailable: no network port could be opened",
));
}
// mDNS is optional: the search by address finds TVs without it
if let Err(e) = start_browsing(&app, &cast) {
log::warn!("cast: {e}");
}
search(&app, &cast);
Ok(cast.list())
}

/// Adds a TV by its IP address (for networks where it can't be found).
#[tauri::command]
pub async fn cast_add_device<R: Runtime>(
app: AppHandle<R>,
state: State<'_, AppState>,
cast: State<'_, Cast>,
address: String,
) -> Result<Device> {
let ip = probe::parse_address(&address)
.ok_or_else(|| Error::msg("Enter the TV's IP address, like 192.168.1.20"))?;
let device = probe::probe(&state.http, ip).await.ok_or_else(|| {
Error::msg(format!(
"No Chromecast answered at {ip}. Check the address in the Google Home app."
))
})?;
remember(state.inner(), &device).await;
if cast.found(device.clone()) {
emit_devices(&app);
}
Ok(device)
}

/// Plays `req` on a TV: on `device_id` (starting a session there), or on the
/// TV already being cast to. Local playback stops — the account streams to
/// one place.
#[tauri::command]
#[allow(clippy::too_many_arguments)] // Tauri injects each managed `State` as an argument
pub async fn cast_play<R: Runtime>(
app: AppHandle<R>,
state: State<'_, AppState>,
player: State<'_, Player>,
probe: State<'_, Arc<crate::probe::Probe>>,
cast: State<'_, Cast>,
device_id: Option<String>,
req: PlayRequest,
meta: Option<Meta>,
) -> Result<()> {
let st = state.inner().clone();
let stream = playback::resolve_and_touch(&st, &req).await?;
let audio_lang =
read_blocking(&st, |conn| Ok(settings::get_str(conn, "player.audioLang"))).await?;
probe.cancel_running().await?;
let _ = player.stop();

let mut urls = vec![stream.url];
urls.extend(stream.alternates);
let mut meta = meta.unwrap_or_default();
meta.title = meta.title.or(req.title.clone());
let item = Box::new(Item {
source: relay::Source {
urls,
user_agent: stream.user_agent,
referrer: stream.referrer,
live: stream.live,
audio_lang,
},
meta,
start: req.start.unwrap_or(0.0),
});

let mut session = cast.session.lock();
let running = session.as_ref().filter(|s| !s.status.lock().finished());
let reuse = match (&device_id, running) {
(None, Some(_)) => true,
(Some(id), Some(s)) => &s.device.id == id,
(None, None) => return Err(Error::msg("Not casting")),
(Some(_), None) => false,
};
if reuse {
let s = session.as_ref().expect("running session");
log::info!(
"cast: {} {}:{} to {}",
req.kind,
req.source_id,
req.id,
s.device.name
);
return s
.tx
.send(Cmd::Load(item))
.map_err(|_| Error::msg("The cast session has ended"));
}

let id = device_id.unwrap_or_default();
let device = cast
.devices
.lock()
.get(&id)
.cloned()
.ok_or_else(|| Error::msg("That TV is no longer on the network"))?;
if let Some(old) = session.take() {
let _ = old.tx.send(Cmd::Stop);
}
let (tx, rx) = mpsc::unbounded_channel();
let status = Arc::new(Mutex::new(Status {
device_id: device.id.clone(),
device_name: device.name.clone(),
state: "connecting",
live: item.source.live,
volume: 1.0,
..Default::default()
}));
let _ = app.emit(STATUS_EVENT, status.lock().clone());
log::info!(
"cast: {} {}:{} to {}",
req.kind,
req.source_id,
req.id,
device.name
);
let _ = tx.send(Cmd::Load(item));
let sid = {
let mut n = cast.next_id.lock();
*n += 1;
*n
};
*session = Some(Session {
id: sid,
device: device.clone(),
tx: tx.clone(),
status: status.clone(),
});
drop(session);
let app2 = app.clone();
tauri::async_runtime::spawn(async move {
run(app2.clone(), device, rx, tx, status).await;
if let Some(cast) = app2.try_state::<Cast>() {
let mut s = cast.session.lock();
if s.as_ref().is_some_and(|s| s.id == sid) {
*s = None;
}
}
});
Ok(())
}

/// play | pause | seek (seconds) | volume (0…1) | mute (0/1)
#[tauri::command]
pub fn cast_control(cast: State<'_, Cast>, action: String, value: Option<f64>) -> Result<()> {
let v = value.unwrap_or(0.0);
let cmd = match action.as_str() {
"play" => Cmd::Play,
"pause" => Cmd::Pause,
"seek" => Cmd::Seek(v),
"volume" => Cmd::Volume(v),
"mute" => Cmd::Mute(v != 0.0),
other => return Err(Error::msg(format!("unknown cast action {other}"))),
};
cast.send(cmd)
}

/// Ends casting (the TV's player closes).
#[tauri::command]
pub fn cast_stop(cast: State<'_, Cast>) -> Result<()> {
cast.stop();
Ok(())
}

/// The running session, if any.
#[tauri::command]
pub fn cast_status(cast: State<'_, Cast>) -> Option<Status> {
cast.session
.lock()
.as_ref()
.map(|s| s.status.lock().clone())
.filter(|s| !s.finished())
}
Loading
Loading