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                let choice = if write { granted.choice } else { Choice::Read };
507                File::from(open_document(&granted, choice).map_err(|_| NOT_CHOSEN)?)
508            } else {
509                if !matches!(granted.choice, Choice::Folder { .. }) {
510                    return Err(NOT_CHOSEN);
511                }
512                if write && !granted.choice.writes() {
513                    return Err(NOT_CHOSEN);
514                }
515                open_beneath(&granted.host, &relative, write)?
516            };
517            let name = relative.file_name().map_or_else(
518                || granted.name.clone(),
519                |name| name.to_string_lossy().into_owned(),
520            );
521            Ok((
522                OwnedFd::from(file),
523                HandedDocument {
524                    reference: reference.to_path_buf(),
525                    name,
526                },
527            ))
528        })();
529        match opened {
530            Ok((fd, document)) => (
531                Reply::Handed {
532                    id,
533                    documents: vec![document],
534                },
535                vec![crate::shell::Descriptor::from(fd)],
536            ),
537            Err(reason) => (failed(id, reason), Vec::new()),
538        }
539    }
540
541    /// A save's bytes are in the file beside it: rename that over the file the person chose.
542    fn saved(&self, id: u64, reference: &Path) -> Reply {
543        let renamed = (|| {
544            let caller = self.caller();
545            let granted = self
546                .serving
547                .grants
548                .document(&caller, reference)
549                .ok_or(NOT_CHOSEN)?;
550            if granted.choice != Choice::Save || granted.reference != reference {
551                return Err(NOT_CHOSEN);
552            }
553            let beside = granted.save_sibling.ok_or(NOT_CHOSEN)?;
554            std::fs::rename(granted.host.with_file_name(beside), &granted.host).map_err(|_| GONE)
555        })();
556        match renamed {
557            Ok(()) => Reply::Saved { id },
558            Err(reason) => failed(id, reason),
559        }
560    }
561
562    /// The host file a reference names, for opening it in an app: one the person chose for it.
563    fn opened_path(&self, path: &Path) -> Result<PathBuf, &'static str> {
564        let granted = self
565            .serving
566            .grants
567            .document(&self.caller(), path)
568            .ok_or(NOT_CHOSEN)?;
569        let within = path
570            .strip_prefix(&granted.reference)
571            .map_err(|_| NOT_CHOSEN)?;
572        if within.as_os_str().is_empty() {
573            return Ok(granted.host);
574        }
575        plain_relative(within).ok_or(NOT_CHOSEN)?;
576        // Inside a chosen folder, and only a folder.
577        if matches!(granted.choice, Choice::Folder { .. }) {
578            Ok(granted.host.join(within))
579        } else {
580            Err(NOT_CHOSEN)
581        }
582    }
583
584    /// Open `uri` the way a link the app asks to open goes: a file only as [`Self::opened_path`]
585    /// allows, anything else in the app that claims its scheme.
586    fn open_uri(&self, id: u64, uri: &str) -> Reply {
587        let Ok(parsed) = url::Url::parse(uri) else {
588            return failed(id, BAD_LINK);
589        };
590        if parsed.scheme() == "file" {
591            let Ok(path) = parsed.to_file_path() else {
592                return failed(id, BAD_LINK);
593            };
594            let host = match self.opened_path(&path) {
595                Ok(host) => host,
596                Err(reason) => return failed(id, reason),
597            };
598            let Some(uri) = file_uri(&host) else {
599                return failed(id, NOT_CHOSEN);
600            };
601            return match self.open(&uri) {
602                Ok(true) => Reply::Opened { id },
603                Ok(false) => failed(id, NOTHING_OPENS),
604                Err(reason) => failed(id, reason),
605            };
606        }
607        match self.open(uri) {
608            Ok(true) => Reply::Opened { id },
609            Ok(false) => Reply::Unclaimed { id },
610            Err(reason) => failed(id, reason),
611        }
612    }
613
614    /// Ask the host to open `uri` in the app's workspace: whether an app took it.
615    fn open(&self, uri: &str) -> Result<bool, &'static str> {
616        match self.serving.opens.open(&self.workspace, uri) {
617            Ok(opened) => Ok(opened.is_some()),
618            Err(error) => {
619                tracing::warn!(app = %self.app, %error, "what an app asked to open did not open");
620                Err(DID_NOT_OPEN)
621            }
622        }
623    }
624}
625
626/// The open descriptor for a chosen document, as `choice` gives it: a file to read or write, or a
627/// folder.
628fn open_document(granted: &Granted, choice: Choice) -> Result<OwnedFd, std::io::Error> {
629    let file = match choice {
630        Choice::Read => crate::portal::open_regular_file(&granted.host)?,
631        Choice::Folder { .. } => crate::portal::open_directory_handle(&granted.host)?,
632        Choice::Save => open_for_save(granted)?,
633    };
634    Ok(OwnedFd::from(file))
635}
636
637fn open_for_save(granted: &Granted) -> std::io::Result<File> {
638    let beside = granted.save_sibling.clone().ok_or_else(|| {
639        std::io::Error::new(
640            std::io::ErrorKind::InvalidInput,
641            "a save writes beside a file",
642        )
643    })?;
644    OpenOptions::new()
645        .write(true)
646        .create(true)
647        .truncate(true)
648        .mode(0o644)
649        .custom_flags(libc::O_NOFOLLOW | libc::O_CLOEXEC)
650        .open(granted.host.with_file_name(beside))
651}
652
653/// `relative` with every component a plain name: what opens beneath a chosen folder, never a
654/// name that climbs out of it.
655fn plain_relative(relative: &Path) -> Option<PathBuf> {
656    let mut plain = PathBuf::new();
657    for component in relative.components() {
658        match component {
659            Component::Normal(name) => plain.push(name),
660            _ => return None,
661        }
662    }
663    Some(plain)
664}
665
666/// Open a file inside a chosen folder, walking it a component at a time with `openat`, never
667/// following a link: the person chose the folder and what is under it, not where a link points.
668fn open_beneath(root: &Path, relative: &Path, write: bool) -> Result<File, &'static str> {
669    let directory = crate::portal::open_directory_handle(root).map_err(|_| NOT_CHOSEN)?;
670    let mut current = OwnedFd::from(directory);
671    let parts: Vec<&std::ffi::OsStr> = relative.iter().collect();
672    let count = parts.len();
673    for (at, part) in parts.into_iter().enumerate() {
674        let last = at.saturating_add(1) == count;
675        let flags = if last && write {
676            libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOFOLLOW | libc::O_CLOEXEC
677        } else if last {
678            libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC
679        } else {
680            libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC
681        };
682        let name = CString::new(part.as_bytes()).map_err(|_| NOT_CHOSEN)?;
683        // SAFETY: `openat` reads the descriptor and the name, both valid for the call.
684        let fd = unsafe { libc::openat(current.as_raw_fd(), name.as_ptr(), flags, 0o644) };
685        if fd < 0 {
686            return Err(NOT_CHOSEN);
687        }
688        // SAFETY: `openat` just returned this descriptor, which nothing else owns.
689        current = unsafe { OwnedFd::from_raw_fd(fd) };
690    }
691    let file = File::from(current);
692    if write && !file.metadata().map_err(|_| NOT_CHOSEN)?.is_file() {
693        return Err(NOT_CHOSEN);
694    }
695    Ok(file)
696}
697
698/// `path` as an RFC 8089 file URI.
699fn file_uri(path: &Path) -> Option<String> {
700    url::Url::from_file_path(path).ok().map(String::from)
701}
702
703fn failed(id: u64, reason: &str) -> Reply {
704    Reply::Failed {
705        id,
706        reason: reason.to_owned(),
707    }
708}
709
710#[cfg(all(test, unix))]
711mod tests {
712    use std::collections::HashMap;
713    use std::io::Read as _;
714    use std::path::{Path, PathBuf};
715    use std::sync::Arc;
716
717    use super::*;
718    use crate::portal::{OpenFileOutcome, PickRequest, SaveOutcome};
719
720    /// A person who chooses what the test put in front of them.
721    struct Chosen(PathBuf);
722
723    impl Person for Chosen {
724        fn choose(
725            &self,
726            _caller: &Caller,
727            _handle: String,
728            _question: &Question,
729        ) -> Result<Vec<PathBuf>, Asked> {
730            Ok(vec![self.0.clone()])
731        }
732    }
733
734    /// A host keeping what was chosen: a reference names it again, and nothing else does.
735    #[derive(Default)]
736    struct Kept(Mutex<HashMap<PathBuf, Granted>>);
737
738    impl Grants for Kept {
739        fn grant(
740            &self,
741            _caller: &Caller,
742            chosen: &Path,
743            choice: Choice,
744        ) -> Result<Granted, String> {
745            let name = chosen
746                .file_name()
747                .map(|name| name.to_string_lossy().into_owned())
748                .ok_or_else(|| "the choice names no file".to_owned())?;
749            let reference = Path::new("/run/tilo/chosen/records")
750                .join("test")
751                .join(&name);
752            let save_sibling = (choice == Choice::Save).then(|| {
753                let mut sibling = std::ffi::OsString::from(".");
754                sibling.push(&name);
755                sibling.push(".tilo-save");
756                sibling
757            });
758            let granted = Granted {
759                reference: reference.clone(),
760                name,
761                host: chosen.to_path_buf(),
762                choice,
763                save_sibling,
764            };
765            self.0
766                .lock()
767                .unwrap_or_else(std::sync::PoisonError::into_inner)
768                .insert(reference, granted.clone());
769            Ok(granted)
770        }
771
772        fn document(&self, _caller: &Caller, reference: &Path) -> Option<Granted> {
773            let kept = self
774                .0
775                .lock()
776                .unwrap_or_else(std::sync::PoisonError::into_inner);
777            kept.iter()
778                .find(|(given, _)| reference.starts_with(given))
779                .map(|(_, granted)| granted.clone())
780        }
781    }
782
783    struct NoOpen;
784
785    impl Opens for NoOpen {
786        fn open(&self, _workspace: &str, _uri: &str) -> Result<Option<()>, String> {
787            Ok(None)
788        }
789    }
790
791    #[test]
792    fn a_choice_hands_its_descriptor_and_a_reference_it_alone_reopens() {
793        let directory = tempfile::tempdir().unwrap();
794        let chosen = directory.path().join("plan.txt");
795        std::fs::write(&chosen, "Spring planting").unwrap();
796        let serving = Serving {
797            person: Some(Arc::new(Chosen(chosen))),
798            grants: Arc::new(Kept::default()),
799            opens: Arc::new(NoOpen),
800        };
801        let stream = pair(
802            serving,
803            "so.tilo.notes",
804            "5ba25f73-87c5-447f-a5a6-880dc4249a81",
805        )
806        .unwrap();
807        let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
808
809        // The chosen file comes as a descriptor opened with the person's rights, and a
810        // reference that names it again.
811        let opened = picker
812            .open_handle(PickRequest::open("Import a plan", "Import"))
813            .recv_timeout(tilo_test_env::hang_bound())
814            .unwrap();
815        let OpenFileOutcome::Opened(opened) = opened else {
816            panic!("the chosen file was not handed over");
817        };
818        assert_eq!(opened.display_name(), "plan.txt");
819        let reference = opened
820            .reference()
821            .expect("a reference names it")
822            .to_path_buf();
823        let mut file = opened.into_file();
824        let mut contents = String::new();
825        file.read_to_string(&mut contents).unwrap();
826        assert_eq!(contents, "Spring planting");
827
828        // The app reopens what it was given …
829        let reopened = picker
830            .reopen(&reference, false)
831            .recv_timeout(tilo_test_env::hang_bound())
832            .unwrap();
833        let OpenFileOutcome::Opened(reopened) = reopened else {
834            panic!("a reference the app was given reopens");
835        };
836        let mut file = reopened.into_file();
837        let mut contents = String::new();
838        file.read_to_string(&mut contents).unwrap();
839        assert_eq!(contents, "Spring planting");
840
841        // … and a reference, or a host path, it was never given opens nothing.
842        for never in [
843            PathBuf::from("/etc/passwd"),
844            directory.path().join("never.txt"),
845        ] {
846            let refused = picker
847                .reopen(&never, false)
848                .recv_timeout(tilo_test_env::hang_bound())
849                .unwrap();
850            assert!(
851                matches!(refused, OpenFileOutcome::Failed(_)),
852                "{} must not be reachable through the chooser",
853                never.display()
854            );
855        }
856    }
857
858    #[test]
859    fn a_save_writes_beside_the_file_and_commits_over_it() {
860        let directory = tempfile::tempdir().unwrap();
861        let destination = directory.path().join("report.txt");
862        let serving = Serving {
863            person: Some(Arc::new(Chosen(destination.clone()))),
864            grants: Arc::new(Kept::default()),
865            opens: Arc::new(NoOpen),
866        };
867        let stream = pair(
868            serving,
869            "so.tilo.notes",
870            "5ba25f73-87c5-447f-a5a6-880dc4249a81",
871        )
872        .unwrap();
873        let picker = crate::shell::picker(stream, crate::unavailable_picker()).unwrap();
874
875        let saving = picker.save_contents(
876            PickRequest::save("Save the report", "Save", "report.txt"),
877            b"the report".to_vec(),
878        );
879        let outcome = saving.recv_timeout(tilo_test_env::hang_bound()).unwrap();
880        assert_eq!(outcome, SaveOutcome::Saved, "the chooser commits the save");
881        assert_eq!(std::fs::read(&destination).unwrap(), b"the report");
882
883        let mut left: Vec<_> = std::fs::read_dir(directory.path())
884            .unwrap()
885            .map(|entry| entry.unwrap().file_name())
886            .collect();
887        left.sort();
888        assert_eq!(
889            left,
890            ["report.txt"],
891            "the bytes are written beside the file and the file is the only thing left"
892        );
893    }
894}