chiark / gitweb /
reorg source
[hippotat.git] / server / sweb.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use super::*;
6
7 /// Sent from hyper worker pool task to client task
8 #[allow(dead_code)] // xxx
9 #[derive(Debug)]
10 pub struct WebRequest {
11   // initial part of body
12   // used up to and including first 2 lines of metadata
13   // end delimiter for the metadata not yet located, but in here somewhere
14   pub initial: Box<[u8]>,
15   pub initial_remaining: usize,
16   pub length_hint: usize,
17   pub body: hyper::body::Body,
18   pub boundary_finder: multipart::BoundaryFinder,
19   pub reply_to: oneshot::Sender<WebResponse>,
20   pub warnings: Warnings,
21   pub conn: Arc<String>,
22 }
23
24 /// Reply from client task to hyper worker pool task
25 #[allow(dead_code)] // xxx
26 #[derive(Debug)]
27 pub struct WebResponse {
28   pub warnings: Warnings,
29   pub data: Result<WebResponseData, AE>,
30 }
31
32 pub type WebResponseData = Vec<u8>;
33
34 pub async fn handle(
35   conn: Arc<String>,
36   global: Arc<Global>,
37   req: hyper::Request<hyper::Body>
38 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
39   if req.method() == Method::GET {
40     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
41     resp.headers_mut().insert(
42       "Content-Type",
43       "text/plain; charset=US-ASCII".try_into().unwrap()
44     );
45     return Ok(resp)
46   }
47
48   let mut warnings: Warnings = default();
49
50   async {
51
52     let get_header = |hn: &str| {
53       let mut values = req.headers().get_all(hn).iter();
54       let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
55       if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
56       let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
57       Ok::<_,AE>(v)
58     };
59
60     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
61     let boundary = match (||{
62       let t = get_header("Content-Type")?;
63       let t: mime::Mime = t.parse().context("parse Content-Type")?;
64       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
65       let b = mime::BOUNDARY;
66       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
67       if t.subtype() != "form-data" {
68         warnings.add(&"Content-Type not /form-data")?;
69       }
70       let b = mkboundary(b.as_str());
71       Ok::<_,AE>(b)
72     })() {
73       Ok(y) => y,
74       Err(e) => {
75         warnings.add(&e.wrap_err("guessing boundary"))?;
76         mkboundary("b")
77       },
78     };
79
80     let length_hint: usize = (||{
81       let clength = get_header("Content-Length")?;
82       let clength = clength.parse().context("parse Content-Length")?;
83       Ok::<_,AE>(clength)
84     })().unwrap_or_else(
85       |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
86     );
87
88     let mut body = req.into_body();
89     let initial = match read_limited_bytes(
90       METADATA_MAX_LEN, default(), length_hint, &mut body
91     ).await {
92       Ok(all) => all,
93       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
94       Err(ReadLimitedError::Hyper(e)) => throw!(e),
95     };
96
97     let boundary_finder = memmem::Finder::new(&boundary);
98     let mut boundary_iter = boundary_finder.find_iter(&initial);
99
100     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
101     else if let Some(start) = boundary_iter.next() { start + boundary.len() }
102     else { throw!(anyhow!("initial boundary not found")) };
103
104     let comp = multipart::process_boundary
105       (&mut warnings, &initial[start..], PartName::m)?
106       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
107
108     if comp.name != PartName::m { throw!(anyhow!(
109       r#"first multipart component must be name="m""#
110     )) }
111
112     let mut meta = MetadataFieldIterator::new(comp.payload);
113
114     let client: ClientName = meta.need_parse().context("client addr")?;
115
116     let mut hmac_got = [0; HMAC_L];
117     let (client_time, hmac_got_l) = (||{
118       let token: &str = meta.need_next().context(r#"find in "m""#)?;
119       let (time_t, hmac_b64) = token.split_once(' ')
120         .ok_or_else(|| anyhow!("split"))?;
121       let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
122       let l = io::copy(
123         &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
124                                               BASE64_CONFIG),
125         &mut &mut hmac_got[..]
126       ).context("parse b64 token")?;
127       let l = l.try_into()?;
128       Ok::<_,AE>((time_t, l))
129     })().context("token")?;
130     let hmac_got = &hmac_got[0..hmac_got_l];
131
132     let client_name = client;
133     let client = global.all_clients.get(&client_name);
134
135     // We attempt to hide whether the client exists we don't try to
136     // hide the hash lookup computationgs, but we do try to hide the
137     // HMAC computation by always doing it.  We hope that the compiler
138     // doesn't produce a specialised implementation for the dummy
139     // secret value.
140     let client_exists = subtle::Choice::from(client.is_some() as u8);
141     let secret = client.map(|c| c.ic.secret.0.as_bytes());
142     let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
143     let client_time_s = format!("{:x}", client_time);
144     let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
145     // We also definitely want a consttime memeq for the hmac value
146     let hmac_ok = hmac_got.ct_eq(&hmac_exp);
147     //dbg!(DumpHex(&hmac_exp), client.is_some());
148     //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
149     if ! bool::from(hmac_ok & client_exists) {
150       debug!("{} rejected client {}", &conn, &client_name);
151       let body = hyper::Body::from("Not authorised\r\n");
152       return Ok(
153         hyper::Response::builder()
154           .status(hyper::StatusCode::FORBIDDEN)
155           .header("Content-Type", r#"text/plain; charset="utf-8""#)
156           .body(body)
157       )
158     }
159
160     let client = client.unwrap();
161     let now = time_t_now();
162     let chk_skew = |a: u64, b: u64, c_ahead_behind| {
163       if let Some(a_ahead) = a.checked_sub(b) {
164         if a_ahead > client.ic.max_clock_skew.as_secs() {
165           throw!(anyhow!("too much clock skew (client {} by {})",
166                          c_ahead_behind, a_ahead));
167         }
168       }
169       Ok::<_,AE>(())
170     };
171     chk_skew(client_time, now, "ahead")?;
172     chk_skew(now, client_time, "behind")?;
173
174     let initial_remaining = meta.remaining_bytes_len();
175
176     //eprintln!("boundary={:?} start={} name={:?} client={}",
177     // boundary, start, &comp.name, &client.ic);
178
179     let (reply_to, reply_recv) = oneshot::channel();
180     trace!("{} {} request, Content-Length={}",
181            &conn, &client_name, length_hint);
182     let wreq = WebRequest {
183       initial,
184       initial_remaining,
185       length_hint,
186       boundary_finder: boundary_finder.into_owned(),
187       body,
188       warnings: mem::take(&mut warnings),
189       reply_to,
190       conn: conn.clone(),
191     };
192
193     client.web.try_send(wreq)
194       .map_err(|_| anyhow!("client task shut down!"))?;
195
196     let reply: WebResponse = reply_recv.await?;
197     warnings = reply.warnings;
198     let data = reply.data?;
199
200     if warnings.warnings.is_empty() {
201       trace!("{} {} responding, {}",
202              &conn, &client_name, data.len());
203     } else {
204       debug!("{} {} responding, {} warnings={:?}",
205              &conn, &client_name, data.len(),
206              &warnings.warnings);
207     }
208
209     let data = hyper::Body::from(data);
210     Ok::<_,AE>(
211       hyper::Response::builder()
212         .header("Content-Type", r#"application/octet-stream"#)
213         .body(data)
214     )
215   }.await.unwrap_or_else(|e| {
216     debug!("{} error {}", &conn, &e);
217     let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
218     for w in warnings.warnings {
219       write!(errmsg, "warning: {}\n", w).unwrap();
220     }
221     hyper::Response::builder()
222       .status(hyper::StatusCode::BAD_REQUEST)
223       .header("Content-Type", r#"text/plain; charset="utf-8""#)
224       .body(errmsg.into())
225   })
226 }