Skip to main content

tilo_dialogs/
shell.rs

1//! Choosers the session shell draws itself, for sessions whose apps reach no
2//! desktop portal (a provider's headless guest).
3//!
4//! The launcher hands every app a connection to the shell's chooser service
5//! ([`FD_ENV`]) and names the app and its workspace on it before the sandbox
6//! starts, so the shell knows who asks without trusting the app. Requests and
7//! replies are newline-delimited JSON ([`Request`], [`Reply`]). The shell
8//! shows its own file chooser. Legacy path results remain limited to existing
9//! grants; owner-confirmed contents selections expose only bounded bytes on this
10//! connection, never a directory grant or a replayable host path. When nobody is at the
11//! computer it answers [`Reply::Nobody`] and the app falls back to the chooser it
12//! brought ([`crate::unattended_picker`] or the desktop's own), so a session with no
13//! portal behind it still answers a Save.
14//!
15//! Links go the same way ([`ShellLink::opener`]): the shell opens a link in
16//! the app that claims its scheme, as its own search does, and answers
17//! [`Reply::Unclaimed`] for one no app it knows opens, which the app then
18//! hands to its desktop's opener.
19
20#![allow(
21    clippy::arithmetic_side_effects,
22    clippy::indexing_slicing,
23    reason = "the descriptor transport reads and writes the system's control buffers by position"
24)]
25#![allow(
26    clippy::borrow_as_ptr,
27    reason = "the descriptor transport hands the system's calls the message it filled"
28)]
29
30use std::collections::HashMap;
31#[cfg(unix)]
32use std::collections::VecDeque;
33use std::fs::File;
34#[cfg(unix)]
35use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd, RawFd};
36use std::path::{Path, PathBuf};
37#[cfg(unix)]
38use std::sync::OnceLock;
39use std::sync::atomic::{AtomicU64, Ordering};
40use std::sync::{Arc, Mutex};
41use tilo_socket::Stream;
42
43use serde::{Deserialize, Serialize};
44
45use crate::portal::{
46    FileFilter, LaunchChannel, LaunchOutcome, LaunchRequest, MultiChannel, MultiOutcome,
47    OpenFileChannel, OpenFileOutcome, OpenedFile, PickKind, PickRequest, PortalChannel,
48    PortalOutcome, SaveChannel, SaveOutcome,
49};
50use crate::{FilePicker, answered};
51
52pub const SERVICE: &str = "chooser";
53pub const FD_ENV: &str = "TILO_SVC_CHOOSER_FD";
54pub const PROTOCOL: u16 = 1;
55/// The largest frame either end writes: a folder of many files answers with one grant each, so
56/// a choice of ten thousand small files fits on one line.
57pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
58
59const NOBODY_TO_CHOOSE_APP: &str = "nobody is at this computer to choose an app";
60const OUT_OF_TURN: &str = "the session's shell answered out of turn";
61// What an app may show the person when the shell's chooser itself is out
62// of reach: what happened, and what to do (`PortalOutcome::Failed` carries a
63// sentence for the person, never a transport error).
64const CLOSED: &str = "The file chooser closed before you chose. Try again.";
65const UNREACHABLE: &str = "The file chooser didn't open. Try again.";
66const CHOOSER_OUT_OF_TURN: &str = "The file chooser gave an answer that doesn't fit. Try again.";
67const LINK_ANSWER: std::time::Duration = std::time::Duration::from_secs(30);
68/// How long a finished save waits for the chooser to rename it over the file.
69const SAVE_COMMIT_WAIT: std::time::Duration = std::time::Duration::from_secs(20);
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
72pub struct Handshake {
73    pub protocol: u16,
74    pub app_id: String,
75    pub workspace_id: String,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "snake_case")]
80pub enum PickMode {
81    Open,
82    Directory,
83    /// A destination directory; older services reject this unknown mode rather
84    /// than silently answering a read-only request.
85    WritableDirectory,
86    Save,
87}
88
89#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
90pub struct Filter {
91    pub name: String,
92    #[serde(default)]
93    pub globs: Vec<String>,
94    #[serde(default)]
95    pub mimetypes: Vec<String>,
96}
97
98/// Retired: the token a contents answer named. Kept so a request written before the chooser
99/// handed descriptors still reads; a choice now answers a descriptor and a reference.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct FilePortalGrant {
102    pub request: u64,
103    pub token: String,
104    pub name: String,
105    pub size: u64,
106}
107
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109#[serde(tag = "type", rename_all = "snake_case")]
110pub enum Request {
111    Pick {
112        id: u64,
113        mode: PickMode,
114        #[serde(default)]
115        multiple: bool,
116        title: String,
117        #[serde(default)]
118        accept_label: String,
119        #[serde(default)]
120        suggested_name: Option<String>,
121        #[serde(default)]
122        filters: Vec<Filter>,
123    },
124    /// Turn a reference the chooser answered back into an open file: a window restored on the
125    /// file it showed, or a file inside a folder the person chose. `write` asks for a Save's
126    /// file beside it, opened for writing.
127    Reopen {
128        id: u64,
129        reference: PathBuf,
130        #[serde(default)]
131        write: bool,
132    },
133    /// A Save's bytes are written through the descriptor: rename the file beside the chosen one
134    /// over it.
135    Saved {
136        id: u64,
137        reference: PathBuf,
138    },
139    /// Retired: a choice of bytes, answered as no request this host serves. Read as what it
140    /// means now — the app gets no files — never written.
141    PickContents {
142        id: u64,
143        multiple: bool,
144        #[serde(default)]
145        directory: bool,
146        title: String,
147        accept_label: String,
148        filters: Vec<Filter>,
149    },
150    /// Retired: a read of a contents grant. See [`Self::PickContents`].
151    ReadContents {
152        id: u64,
153        grant: FilePortalGrant,
154        offset: u64,
155        max_bytes: u32,
156    },
157    /// Retired: the release of a contents grant. See [`Self::PickContents`].
158    ReleaseContents {
159        id: u64,
160        grant: FilePortalGrant,
161    },
162    Open {
163        id: u64,
164        path: PathBuf,
165    },
166    OpenUri {
167        id: u64,
168        uri: String,
169    },
170    ChooseApp {
171        id: u64,
172        purpose: String,
173    },
174    AwaitIdentity {
175        id: u64,
176    },
177    ChooseIdentity {
178        id: u64,
179    },
180}
181
182/// One chosen file or folder: what reopens it later, and what it is called.
183#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
184pub struct HandedDocument {
185    /// The documents-store path of the chosen item, which the chooser turns back into a
186    /// descriptor ([`Request::Reopen`]); never a host path the app could use itself.
187    pub reference: PathBuf,
188    pub name: String,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct ChosenApp {
193    pub id: String,
194    pub name: String,
195    #[serde(default)]
196    pub window_ids: Vec<String>,
197}
198
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200#[serde(tag = "type", rename_all = "snake_case")]
201pub enum Reply {
202    /// The chosen files or folders, each with the descriptor that opens it: the descriptors
203    /// travel with this frame as `SCM_RIGHTS`, one per document, in order.
204    Handed {
205        id: u64,
206        documents: Vec<HandedDocument>,
207    },
208    /// A Save's bytes are in the file beside the chosen one, which is now renamed over it.
209    Saved {
210        id: u64,
211    },
212    /// Retired: an answer from before the chooser handed descriptors. Read as a choice of
213    /// nothing; never written.
214    ContentsGranted {
215        id: u64,
216        grants: Vec<FilePortalGrant>,
217    },
218    /// Retired: bytes of a contents grant. Read as a choice of nothing; never written.
219    ContentsChunk {
220        id: u64,
221        bytes: Vec<u8>,
222        eof: bool,
223    },
224    /// Retired: the release of a contents grant. Read as a choice of nothing; never written.
225    ContentsReleased {
226        id: u64,
227    },
228    /// Retired: an answer from before the chooser handed descriptors. Read as a choice of
229    /// nothing; never written.
230    Picked {
231        id: u64,
232        paths: Vec<PathBuf>,
233    },
234    Cancelled {
235        id: u64,
236    },
237    Nobody {
238        id: u64,
239    },
240    Opened {
241        id: u64,
242    },
243    Unclaimed {
244        id: u64,
245    },
246    Failed {
247        id: u64,
248        reason: String,
249    },
250    AppChosen {
251        id: u64,
252        app: ChosenApp,
253    },
254    IdentitySelected {
255        id: u64,
256    },
257}
258
259impl Reply {
260    #[must_use]
261    pub fn id(&self) -> u64 {
262        match self {
263            Reply::ContentsGranted { id, .. }
264            | Reply::ContentsChunk { id, .. }
265            | Reply::ContentsReleased { id }
266            | Reply::Handed { id, .. }
267            | Reply::Saved { id }
268            | Reply::Picked { id, .. }
269            | Reply::Cancelled { id }
270            | Reply::Nobody { id }
271            | Reply::Opened { id }
272            | Reply::Unclaimed { id }
273            | Reply::IdentitySelected { id }
274            | Reply::AppChosen { id, .. }
275            | Reply::Failed { id, .. } => *id,
276        }
277    }
278}
279
280impl Filter {
281    fn from_portal(filter: &FileFilter) -> Self {
282        Self {
283            name: filter.name.clone(),
284            globs: filter.globs.clone(),
285            mimetypes: filter.mimetypes.clone(),
286        }
287    }
288}
289
290/// The most descriptors one message carries: the kernel's own bound leaves room for fewer, so a
291/// choice of ten thousand files arrives in several messages.
292#[cfg(unix)]
293const MAX_FDS_PER_MESSAGE: usize = 64;
294
295/// A descriptor handed with a reply: an open file or folder, whatever the app's sandbox did not
296/// let it reach by path. It is the platform's one descriptor type ([`tilo_socket::Descriptor`]):
297/// a file descriptor on Unix and a handle on Windows, and either becomes the file it holds open.
298pub(crate) use tilo_socket::Descriptor;
299
300type Answer = Box<dyn FnOnce(Reply, Vec<Descriptor>) + Send>;
301
302struct Connection {
303    writer: Mutex<Stream>,
304    pending: Mutex<Option<HashMap<u64, Answer>>>,
305    next_id: AtomicU64,
306}
307
308impl Connection {
309    /// Send `request` (its id is filled in) and call `answer` with the reply and the descriptors
310    /// that came with it, on the connection's reader thread, or with a failure if it cannot be
311    /// sent.
312    fn ask(&self, build: impl FnOnce(u64) -> Request, answer: Answer) {
313        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
314        let refused = match self.pending.lock() {
315            Ok(mut pending) => match pending.as_mut() {
316                Some(pending) => {
317                    pending.insert(id, answer);
318                    None
319                }
320                None => Some(answer),
321            },
322            Err(_) => Some(answer),
323        };
324        if let Some(answer) = refused {
325            answer(
326                Reply::Failed {
327                    id,
328                    reason: CLOSED.to_owned(),
329                },
330                Vec::new(),
331            );
332            return;
333        }
334        let sent = serde_json::to_vec(&build(id))
335            .map_err(std::io::Error::other)
336            .and_then(|mut frame| {
337                frame.push(b'\n');
338                let mut writer = self
339                    .writer
340                    .lock()
341                    .map_err(|_| std::io::Error::other("chooser writer poisoned"))?;
342                let mut written = 0;
343                while written < frame.len() {
344                    written += std::io::Write::write(&mut *writer, &frame[written..])?;
345                }
346                std::io::Write::flush(&mut *writer)
347            });
348        if let Err(error) = sent
349            && let Some(answer) = self.take(id)
350        {
351            tracing::warn!(%error, "the session's file chooser is out of reach");
352            answer(
353                Reply::Failed {
354                    id,
355                    reason: UNREACHABLE.to_owned(),
356                },
357                Vec::new(),
358            );
359        }
360    }
361
362    fn take(&self, id: u64) -> Option<Answer> {
363        self.pending
364            .lock()
365            .ok()?
366            .as_mut()
367            .and_then(|pending| pending.remove(&id))
368    }
369
370    /// The shell hung up: answer everything still waiting, and refuse what comes.
371    fn close(&self) {
372        let waiting = self
373            .pending
374            .lock()
375            .ok()
376            .and_then(|mut pending| pending.take())
377            .unwrap_or_default();
378        for (id, answer) in waiting {
379            answer(
380                Reply::Failed {
381                    id,
382                    reason: CLOSED.to_owned(),
383                },
384                Vec::new(),
385            );
386        }
387    }
388}
389
390fn read_replies(connection: &Connection, stream: Stream) {
391    let mut reader = FrameReader::new(stream);
392    while let Ok(Some((reply, fds))) = reader.reply() {
393        if let Some(answer) = connection.take(reply.id()) {
394            answer(reply, fds);
395        }
396    }
397    connection.close();
398}
399
400/// Newline-delimited frames, with the descriptors a reply carried: a stream socket delivers a
401/// frame's bytes and its descriptors together, so a reader keeps the descriptors in the order
402/// they arrived and hands the next one to each chosen document.
403pub(crate) struct FrameReader {
404    stream: Stream,
405    buffer: Vec<u8>,
406    #[cfg(unix)]
407    fds: VecDeque<Descriptor>,
408}
409
410impl FrameReader {
411    pub(crate) fn new(stream: Stream) -> Self {
412        Self {
413            stream,
414            buffer: Vec::new(),
415            #[cfg(unix)]
416            fds: VecDeque::new(),
417        }
418    }
419
420    /// The next frame's line (without its newline), or `None` when the far end hung up.
421    pub(crate) fn line(&mut self) -> std::io::Result<Option<Vec<u8>>> {
422        loop {
423            if let Some(at) = self.buffer.iter().position(|byte| *byte == b'\n') {
424                let line = self.buffer[..at].to_vec();
425                self.buffer.drain(..=at);
426                return Ok(Some(line));
427            }
428            if self.buffer.len() > MAX_FRAME_BYTES {
429                return Err(std::io::Error::new(
430                    std::io::ErrorKind::InvalidData,
431                    "a chooser frame is larger than the wire allows",
432                ));
433            }
434            if !self.fill()? {
435                return Ok(None);
436            }
437        }
438    }
439
440    /// The next reply, with the descriptors its documents carried.
441    pub(crate) fn reply(&mut self) -> std::io::Result<Option<(Reply, Vec<Descriptor>)>> {
442        let Some(line) = self.line()? else {
443            return Ok(None);
444        };
445        let reply: Reply = match serde_json::from_slice(line.trim_ascii_end()) {
446            Ok(reply) => reply,
447            Err(error) => {
448                return Err(std::io::Error::new(
449                    std::io::ErrorKind::InvalidData,
450                    format!("an unreadable chooser reply: {error}"),
451                ));
452            }
453        };
454        let wanted = match &reply {
455            Reply::Handed { documents, .. } => documents.len(),
456            _ => 0,
457        };
458        let fds = self.take_fds(wanted);
459        Ok(Some((reply, fds)))
460    }
461
462    #[cfg(unix)]
463    fn take_fds(&mut self, wanted: usize) -> Vec<Descriptor> {
464        (0..wanted).filter_map(|_| self.fds.pop_front()).collect()
465    }
466
467    #[cfg(not(unix))]
468    #[allow(
469        clippy::unused_self,
470        reason = "a pipe carries no handles beside a line, and the call is the same"
471    )]
472    fn take_fds(&self, _wanted: usize) -> Vec<Descriptor> {
473        Vec::new()
474    }
475
476    #[cfg(not(unix))]
477    fn fill(&mut self) -> std::io::Result<bool> {
478        let mut bytes = [0_u8; 8192];
479        let read = std::io::Read::read(&mut self.stream, &mut bytes)?;
480        if read == 0 {
481            return Ok(false);
482        }
483        self.buffer.extend_from_slice(&bytes[..read]);
484        Ok(true)
485    }
486
487    #[cfg(unix)]
488    fn fill(&mut self) -> std::io::Result<bool> {
489        let mut bytes = [0_u8; 8192];
490        // Room for the descriptors one message may carry, aligned for the control message.
491        let space = cmsg_space(MAX_FDS_PER_MESSAGE * std::mem::size_of::<RawFd>());
492        let mut control = vec![0_u8; space];
493        let mut iov = libc::iovec {
494            iov_base: bytes.as_mut_ptr().cast(),
495            iov_len: bytes.len(),
496        };
497        // SAFETY: an empty message header filled in below, with an iovec and control buffer
498        // sized for what the system writes into them.
499        let mut message: libc::msghdr = unsafe { std::mem::zeroed() };
500        message.msg_iov = &raw mut iov;
501        message.msg_iovlen = 1;
502        message.msg_control = control.as_mut_ptr().cast();
503        message.msg_controllen = control_len(&control)?;
504        // SAFETY: `recvmsg` reads the descriptor and writes only the buffers above.
505        let read = unsafe { libc::recvmsg(self.stream.as_raw_fd(), &mut message, 0) };
506        if read < 0 {
507            return Err(std::io::Error::last_os_error());
508        }
509        if read == 0 {
510            return Ok(false);
511        }
512        self.buffer
513            .extend_from_slice(&bytes[..usize::try_from(read).unwrap_or(0)]);
514        if message.msg_flags & libc::MSG_CTRUNC != 0 {
515            tracing::warn!("the chooser's descriptors were truncated");
516        }
517        // SAFETY: the header is the one `recvmsg` filled, so its control messages are valid.
518        let mut header = unsafe { libc::CMSG_FIRSTHDR(&message) };
519        while !header.is_null() {
520            // SAFETY: `header` points at a control message the system wrote.
521            let control = unsafe { &*header };
522            if control.cmsg_level == libc::SOL_SOCKET && control.cmsg_type == libc::SCM_RIGHTS {
523                let data = unsafe { libc::CMSG_DATA(header) }.cast::<RawFd>();
524                let count = control.cmsg_len as usize - unsafe { libc::CMSG_LEN(0) } as usize;
525                for at in 0..count / std::mem::size_of::<RawFd>() {
526                    // SAFETY: the control message holds `count` bytes of descriptors.
527                    let fd = unsafe { *data.add(at) };
528                    // SAFETY: the descriptor arrived with this message and nothing else owns it.
529                    self.fds
530                        .push_back(Descriptor::from(unsafe { OwnedFd::from_raw_fd(fd) }));
531                }
532            }
533            // SAFETY: `header` is one of the message's control messages.
534            header = unsafe { libc::CMSG_NXTHDR(&message, header) };
535        }
536        Ok(true)
537    }
538}
539
540#[cfg(unix)]
541fn cmsg_space(bytes: usize) -> usize {
542    // SAFETY: `CMSG_SPACE` is a size computation.
543    unsafe { libc::CMSG_SPACE(u32::try_from(bytes).unwrap_or(u32::MAX)) as usize }
544}
545
546/// `control`'s length as `msghdr::msg_controllen`: `usize` on glibc, `socklen_t` on musl.
547#[cfg(unix)]
548fn control_len<T: TryFrom<usize>>(control: &[u8]) -> std::io::Result<T> {
549    T::try_from(control.len()).map_err(|_| std::io::Error::other("control buffer too large"))
550}
551
552/// Write `line` as one frame, carrying `fds` as `SCM_RIGHTS`: the descriptors travel in the same
553/// message as the first bytes of the line, so the reader sees them in the order the line names
554/// the documents they open.
555#[cfg(unix)]
556pub(crate) fn send_frame(stream: &Stream, line: &[u8], fds: &[Descriptor]) -> std::io::Result<()> {
557    let pieces = fds.len().div_ceil(MAX_FDS_PER_MESSAGE).max(1);
558    let size = line.len().div_ceil(pieces).max(1);
559    let mut at = 0;
560    for (index, piece) in line.chunks(size).enumerate() {
561        let from = index.saturating_mul(MAX_FDS_PER_MESSAGE).min(fds.len());
562        let to = from.saturating_add(MAX_FDS_PER_MESSAGE).min(fds.len());
563        write_piece(stream, piece, &fds[from..to])?;
564        at += piece.len();
565    }
566    if at < line.len() {
567        write_piece(stream, &line[at..], &[])?;
568    }
569    Ok(())
570}
571
572/// Write `line` as one frame. A pipe carries no handles beside a line, so a frame that would hand
573/// a chosen file over is refused rather than written without it.
574#[cfg(windows)]
575#[allow(
576    dead_code,
577    reason = "the server that writes frames is built where a session serves a socket"
578)]
579pub(crate) fn send_frame(stream: &Stream, line: &[u8], fds: &[Descriptor]) -> std::io::Result<()> {
580    if !fds.is_empty() {
581        return Err(std::io::Error::new(
582            std::io::ErrorKind::Unsupported,
583            "this connection cannot carry a chosen file",
584        ));
585    }
586    let mut writer = stream;
587    std::io::Write::write_all(&mut writer, line)?;
588    std::io::Write::flush(&mut writer)
589}
590
591#[cfg(unix)]
592fn write_piece(stream: &Stream, bytes: &[u8], fds: &[Descriptor]) -> std::io::Result<()> {
593    let mut iov = libc::iovec {
594        iov_base: bytes.as_ptr().cast_mut().cast(),
595        iov_len: bytes.len(),
596    };
597    // SAFETY: an empty message header filled in below.
598    let mut message: libc::msghdr = unsafe { std::mem::zeroed() };
599    message.msg_iov = &raw mut iov;
600    message.msg_iovlen = 1;
601    let mut control = if fds.is_empty() {
602        Vec::new()
603    } else {
604        vec![0_u8; cmsg_space(fds.len() * std::mem::size_of::<RawFd>())]
605    };
606    if !fds.is_empty() {
607        message.msg_control = control.as_mut_ptr().cast();
608        message.msg_controllen = control_len(&control)?;
609        // SAFETY: the header is empty and the control buffer has room for one message.
610        let header = unsafe { libc::CMSG_FIRSTHDR(&message) };
611        if header.is_null() {
612            return Err(std::io::Error::other(
613                "no room for the chooser's descriptors",
614            ));
615        }
616        // SAFETY: `header` points into `control`, sized by `cmsg_space`.
617        unsafe {
618            (*header).cmsg_level = libc::SOL_SOCKET;
619            (*header).cmsg_type = libc::SCM_RIGHTS;
620            // `cmsg_len` is `usize` on glibc and `socklen_t` on musl.
621            (*header).cmsg_len = libc::CMSG_LEN(
622                u32::try_from(fds.len() * std::mem::size_of::<RawFd>()).unwrap_or(u32::MAX),
623            ) as _;
624            let data = libc::CMSG_DATA(header).cast::<RawFd>();
625            for (at, fd) in fds.iter().enumerate() {
626                *data.add(at) = fd.as_raw_fd();
627            }
628        }
629    }
630    // SAFETY: `sendmsg` reads the descriptor and the buffers it names.
631    let sent = unsafe { libc::sendmsg(stream.as_raw_fd(), &message, libc::MSG_NOSIGNAL) };
632    if sent < 0 {
633        return Err(std::io::Error::last_os_error());
634    }
635    let sent = usize::try_from(sent).unwrap_or(0);
636    if sent < bytes.len() {
637        let mut rest = &bytes[sent..];
638        while !rest.is_empty() {
639            match std::io::Write::write(&mut &*stream, rest) {
640                Ok(0) => {
641                    return Err(std::io::Error::from(std::io::ErrorKind::WriteZero));
642                }
643                Ok(written) => rest = &rest[written..],
644                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
645                Err(error) => return Err(error),
646            }
647        }
648    }
649    Ok(())
650}
651
652#[derive(Clone)]
653pub struct ShellLink(Arc<LinkInner>);
654
655struct LinkInner {
656    connection: Arc<Connection>,
657}
658
659impl Drop for LinkInner {
660    fn drop(&mut self) {
661        if let Ok(writer) = self.connection.writer.lock() {
662            let _ = writer.shutdown(std::net::Shutdown::Both);
663        }
664        self.connection.close();
665    }
666}
667
668impl ShellLink {
669    pub fn connect(stream: Stream) -> std::io::Result<Self> {
670        let reader = stream.try_clone()?;
671        let connection = Arc::new(Connection {
672            writer: Mutex::new(stream),
673            pending: Mutex::new(Some(HashMap::new())),
674            next_id: AtomicU64::new(1),
675        });
676        let reading = Arc::clone(&connection);
677        std::thread::Builder::new()
678            .name("tilo-shell-chooser".into())
679            .spawn(move || read_replies(&reading, reader))?;
680        Ok(Self(Arc::new(LinkInner { connection })))
681    }
682
683    #[must_use]
684    pub fn picker(&self, elsewhere: Arc<dyn FilePicker>) -> Arc<dyn FilePicker> {
685        Arc::new(ShellChooser {
686            link: self.clone(),
687            elsewhere,
688        })
689    }
690
691    #[must_use]
692    pub fn opener(&self, elsewhere: Arc<dyn crate::UriOpener>) -> Arc<dyn crate::UriOpener> {
693        Arc::new(ShellOpener {
694            link: self.clone(),
695            elsewhere,
696        })
697    }
698
699    pub fn choose_app(
700        &self,
701        purpose: &str,
702        chosen: impl FnOnce(Result<Option<ChosenApp>, String>) + Send + 'static,
703    ) {
704        let purpose = purpose.to_owned();
705        self.connection().ask(
706            move |id| Request::ChooseApp { id, purpose },
707            Box::new(move |reply, _fds| {
708                chosen(match reply {
709                    Reply::AppChosen { app, .. } => Ok(Some(app)),
710                    Reply::Cancelled { .. } => Ok(None),
711                    Reply::Nobody { .. } => Err(NOBODY_TO_CHOOSE_APP.to_owned()),
712                    Reply::Failed { reason, .. } => Err(reason),
713                    _ => Err(OUT_OF_TURN.to_owned()),
714                });
715            }),
716        );
717    }
718
719    /// Ask the chooser to open `reference` again: the file a window showed, or one inside a
720    /// folder the person chose. `write` asks for the file beside a Save, opened for writing.
721    pub fn reopen(
722        &self,
723        reference: &Path,
724        write: bool,
725        answer: impl FnOnce(Result<(File, PathBuf, String), String>) + Send + 'static,
726    ) {
727        let asked = reference.to_path_buf();
728        self.connection().ask(
729            move |id| Request::Reopen {
730                id,
731                reference: asked,
732                write,
733            },
734            Box::new(move |reply, fds| {
735                answer(match reply {
736                    Reply::Handed { documents, .. } => {
737                        match (documents.into_iter().next(), fds.into_iter().next()) {
738                            (Some(document), Some(fd)) => {
739                                Ok((fd.into_file(), document.reference, document.name))
740                            }
741                            _ => Err(CHOOSER_OUT_OF_TURN.to_owned()),
742                        }
743                    }
744                    Reply::Cancelled { .. } => Err(CLOSED.to_owned()),
745                    Reply::Failed { reason, .. } => Err(reason),
746                    _ => Err(CHOOSER_OUT_OF_TURN.to_owned()),
747                });
748            }),
749        );
750    }
751
752    /// The bytes of a Save are written: rename the file beside it over it, and
753    /// answer whether the file was replaced.
754    pub fn saved(
755        &self,
756        reference: &Path,
757        answer: impl FnOnce(Result<(), String>) + Send + 'static,
758    ) {
759        let asked = reference.to_path_buf();
760        self.connection().ask(
761            move |id| Request::Saved {
762                id,
763                reference: asked,
764            },
765            Box::new(move |reply, _fds| {
766                answer(match reply {
767                    Reply::Saved { .. } => Ok(()),
768                    Reply::Failed { reason, .. } => Err(reason),
769                    _ => Err(CHOOSER_OUT_OF_TURN.to_owned()),
770                });
771            }),
772        );
773    }
774
775    fn connection(&self) -> &Connection {
776        &self.0.connection
777    }
778
779    /// The chooser the launcher handed this process, when it handed one. On Windows a process is
780    /// handed its connections over its process link instead, and an instance takes its chooser
781    /// with them ([`picker`]): no process inherits one.
782    #[cfg(windows)]
783    pub fn inherited() -> Option<Self> {
784        None
785    }
786
787    /// The chooser the launcher handed this process (`TILO_SVC_SHELL_FD`), when it handed one.
788    #[cfg(unix)]
789    pub fn inherited() -> Option<Self> {
790        static INHERITED: OnceLock<Option<ShellLink>> = OnceLock::new();
791        INHERITED
792            .get_or_init(|| {
793                let fd = std::env::var(FD_ENV).ok()?.parse::<RawFd>().ok()?;
794                let stream = adopt_socket(fd)?;
795                Self::connect(stream)
796                    .inspect_err(
797                        |error| tracing::warn!(%error, "the session's file chooser is unusable"),
798                    )
799                    .ok()
800            })
801            .clone()
802    }
803}
804
805/// The shell's chooser over `stream`, asking `elsewhere` what the session answers `Nobody` for:
806/// a session with no portal behind it has nobody to choose a path for an app, and the save
807/// directory or the desktop's own chooser still answers a Save.
808pub fn picker(
809    stream: Stream,
810    elsewhere: Arc<dyn FilePicker>,
811) -> std::io::Result<Arc<dyn FilePicker>> {
812    Ok(ShellLink::connect(stream)?.picker(elsewhere))
813}
814
815pub fn inherited_picker(elsewhere: Arc<dyn FilePicker>) -> Option<Arc<dyn FilePicker>> {
816    ShellLink::inherited().map(|link| link.picker(elsewhere))
817}
818
819pub fn inherited_opener(elsewhere: Arc<dyn crate::UriOpener>) -> Option<Arc<dyn crate::UriOpener>> {
820    ShellLink::inherited().map(|link| link.opener(elsewhere))
821}
822
823#[cfg(unix)]
824fn adopt_socket(fd: RawFd) -> Option<Stream> {
825    if fd <= 2 {
826        return None;
827    }
828    let mut stat = std::mem::MaybeUninit::<libc::stat>::zeroed();
829    // SAFETY: `fstat` only writes the buffer it is given, sized for it.
830    if unsafe { libc::fstat(fd, stat.as_mut_ptr()) } != 0 {
831        return None;
832    }
833    // SAFETY: `fstat` succeeded, so it filled the buffer.
834    let stat = unsafe { stat.assume_init() };
835    if stat.st_mode & libc::S_IFMT != libc::S_IFSOCK {
836        return None;
837    }
838    // The launcher hands it over inheritable; the app's own children must
839    // not speak for it.
840    // SAFETY: setting a descriptor flag on a descriptor we are adopting.
841    unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) };
842    // SAFETY: the descriptor is an open socket nothing else in this process
843    // owns: the launcher placed it for this adoption, which runs once.
844    Some(unsafe { Stream::from_raw_fd(fd) })
845}
846
847struct ShellChooser {
848    link: ShellLink,
849    /// What answers a request the session says `Nobody` for: a session with no portal behind it
850    /// has nobody to choose a path, and the unattended picker or the desktop's chooser still
851    /// answers a Save.
852    elsewhere: Arc<dyn FilePicker>,
853}
854
855struct ShellOpener {
856    link: ShellLink,
857    elsewhere: Arc<dyn crate::UriOpener>,
858}
859
860impl crate::UriOpener for ShellOpener {
861    fn open(&self, uri: &str) -> std::io::Result<()> {
862        if let Err(error) = url::Url::parse(uri) {
863            return Err(std::io::Error::new(
864                std::io::ErrorKind::InvalidInput,
865                format!("bad URI: {error}"),
866            ));
867        }
868        let (tx, rx) = std::sync::mpsc::channel();
869        let asked = uri.to_owned();
870        self.link.connection().ask(
871            move |id| Request::OpenUri { id, uri: asked },
872            Box::new(move |reply, _fds| {
873                let _ = tx.send(reply);
874            }),
875        );
876        match rx.recv_timeout(LINK_ANSWER) {
877            Ok(Reply::Opened { .. }) => Ok(()),
878            Ok(Reply::Unclaimed { .. }) => self.elsewhere.open(uri),
879            Ok(Reply::Failed { reason, .. }) if reason == CLOSED || reason == UNREACHABLE => {
880                self.elsewhere.open(uri)
881            }
882            Ok(Reply::Failed { reason, .. }) => Err(std::io::Error::other(reason)),
883            Ok(_) => Err(std::io::Error::other(OUT_OF_TURN)),
884            Err(_) => Err(std::io::Error::new(
885                std::io::ErrorKind::TimedOut,
886                "the session's shell did not open the link",
887            )),
888        }
889    }
890}
891
892fn channel<T: Send + 'static>() -> (impl FnOnce(T) + Send, std::sync::mpsc::Receiver<T>) {
893    let (tx, rx) = std::sync::mpsc::channel();
894    let wake = tilo_rt::wake::WakeHandle::new();
895    let deliver = move |outcome: T| {
896        if tx.send(outcome).is_ok() {
897            wake.wake();
898        }
899    };
900    (deliver, rx)
901}
902
903#[cfg(test)]
904mod directory_contract_tests {
905    use super::*;
906
907    #[test]
908    fn writable_directory_survives_wire_encoding_without_upgrading_read_picks() {
909        for (request, expected) in [
910            (
911                PickRequest::directory("Read folder", "Choose"),
912                PickMode::Directory,
913            ),
914            (
915                PickRequest::writable_directory("Import into folder", "Import here"),
916                PickMode::WritableDirectory,
917            ),
918        ] {
919            let frame = serde_json::to_vec(&pick_request(&request)(7)).unwrap();
920            let Request::Pick {
921                mode,
922                multiple,
923                suggested_name,
924                ..
925            } = serde_json::from_slice::<Request>(&frame).unwrap()
926            else {
927                panic!("not a pick")
928            };
929            assert_eq!(mode, expected);
930            assert!(!multiple);
931            assert_eq!(suggested_name, None);
932        }
933    }
934}
935
936fn pick_request(request: &PickRequest) -> impl FnOnce(u64) -> Request + use<> {
937    let (mode, multiple, suggested_name) = match &request.kind {
938        PickKind::Open { multiple } => (PickMode::Open, *multiple, None),
939        PickKind::Directory if request.is_writable_directory() => {
940            (PickMode::WritableDirectory, false, None)
941        }
942        PickKind::Directory => (PickMode::Directory, false, None),
943        PickKind::Save { suggested_name } => (PickMode::Save, false, Some(suggested_name.clone())),
944    };
945    let title = request.title.clone();
946    let accept_label = request.accept_label.clone();
947    let filters = request.filters.iter().map(Filter::from_portal).collect();
948    move |id| Request::Pick {
949        id,
950        mode,
951        multiple,
952        title,
953        accept_label,
954        suggested_name,
955        filters,
956    }
957}
958
959impl ShellChooser {
960    /// Ask the shell for a pick, and hand the answer to `handed` with the descriptors it came
961    /// with; anything the shell does not answer goes to `elsewhere`, as before.
962    fn pick_with<T: Send + 'static>(
963        &self,
964        request: PickRequest,
965        deliver: impl FnOnce(T) + Send + 'static,
966        handed: impl FnOnce(Vec<HandedDocument>, Vec<Descriptor>) -> T + Send + 'static,
967        cancelled: T,
968        failed: impl FnOnce(String) -> T + Send + 'static,
969        nowhere: impl FnOnce(&dyn FilePicker, PickRequest) -> T + Send + 'static,
970    ) {
971        let fallback = Arc::clone(&self.elsewhere);
972        let build = pick_request(&request);
973        self.link.connection().ask(
974            build,
975            Box::new(move |reply, fds| {
976                deliver(match reply {
977                    Reply::Handed { documents, .. } if !documents.is_empty() => {
978                        if documents.len() == fds.len() {
979                            handed(documents, fds)
980                        } else {
981                            failed(CHOOSER_OUT_OF_TURN.to_owned())
982                        }
983                    }
984                    Reply::Handed { .. } | Reply::Cancelled { .. } => cancelled,
985                    Reply::Nobody { .. } => nowhere(&*fallback, request),
986                    Reply::Failed { reason, .. } => failed(reason),
987                    _ => failed(CHOOSER_OUT_OF_TURN.to_owned()),
988                });
989            }),
990        );
991    }
992}
993
994/// The file a save writes, and the commit that renames it over the file the person chose.
995fn keeping(link: &ShellLink, document: HandedDocument, fd: Descriptor) -> OpenedFile {
996    let reference = document.reference.clone();
997    let link = link.clone();
998    let file = fd.into_file();
999    OpenedFile::keeping(file, document.name, reference.clone(), move || {
1000        commit(&link, &reference);
1001    })
1002}
1003
1004/// Finish a save: rename the file beside the chosen one over it, and wait briefly for the
1005/// chooser to answer so the file is there when the write returns.
1006fn commit(link: &ShellLink, reference: &Path) {
1007    let (tx, rx) = std::sync::mpsc::channel();
1008    link.saved(reference, move |outcome| {
1009        let _ = tx.send(outcome);
1010    });
1011    match rx.recv_timeout(SAVE_COMMIT_WAIT) {
1012        Ok(Ok(())) => {}
1013        Ok(Err(reason)) => tracing::warn!(%reason, "a save was not committed"),
1014        Err(_) => tracing::warn!("the chooser did not commit a save in time"),
1015    }
1016}
1017
1018/// Write `bytes` through `file` and commit the save: what a Save's bytes go through, never the
1019/// file the person sees until they are all there.
1020/// Write `bytes` over `file` and make them durable, answering why not.
1021fn write_bytes(mut file: File, bytes: &[u8]) -> Result<(), String> {
1022    file.set_len(0)
1023        .and_then(|()| std::io::Write::write_all(&mut file, bytes))
1024        .and_then(|()| file.sync_all())
1025        .map_err(|error| error.to_string())
1026}
1027
1028fn write_and_commit(
1029    link: &ShellLink,
1030    mut file: File,
1031    reference: &Path,
1032    bytes: &[u8],
1033) -> SaveOutcome {
1034    let written = file
1035        .set_len(0)
1036        .and_then(|()| std::io::Write::write_all(&mut file, bytes))
1037        .and_then(|()| file.sync_all());
1038    drop(file);
1039    if let Err(error) = written {
1040        return SaveOutcome::Failed(error.to_string());
1041    }
1042    let (tx, rx) = std::sync::mpsc::channel();
1043    link.saved(reference, move |outcome| {
1044        let _ = tx.send(outcome);
1045    });
1046    match rx.recv_timeout(SAVE_COMMIT_WAIT) {
1047        Ok(Ok(())) => SaveOutcome::Saved,
1048        Ok(Err(reason)) => SaveOutcome::Failed(reason),
1049        Err(_) => SaveOutcome::Failed("the chooser did not commit the save in time".to_owned()),
1050    }
1051}
1052
1053fn closed_recv<T>(rx: &std::sync::mpsc::Receiver<T>, closed: T) -> T {
1054    rx.recv().unwrap_or(closed)
1055}
1056
1057fn handed_reference(document: HandedDocument) -> PathBuf {
1058    document.reference
1059}
1060
1061impl FilePicker for ShellChooser {
1062    fn pick(&self, request: PickRequest) -> PortalChannel {
1063        let (deliver, rx) = channel();
1064        self.pick_with(
1065            request,
1066            deliver,
1067            |documents, _fds| {
1068                documents
1069                    .into_iter()
1070                    .next()
1071                    .map_or(PortalOutcome::Cancelled, |document| {
1072                        PortalOutcome::Opened(handed_reference(document))
1073                    })
1074            },
1075            PortalOutcome::Cancelled,
1076            PortalOutcome::Failed,
1077            |picker, request| {
1078                closed_recv(&picker.pick(request), PortalOutcome::Failed(CLOSED.into()))
1079            },
1080        );
1081        rx
1082    }
1083
1084    fn pick_multiple(&self, request: PickRequest) -> MultiChannel {
1085        let (deliver, rx) = channel();
1086        self.pick_with(
1087            request,
1088            deliver,
1089            |documents, _fds| {
1090                MultiOutcome::Selected(documents.into_iter().map(handed_reference).collect())
1091            },
1092            MultiOutcome::Cancelled,
1093            MultiOutcome::Failed,
1094            |picker, request| {
1095                closed_recv(
1096                    &picker.pick_multiple(request),
1097                    MultiOutcome::Failed(CLOSED.into()),
1098                )
1099            },
1100        );
1101        rx
1102    }
1103
1104    /// The chosen file or folder, opened by the descriptor the chooser handed over, so the app
1105    /// reads it in place on a host where its path names nothing.
1106    fn open_handle(&self, request: PickRequest) -> OpenFileChannel {
1107        if !matches!(
1108            request.kind,
1109            PickKind::Open { multiple: false } | PickKind::Directory
1110        ) {
1111            return answered(OpenFileOutcome::Failed(
1112                "a handle request must be a single-file Open or a folder chooser".to_string(),
1113            ));
1114        }
1115        let (deliver, rx) = channel();
1116        self.pick_with(
1117            request,
1118            deliver,
1119            |documents, fds| match (documents.into_iter().next(), fds.into_iter().next()) {
1120                (Some(document), Some(fd)) => {
1121                    OpenFileOutcome::Opened(OpenedFile::at(fd.into_file(), &document.reference))
1122                }
1123                _ => OpenFileOutcome::Failed(CHOOSER_OUT_OF_TURN.to_owned()),
1124            },
1125            OpenFileOutcome::Cancelled,
1126            OpenFileOutcome::Failed,
1127            |picker, request| {
1128                closed_recv(
1129                    &picker.open_handle(request),
1130                    OpenFileOutcome::Failed(CLOSED.into()),
1131                )
1132            },
1133        );
1134        rx
1135    }
1136
1137    /// Open the file or folder a reference names again: the window a choice made, or one inside
1138    /// the folder the person chose.
1139    fn reopen(&self, reference: &std::path::Path, write: bool) -> OpenFileChannel {
1140        let (deliver, rx) = channel();
1141        self.link.reopen(reference, write, move |answer| {
1142            deliver(match answer {
1143                Ok((file, held, name)) => {
1144                    OpenFileOutcome::Opened(OpenedFile::named(file, name, held))
1145                }
1146                Err(reason) => OpenFileOutcome::Failed(reason),
1147            });
1148        });
1149        rx
1150    }
1151
1152    /// A Save handed as a write descriptor: the app's writes land in the file beside the chosen
1153    /// one, and dropping the file renames it over the file the person chose.
1154    fn save_file(&self, request: PickRequest) -> OpenFileChannel {
1155        if request.suggested_name().is_none() {
1156            return answered(OpenFileOutcome::Failed(
1157                "a save request names a file".to_string(),
1158            ));
1159        }
1160        let (deliver, rx) = channel();
1161        let link = self.link.clone();
1162        self.pick_with(
1163            request,
1164            deliver,
1165            move |documents, fds| match (documents.into_iter().next(), fds.into_iter().next()) {
1166                (Some(document), Some(fd)) => OpenFileOutcome::Opened(keeping(&link, document, fd)),
1167                _ => OpenFileOutcome::Failed(CHOOSER_OUT_OF_TURN.to_owned()),
1168            },
1169            OpenFileOutcome::Cancelled,
1170            OpenFileOutcome::Failed,
1171            |picker, request| {
1172                closed_recv(
1173                    &picker.save_file(request),
1174                    OpenFileOutcome::Failed(CLOSED.into()),
1175                )
1176            },
1177        );
1178        rx
1179    }
1180
1181    /// A Save whose bytes are written through the descriptor, then committed by the chooser.
1182    fn save_contents(&self, request: PickRequest, bytes: Vec<u8>) -> SaveChannel {
1183        if request.suggested_name().is_none() {
1184            return answered(SaveOutcome::Failed(
1185                "only a Save chooser saves contents".to_owned(),
1186            ));
1187        }
1188        let (deliver, rx) = channel();
1189        let link = self.link.clone();
1190        let fallback = Arc::clone(&self.elsewhere);
1191        let build = pick_request(&request);
1192        self.link.connection().ask(
1193            build,
1194            Box::new(move |reply, fds| {
1195                let saving = match reply {
1196                    Reply::Handed { documents, .. } => {
1197                        match (documents.into_iter().next(), fds.into_iter().next()) {
1198                            (Some(document), Some(fd)) => {
1199                                Some((fd.into_file(), document.reference))
1200                            }
1201                            _ => None,
1202                        }
1203                    }
1204                    Reply::Cancelled { .. } => return deliver(SaveOutcome::Cancelled),
1205                    Reply::Nobody { .. } => {
1206                        return deliver(closed_recv(
1207                            &fallback.save_contents(request, bytes),
1208                            SaveOutcome::Failed(CLOSED.to_owned()),
1209                        ));
1210                    }
1211                    Reply::Failed { reason, .. } => return deliver(SaveOutcome::Failed(reason)),
1212                    _ => return deliver(SaveOutcome::Failed(CHOOSER_OUT_OF_TURN.to_owned())),
1213                };
1214                let Some((file, reference)) = saving else {
1215                    return deliver(SaveOutcome::Failed(CHOOSER_OUT_OF_TURN.to_owned()));
1216                };
1217                // Write now, on this thread; the commit asks the chooser again, so it is left to
1218                // the reader loop that must answer it.
1219                if let Err(reason) = write_bytes(file, &bytes) {
1220                    return deliver(SaveOutcome::Failed(reason));
1221                }
1222                link.saved(&reference, move |outcome| {
1223                    deliver(match outcome {
1224                        Ok(()) => SaveOutcome::Saved,
1225                        Err(reason) => SaveOutcome::Failed(reason),
1226                    });
1227                });
1228            }),
1229        );
1230        rx
1231    }
1232
1233    /// A destination the app writes to again on every later Save, named by its reference: each
1234    /// write reopens the file beside the chosen one and commits it over the file.
1235    fn save_destination(&self, request: PickRequest) -> crate::portal::DestinationChannel {
1236        if request.suggested_name().is_none() {
1237            return crate::portal::DestinationChannel::answered(
1238                crate::portal::DestinationOutcome::Failed(
1239                    "only a Save chooser chooses where to save".to_owned(),
1240                ),
1241            );
1242        }
1243        let (tx, rx) = std::sync::mpsc::channel();
1244        let link = self.link.clone();
1245        let fallback = Arc::clone(&self.elsewhere);
1246        let build = pick_request(&request);
1247        self.link.connection().ask(
1248            build,
1249            Box::new(move |reply, fds| {
1250                let outcome = match reply {
1251                    Reply::Handed { documents, .. } => {
1252                        match (documents.into_iter().next(), fds.into_iter().next()) {
1253                            (Some(document), Some(fd)) => {
1254                                let first = Arc::new(Mutex::new(Some(fd.into_file())));
1255                                let reference = document.reference.clone();
1256                                let name = document.name;
1257                                let writer = {
1258                                    let link = link.clone();
1259                                    let reference = reference.clone();
1260                                    move |bytes: Vec<u8>| {
1261                                        let link = link.clone();
1262                                        let reference = reference.clone();
1263                                        let taken =
1264                                            first.lock().ok().and_then(|mut first| first.take());
1265                                        let (send, receive) = std::sync::mpsc::channel();
1266                                        let spawned = tilo_rt::background::Background::current()
1267                                            .spawn("tilo-shell-save", move || {
1268                                                let outcome = match taken {
1269                                                    Some(file) => write_and_commit(
1270                                                        &link, file, &reference, &bytes,
1271                                                    ),
1272                                                    None => {
1273                                                        reopen_and_write(&link, &reference, &bytes)
1274                                                    }
1275                                                };
1276                                                let _ = send.send(outcome);
1277                                            });
1278                                        if spawned.is_err() {
1279                                            let (send, receive) = std::sync::mpsc::channel();
1280                                            let _ = send.send(SaveOutcome::Failed(
1281                                                "this host runs no background work".to_owned(),
1282                                            ));
1283                                            return receive;
1284                                        }
1285                                        receive
1286                                    }
1287                                };
1288                                crate::portal::DestinationOutcome::Chosen(
1289                                    crate::portal::SaveDestination::kept_at(
1290                                        name, reference, writer,
1291                                    ),
1292                                )
1293                            }
1294                            _ => crate::portal::DestinationOutcome::Failed(
1295                                CHOOSER_OUT_OF_TURN.to_owned(),
1296                            ),
1297                        }
1298                    }
1299                    Reply::Cancelled { .. } => crate::portal::DestinationOutcome::Cancelled,
1300                    Reply::Nobody { .. } => {
1301                        let outcome =
1302                            fallback
1303                                .save_destination(request)
1304                                .recv()
1305                                .unwrap_or_else(|_| {
1306                                    crate::portal::DestinationOutcome::Failed(CLOSED.to_owned())
1307                                });
1308                        let _ = tx.send(outcome);
1309                        return;
1310                    }
1311                    Reply::Failed { reason, .. } => {
1312                        crate::portal::DestinationOutcome::Failed(reason)
1313                    }
1314                    _ => crate::portal::DestinationOutcome::Failed(CHOOSER_OUT_OF_TURN.to_owned()),
1315                };
1316                let _ = tx.send(outcome);
1317            }),
1318        );
1319        crate::portal::DestinationChannel::from_outcomes(rx)
1320    }
1321
1322    fn launch(&self, request: LaunchRequest) -> LaunchChannel {
1323        if !request.path.is_absolute() {
1324            return answered(LaunchOutcome::Failed(
1325                "desktop-open path must be absolute".into(),
1326            ));
1327        }
1328        if request.is_reveal() {
1329            return answered(LaunchOutcome::Failed(
1330                "this session cannot show a file's folder".into(),
1331            ));
1332        }
1333        let (deliver, rx) = channel();
1334        let path = request.path;
1335        self.link.connection().ask(
1336            move |id| Request::Open { id, path },
1337            Box::new(move |reply, _fds| {
1338                deliver(match reply {
1339                    Reply::Opened { .. } => LaunchOutcome::Opened,
1340                    Reply::Failed { reason, .. } => LaunchOutcome::Failed(reason),
1341                    _ => LaunchOutcome::Failed(CHOOSER_OUT_OF_TURN.into()),
1342                });
1343            }),
1344        );
1345        rx
1346    }
1347}
1348
1349/// Reopen the file a Save writes and commit `bytes`: the place a destination writes to again.
1350fn reopen_and_write(link: &ShellLink, reference: &Path, bytes: &[u8]) -> SaveOutcome {
1351    let (tx, rx) = std::sync::mpsc::channel();
1352    link.reopen(reference, true, move |opened| {
1353        let _ = tx.send(opened);
1354    });
1355    match rx.recv_timeout(LINK_ANSWER) {
1356        Ok(Ok((file, held, _name))) => write_and_commit(link, file, &held, bytes),
1357        Ok(Err(reason)) => SaveOutcome::Failed(reason),
1358        Err(_) => SaveOutcome::Failed("the chooser did not answer in time".to_owned()),
1359    }
1360}
1361
1362#[cfg(test)]
1363mod tests {
1364    use super::*;
1365    #[cfg(unix)]
1366    use std::io::Read as _;
1367    use std::io::{BufRead as _, BufReader};
1368    use std::path::Path;
1369    use std::time::Duration;
1370
1371    fn answer() -> Duration {
1372        tilo_test_env::hang_bound()
1373    }
1374
1375    /// A reply the shell writes, with the files it hands over.
1376    struct Answer(Reply, Vec<std::fs::File>);
1377
1378    impl Answer {
1379        fn reply(reply: Reply) -> Self {
1380            Self(reply, Vec::new())
1381        }
1382
1383        /// A choice of `documents`, each opened in `file`.
1384        fn handed(id: u64, documents: &[(&str, std::fs::File)]) -> Self {
1385            Self(
1386                Reply::Handed {
1387                    id,
1388                    documents: documents
1389                        .iter()
1390                        .map(|(reference, _)| HandedDocument {
1391                            reference: PathBuf::from(reference),
1392                            name: Path::new(reference)
1393                                .file_name()
1394                                .map_or_else(String::new, |name| {
1395                                    name.to_string_lossy().into_owned()
1396                                }),
1397                        })
1398                        .collect(),
1399                },
1400                documents
1401                    .iter()
1402                    .map(|(_, file)| file.try_clone().unwrap())
1403                    .collect(),
1404            )
1405        }
1406    }
1407
1408    fn shell(respond: impl Fn(Request) -> Answer + Send + 'static) -> Stream {
1409        let (app, shell) = tilo_socket::pair().unwrap();
1410        std::thread::spawn(move || {
1411            let writer = shell.try_clone().unwrap();
1412            for line in BufReader::new(shell).lines() {
1413                let Ok(line) = line else { break };
1414                let request: Request = serde_json::from_str(&line).unwrap();
1415                let Answer(reply, files) = respond(request);
1416                let mut frame = serde_json::to_vec(&reply).unwrap();
1417                frame.push(b'\n');
1418                #[cfg(unix)]
1419                let fds: Vec<Descriptor> = files
1420                    .into_iter()
1421                    .map(|file| Descriptor::from(OwnedFd::from(file)))
1422                    .collect();
1423                #[cfg(not(unix))]
1424                let fds: Vec<Descriptor> = {
1425                    drop(files);
1426                    Vec::new()
1427                };
1428                if send_frame(&writer, &frame, &fds).is_err() {
1429                    break;
1430                }
1431            }
1432        });
1433        app
1434    }
1435
1436    fn id_of(request: &Request) -> u64 {
1437        match request {
1438            Request::Pick { id, .. }
1439            | Request::Open { id, .. }
1440            | Request::OpenUri { id, .. }
1441            | Request::Reopen { id, .. }
1442            | Request::Saved { id, .. }
1443            | Request::PickContents { id, .. }
1444            | Request::ReadContents { id, .. }
1445            | Request::ReleaseContents { id, .. }
1446            | Request::ChooseApp { id, .. }
1447            | Request::AwaitIdentity { id }
1448            | Request::ChooseIdentity { id } => *id,
1449        }
1450    }
1451
1452    #[cfg(unix)]
1453    #[test]
1454    fn only_an_inherited_socket_is_adopted() {
1455        use std::os::fd::IntoRawFd as _;
1456
1457        let file = tempfile::tempfile().unwrap().into_raw_fd();
1458        assert!(adopt_socket(file).is_none(), "a file is not the chooser");
1459        // SAFETY: the test owns `file` and nothing adopted it.
1460        drop(unsafe { std::fs::File::from_raw_fd(file) });
1461        assert!(adopt_socket(2).is_none());
1462
1463        let (app, mut shell) = tilo_socket::pair().unwrap();
1464        let adopted = adopt_socket(app.into_raw_fd()).expect("a socket is adopted");
1465        // SAFETY: reading the flags of a descriptor the test owns.
1466        let flags =
1467            unsafe { libc::fcntl(std::os::fd::AsRawFd::as_raw_fd(&adopted), libc::F_GETFD) };
1468        assert_ne!(
1469            flags & libc::FD_CLOEXEC,
1470            0,
1471            "the app's children don't inherit it"
1472        );
1473        drop(adopted);
1474        let mut rest = Vec::new();
1475        shell.read_to_end(&mut rest).unwrap();
1476        assert!(rest.is_empty(), "dropping the adopted socket closes it");
1477    }
1478
1479    tilo_test_env::scenario! {
1480        fn an_app_asks_its_shell_and_reports_the_shells_answer;
1481
1482        phase the_shell_chooser_keeps_the_picker_contract;
1483        {
1484            let chooser = picker(
1485                shell(|request| {
1486                    Answer::reply(Reply::Failed {
1487                        id: id_of(&request),
1488                        reason: "no".into(),
1489                    })
1490                }),
1491                crate::unavailable_picker(),
1492            )
1493            .unwrap();
1494            crate::conformance::check_picker_contract(&*chooser);
1495        }
1496
1497        phase a_pick_carries_the_request_and_delivers_what_the_shell_chose;
1498        {
1499            let (seen_tx, seen) = std::sync::mpsc::channel();
1500            let chooser = picker(
1501                shell(move |request| {
1502                    let id = id_of(&request);
1503                    let _ = seen_tx.send(request);
1504                    let with = |name: &str| {
1505                        let file = tempfile::tempfile().unwrap();
1506                        (name.to_owned(), file)
1507                    };
1508                    let documents = [with("/data/in/x.xlsx"), with("/data/in/y.xlsx")];
1509                    Answer::handed(
1510                        id,
1511                        &documents
1512                            .iter()
1513                            .map(|(name, file)| (name.as_str(), file.try_clone().unwrap()))
1514                            .collect::<Vec<_>>(),
1515                    )
1516                }),
1517                crate::unavailable_picker(),
1518            )
1519            .unwrap();
1520            let request = PickRequest::open("Import spreadsheet", "Import")
1521                .filter(FileFilter::new("Excel").glob("*.xlsx"));
1522            assert_eq!(
1523                chooser.pick(request).recv_timeout(answer()).unwrap(),
1524                PortalOutcome::Opened("/data/in/x.xlsx".into())
1525            );
1526            let Request::Pick {
1527                mode,
1528                multiple,
1529                title,
1530                accept_label,
1531                suggested_name,
1532                filters,
1533                ..
1534            } = seen.recv_timeout(answer()).unwrap()
1535            else {
1536                panic!("a chooser request is a pick");
1537            };
1538            assert_eq!(mode, PickMode::Open);
1539            assert!(!multiple);
1540            assert_eq!(title, "Import spreadsheet");
1541            assert_eq!(accept_label, "Import");
1542            assert_eq!(suggested_name, None);
1543            assert_eq!(
1544                filters.first().map(|f| f.globs.clone()),
1545                Some(vec!["*.xlsx".to_owned()])
1546            );
1547
1548            assert_eq!(
1549                chooser
1550                    .pick_multiple(PickRequest::open_multiple("Open", "Open"))
1551                    .recv_timeout(answer())
1552                    .unwrap(),
1553                MultiOutcome::Selected(vec!["/data/in/x.xlsx".into(), "/data/in/y.xlsx".into()])
1554            );
1555            let Request::Pick { multiple, .. } = seen.recv_timeout(answer()).unwrap() else {
1556                panic!("a chooser request is a pick");
1557            };
1558            assert!(multiple);
1559        }
1560
1561        phase nobody_at_the_computer_falls_back_to_the_unattended_picker;
1562        {
1563            let directory = tempfile::tempdir().unwrap();
1564            let unattended = crate::unattended_picker(directory.path().to_path_buf());
1565            let nobody = |request: Request| {
1566                Answer::reply(Reply::Nobody {
1567                    id: id_of(&request),
1568                })
1569            };
1570            let chooser = picker(shell(nobody), unattended.expect("an unattended picker")).unwrap();
1571            assert_eq!(
1572                chooser
1573                    .pick(PickRequest::save("Save", "Save", "report.xlsx"))
1574                    .recv_timeout(answer())
1575                    .unwrap(),
1576                PortalOutcome::Opened(directory.path().join("report.xlsx"))
1577            );
1578            assert!(matches!(
1579                chooser.pick(PickRequest::open("Open", "Open")).recv_timeout(answer()),
1580                Ok(PortalOutcome::Failed(reason)) if reason.contains("nobody")
1581            ));
1582
1583            // An app that brought no chooser of its own says plainly there is none.
1584            let alone = picker(shell(nobody), crate::unavailable_picker()).unwrap();
1585            assert!(matches!(
1586                alone
1587                    .pick(PickRequest::save("Save", "Save", "report.xlsx"))
1588                    .recv_timeout(answer()),
1589                Ok(PortalOutcome::Failed(_))
1590            ));
1591        }
1592
1593        phase opening_a_file_asks_the_shell_and_reports_its_answer;
1594        {
1595            let chooser = picker(
1596                shell(|request| {
1597                    Answer::reply(match request {
1598                        Request::Open { id, path } if path == Path::new("/data/in/a.docx") => {
1599                            Reply::Opened { id }
1600                        }
1601                        other => Reply::Failed {
1602                            id: id_of(&other),
1603                            reason: "not granted".into(),
1604                        },
1605                    })
1606                }),
1607                crate::unavailable_picker(),
1608            )
1609            .unwrap();
1610            assert_eq!(
1611                chooser
1612                    .launch(LaunchRequest::open("/data/in/a.docx"))
1613                    .recv_timeout(answer())
1614                    .unwrap(),
1615                LaunchOutcome::Opened
1616            );
1617            assert_eq!(
1618                chooser
1619                    .launch(LaunchRequest::open("/etc/shadow"))
1620                    .recv_timeout(answer())
1621                    .unwrap(),
1622                LaunchOutcome::Failed("not granted".into())
1623            );
1624        }
1625
1626        phase the_app_chooser_answers_the_app_chosen_or_none;
1627        {
1628            let terminal = ChosenApp {
1629                id: "org.example.Terminal".into(),
1630                name: "Terminal".into(),
1631                window_ids: vec!["org.example.Terminal".into(), "terminal".into()],
1632            };
1633            let answer_with = terminal.clone();
1634            let link = ShellLink::connect(shell(move |request| {
1635                Answer::reply(match request {
1636                    Request::ChooseApp { id, purpose } if purpose == "Paste in apps" => {
1637                        Reply::AppChosen {
1638                            id,
1639                            app: answer_with.clone(),
1640                        }
1641                    }
1642                    other => Reply::Cancelled { id: id_of(&other) },
1643                })
1644            }))
1645            .unwrap();
1646            let (chosen_tx, chosen) = std::sync::mpsc::channel();
1647            let tx = chosen_tx.clone();
1648            link.choose_app("Paste in apps", move |outcome| tx.send(outcome).unwrap());
1649            assert_eq!(chosen.recv_timeout(answer()).unwrap(), Ok(Some(terminal)));
1650            link.choose_app("Something else", move |outcome| {
1651                chosen_tx.send(outcome).unwrap();
1652            });
1653            assert_eq!(chosen.recv_timeout(answer()).unwrap(), Ok(None));
1654        }
1655
1656        phase a_link_opens_through_the_shell_and_only_what_it_leaves_goes_elsewhere;
1657        {
1658            let elsewhere = Arc::new(Elsewhere::default());
1659            let opener = ShellLink::connect(shell(|request| {
1660                Answer::reply(match request {
1661                    Request::OpenUri { id, uri } if uri.starts_with("settings:") => {
1662                        Reply::Opened { id }
1663                    }
1664                    Request::OpenUri { id, uri } if uri.starts_with("mailto:") => {
1665                        Reply::Unclaimed { id }
1666                    }
1667                    other => Reply::Failed {
1668                        id: id_of(&other),
1669                        reason: "the app could not start".into(),
1670                    },
1671                })
1672            }))
1673            .unwrap()
1674            .opener(Arc::clone(&elsewhere) as Arc<dyn crate::UriOpener>);
1675            crate::conformance::check_opener_contract(&*opener);
1676
1677            opener.open("settings://updates").unwrap();
1678            assert!(elsewhere.0.lock().unwrap().is_empty());
1679            opener.open("mailto:ada@example.test").unwrap();
1680            assert_eq!(*elsewhere.0.lock().unwrap(), ["mailto:ada@example.test"]);
1681            let refused = opener.open("web+notes:today").unwrap_err();
1682            assert_eq!(refused.to_string(), "the app could not start");
1683            assert_eq!(
1684                elsewhere.0.lock().unwrap().len(),
1685                1,
1686                "a refusal is reported, not rerouted"
1687            );
1688
1689            let (app, gone) = tilo_socket::pair().unwrap();
1690            drop(gone);
1691            let alone = ShellLink::connect(app)
1692                .unwrap()
1693                .opener(Arc::clone(&elsewhere) as Arc<dyn crate::UriOpener>);
1694            alone.open("https://example.test/").unwrap();
1695            assert_eq!(
1696                elsewhere.0.lock().unwrap().last().map(String::as_str),
1697                Some("https://example.test/"),
1698                "without its shell an app's links still open"
1699            );
1700        }
1701
1702        phase a_cancelled_pick_and_a_gone_shell_answer_instead_of_hanging;
1703        {
1704            let chooser = picker(
1705                shell(|request| {
1706                    Answer::reply(Reply::Cancelled {
1707                        id: id_of(&request),
1708                    })
1709                }),
1710                crate::unavailable_picker(),
1711            )
1712            .unwrap();
1713            assert_eq!(
1714                chooser
1715                    .pick(PickRequest::open("Open", "Open"))
1716                    .recv_timeout(answer())
1717                    .unwrap(),
1718                PortalOutcome::Cancelled
1719            );
1720
1721            let (app, shell) = tilo_socket::pair().unwrap();
1722            let chooser = picker(app, crate::unavailable_picker()).unwrap();
1723            let waiting = chooser.pick(PickRequest::open("Open", "Open"));
1724            drop(shell);
1725            assert!(matches!(
1726                waiting.recv_timeout(answer()),
1727                Ok(PortalOutcome::Failed(_))
1728            ));
1729            assert!(matches!(
1730                chooser
1731                    .launch(LaunchRequest::open("/data/in/a.docx"))
1732                    .recv_timeout(answer()),
1733                Ok(LaunchOutcome::Failed(_))
1734            ));
1735        }
1736    }
1737
1738    #[derive(Default)]
1739    struct Elsewhere(Mutex<Vec<String>>);
1740
1741    impl crate::UriOpener for Elsewhere {
1742        fn open(&self, uri: &str) -> std::io::Result<()> {
1743            self.0.lock().unwrap().push(uri.to_owned());
1744            Ok(())
1745        }
1746    }
1747}