Skip to main content

hypersig_desktop/
handoff.rs

1//! What a second copy of the application hands the copy already running:
2//! its command line and its working directory, sent to the running copy's
3//! server with the token that copy wrote next to its lock.
4
5use std::ffi::{OsStr, OsString};
6use std::fs;
7use std::io::{self, Read as _, Write as _};
8use std::net::{Ipv4Addr, SocketAddr, TcpStream};
9use std::path::{Path, PathBuf};
10use std::thread;
11use std::time::Duration;
12
13use tokio::sync::broadcast;
14
15/// The path a second copy posts its launch to, which the guard answers
16/// before the application's router sees it.
17pub(crate) const PATH: &str = "/_hypersig_desktop/handoff";
18/// The header the handoff token travels in.
19pub(crate) const HEADER: &str = "hypersig-desktop-handoff";
20/// The most a launch may take, which a command line stays well under.
21pub(crate) const LIMIT: usize = 1 << 20;
22
23/// How long a second copy keeps trying while the running copy starts.
24const PATIENCE: Duration = Duration::from_secs(3);
25const RETRY: Duration = Duration::from_millis(100);
26
27/// Another start of the application, which handed its command line to this
28/// copy instead of running, from [`Launches::next`].
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub struct Launch {
31    dir: PathBuf,
32    args: Vec<OsString>,
33}
34
35impl Launch {
36    pub(crate) fn new(dir: PathBuf, args: Vec<OsString>) -> Self {
37        Self { dir, args }
38    }
39
40    /// The arguments after the program's name, as `std::env::args_os` gave them.
41    #[must_use]
42    pub fn args(&self) -> &[OsString] {
43        &self.args
44    }
45
46    /// The working directory of that start, which a relative path in
47    /// [`args`](Self::args) is relative to.
48    #[must_use]
49    pub fn current_dir(&self) -> &Path {
50        &self.dir
51    }
52
53    /// `dir`, then each argument, each as its length and its bytes.
54    pub(crate) fn encode(&self) -> Vec<u8> {
55        let mut bytes = Vec::new();
56        for part in
57            std::iter::once(self.dir.as_os_str()).chain(self.args.iter().map(OsString::as_os_str))
58        {
59            let raw = raw(part);
60            let len = u32::try_from(raw.len()).unwrap_or(u32::MAX);
61            bytes.extend_from_slice(&len.to_le_bytes());
62            bytes.extend_from_slice(&raw);
63        }
64        bytes
65    }
66
67    /// The launch [`encode`](Self::encode) wrote, or `None` when `bytes`
68    /// is not one.
69    pub(crate) fn decode(mut bytes: &[u8]) -> Option<Self> {
70        let mut parts = Vec::new();
71        while !bytes.is_empty() {
72            let (len, rest) = bytes.split_first_chunk::<4>()?;
73            let len = usize::try_from(u32::from_le_bytes(*len)).ok()?;
74            if rest.len() < len {
75                return None;
76            }
77            let (part, rest) = rest.split_at(len);
78            parts.push(cooked(part)?);
79            bytes = rest;
80        }
81        let mut parts = parts.into_iter();
82        let dir = PathBuf::from(parts.next()?);
83        Some(Self::new(dir, parts.collect()))
84    }
85}
86
87/// The launches handed to this copy after [`Os::launches`](crate::Os::launches)
88/// was called.
89#[derive(Debug)]
90pub struct Launches {
91    receiver: broadcast::Receiver<Launch>,
92}
93
94impl Launches {
95    pub(crate) fn new(receiver: broadcast::Receiver<Launch>) -> Self {
96        Self { receiver }
97    }
98
99    /// The next launch, or `None` once the application is closing.
100    pub async fn next(&mut self) -> Option<Launch> {
101        loop {
102            match self.receiver.recv().await {
103                Ok(launch) => return Some(launch),
104                Err(broadcast::error::RecvError::Lagged(missed)) => {
105                    tracing::warn!(
106                        missed,
107                        "launches arrived faster than they were taken, and the oldest were dropped"
108                    );
109                }
110                Err(broadcast::error::RecvError::Closed) => return None,
111            }
112        }
113    }
114}
115
116/// The channel every [`Launches`] of one run listens on.
117pub(crate) fn channel() -> broadcast::Sender<Launch> {
118    broadcast::channel(16).0
119}
120
121/// Writes `token` to `dir/handoff`, readable by this user alone on Unix.
122pub(crate) fn write_token(dir: &Path, token: &str) -> io::Result<()> {
123    let mut options = fs::File::options();
124    options.create(true).write(true).truncate(true);
125    #[cfg(unix)]
126    std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
127    options
128        .open(dir.join("handoff"))?
129        .write_all(token.as_bytes())
130}
131
132/// Hands this start's command line to the copy running from `dir`, and
133/// returns whether that copy took it.
134pub(crate) fn hand_over(dir: &Path) -> bool {
135    let launch = Launch::new(
136        std::env::current_dir().unwrap_or_default(),
137        std::env::args_os().skip(1).collect(),
138    );
139    let body = launch.encode();
140    let mut waited = Duration::ZERO;
141    loop {
142        match send(dir, &body) {
143            Ok(()) => return true,
144            Err(error) if waited >= PATIENCE => {
145                tracing::error!(%error, "the copy already running did not take this start's command line");
146                return false;
147            }
148            Err(_) => {
149                thread::sleep(RETRY);
150                waited += RETRY;
151            }
152        }
153    }
154}
155
156/// Posts `body` to the server whose port and token are recorded in `dir`.
157fn send(dir: &Path, body: &[u8]) -> io::Result<()> {
158    let port: u16 = fs::read_to_string(dir.join("port"))?
159        .trim()
160        .parse()
161        .map_err(io::Error::other)?;
162    let token = fs::read_to_string(dir.join("handoff"))?;
163    let address = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
164    let mut stream = TcpStream::connect_timeout(&address, Duration::from_secs(1))?;
165    stream.set_read_timeout(Some(Duration::from_secs(2)))?;
166    write!(
167        stream,
168        "POST {PATH} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n{HEADER}: {}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
169        token.trim(),
170        body.len()
171    )?;
172    stream.write_all(body)?;
173    let mut answer = [0; 12];
174    stream.read_exact(&mut answer)?;
175    if answer.ends_with(b" 204") {
176        Ok(())
177    } else {
178        Err(io::Error::other(format!(
179            "the copy already running answered {}",
180            String::from_utf8_lossy(&answer)
181        )))
182    }
183}
184
185/// The bytes of `text` as the system holds them.
186#[cfg(unix)]
187fn raw(text: &OsStr) -> Vec<u8> {
188    std::os::unix::ffi::OsStrExt::as_bytes(text).to_vec()
189}
190
191/// The bytes of `text` as the system holds them.
192#[cfg(windows)]
193fn raw(text: &OsStr) -> Vec<u8> {
194    std::os::windows::ffi::OsStrExt::encode_wide(text)
195        .flat_map(u16::to_le_bytes)
196        .collect()
197}
198
199/// The text `raw` wrote `bytes` from.
200#[cfg(unix)]
201#[expect(
202    clippy::unnecessary_wraps,
203    reason = "on Windows an odd length is not text"
204)]
205fn cooked(bytes: &[u8]) -> Option<OsString> {
206    Some(std::os::unix::ffi::OsStringExt::from_vec(bytes.to_vec()))
207}
208
209/// The text `raw` wrote `bytes` from.
210#[cfg(windows)]
211fn cooked(bytes: &[u8]) -> Option<OsString> {
212    let (pairs, odd) = bytes.as_chunks::<2>();
213    if !odd.is_empty() {
214        return None;
215    }
216    let wide: Vec<u16> = pairs.iter().map(|&pair| u16::from_le_bytes(pair)).collect();
217    Some(std::os::windows::ffi::OsStringExt::from_wide(&wide))
218}
219
220#[cfg(test)]
221mod tests {
222    use std::ffi::OsString;
223    use std::path::PathBuf;
224
225    use super::Launch;
226
227    #[test]
228    fn a_launch_comes_back_as_it_was_sent() {
229        let launch = Launch::new(
230            PathBuf::from("/home/me/notes"),
231            vec![
232                OsString::from("today.md"),
233                OsString::new(),
234                OsString::from("日本語.md"),
235            ],
236        );
237        assert_eq!(Launch::decode(&launch.encode()), Some(launch));
238    }
239
240    #[test]
241    fn bytes_that_are_not_a_launch_are_refused() {
242        assert_eq!(Launch::decode(&[]), None);
243        assert_eq!(Launch::decode(&[9, 0, 0, 0, b'a']), None);
244        assert_eq!(Launch::decode(&[1, 0]), None);
245    }
246}