1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
5 use hippotat::prelude::*;
7 #[derive(StructOpt,Debug)]
16 const METADATA_MAX_LEN: usize = MAX_OVERHEAD;
18 type AllClients = HashMap<ClientName, ClientHandles>;
20 struct ClientHandles {
21 ic: Arc<InstanceConfig>,
22 web: tokio::sync::mpsc::Sender<WebRequest>,
25 /// Sent from hyper worker pool task to client task
26 #[allow(dead_code)] // xxx
28 // initial part of body
29 // used up to and including first 2 lines of metadata
30 // end delimiter for the metadata not yet located, but in here somewhere
32 initial_remaining: usize,
34 body: hyper::body::Body,
35 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
39 /// Reply from client task to hyper worker pool task
40 #[allow(dead_code)] // xxx
43 data: Result<WebResponseData, AE>,
46 type WebResponseData = ();
49 all_clients: Arc<AllClients>,
50 req: hyper::Request<hyper::Body>
51 ) -> Result<hyper::Response<hyper::Body>, Void> {
52 if req.method() == Method::GET {
53 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
54 resp.headers_mut().insert(
56 "text/plain; charset=US-ASCII".try_into().unwrap()
61 let mut warnings: Warnings = default();
65 let get_header = |hn: &str| {
66 let mut values = req.headers().get_all(hn).iter();
67 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
68 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
69 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
73 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
74 let boundary = match (||{
75 let t = get_header("Content-Type")?;
76 let t: mime::Mime = t.parse().context("parse Content-Type")?;
77 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
78 let b = mime::BOUNDARY;
79 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
80 if t.subtype() != "form-data" {
81 warnings.add(&"Content-Type not /form-data")?;
83 let b = mkboundary(b.as_str());
88 warnings.add(&e.wrap_err("guessing boundary"))?;
93 let length_hint: usize = (||{
94 let clength = get_header("Content-Length")?;
95 let clength = clength.parse().context("parse Content-Length")?;
98 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
101 let mut body = req.into_body();
102 let initial = match read_limited_bytes(
103 METADATA_MAX_LEN, default(), length_hint, &mut body
106 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
107 Err(ReadLimitedError::Hyper(e)) => throw!(e),
110 let finder = memmem::Finder::new(&boundary);
111 let mut find_iter = finder.find_iter(&initial);
113 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
114 else if let Some(start) = find_iter.next() { start + boundary.len() }
115 else { throw!(anyhow!("initial boundary not found")) };
117 let comp = multipart::process_component
118 (&mut warnings, &initial[start..], PartName::m)?
119 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
121 if comp.name != PartName::m { throw!(anyhow!(
122 r#"first multipart component must be name="m""#
125 let mut meta = MetadataFieldIterator::new(comp.payload_start);
127 let client: ClientName = meta.need_parse().context("client addr")?;
129 let mut hmac_got = [0; HMAC_L];
130 let (client_time, hmac_got_l) = (||{
131 let token: &str = meta.need_next().context(r#"find in "m""#)?;
132 let (time_t, hmac_b64) = token.split_once(' ')
133 .ok_or_else(|| anyhow!("split"))?;
134 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
136 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
138 &mut &mut hmac_got[..]
139 ).context("parse b64 token")?;
140 let l = l.try_into()?;
141 Ok::<_,AE>((time_t, l))
142 })().context("token")?;
143 let hmac_got = &hmac_got[0..hmac_got_l];
145 let client = all_clients.get(&client);
147 // We attempt to hide whether the client exists we don't try to
148 // hide the hash lookup computationgs, but we do try to hide the
149 // HMAC computation by always doing it. We hope that the compiler
150 // doesn't produce a specialised implementation for the dummy
152 let client_exists = subtle::Choice::from(client.is_some() as u8);
153 let secret = client.map(|c| c.ic.secret.0.as_bytes());
154 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
155 let client_time_s = format!("{:x}", client_time);
156 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
157 // We also definitely want a consttime memeq for the hmac value
158 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
159 //dbg!(DumpHex(&hmac_exp), client.is_some());
160 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
161 if ! bool::from(hmac_ok & client_exists) {
162 throw!(anyhow!("xxx should be a 403 error"));
165 let client = client.unwrap();
166 let now = time_t_now();
167 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
168 if let Some(a_ahead) = a.checked_sub(b) {
169 if a_ahead > client.ic.max_clock_skew.as_secs() {
170 throw!(anyhow!("too much clock skew (client {} by {})",
171 c_ahead_behind, a_ahead));
176 chk_skew(client_time, now, "ahead")?;
177 chk_skew(now, client_time, "behind")?;
179 let initial_remaining = meta.remaining_bytes_len();
181 //eprintln!("boundary={:?} start={} name={:?} client={}",
182 // boundary, start, &comp.name, &client.ic);
184 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
185 let wreq = WebRequest {
190 warnings: mem::take(&mut warnings),
193 trace!("{} request", &client.ic);
195 client.web.try_send(wreq)
196 .map_err(|_| anyhow!("client task shut down!"))?;
198 let reply: WebResponse = reply_recv.await?;
199 warnings = reply.warnings;
206 eprintln!("error={}", e);
210 eprintln!("warnings={:?}", &warnings);
212 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
215 #[allow(unused_variables)] // xxx
216 async fn run_client(ic: Arc<InstanceConfig>,
217 mut web: mpsc::Receiver<WebRequest>)
221 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
222 max_requests_outstanding: u32,
224 let mut outstanding: VecDeque<Outstanding> = default();
225 let downbound: VecDeque<(/*xxx*/)> = default();
227 let try_send_response = |
228 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
229 response: WebResponse
231 reply_to.send(response)
232 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
237 if ! downbound.is_empty() {
238 outstanding.pop_front()
239 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
240 |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
242 Some(outstanding.remove(i).unwrap())
247 let response = WebResponse {
252 try_send_response(ret.reply_to, response);
259 initial, initial_remaining, length_hint, mut body,
261 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
265 let whole_request = read_limited_bytes(
266 ic.max_batch_up.sat(),
270 ).await.context("read request body")?;
272 dbg!(whole_request.len());
276 multipart::ComponentIterator::resume_mid_component(
277 &initial[initial_remaining..],
282 Ok(()) => outstanding.push_back(Outstanding {
284 max_requests_outstanding: 42, // xxx
287 try_send_response(reply_to, WebResponse {
296 //Err(anyhow!("xxx"))
301 let opts = Opts::from_args();
307 let (global, ipif) = config::startup(
308 "hippotatd", LinkEnd::Server,
309 &opts.config, &opts.log, |ics|
311 let global = config::InstanceConfigGlobal::from(&ics);
312 let ipif = Ipif::start(&global.ipif, None)?;
314 let all_clients: AllClients = ics.into_iter().map(|ic| {
315 let ic = Arc::new(ic);
317 let (web_send, web_recv) = mpsc::channel(
318 5 // xxx should me max_requests_outstanding but that's
319 // marked client-only so needs rework
322 let ic_ = ic.clone();
323 tasks.push((tokio::spawn(async move {
324 run_client(ic_, web_recv).await.void_unwrap_err()
325 }), format!("client {}", &ic)));
333 let all_clients = Arc::new(all_clients);
335 for addr in &global.addrs {
336 let all_clients_ = all_clients.clone();
337 let make_service = hyper::service::make_service_fn(move |_conn| {
338 let all_clients_ = all_clients_.clone();
339 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
340 handle(all_clients_.clone(), req)
344 let addr = SocketAddr::new(*addr, global.port);
345 let server = hyper::Server::try_bind(&addr)
347 .http1_preserve_header_case(true)
348 .serve(make_service);
349 info!("listening on {}", &addr);
350 let task = tokio::task::spawn(async move {
352 Ok(()) => anyhow!("shut down?!"),
356 tasks.push((task, format!("http server {}", addr)));
362 let died = future::select_all(
363 tasks.iter_mut().map(|e| &mut e.0)
365 error!("xxx {:?}", &died);
367 ipif.quitting(None).await;