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;
20 config: config::InstanceConfigGlobal,
21 all_clients: HashMap<ClientName, Client>,
26 ic: Arc<InstanceConfig>,
27 web: tokio::sync::mpsc::Sender<WebRequest>,
30 /// Sent from hyper worker pool task to client task
31 #[allow(dead_code)] // xxx
34 // initial part of body
35 // used up to and including first 2 lines of metadata
36 // end delimiter for the metadata not yet located, but in here somewhere
38 initial_remaining: usize,
40 body: hyper::body::Body,
41 boundary_finder: multipart::BoundaryFinder,
42 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
47 /// Reply from client task to hyper worker pool task
48 #[allow(dead_code)] // xxx
52 data: Result<WebResponseData, AE>,
55 type WebResponseData = Vec<u8>;
57 #[throws(PacketError)]
58 pub fn route_packet(_global: &Global,
59 conn: &str, link: &dyn Display,
60 packet: Box<[u8]>, daddr: IpAddr)
63 trace!("{} {} discarding packet daddr={:?} len={}",
64 conn, link, daddr, packet.len());
70 req: hyper::Request<hyper::Body>
71 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
72 if req.method() == Method::GET {
73 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
74 resp.headers_mut().insert(
76 "text/plain; charset=US-ASCII".try_into().unwrap()
81 let mut warnings: Warnings = default();
85 let get_header = |hn: &str| {
86 let mut values = req.headers().get_all(hn).iter();
87 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
88 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
89 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
93 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
94 let boundary = match (||{
95 let t = get_header("Content-Type")?;
96 let t: mime::Mime = t.parse().context("parse Content-Type")?;
97 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
98 let b = mime::BOUNDARY;
99 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
100 if t.subtype() != "form-data" {
101 warnings.add(&"Content-Type not /form-data")?;
103 let b = mkboundary(b.as_str());
108 warnings.add(&e.wrap_err("guessing boundary"))?;
113 let length_hint: usize = (||{
114 let clength = get_header("Content-Length")?;
115 let clength = clength.parse().context("parse Content-Length")?;
118 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
121 let mut body = req.into_body();
122 let initial = match read_limited_bytes(
123 METADATA_MAX_LEN, default(), length_hint, &mut body
126 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
127 Err(ReadLimitedError::Hyper(e)) => throw!(e),
130 let boundary_finder = memmem::Finder::new(&boundary);
131 let mut boundary_iter = boundary_finder.find_iter(&initial);
133 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
134 else if let Some(start) = boundary_iter.next() { start + boundary.len() }
135 else { throw!(anyhow!("initial boundary not found")) };
137 let comp = multipart::process_boundary
138 (&mut warnings, &initial[start..], PartName::m)?
139 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
141 if comp.name != PartName::m { throw!(anyhow!(
142 r#"first multipart component must be name="m""#
145 let mut meta = MetadataFieldIterator::new(comp.payload);
147 let client: ClientName = meta.need_parse().context("client addr")?;
149 let mut hmac_got = [0; HMAC_L];
150 let (client_time, hmac_got_l) = (||{
151 let token: &str = meta.need_next().context(r#"find in "m""#)?;
152 let (time_t, hmac_b64) = token.split_once(' ')
153 .ok_or_else(|| anyhow!("split"))?;
154 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
156 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
158 &mut &mut hmac_got[..]
159 ).context("parse b64 token")?;
160 let l = l.try_into()?;
161 Ok::<_,AE>((time_t, l))
162 })().context("token")?;
163 let hmac_got = &hmac_got[0..hmac_got_l];
165 let client_name = client;
166 let client = global.all_clients.get(&client_name);
168 // We attempt to hide whether the client exists we don't try to
169 // hide the hash lookup computationgs, but we do try to hide the
170 // HMAC computation by always doing it. We hope that the compiler
171 // doesn't produce a specialised implementation for the dummy
173 let client_exists = subtle::Choice::from(client.is_some() as u8);
174 let secret = client.map(|c| c.ic.secret.0.as_bytes());
175 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
176 let client_time_s = format!("{:x}", client_time);
177 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
178 // We also definitely want a consttime memeq for the hmac value
179 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
180 //dbg!(DumpHex(&hmac_exp), client.is_some());
181 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
182 if ! bool::from(hmac_ok & client_exists) {
183 debug!("{} rejected client {}", &conn, &client_name);
184 let body = hyper::Body::from("Not authorised\r\n");
186 hyper::Response::builder()
187 .status(hyper::StatusCode::FORBIDDEN)
188 .header("Content-Type", r#"text/plain; charset="utf-8""#)
193 let client = client.unwrap();
194 let now = time_t_now();
195 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
196 if let Some(a_ahead) = a.checked_sub(b) {
197 if a_ahead > client.ic.max_clock_skew.as_secs() {
198 throw!(anyhow!("too much clock skew (client {} by {})",
199 c_ahead_behind, a_ahead));
204 chk_skew(client_time, now, "ahead")?;
205 chk_skew(now, client_time, "behind")?;
207 let initial_remaining = meta.remaining_bytes_len();
209 //eprintln!("boundary={:?} start={} name={:?} client={}",
210 // boundary, start, &comp.name, &client.ic);
212 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
213 trace!("{} {} request, Content-Length={}",
214 &conn, &client_name, length_hint);
215 let wreq = WebRequest {
219 boundary_finder: boundary_finder.into_owned(),
221 warnings: mem::take(&mut warnings),
226 client.web.try_send(wreq)
227 .map_err(|_| anyhow!("client task shut down!"))?;
229 let reply: WebResponse = reply_recv.await?;
230 warnings = reply.warnings;
231 let data = reply.data?;
233 if warnings.warnings.is_empty() {
234 trace!("{} {} responding, {}",
235 &conn, &client_name, data.len());
237 debug!("{} {} responding, {} warnings={:?}",
238 &conn, &client_name, data.len(),
242 let data = hyper::Body::from(data);
244 hyper::Response::builder()
245 .header("Content-Type", r#"application/octet-stream"#)
248 }.await.unwrap_or_else(|e| {
249 debug!("{} error {}", &conn, &e);
250 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
251 for w in warnings.warnings {
252 write!(errmsg, "warning: {}\n", w).unwrap();
254 hyper::Response::builder()
255 .status(hyper::StatusCode::BAD_REQUEST)
256 .header("Content-Type", r#"text/plain; charset="utf-8""#)
261 #[allow(unused_variables)] // xxx
262 #[allow(unused_mut)] // xxx
263 async fn run_client(global: Arc<Global>,
264 ic: Arc<InstanceConfig>,
265 mut web: mpsc::Receiver<WebRequest>)
269 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
270 oi: OutstandingInner,
273 struct OutstandingInner {
274 target_requests_outstanding: u32,
276 let mut outstanding: VecDeque<Outstanding> = default();
277 let downbound: VecDeque<(/*xxx*/)> = default();
279 let try_send_response = |
280 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
281 response: WebResponse
283 reply_to.send(response)
284 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
289 if ! downbound.is_empty() {
290 outstanding.pop_front()
291 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
292 |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
294 Some(outstanding.remove(i).unwrap())
299 let response = WebResponse {
300 data: Ok(vec![ /* xxx */ ]),
304 try_send_response(ret.reply_to, response);
311 initial, initial_remaining, length_hint, mut body,
313 reply_to, conn, mut warnings,
314 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
318 let initial_used = initial.len() - initial_remaining;
320 let whole_request = read_limited_bytes(
321 ic.max_batch_up.sat(),
325 ).await.context("read request body")?;
327 let (meta, mut comps) =
328 multipart::ComponentIterator::resume_mid_component(
329 &whole_request[initial_used..],
331 ).context("resume parsing body, after auth checks")?;
333 let mut meta = MetadataFieldIterator::new(&meta);
336 { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
337 let $server:ident, $client:ident $($code:tt)*
341 let $client $($code)*
343 if $client $badcmp $server {
344 throw!(anyhow!("mismatch: client={:?} {} server={:?}",
345 $client, stringify!($badcmp), $server));
349 })().context(stringify!($v))?;
355 target_requests_outstanding, ( != ), client,
356 let server, client: u32 = meta.need_parse()?;
360 http_timeout, ( > ), client,
361 let server, client = Duration::from_secs(meta.need_parse()?);
366 let server, client: u32 = meta.parse()?.unwrap_or(server);
370 max_batch_down, (), min(client, server),
371 let server, client: u32 = meta.parse()?.unwrap_or(server);
375 max_batch_up, ( > ), client,
376 let server, client = meta.parse()?.unwrap_or(server);
379 while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
380 if comp.name != PartName::d {
381 warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
383 checkn(Mime2Slip, mtu, comp.payload, |header| {
384 let saddr = ip_packet_addr::<false>(header)?;
385 if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
386 let daddr = ip_packet_addr::<true>(header)?;
388 }, |(daddr,packet)| route_packet(
389 &global, &conn, &ic.link.client, daddr,packet
391 |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
395 let oi = OutstandingInner {
396 target_requests_outstanding,
400 Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
402 try_send_response(reply_to, WebResponse {
411 //Err(anyhow!("xxx"))
416 let opts = Opts::from_args();
422 let (global, ipif) = config::startup(
423 "hippotatd", LinkEnd::Server,
424 &opts.config, &opts.log, |ics|
426 let global_config = config::InstanceConfigGlobal::from(&ics);
428 let ipif = Ipif::start(&global_config.ipif, None)?;
430 let ics = ics.into_iter().map(Arc::new).collect_vec();
431 let (client_handles_send, client_handles_recv) = ics.iter()
432 .map(|_ic| mpsc::channel(
433 5 // xxx should me max_requests_outstanding but that's
434 // marked client-only so needs rework
435 )).unzip::<_,_,Vec<_>,Vec<_>>();
437 let all_clients = izip!(
440 ).map(|(ic, web_send)| {
448 let global = Arc::new(Global {
449 config: global_config,
453 for (ic, web_recv) in izip!(
457 let global_ = global.clone();
458 let ic_ = ic.clone();
459 tasks.push((tokio::spawn(async move {
460 run_client(global_, ic_, web_recv).await.void_unwrap_err()
461 }), format!("client {}", &ic)));
464 for addr in &global.config.addrs {
465 let global_ = global.clone();
466 let make_service = hyper::service::make_service_fn(
467 move |conn: &hyper::server::conn::AddrStream| {
468 let global_ = global_.clone();
469 let conn = Arc::new(format!("[{}]", conn.remote_addr()));
470 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
471 handle(conn.clone(), global_.clone(), req)
476 let addr = SocketAddr::new(*addr, global.config.port);
477 let server = hyper::Server::try_bind(&addr)
479 .http1_preserve_header_case(true)
480 .serve(make_service);
481 info!("listening on {}", &addr);
482 let task = tokio::task::spawn(async move {
484 Ok(()) => anyhow!("shut down?!"),
488 tasks.push((task, format!("http server {}", addr)));
494 let died = future::select_all(
495 tasks.iter_mut().map(|e| &mut e.0)
497 error!("xxx {:?}", &died);
499 ipif.quitting(None).await;