Skip to main content

tilo_dialogs/
chooser_service.rs

1//! The server side of the shell's chooser protocol ([`crate::shell`]).
2//!
3//! One server answers every app's connection the same way, wherever it runs: a desktop session
4//! serves it on the launcher's socket, and a device daemon serves it on a socket pair it makes
5//! for the tilolang host it starts. What differs is only what the host fills in
6//! ([`Serving`]): where the person is asked, and how a link opens in an app.
7//!
8//! The person's choice is the grant: the host keeps the chosen file or folder for the app
9//! ([`Grants`]), and the answer carries a descriptor opened with the person's rights, so an app
10//! in a sandbox reads and writes exactly what was chosen without a host path. The reference the
11//! answer also carries names the same document again later ([`crate::shell::Request::Reopen`]);
12//! a save writes its bytes into a file beside the chosen one, which the chooser renames over the
13//! file only when the app says they are all there ([`crate::shell::Request::Saved`]).
14
15use std::ffi::CString;
16use std::fs::{File, OpenOptions};
17use std::io::Write as _;
18use std::os::fd::{AsRawFd as _, FromRawFd as _, OwnedFd};
19use std::os::unix::ffi::OsStrExt as _;
20use std::os::unix::fs::OpenOptionsExt as _;
21use std::os::unix::net::{UnixListener, UnixStream};
22use std::path::{Component, Path, PathBuf};
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::sync::{Arc, Mutex};
25
26use crate::portal::FileFilter;
27use crate::shell::{
28    Filter, FrameReader, HandedDocument, Handshake, MAX_FRAME_BYTES, PROTOCOL, PickMode, Reply,
29    Request, send_frame,
30};
31/// Names an app or a workspace may have on the handshake.
32const MAX_NAME: usize = 255;
33
34// What an app shows the person when the chooser could not do what it asked: what happened, and
35// what to do.
36pub const CANNOT_HAND: &str = "Files can't be handed to this app on this computer.";
37pub const DOES_NOT_FIT: &str =
38    "The file chooser's answer doesn't fit what the app asked for. Try again.";
39const GONE: &str = "That file is no longer available to the app. Choose it again.";
40pub const NOT_CHOSEN: &str = "This app can only open files you chose for it.";
41pub const NOTHING_OPENS: &str = "Nothing on this computer opens this file.";
42const BAD_LINK: &str = "That link isn't a web address or anything else that can be opened.";
43const DID_NOT_OPEN: &str = "It didn't open. Try again.";
44pub const NO_APP_CHOOSER: &str = "This computer can't ask you to choose an app yet.";
45const NO_IDENTITY_CHOOSER: &str = "This computer can't ask you to choose an identity yet.";
46const NOT_ASKED: &str = "The file chooser couldn't be shown. Try again.";
47
48/// What a chooser server is served with.
49#[derive(Clone)]
50pub struct Serving {
51    /// Where the person is asked; `None` when nobody is here to answer one.
52    pub person: Option<Arc<dyn Person>>,
53    /// What a choice gives the app and what it reopens: the host's document records.
54    pub grants: Arc<dyn Grants>,
55    /// What opens a link or a chosen file in an app.
56    pub opens: Arc<dyn Opens>,
57}
58
59/// Who asks, as the chooser knows an app: the launcher's name for it, and its workspace.
60#[derive(Debug, Clone)]
61pub struct Caller {
62    pub app: String,
63    pub workspace: String,
64}
65
66/// The question a pick asks the person, in the chooser's own words: the same fields on every
67/// host, whatever draws the sheet.
68#[derive(Debug, Clone, PartialEq, Eq)]
69#[allow(
70    clippy::struct_excessive_bools,
71    reason = "each flag is one of the chooser's independent options"
72)]
73pub struct Question {
74    pub title: String,
75    pub save: bool,
76    pub directory: bool,
77    pub writable_directory: bool,
78    pub multiple: bool,
79    pub accept_label: Option<String>,
80    pub current_name: Option<String>,
81    pub filters: Vec<FileFilter>,
82}
83
84impl Question {
85    /// What a choice answering this question gives the app.
86    #[must_use]
87    pub const fn choice(&self) -> Choice {
88        if self.save {
89            Choice::Save
90        } else if self.directory {
91            Choice::Folder {
92                write: self.writable_directory,
93            }
94        } else {
95            Choice::Read
96        }
97    }
98}
99
100/// What a choice allows the app: one file to read, one file to replace when a save ends, or a
101/// folder and everything under it.
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
103pub enum Choice {
104    Read,
105    Folder { write: bool },
106    Save,
107}
108
109impl Choice {
110    /// Whether the choice lets the app change what it names.
111    #[must_use]
112    pub const fn writes(self) -> bool {
113        matches!(self, Self::Save | Self::Folder { write: true })
114    }
115}
116
117/// One document the person gave the app, as the chooser opens it.
118#[derive(Debug, Clone)]
119pub struct Granted {
120    /// The path the app reaches it by inside its sandbox.
121    pub reference: PathBuf,
122    /// Its name there.
123    pub name: String,
124    /// The host file or folder behind the reference.
125    pub host: PathBuf,
126    /// What the choice allows.
127    pub choice: Choice,
128    /// Where a save writes before its bytes replace the file.
129    pub save_sibling: Option<std::ffi::OsString>,
130}
131
132/// Where the chooser's documents and their grants live. The host answers it, so the chooser
133/// reaches a person's choices through the host's records instead of a store of its own.
134pub trait Grants: Send + Sync {
135    /// Keep what the person chose for `caller` as `choice`, answering the document to hand over.
136    ///
137    /// # Errors
138    /// What the app shows the person when the choice cannot be kept.
139    fn grant(&self, caller: &Caller, chosen: &Path, choice: Choice) -> Result<Granted, String>;
140
141    /// The document `reference` names for `caller`, if the person gave that app this file.
142    fn document(&self, caller: &Caller, reference: &Path) -> Option<Granted>;
143}
144
145/// Why the person gave no files: they dismissed the sheet, or it could not be shown.
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
147pub enum Asked {
148    Cancelled,
149    Failed,
150}
151
152/// Where a host asks the person.
153pub trait Person: Send + Sync {
154    /// Ask the person `question` for `caller` under `handle`, and answer the host paths they
155    /// chose. Blocks for as long as the person takes.
156    ///
157    /// # Errors
158    /// [`Asked::Cancelled`] when they chose nothing, [`Asked::Failed`] when the sheet could not
159    /// be shown.
160    fn choose(
161        &self,
162        caller: &Caller,
163        handle: String,
164        question: &Question,
165    ) -> Result<Vec<PathBuf>, Asked>;
166}
167
168/// Where a link or a chosen file opens in an app.
169pub trait Opens: Send + Sync {
170    /// Open `uri` in `workspace` in the app that takes it; `None` when nothing does.
171    ///
172    /// # Errors
173    /// The app that takes it did not start.
174    fn open(&self, workspace: &str, uri: &str) -> Result<Option<()>, String>;
175}
176
177/// Open `stream` as one app's chooser connection: the launcher's handshake first, then what the
178/// app asks for. The connection is served on the calling thread, so callers run it on one of
179/// their own.
180pub fn serve_connection(serving: Arc<Serving>, stream: UnixStream) {
181    let Ok(writer) = stream.try_clone() else {
182        return;
183    };
184    let mut reader = FrameReader::new(stream);
185    let Some(handshake) = read_handshake(&mut reader) else {
186        tracing::warn!("a chooser connection named no app: it is closed");
187        return;
188    };
189    let connection = Arc::new(Connection {
190        serving,
191        number: CONNECTIONS.fetch_add(1, Ordering::Relaxed),
192        app: handshake.app_id,
193        workspace: handshake.workspace_id,
194        writer: Mutex::new(writer),
195    });
196    loop {
197        let frame = match reader.line() {
198            Ok(Some(frame)) => frame,
199            Ok(None) => break,
200            Err(error) => {
201                tracing::warn!(app = %connection.app, %error, "a chooser request is unreadable");
202                break;
203            }
204        };
205        let request = match serde_json::from_slice::<Request>(frame.trim_ascii_end()) {
206            Ok(request) => request,
207            Err(error) => {
208                tracing::warn!(app = %connection.app, %error, "a chooser request does not decode");
209                break;
210            }
211        };
212        match request {
213            Request::Reopen {
214                id,
215                reference,
216                write,
217            } => {
218                let (reply, fds) = connection.reopen(id, &reference, write);
219                connection.say_with(&reply, &fds);
220            }
221            Request::Saved { id, reference } => connection.say(&connection.saved(id, &reference)),
222            Request::ChooseApp { id, .. } => connection.say(&Reply::Failed {
223                id,
224                reason: NO_APP_CHOOSER.to_owned(),
225            }),
226            Request::AwaitIdentity { id } | Request::ChooseIdentity { id } => {
227                connection.say(&Reply::Failed {
228                    id,
229                    reason: NO_IDENTITY_CHOOSER.to_owned(),
230                });
231            }
232            request @ Request::Pick { .. } => {
233                Connection::ask_person(&connection, request);
234            }
235            waits => {
236                let asking = Arc::clone(&connection);
237                if let Err(error) = std::thread::Builder::new()
238                    .name("tilo-chooser-ask".into())
239                    .spawn(move || {
240                        let reply = asking.answer(waits);
241                        asking.say(&reply);
242                    })
243                {
244                    tracing::warn!(%error, "a chooser request could not be answered");
245                }
246            }
247        }
248    }
249}
250
251/// Accept connections until the listener closes.
252pub fn serve_listener(listener: &UnixListener, serving: &Arc<Serving>) {
253    for stream in listener.incoming() {
254        match stream {
255            Ok(stream) => {
256                let serving = Arc::clone(serving);
257                if let Err(error) = std::thread::Builder::new()
258                    .name("tilo-chooser-app".into())
259                    .spawn(move || serve_connection(serving, stream))
260                {
261                    tracing::warn!(%error, "a chooser connection could not be served");
262                }
263            }
264            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
265            Err(error) => {
266                tracing::warn!(%error, "the chooser service's accept failed");
267                std::thread::sleep(std::time::Duration::from_millis(100));
268            }
269        }
270    }
271}
272
273/// A socket pair for one app: the caller's end, already named by the handshake, and the server
274/// serving the other end on a thread of its own. What a device daemon hands a tilolang host it
275/// starts, in place of a session's socket.
276///
277/// # Errors
278/// The pair or the serving thread cannot be made.
279pub fn pair(serving: Serving, app: &str, workspace: &str) -> std::io::Result<UnixStream> {
280    let (app_end, runtime_end) = UnixStream::pair()?;
281    let handshake = Handshake {
282        protocol: PROTOCOL,
283        app_id: app.to_owned(),
284        workspace_id: workspace.to_owned(),
285    };
286    let mut frame = serde_json::to_vec(&handshake).map_err(std::io::Error::other)?;
287    frame.push(b'\n');
288    let mut writer = app_end.try_clone()?;
289    writer.write_all(&frame)?;
290    writer.flush()?;
291    let serving = Arc::new(serving);
292    std::thread::Builder::new()
293        .name("tilo-chooser".into())
294        .spawn(move || serve_connection(serving, runtime_end))?;
295    Ok(app_end)
296}
297
298static CONNECTIONS: AtomicU64 = AtomicU64::new(0);
299
300/// One app's connection: who it is, as its launcher named it, and what it holds.
301struct Connection {
302    serving: Arc<Serving>,
303    /// Which connection this is, for its questions' handles.
304    number: u64,
305    app: String,
306    workspace: String,
307    writer: Mutex<UnixStream>,
308}
309
310/// The question a pick asks; `None` for a request that is no pick.
311fn pick_question(request: Request) -> Option<(u64, Question)> {
312    match request {
313        Request::Pick {
314            id,
315            mode,
316            multiple,
317            title,
318            accept_label,
319            suggested_name,
320            filters,
321        } => Some((
322            id,
323            Question {
324                title,
325                save: mode == PickMode::Save,
326                directory: matches!(mode, PickMode::Directory | PickMode::WritableDirectory),
327                writable_directory: mode == PickMode::WritableDirectory,
328                multiple,
329                accept_label: Some(accept_label).filter(|label| !label.is_empty()),
330                current_name: suggested_name.filter(|name| !name.is_empty()),
331                filters: filters.iter().map(filter_of).collect(),
332            },
333        )),
334        _ => None,
335    }
336}
337
338fn filter_of(filter: &Filter) -> FileFilter {
339    let mut made = FileFilter::new(&filter.name);
340    for glob in &filter.globs {
341        made = made.glob(glob);
342    }
343    for mimetype in &filter.mimetypes {
344        made = made.mimetype(mimetype);
345    }
346    made
347}
348
349/// The launcher's handshake, the connection's first line.
350fn read_handshake(reader: &mut FrameReader) -> Option<Handshake> {
351    let frame = reader.line().ok()??;
352    let handshake: Handshake = serde_json::from_slice(frame.trim_ascii_end()).ok()?;
353    let named = |name: &str| !name.is_empty() && name.len() <= MAX_NAME;
354    (handshake.protocol == PROTOCOL && named(&handshake.app_id) && named(&handshake.workspace_id))
355        .then_some(handshake)
356}
357
358impl Connection {
359    /// Write `reply` as its line; a reply the wire cannot carry is logged, and an app that stopped
360    /// reading has gone.
361    fn say(&self, reply: &Reply) {
362        self.say_with(reply, &[]);
363    }
364
365    fn say_with(&self, reply: &Reply, fds: &[crate::shell::Descriptor]) {
366        let Ok(mut frame) = serde_json::to_vec(reply) else {
367            return;
368        };
369        if frame.len() >= MAX_FRAME_BYTES {
370            tracing::warn!(app = %self.app, "a chooser reply is larger than the wire allows");
371            return;
372        }
373        frame.push(b'\n');
374        let writer = self
375            .writer
376            .lock()
377            .unwrap_or_else(std::sync::PoisonError::into_inner);
378        if let Err(error) = send_frame(&writer, &frame, fds) {
379            tracing::debug!(%error, app = %self.app, "an app closed its end of the chooser");
380        }
381    }
382
383    /// Who asks, as the launcher named it on the handshake.
384    fn caller(&self) -> Caller {
385        Caller {
386            app: self.app.clone(),
387            workspace: self.workspace.clone(),
388        }
389    }
390
391    /// Ask the person what `request` asks for, and answer the app once they chose. Their answer
392    /// can take as long as they like, so the question runs on a thread of its own and nothing on
393    /// this connection waits for it: the app's other requests are answered meanwhile.
394    fn ask_person(connection: &Arc<Self>, request: Request) {
395        let Some((id, question)) = pick_question(request) else {
396            return;
397        };
398        let Some(person) = connection.serving.person.clone() else {
399            return connection.say(&Reply::Nobody { id });
400        };
401        let caller = Caller {
402            app: connection.app.clone(),
403            workspace: connection.workspace.clone(),
404        };
405        let handle = format!("chooser:{}:{id}", connection.number);
406        let asking = Arc::clone(connection);
407        let chosen = person.choose(&caller, handle, &question);
408        let reply = match chosen {
409            Ok(paths) => {
410                let (reply, fds) = asking.hand(id, &paths, question.choice());
411                asking.say_with(&reply, &fds);
412                return;
413            }
414            Err(Asked::Cancelled) => Reply::Cancelled { id },
415            Err(Asked::Failed) => failed(id, NOT_ASKED),
416        };
417        asking.say(&reply);
418    }
419
420    /// Answer a request that waits for another app: opening a link or a file.
421    fn answer(&self, request: Request) -> Reply {
422        match request {
423            Request::Open { id, path } => match self.opened_path(&path) {
424                Ok(host) => match file_uri(&host) {
425                    Some(uri) => match self.open(&uri) {
426                        Ok(true) => Reply::Opened { id },
427                        Ok(false) => failed(id, NOTHING_OPENS),
428                        Err(reason) => failed(id, reason),
429                    },
430                    None => failed(id, NOT_CHOSEN),
431                },
432                Err(reason) => failed(id, reason),
433            },
434            Request::OpenUri { id, uri } => self.open_uri(id, &uri),
435            Request::Pick { id, .. }
436            | Request::Reopen { id, .. }
437            | Request::Saved { id, .. }
438            | Request::ChooseApp { id, .. }
439            | Request::AwaitIdentity { id }
440            | Request::ChooseIdentity { id }
441            | Request::PickContents { id, .. }
442            | Request::ReadContents { id, .. }
443            | Request::ReleaseContents { id, .. } => failed(id, DOES_NOT_FIT),
444        }
445    }
446
447    /// The chosen items themselves: kept for the app by its host, and handed with a descriptor
448    /// opened with the person's rights. Never a host path.
449    fn hand(
450        &self,
451        id: u64,
452        paths: &[PathBuf],
453        choice: Choice,
454    ) -> (Reply, Vec<crate::shell::Descriptor>) {
455        let caller = self.caller();
456        let mut documents = Vec::with_capacity(paths.len());
457        let mut fds = Vec::with_capacity(paths.len());
458        for path in paths {
459            let granted = match self.serving.grants.grant(&caller, path, choice) {
460                Ok(granted) => granted,
461                Err(reason) => {
462                    tracing::debug!(%reason, path = %path.display(), "a chosen item is not kept for the app");
463                    return (failed(id, &reason), Vec::new());
464                }
465            };
466            match open_document(&granted, choice) {
467                Ok(fd) => {
468                    documents.push(HandedDocument {
469                        reference: granted.reference,
470                        name: granted.name,
471                    });
472                    fds.push(crate::shell::Descriptor::from(fd));
473                }
474                Err(error) => {
475                    tracing::debug!(%error, "a chosen item cannot be opened for the app");
476                    return (failed(id, DOES_NOT_FIT), Vec::new());
477                }
478            }
479        }
480        if documents.is_empty() {
481            return (failed(id, DOES_NOT_FIT), Vec::new());
482        }
483        (Reply::Handed { id, documents }, fds)
484    }
485
486    /// Turn a reference back into an open descriptor: the file a window showed, or a file inside
487    /// a folder the person chose. Only a document of this app is reached.
488    fn reopen(
489        &self,
490        id: u64,
491        reference: &Path,
492        write: bool,
493    ) -> (Reply, Vec<crate::shell::Descriptor>) {
494        let opened = (|| {
495            let caller = self.caller();
496            let granted = self
497                .serving
498                .grants
499                .document(&caller, reference)
500                .ok_or(NOT_CHOSEN)?;
501            let within = reference
502                .strip_prefix(&granted.reference)
503                .map_err(|_| NOT_CHOSEN)?;
504            let relative = plain_relative(within).ok_or(NOT_CHOSEN)?;
505            let file = if relative.as_os_str().is_empty() {
506                // A folder opens as a folder, to read what it holds; a file to read unless the
507                // app asked to write what its choice lets it.
508                let choice = match granted.choice {
509                    Choice::Folder { write: may } => Choice::Folder {
510                        write: write && may,
511                    },
512                    _ if write => granted.choice,
513                    _ => Choice::Read,
514                };
515                File::from(open_document(&granted, choice).map_err(|_| NOT_CHOSEN)?)
516            } else {
517                if !matches!(granted.choice, Choice::Folder { .. }) {
518                    return Err(NOT_CHOSEN);
519                }
520                if write && !granted.choice.writes() {
521                    return Err(NOT_CHOSEN);
522                }
523                open_beneath(&granted.host, &relative, write)?
524            };
525            let name = relative.file_name().map_or_else(
526                || granted.name.clone(),
527                |name| name.to_string_lossy().into_owned(),
528            );
529            Ok((
530                OwnedFd::from(file),
531                HandedDocument {
532                    reference: reference.to_path_buf(),
533                    name,
534                },
535            ))
536        })();
537        match opened {
538            Ok((fd, document)) => (
539                Reply::Handed {
540                    id,
541                    documents: vec![document],
542                },
543                vec![crate::shell::Descriptor::from(fd)],
544            ),
545            Err(reason) => (failed(id, reason), Vec::new()),
546        }
547    }
548
549    /// A save's bytes are in the file beside it: rename that over the file the person chose.
550    fn saved(&self, id: u64, reference: &Path) -> Reply {
551        let renamed = (|| {
552            let caller = self.caller();
553            let granted = self
554                .serving
555                .grants
556                .document(&caller, reference)
557                .ok_or(NOT_CHOSEN)?;
558            if granted.choice != Choice::Save || granted.reference != reference {
559                return Err(NOT_CHOSEN);
560            }
561            let beside = granted.save_sibling.ok_or(NOT_CHOSEN)?;
562            std::fs::rename(granted.host.with_file_name(beside), &granted.host).map_err(|_| GONE)
563        })();
564        match renamed {
565            Ok(()) => Reply::Saved { id },
566            Err(reason) => failed(id, reason),
567        }
568    }
569
570    /// The host file a reference names, for opening it in an app: one the person chose for it.
571    fn opened_path(&self, path: &Path) -> Result<PathBuf, &'static str> {
572        let granted = self
573            .serving
574            .grants
575            .document(&self.caller(), path)
576            .ok_or(NOT_CHOSEN)?;
577        let within = path
578            .strip_prefix(&granted.reference)
579            .map_err(|_| NOT_CHOSEN)?;
580        if within.as_os_str().is_empty() {
581            return Ok(granted.host);
582        }
583        plain_relative(within).ok_or(NOT_CHOSEN)?;
584        // Inside a chosen folder, and only a folder.
585        if matches!(granted.choice, Choice::Folder { .. }) {
586            Ok(granted.host.join(within))
587        } else {
588            Err(NOT_CHOSEN)
589        }
590    }
591
592    /// Open `uri` the way a link the app asks to open goes: a file only as [`Self::opened_path`]
593    /// allows, anything else in the app that claims its scheme.
594    fn open_uri(&self, id: u64, uri: &str) -> Reply {
595        let Ok(parsed) = url::Url::parse(uri) else {
596            return failed(id, BAD_LINK);
597        };
598        if parsed.scheme() == "file" {
599            let Ok(path) = parsed.to_file_path() else {
600                return failed(id, BAD_LINK);
601            };
602            let host = match self.opened_path(&path) {
603                Ok(host) => host,
604                Err(reason) => return failed(id, reason),
605            };
606            let Some(uri) = file_uri(&host) else {
607                return failed(id, NOT_CHOSEN);
608            };
609            return match self.open(&uri) {
610                Ok(true) => Reply::Opened { id },
611                Ok(false) => failed(id, NOTHING_OPENS),
612                Err(reason) => failed(id, reason),
613            };
614        }
615        match self.open(uri) {
616            Ok(true) => Reply::Opened { id },
617            Ok(false) => Reply::Unclaimed { id },
618            Err(reason) => failed(id, reason),
619        }
620    }
621
622    /// Ask the host to open `uri` in the app's workspace: whether an app took it.
623    fn open(&self, uri: &str) -> Result<bool, &'static str> {
624        match self.serving.opens.open(&self.workspace, uri) {
625            Ok(opened) => Ok(opened.is_some()),
626            Err(error) => {
627                tracing::warn!(app = %self.app, %error, "what an app asked to open did not open");
628                Err(DID_NOT_OPEN)
629            }
630        }
631    }
632}
633
634/// The open descriptor for a chosen document, as `choice` gives it: a file to read or write, or a
635/// folder.
636fn open_document(granted: &Granted, choice: Choice) -> Result<OwnedFd, std::io::Error> {
637    let file = match choice {
638        Choice::Read => crate::portal::open_regular_file(&granted.host)?,
639        Choice::Folder { .. } => crate::portal::open_directory_handle(&granted.host)?,
640        Choice::Save => open_for_save(granted)?,
641    };
642    Ok(OwnedFd::from(file))
643}
644
645fn open_for_save(granted: &Granted) -> std::io::Result<File> {
646    let beside = granted.save_sibling.clone().ok_or_else(|| {
647        std::io::Error::new(
648            std::io::ErrorKind::InvalidInput,
649            "a save writes beside a file",
650        )
651    })?;
652    OpenOptions::new()
653        .write(true)
654        .create(true)
655        .truncate(true)
656        .mode(0o644)
657        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
658        .open(granted.host.with_file_name(beside))
659}
660
661/// `relative` with every component a plain name: what opens beneath a chosen folder, never a
662/// name that climbs out of it.
663fn plain_relative(relative: &Path) -> Option<PathBuf> {
664    let mut plain = PathBuf::new();
665    for component in relative.components() {
666        match component {
667            Component::Normal(name) => plain.push(name),
668            _ => return None,
669        }
670    }
671    Some(plain)
672}
673
674/// Open a file inside a chosen folder, walking it a component at a time with `openat`, never
675/// following a link: the person chose the folder and what is under it, not where a link points.
676fn open_beneath(root: &Path, relative: &Path, write: bool) -> Result<File, &'static str> {
677    let directory = crate::portal::open_directory_handle(root).map_err(|_| NOT_CHOSEN)?;
678    let mut current = OwnedFd::from(directory);
679    let parts: Vec<&std::ffi::OsStr> = relative.iter().collect();
680    let count = parts.len();
681    for (at, part) in parts.into_iter().enumerate() {
682        let last = at.saturating_add(1) == count;
683        let flags = if last && write {
684            libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW | libc::O_CLOEXEC
685        } else if last {
686            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC
687        } else {
688            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC
689        };
690        let name = CString::new(part.as_bytes()).map_err(|_| NOT_CHOSEN)?;
691        // SAFETY: `openat` reads the descriptor and the name, both valid for the call.
692        let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags, 0o644) };
693        if fd < 0 {
694            return Err(NOT_CHOSEN);
695        }
696        // SAFETY: `openat` just returned this descriptor, which nothing else owns.
697        current = unsafe { OwnedFd::from_raw_fd(fd) };
698    }
699    let file = File::from(current);
700    if write && !file.metadata().map_err(|_| NOT_CHOSEN)?.is_file() {
701        return Err(NOT_CHOSEN);
702    }
703    Ok(file)
704}
705
706/// `path` as an RFC 8089 file URI.
707fn file_uri(path: &Path) -> Option<String> {
708    url::Url::from_file_path(path).ok().map(String::from)
709}
710
711fn failed(id: u64, reason: &str) -> Reply {
712    Reply::Failed {
713        id,
714        reason: reason.to_owned(),
715    }
716}
717
718#[cfg(all(test, unix))]
719mod tests {
720    use std::collections::HashMap;
721    use std::io::Read as _;
722    use std::path::{Path, PathBuf};
723    use std::sync::Arc;
724
725    use super::*;
726    use crate::portal::{OpenFileOutcome, PickRequest, SaveOutcome};
727
728    /// A person who chooses what the test put in front of them.
729    struct Chosen(PathBuf);
730
731    impl Person for Chosen {
732        fn choose(
733            &self,
734            _caller: &Caller,
735            _handle: String,
736            _question: &Question,
737        ) -> Result<Vec<PathBuf>, Asked> {
738            Ok(vec![self.0.clone()])
739        }
740    }
741
742    /// A host keeping what was chosen: a reference names it again, and nothing else does.
743    #[derive(Default)]
744    struct Kept(Mutex<HashMap<PathBuf, Granted>>);
745
746    impl Grants for Kept {
747        fn grant(
748            &self,
749            _caller: &Caller,
750            chosen: &Path,
751            choice: Choice,
752        ) -> Result<Granted, String> {
753            let name = chosen
754                .file_name()
755                .map(|name| name.to_string_lossy().into_owned())
756                .ok_or_else(|| "the choice names no file".to_owned())?;
757            let reference = Path::new("/run/tilo/chosen/records")
758                .join("test")
759                .join(&name);
760            let save_sibling = (choice == Choice::Save).then(|| {
761                let mut sibling = std::ffi::OsString::from(".");
762                sibling.push(&name);
763                sibling.push(".tilo-save");
764                sibling
765            });
766            let granted = Granted {
767                reference: reference.clone(),
768                name,
769                host: chosen.to_path_buf(),
770                choice,
771                save_sibling,
772            };
773            self.0
774                .lock()
775                .unwrap_or_else(std::sync::PoisonError::into_inner)
776                .insert(reference, granted.clone());
777            Ok(granted)
778        }
779
780        fn document(&self, _caller: &Caller, reference: &Path) -> Option<Granted> {
781            let kept = self
782                .0
783                .lock()
784                .unwrap_or_else(std::sync::PoisonError::into_inner);
785            kept.iter()
786                .find(|(given, _)| reference.starts_with(given))
787                .map(|(_, granted)| granted.clone())
788        }
789    }
790
791    struct NoOpen;
792
793    impl Opens for NoOpen {
794        fn open(&self, _workspace: &str, _uri: &str) -> Result<Option<()>, String> {
795            Ok(None)
796        }
797    }
798
799    #[test]
800    fn a_choice_hands_its_descriptor_and_a_reference_it_alone_reopens() {
801        let directory = tempfile::tempdir().unwrap();
802        let chosen = directory.path().join("plan.txt");
803        std::fs::write(&chosen, "Spring planting").unwrap();
804        let serving = Serving {
805            person: Some(Arc::new(Chosen(chosen))),
806            grants: Arc::new(Kept::default()),
807            opens: Arc::new(NoOpen),
808        };
809        let stream = pair(
810            serving,
811            "so.tilo.notes",
812            "5ba25f73-87c5-447f-a5a6-880dc4249a81",
813        )
814        .unwrap();
815        let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
816
817        // The chosen file comes as a descriptor opened with the person's rights, and a
818        // reference that names it again.
819        let opened = picker
820            .open_handle(PickRequest::open("Import a plan", "Import"))
821            .recv_timeout(tilo_test_env::hang_bound())
822            .unwrap();
823        let OpenFileOutcome::Opened(opened) = opened else {
824            panic!("the chosen file was not handed over");
825        };
826        assert_eq!(opened.display_name(), "plan.txt");
827        let reference = opened
828            .reference()
829            .expect("a reference names it")
830            .to_path_buf();
831        let mut file = opened.into_file();
832        let mut contents = String::new();
833        file.read_to_string(&mut contents).unwrap();
834        assert_eq!(contents, "Spring planting");
835
836        // The app reopens what it was given …
837        let reopened = picker
838            .reopen(&reference, false)
839            .recv_timeout(tilo_test_env::hang_bound())
840            .unwrap();
841        let OpenFileOutcome::Opened(reopened) = reopened else {
842            panic!("a reference the app was given reopens");
843        };
844        let mut file = reopened.into_file();
845        let mut contents = String::new();
846        file.read_to_string(&mut contents).unwrap();
847        assert_eq!(contents, "Spring planting");
848
849        // … and a reference, or a host path, it was never given opens nothing.
850        for never in [
851            PathBuf::from("/etc/passwd"),
852            directory.path().join("never.txt"),
853        ] {
854            let refused = picker
855                .reopen(&never, false)
856                .recv_timeout(tilo_test_env::hang_bound())
857                .unwrap();
858            assert!(
859                matches!(refused, OpenFileOutcome::Failed(_)),
860                "{} must not be reachable through the chooser",
861                never.display()
862            );
863        }
864    }
865
866    #[test]
867    fn a_save_writes_beside_the_file_and_commits_over_it() {
868        let directory = tempfile::tempdir().unwrap();
869        let destination = directory.path().join("report.txt");
870        let serving = Serving {
871            person: Some(Arc::new(Chosen(destination.clone()))),
872            grants: Arc::new(Kept::default()),
873            opens: Arc::new(NoOpen),
874        };
875        let stream = pair(
876            serving,
877            "so.tilo.notes",
878            "5ba25f73-87c5-447f-a5a6-880dc4249a81",
879        )
880        .unwrap();
881        let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
882
883        let saving = picker.save_contents(
884            PickRequest::save("Save the report", "Save", "report.txt"),
885            b"the report".to_vec(),
886        );
887        let outcome = saving.recv_timeout(tilo_test_env::hang_bound()).unwrap();
888        assert_eq!(outcome, SaveOutcome::Saved, "the chooser commits the save");
889        assert_eq!(std::fs::read(&destination).unwrap(), b"the report");
890
891        let mut left: Vec<_> = std::fs::read_dir(directory.path())
892            .unwrap()
893            .map(|entry| entry.unwrap().file_name())
894            .collect();
895        left.sort();
896        assert_eq!(
897            left,
898            ["report.txt"],
899            "the bytes are written beside the file and the file is the only thing left"
900        );
901    }
902}