aboutsummaryrefslogtreecommitdiff
path: root/src/dav/mod.rs
blob: 906cfdd349dd6b441ce8f3e8f6bb5a558a4e37a7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// utils
pub mod error;
pub mod xml;

// webdav
pub mod types;
pub mod encoder;
pub mod decoder;

// calendar
mod caltypes;
mod calencoder;
mod caldecoder;

// wip
mod acltypes;
mod versioningtypes;

// final type
pub mod realization;


use std::net::SocketAddr;

use anyhow::{anyhow, Result};
use base64::Engine;
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;

use crate::config::DavUnsecureConfig;
use crate::login::ArcLoginProvider;
use crate::user::User;

pub struct Server {
    bind_addr: SocketAddr,
    login_provider: ArcLoginProvider,
}

pub fn new_unsecure(config: DavUnsecureConfig, login: ArcLoginProvider) -> Server {
    Server {
        bind_addr: config.bind_addr,
        login_provider: login,
    }
}

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,
            };
            tracing::info!("Accepted connection from {}", remote_addr);
            let stream = TokioIo::new(socket);
            let login = self.login_provider.clone();
            let conn = tokio::spawn(async move {
                //@FIXME should create a generic "public web" server on which "routers" could be
                //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();
                    async move {
                        auth(login, req).await
                    }
                })).await {
                    Err(e) => tracing::warn!(err=?e, "connection failed"),
                    Ok(()) => tracing::trace!("connection terminated with success"),
                }
            });
            connections.push(conn);
        }
        drop(tcp);

        tracing::info!("Server shutting down, draining remaining connections...");
        while connections.next().await.is_some() {}

        Ok(())
    }
}

//@FIXME We should not support only BasicAuth
async fn auth(
    login: ArcLoginProvider,
    req: Request<impl hyper::body::Body>, 
) -> Result<Response<Full<Bytes>>> {

    let auth_val = match req.headers().get("Authorization") {
        Some(hv) => hv.to_str()?,
        None => return Ok(Response::builder()
            .status(401)
            .body(Full::new(Bytes::from("Missing Authorization field")))?),
    };

    let b64_creds_maybe_padded = match auth_val.split_once(" ") {
        Some(("Basic", b64)) => b64,
        _ => return Ok(Response::builder()
            .status(400)
            .body(Full::new(Bytes::from("Unsupported Authorization field")))?),
    };

    // 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
    let creds = match login.login(username, password).await {
        Ok(c) => c,
        Err(e) => return Ok(Response::builder()
            .status(401)
            .body(Full::new(Bytes::from("Wrong credentials")))?),
    };

    // Build a user
    let user = User::new(username.into(), creds).await?;

    // Call router with user
    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();
    match path_segments.as_slice() {
        [] => tracing::info!("root"),
        [ 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"),
        _ => return Ok(Response::builder()
            .status(404)
            .body(Full::new(Bytes::from("Resource not found")))?),
    }
    Ok(Response::new(Full::new(Bytes::from("Hello World!"))))
}

async fn collections(user: std::sync::Arc<User>, req: Request<impl hyper::body::Body>) -> Result<Response<Full<Bytes>>> {
    unimplemented!();
}