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 trace = |how| trace!("{} {} route {} daddr={:?} len={}",
68 conn, link, how, daddr, packet.len());
70 if daddr == c.vaddr || ! c.vnetwork.iter().any(|n| n.contains(&daddr)) {
71 trace("ipif inbound xxx discarding");
72 } else if daddr == c.vrelay {
73 trace("discard (relay)");
74 } else if let Some(_client) = global.all_clients.get(&ClientName(daddr)) {
75 trace("ipif route xxx discarding");
77 trace("discard (no client)");
84 req: hyper::Request<hyper::Body>
85 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
86 if req.method() == Method::GET {
87 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
88 resp.headers_mut().insert(
90 "text/plain; charset=US-ASCII".try_into().unwrap()
95 let mut warnings: Warnings = default();
99 let get_header = |hn: &str| {
100 let mut values = req.headers().get_all(hn).iter();
101 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
102 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
103 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
107 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
108 let boundary = match (||{
109 let t = get_header("Content-Type")?;
110 let t: mime::Mime = t.parse().context("parse Content-Type")?;
111 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
112 let b = mime::BOUNDARY;
113 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
114 if t.subtype() != "form-data" {
115 warnings.add(&"Content-Type not /form-data")?;
117 let b = mkboundary(b.as_str());
122 warnings.add(&e.wrap_err("guessing boundary"))?;
127 let length_hint: usize = (||{
128 let clength = get_header("Content-Length")?;
129 let clength = clength.parse().context("parse Content-Length")?;
132 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
135 let mut body = req.into_body();
136 let initial = match read_limited_bytes(
137 METADATA_MAX_LEN, default(), length_hint, &mut body
140 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
141 Err(ReadLimitedError::Hyper(e)) => throw!(e),
144 let boundary_finder = memmem::Finder::new(&boundary);
145 let mut boundary_iter = boundary_finder.find_iter(&initial);
147 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
148 else if let Some(start) = boundary_iter.next() { start + boundary.len() }
149 else { throw!(anyhow!("initial boundary not found")) };
151 let comp = multipart::process_boundary
152 (&mut warnings, &initial[start..], PartName::m)?
153 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
155 if comp.name != PartName::m { throw!(anyhow!(
156 r#"first multipart component must be name="m""#
159 let mut meta = MetadataFieldIterator::new(comp.payload);
161 let client: ClientName = meta.need_parse().context("client addr")?;
163 let mut hmac_got = [0; HMAC_L];
164 let (client_time, hmac_got_l) = (||{
165 let token: &str = meta.need_next().context(r#"find in "m""#)?;
166 let (time_t, hmac_b64) = token.split_once(' ')
167 .ok_or_else(|| anyhow!("split"))?;
168 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
170 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
172 &mut &mut hmac_got[..]
173 ).context("parse b64 token")?;
174 let l = l.try_into()?;
175 Ok::<_,AE>((time_t, l))
176 })().context("token")?;
177 let hmac_got = &hmac_got[0..hmac_got_l];
179 let client_name = client;
180 let client = global.all_clients.get(&client_name);
182 // We attempt to hide whether the client exists we don't try to
183 // hide the hash lookup computationgs, but we do try to hide the
184 // HMAC computation by always doing it. We hope that the compiler
185 // doesn't produce a specialised implementation for the dummy
187 let client_exists = subtle::Choice::from(client.is_some() as u8);
188 let secret = client.map(|c| c.ic.secret.0.as_bytes());
189 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
190 let client_time_s = format!("{:x}", client_time);
191 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
192 // We also definitely want a consttime memeq for the hmac value
193 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
194 //dbg!(DumpHex(&hmac_exp), client.is_some());
195 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
196 if ! bool::from(hmac_ok & client_exists) {
197 debug!("{} rejected client {}", &conn, &client_name);
198 let body = hyper::Body::from("Not authorised\r\n");
200 hyper::Response::builder()
201 .status(hyper::StatusCode::FORBIDDEN)
202 .header("Content-Type", r#"text/plain; charset="utf-8""#)
207 let client = client.unwrap();
208 let now = time_t_now();
209 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
210 if let Some(a_ahead) = a.checked_sub(b) {
211 if a_ahead > client.ic.max_clock_skew.as_secs() {
212 throw!(anyhow!("too much clock skew (client {} by {})",
213 c_ahead_behind, a_ahead));
218 chk_skew(client_time, now, "ahead")?;
219 chk_skew(now, client_time, "behind")?;
221 let initial_remaining = meta.remaining_bytes_len();
223 //eprintln!("boundary={:?} start={} name={:?} client={}",
224 // boundary, start, &comp.name, &client.ic);
226 let (reply_to, reply_recv) = oneshot::channel();
227 trace!("{} {} request, Content-Length={}",
228 &conn, &client_name, length_hint);
229 let wreq = WebRequest {
233 boundary_finder: boundary_finder.into_owned(),
235 warnings: mem::take(&mut warnings),
240 client.web.try_send(wreq)
241 .map_err(|_| anyhow!("client task shut down!"))?;
243 let reply: WebResponse = reply_recv.await?;
244 warnings = reply.warnings;
245 let data = reply.data?;
247 if warnings.warnings.is_empty() {
248 trace!("{} {} responding, {}",
249 &conn, &client_name, data.len());
251 debug!("{} {} responding, {} warnings={:?}",
252 &conn, &client_name, data.len(),
256 let data = hyper::Body::from(data);
258 hyper::Response::builder()
259 .header("Content-Type", r#"application/octet-stream"#)
262 }.await.unwrap_or_else(|e| {
263 debug!("{} error {}", &conn, &e);
264 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
265 for w in warnings.warnings {
266 write!(errmsg, "warning: {}\n", w).unwrap();
268 hyper::Response::builder()
269 .status(hyper::StatusCode::BAD_REQUEST)
270 .header("Content-Type", r#"text/plain; charset="utf-8""#)
275 #[allow(unused_variables)] // xxx
276 #[allow(unused_mut)] // xxx
277 async fn run_client(global: Arc<Global>,
278 ic: Arc<InstanceConfig>,
279 mut web: mpsc::Receiver<WebRequest>,
280 mut routed: mpsc::Receiver<RoutedPacket>)
284 reply_to: oneshot::Sender<WebResponse>,
285 oi: OutstandingInner,
288 struct OutstandingInner {
289 target_requests_outstanding: u32,
291 let mut outstanding: VecDeque<Outstanding> = default();
292 let downbound: VecDeque<(/*xxx*/)> = default();
294 let try_send_response = |
295 reply_to: oneshot::Sender<WebResponse>,
296 response: WebResponse
298 reply_to.send(response)
299 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
304 if ! downbound.is_empty() {
305 outstanding.pop_front()
306 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
307 |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
309 Some(outstanding.remove(i).unwrap())
314 let response = WebResponse {
315 data: Ok(vec![ /* xxx */ ]),
319 try_send_response(ret.reply_to, response);
326 initial, initial_remaining, length_hint, mut body,
328 reply_to, conn, mut warnings,
329 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
333 let initial_used = initial.len() - initial_remaining;
335 let whole_request = read_limited_bytes(
336 ic.max_batch_up.sat(),
340 ).await.context("read request body")?;
342 let (meta, mut comps) =
343 multipart::ComponentIterator::resume_mid_component(
344 &whole_request[initial_used..],
346 ).context("resume parsing body, after auth checks")?;
348 let mut meta = MetadataFieldIterator::new(&meta);
351 { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
352 let $server:ident, $client:ident $($code:tt)*
356 let $client $($code)*
358 if $client $badcmp $server {
359 throw!(anyhow!("mismatch: client={:?} {} server={:?}",
360 $client, stringify!($badcmp), $server));
364 })().context(stringify!($v))?;
370 target_requests_outstanding, ( != ), client,
371 let server, client: u32 = meta.need_parse()?;
375 http_timeout, ( > ), client,
376 let server, client = Duration::from_secs(meta.need_parse()?);
381 let server, client: u32 = meta.parse()?.unwrap_or(server);
385 max_batch_down, (), min(client, server),
386 let server, client: u32 = meta.parse()?.unwrap_or(server);
390 max_batch_up, ( > ), client,
391 let server, client = meta.parse()?.unwrap_or(server);
394 while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
395 if comp.name != PartName::d {
396 warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
398 checkn(Mime2Slip, mtu, comp.payload, |header| {
399 let saddr = ip_packet_addr::<false>(header)?;
400 if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
401 let daddr = ip_packet_addr::<true>(header)?;
403 }, |(daddr,packet)| route_packet(
404 &global, &conn, &ic.link.client, daddr,packet
406 |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
410 let oi = OutstandingInner {
411 target_requests_outstanding,
415 Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
417 try_send_response(reply_to, WebResponse {
426 //Err(anyhow!("xxx"))
431 let opts = Opts::from_args();
437 let (global, ipif) = config::startup(
438 "hippotatd", LinkEnd::Server,
439 &opts.config, &opts.log, |ics|
441 let global_config = config::InstanceConfigGlobal::from(&ics);
443 let ipif = Ipif::start(&global_config.ipif, None)?;
445 let ics = ics.into_iter().map(Arc::new).collect_vec();
446 let (client_handles_send, client_handles_recv) = ics.iter()
448 let (web_send, web_recv) = mpsc::channel(
449 5 // xxx should me max_requests_outstanding but that's
450 // marked client-only so needs rework
452 let (route_send, route_recv) = mpsc::channel(
455 ((web_send, route_send), (web_recv, route_recv))
456 }).unzip::<_,_,Vec<_>,Vec<_>>();
458 let all_clients = izip!(
461 ).map(|(ic, (web_send, route_send))| {
470 let global = Arc::new(Global {
471 config: global_config,
475 for (ic, (web_recv, route_recv)) in izip!(
479 let global_ = global.clone();
480 let ic_ = ic.clone();
481 tasks.push((tokio::spawn(async move {
482 run_client(global_, ic_, web_recv, route_recv)
483 .await.void_unwrap_err()
484 }), format!("client {}", &ic)));
487 for addr in &global.config.addrs {
488 let global_ = global.clone();
489 let make_service = hyper::service::make_service_fn(
490 move |conn: &hyper::server::conn::AddrStream| {
491 let global_ = global_.clone();
492 let conn = Arc::new(format!("[{}]", conn.remote_addr()));
493 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
494 handle(conn.clone(), global_.clone(), req)
499 let addr = SocketAddr::new(*addr, global.config.port);
500 let server = hyper::Server::try_bind(&addr)
502 .http1_preserve_header_case(true)
503 .serve(make_service);
504 info!("listening on {}", &addr);
505 let task = tokio::task::spawn(async move {
507 Ok(()) => anyhow!("shut down?!"),
511 tasks.push((task, format!("http server {}", addr)));
517 let died = future::select_all(
518 tasks.iter_mut().map(|e| &mut e.0)
520 error!("xxx {:?}", &died);
522 ipif.quitting(None).await;