1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
7 /// Sent from hyper worker pool task to client task
8 #[allow(dead_code)] // xxx
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,
25 /// Reply from client task to hyper worker pool task
26 #[allow(dead_code)] // xxx
28 pub struct WebResponse {
29 pub warnings: Warnings,
30 pub data: Result<WebResponseData, AE>,
33 pub type WebResponseData = Vec<u8>;
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(
44 "text/plain; charset=US-ASCII".try_into().unwrap()
49 let mut warnings: Warnings = default();
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))?;
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")?;
71 let b = mkboundary(b.as_str());
76 warnings.add(&e.wrap_err("guessing boundary"))?;
81 let length_hint: usize = (||{
82 let clength = get_header("Content-Length")?;
83 let clength = clength.parse().context("parse Content-Length")?;
86 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
89 let mut body = req.into_body();
90 let initial = match read_limited_bytes(
91 METADATA_MAX_LEN, default(), length_hint, &mut body
94 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
95 Err(ReadLimitedError::Hyper(e)) => throw!(e),
98 let boundary_finder = memmem::Finder::new(&boundary);
99 let mut boundary_iter = boundary_finder.find_iter(&initial);
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")) };
105 let comp = multipart::process_boundary
106 (&mut warnings, &initial[start..], PartName::m)?
107 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
109 if comp.name != PartName::m { throw!(anyhow!(
110 r#"first multipart component must be name="m""#
113 let mut meta = MetadataFieldIterator::new(comp.payload);
115 let client: ClientName = meta.need_parse().context("client addr")?;
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")?;
124 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
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];
133 let client_name = client;
134 let client = global.all_clients.get(&client_name);
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
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");
154 hyper::Response::builder()
155 .status(hyper::StatusCode::FORBIDDEN)
156 .header("Content-Type", r#"text/plain; charset="utf-8""#)
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));
172 chk_skew(client_time, now, "ahead")?;
173 chk_skew(now, client_time, "behind")?;
175 let initial_remaining = meta.remaining_bytes_len();
177 //eprintln!("boundary={:?} start={} name={:?} client={}",
178 // boundary, start, &comp.name, &client.ic);
180 let (reply_to, reply_recv) = oneshot::channel();
181 trace!(target: "hippotatd",
182 "{} {} request, Content-Length={}",
183 &conn, &client_name, length_hint);
184 let wreq = WebRequest {
188 boundary_finder: boundary_finder.into_owned(),
190 warnings: mem::take(&mut warnings),
193 may_route: MayRoute::came_from_outside_hippotatd(),
196 client.web.try_send(wreq)
197 .map_err(|_| anyhow!("client task shut down!"))?;
199 let reply: WebResponse = reply_recv.await?;
200 warnings = reply.warnings;
201 let data = reply.data?;
203 if warnings.warnings.is_empty() {
204 trace!("{} {} responding, {}",
205 &conn, &client_name, data.len());
207 debug!("{} {} responding, {} warnings={:?}",
208 &conn, &client_name, data.len(),
212 let data = hyper::Body::from(data);
214 hyper::Response::builder()
215 .header("Content-Type", r#"application/octet-stream"#)
218 }.await.unwrap_or_else(|e| {
219 debug!("{} error {}", &conn, &e);
220 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
221 for w in warnings.warnings {
222 write!(errmsg, "warning: {}\n", w).unwrap();
224 hyper::Response::builder()
225 .status(hyper::StatusCode::BAD_REQUEST)
226 .header("Content-Type", r#"text/plain; charset="utf-8""#)