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;
18 type AllClients = HashMap<ClientName, ClientHandles>;
20 struct ClientHandles {
21 ic: Arc<InstanceConfig>,
22 web: tokio::sync::mpsc::Sender<WebRequest>,
26 reply: tokio::sync::oneshot::Sender<()>,
30 all_clients: Arc<AllClients>,
31 req: hyper::Request<hyper::Body>
32 ) -> Result<hyper::Response<hyper::Body>, Void> {
33 if req.method() == Method::GET {
34 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
35 resp.headers_mut().insert(
37 "text/plain; charset=US-ASCII".try_into().unwrap()
42 let mut warnings: Warnings = default();
46 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
47 let boundary = match (||{
48 let mut ctypes = req.headers().get_all("Content-Type").iter();
49 let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
50 if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
51 let t = t.to_str().context("interpret Content-Type as utf-8")?;
52 let t: mime::Mime = t.parse().context("parse Content-Type")?;
53 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
54 let b = mime::BOUNDARY;
55 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
56 if t.subtype() != "form-data" {
57 warnings.add(&"Content-Type not /form-data")?;
59 let b = mkboundary(b.as_str());
64 warnings.add(&e.wrap_err("guessing boundary"))?;
69 let mut body = req.into_body();
70 let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
72 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
73 Err(ReadLimitedError::Hyper(e)) => throw!(e),
76 let finder = memmem::Finder::new(&boundary);
77 let mut find_iter = finder.find_iter(&initial);
79 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
80 else if let Some(start) = find_iter.next() { start + boundary.len() }
81 else { throw!(anyhow!("initial boundary not found")) };
83 let comp = multipart::process_component
84 (&mut warnings, &initial[start..], PartName::m)?
85 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
87 if comp.name != PartName::m { throw!(anyhow!(
88 r#"first multipart component must be name="m""#
91 let mut meta = MetadataFieldIterator::new(comp.payload_start);
93 let client: ClientName = meta.need_parse().context("client addr")?;
95 let (client_time, hmac_got) = (||{
96 let token: &str = meta.need_next().context(r#"find in "m""#)?;
97 let (time_t, hmac_got) = token.split_once(' ')
98 .ok_or_else(|| anyhow!("split"))?;
99 let time_t: u64 = time_t.parse().context("parse time_t")?;
100 Ok::<_,AE>((time_t, hmac_got))
101 })().context("token")?;
103 let client = all_clients.get(&client);
105 // We attempt to hide whether the client exists we don't try to
106 // hide the hash lookup computationgs, but we do try to hide the
107 // HMAC computation by always doing it. We hope that the compiler
108 // doesn't produce a specialised implementation for the dummy
110 let client_exists = subtle::Choice::from(client.is_some() as u8);
111 let secret = client.map(|c| c.ic.secret.0.as_bytes());
112 let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
113 let client_time_s = format!("{:x}", client_time);
114 let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
115 // We also definitely want a consttime memeq for the hmac value
116 let hmac_ok = hmac_got.as_bytes().ct_eq(&hmac_exp);
117 if ! bool::from(hmac_ok & client_exists) {
118 throw!(anyhow!("xxx should be a 403 error"));
121 let client = client.unwrap();
122 let now = time_t_now();
123 let chk_skew = |a: u64, b: u64, c_ahead_behind| {
124 if let Some(a_ahead) = a.checked_sub(b) {
125 if a_ahead > client.ic.max_clock_skew.as_secs() {
126 throw!(anyhow!("too much clock skew (client {} by {})",
127 c_ahead_behind, a_ahead));
132 chk_skew(client_time, now, "ahead")?;
133 chk_skew(now, client_time, "behind")?;
135 eprintln!("boundary={:?} start={} name={:?} client={}",
136 boundary, start, &comp.name, &client.ic);
143 eprintln!("error={}", e);
147 eprintln!("warnings={:?}", &warnings);
149 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
152 async fn run_client(_ic: Arc<InstanceConfig>, _web: mpsc::Receiver<WebRequest>)
155 tokio::time::sleep(Duration::from_secs(1_000_000_000)).await;
161 let opts = Opts::from_args();
167 let (global, ipif) = config::startup(
168 "hippotatd", LinkEnd::Server,
169 &opts.config, &opts.log, |ics|
171 let global = config::InstanceConfigGlobal::from(&ics);
172 let ipif = Ipif::start(&global.ipif, None)?;
174 let all_clients: AllClients = ics.into_iter().map(|ic| {
175 let ic = Arc::new(ic);
177 let (web_send, web_recv) = mpsc::channel(
178 5 // xxx should me max_requests_outstanding but that's
179 // marked client-only so needs rework
182 let ic_ = ic.clone();
183 tasks.push((tokio::spawn(async move {
184 run_client(ic_, web_recv).await.void_unwrap_err()
185 }), format!("client {}", &ic)));
193 let all_clients = Arc::new(all_clients);
195 for addr in &global.addrs {
196 let all_clients_ = all_clients.clone();
197 let make_service = hyper::service::make_service_fn(move |_conn| {
198 let all_clients_ = all_clients_.clone();
199 async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
200 handle(all_clients_.clone(), req)
204 let addr = SocketAddr::new(*addr, global.port);
205 let server = hyper::Server::try_bind(&addr)
207 .http1_preserve_header_case(true)
208 .serve(make_service);
209 info!("listening on {}", &addr);
210 let task = tokio::task::spawn(async move {
212 Ok(()) => anyhow!("shut down?!"),
216 tasks.push((task, format!("http server {}", addr)));
222 let died = future::select_all(
223 tasks.iter_mut().map(|e| &mut e.0)
225 error!("xxx {:?}", &died);
227 ipif.quitting(None).await;