aboutsummaryrefslogtreecommitdiff
path: root/aero-proto
diff options
context:
space:
mode:
authorQuentin Dufour <quentin@deuxfleurs.fr>2024-03-16 16:48:46 +0100
committerQuentin Dufour <quentin@deuxfleurs.fr>2024-03-16 16:48:46 +0100
commit902d33c4344f4e38c021ff20b2197ee1dfbd347f (patch)
tree3cea2a5cf9f635eccaa280cd04475e0d580d2eb0 /aero-proto
parent3abdafb0dbbc9290329e4974e821933426b32f91 (diff)
downloadaerogramme-902d33c4344f4e38c021ff20b2197ee1dfbd347f.tar.gz
aerogramme-902d33c4344f4e38c021ff20b2197ee1dfbd347f.zip
bind streaming codec to hyper 1.x
Diffstat (limited to 'aero-proto')
-rw-r--r--aero-proto/Cargo.toml2
-rw-r--r--aero-proto/src/dav.rs157
2 files changed, 135 insertions, 24 deletions
diff --git a/aero-proto/Cargo.toml b/aero-proto/Cargo.toml
index df8c696..e9f28d1 100644
--- a/aero-proto/Cargo.toml
+++ b/aero-proto/Cargo.toml
@@ -22,6 +22,7 @@ futures.workspace = true
tokio.workspace = true
tokio-util.workspace = true
tokio-rustls.workspace = true
+tokio-stream.workspace = true
rustls.workspace = true
rustls-pemfile.workspace = true
imap-codec.workspace = true
@@ -33,3 +34,4 @@ duplexify.workspace = true
smtp-message.workspace = true
smtp-server.workspace = true
tracing.workspace = true
+quick-xml.workspace = true
diff --git a/aero-proto/src/dav.rs b/aero-proto/src/dav.rs
index 42fde2c..3981b61 100644
--- a/aero-proto/src/dav.rs
+++ b/aero-proto/src/dav.rs
@@ -6,6 +6,8 @@ use base64::Engine;
use hyper::service::service_fn;
use hyper::{Request, Response, body::Bytes};
use hyper::server::conn::http1 as http;
+use hyper::rt::{Read, Write};
+use hyper::body::Incoming;
use hyper_util::rt::TokioIo;
use http_body_util::Full;
use futures::stream::{FuturesUnordered, StreamExt};
@@ -13,13 +15,16 @@ use tokio::net::TcpListener;
use tokio::sync::watch;
use tokio_rustls::TlsAcceptor;
use tokio::net::TcpStream;
-use hyper::rt::{Read, Write};
use tokio::io::{AsyncRead, AsyncWrite};
+use tokio::io::AsyncWriteExt;
use rustls_pemfile::{certs, private_key};
use aero_user::config::{DavConfig, DavUnsecureConfig};
use aero_user::login::ArcLoginProvider;
use aero_collections::user::User;
+use aero_dav::types::{PropFind, Multistatus, PropValue, ResponseDescription};
+use aero_dav::realization::{Core, Calendar};
+use aero_dav::xml as dav;
pub struct Server {
bind_addr: SocketAddr,
@@ -94,13 +99,10 @@ impl Server {
//abitrarily bound
//@FIXME replace with a handler supporting http2 and TLS
-
match http::Builder::new().serve_connection(stream, service_fn(|req: Request<hyper::body::Incoming>| {
let login = login.clone();
tracing::info!("{:?} {:?}", req.method(), req.uri());
- async move {
- auth(login, req).await
- }
+ auth(login, req)
})).await {
Err(e) => tracing::warn!(err=?e, "connection failed"),
Ok(()) => tracing::trace!("connection terminated with success"),
@@ -127,11 +129,13 @@ impl Server {
}
}
+use http_body_util::BodyExt;
+
//@FIXME We should not support only BasicAuth
async fn auth(
login: ArcLoginProvider,
- req: Request<impl hyper::body::Body>,
-) -> Result<Response<Full<Bytes>>> {
+ req: Request<Incoming>,
+) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
tracing::info!("headers: {:?}", req.headers());
let auth_val = match req.headers().get(hyper::header::AUTHORIZATION) {
@@ -141,7 +145,7 @@ async fn auth(
return Ok(Response::builder()
.status(401)
.header("WWW-Authenticate", "Basic realm=\"Aerogramme\"")
- .body(Full::new(Bytes::from("Missing Authorization field")))?)
+ .body(text_body("Missing Authorization field"))?)
},
};
@@ -151,7 +155,7 @@ async fn auth(
tracing::info!("Unsupported authorization field");
return Ok(Response::builder()
.status(400)
- .body(Full::new(Bytes::from("Unsupported Authorization field")))?)
+ .body(text_body("Unsupported Authorization field"))?)
},
};
@@ -176,7 +180,7 @@ async fn auth(
return Ok(Response::builder()
.status(401)
.header("WWW-Authenticate", "Basic realm=\"Aerogramme\"")
- .body(Full::new(Bytes::from("Wrong credentials")))?)
+ .body(text_body("Wrong credentials"))?)
},
};
@@ -187,26 +191,131 @@ async fn auth(
router(user, req).await
}
-async fn router(user: std::sync::Arc<User>, req: Request<impl hyper::body::Body>) -> Result<Response<Full<Bytes>>> {
- let path_segments: Vec<_> = req.uri().path().split("/").filter(|s| *s != "").collect();
- tracing::info!("router");
- match path_segments.as_slice() {
- [] => tracing::info!("root"),
- [ username, ..] if *username != user.username => return Ok(Response::builder()
+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();
+
+ match (method.as_str(), path_segments.as_slice()) {
+ ("PROPFIND", []) => propfind_root(user, req).await,
+ (_, [ username, ..]) if *username != user.username => return Ok(Response::builder()
.status(403)
- .body(Full::new(Bytes::from("Accessing other user ressources is not allowed")))?),
- [ _ ] => tracing::info!("user home"),
- [ _, "calendar" ] => tracing::info!("user calendars"),
- [ _, "calendar", colname ] => tracing::info!(name=colname, "selected calendar"),
- [ _, "calendar", colname, member ] => tracing::info!(name=colname, obj=member, "selected event"),
+ .body(text_body("Accessing other user ressources is not allowed"))?),
+ ("PROPFIND", [ _ ]) => propfind_home(user, &req).await,
+ ("PROPFIND", [ _, "calendar" ]) => propfind_all_calendars(user, &req).await,
+ ("PROPFIND", [ _, "calendar", colname ]) => propfind_this_calendar(user, &req, colname).await,
+ ("PROPFIND", [ _, "calendar", colname, event ]) => propfind_event(user, req, colname, event).await,
_ => return Ok(Response::builder()
- .status(404)
- .body(Full::new(Bytes::from("Resource not found")))?),
+ .status(501)
+ .body(text_body("Not implemented"))?),
}
- Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}
+/// <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>
+
+async fn propfind_root(user: std::sync::Arc<User>, req: Request<Incoming>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ tracing::info!("root");
+
+ let r = deserialize::<PropFind<Core>>(req).await?;
+ println!("r: {:?}", r);
+ serialize(Multistatus::<Core, PropValue<Core>> {
+ responses: vec![],
+ responsedescription: Some(ResponseDescription("hello world".to_string())),
+ })
+}
+
+async fn propfind_home(user: std::sync::Arc<User>, req: &Request<impl hyper::body::Body>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ tracing::info!("user home");
+ Ok(Response::new(text_body("Hello World!")))
+}
+
+async fn propfind_all_calendars(user: std::sync::Arc<User>, req: &Request<impl hyper::body::Body>) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ tracing::info!("calendar");
+ Ok(Response::new(text_body("Hello World!")))
+}
+
+async fn propfind_this_calendar(
+ user: std::sync::Arc<User>,
+ req: &Request<Incoming>,
+ colname: &str
+) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ tracing::info!(name=colname, "selected calendar");
+ Ok(Response::new(text_body("Hello World!")))
+}
+
+async fn propfind_event(
+ user: std::sync::Arc<User>,
+ req: Request<Incoming>,
+ colname: &str,
+ event: &str,
+) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ tracing::info!(name=colname, obj=event, "selected event");
+ Ok(Response::new(text_body("Hello World!")))
+}
+
+
#[allow(dead_code)]
async fn collections(_user: std::sync::Arc<User>, _req: Request<impl hyper::body::Body>) -> Result<Response<Full<Bytes>>> {
unimplemented!();
}
+
+
+use futures::stream::TryStreamExt;
+use http_body_util::{BodyStream, Empty};
+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};
+
+
+fn text_body(txt: &'static str) -> BoxBody<Bytes, std::io::Error> {
+ BoxBody::new(Full::new(Bytes::from(txt)).map_err(|e| match e {}))
+}
+
+fn serialize<T: dav::QWrite + Send + 'static>(elem: T) -> Result<Response<BoxBody<Bytes, std::io::Error>>> {
+ 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);
+ let ns_to_apply = vec![ ("xmlns:D".into(), "DAV:".into()) ];
+ let mut qwriter = dav::Writer { q, ns_to_apply };
+ 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()
+ .status(hyper::StatusCode::OK)
+ .body(boxed_body)?;
+
+ Ok(response)
+}
+
+
+/// Deserialize a request body to an XML request
+async fn deserialize<T: dav::Node<T>>(req: Request<Incoming>) -> Result<T> {
+ 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);
+ let mut rdr = dav::Reader::new(quick_xml::reader::NsReader::from_reader(async_read)).await?;
+ let parsed = rdr.find::<T>().await?;
+ Ok(parsed)
+}