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 pub type RoutedPacket = Box<[u8]>; // not MIME data
32 /// Sent from hyper worker pool task to client task
33 #[allow(dead_code)] // xxx
36 // initial part of body
37 // used up to and including first 2 lines of metadata
38 // end delimiter for the metadata not yet located, but in here somewhere
40 initial_remaining: usize,
42 body: hyper::body::Body,
43 boundary_finder: multipart::BoundaryFinder,
44 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
49 /// Reply from client task to hyper worker pool task
50 #[allow(dead_code)] // xxx
54 data: Result<WebResponseData, AE>,
57 type WebResponseData = Vec<u8>;
59 #[throws(PacketError)]
60 pub fn route_packet(_global: &Global,
61 conn: &str, link: &dyn Display,
62 packet: RoutedPacket, daddr: IpAddr)
65 trace!("{} {} discarding packet daddr={:?} len={}",
66 conn, link, daddr, packet.len());
72 req: hyper::Request<hyper::Body>
73 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
74 if req.method() == Method::GET {
75 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
76 resp.headers_mut().insert(
78 "text/plain; charset=US-ASCII".try_into().unwrap()
83 let mut warnings: Warnings = default();
87 let get_header = |hn: &str| {
88 let mut values = req.headers().get_all(hn).iter();
89 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
90 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
91 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
95 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
96 let boundary = match (||{
97 let t = get_header("Content-Type")?;
98 let t: mime::Mime = t.parse().context("parse Content-Type")?;
99 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
100 let b = mime::BOUNDARY;
101 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
102 if t.subtype() != "form-data" {
103 warnings.add(&"Content-Type not /form-data")?;
105 let b = mkboundary(b.as_str());
110 warnings.add(&e.wrap_err("guessing boundary"))?;
115 let length_hint: usize = (||{
116 let clength = get_header("Content-Length")?;
117 let clength = clength.parse().context("parse Content-Length")?;
120 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
123 let mut body = req.into_body();
124 let initial = match read_limited_bytes(
125 METADATA_MAX_LEN, default(), length_hint, &mut body
128 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
129 Err(ReadLimitedError::Hyper(e)) => throw!(e),
132 let boundary_finder = memmem::Finder::new(&boundary);
133 let mut boundary_iter = boundary_finder.find_iter(&initial);
135 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
136 else if let Some(start) = boundary_iter.next() { start + boundary.len() }
137 else { throw!(anyhow!("initial boundary not found")) };
139 let comp = multipart::process_boundary
140 (&mut warnings, &initial[start..], PartName::m)?
141 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
143 if comp.name != PartName::m { throw!(anyhow!(
144 r#"first multipart component must be name="m""#
147 let mut meta = MetadataFieldIterator::new(comp.payload);
149 let client: ClientName = meta.need_parse().context("client addr")?;
151 let mut hmac_got = [0; HMAC_L];
152 let (client_time, hmac_got_l) = (||{
153 let token: &str = meta.need_next().context(r#"find in "m""#)?;
154 let (time_t, hmac_b64) = token.split_once(' ')
155 .ok_or_else(|| anyhow!("split"))?;
156 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
158 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
160 &mut &mut hmac_got[..]
161 ).context("parse b64 token")?;
162 let l = l.try_into()?;
163 Ok::<_,AE>((time_t, l))
164 })().context("token")?;
165 let hmac_got = &hmac_got[0..hmac_got_l];
167 let client_name = client;
168 let client = global.all_clients.get(&client_name);
170 // We attempt to hide whether the client exists we don't try to
171 // hide the hash lookup computationgs, but we do try to hide the
172 // HMAC computation by always doing it. We hope that the compiler
173 // doesn't produce a specialised implementation for the dummy
175 let client_exists = subtle::Choice::from(client.is_some() as u8);
176 let secret = client.map(|c| c.ic.secret.0.as_bytes());
177 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
178 let client_time_s = format!("{:x}", client_time);
179 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
180 // We also definitely want a consttime memeq for the hmac value
181 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
182 //dbg!(DumpHex(&hmac_exp), client.is_some());
183 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
184 if ! bool::from(hmac_ok & client_exists) {
185 debug!("{} rejected client {}", &conn, &client_name);
186 let body = hyper::Body::from("Not authorised\r\n");
188 hyper::Response::builder()
189 .status(hyper::StatusCode::FORBIDDEN)
190 .header("Content-Type", r#"text/plain; charset="utf-8""#)
195 let client = client.unwrap();
196 let now = time_t_now();
197 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
198 if let Some(a_ahead) = a.checked_sub(b) {
199 if a_ahead > client.ic.max_clock_skew.as_secs() {
200 throw!(anyhow!("too much clock skew (client {} by {})",
201 c_ahead_behind, a_ahead));
206 chk_skew(client_time, now, "ahead")?;
207 chk_skew(now, client_time, "behind")?;
209 let initial_remaining = meta.remaining_bytes_len();
211 //eprintln!("boundary={:?} start={} name={:?} client={}",
212 // boundary, start, &comp.name, &client.ic);
214 let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
215 trace!("{} {} request, Content-Length={}",
216 &conn, &client_name, length_hint);
217 let wreq = WebRequest {
221 boundary_finder: boundary_finder.into_owned(),
223 warnings: mem::take(&mut warnings),
228 client.web.try_send(wreq)
229 .map_err(|_| anyhow!("client task shut down!"))?;
231 let reply: WebResponse = reply_recv.await?;
232 warnings = reply.warnings;
233 let data = reply.data?;
235 if warnings.warnings.is_empty() {
236 trace!("{} {} responding, {}",
237 &conn, &client_name, data.len());
239 debug!("{} {} responding, {} warnings={:?}",
240 &conn, &client_name, data.len(),
244 let data = hyper::Body::from(data);
246 hyper::Response::builder()
247 .header("Content-Type", r#"application/octet-stream"#)
250 }.await.unwrap_or_else(|e| {
251 debug!("{} error {}", &conn, &e);
252 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
253 for w in warnings.warnings {
254 write!(errmsg, "warning: {}\n", w).unwrap();
256 hyper::Response::builder()
257 .status(hyper::StatusCode::BAD_REQUEST)
258 .header("Content-Type", r#"text/plain; charset="utf-8""#)
263 #[allow(unused_variables)] // xxx
264 #[allow(unused_mut)] // xxx
265 async fn run_client(global: Arc<Global>,
266 ic: Arc<InstanceConfig>,
267 mut web: mpsc::Receiver<WebRequest>)
271 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
272 oi: OutstandingInner,
275 struct OutstandingInner {
276 target_requests_outstanding: u32,
278 let mut outstanding: VecDeque<Outstanding> = default();
279 let downbound: VecDeque<(/*xxx*/)> = default();
281 let try_send_response = |
282 reply_to: tokio::sync::oneshot::Sender<WebResponse>,
283 response: WebResponse
285 reply_to.send(response)
286 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
291 if ! downbound.is_empty() {
292 outstanding.pop_front()
293 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
294 |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
296 Some(outstanding.remove(i).unwrap())
301 let response = WebResponse {
302 data: Ok(vec![ /* xxx */ ]),
306 try_send_response(ret.reply_to, response);
313 initial, initial_remaining, length_hint, mut body,
315 reply_to, conn, mut warnings,
316 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
320 let initial_used = initial.len() - initial_remaining;
322 let whole_request = read_limited_bytes(
323 ic.max_batch_up.sat(),
327 ).await.context("read request body")?;
329 let (meta, mut comps) =
330 multipart::ComponentIterator::resume_mid_component(
331 &whole_request[initial_used..],
333 ).context("resume parsing body, after auth checks")?;
335 let mut meta = MetadataFieldIterator::new(&meta);
338 { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
339 let $server:ident, $client:ident $($code:tt)*
343 let $client $($code)*
345 if $client $badcmp $server {
346 throw!(anyhow!("mismatch: client={:?} {} server={:?}",
347 $client, stringify!($badcmp), $server));
351 })().context(stringify!($v))?;
357 target_requests_outstanding, ( != ), client,
358 let server, client: u32 = meta.need_parse()?;
362 http_timeout, ( > ), client,
363 let server, client = Duration::from_secs(meta.need_parse()?);
368 let server, client: u32 = meta.parse()?.unwrap_or(server);
372 max_batch_down, (), min(client, server),
373 let server, client: u32 = meta.parse()?.unwrap_or(server);
377 max_batch_up, ( > ), client,
378 let server, client = meta.parse()?.unwrap_or(server);
381 while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
382 if comp.name != PartName::d {
383 warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
385 checkn(Mime2Slip, mtu, comp.payload, |header| {
386 let saddr = ip_packet_addr::<false>(header)?;
387 if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
388 let daddr = ip_packet_addr::<true>(header)?;
390 }, |(daddr,packet)| route_packet(
391 &global, &conn, &ic.link.client, daddr,packet
393 |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
397 let oi = OutstandingInner {
398 target_requests_outstanding,
402 Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
404 try_send_response(reply_to, WebResponse {
413 //Err(anyhow!("xxx"))
418 let opts = Opts::from_args();
424 let (global, ipif) = config::startup(
425 "hippotatd", LinkEnd::Server,
426 &opts.config, &opts.log, |ics|
428 let global_config = config::InstanceConfigGlobal::from(&ics);
430 let ipif = Ipif::start(&global_config.ipif, None)?;
432 let ics = ics.into_iter().map(Arc::new).collect_vec();
433 let (client_handles_send, client_handles_recv) = ics.iter()
434 .map(|_ic| mpsc::channel(
435 5 // xxx should me max_requests_outstanding but that's
436 // marked client-only so needs rework
437 )).unzip::<_,_,Vec<_>,Vec<_>>();
439 let all_clients = izip!(
442 ).map(|(ic, web_send)| {
450 let global = Arc::new(Global {
451 config: global_config,
455 for (ic, web_recv) in izip!(
459 let global_ = global.clone();
460 let ic_ = ic.clone();
461 tasks.push((tokio::spawn(async move {
462 run_client(global_, ic_, web_recv).await.void_unwrap_err()
463 }), format!("client {}", &ic)));
466 for addr in &global.config.addrs {
467 let global_ = global.clone();
468 let make_service = hyper::service::make_service_fn(
469 move |conn: &hyper::server::conn::AddrStream| {
470 let global_ = global_.clone();
471 let conn = Arc::new(format!("[{}]", conn.remote_addr()));
472 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
473 handle(conn.clone(), global_.clone(), req)
478 let addr = SocketAddr::new(*addr, global.config.port);
479 let server = hyper::Server::try_bind(&addr)
481 .http1_preserve_header_case(true)
482 .serve(make_service);
483 info!("listening on {}", &addr);
484 let task = tokio::task::spawn(async move {
486 Ok(()) => anyhow!("shut down?!"),
490 tasks.push((task, format!("http server {}", addr)));
496 let died = future::select_all(
497 tasks.iter_mut().map(|e| &mut e.0)
499 error!("xxx {:?}", &died);
501 ipif.quitting(None).await;