use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::HashSet;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::pin::Pin;
use std::rc::Rc;
use std::task::Context;
use std::task::Poll;
use tokio::sync::Notify;
use crate::gate::GateExt;
use crate::gate::GateToken;
use crate::gate::NetGate;
use crate::gate::Reach;
use crate::gate::ReachKey;
use crate::gate::Verdict;
use crate::gate::describe;
use crate::gate::interfaces_pending;
use crate::rt::Cancel;
use crate::rt::OrCancel;
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Question {
Reach(ReachKey),
Interfaces,
}
pub(crate) struct GateCache {
gate: Rc<dyn NetGate>,
answers: RefCell<HashMap<Question, Verdict>>,
asking: RefCell<HashSet<Question>>,
changed: Notify,
on_answer: RefCell<Option<Rc<dyn Fn()>>>,
cancel: Cancel,
}
impl GateCache {
pub(crate) fn new(gate: Rc<dyn NetGate>) -> Rc<Self> {
Rc::new(Self {
gate,
answers: RefCell::new(HashMap::new()),
asking: RefCell::new(HashSet::new()),
changed: Notify::new(),
on_answer: RefCell::new(None),
cancel: Cancel::new(),
})
}
pub(crate) fn set_on_answer(&self, f: impl Fn() + 'static) {
*self.on_answer.borrow_mut() = Some(Rc::new(f));
}
pub(crate) fn close(&self) {
self.cancel.cancel();
self.changed.notify_waiters();
}
pub(crate) fn lookup(
self: &Rc<Self>,
reach: &Reach,
) -> Option<Result<GateToken, String>> {
let question = Question::Reach(ReachKey::from(reach));
let verdict = self.answered(&question).or_else(|| {
catch(|| self.gate.decide(reach)).unwrap_or_else(|| {
Some(Verdict::Deny(format!(
"The permission gate failed for \"{}\"",
describe(reach)
)))
})
});
match verdict {
Some(Verdict::Allow) => Some(Ok(GateToken::new(reach.clone()))),
Some(Verdict::Deny(why)) => Some(Err(why)),
None => {
self.start_ask(question, Some(reach.clone()));
None
}
}
}
pub(crate) fn lookup_interfaces(
self: &Rc<Self>,
) -> Option<Result<(), String>> {
let question = Question::Interfaces;
let verdict = self.answered(&question).or_else(|| {
catch(|| self.gate.interfaces())
.unwrap_or_else(|| Some(interfaces_pending()))
});
match verdict {
Some(v) => Some(v.into_result()),
None => {
self.start_ask(question, None);
None
}
}
}
pub(crate) async fn verdict(
self: &Rc<Self>,
reach: Reach,
) -> Result<GateToken, String> {
loop {
let notified = self.changed.notified();
let mut notified = std::pin::pin!(notified);
notified.as_mut().enable();
if let Some(answer) = self.lookup(&reach) {
return answer;
}
if self.cancel.is_cancelled() {
return Err(closed());
}
notified.await;
}
}
pub(crate) async fn interfaces(self: &Rc<Self>) -> Result<(), String> {
loop {
let notified = self.changed.notified();
let mut notified = std::pin::pin!(notified);
notified.as_mut().enable();
if let Some(answer) = self.lookup_interfaces() {
return answer;
}
if self.cancel.is_cancelled() {
return Err(closed());
}
notified.await;
}
}
fn answered(&self, question: &Question) -> Option<Verdict> {
self.answers.borrow().get(question).cloned()
}
fn start_ask(self: &Rc<Self>, question: Question, reach: Option<Reach>) {
if self.cancel.is_cancelled()
|| !self.asking.borrow_mut().insert(question.clone())
{
return;
}
let this = self.clone();
let cancel = self.cancel.clone();
crate::rt::spawn(
async move {
let timeout = this.gate.ask_timeout();
let what = match &reach {
Some(r) => format!("net access to \"{}\"", describe(r)),
None => "the network interfaces".to_string(),
};
let future = catch(|| match reach {
Some(r) => this.gate.ask(r),
None => this.gate.ask_interfaces(),
});
let verdict = match future {
None => Verdict::Deny(format!("The permission gate failed for {what}")),
Some(future) => {
match tokio::time::timeout(timeout, CatchUnwind(future)).await {
Ok(Some(verdict)) => verdict,
Ok(None) => {
Verdict::Deny(format!("The permission gate failed for {what}"))
}
Err(_) => Verdict::Deny(format!(
"The permission request for {what} was not answered within {} ms",
timeout.as_millis()
)),
}
}
};
this.asking.borrow_mut().remove(&question);
this.answers.borrow_mut().insert(question, verdict);
this.changed.notify_waiters();
let on_answer = this.on_answer.borrow().clone();
if let Some(f) = on_answer {
f();
}
}
.or_cancel(cancel),
);
}
}
fn closed() -> String {
"The connection closed before the permission was answered".to_string()
}
fn catch<T>(f: impl FnOnce() -> T) -> Option<T> {
std::panic::catch_unwind(AssertUnwindSafe(f)).ok()
}
struct CatchUnwind<F>(F);
impl<F: Future + Unpin> Future for CatchUnwind<F> {
type Output = Option<F::Output>;
fn poll(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Self::Output> {
let inner = &mut self.0;
match std::panic::catch_unwind(AssertUnwindSafe(|| {
Pin::new(&mut *inner).poll(cx)
})) {
Ok(Poll::Ready(v)) => Poll::Ready(Some(v)),
Ok(Poll::Pending) => Poll::Pending,
Err(_) => Poll::Ready(None),
}
}
}
pub(crate) enum Verdicts<'a> {
Cache(Rc<GateCache>),
Sync(&'a dyn NetGate),
}
impl Verdicts<'_> {
pub(crate) async fn reach(&self, reach: Reach) -> Result<GateToken, String> {
match self {
Verdicts::Cache(cache) => cache.verdict(reach).await,
Verdicts::Sync(gate) => {
gate.check(&reach).map(|()| GateToken::new(reach))
}
}
}
pub(crate) async fn interfaces(&self) -> Result<(), String> {
match self {
Verdicts::Cache(cache) => cache.interfaces().await,
Verdicts::Sync(gate) => gate.check_interfaces(),
}
}
}