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: 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: 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)
64 let c = &global.config;
65 let trace = |how| trace!("{} {} route {} daddr={:?} len={}",
66 conn, link, how, daddr, packet.len());
68 if daddr == c.vaddr || ! c.vnetwork.iter().any(|n| n.contains(&daddr)) {
69 trace("ipif inbound xxx discarding");
70 } else if daddr == c.vrelay {
71 trace("discard (relay)");
72 } else if let Some(_client) = global.all_clients.get(&ClientName(daddr)) {
73 trace("ipif route xxx discarding");
75 trace("discard (no client)");
82 req: hyper::Request<hyper::Body>
83 ) -> Result<hyper::Response<hyper::Body>, hyper::http::Error> {
84 if req.method() == Method::GET {
85 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
86 resp.headers_mut().insert(
88 "text/plain; charset=US-ASCII".try_into().unwrap()
93 let mut warnings: Warnings = default();
97 let get_header = |hn: &str| {
98 let mut values = req.headers().get_all(hn).iter();
99 let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
100 if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
101 let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
105 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
106 let boundary = match (||{
107 let t = get_header("Content-Type")?;
108 let t: mime::Mime = t.parse().context("parse Content-Type")?;
109 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
110 let b = mime::BOUNDARY;
111 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
112 if t.subtype() != "form-data" {
113 warnings.add(&"Content-Type not /form-data")?;
115 let b = mkboundary(b.as_str());
120 warnings.add(&e.wrap_err("guessing boundary"))?;
125 let length_hint: usize = (||{
126 let clength = get_header("Content-Length")?;
127 let clength = clength.parse().context("parse Content-Length")?;
130 |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
133 let mut body = req.into_body();
134 let initial = match read_limited_bytes(
135 METADATA_MAX_LEN, default(), length_hint, &mut body
138 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
139 Err(ReadLimitedError::Hyper(e)) => throw!(e),
142 let boundary_finder = memmem::Finder::new(&boundary);
143 let mut boundary_iter = boundary_finder.find_iter(&initial);
145 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
146 else if let Some(start) = boundary_iter.next() { start + boundary.len() }
147 else { throw!(anyhow!("initial boundary not found")) };
149 let comp = multipart::process_boundary
150 (&mut warnings, &initial[start..], PartName::m)?
151 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
153 if comp.name != PartName::m { throw!(anyhow!(
154 r#"first multipart component must be name="m""#
157 let mut meta = MetadataFieldIterator::new(comp.payload);
159 let client: ClientName = meta.need_parse().context("client addr")?;
161 let mut hmac_got = [0; HMAC_L];
162 let (client_time, hmac_got_l) = (||{
163 let token: &str = meta.need_next().context(r#"find in "m""#)?;
164 let (time_t, hmac_b64) = token.split_once(' ')
165 .ok_or_else(|| anyhow!("split"))?;
166 let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
168 &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
170 &mut &mut hmac_got[..]
171 ).context("parse b64 token")?;
172 let l = l.try_into()?;
173 Ok::<_,AE>((time_t, l))
174 })().context("token")?;
175 let hmac_got = &hmac_got[0..hmac_got_l];
177 let client_name = client;
178 let client = global.all_clients.get(&client_name);
180 // We attempt to hide whether the client exists we don't try to
181 // hide the hash lookup computationgs, but we do try to hide the
182 // HMAC computation by always doing it. We hope that the compiler
183 // doesn't produce a specialised implementation for the dummy
185 let client_exists = subtle::Choice::from(client.is_some() as u8);
186 let secret = client.map(|c| c.ic.secret.0.as_bytes());
187 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
188 let client_time_s = format!("{:x}", client_time);
189 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
190 // We also definitely want a consttime memeq for the hmac value
191 let hmac_ok = hmac_got.ct_eq(&hmac_exp);
192 //dbg!(DumpHex(&hmac_exp), client.is_some());
193 //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
194 if ! bool::from(hmac_ok & client_exists) {
195 debug!("{} rejected client {}", &conn, &client_name);
196 let body = hyper::Body::from("Not authorised\r\n");
198 hyper::Response::builder()
199 .status(hyper::StatusCode::FORBIDDEN)
200 .header("Content-Type", r#"text/plain; charset="utf-8""#)
205 let client = client.unwrap();
206 let now = time_t_now();
207 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
208 if let Some(a_ahead) = a.checked_sub(b) {
209 if a_ahead > client.ic.max_clock_skew.as_secs() {
210 throw!(anyhow!("too much clock skew (client {} by {})",
211 c_ahead_behind, a_ahead));
216 chk_skew(client_time, now, "ahead")?;
217 chk_skew(now, client_time, "behind")?;
219 let initial_remaining = meta.remaining_bytes_len();
221 //eprintln!("boundary={:?} start={} name={:?} client={}",
222 // boundary, start, &comp.name, &client.ic);
224 let (reply_to, reply_recv) = oneshot::channel();
225 trace!("{} {} request, Content-Length={}",
226 &conn, &client_name, length_hint);
227 let wreq = WebRequest {
231 boundary_finder: boundary_finder.into_owned(),
233 warnings: mem::take(&mut warnings),
238 client.web.try_send(wreq)
239 .map_err(|_| anyhow!("client task shut down!"))?;
241 let reply: WebResponse = reply_recv.await?;
242 warnings = reply.warnings;
243 let data = reply.data?;
245 if warnings.warnings.is_empty() {
246 trace!("{} {} responding, {}",
247 &conn, &client_name, data.len());
249 debug!("{} {} responding, {} warnings={:?}",
250 &conn, &client_name, data.len(),
254 let data = hyper::Body::from(data);
256 hyper::Response::builder()
257 .header("Content-Type", r#"application/octet-stream"#)
260 }.await.unwrap_or_else(|e| {
261 debug!("{} error {}", &conn, &e);
262 let mut errmsg = format!("ERROR\n\n{:?}\n\n", &e);
263 for w in warnings.warnings {
264 write!(errmsg, "warning: {}\n", w).unwrap();
266 hyper::Response::builder()
267 .status(hyper::StatusCode::BAD_REQUEST)
268 .header("Content-Type", r#"text/plain; charset="utf-8""#)
273 #[allow(unused_variables)] // xxx
274 #[allow(unused_mut)] // xxx
275 async fn run_client(global: Arc<Global>,
276 ic: Arc<InstanceConfig>,
277 mut web: mpsc::Receiver<WebRequest>)
281 reply_to: oneshot::Sender<WebResponse>,
282 oi: OutstandingInner,
285 struct OutstandingInner {
286 target_requests_outstanding: u32,
288 let mut outstanding: VecDeque<Outstanding> = default();
289 let downbound: VecDeque<(/*xxx*/)> = default();
291 let try_send_response = |
292 reply_to: oneshot::Sender<WebResponse>,
293 response: WebResponse
295 reply_to.send(response)
296 .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
301 if ! downbound.is_empty() {
302 outstanding.pop_front()
303 } else if let Some((i,_)) = outstanding.iter().enumerate().find({
304 |(_,o)| outstanding.len() > o.oi.target_requests_outstanding.sat()
306 Some(outstanding.remove(i).unwrap())
311 let response = WebResponse {
312 data: Ok(vec![ /* xxx */ ]),
316 try_send_response(ret.reply_to, response);
323 initial, initial_remaining, length_hint, mut body,
325 reply_to, conn, mut warnings,
326 } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
330 let initial_used = initial.len() - initial_remaining;
332 let whole_request = read_limited_bytes(
333 ic.max_batch_up.sat(),
337 ).await.context("read request body")?;
339 let (meta, mut comps) =
340 multipart::ComponentIterator::resume_mid_component(
341 &whole_request[initial_used..],
343 ).context("resume parsing body, after auth checks")?;
345 let mut meta = MetadataFieldIterator::new(&meta);
348 { $v:ident, ( $( $badcmp:tt )? ), $ret:expr,
349 let $server:ident, $client:ident $($code:tt)*
353 let $client $($code)*
355 if $client $badcmp $server {
356 throw!(anyhow!("mismatch: client={:?} {} server={:?}",
357 $client, stringify!($badcmp), $server));
361 })().context(stringify!($v))?;
367 target_requests_outstanding, ( != ), client,
368 let server, client: u32 = meta.need_parse()?;
372 http_timeout, ( > ), client,
373 let server, client = Duration::from_secs(meta.need_parse()?);
378 let server, client: u32 = meta.parse()?.unwrap_or(server);
382 max_batch_down, (), min(client, server),
383 let server, client: u32 = meta.parse()?.unwrap_or(server);
387 max_batch_up, ( > ), client,
388 let server, client = meta.parse()?.unwrap_or(server);
391 while let Some(comp) = comps.next(&mut warnings, PartName::d)? {
392 if comp.name != PartName::d {
393 warnings.add(&format_args!("unexpected part {:?}", comp.name))?;
395 checkn(Mime2Slip, mtu, comp.payload, |header| {
396 let saddr = ip_packet_addr::<false>(header)?;
397 if saddr != ic.link.client.0 { throw!(PE::Src(saddr)) }
398 let daddr = ip_packet_addr::<true>(header)?;
400 }, |(daddr,packet)| route_packet(
401 &global, &conn, &ic.link.client, daddr,packet
403 |e| Ok::<_,SlipFramesError<_>>({ warnings.add(&e)?; })
407 let oi = OutstandingInner {
408 target_requests_outstanding,
412 Ok(oi) => outstanding.push_back(Outstanding { reply_to, oi }),
414 try_send_response(reply_to, WebResponse {
423 //Err(anyhow!("xxx"))
428 let opts = Opts::from_args();
434 let (global, ipif) = config::startup(
435 "hippotatd", LinkEnd::Server,
436 &opts.config, &opts.log, |ics|
438 let global_config = config::InstanceConfigGlobal::from(&ics);
440 let ipif = Ipif::start(&global_config.ipif, None)?;
442 let ics = ics.into_iter().map(Arc::new).collect_vec();
443 let (client_handles_send, client_handles_recv) = ics.iter()
444 .map(|_ic| mpsc::channel(
445 5 // xxx should me max_requests_outstanding but that's
446 // marked client-only so needs rework
447 )).unzip::<_,_,Vec<_>,Vec<_>>();
449 let all_clients = izip!(
452 ).map(|(ic, web_send)| {
460 let global = Arc::new(Global {
461 config: global_config,
465 for (ic, web_recv) in izip!(
469 let global_ = global.clone();
470 let ic_ = ic.clone();
471 tasks.push((tokio::spawn(async move {
472 run_client(global_, ic_, web_recv).await.void_unwrap_err()
473 }), format!("client {}", &ic)));
476 for addr in &global.config.addrs {
477 let global_ = global.clone();
478 let make_service = hyper::service::make_service_fn(
479 move |conn: &hyper::server::conn::AddrStream| {
480 let global_ = global_.clone();
481 let conn = Arc::new(format!("[{}]", conn.remote_addr()));
482 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
483 handle(conn.clone(), global_.clone(), req)
488 let addr = SocketAddr::new(*addr, global.config.port);
489 let server = hyper::Server::try_bind(&addr)
491 .http1_preserve_header_case(true)
492 .serve(make_service);
493 info!("listening on {}", &addr);
494 let task = tokio::task::spawn(async move {
496 Ok(()) => anyhow!("shut down?!"),
500 tasks.push((task, format!("http server {}", addr)));
506 let died = future::select_all(
507 tasks.iter_mut().map(|e| &mut e.0)
509 error!("xxx {:?}", &died);
511 ipif.quitting(None).await;