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: tokio::sync::oneshot::Sender<WebResponse>,
37 /// Reply from client task to hyper worker pool task
38 type WebResponse = Result<WebResponseData, AE>;
39 type WebResponseData = ();
42 all_clients: Arc<AllClients>,
43 req: hyper::Request<hyper::Body>
44 ) -> Result<hyper::Response<hyper::Body>, Void> {
45 if req.method() == Method::GET {
46 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
47 resp.headers_mut().insert(
49 "text/plain; charset=US-ASCII".try_into().unwrap()
54 let mut warnings: Warnings = default();
58 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
59 let boundary = match (||{
60 let mut ctypes = req.headers().get_all("Content-Type").iter();
61 let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
62 if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
63 let t = t.to_str().context("interpret Content-Type as utf-8")?;
64 let t: mime::Mime = t.parse().context("parse Content-Type")?;
65 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
66 let b = mime::BOUNDARY;
67 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
68 if t.subtype() != "form-data" {
69 warnings.add(&"Content-Type not /form-data")?;
71 let b = mkboundary(b.as_str());
76 warnings.add(&e.wrap_err("guessing boundary"))?;
81 let mut body = req.into_body();
82 let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
84 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
85 Err(ReadLimitedError::Hyper(e)) => throw!(e),
88 let finder = memmem::Finder::new(&boundary);
89 let mut find_iter = finder.find_iter(&initial);
91 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
92 else if let Some(start) = find_iter.next() { start + boundary.len() }
93 else { throw!(anyhow!("initial boundary not found")) };
95 let comp = multipart::process_component
96 (&mut warnings, &initial[start..], PartName::m)?
97 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
99 if comp.name != PartName::m { throw!(anyhow!(
100 r#"first multipart component must be name="m""#
103 let mut meta = MetadataFieldIterator::new(comp.payload_start);
105 let client: ClientName = meta.need_parse().context("client addr")?;
107 let mut hmac_got = [0; HMAC_L];
108 let (client_time, hmac_got_l) = (||{
109 let token: &str = meta.need_next().context(r#"find in "m""#)?;
110 let (time_t, hmac_b64) = token.split_once(' ')
111 .ok_or_else(|| anyhow!("split"))?;
112 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
114 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
116 &mut &mut hmac_got[..]
117 ).context("parse b64 token")?;
118 let l = l.try_into()?;
119 Ok::<_,AE>((time_t, l))
120 })().context("token")?;
121 let hmac_got = &hmac_got[0..hmac_got_l];
123 let client = all_clients.get(&client);
125 // We attempt to hide whether the client exists we don't try to
126 // hide the hash lookup computationgs, but we do try to hide the
127 // HMAC computation by always doing it. We hope that the compiler
128 // doesn't produce a specialised implementation for the dummy
130 let client_exists = subtle::Choice::from(client.is_some() as u8);
131 let secret = client.map(|c| c.ic.secret.0.as_bytes());
132 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
133 let client_time_s = format!("{:x}", client_time);
134 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
135 // We also definitely want a consttime memeq for the hmac value
136 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
137 //dbg!(DumpHex(&hmac_exp), client.is_some());
138 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
139 if ! bool::from(hmac_ok & client_exists) {
140 throw!(anyhow!("xxx should be a 403 error"));
143 let client = client.unwrap();
144 let now = time_t_now();
145 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
146 if let Some(a_ahead) = a.checked_sub(b) {
147 if a_ahead > client.ic.max_clock_skew.as_secs() {
148 throw!(anyhow!("too much clock skew (client {} by {})",
149 c_ahead_behind, a_ahead));
154 chk_skew(client_time, now, "ahead")?;
155 chk_skew(now, client_time, "behind")?;
157 let initial_remaining = meta.remaining_bytes_len();
159 //eprintln!("boundary={:?} start={} name={:?} client={}",
160 // boundary, start, &comp.name, &client.ic);
162 let (reply, reply_recv) = tokio::sync::oneshot::channel();
163 let wreq = WebRequest {
169 trace!("{} request", &client.ic);
171 client.web.try_send(wreq)
172 .map_err(|_| anyhow!("client task shut down!"))?;
174 let reply: WebResponse = reply_recv.await?;
181 eprintln!("error={}", e);
185 eprintln!("warnings={:?}", &warnings);
187 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
190 async fn run_client(_ic: Arc<InstanceConfig>,
191 mut web: mpsc::Receiver<WebRequest>)
195 reply: tokio::sync::oneshot::Sender<WebResponse>,
196 max_requests_outstanding: u32,
198 let mut outstanding: VecDeque<Outstanding> = default();
199 let downbound: VecDeque<(/*xxx*/)> = default();
203 if ! downbound.is_empty() {
204 outstanding.pop_front()
205 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
206 |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
208 Some(outstanding.remove(i).unwrap())
213 ret.reply.send(Ok(() /* dummy */))
214 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
220 let req = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
221 outstanding.push_back(Outstanding {
223 max_requests_outstanding: 42, // xxx
228 //Err(anyhow!("xxx"))
233 let opts = Opts::from_args();
239 let (global, ipif) = config::startup(
240 "hippotatd", LinkEnd::Server,
241 &opts.config, &opts.log, |ics|
243 let global = config::InstanceConfigGlobal::from(&ics);
244 let ipif = Ipif::start(&global.ipif, None)?;
246 let all_clients: AllClients = ics.into_iter().map(|ic| {
247 let ic = Arc::new(ic);
249 let (web_send, web_recv) = mpsc::channel(
250 5 // xxx should me max_requests_outstanding but that's
251 // marked client-only so needs rework
254 let ic_ = ic.clone();
255 tasks.push((tokio::spawn(async move {
256 run_client(ic_, web_recv).await.void_unwrap_err()
257 }), format!("client {}", &ic)));
265 let all_clients = Arc::new(all_clients);
267 for addr in &global.addrs {
268 let all_clients_ = all_clients.clone();
269 let make_service = hyper::service::make_service_fn(move |_conn| {
270 let all_clients_ = all_clients_.clone();
271 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
272 handle(all_clients_.clone(), req)
276 let addr = SocketAddr::new(*addr, global.port);
277 let server = hyper::Server::try_bind(&addr)
279 .http1_preserve_header_case(true)
280 .serve(make_service);
281 info!("listening on {}", &addr);
282 let task = tokio::task::spawn(async move {
284 Ok(()) => anyhow!("shut down?!"),
288 tasks.push((task, format!("http server {}", addr)));
294 let died = future::select_all(
295 tasks.iter_mut().map(|e| &mut e.0)
297 error!("xxx {:?}", &died);
299 ipif.quitting(None).await;