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