Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

23.7 KB
Raw Blame
// SPDX-License-Identifier: MPL-2.0
use std::{fmt, path::PathBuf};

use nectarlink_protocol::messages::{DeviceInfo, PowerLevel};

use crate::media::{MediaAction, MediaError};
use crate::{identity::KeyProtector, notifications::NotificationError};

/// Configuration for starting a [`Node`](crate::Node).
#[derive(Clone)]
pub struct NodeConfig {
    /// Directory for the device key, trust store and caches.
    pub data_dir: PathBuf,
    /// This device's description, sent to peers.
    pub device: DeviceInfo,
    /// The app version, e.g. "0.1.0".
    pub app_version: String,
    /// This device's power level (phones) or [`PowerLevel::NotApplicable`].
    pub power: PowerLevel,
    /// Allow connections through relay servers ("Reach my phone away from
    /// home"). Off by default: LAN only.
    pub away_mode: bool,
    /// Discover and announce on the local network via mDNS.
    pub lan_discovery: bool,
    /// Fixed UDP port to listen on (0 = any). A fixed port makes firewall
    /// rules simpler on the desktop.
    pub port: u16,
    /// How the device key is protected at rest. `None` uses the platform
    /// default (DPAPI on Windows).
    pub key_protector: Option<std::sync::Arc<dyn KeyProtector>>,
    /// Where received files go once complete. `None`: a `received` folder
    /// in `data_dir`.
    pub downloads_dir: Option<PathBuf>,
    /// Capabilities this device offers beyond the ones every build does
    /// (docs/protocol/capabilities.md), e.g. `media.control`.
    pub capabilities: Vec<String>,
    /// TCP/UDP port for LocalSend v2.1 interop (defaults to 53317, or
    /// `NECTARLINK_LOCALSEND_PORT` when set).
    pub localsend_port: u16,
    /// Loopback TCP port on a phone (`127.0.0.1:<port>`) for the USB tunnel
    /// (`adb forward tcp:0 tcp:<usb_port>`). Typically `Some(53319)` on
    /// phones and `None` on PCs.
    pub usb_port: Option<u16>,
    /// ADB server address on a PC (`127.0.0.1:5037`) for automatic USB
    /// detection, port forwarding, and USB auto-pairing.
    pub adb_server: Option<std::net::SocketAddr>,
    /// How connections pace bulk data (file transfers): the congestion
    /// controller and the flow-control windows.
    pub transport: TransportTuning,
}

/// The congestion controller for connections.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Congestion {
    /// Loss-based (RFC 9438), noq's default: grows fast until the network
    /// drops packets, filling router buffers on the way.
    Cubic,
    /// Model-based (BBRv3): sends at the measured bottleneck rate and keeps
    /// the queue short.
    Bbr3,
    /// Loss-based (RFC 9002, the QUIC specification's own), with gentler
    /// growth than Cubic. The default: on a Wi-Fi 6 network it moved files
    /// as fast as Cubic with about half the added delay for other traffic,
    /// and without the dropped packets Cubic caused (2026-10-23).
    NewReno,
}

/// Transport settings for bulk data. The defaults are what ships; the
/// environment can override them for measurements on real networks:
/// `NECTARLINK_CONGESTION` (`cubic`, `bbr3`, `newreno`) and
/// `NECTARLINK_WINDOW_MB` (the per-stream window; the connection gets twice it).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TransportTuning {
    pub congestion: Congestion,
    /// Bytes a single stream may have in flight.
    pub stream_window: u32,
    /// Bytes all streams of a connection may have in flight together.
    pub connection_window: u32,
}

impl Default for TransportTuning {
    fn default() -> Self {
        // Room for a file transfer to keep the link busy through Wi-Fi's
        // latency spikes (the QUIC defaults suit ~100 Mbit/s at 100 ms).
        TransportTuning {
            congestion: Congestion::NewReno,
            stream_window: 16 << 20,
            connection_window: 32 << 20,
        }
    }
}

impl TransportTuning {
    /// The defaults, with any `NECTARLINK_CONGESTION` / `NECTARLINK_WINDOW_MB` override.
    pub fn from_env() -> Self {
        Self::parse(
            std::env::var("NECTARLINK_CONGESTION").ok().as_deref(),
            std::env::var("NECTARLINK_WINDOW_MB").ok().as_deref(),
        )
    }

