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,
33 body: hyper::body::Body,
34 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
38 /// Reply from client task to hyper worker pool task
39 #[allow(dead_code)] // xxx
42 data: Result<WebResponseData, AE>,
45 type WebResponseData = ();
48 all_clients: Arc<AllClients>,
49 req: hyper::Request<hyper::Body>
50 ) -> Result<hyper::Response<hyper::Body>, Void> {
51 if req.method() == Method::GET {
52 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
53 resp.headers_mut().insert(
55 "text/plain; charset=US-ASCII".try_into().unwrap()
60 let mut warnings: Warnings = default();
64 let get_header = |hn: &str| {
65 let mut values = req.headers().get_all(hn).iter();
66 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
67 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
68 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
72 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
73 let boundary = match (||{
74 let t = get_header("Content-Type")?;
75 let t: mime::Mime = t.parse().context("parse Content-Type")?;
76 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
77 let b = mime::BOUNDARY;
78 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
79 if t.subtype() != "form-data" {
80 warnings.add(&"Content-Type not /form-data")?;
82 let b = mkboundary(b.as_str());
87 warnings.add(&e.wrap_err("guessing boundary"))?;
92 let length_hint: usize = (||{
93 let clength = get_header("Content-Length")?;
94 let clength = clength.parse().context("parse Content-Length")?;
97 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
100 let mut body = req.into_body();
101 let initial = match read_limited_bytes(
102 METADATA_MAX_LEN, default(), length_hint, &mut body
105 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
106 Err(ReadLimitedError::Hyper(e)) => throw!(e),
109 let finder = memmem::Finder::new(&boundary);
110 let mut find_iter = finder.find_iter(&initial);
112 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
113 else if let Some(start) = find_iter.next() { start + boundary.len() }
114 else { throw!(anyhow!("initial boundary not found")) };
116 let comp = multipart::process_component
117 (&mut warnings, &initial[start..], PartName::m)?
118 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
120 if comp.name != PartName::m { throw!(anyhow!(
121 r#"first multipart component must be name="m""#
124 let mut meta = MetadataFieldIterator::new(comp.payload_start);
126 let client: ClientName = meta.need_parse().context("client addr")?;
128 let mut hmac_got = [0; HMAC_L];
129 let (client_time, hmac_got_l) = (||{
130 let token: &str = meta.need_next().context(r#"find in "m""#)?;
131 let (time_t, hmac_b64) = token.split_once(' ')
132 .ok_or_else(|| anyhow!("split"))?;
133 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
135 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
137 &mut &mut hmac_got[..]
138 ).context("parse b64 token")?;
139 let l = l.try_into()?;
140 Ok::<_,AE>((time_t, l))
141 })().context("token")?;
142 let hmac_got = &hmac_got[0..hmac_got_l];
144 let client = all_clients.get(&client);
146 // We attempt to hide whether the client exists we don't try to
147 // hide the hash lookup computationgs, but we do try to hide the
148 // HMAC computation by always doing it. We hope that the compiler
149 // doesn't produce a specialised implementation for the dummy
151 let client_exists = subtle::Choice::from(client.is_some() as u8);
152 let secret = client.map(|c| c.ic.secret.0.as_bytes());
153 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
154 let client_time_s = format!("{:x}", client_time);
155 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
156 // We also definitely want a consttime memeq for the hmac value
157 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
158 //dbg!(DumpHex(&hmac_exp), client.is_some());
159 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
160 if ! bool::from(hmac_ok & client_exists) {
161 throw!(anyhow!("xxx should be a 403 error"));
164 let client = client.unwrap();
165 let now = time_t_now();
166 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
167 if let Some(a_ahead) = a.checked_sub(b) {
168 if a_ahead > client.ic.max_clock_skew.as_secs() {
169 throw!(anyhow!("too much clock skew (client {} by {})",
170 c_ahead_behind, a_ahead));
175 chk_skew(client_time, now, "ahead")?;
176 chk_skew(now, client_time, "behind")?;
178 let initial_remaining = meta.remaining_bytes_len();
180 //eprintln!("boundary={:?} start={} name={:?} client={}",
181 // boundary, start, &comp.name, &client.ic);
183 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
184 let wreq = WebRequest {
188 warnings: mem::take(&mut warnings),
191 trace!("{} request", &client.ic);
193 client.web.try_send(wreq)
194 .map_err(|_| anyhow!("client task shut down!"))?;
196 let reply: WebResponse = reply_recv.await?;
197 warnings = reply.warnings;
204 eprintln!("error={}", e);
208 eprintln!("warnings={:?}", &warnings);
210 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
213 #[allow(unused_variables)] // xxx
214 async fn run_client(_ic: Arc<InstanceConfig>,
215 mut web: mpsc::Receiver<WebRequest>)
219 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
220 max_requests_outstanding: u32,
222 let mut outstanding: VecDeque<Outstanding> = default();
223 let downbound: VecDeque<(/*xxx*/)> = default();
225 let try_send_response = |
226 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
227 response: WebResponse
229 reply_to.send(response)
230 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
235 if ! downbound.is_empty() {
236 outstanding.pop_front()
237 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
238 |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
240 Some(outstanding.remove(i).unwrap())
245 let response = WebResponse {
250 try_send_response(ret.reply_to, response);
257 initial, initial_remaining, body,
259 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
265 let whole_request = body.try_fold(
267 |mut w, by| async move { w.extend_from_slice(&by); Ok(w) },
268 ).await.context("read request body")?;
270 dbg!(whole_request.len());
274 multipart::ComponentIterator::resume_mid_component(
275 &initial[initial_remaining..],
280 Ok(()) => outstanding.push_back(Outstanding {
282 max_requests_outstanding: 42, // xxx
285 try_send_response(reply_to, WebResponse {
294 //Err(anyhow!("xxx"))
299 let opts = Opts::from_args();
305 let (global, ipif) = config::startup(
306 "hippotatd", LinkEnd::Server,
307 &opts.config, &opts.log, |ics|
309 let global = config::InstanceConfigGlobal::from(&ics);
310 let ipif = Ipif::start(&global.ipif, None)?;
312 let all_clients: AllClients = ics.into_iter().map(|ic| {
313 let ic = Arc::new(ic);
315 let (web_send, web_recv) = mpsc::channel(
316 5 // xxx should me max_requests_outstanding but that's
317 // marked client-only so needs rework
320 let ic_ = ic.clone();
321 tasks.push((tokio::spawn(async move {
322 run_client(ic_, web_recv).await.void_unwrap_err()
323 }), format!("client {}", &ic)));
331 let all_clients = Arc::new(all_clients);
333 for addr in &global.addrs {
334 let all_clients_ = all_clients.clone();
335 let make_service = hyper::service::make_service_fn(move |_conn| {
336 let all_clients_ = all_clients_.clone();
337 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
338 handle(all_clients_.clone(), req)
342 let addr = SocketAddr::new(*addr, global.port);
343 let server = hyper::Server::try_bind(&addr)
345 .http1_preserve_header_case(true)
346 .serve(make_service);
347 info!("listening on {}", &addr);
348 let task = tokio::task::spawn(async move {
350 Ok(()) => anyhow!("shut down?!"),
354 tasks.push((task, format!("http server {}", addr)));
360 let died = future::select_all(
361 tasks.iter_mut().map(|e| &mut e.0)
363 error!("xxx {:?}", &died);
365 ipif.quitting(None).await;