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;
17 const INTERNAL_QUEUE: usize = 15; // xxx: config
21 config: config::InstanceConfigGlobal,
22 all_clients: HashMap<ClientName, Client>,
27 ic: Arc<InstanceConfig>,
28 web: mpsc::Sender<WebRequest>,
29 route: mpsc::Sender<RoutedPacket>,
32 pub type RoutedPacket = Box<[u8]>; // not MIME data
34 /// Sent from hyper worker pool task to client task
35 #[allow(dead_code)] // xxx
38 // initial part of body
39 // used up to and including first 2 lines of metadata
40 // end delimiter for the metadata not yet located, but in here somewhere
42 initial_remaining: usize,
44 body: hyper::body::Body,
45 boundary_finder: multipart::BoundaryFinder,
46 reply_to: oneshot::Sender<WebResponse>,
51 /// Reply from client task to hyper worker pool task
52 #[allow(dead_code)] // xxx
56 data: Result<WebResponseData, AE>,
59 type WebResponseData = Vec<u8>;
61 #[throws(PacketError)]
62 pub async fn route_packet(global: &Global,
63 conn: &str, link: &(dyn Display + Sync),
64 packet: RoutedPacket, daddr: IpAddr)
66 let c = &global.config;
67 let len = packet.len();
68 let trace = |how: &str, why: &str| {
69 trace!("{} {} {} {} {:?} len={}",
70 conn, link, how, why, daddr, len);
74 if daddr == c.vaddr || ! c.vnetwork.iter().any(|n| n.contains(&daddr)) {
75 (None, "ipif-inbound-xxx")
76 } else if daddr == c.vrelay {
78 } else if let Some(client) = global.all_clients.get(&ClientName(daddr)) {
79 (Some(&client.route), "client")
84 let dest = if let Some(d) = dest { d } else {
85 trace("discard", why); return;
88 match dest.send(packet).await {
89 Ok(()) => trace("forward", why),
90 Err(_) => trace("task-crashed!", why),
97 req: hyper::Request<hyper::Body>
98 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
99 if req.method() == Method::GET {
100 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
101 resp.headers_mut().insert(
103 "text/plain; charset=US-ASCII".try_into().unwrap()
108 let mut warnings: Warnings = default();
112 let get_header = |hn: &str| {
113 let mut values = req.headers().get_all(hn).iter();
114 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
115 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
116 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
120 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
121 let boundary = match (||{
122 let t = get_header("Content-Type")?;
123 let t: mime::Mime = t.parse().context("parse Content-Type")?;
124 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
125 let b = mime::BOUNDARY;
126 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
127 if t.subtype() != "form-data" {
128 warnings.add(&"Content-Type not /form-data")?;
130 let b = mkboundary(b.as_str());
135 warnings.add(&e.wrap_err("guessing boundary"))?;
140 let length_hint: usize = (||{
141 let clength = get_header("Content-Length")?;
142 let clength = clength.parse().context("parse Content-Length")?;
145 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
148 let mut body = req.into_body();
149 let initial = match read_limited_bytes(
150 METADATA_MAX_LEN, default(), length_hint, &mut body
153 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
154 Err(ReadLimitedError::Hyper(e)) => throw!(e),
157 let boundary_finder = memmem::Finder::new(&boundary);
158 let mut boundary_iter = boundary_finder.find_iter(&initial);
160 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
161 else if let Some(start) = boundary_iter.next() { start + boundary.len() }
162 else { throw!(anyhow!("initial boundary not found")) };
164 let comp = multipart::process_boundary
165 (&mut warnings, &initial[start..], PartName::m)?
166 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
168 if comp.name != PartName::m { throw!(anyhow!(
169 r#"first multipart component must be name="m""#
172 let mut meta = MetadataFieldIterator::new(comp.payload);
174 let client: ClientName = meta.need_parse().context("client addr")?;
176 let mut hmac_got = [0; HMAC_L];
177 let (client_time, hmac_got_l) = (||{
178 let token: &str = meta.need_next().context(r#"find in "m""#)?;
179 let (time_t, hmac_b64) = token.split_once(' ')
180 .ok_or_else(|| anyhow!("split"))?;
181 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
183 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
185 &mut &mut hmac_got[..]
186 ).context("parse b64 token")?;
187 let l = l.try_into()?;
188 Ok::<_,AE>((time_t, l))
189 })().context("token")?;
190 let hmac_got = &hmac_got[0..hmac_got_l];
192 let client_name = client;
193 let client = global.all_clients.get(&client_name);
195 // We attempt to hide whether the client exists we don't try to
196 // hide the hash lookup computationgs, but we do try to hide the
197 // HMAC computation by always doing it. We hope that the compiler
198 // doesn't produce a specialised implementation for the dummy
200 let client_exists = subtle::Choice::from(client.is_some() as u8);
201 let secret = client.map(|c| c.ic.secret.0.as_bytes());
202 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
203 let client_time_s = format!("{:x}", client_time);
204 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
205 // We also definitely want a consttime memeq for the hmac value
206 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
207 //dbg!(DumpHex(&hmac_exp), client.is_some());
208 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
209 if ! bool::from(hmac_ok & client_exists) {
210 debug!("{} rejected client {}", &conn, &client_name);
211 let body = hyper::Body::from("Not authorised\r\n");
213 hyper::Response::builder()
214 .status(hyper::StatusCode::FORBIDDEN)
215 .header("Content-Type", r#"text/plain; charset="utf-8""#)
220 let client = client.unwrap();
221 let now = time_t_now();
222 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
223 if let Some(a_ahead) = a.checked_sub(b) {
224 if a_ahead > client.ic.max_clock_skew.as_secs() {
225 throw!(anyhow!("too much clock skew (client {} by {})",
226 c_ahead_behind, a_ahead));
231 chk_skew(client_time, now, "ahead")?;
232 chk_skew(now, client_time, "behind")?;
234 let initial_remaining = meta.remaining_bytes_len();
236 //eprintln!("boundary={:?} start={} name={:?} client={}",
237 // boundary, start, &comp.name, &client.ic);
239 let (reply_to, reply_recv) = oneshot::channel();
240 trace!("{} {} request, Content-Length={}",
241 &conn, &client_name, length_hint);
242 let wreq = WebRequest {
246 boundary_finder: boundary_finder.into_owned(),
248 warnings: mem::take(&mut warnings),
253 client.web.try_send(wreq)
254 .map_err(|_| anyhow!("client task shut down!"))?;
256 let reply: WebResponse = reply_recv.await?;
257 warnings = reply.warnings;
258 let data = reply.data?;
260 if warnings.warnings.is_empty() {
261 trace!("{} {} responding, {}",
262 &conn, &client_name, data.len());
264 debug!("{} {} responding, {} warnings={:?}",
265 &conn, &client_name, data.len(),
269 let data = hyper::Body::from(data);
271 hyper::Response::builder()
272 .header("Content-Type", r#"application/octet-stream"#)
275 }.await.unwrap_or_else(|e| {
276 debug!("{} error {}", &conn, &e);
277 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
278 for w in warnings.warnings {
279 write!(errmsg, "warning: {}\n", w).unwrap();
281 hyper::Response::builder()
282 .status(hyper::StatusCode::BAD_REQUEST)
283 .header("Content-Type", r#"text/plain; charset="utf-8""#)
288 #[allow(unused_variables)] // xxx
289 #[allow(unused_mut)] // xxx
290 async fn run_client(global: Arc<Global>,
291 ic: Arc<InstanceConfig>,
292 mut web: mpsc::Receiver<WebRequest>,
293 mut routed: mpsc::Receiver<RoutedPacket>)
297 reply_to: oneshot::Sender<WebResponse>,
298 oi: OutstandingInner,
301 struct OutstandingInner {
302 target_requests_outstanding: u32,
304 let mut outstanding: VecDeque<Outstanding> = default();
305 let downbound: VecDeque<(/*xxx*/)> = default();
307 let try_send_response = |
308 reply_to: oneshot::Sender<WebResponse>,
309 response: WebResponse
311 reply_to.send(response)
312 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
317 if ! downbound.is_empty() {
318 outstanding.pop_front()
319 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
320 |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
322 Some(outstanding.remove(i).unwrap())
327 let response = WebResponse {
328 data: Ok(vec![ /* xxx */ ]),
332 try_send_response(ret.reply_to, response);
339 initial, initial_remaining, length_hint, mut body,
341 reply_to, conn, mut warnings,
342 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
346 let initial_used = initial.len() - initial_remaining;
348 let whole_request = read_limited_bytes(
349 ic.max_batch_up.sat(),
353 ).await.context("read request body")?;
355 let (meta, mut comps) =
356 multipart::ComponentIterator::resume_mid_component(
357 &whole_request[initial_used..],
359 ).context("resume parsing body, after auth checks")?;
361 let mut meta = MetadataFieldIterator::new(&meta);
364 { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
365 let $server:ident, $client:ident $($code:tt)*
369 let $client $($code)*
371 if $client $badcmp $server {
372 throw!(anyhow!("mismatch: client={:?} {} server={:?}",
373 $client, stringify!($badcmp), $server));
377 })().context(stringify!($v))?;
383 target_requests_outstanding, ( != ), client,
384 let server, client: u32 = meta.need_parse()?;
388 http_timeout, ( > ), client,
389 let server, client = Duration::from_secs(meta.need_parse()?);
394 let server, client: u32 = meta.parse()?.unwrap_or(server);
398 max_batch_down, (), min(client, server),
399 let server, client: u32 = meta.parse()?.unwrap_or(server);
403 max_batch_up, ( > ), client,
404 let server, client = meta.parse()?.unwrap_or(server);
407 while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
408 if comp.name != PartName::d {
409 warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
411 checkn(Mime2Slip, mtu, comp.payload, |header| {
412 let saddr = ip_packet_addr::<false>(header)?;
413 if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
414 let daddr = ip_packet_addr::<true>(header)?;
416 }, |(daddr,packet)| route_packet(
417 &global, &conn, &ic.link.client, daddr,packet
419 |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
423 let oi = OutstandingInner {
424 target_requests_outstanding,
428 Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
430 try_send_response(reply_to, WebResponse {
439 //Err(anyhow!("xxx"))
444 let opts = Opts::from_args();
450 let (global, ipif) = config::startup(
451 "hippotatd", LinkEnd::Server,
452 &opts.config, &opts.log, |ics|
454 let global_config = config::InstanceConfigGlobal::from(&ics);
456 let ipif = Ipif::start(&global_config.ipif, None)?;
458 let ics = ics.into_iter().map(Arc::new).collect_vec();
459 let (client_handles_send, client_handles_recv) = ics.iter()
461 let (web_send, web_recv) = mpsc::channel(
462 5 // xxx should me max_requests_outstanding but that's
463 // marked client-only so needs rework
465 let (route_send, route_recv) = mpsc::channel(
468 ((web_send, route_send), (web_recv, route_recv))
469 }).unzip::<_,_,Vec<_>,Vec<_>>();
471 let all_clients = izip!(
474 ).map(|(ic, (web_send, route_send))| {
483 let global = Arc::new(Global {
484 config: global_config,
488 for (ic, (web_recv, route_recv)) in izip!(
492 let global_ = global.clone();
493 let ic_ = ic.clone();
494 tasks.push((tokio::spawn(async move {
495 run_client(global_, ic_, web_recv, route_recv)
496 .await.void_unwrap_err()
497 }), format!("client {}", &ic)));
500 for addr in &global.config.addrs {
501 let global_ = global.clone();
502 let make_service = hyper::service::make_service_fn(
503 move |conn: &hyper::server::conn::AddrStream| {
504 let global_ = global_.clone();
505 let conn = Arc::new(format!("[{}]", conn.remote_addr()));
506 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
507 handle(conn.clone(), global_.clone(), req)
512 let addr = SocketAddr::new(*addr, global.config.port);
513 let server = hyper::Server::try_bind(&addr)
515 .http1_preserve_header_case(true)
516 .serve(make_service);
517 info!("listening on {}", &addr);
518 let task = tokio::task::spawn(async move {
520 Ok(()) => anyhow!("shut down?!"),
524 tasks.push((task, format!("http server {}", addr)));
530 let died = future::select_all(
531 tasks.iter_mut().map(|e| &mut e.0)
533 error!("xxx {:?}", &died);
535 ipif.quitting(None).await;