Skip to main content

gasm_host/
consent.rs

1//! Player consent: the window runner asks before a game reaches outside itself, a
2//! network host (gasm:net, gasm:fetch) or saving files for the player (gasm:files).
3//! Four answers: this time (until the game ends), always (remembered), no (asked
4//! again next run) and never (remembered). Remembered answers live in
5//! `<data dir>/gasm/consent/<game>.txt`, one `allow <subject>` / `deny <subject>`
6//! line each; `gasm-run --forget-consent <game|all>` removes them.
7//!
8//! Requests wait while a question is open: a connection stays connecting, a fetch
9//! or a save pending, and each fails as a refused one would if the answer is no.
10//! Headless runs never ask (they deny what the command line didn't allow).
11
12use std::collections::{BTreeMap, VecDeque};
13use std::path::PathBuf;
14use std::sync::{Arc, Mutex};
15
16/// What a game asks for: `net:<host>` (`net:a.org,b.org` for a manifest's hosts,
17/// asked at once and answered for each), `save`, or `mod:<file>` (a mod whose
18/// manifest asks for hosts; allowing it allows them).
19pub type Subject = String;
20
21pub fn net_subject(host: &str) -> Subject {
22    format!("net:{host}")
23}
24pub const SAVE: &str = "save";
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
27pub enum Answer {
28    /// allowed until the game ends
29    ThisTime,
30    /// allowed, remembered
31    Always,
32    /// denied this time, asked again next run
33    No,
34    /// denied, remembered
35    Never,
36}
37
38#[derive(Debug)]
39pub struct Store {
40    file: Option<PathBuf>,
41    remembered: BTreeMap<Subject, bool>,
42    session: BTreeMap<Subject, bool>,
43    /// asked for and not answered yet, in order
44    questions: VecDeque<Subject>,
45    /// headless and tests: unanswered means no
46    ask: bool,
47    /// mod file -> the hosts its manifest asks for
48    mod_hosts: BTreeMap<String, Vec<String>>,
49}
50
51/// Shared by the host's gasm:net, gasm:fetch and gasm:files and the window runner.
52pub type Consent = Arc<Mutex<Store>>;
53
54impl Store {
55    /// A store that asks (the window runner), with this game's remembered answers.
56    pub fn open(game: &str) -> Store {
57        let file = crate::storage::data_root().map(|r| r.join("consent").join(format!("{game}.txt")));
58        let mut remembered = BTreeMap::new();
59        if let Some(text) = file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()) {
60            for line in text.lines() {
61                match line.trim().split_once(' ') {
62                    Some(("allow", s)) => _ = remembered.insert(s.to_owned(), true),
63                    Some(("deny", s)) => _ = remembered.insert(s.to_owned(), false),
64                    _ => {}
65                }
66            }
67        }
68        Store { file, remembered, session: BTreeMap::new(), questions: VecDeque::new(), ask: true, mod_hosts: BTreeMap::new() }
69    }
70
71    /// A store that never asks: unanswered is no (headless runs).
72    pub fn never_ask() -> Store {
73        Store { file: None, remembered: BTreeMap::new(), session: BTreeMap::new(), questions: VecDeque::new(), ask: false, mod_hosts: BTreeMap::new() }
74    }
75
76    pub fn shared(self) -> Consent {
77        Arc::new(Mutex::new(self))
78    }
79
80    /// The answer so far: Some(allowed), or None while the player hasn't answered
81    /// (the question is queued once).
82    pub fn check(&mut self, subject: &str) -> Option<bool> {
83        if let Some(&a) = self.session.get(subject).or_else(|| self.remembered.get(subject)) {
84            return Some(a);
85        }
86        if !self.ask {
87            return Some(false);
88        }
89        if !self.questions.iter().any(|q| q == subject) {
90            self.questions.push_back(subject.to_owned());
91        }
92        None
93    }
94
95    /// A manifest's hosts and saves, asked about before the game starts (one question
96    /// for the hosts not answered yet).
97    pub fn ask_up_front(&mut self, hosts: &[String], files: bool) {
98        let open: Vec<&str> = hosts.iter().map(String::as_str).filter(|h| self.answered(&net_subject(h)).is_none()).collect();
99        if !open.is_empty() {
100            self.queue(net_subject(&open.join(",")));
101        }
102        if files {
103            _ = self.check(SAVE);
104        }
105    }
106
107    /// A mod whose manifest asks for hosts: Some(allowed) if answered, else asked
108    /// (before the game starts) and None.
109    pub fn check_mod(&mut self, file: &str, hosts: &[String]) -> Option<bool> {
110        self.mod_hosts.insert(file.to_owned(), hosts.to_vec());
111        let subject = format!("mod:{file}");
112        let a = self.answered(&subject);
113        if a == Some(true) {
114            for h in hosts {
115                self.session.insert(net_subject(h), true);
116            }
117        }
118        if a.is_none() {
119            if !self.ask {
120                return Some(false);
121            }
122            self.queue(subject);
123        }
124        a
125    }
126
127    fn answered(&self, subject: &str) -> Option<bool> {
128        self.session.get(subject).or_else(|| self.remembered.get(subject)).copied()
129    }
130
131    fn queue(&mut self, subject: Subject) {
132        if self.ask && !self.questions.contains(&subject) {
133            self.questions.push_back(subject);
134        }
135    }
136
137    /// Whether questions are waiting (the window runner doesn't start a game meanwhile).
138    pub fn asking(&self) -> bool {
139        !self.questions.is_empty()
140    }
141
142    /// The hosts a mod's manifest asks for (for the question).
143    pub fn mod_hosts(&self, file: &str) -> &[String] {
144        self.mod_hosts.get(file).map_or(&[], Vec::as_slice)
145    }
146
147    /// The next question to put to the player.
148    pub fn question(&self) -> Option<&Subject> {
149        self.questions.front()
150    }
151
152    pub fn answer(&mut self, subject: &str, answer: Answer) {
153        self.questions.retain(|q| q != subject);
154        let allowed = matches!(answer, Answer::ThisTime | Answer::Always);
155        // a manifest's hosts: an answer for each; an allowed mod allows its hosts
156        let mut subjects: Vec<String> = match subject.strip_prefix("net:") {
157            Some(hosts) => hosts.split(',').map(net_subject).collect(),
158            None => vec![subject.to_owned()],
159        };
160        if let (Some(file), true) = (subject.strip_prefix("mod:"), allowed) {
161            for h in self.mod_hosts(file).to_vec() {
162                self.session.insert(net_subject(&h), true);
163            }
164        }
165        for s in subjects.drain(..) {
166            self.session.insert(s.clone(), allowed);
167            if matches!(answer, Answer::Always | Answer::Never) {
168                self.remembered.insert(s, allowed);
169            }
170        }
171        if matches!(answer, Answer::Always | Answer::Never) {
172            self.save();
173        }
174        eprintln!("[gasm] consent: {subject}: {}", match answer {
175            Answer::ThisTime => "allowed this time",
176            Answer::Always => "always allowed",
177            Answer::No => "denied this time",
178            Answer::Never => "never allowed",
179        });
180    }
181
182    fn save(&self) {
183        let Some(f) = &self.file else { return };
184        let text: String = self.remembered.iter().map(|(s, &a)| format!("{} {s}\n", if a { "allow" } else { "deny" })).collect();
185        let r = f.parent().map_or(Ok(()), std::fs::create_dir_all).and_then(|_| std::fs::write(f, text));
186        if let Err(e) = r {
187            eprintln!("[gasm] consent: {}: {e}", f.display());
188        }
189    }
190}
191
192/// `--forget-consent <game|all>`: remove remembered answers; what was removed.
193pub fn forget(game: &str) -> Result<String, String> {
194    let dir = crate::storage::data_root().map(|r| r.join("consent")).ok_or("no data directory")?;
195    if game == "all" {
196        return match std::fs::remove_dir_all(&dir) {
197            Ok(()) => Ok(format!("removed every remembered answer ({})", dir.display())),
198            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok("no remembered answers".into()),
199            Err(e) => Err(format!("{}: {e}", dir.display())),
200        };
201    }
202    let f = dir.join(format!("{game}.txt"));
203    match std::fs::remove_file(&f) {
204        Ok(()) => Ok(format!("removed the remembered answers for {game} ({})", f.display())),
205        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(format!("no remembered answers for {game}")),
206        Err(e) => Err(format!("{}: {e}", f.display())),
207    }
208}
209
210/// The question for the player, in words: what the game wants, and to what.
211pub fn describe(subject: &str) -> (&'static str, String) {
212    if let Some(hosts) = subject.strip_prefix("net:") {
213        return ("wants to connect to", hosts.replace(',', ", "));
214    }
215    if let Some(file) = subject.strip_prefix("mod:") {
216        return ("wants to load a mod that connects out", file.to_owned());
217    }
218    ("wants to save files for you", "in Pictures or Downloads".to_owned())
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224
225    #[test]
226    fn answers() {
227        let mut s = Store { file: None, remembered: BTreeMap::new(), session: BTreeMap::new(), questions: VecDeque::new(), ask: true, mod_hosts: BTreeMap::new() };
228        assert_eq!(s.check("net:a.org"), None);
229        assert_eq!(s.check("net:a.org"), None);
230        assert_eq!(s.check("save"), None);
231        assert_eq!(s.question().map(String::as_str), Some("net:a.org")); // asked once each, in order
232        s.answer("net:a.org", Answer::ThisTime);
233        assert_eq!(s.check("net:a.org"), Some(true));
234        assert_eq!(s.question().map(String::as_str), Some("save"));
235        s.answer("save", Answer::Never);
236        assert_eq!((s.check("save"), s.remembered.get("save")), (Some(false), Some(&false)));
237        assert_eq!(s.question(), None);
238        assert_eq!(Store::never_ask().check("net:b.org"), Some(false));
239    }
240
241    #[test]
242    fn up_front_and_mods() {
243        let mut s = Store::never_ask();
244        s.ask = true;
245        s.ask_up_front(&["a.org".into(), "b.org".into()], false);
246        assert_eq!(s.question().map(String::as_str), Some("net:a.org,b.org"));
247        s.answer("net:a.org,b.org", Answer::ThisTime);
248        assert_eq!((s.check("net:a.org"), s.check("net:b.org")), (Some(true), Some(true)));
249        assert_eq!(s.check_mod("roads.pck", &["c.org".into()]), None);
250        assert_eq!(s.question().map(String::as_str), Some("mod:roads.pck"));
251        s.answer("mod:roads.pck", Answer::ThisTime);
252        assert_eq!((s.check_mod("roads.pck", &["c.org".into()]), s.check("net:c.org")), (Some(true), Some(true)));
253        assert_eq!(Store::never_ask().check_mod("x.pck", &["d.org".into()]), Some(false));
254    }
255}