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 mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
65 let boundary = match (||{
66 let mut ctypes = req.headers().get_all("Content-Type").iter();
67 let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
68 if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
69 let t = t.to_str().context("interpret Content-Type as utf-8")?;
70 let t: mime::Mime = t.parse().context("parse Content-Type")?;
71 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
72 let b = mime::BOUNDARY;
73 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
74 if t.subtype() != "form-data" {
75 warnings.add(&"Content-Type not /form-data")?;
77 let b = mkboundary(b.as_str());
82 warnings.add(&e.wrap_err("guessing boundary"))?;
87 let mut body = req.into_body();
88 let initial = match read_limited_bytes(
89 METADATA_MAX_LEN, default(), &mut body
92 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
93 Err(ReadLimitedError::Hyper(e)) => throw!(e),
96 let finder = memmem::Finder::new(&boundary);
97 let mut find_iter = finder.find_iter(&initial);
99 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
100 else if let Some(start) = find_iter.next() { start + boundary.len() }
101 else { throw!(anyhow!("initial boundary not found")) };
103 let comp = multipart::process_component
104 (&mut warnings, &initial[start..], PartName::m)?
105 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
107 if comp.name != PartName::m { throw!(anyhow!(
108 r#"first multipart component must be name="m""#
111 let mut meta = MetadataFieldIterator::new(comp.payload_start);
113 let client: ClientName = meta.need_parse().context("client addr")?;
115 let mut hmac_got = [0; HMAC_L];
116 let (client_time, hmac_got_l) = (||{
117 let token: &str = meta.need_next().context(r#"find in "m""#)?;
118 let (time_t, hmac_b64) = token.split_once(' ')
119 .ok_or_else(|| anyhow!("split"))?;
120 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
122 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
124 &mut &mut hmac_got[..]
125 ).context("parse b64 token")?;
126 let l = l.try_into()?;
127 Ok::<_,AE>((time_t, l))
128 })().context("token")?;
129 let hmac_got = &hmac_got[0..hmac_got_l];
131 let client = all_clients.get(&client);
133 // We attempt to hide whether the client exists we don't try to
134 // hide the hash lookup computationgs, but we do try to hide the
135 // HMAC computation by always doing it. We hope that the compiler
136 // doesn't produce a specialised implementation for the dummy
138 let client_exists = subtle::Choice::from(client.is_some() as u8);
139 let secret = client.map(|c| c.ic.secret.0.as_bytes());
140 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
141 let client_time_s = format!("{:x}", client_time);
142 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
143 // We also definitely want a consttime memeq for the hmac value
144 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
145 //dbg!(DumpHex(&hmac_exp), client.is_some());
146 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
147 if ! bool::from(hmac_ok & client_exists) {
148 throw!(anyhow!("xxx should be a 403 error"));
151 let client = client.unwrap();
152 let now = time_t_now();
153 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
154 if let Some(a_ahead) = a.checked_sub(b) {
155 if a_ahead > client.ic.max_clock_skew.as_secs() {
156 throw!(anyhow!("too much clock skew (client {} by {})",
157 c_ahead_behind, a_ahead));
162 chk_skew(client_time, now, "ahead")?;
163 chk_skew(now, client_time, "behind")?;
165 let initial_remaining = meta.remaining_bytes_len();
167 //eprintln!("boundary={:?} start={} name={:?} client={}",
168 // boundary, start, &comp.name, &client.ic);
170 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
171 let wreq = WebRequest {
175 warnings: mem::take(&mut warnings),
178 trace!("{} request", &client.ic);
180 client.web.try_send(wreq)
181 .map_err(|_| anyhow!("client task shut down!"))?;
183 let reply: WebResponse = reply_recv.await?;
184 warnings = reply.warnings;
191 eprintln!("error={}", e);
195 eprintln!("warnings={:?}", &warnings);
197 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
200 #[allow(unused_variables)] // xxx
201 async fn run_client(_ic: Arc<InstanceConfig>,
202 mut web: mpsc::Receiver<WebRequest>)
206 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
207 max_requests_outstanding: u32,
209 let mut outstanding: VecDeque<Outstanding> = default();
210 let downbound: VecDeque<(/*xxx*/)> = default();
212 let try_send_response = |
213 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
214 response: WebResponse
216 reply_to.send(response)
217 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
222 if ! downbound.is_empty() {
223 outstanding.pop_front()
224 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
225 |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
227 Some(outstanding.remove(i).unwrap())
232 let response = WebResponse {
237 try_send_response(ret.reply_to, response);
244 initial, initial_remaining, body,
246 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
252 let whole_request = body.try_fold(
254 |mut w, by| async move { w.extend_from_slice(&by); Ok(w) },
255 ).await.context("read request body")?;
257 dbg!(whole_request.len());
261 multipart::ComponentIterator::resume_mid_component(
262 &initial[initial_remaining..],
267 Ok(()) => outstanding.push_back(Outstanding {
269 max_requests_outstanding: 42, // xxx
272 try_send_response(reply_to, WebResponse {
281 //Err(anyhow!("xxx"))
286 let opts = Opts::from_args();
292 let (global, ipif) = config::startup(
293 "hippotatd", LinkEnd::Server,
294 &opts.config, &opts.log, |ics|
296 let global = config::InstanceConfigGlobal::from(&ics);
297 let ipif = Ipif::start(&global.ipif, None)?;
299 let all_clients: AllClients = ics.into_iter().map(|ic| {
300 let ic = Arc::new(ic);
302 let (web_send, web_recv) = mpsc::channel(
303 5 // xxx should me max_requests_outstanding but that's
304 // marked client-only so needs rework
307 let ic_ = ic.clone();
308 tasks.push((tokio::spawn(async move {
309 run_client(ic_, web_recv).await.void_unwrap_err()
310 }), format!("client {}", &ic)));
318 let all_clients = Arc::new(all_clients);
320 for addr in &global.addrs {
321 let all_clients_ = all_clients.clone();
322 let make_service = hyper::service::make_service_fn(move |_conn| {
323 let all_clients_ = all_clients_.clone();
324 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
325 handle(all_clients_.clone(), req)
329 let addr = SocketAddr::new(*addr, global.port);
330 let server = hyper::Server::try_bind(&addr)
332 .http1_preserve_header_case(true)
333 .serve(make_service);
334 info!("listening on {}", &addr);
335 let task = tokio::task::spawn(async move {
337 Ok(()) => anyhow!("shut down?!"),
341 tasks.push((task, format!("http server {}", addr)));
347 let died = future::select_all(
348 tasks.iter_mut().map(|e| &mut e.0)
350 error!("xxx {:?}", &died);
352 ipif.quitting(None).await;