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