use async_trait::async_trait;
use serde_json::Value;
use std::path::PathBuf;
use crate::error::{KxcError, Result};
#[async_trait]
pub trait Transport: Send {
async fn send_json(&mut self, doc: &Value) -> Result<()>;
async fn recv_json(&mut self) -> Result<Value>;
}
pub fn socket_candidates() -> Vec<PathBuf> {
let mut v = Vec::new();
let sock = "org.keepassxc.KeePassXC.BrowserServer";
if let Ok(dir) = std::env::var("XDG_RUNTIME_DIR") {
v.push(PathBuf::from(&dir).join(sock));
v.push(PathBuf::from(&dir).join("app/org.keepassxc.KeePassXC").join(sock));
v.push(PathBuf::from(&dir).join("kpxc_server"));
}
if let Ok(tmp) = std::env::var("TMPDIR") {
v.push(PathBuf::from(&tmp).join(sock)); }
v.push(PathBuf::from("/tmp").join(sock));
v
}
#[cfg(unix)]
pub mod unix {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::UnixStream;
pub struct UnixTransport {
stream: UnixStream,
buf: Vec<u8>,
}
impl UnixTransport {
pub async fn connect_auto() -> Result<Self> {
let candidates = socket_candidates();
for p in &candidates {
if let Ok(stream) = UnixStream::connect(p).await {
tracing::debug!(path = %p.display(), "connected to KeePassXC socket");
return Ok(Self { stream, buf: Vec::with_capacity(8192) });
}
}
let tried = candidates
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
Err(KxcError::SocketNotFound(tried))
}
pub async fn connect_path(p: &std::path::Path) -> Result<Self> {
let stream = UnixStream::connect(p).await?;
Ok(Self { stream, buf: Vec::with_capacity(8192) })
}
fn try_take_doc(&mut self) -> Option<Value> {
let mut iter = serde_json::Deserializer::from_slice(&self.buf).into_iter::<Value>();
match iter.next() {
Some(Ok(v)) => {
let consumed = iter.byte_offset();
self.buf.drain(..consumed);
Some(v)
}
_ => None,
}
}
}
#[async_trait]
impl Transport for UnixTransport {
async fn send_json(&mut self, doc: &Value) -> Result<()> {
let bytes = serde_json::to_vec(doc)?;
self.stream.write_all(&bytes).await?;
self.stream.flush().await?;
Ok(())
}
async fn recv_json(&mut self) -> Result<Value> {
loop {
if let Some(doc) = self.try_take_doc() {
return Ok(doc);
}
let mut chunk = [0u8; 8192];
let n = self.stream.read(&mut chunk).await?;
if n == 0 {
return Err(KxcError::ConnectionClosed);
}
self.buf.extend_from_slice(&chunk[..n]);
}
}
}
}
pub mod mock {
use super::*;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex};
type Responder = Box<dyn FnMut(&Value) -> Vec<Value> + Send>;
#[derive(Clone)]
pub struct MockTransport {
pub sent: Arc<Mutex<Vec<Value>>>,
pub to_receive: Arc<Mutex<VecDeque<Value>>>,
responder: Arc<Mutex<Option<Responder>>>,
}
impl MockTransport {
pub fn new() -> Self {
Self {
sent: Arc::new(Mutex::new(Vec::new())),
to_receive: Arc::new(Mutex::new(VecDeque::new())),
responder: Arc::new(Mutex::new(None)),
}
}
pub fn with_responder(f: impl FnMut(&Value) -> Vec<Value> + Send + 'static) -> Self {
let t = Self::new();
*t.responder.lock().unwrap() = Some(Box::new(f));
t
}
pub fn push_incoming(&self, v: Value) {
self.to_receive.lock().unwrap().push_back(v);
}
pub fn last_sent(&self) -> Option<Value> {
self.sent.lock().unwrap().last().cloned()
}
}
#[async_trait]
impl Transport for MockTransport {
async fn send_json(&mut self, doc: &Value) -> Result<()> {
self.sent.lock().unwrap().push(doc.clone());
if let Some(r) = self.responder.lock().unwrap().as_mut() {
let replies = r(doc);
let mut q = self.to_receive.lock().unwrap();
for v in replies {
q.push_back(v);
}
}
Ok(())
}
async fn recv_json(&mut self) -> Result<Value> {
self.to_receive
.lock()
.unwrap()
.pop_front()
.ok_or(KxcError::ConnectionClosed)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn candidates_are_nonempty_and_ordered() {
std::env::set_var("XDG_RUNTIME_DIR", "/run/user/1000");
let c = socket_candidates();
assert!(c.len() >= 3);
assert!(c[0].ends_with("org.keepassxc.KeePassXC.BrowserServer"));
}
}