From 902d33c4344f4e38c021ff20b2197ee1dfbd347f Mon Sep 17 00:00:00 2001 From: Quentin Dufour Date: Sat, 16 Mar 2024 16:48:46 +0100 Subject: bind streaming codec to hyper 1.x --- aero-proto/src/dav.rs | 157 ++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 133 insertions(+), 24 deletions(-) (limited to 'aero-proto/src/dav.rs') 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| { 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, -) -> Result>> { + req: Request, +) -> Result>> { 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, req: Request) -> Result>> { - 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, req: Request) -> Result>> { + 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!")))) } +/// +/// +/// + +async fn propfind_root(user: std::sync::Arc, req: Request) -> Result>> { + tracing::info!("root"); + + let r = deserialize::>(req).await?; + println!("r: {:?}", r); + serialize(Multistatus::> { + responses: vec![], + responsedescription: Some(ResponseDescription("hello world".to_string())), + }) +} + +async fn propfind_home(user: std::sync::Arc, req: &Request) -> Result>> { + tracing::info!("user home"); + Ok(Response::new(text_body("Hello World!"))) +} + +async fn propfind_all_calendars(user: std::sync::Arc, req: &Request) -> Result>> { + tracing::info!("calendar"); + Ok(Response::new(text_body("Hello World!"))) +} + +async fn propfind_this_calendar( + user: std::sync::Arc, + req: &Request, + colname: &str +) -> Result>> { + tracing::info!(name=colname, "selected calendar"); + Ok(Response::new(text_body("Hello World!"))) +} + +async fn propfind_event( + user: std::sync::Arc, + req: Request, + colname: &str, + event: &str, +) -> Result>> { + 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, _req: Request) -> Result>> { 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 { + BoxBody::new(Full::new(Bytes::from(txt)).map_err(|e| match e {})) +} + +fn serialize(elem: T) -> Result>> { + let (tx, rx) = tokio::sync::mpsc::channel::(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>(req: Request) -> Result { + 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::().await?; + Ok(parsed) +} -- cgit v1.2.3