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
9 pub struct WebRequest {
10 // initial part of body
11 // used up to and including first 2 lines of metadata
12 // end delimiter for the metadata not yet located, but in here somewhere
13 pub initial: Box<[u8]>,
14 pub initial_remaining: usize,
15 pub length_hint: usize,
16 pub body: hyper::body::Body,
17 pub boundary_finder: multipart::BoundaryFinder,
18 pub reply_to: oneshot::Sender<WebResponse>,
19 pub warnings: Warnings,
20 pub conn: Arc<String>,
21 pub may_route: MayRoute,
24 /// Reply from client task to hyper worker pool task
26 pub struct WebResponse {
27 pub warnings: Warnings,
28 pub data: Result<WebResponseData, AE>,
31 pub type WebResponseData = FrameQueueBuf;
32 pub type WebResponseBody = BufBody<FrameQueueBuf>;
37 req: hyper::Request<hyper::Body>
38 ) -> Result<hyper::Response<WebResponseBody>, hyper::http::Error> {
39 if req.method() == Method::GET {
40 let mut resp = hyper::Response::new(BufBody::display("hippotat\r\n"));
41 resp.headers_mut().insert(
43 "text/plain; charset=US-ASCII".try_into().unwrap()
48 let mut warnings: Warnings = default();
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))?;
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")?;
70 let b = mkboundary(b.as_str());
75 warnings.add(&e.wrap_err("guessing boundary"))?;
80 let length_hint: usize = (||{
81 let clength = get_header("Content-Length")?;
82 let clength = clength.parse().context("parse Content-Length")?;
85 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
88 let mut body = req.into_body();
89 let initial = match read_limited_bytes(
90 METADATA_MAX_LEN, default(), length_hint, &mut body
93 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
94 Err(ReadLimitedError::Hyper(e)) => throw!(e),
97 let boundary_finder = memmem::Finder::new(&boundary);
98 let mut boundary_iter = boundary_finder.find_iter(&initial);
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")) };
104 let comp = multipart::process_boundary
105 (&mut warnings, &initial[start..], PartName::m)?
106 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
108 if comp.name != PartName::m { throw!(anyhow!(
109 r#"first multipart component must be name="m""#
112 let mut meta = MetadataFieldIterator::new(comp.payload);
114 let client: ClientName = meta.need_parse().context("client addr")?;
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")?;
123 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
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];
132 let client_name = client;
133 let client = global.all_clients.get(&client_name);
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
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 = BufBody::display("Not authorised\r\n");
153 hyper::Response::builder()
154 .status(hyper::StatusCode::FORBIDDEN)
155 .header("Content-Type", r#"text/plain; charset="utf-8""#)
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));
171 chk_skew(client_time, now, "ahead")?;
172 chk_skew(now, client_time, "behind")?;
174 let initial_remaining = meta.remaining_bytes_len();
176 //eprintln!("boundary={:?} start={} name={:?} client={}",
177 // boundary, start, &comp.name, &client.ic);
179 let (reply_to, reply_recv) = oneshot::channel();
180 trace!("{} {} request, Content-Length={}",
181 &conn, &client_name, length_hint);
182 let wreq = WebRequest {
186 boundary_finder: boundary_finder.into_owned(),
188 warnings: mem::take(&mut warnings),
191 may_route: MayRoute::came_from_outside_hippotatd(),
194 client.web.try_send(wreq)
195 .map_err(|_| anyhow!("client user task overloaded"))?;
197 let reply: WebResponse = reply_recv.await?;
198 warnings = reply.warnings;
199 let data = reply.data?;
201 if warnings.warnings.is_empty() {
202 trace!("{} {} responding, {}",
203 &conn, &client_name, data.len());
205 debug!("{} {} responding, {} warnings={:?}",
206 &conn, &client_name, data.len(),
210 let data = BufBody::new(data);
212 hyper::Response::builder()
213 .header("Content-Type", r#"application/octet-stream"#)
216 }.await.unwrap_or_else(|e| {
217 debug!("{} error {}", &conn, &e);
218 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
219 for w in warnings.warnings {
220 write!(errmsg, "warning: {}\n", w).unwrap();
222 hyper::Response::builder()
223 .status(hyper::StatusCode::BAD_REQUEST)
224 .header("Content-Type", r#"text/plain; charset="utf-8""#)
225 .body(BufBody::display(errmsg))