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;
|
|
|
|
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 hyper::rt::{Read, Write};
|
|
|
|
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-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-02-27 00:05:51 +00:00
|
|
|
async move {
|
|
|
|
auth(login, req).await
|
|
|
|
}
|
|
|
|
})).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-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,
|
|
|
|
req: Request<impl hyper::body::Body>,
|
|
|
|
) -> Result<Response<Full<Bytes>>> {
|
|
|
|
|
2024-03-13 14:45:36 +00:00
|
|
|
tracing::info!("headers: {:?}", req.headers());
|
|
|
|
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\"")
|
|
|
|
.body(Full::new(Bytes::from("Missing Authorization field")))?)
|
|
|
|
},
|
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)
|
|
|
|
.body(Full::new(Bytes::from("Unsupported Authorization field")))?)
|
|
|
|
},
|
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\"")
|
|
|
|
.body(Full::new(Bytes::from("Wrong credentials")))?)
|
|
|
|
},
|
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
|
|
|
}
|
|
|
|
|
2024-02-27 18:30:51 +00:00
|
|
|
async fn router(user: std::sync::Arc<User>, req: Request<impl hyper::body::Body>) -> Result<Response<Full<Bytes>>> {
|
2024-02-26 23:12:01 +00:00
|
|
|
let path_segments: Vec<_> = req.uri().path().split("/").filter(|s| *s != "").collect();
|
2024-03-13 14:45:36 +00:00
|
|
|
tracing::info!("router");
|
2024-02-26 23:12:01 +00:00
|
|
|
match path_segments.as_slice() {
|
|
|
|
[] => tracing::info!("root"),
|
2024-02-27 18:30:51 +00:00
|
|
|
[ username, ..] if *username != user.username => return Ok(Response::builder()
|
|
|
|
.status(403)
|
|
|
|
.body(Full::new(Bytes::from("Accessing other user ressources is not allowed")))?),
|
2024-02-28 09:20:28 +00:00
|
|
|
[ _ ] => 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"),
|
2024-02-27 18:30:51 +00:00
|
|
|
_ => return Ok(Response::builder()
|
|
|
|
.status(404)
|
|
|
|
.body(Full::new(Bytes::from("Resource not found")))?),
|
2024-02-26 22:59:29 +00:00
|
|
|
}
|
|
|
|
Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
|
|
|
|
}
|
2024-02-28 09:20:28 +00:00
|
|
|
|
2024-03-08 08:55:33 +00:00
|
|
|
#[allow(dead_code)]
|
|
|
|
async fn collections(_user: std::sync::Arc<User>, _req: Request<impl hyper::body::Body>) -> Result<Response<Full<Bytes>>> {
|
2024-02-28 09:20:28 +00:00
|
|
|
unimplemented!();
|
|
|
|
}
|