aerogramme/aero-proto/src/dav.rs

835 lines
31 KiB
Rust
Raw Normal View History

2024-02-26 22:59:29 +00:00
use std::net::SocketAddr;
2024-03-13 14:45:36 +00:00
use std::sync::Arc;
2024-02-26 22:59:29 +00:00
2024-02-27 00:05:51 +00:00
use anyhow::{anyhow, Result};
use base64::Engine;
2024-02-26 22:59:29 +00:00
use hyper::service::service_fn;
use hyper::{Request, Response, body::Bytes};
use hyper::server::conn::http1 as http;
2024-03-16 15:48:46 +00:00
use hyper::rt::{Read, Write};
use hyper::body::Incoming;
2024-02-26 22:59:29 +00:00
use hyper_util::rt::TokioIo;
use http_body_util::Full;
use futures::stream::{FuturesUnordered, StreamExt};
use tokio::net::TcpListener;
use tokio::sync::watch;
2024-03-13 14:45:36 +00:00
use tokio_rustls::TlsAcceptor;
use tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncWrite};
use rustls_pemfile::{certs, private_key};
2024-02-26 22:59:29 +00:00
2024-03-13 14:45:36 +00:00
use aero_user::config::{DavConfig, DavUnsecureConfig};
2024-03-08 08:55:33 +00:00
use aero_user::login::ArcLoginProvider;
use aero_collections::user::User;
2024-03-17 09:31:05 +00:00
use aero_dav::types as dav;
2024-03-18 11:00:40 +00:00
use aero_dav::caltypes as cal;
2024-03-19 16:36:32 +00:00
use aero_dav::acltypes as acl;
use aero_dav::realization::{All, self as all};
2024-03-17 09:31:05 +00:00
use aero_dav::xml as dxml;
2024-02-26 22:59:29 +00:00
2024-03-20 16:31:54 +00:00
type ArcUser = std::sync::Arc<User>;
2024-02-26 22:59:29 +00:00
pub struct Server {
bind_addr: SocketAddr,
login_provider: ArcLoginProvider,
2024-03-13 14:45:36 +00:00
tls: Option<TlsAcceptor>,
2024-02-26 22:59:29 +00:00
}
pub fn new_unsecure(config: DavUnsecureConfig, login: ArcLoginProvider) -> Server {
Server {
bind_addr: config.bind_addr,
login_provider: login,
2024-03-13 14:45:36 +00:00
tls: None,
2024-02-26 22:59:29 +00:00
}
}
2024-03-13 14:45:36 +00:00
pub fn new(config: DavConfig, login: ArcLoginProvider) -> Result<Server> {
let loaded_certs = certs(&mut std::io::BufReader::new(std::fs::File::open(
config.certs,
)?))
.collect::<Result<Vec<_>, _>>()?;
let loaded_key = private_key(&mut std::io::BufReader::new(std::fs::File::open(
config.key,
)?))?
.unwrap();
let tls_config = rustls::ServerConfig::builder()
.with_no_client_auth()
.with_single_cert(loaded_certs, loaded_key)?;
let acceptor = TlsAcceptor::from(Arc::new(tls_config));
Ok(Server {
bind_addr: config.bind_addr,
login_provider: login,
tls: Some(acceptor),
})
}
trait Stream: Read + Write + Send + Unpin {}
impl<T: Unpin + AsyncRead + AsyncWrite + Send> Stream for TokioIo<T> {}
2024-02-26 22:59:29 +00:00
impl Server {
pub async fn run(self: Self, mut must_exit: watch::Receiver<bool>) -> Result<()> {
let tcp = TcpListener::bind(self.bind_addr).await?;
tracing::info!("DAV server listening on {:#}", self.bind_addr);
let mut connections = FuturesUnordered::new();
while !*must_exit.borrow() {
let wait_conn_finished = async {
if connections.is_empty() {
futures::future::pending().await
} else {
connections.next().await
}
};
let (socket, remote_addr) = tokio::select! {
a = tcp.accept() => a?,
_ = wait_conn_finished => continue,
_ = must_exit.changed() => continue,
};
2024-02-27 18:30:51 +00:00
tracing::info!("Accepted connection from {}", remote_addr);
2024-03-13 14:45:36 +00:00
let stream = match self.build_stream(socket).await {
Ok(v) => v,
Err(e) => {
tracing::error!(err=?e, "TLS acceptor failed");
continue
}
};
2024-02-27 00:05:51 +00:00
let login = self.login_provider.clone();
let conn = tokio::spawn(async move {
2024-02-26 22:59:29 +00:00
//@FIXME should create a generic "public web" server on which "routers" could be
//abitrarily bound
//@FIXME replace with a handler supporting http2 and TLS
2024-03-13 14:45:36 +00:00
2024-02-27 00:05:51 +00:00
match http::Builder::new().serve_connection(stream, service_fn(|req: Request<hyper::body::Incoming>| {
let login = login.clone();
2024-03-13 14:45:36 +00:00
tracing::info!("{:?} {:?}", req.method(), req.uri());
2024-03-20 13:46:07 +00:00
async {
match auth(login, req).await {
Ok(v) => Ok(v),
Err(e) => {
tracing::error!(err=?e, "internal error");
Response::builder()
.status(500)
.body(text_body("Internal error"))
},
}
}
2024-02-27 00:05:51 +00:00
})).await {
2024-02-26 22:59:29 +00:00
Err(e) => tracing::warn!(err=?e, "connection failed"),
Ok(()) => tracing::trace!("connection terminated with success"),
}
});
connections.push(conn);
}
drop(tcp);
2024-02-27 18:30:51 +00:00
tracing::info!("Server shutting down, draining remaining connections...");
2024-02-26 22:59:29 +00:00
while connections.next().await.is_some() {}
Ok(())
}
2024-03-13 14:45:36 +00:00
async fn build_stream(&self, socket: TcpStream) -> Result<Box<dyn Stream>> {
match self.tls.clone() {
Some(acceptor) => {
let stream = acceptor.accept(socket).await?;
Ok(Box::new(TokioIo::new(stream)))
}
None => Ok(Box::new(TokioIo::new(socket))),
}
}
2024-02-26 22:59:29 +00:00
}
2024-03-16 15:48:46 +00:00
use http_body_util::BodyExt;
2024-02-27 18:30:51 +00:00
//@FIXME We should not support only BasicAuth
2024-02-27 00:05:51 +00:00
async fn auth(
login: ArcLoginProvider,
2024-03-16 15:48:46 +00:00
req: Request<Incoming>,
) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
2024-03-13 14:45:36 +00:00
let auth_val = match req.headers().get(hyper::header::AUTHORIZATION) {
2024-02-27 00:05:51 +00:00
Some(hv) => hv.to_str()?,
2024-03-13 14:45:36 +00:00
None => {
tracing::info!("Missing authorization field");
return Ok(Response::builder()
.status(401)
.header("WWW-Authenticate", "Basic realm=\"Aerogramme\"")
2024-03-16 15:48:46 +00:00
.body(text_body("Missing Authorization field"))?)
2024-03-13 14:45:36 +00:00
},
2024-02-27 00:05:51 +00:00
};
let b64_creds_maybe_padded = match auth_val.split_once(" ") {
Some(("Basic", b64)) => b64,
2024-03-13 14:45:36 +00:00
_ => {
tracing::info!("Unsupported authorization field");
return Ok(Response::builder()
.status(400)
2024-03-16 15:48:46 +00:00
.body(text_body("Unsupported Authorization field"))?)
2024-03-13 14:45:36 +00:00
},
2024-02-27 00:05:51 +00:00
};
// base64urlencoded may have trailing equals, base64urlsafe has not
// theoretically authorization is padded but "be liberal in what you accept"
let b64_creds_clean = b64_creds_maybe_padded.trim_end_matches('=');
// Decode base64
let creds = base64::engine::general_purpose::STANDARD_NO_PAD.decode(b64_creds_clean)?;
let str_creds = std::str::from_utf8(&creds)?;
// Split username and password
let (username, password) = str_creds
.split_once(':')
.ok_or(anyhow!("Missing colon in Authorization, can't split decoded value into a username/password pair"))?;
// Call login provider
2024-02-27 17:33:49 +00:00
let creds = match login.login(username, password).await {
Ok(c) => c,
2024-03-13 14:45:36 +00:00
Err(_) => {
tracing::info!(user=username, "Wrong credentials");
return Ok(Response::builder()
.status(401)
.header("WWW-Authenticate", "Basic realm=\"Aerogramme\"")
2024-03-16 15:48:46 +00:00
.body(text_body("Wrong credentials"))?)
2024-03-13 14:45:36 +00:00
},
2024-02-27 17:33:49 +00:00
};
2024-02-27 18:30:51 +00:00
// Build a user
let user = User::new(username.into(), creds).await?;
2024-02-27 00:05:51 +00:00
// Call router with user
2024-02-27 18:30:51 +00:00
router(user, req).await
2024-02-27 00:05:51 +00:00
}
/// Path is a voluntarily feature limited
/// compared to the expressiveness of a UNIX path
/// For example getting parent with ../ is not supported, scheme is not supported, etc.
/// More complex support could be added later if needed by clients
enum Path<'a> {
Abs(Vec<&'a str>),
Rel(Vec<&'a str>),
}
impl<'a> Path<'a> {
fn new(path: &'a str) -> Result<Self> {
// This check is naive, it does not aim at detecting all fully qualified
// URL or protect from any attack, its only goal is to help debugging.
if path.starts_with("http://") || path.starts_with("https://") {
anyhow::bail!("Full URL are not supported")
}
let path_segments: Vec<_> = path.split("/").filter(|s| *s != "" && *s != ".").collect();
if path.starts_with("/") {
return Ok(Path::Abs(path_segments))
}
Ok(Path::Rel(path_segments))
}
}
2024-03-16 15:48:46 +00:00
async fn router(user: std::sync::Arc<User>, req: Request<Incoming>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
let path = req.uri().path().to_string();
let path_segments: Vec<_> = path.split("/").filter(|s| *s != "").collect();
let method = req.method().as_str().to_uppercase();
2024-03-20 13:46:07 +00:00
let node = match (RootNode {}).fetch(&user, &path_segments) {
2024-03-18 14:04:46 +00:00
Ok(v) => v,
Err(e) => {
tracing::warn!(err=?e, "dav node fetch failed");
return Ok(Response::builder()
.status(404)
.body(text_body("Resource not found"))?)
}
};
2024-03-16 15:48:46 +00:00
2024-03-18 14:04:46 +00:00
match method.as_str() {
"OPTIONS" => return Ok(Response::builder()
2024-03-17 09:31:05 +00:00
.status(200)
.header("DAV", "1")
.header("Allow", "HEAD,GET,PUT,OPTIONS,DELETE,PROPFIND,PROPPATCH,MKCOL,COPY,MOVE,LOCK,UNLOCK,MKCALENDAR,REPORT")
2024-03-17 09:31:05 +00:00
.body(text_body(""))?),
2024-03-18 15:14:38 +00:00
"HEAD" | "GET" => {
tracing::warn!("HEAD+GET not correctly implemented");
return Ok(Response::builder()
2024-03-18 21:56:49 +00:00
.status(404)
2024-03-18 15:14:38 +00:00
.body(text_body(""))?)
},
2024-03-18 14:04:46 +00:00
"PROPFIND" => propfind(user, req, node).await,
"REPORT" => report(user, req, node).await,
2024-02-27 18:30:51 +00:00
_ => return Ok(Response::builder()
2024-03-16 15:48:46 +00:00
.status(501)
.body(text_body("HTTP Method not implemented"))?),
2024-02-26 22:59:29 +00:00
}
}
2024-02-28 09:20:28 +00:00
// <D:propfind xmlns:D='DAV:' xmlns:A='http://apple.com/ns/ical/'>
// <D:prop>
// <D:getcontenttype/>
// <D:resourcetype/>
// <D:displayname/>
// <A:calendar-color/>
// </D:prop>
// </D:propfind>
// <D:propfind xmlns:D='DAV:' xmlns:A='http://apple.com/ns/ical/' xmlns:C='urn:ietf:params:xml:ns:caldav'>
// <D:prop>
// <D:resourcetype/>
// <D:owner/>
// <D:displayname/>
// <D:current-user-principal/>
// <D:current-user-privilege-set/>
// <A:calendar-color/>
// <C:calendar-home-set/>
// </D:prop>
// </D:propfind>
// <D:propfind xmlns:D='DAV:' xmlns:C='urn:ietf:params:xml:ns:caldav' xmlns:CS='http://calendarserver.org/ns/'>
// <D:prop>
// <D:resourcetype/>
// <D:owner/>
// <D:current-user-principal/>
// <D:current-user-privilege-set/>
// <D:supported-report-set/>
// <C:supported-calendar-component-set/>
// <CS:getctag/>
// </D:prop>
// </D:propfind>
2024-03-18 15:14:38 +00:00
// <C:calendar-multiget xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:caldav">
// <D:prop>
// <D:getetag/>
// <C:calendar-data/>
// </D:prop>
// <D:href>/alice/calendar/personal/something.ics</D:href>
// </C:calendar-multiget>
2024-03-19 16:36:32 +00:00
const ALLPROP: [dav::PropertyRequest<All>; 10] = [
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::CreationDate,
2024-03-18 11:00:40 +00:00
dav::PropertyRequest::DisplayName,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::GetContentLanguage,
dav::PropertyRequest::GetContentLength,
dav::PropertyRequest::GetContentType,
dav::PropertyRequest::GetEtag,
dav::PropertyRequest::GetLastModified,
dav::PropertyRequest::LockDiscovery,
2024-03-18 11:00:40 +00:00
dav::PropertyRequest::ResourceType,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::SupportedLock,
2024-03-18 11:00:40 +00:00
];
2024-03-16 15:48:46 +00:00
// ---------- Building objects
async fn propfind(user: std::sync::Arc<User>, req: Request<Incoming>, base_node: Box<dyn DavNode>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
2024-03-18 11:00:40 +00:00
let depth = depth(&req);
if matches!(depth, dav::Depth::Infinity) {
return Ok(Response::builder()
.status(501)
.body(text_body("Depth: Infinity not implemented"))?)
}
2024-03-18 21:56:49 +00:00
let status = hyper::StatusCode::from_u16(207)?;
2024-03-18 11:00:40 +00:00
2024-03-17 09:31:05 +00:00
// A client may choose not to submit a request body. An empty PROPFIND
// request body MUST be treated as if it were an 'allprop' request.
// @FIXME here we handle any invalid data as an allprop, an empty request is thus correctly
// handled, but corrupted requests are also silently handled as allprop.
2024-03-19 16:36:32 +00:00
let propfind = deserialize::<dav::PropFind<All>>(req).await.unwrap_or_else(|_| dav::PropFind::<All>::AllProp(None));
2024-03-17 09:31:05 +00:00
tracing::debug!(recv=?propfind, "inferred propfind request");
// Collect nodes as PROPFIND is not limited at the targeted node
let mut nodes = vec![];
if matches!(depth, dav::Depth::One | dav::Depth::Infinity) {
nodes.extend(base_node.children(&user));
2024-03-17 09:31:05 +00:00
}
nodes.push(base_node);
2024-03-16 15:48:46 +00:00
// Expand properties request
2024-03-17 09:31:05 +00:00
let propname = match propfind {
dav::PropFind::PropName => None,
dav::PropFind::AllProp(None) => Some(dav::PropName(ALLPROP.to_vec())),
2024-03-17 09:31:05 +00:00
dav::PropFind::AllProp(Some(dav::Include(mut include))) => {
2024-03-18 15:14:38 +00:00
include.extend_from_slice(&ALLPROP);
Some(dav::PropName(include))
2024-03-17 09:31:05 +00:00
},
dav::PropFind::Prop(inner) => Some(inner),
2024-03-17 09:31:05 +00:00
};
// Not Found is currently impossible considering the way we designed this function
let not_found = vec![];
serialize(status, multistatus(&user, nodes, not_found, propname))
}
async fn report(user: std::sync::Arc<User>, req: Request<Incoming>, node: Box<dyn DavNode>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
let status = hyper::StatusCode::from_u16(207)?;
2024-03-20 16:31:54 +00:00
let report = match deserialize::<cal::Report<All>>(req).await {
Ok(v) => v,
Err(e) => {
tracing::error!(err=?e, "unable to decode REPORT body");
return Ok(Response::builder()
.status(400)
.body(text_body("Bad request"))?)
}
};
// Multiget is really like a propfind where Depth: 0|1|Infinity is replaced by an arbitrary
// list of URLs
let multiget = match report {
cal::Report::Multiget(m) => m,
_ => return Ok(Response::builder()
.status(501)
.body(text_body("Not implemented"))?),
};
// Getting the list of nodes
2024-03-20 13:46:07 +00:00
let (ok_node, not_found): (Vec<_>, Vec<_>) = multiget.href.into_iter().map(|h| match Path::new(h.0.as_str()) {
Ok(Path::Abs(p)) => RootNode{}.fetch(&user, p.as_slice()).or(Err(h)),
Ok(Path::Rel(p)) => node.fetch(&user, p.as_slice()).or(Err(h)),
Err(_) => Err(h),
}).partition(|v| matches!(v, Result::Ok(_)));
let ok_node = ok_node.into_iter().filter_map(|v| v.ok()).collect();
let not_found = not_found.into_iter().filter_map(|v| v.err()).collect();
// Getting props
let props = match multiget.selector {
None | Some(cal::CalendarSelector::AllProp) => Some(dav::PropName(ALLPROP.to_vec())),
Some(cal::CalendarSelector::PropName) => None,
Some(cal::CalendarSelector::Prop(inner)) => Some(inner),
};
2024-03-20 13:46:07 +00:00
serialize(status, multistatus(&user, ok_node, not_found, props))
}
fn multistatus(user: &ArcUser, nodes: Vec<Box<dyn DavNode>>, not_found: Vec<dav::Href>, props: Option<dav::PropName<All>>) -> dav::Multistatus<All> {
// Collect properties on existing objects
let mut responses: Vec<dav::Response<All>> = match props {
Some(props) => nodes.into_iter().map(|n| n.response_props(user, props.clone())).collect(),
None => nodes.into_iter().map(|n| n.response_propname(user)).collect(),
};
// Register not found objects only if relevant
if !not_found.is_empty() {
responses.push(dav::Response {
status_or_propstat: dav::StatusOrPropstat::Status(
not_found,
dav::Status(hyper::StatusCode::NOT_FOUND),
),
error: None,
location: None,
responsedescription: None,
});
}
// Build response
dav::Multistatus::<All> {
responses,
responsedescription: None,
}
2024-03-16 15:48:46 +00:00
}
2024-03-18 11:00:40 +00:00
// ---- HTTP DAV Binding
2024-03-16 15:48:46 +00:00
use futures::stream::TryStreamExt;
2024-03-17 09:31:05 +00:00
use http_body_util::BodyStream;
2024-03-16 15:48:46 +00:00
use http_body_util::StreamBody;
use http_body_util::combinators::BoxBody;
use hyper::body::Frame;
use tokio_util::sync::PollSender;
use std::io::{Error, ErrorKind};
use futures::sink::SinkExt;
use tokio_util::io::{SinkWriter, CopyToBytes};
2024-03-18 11:00:40 +00:00
fn depth(req: &Request<impl hyper::body::Body>) -> dav::Depth {
match req.headers().get("Depth").map(hyper::header::HeaderValue::to_str) {
Some(Ok("0")) => dav::Depth::Zero,
Some(Ok("1")) => dav::Depth::One,
Some(Ok("Infinity")) => dav::Depth::Infinity,
_ => dav::Depth::Zero,
2024-03-18 11:00:40 +00:00
}
}
2024-03-16 15:48:46 +00:00
fn text_body(txt: &'static str) -> BoxBody<Bytes, std::io::Error> {
BoxBody::new(Full::new(Bytes::from(txt)).map_err(|e| match e {}))
}
2024-03-18 21:56:49 +00:00
fn serialize<T: dxml::QWrite + Send + 'static>(status_ok: hyper::StatusCode, elem: T) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
2024-03-16 15:48:46 +00:00
let (tx, rx) = tokio::sync::mpsc::channel::<Bytes>(1);
// Build the writer
tokio::task::spawn(async move {
let sink = PollSender::new(tx).sink_map_err(|_| Error::from(ErrorKind::BrokenPipe));
let mut writer = SinkWriter::new(CopyToBytes::new(sink));
let q = quick_xml::writer::Writer::new_with_indent(&mut writer, b' ', 4);
2024-03-18 14:04:46 +00:00
let ns_to_apply = vec![ ("xmlns:D".into(), "DAV:".into()), ("xmlns:C".into(), "urn:ietf:params:xml:ns:caldav".into()) ];
2024-03-17 09:31:05 +00:00
let mut qwriter = dxml::Writer { q, ns_to_apply };
2024-03-18 21:56:49 +00:00
let decl = quick_xml::events::BytesDecl::from_start(quick_xml::events::BytesStart::from_content("xml version=\"1.0\" encoding=\"utf-8\"", 0));
2024-03-18 11:00:40 +00:00
match qwriter.q.write_event_async(quick_xml::events::Event::Decl(decl)).await {
Ok(_) => (),
Err(e) => tracing::error!(err=?e, "unable to write XML declaration <?xml ... >"),
}
2024-03-16 15:48:46 +00:00
match elem.qwrite(&mut qwriter).await {
Ok(_) => tracing::debug!("fully serialized object"),
Err(e) => tracing::error!(err=?e, "failed to serialize object"),
}
});
// Build the reader
let recv = tokio_stream::wrappers::ReceiverStream::new(rx);
let stream = StreamBody::new(recv.map(|v| Ok(Frame::data(v))));
let boxed_body = BoxBody::new(stream);
let response = Response::builder()
2024-03-18 21:56:49 +00:00
.status(status_ok)
.header("content-type", "application/xml; charset=\"utf-8\"")
2024-03-16 15:48:46 +00:00
.body(boxed_body)?;
Ok(response)
}
/// Deserialize a request body to an XML request
2024-03-17 09:31:05 +00:00
async fn deserialize<T: dxml::Node<T>>(req: Request<Incoming>) -> Result<T> {
2024-03-16 15:48:46 +00:00
let stream_of_frames = BodyStream::new(req.into_body());
let stream_of_bytes = stream_of_frames
.try_filter_map(|frame| async move { Ok(frame.into_data().ok()) })
.map_err(|err| std::io::Error::new(std::io::ErrorKind::Other, err));
let async_read = tokio_util::io::StreamReader::new(stream_of_bytes);
let async_read = std::pin::pin!(async_read);
2024-03-17 09:31:05 +00:00
let mut rdr = dxml::Reader::new(quick_xml::reader::NsReader::from_reader(async_read)).await?;
2024-03-16 15:48:46 +00:00
let parsed = rdr.find::<T>().await?;
Ok(parsed)
}
2024-03-18 11:00:40 +00:00
//---
2024-03-18 14:04:46 +00:00
trait DavNode: Send {
// ------- specialized logic
2024-03-18 11:00:40 +00:00
// recurence
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>>;
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>>;
2024-03-18 11:00:40 +00:00
// node properties
2024-03-18 14:04:46 +00:00
fn path(&self, user: &ArcUser) -> String;
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All>;
fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>>;
2024-03-18 11:00:40 +00:00
// --- shared
fn response_propname(&self, user: &ArcUser) -> dav::Response<All> {
dav::Response {
status_or_propstat: dav::StatusOrPropstat::PropStat(
dav::Href(self.path(user)),
vec![
dav::PropStat {
status: dav::Status(hyper::StatusCode::OK),
prop: dav::AnyProp(self.supported_properties(user).0.into_iter().map(dav::AnyProperty::Request).collect()),
2024-03-18 11:00:40 +00:00
error: None,
responsedescription: None,
}
],
),
error: None,
location: None,
responsedescription: None
2024-03-18 11:00:40 +00:00
}
}
fn response_props(&self, user: &ArcUser, props: dav::PropName<All>) -> dav::Response<All> {
let mut prop_desc = vec![];
let (found, not_found): (Vec<_>, Vec<_>) = self.properties(user, props).into_iter().partition(|v| matches!(v, dav::AnyProperty::Value(_)));
// If at least one property has been found on this object, adding a HTTP 200 propstat to
// the response
if !found.is_empty() {
prop_desc.push(dav::PropStat {
status: dav::Status(hyper::StatusCode::OK),
prop: dav::AnyProp(found),
error: None,
responsedescription: None,
});
2024-03-18 11:00:40 +00:00
}
// If at least one property can't be found on this object, adding a HTTP 404 propstat to
// the response
if !not_found.is_empty() {
prop_desc.push(dav::PropStat {
status: dav::Status(hyper::StatusCode::NOT_FOUND),
prop: dav::AnyProp(not_found),
2024-03-18 11:00:40 +00:00
error: None,
responsedescription: None,
})
}
// Build the finale response
dav::Response {
status_or_propstat: dav::StatusOrPropstat::PropStat(dav::Href(self.path(user)), prop_desc),
error: None,
location: None,
responsedescription: None
2024-03-18 11:00:40 +00:00
}
}
}
2024-03-20 13:46:07 +00:00
#[derive(Clone)]
2024-03-18 11:00:40 +00:00
struct RootNode {}
impl DavNode for RootNode {
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>> {
2024-03-18 14:04:46 +00:00
if path.len() == 0 {
2024-03-20 13:46:07 +00:00
return Ok(Box::new(self.clone()))
2024-03-18 14:04:46 +00:00
}
if path[0] == user.username {
let child = Box::new(HomeNode {});
return child.fetch(user, &path[1..])
}
Err(anyhow!("Not found"))
}
fn path(&self, user: &ArcUser) -> String {
2024-03-18 11:00:40 +00:00
"/".into()
}
2024-03-18 14:33:28 +00:00
2024-03-18 11:00:40 +00:00
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>> {
vec![Box::new(HomeNode { })]
}
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
2024-03-18 11:00:40 +00:00
dav::PropName(vec![
dav::PropertyRequest::DisplayName,
dav::PropertyRequest::ResourceType,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::GetContentType,
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::Extension(all::PropertyRequest::Acl(acl::PropertyRequest::CurrentUserPrincipal)),
2024-03-18 11:00:40 +00:00
])
}
2024-03-19 16:36:32 +00:00
fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>> {
2024-03-18 20:44:44 +00:00
prop.0.into_iter().map(|n| match n {
dav::PropertyRequest::DisplayName => dav::AnyProperty::Value(dav::Property::DisplayName("DAV Root".to_string())),
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::ResourceType => dav::AnyProperty::Value(dav::Property::ResourceType(vec![
dav::ResourceType::Collection,
])),
2024-03-18 20:44:44 +00:00
dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("httpd/unix-directory".into())),
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::Extension(all::PropertyRequest::Acl(acl::PropertyRequest::CurrentUserPrincipal)) =>
dav::AnyProperty::Value(dav::Property::Extension(all::Property::Acl(acl::Property::CurrentUserPrincipal(acl::User::Authenticated(dav::Href(HomeNode{}.path(user))))))),
2024-03-18 20:44:44 +00:00
v => dav::AnyProperty::Request(v),
}).collect()
2024-03-18 11:00:40 +00:00
}
}
2024-03-20 13:46:07 +00:00
#[derive(Clone)]
2024-03-18 11:00:40 +00:00
struct HomeNode {}
impl DavNode for HomeNode {
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>> {
2024-03-18 14:04:46 +00:00
if path.len() == 0 {
2024-03-20 13:46:07 +00:00
return Ok(Box::new(self.clone()))
2024-03-18 14:04:46 +00:00
}
if path[0] == "calendar" {
let child = Box::new(CalendarListNode {});
return child.fetch(user, &path[1..])
}
Err(anyhow!("Not found"))
}
fn path(&self, user: &ArcUser) -> String {
2024-03-18 14:33:28 +00:00
format!("/{}/", user.username)
2024-03-18 14:04:46 +00:00
}
2024-03-18 11:00:40 +00:00
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>> {
vec![Box::new(CalendarListNode { })]
}
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
2024-03-18 11:00:40 +00:00
dav::PropName(vec![
dav::PropertyRequest::DisplayName,
dav::PropertyRequest::ResourceType,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::GetContentType,
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::CalendarHomeSet)),
2024-03-18 11:00:40 +00:00
])
}
2024-03-19 16:36:32 +00:00
fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>> {
2024-03-18 20:44:44 +00:00
prop.0.into_iter().map(|n| match n {
dav::PropertyRequest::DisplayName => dav::AnyProperty::Value(dav::Property::DisplayName(format!("{} home", user.username))),
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::ResourceType => dav::AnyProperty::Value(dav::Property::ResourceType(vec![
dav::ResourceType::Collection,
dav::ResourceType::Extension(all::ResourceType::Acl(acl::ResourceType::Principal)),
])),
2024-03-18 20:44:44 +00:00
dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("httpd/unix-directory".into())),
2024-03-19 16:36:32 +00:00
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::CalendarHomeSet)) =>
dav::AnyProperty::Value(dav::Property::Extension(all::Property::Cal(cal::Property::CalendarHomeSet(dav::Href(CalendarListNode{}.path(user)))))),
2024-03-18 20:44:44 +00:00
v => dav::AnyProperty::Request(v),
}).collect()
2024-03-18 11:00:40 +00:00
}
}
2024-03-20 13:46:07 +00:00
#[derive(Clone)]
2024-03-18 11:00:40 +00:00
struct CalendarListNode {}
impl DavNode for CalendarListNode {
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>> {
2024-03-18 14:04:46 +00:00
if path.len() == 0 {
2024-03-20 13:46:07 +00:00
return Ok(Box::new(self.clone()))
2024-03-18 14:04:46 +00:00
}
//@FIXME hardcoded logic
if path[0] == "personal" {
let child = Box::new(CalendarNode { name: "personal".to_string() });
return child.fetch(user, &path[1..])
}
Err(anyhow!("Not found"))
}
fn path(&self, user: &ArcUser) -> String {
2024-03-18 14:33:28 +00:00
format!("/{}/calendar/", user.username)
2024-03-18 14:04:46 +00:00
}
2024-03-18 11:00:40 +00:00
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>> {
vec![Box::new(CalendarNode { name: "personal".into() })]
}
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
2024-03-18 11:00:40 +00:00
dav::PropName(vec![
dav::PropertyRequest::DisplayName,
dav::PropertyRequest::ResourceType,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::GetContentType,
2024-03-18 11:00:40 +00:00
])
}
2024-03-19 16:36:32 +00:00
fn properties(&self, user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>> {
2024-03-18 20:44:44 +00:00
prop.0.into_iter().map(|n| match n {
dav::PropertyRequest::DisplayName => dav::AnyProperty::Value(dav::Property::DisplayName(format!("{} calendars", user.username))),
dav::PropertyRequest::ResourceType => dav::AnyProperty::Value(dav::Property::ResourceType(vec![dav::ResourceType::Collection])),
dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("httpd/unix-directory".into())),
v => dav::AnyProperty::Request(v),
}).collect()
2024-03-18 11:00:40 +00:00
}
}
2024-03-20 13:46:07 +00:00
#[derive(Clone)]
2024-03-18 11:00:40 +00:00
struct CalendarNode {
name: String,
}
impl DavNode for CalendarNode {
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>> {
2024-03-18 14:04:46 +00:00
if path.len() == 0 {
2024-03-20 13:46:07 +00:00
return Ok(Box::new(self.clone()))
2024-03-18 14:04:46 +00:00
}
//@FIXME hardcoded logic
if path[0] == "something.ics" {
2024-03-18 14:33:28 +00:00
let child = Box::new(EventNode {
calendar: self.name.to_string(),
event_file: "something.ics".to_string(),
});
2024-03-18 14:04:46 +00:00
return child.fetch(user, &path[1..])
}
Err(anyhow!("Not found"))
}
fn path(&self, user: &ArcUser) -> String {
2024-03-18 14:33:28 +00:00
format!("/{}/calendar/{}/", user.username, self.name)
2024-03-18 14:04:46 +00:00
}
2024-03-18 11:00:40 +00:00
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>> {
2024-03-18 14:33:28 +00:00
vec![Box::new(EventNode { calendar: self.name.to_string(), event_file: "something.ics".into() })]
2024-03-18 11:00:40 +00:00
}
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
2024-03-18 11:00:40 +00:00
dav::PropName(vec![
dav::PropertyRequest::DisplayName,
dav::PropertyRequest::ResourceType,
2024-03-18 15:14:38 +00:00
dav::PropertyRequest::GetContentType,
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::SupportedCalendarComponentSet)),
2024-03-18 11:00:40 +00:00
])
}
2024-03-19 16:36:32 +00:00
fn properties(&self, _user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>> {
2024-03-18 20:44:44 +00:00
prop.0.into_iter().map(|n| match n {
dav::PropertyRequest::DisplayName => dav::AnyProperty::Value(dav::Property::DisplayName(format!("{} calendar", self.name))),
dav::PropertyRequest::ResourceType => dav::AnyProperty::Value(dav::Property::ResourceType(vec![
2024-03-18 11:00:40 +00:00
dav::ResourceType::Collection,
2024-03-19 16:36:32 +00:00
dav::ResourceType::Extension(all::ResourceType::Cal(cal::ResourceType::Calendar)),
2024-03-18 11:00:40 +00:00
])),
2024-03-18 21:56:49 +00:00
//dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("httpd/unix-directory".into())),
//@FIXME seems wrong but seems to be what Thunderbird expects...
dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("text/calendar".into())),
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::SupportedCalendarComponentSet))
=> dav::AnyProperty::Value(dav::Property::Extension(all::Property::Cal(cal::Property::SupportedCalendarComponentSet(vec![
cal::CompSupport(cal::Component::VEvent),
])))),
2024-03-18 20:44:44 +00:00
v => dav::AnyProperty::Request(v),
}).collect()
2024-03-18 11:00:40 +00:00
}
}
const FAKE_ICS: &str = r#"BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//Example Corp.//CalDAV Client//EN
BEGIN:VTIMEZONE
LAST-MODIFIED:20040110T032845Z
TZID:US/Eastern
BEGIN:DAYLIGHT
DTSTART:20000404T020000
RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=4
TZNAME:EDT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
END:DAYLIGHT
BEGIN:STANDARD
DTSTART:20001026T020000
RRULE:FREQ=YEARLY;BYDAY=-1SU;BYMONTH=10
TZNAME:EST
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
DTSTAMP:20240406T001102Z
DTSTART;TZID=US/Eastern:20240406T100000
DURATION:PT1H
SUMMARY:Event #1
Description:Go Steelers!
UID:74855313FA803DA593CD579A@example.com
END:VEVENT
END:VCALENDAR"#;
2024-03-20 13:46:07 +00:00
#[derive(Clone)]
2024-03-18 11:00:40 +00:00
struct EventNode {
2024-03-18 14:33:28 +00:00
calendar: String,
event_file: String,
2024-03-18 11:00:40 +00:00
}
impl DavNode for EventNode {
2024-03-20 13:46:07 +00:00
fn fetch(&self, user: &ArcUser, path: &[&str]) -> Result<Box<dyn DavNode>> {
2024-03-18 14:04:46 +00:00
if path.len() == 0 {
2024-03-20 13:46:07 +00:00
return Ok(Box::new(self.clone()))
2024-03-18 14:04:46 +00:00
}
Err(anyhow!("Not found"))
}
fn path(&self, user: &ArcUser) -> String {
2024-03-18 14:33:28 +00:00
format!("/{}/calendar/{}/{}", user.username, self.calendar, self.event_file)
2024-03-18 14:04:46 +00:00
}
2024-03-18 11:00:40 +00:00
fn children(&self, user: &ArcUser) -> Vec<Box<dyn DavNode>> {
vec![]
}
2024-03-19 16:36:32 +00:00
fn supported_properties(&self, user: &ArcUser) -> dav::PropName<All> {
2024-03-18 11:00:40 +00:00
dav::PropName(vec![
dav::PropertyRequest::DisplayName,
dav::PropertyRequest::ResourceType,
dav::PropertyRequest::GetEtag,
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::CalendarData(cal::CalendarDataRequest::default()))),
2024-03-18 11:00:40 +00:00
])
}
2024-03-19 16:36:32 +00:00
fn properties(&self, _user: &ArcUser, prop: dav::PropName<All>) -> Vec<dav::AnyProperty<All>> {
2024-03-18 20:44:44 +00:00
prop.0.into_iter().map(|n| match n {
dav::PropertyRequest::DisplayName => dav::AnyProperty::Value(dav::Property::DisplayName(format!("{} event", self.event_file))),
dav::PropertyRequest::ResourceType => dav::AnyProperty::Value(dav::Property::ResourceType(vec![])),
dav::PropertyRequest::GetContentType => dav::AnyProperty::Value(dav::Property::GetContentType("text/calendar".into())),
dav::PropertyRequest::GetEtag => dav::AnyProperty::Value(dav::Property::GetEtag("\"abcdefg\"".into())),
dav::PropertyRequest::Extension(all::PropertyRequest::Cal(cal::PropertyRequest::CalendarData(req))) =>
dav::AnyProperty::Value(dav::Property::Extension(all::Property::Cal(cal::Property::CalendarData(cal::CalendarDataPayload { mime: None, payload: FAKE_ICS.into() })))),
2024-03-18 20:44:44 +00:00
v => dav::AnyProperty::Request(v),
}).collect()
2024-03-18 11:00:40 +00:00
}
}