    /// The defaults with the given overrides; unknown values keep the default.
    pub fn parse(congestion: Option<&str>, window_mb: Option<&str>) -> Self {
        let mut tuning = TransportTuning::default();
        match congestion.map(|c| c.trim().to_ascii_lowercase()).as_deref() {
            Some("cubic") => tuning.congestion = Congestion::Cubic,
            Some("bbr" | "bbr3") => tuning.congestion = Congestion::Bbr3,
            Some("newreno" | "reno") => tuning.congestion = Congestion::NewReno,
            _ => {}
        }
        if let Some(mb) =
            window_mb.and_then(|w| w.trim().parse::<u32>().ok()).filter(|mb| (1..=1024).contains(mb))
        {
            tuning.stream_window = mb << 20;
            tuning.connection_window = (mb << 20).saturating_mul(2);
        }
        tuning
    }
}

impl NodeConfig {
    pub fn new(data_dir: impl Into<PathBuf>, device: DeviceInfo, app_version: impl Into<String>) -> Self {
        let localsend_port = std::env::var("NECTARLINK_LOCALSEND_PORT")
            .ok()
            .and_then(|v| v.parse::<u16>().ok())
            .unwrap_or(crate::LOCALSEND_DEFAULT_PORT);
        NodeConfig {
            data_dir: data_dir.into(),
            device,
            app_version: app_version.into(),
            power: PowerLevel::NotApplicable,
            away_mode: false,
            lan_discovery: true,
            port: 0,
            key_protector: None,
            downloads_dir: None,
            capabilities: vec![nectarlink_protocol::messages::continuity_camera::RECEIVE.into()],
            localsend_port,
            usb_port: None,
            adb_server: None,
            transport: TransportTuning::from_env(),
        }
    }
}

impl fmt::Debug for NodeConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("NodeConfig")
            .field("data_dir", &self.data_dir)
            .field("device", &self.device)
            .field("app_version", &self.app_version)
            .field("power", &self.power)
            .field("away_mode", &self.away_mode)
            .field("lan_discovery", &self.lan_discovery)
            .field("port", &self.port)
            .field("localsend_port", &self.localsend_port)
            .field("usb_port", &self.usb_port)
            .field("adb_server", &self.adb_server)
            .field("transport", &self.transport)
            .field("downloads_dir", &self.downloads_dir)
            .finish_non_exhaustive()
    }
}

