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(METADATA_MAX_LEN, &mut body).await {
90 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
91 Err(ReadLimitedError::Hyper(e)) => throw!(e),
94 let finder = memmem::Finder::new(&boundary);
95 let mut find_iter = finder.find_iter(&initial);
97 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
98 else if let Some(start) = find_iter.next() { start + boundary.len() }
99 else { throw!(anyhow!("initial boundary not found")) };
101 let comp = multipart::process_component
102 (&mut warnings, &initial[start..], PartName::m)?
103 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
105 if comp.name != PartName::m { throw!(anyhow!(
106 r#"first multipart component must be name="m""#
109 let mut meta = MetadataFieldIterator::new(comp.payload_start);
111 let client: ClientName = meta.need_parse().context("client addr")?;
113 let mut hmac_got = [0; HMAC_L];
114 let (client_time, hmac_got_l) = (||{
115 let token: &str = meta.need_next().context(r#"find in "m""#)?;
116 let (time_t, hmac_b64) = token.split_once(' ')
117 .ok_or_else(|| anyhow!("split"))?;
118 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
120 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
122 &mut &mut hmac_got[..]
123 ).context("parse b64 token")?;
124 let l = l.try_into()?;
125 Ok::<_,AE>((time_t, l))
126 })().context("token")?;
127 let hmac_got = &hmac_got[0..hmac_got_l];
129 let client = all_clients.get(&client);
131 // We attempt to hide whether the client exists we don't try to
132 // hide the hash lookup computationgs, but we do try to hide the
133 // HMAC computation by always doing it. We hope that the compiler
134 // doesn't produce a specialised implementation for the dummy
136 let client_exists = subtle::Choice::from(client.is_some() as u8);
137 let secret = client.map(|c| c.ic.secret.0.as_bytes());
138 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
139 let client_time_s = format!("{:x}", client_time);
140 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
141 // We also definitely want a consttime memeq for the hmac value
142 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
143 //dbg!(DumpHex(&hmac_exp), client.is_some());
144 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
145 if ! bool::from(hmac_ok & client_exists) {
146 throw!(anyhow!("xxx should be a 403 error"));
149 let client = client.unwrap();
150 let now = time_t_now();
151 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
152 if let Some(a_ahead) = a.checked_sub(b) {
153 if a_ahead > client.ic.max_clock_skew.as_secs() {
154 throw!(anyhow!("too much clock skew (client {} by {})",
155 c_ahead_behind, a_ahead));
160 chk_skew(client_time, now, "ahead")?;
161 chk_skew(now, client_time, "behind")?;
163 let initial_remaining = meta.remaining_bytes_len();
165 //eprintln!("boundary={:?} start={} name={:?} client={}",
166 // boundary, start, &comp.name, &client.ic);
168 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
169 let wreq = WebRequest {
173 warnings: mem::take(&mut warnings),
176 trace!("{} request", &client.ic);
178 client.web.try_send(wreq)
179 .map_err(|_| anyhow!("client task shut down!"))?;
181 let reply: WebResponse = reply_recv.await?;
182 warnings = reply.warnings;
189 eprintln!("error={}", e);
193 eprintln!("warnings={:?}", &warnings);
195 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
198 #[allow(unused_variables)] // xxx
199 async fn run_client(_ic: Arc<InstanceConfig>,
200 mut web: mpsc::Receiver<WebRequest>)
204 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
205 max_requests_outstanding: u32,
207 let mut outstanding: VecDeque<Outstanding> = default();
208 let downbound: VecDeque<(/*xxx*/)> = default();
210 let try_send_response = |
211 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
212 response: WebResponse
214 reply_to.send(response)
215 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
220 if ! downbound.is_empty() {
221 outstanding.pop_front()
222 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
223 |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
225 Some(outstanding.remove(i).unwrap())
230 let response = WebResponse {
235 try_send_response(ret.reply_to, response);
242 initial, initial_remaining, body,
244 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
248 let whole_request = body.try_fold(
250 |mut w, by| async move { w.extend_from_slice(&by); Ok(w) },
251 ).await.context("read request body")?;
253 dbg!(whole_request.len());
257 multipart::ComponentIterator::resume_mid_component(
258 &initial[initial_remaining..],
263 Ok(()) => outstanding.push_back(Outstanding {
265 max_requests_outstanding: 42, // xxx
268 try_send_response(reply_to, WebResponse {
277 //Err(anyhow!("xxx"))
282 let opts = Opts::from_args();
288 let (global, ipif) = config::startup(
289 "hippotatd", LinkEnd::Server,
290 &opts.config, &opts.log, |ics|
292 let global = config::InstanceConfigGlobal::from(&ics);
293 let ipif = Ipif::start(&global.ipif, None)?;
295 let all_clients: AllClients = ics.into_iter().map(|ic| {
296 let ic = Arc::new(ic);
298 let (web_send, web_recv) = mpsc::channel(
299 5 // xxx should me max_requests_outstanding but that's
300 // marked client-only so needs rework
303 let ic_ = ic.clone();
304 tasks.push((tokio::spawn(async move {
305 run_client(ic_, web_recv).await.void_unwrap_err()
306 }), format!("client {}", &ic)));
314 let all_clients = Arc::new(all_clients);
316 for addr in &global.addrs {
317 let all_clients_ = all_clients.clone();
318 let make_service = hyper::service::make_service_fn(move |_conn| {
319 let all_clients_ = all_clients_.clone();
320 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
321 handle(all_clients_.clone(), req)
325 let addr = SocketAddr::new(*addr, global.port);
326 let server = hyper::Server::try_bind(&addr)
328 .http1_preserve_header_case(true)
329 .serve(make_service);
330 info!("listening on {}", &addr);
331 let task = tokio::task::spawn(async move {
333 Ok(()) => anyhow!("shut down?!"),
337 tasks.push((task, format!("http server {}", addr)));
343 let died = future::select_all(
344 tasks.iter_mut().map(|e| &mut e.0)
346 error!("xxx {:?}", &died);
348 ipif.quitting(None).await;