chiark / gitweb /
764b22f5e2954a98e9d6eede7c034fbb8c54dc56
[hippotat.git] / src / bin / server.rs
1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
4
5 use hippotat::prelude::*;
6
7 #[derive(StructOpt,Debug)]
8 pub struct Opts {
9   #[structopt(flatten)]
10   log: LogOpts,
11
12   #[structopt(flatten)]
13   config: config::Opts,
14 }
15
16 const METADATA_MAX_LEN: usize = MAX_OVERHEAD;
17
18 type AllClients = HashMap<ClientName, ClientHandles>;
19
20 struct ClientHandles {
21   ic: Arc<InstanceConfig>,
22   web: tokio::sync::mpsc::Sender<WebRequest>,
23 }
24
25 /// Sent from hyper worker pool task to client task
26 #[allow(dead_code)] // xxx
27 struct WebRequest {
28   // initial part of body
29   // used up to and including first 2 lines of metadata
30   // end delimiter for the metadata not yet located, but in here somewhere
31   initial: Box<[u8]>,
32   initial_remaining: usize,
33   body: hyper::body::Body,
34   reply: tokio::sync::oneshot::Sender<WebResponse>,
35 }
36
37 /// Reply from client task to hyper worker pool task
38 type WebResponse = Result<WebResponseData, AE>;
39 type WebResponseData = ();
40
41 async fn handle(
42   all_clients: Arc<AllClients>,
43   req: hyper::Request<hyper::Body>
44 ) -> Result<hyper::Response<hyper::Body>, Void> {
45   if req.method() == Method::GET {
46     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
47     resp.headers_mut().insert(
48       "Content-Type",
49       "text/plain; charset=US-ASCII".try_into().unwrap()
50     );
51     return Ok(resp)
52   }
53
54   let mut warnings: Warnings = default();
55
56   match async {
57
58     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
59     let boundary = match (||{
60       let mut ctypes = req.headers().get_all("Content-Type").iter();
61       let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
62       if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
63       let t = t.to_str().context("interpret Content-Type as utf-8")?;
64       let t: mime::Mime = t.parse().context("parse Content-Type")?;
65       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
66       let b = mime::BOUNDARY;
67       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
68       if t.subtype() != "form-data" {
69         warnings.add(&"Content-Type not /form-data")?;
70       }
71       let b = mkboundary(b.as_str());
72       Ok::<_,AE>(b)
73     })() {
74       Ok(y) => y,
75       Err(e) => {
76         warnings.add(&e.wrap_err("guessing boundary"))?;
77         mkboundary("b")
78       },
79     };
80
81     let mut body = req.into_body();
82     let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
83       Ok(all) => all,
84       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
85       Err(ReadLimitedError::Hyper(e)) => throw!(e),
86     };
87
88     let finder = memmem::Finder::new(&boundary);
89     let mut find_iter = finder.find_iter(&initial);
90
91     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
92     else if let Some(start) = find_iter.next() { start + boundary.len() }
93     else { throw!(anyhow!("initial boundary not found")) };
94
95     let comp = multipart::process_component
96       (&mut warnings, &initial[start..], PartName::m)?
97       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
98
99     if comp.name != PartName::m { throw!(anyhow!(
100       r#"first multipart component must be name="m""#
101     )) }
102
103     let mut meta = MetadataFieldIterator::new(comp.payload_start);
104
105     let client: ClientName = meta.need_parse().context("client addr")?;
106
107     let mut hmac_got = [0; HMAC_L];
108     let (client_time, hmac_got_l) = (||{
109       let token: &str = meta.need_next().context(r#"find in "m""#)?;
110       let (time_t, hmac_b64) = token.split_once(' ')
111         .ok_or_else(|| anyhow!("split"))?;
112       let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
113       let l = io::copy(
114         &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
115                                               BASE64_CONFIG),
116         &mut &mut hmac_got[..]
117       ).context("parse b64 token")?;
118       let l = l.try_into()?;
119       Ok::<_,AE>((time_t, l))
120     })().context("token")?;
121     let hmac_got = &hmac_got[0..hmac_got_l];
122
123     let client = all_clients.get(&client);
124
125     // We attempt to hide whether the client exists we don't try to
126     // hide the hash lookup computationgs, but we do try to hide the
127     // HMAC computation by always doing it.  We hope that the compiler
128     // doesn't produce a specialised implementation for the dummy
129     // secret value.
130     let client_exists = subtle::Choice::from(client.is_some() as u8);
131     let secret = client.map(|c| c.ic.secret.0.as_bytes());
132     let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
133     let client_time_s = format!("{:x}", client_time);
134     let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
135     // We also definitely want a consttime memeq for the hmac value
136     let hmac_ok = hmac_got.ct_eq(&hmac_exp);
137     //dbg!(DumpHex(&hmac_exp), client.is_some());
138     //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
139     if ! bool::from(hmac_ok & client_exists) {
140       throw!(anyhow!("xxx should be a 403 error"));
141     }
142
143     let client = client.unwrap();
144     let now = time_t_now();
145     let chk_skew = |a: u64, b: u64, c_ahead_behind| {
146       if let Some(a_ahead) = a.checked_sub(b) {
147         if a_ahead > client.ic.max_clock_skew.as_secs() {
148           throw!(anyhow!("too much clock skew (client {} by {})",
149                          c_ahead_behind, a_ahead));
150         }
151       }
152       Ok::<_,AE>(())
153     };
154     chk_skew(client_time, now, "ahead")?;
155     chk_skew(now, client_time, "behind")?;
156
157     let initial_remaining = meta.remaining_bytes_len();
158
159     //eprintln!("boundary={:?} start={} name={:?} client={}",
160     // boundary, start, &comp.name, &client.ic);
161
162     let (reply, reply_recv) = tokio::sync::oneshot::channel();
163     let wreq = WebRequest {
164       initial,
165       initial_remaining,
166       body,
167       reply
168     };
169     trace!("{} request", &client.ic);
170
171     client.web.try_send(wreq)
172       .map_err(|_| anyhow!("client task shut down!"))?;
173
174     let reply: WebResponse = reply_recv.await?;
175
176     reply
177   }.await {
178     Ok(()) => {
179     },
180     Err(e) => {
181       eprintln!("error={}", e);
182     }
183   }
184
185   eprintln!("warnings={:?}", &warnings);
186
187   Ok(hyper::Response::new(hyper::Body::from("Hello World")))
188 }
189
190 async fn run_client(_ic: Arc<InstanceConfig>,
191                     mut web: mpsc::Receiver<WebRequest>)
192                     -> Result<Void, AE>
193 {
194   struct Outstanding {
195     reply: tokio::sync::oneshot::Sender<WebResponse>,
196     max_requests_outstanding: u32,
197   }
198   let mut outstanding: VecDeque<Outstanding> = default();
199   let  downbound: VecDeque<(/*xxx*/)> = default();
200
201   loop {
202     if let Some(ret) = {
203       if ! downbound.is_empty() {
204         outstanding.pop_front()
205       } else if let Some((i,_)) = outstanding.iter().enumerate().find({
206         |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
207       }) {
208         Some(outstanding.remove(i).unwrap())
209       } else {
210         None
211       }
212     } {
213       ret.reply.send(Ok(() /* dummy */))
214         .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
215     }
216
217     select!{
218       req = web.recv() =>
219       {
220         let req = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
221         outstanding.push_back(Outstanding {
222           reply: req.reply,
223           max_requests_outstanding: 42, // xxx
224         });
225       }
226     }
227   }
228   //Err(anyhow!("xxx"))
229 }
230
231 #[tokio::main]
232 async fn main() {
233   let opts = Opts::from_args();
234   let mut tasks: Vec<(
235     JoinHandle<AE>,
236     String,
237   )> = vec![];
238
239   let (global, ipif) = config::startup(
240     "hippotatd", LinkEnd::Server,
241     &opts.config, &opts.log, |ics|
242   {
243     let global = config::InstanceConfigGlobal::from(&ics);
244     let ipif = Ipif::start(&global.ipif, None)?;
245
246     let all_clients: AllClients = ics.into_iter().map(|ic| {
247       let ic = Arc::new(ic);
248
249       let (web_send, web_recv) = mpsc::channel(
250         5 // xxx should me max_requests_outstanding but that's
251           // marked client-only so needs rework
252       );
253
254       let ic_ = ic.clone();
255       tasks.push((tokio::spawn(async move {
256         run_client(ic_, web_recv).await.void_unwrap_err()
257       }), format!("client {}", &ic)));
258
259       (ic.link.client,
260        ClientHandles {
261          ic,
262          web: web_send,
263        })
264     }).collect();
265     let all_clients = Arc::new(all_clients);
266
267     for addr in &global.addrs {
268       let all_clients_ = all_clients.clone();
269       let make_service = hyper::service::make_service_fn(move |_conn| {
270         let all_clients_ = all_clients_.clone();
271         async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
272           handle(all_clients_.clone(), req)
273         }) ) } }
274       );
275
276       let addr = SocketAddr::new(*addr, global.port);
277       let server = hyper::Server::try_bind(&addr)
278         .context("bind")?
279         .http1_preserve_header_case(true)
280         .serve(make_service);
281       info!("listening on {}", &addr);
282       let task = tokio::task::spawn(async move {
283         match server.await {
284           Ok(()) => anyhow!("shut down?!"),
285           Err(e) => e.into(),
286         }
287       });
288       tasks.push((task, format!("http server {}", addr)));
289     }
290     
291     Ok((global, ipif))
292   });
293
294   let died = future::select_all(
295     tasks.iter_mut().map(|e| &mut e.0)
296   ).await;
297   error!("xxx {:?}", &died);
298
299   ipif.quitting(None).await;
300
301   dbg!(global);
302 }