/// Platform services the app provides to the core.
///
/// Implemented by each app (Windows, Android). Calls may come from any
/// thread and must not block for long.
pub trait Platform: Send + Sync + 'static {
    /// Start ringing loudly (find my device), even on silent.
    fn start_ringing(&self) {}
    /// Stop ringing.
    fn stop_ringing(&self) {}

    /// Dismiss one of this device's notifications (a PC dismissed it).
    fn dismiss_notification(&self, _key: &str) -> Result<(), NotificationError> {
        Err(NotificationError::Unsupported)
    }
    /// Run an action of one of this device's notifications; `reply` holds
    /// the text for a reply action.
    fn run_notification_action(
        &self,
        _key: &str,
        _action: &str,
        _reply: Option<&str>,
    ) -> Result<(), NotificationError> {
        Err(NotificationError::Unsupported)
    }

    /// Put text on this device's clipboard (a paired device sent it).
    /// `Err` holds a reason for logs, never the text.
    fn set_clipboard(&self, _text: &str) -> Result<(), String> {
        Err("this device has no clipboard".into())
    }

    /// Put text (with optional HTML and RTF rich text) on this device's
    /// clipboard. Defaults to calling [`Platform::set_clipboard`].
    fn set_clipboard_rich(&self, text: &str, _html: Option<&str>, _rtf: Option<&str>) -> Result<(), String> {
        self.set_clipboard(text)
    }

    /// Put an image on this device's clipboard (a paired device sent it).
    /// `mime` is `image/png` or `image/jpeg`.
    fn set_clipboard_image(&self, _mime: &str, _bytes: &[u8]) -> Result<(), String> {
        Err("this device has no clipboard".into())
    }

    /// Lock or sleep this PC (a paired phone asked). Runs after the phone
    /// got its answer. `Err` holds a reason for logs.
    fn power(&self, _action: crate::actions::PowerAction) -> Result<(), String> {
        Err("this device doesn't lock or sleep on request".into())
    }

    /// Open a web link a paired device sent (http or https; checked).
    fn open_link(&self, _from: &nectarlink_protocol::DeviceId, _url: &str) -> Result<(), String> {
        Err("this device doesn't open links".into())
    }

    /// Show or update an ongoing or completed task notification sent by a paired
    /// device (`task.notify`, `docs/protocol/actions.md`).
    fn task_notify(
        &self,
        _from: &nectarlink_protocol::DeviceId,
        _task: &crate::TaskNotify,
    ) -> Result<(), String> {
        Err("this device doesn't show task notifications".into())
    }

    /// List photo and video albums on this phone (`photos.albums`).
    fn photo_albums(&self) -> Result<Vec<crate::PhotoAlbum>, String> {
        Err("this device doesn't share photos".into())
    }

    /// List photos and videos on this phone (or in `album`), newest first by
    /// date and then by a stable order of its own (`photos.list`). `before`
    /// is the previous page's last item (date and ID): list only what comes
    /// after it in that order; from the latest when `None`.
    fn photo_list(
        &self,
        _album: Option<&str>,
        _before: Option<(i64, &str)>,
        _limit: u32,
    ) -> Result<Vec<crate::PhotoItem>, String> {
        Err("this device doesn't share photos".into())
    }

    /// Small JPEG thumbnails for the requested item IDs (`photos.thumbs`).
    /// Items whose thumbnail can't be generated are omitted rather than
    /// failing the batch.
    fn photo_thumbs(&self, _ids: &[String]) -> Result<Vec<crate::PhotoThumb>, String> {
        Err("this device doesn't share photos".into())
    }

    /// Open a photo or video on this phone for sending it to a PC that asked
    /// (`photos.get`). `Err` (a reason for logs) when it's gone.
    fn open_photo(&self, _id: &str) -> Result<crate::OutgoingFile, String> {
        Err("this device doesn't share photos".into())
    }

    /// Where a phone's screen (`session` 0, with its sound) or app window
    /// goes on this PC, when it starts streaming (after
    /// [`Node::mirror_start`](crate::Node::mirror_start)). `None` refuses
    /// the stream.
    fn mirror_sink(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _session: u32,
    ) -> Option<std::sync::Arc<dyn crate::MirrorSink>> {
        None
    }

    /// A PC asked for this phone's screen: ask the user, then (if they
    /// agree) stream it with [`Node::mirror_open`](crate::Node::mirror_open).
    /// Or, with `options.app`, for an app in a window of its own: run it on
    /// a display of its own and stream that (no asking: that's Elevated).
    /// The stream's config packets carry `options.session`. `Err` (a
    /// reason for logs) when it can't.
    fn mirror_requested(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _options: &crate::MirrorStart,
    ) -> Result<(), String> {
        Err("this device doesn't share its screen".into())
    }

    /// The PC stopped watching: stop sharing the screen or app window.
    fn mirror_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32) {}

    /// The PC's mouse or keyboard on this phone's mirrored screen or app
    /// window (checked, and only while it offers `mirror.input`, or
    /// `mirror.virtual_display` for app windows). Must return quickly.
    fn mirror_input(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32, _input: crate::MirrorInput) {
    }

    /// The PC's decoder needs a fresh start: encode a keyframe next.
    fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId, _session: u32) {}

    /// The PC resized an app window (`session` != 0): resize its display and
    /// restart its encoder at `width × height` pixels.
    fn mirror_resize_requested(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _session: u32,
        _width: u32,
        _height: u32,
    ) {
    }

    /// The PC changed `stay_awake` or `screen_off` while mirroring this phone's
    /// screen (`session == 0`).
    fn mirror_power_requested(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _stay_awake: bool,
        _screen_off: bool,
    ) {
    }

    /// The apps a PC may open in windows of their own (launchable ones),
    /// with small PNG icons (a PC asked).
    fn phone_apps(&self) -> Result<Vec<crate::PhoneApp>, String> {
        Err("this device doesn't open apps in windows".into())
    }

    /// This phone's latest conversations, newest first (a PC asked).
    fn sms_threads(&self, _limit: u32) -> Result<Vec<crate::SmsThread>, String> {
        Err("this device has no messages".into())
    }

    /// A conversation's messages before `before` (Unix ms; the latest when
    /// `None`), newest first.
    fn sms_messages(
        &self,
        _thread: &str,
        _before: Option<i64>,
        _limit: u32,
    ) -> Result<Vec<crate::SmsMessage>, String> {
        Err("this device has no messages".into())
    }

    /// Send a text (checked: 1-20 recipients, not empty).
    fn sms_send(&self, _to: &[String], _body: &str) -> Result<(), String> {
        Err("this device doesn't send texts".into())
    }

    /// Send a text or MMS with optional image attachments (checked: 1-20
    /// recipients, body or attachments non-empty, attachment MIME and sizes
    /// within limits).
    fn send_sms_with_attachments(
        &self,
        to: &[String],
        body: &str,
        attachments: &[crate::SmsAttachment],
    ) -> Result<(), String> {
        if attachments.is_empty() {
            self.sms_send(to, body)
        } else {
            Err("MMS attachments are not supported on this device".into())
        }
    }

    /// A picture in a message: its type and bytes.
    fn sms_part(&self, _id: &str) -> Result<(String, Vec<u8>), String> {
        Err("this device has no messages".into())
    }

    /// Answer, decline or silence this phone's call `id` (a PC asked; the
    /// core checked it's the call in progress). `Err` holds a reason for logs.
    fn call_command(&self, _id: &str, _command: crate::CallCommand) -> Result<(), String> {
        Err("this device doesn't take calls".into())
    }

    /// This phone's recent calls before `before` (Unix ms; the latest when
    /// `None`), newest first (a PC asked).
    fn call_log(&self, _before: Option<i64>, _limit: u32) -> Result<Vec<crate::CallLogEntry>, String> {
        Err("this device has no call history".into())
    }

    /// Place a call to `number` (or open the dialer with it filled in) on
    /// this phone (a PC asked; checked not blank).
    fn call_dial(&self, _number: &str) -> Result<(), String> {
        Err("this device doesn't place calls".into())
    }

    /// The SIMs (and calling apps) this phone places calls with, and the one
    /// it uses without asking (a PC asked; offered as `call.sims`).
    fn call_sims(&self) -> Result<nectarlink_protocol::messages::CallSims, String> {
        Ok(Default::default())
    }

    /// Like [`call_dial`](Self::call_dial), on the SIM `sim` (an id from
    /// [`call_sims`](Self::call_sims)).
    fn call_dial_on(&self, number: &str, _sim: &str) -> Result<(), String> {
        self.call_dial(number)
    }

    /// This phone's contacts matching `query` (or all with phone numbers
    /// when `None`), favorites first then alphabetical, skipping `offset`
    /// (a PC asked).
    fn contacts(
        &self,
        _query: Option<&str>,
        _offset: u32,
        _limit: u32,
    ) -> Result<Vec<crate::Contact>, String> {
        Err("this device has no contacts".into())
    }

    /// Play on phone: a paired PC offers to stream what `player` plays
    /// (`title`). The phone shows the offer; taking it starts mirroring with
    /// `watch` set to `player`. With `file`, the phone plays that video file
    /// itself instead, read with [`Node::watch_file_read`](crate::Node::watch_file_read).
    fn watch_offered(
        &self,
        _from: &nectarlink_protocol::DeviceId,
        _player: &str,
        _title: Option<&str>,
        _file: Option<&nectarlink_protocol::messages::WatchFile>,
    ) -> Result<(), String> {
        Err("this device doesn't show a PC's playback".into())
    }

    /// Run a command on one of this device's media players (a paired device
    /// asked); `position` is set for [`MediaAction::Seek`].
    fn media_command(
        &self,
        _player: &str,
        _action: MediaAction,
        _position: Option<u64>,
    ) -> Result<(), MediaError> {
        Err(MediaError::Unsupported)
    }

    /// Inject pointer, keyboard or presentation input from a paired phone
    /// (`docs/protocol/remote.md`).
    fn remote_input(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _input: crate::RemoteInput,
    ) -> Result<(), String> {
        Err("this device doesn't take remote input".into())
    }

    /// Change one of this phone's quick settings (`phone.toggle.set`,
    /// `docs/protocol/toggles.md`). `id` and `value` have been validated and
    /// checked against this phone's capabilities. `Err` holds a reason for logs.
    fn set_phone_toggle(&self, _id: &str, _value: &crate::PhoneToggleValue) -> Result<(), String> {
        Err("this device has no phone toggles".into())
    }

    /// Run a Deck tile's action on this PC (`deck.press`, `docs/protocol/deck.md`).
    /// `tile` has been validated against the current Deck layout and the
    /// required per-device toggles (`remote_input`, plus `commands` for
    /// `run_command` tiles). `Err` holds a reason for logs.
    fn deck_press(&self, _from: &nectarlink_protocol::DeviceId, _tile: &str) -> Result<(), String> {
        Err("this device has no deck actions".into())
    }

    /// Change this PC's master speaker volume (`0..=100`) and/or mute state
    /// (`pc.audio.set`, `docs/protocol/deck.md` §2.5). `volume` and `muted`
    /// have been validated and the per-device permission checked.
    fn set_pc_audio(
        &self,
        _from: &nectarlink_protocol::DeviceId,
        _volume: Option<u8>,
        _muted: Option<bool>,
    ) -> Result<(), String> {
        Err("this device has no PC audio controls".into())
    }

    /// List immediate children of `path` (`""` for the shared storage root) on
    /// this phone (`storage.list`, `docs/protocol/storage.md`).
    fn storage_list(&self, _path: &str) -> Result<Vec<crate::StorageEntry>, crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Open a file in this phone's shared storage for ranged reading (`storage.read`).
    fn storage_open_read(&self, _path: &str) -> Result<crate::StorageReadFile, crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Commit a fully staged upload (`staged`) to `path` in this phone's shared
    /// storage (`storage.write`).
    fn storage_write(
        &self,
        _path: &str,
        _staged: &std::path::Path,
        _modified: Option<i64>,
    ) -> Result<crate::StorageWriteDone, crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Create directory `path` in this phone's shared storage (`storage.mkdir`).
    fn storage_mkdir(&self, _path: &str) -> Result<(), crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Rename or move `from` to `to` in this phone's shared storage (`storage.rename`).
    fn storage_rename(&self, _from: &str, _to: &str) -> Result<(), crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Delete `path` in this phone's shared storage (`storage.delete`). Media
    /// items move to the phone's trash where supported; otherwise deletion
    /// requires `confirmed == true`.
    fn storage_delete(&self, _path: &str, _confirmed: bool) -> Result<(), crate::StorageError> {
        Err(crate::StorageError::Unsupported)
    }

    /// Where a phone's webcam video stream goes on this PC when it starts
    /// streaming (`docs/protocol/webcam.md`). `None` refuses the stream.
    fn webcam_sink(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
    ) -> Option<std::sync::Arc<dyn crate::WebcamSink>> {
        None
    }

    /// A PC asked this phone to start streaming its camera (or updated camera /
    /// resolution while already streaming): prompt the user for consent (or
    /// update the running stream) and stream with [`Node::webcam_open`](crate::Node::webcam_open).
    fn webcam_requested(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _options: &crate::WebcamStart,
    ) -> Result<(), String> {
        Err("this device doesn't stream a camera".into())
    }

    /// Where a phone's microphone goes on this PC when it starts streaming
    /// (`docs/protocol/mic.md`). `None` refuses the stream.
    fn mic_sink(&self, _peer: &nectarlink_protocol::DeviceId) -> Option<std::sync::Arc<dyn crate::MicSink>> {
        None
    }

    /// A paired PC asked for this phone's microphone: ask the user, then
    /// stream with [`Node::mic_open`](crate::Node::mic_open).
    fn mic_requested(&self, _peer: &nectarlink_protocol::DeviceId) -> Result<(), String> {
        Err("this device doesn't stream its microphone".into())
    }

    /// The PC stopped listening to this phone's microphone: stop recording.
    fn mic_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}

    /// The PC stopped using this phone's webcam: stop streaming.
    fn webcam_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}

    /// The PC's webcam decoder needs a fresh keyframe (`webcam.keyframe`).
    fn webcam_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}

    /// A paired PC requested a Continuity Camera capture (`camera.capture.request`).
    /// Return `Ok(())` if the phone launched or queued the capture UI, or `Err(reason)` if unavailable.
    fn camera_capture_requested(
        &self,
        _peer: &nectarlink_protocol::DeviceId,
        _request: &crate::CameraCaptureRequest,
    ) -> Result<(), String> {
        Err("camera capture not supported on this device".into())
    }

    /// The peer cancelled an in-flight Continuity Camera capture (`camera.capture.cancel`).
    fn camera_capture_cancelled(&self, _peer: &nectarlink_protocol::DeviceId, _request_id: &str) {}
}

/// A platform that does nothing; useful for tests and headless tools.
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopPlatform;

impl Platform for NoopPlatform {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn transport_overrides_parse_and_bad_values_keep_the_defaults() {
        let default = TransportTuning::default();
        assert_eq!(TransportTuning::parse(None, None), default);
        assert_eq!(default.congestion, Congestion::NewReno);
        assert_eq!(TransportTuning::parse(Some("cubic"), None).congestion, Congestion::Cubic);
        assert_eq!(TransportTuning::parse(Some(" BBR3 "), None).congestion, Congestion::Bbr3);
        assert_eq!(TransportTuning::parse(Some("bbr"), None).congestion, Congestion::Bbr3);
        assert_eq!(TransportTuning::parse(Some("newreno"), None).congestion, Congestion::NewReno);
        assert_eq!(TransportTuning::parse(Some("vegas"), None), default, "unknown controller");
        let small = TransportTuning::parse(None, Some("4"));
        assert_eq!((small.stream_window, small.connection_window), (4 << 20, 8 << 20));
        assert_eq!(TransportTuning::parse(None, Some("0")), default, "a zero window would stall");
        assert_eq!(TransportTuning::parse(None, Some("lots")), default);
    }
}