chiark / gitweb /
1764470ba118ae8dc47c560a6161a1b20f13b79f
[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   length_hint: usize,
34   body: hyper::body::Body,
35   boundary_finder: multipart::BoundaryFinder,
36   reply_to: tokio::sync::oneshot::Sender<WebResponse>,
37   warnings: Warnings,
38 }
39
40 /// Reply from client task to hyper worker pool task
41 #[allow(dead_code)] // xxx
42 struct WebResponse {
43   warnings: Warnings,
44   data: Result<WebResponseData, AE>,
45 }
46
47 type WebResponseData = ();
48
49 async fn handle(
50   all_clients: Arc<AllClients>,
51   req: hyper::Request<hyper::Body>
52 ) -> Result<hyper::Response<hyper::Body>, Void> {
53   if req.method() == Method::GET {
54     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
55     resp.headers_mut().insert(
56       "Content-Type",
57       "text/plain; charset=US-ASCII".try_into().unwrap()
58     );
59     return Ok(resp)
60   }
61
62   let mut warnings: Warnings = default();
63
64   match async {
65
66     let get_header = |hn: &str| {
67       let mut values = req.headers().get_all(hn).iter();
68       let v = values.next().ok_or_else(|| anyhow!("missing {}", hn))?;
69       if values.next().is_some() { throw!(anyhow!("multiple {}!", hn)); }
70       let v = v.to_str().context(anyhow!("interpret {} as UTF-8", hn))?;
71       Ok::<_,AE>(v)
72     };
73
74     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
75     let boundary = match (||{
76       let t = get_header("Content-Type")?;
77       let t: mime::Mime = t.parse().context("parse Content-Type")?;
78       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
79       let b = mime::BOUNDARY;
80       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
81       if t.subtype() != "form-data" {
82         warnings.add(&"Content-Type not /form-data")?;
83       }
84       let b = mkboundary(b.as_str());
85       Ok::<_,AE>(b)
86     })() {
87       Ok(y) => y,
88       Err(e) => {
89         warnings.add(&e.wrap_err("guessing boundary"))?;
90         mkboundary("b")
91       },
92     };
93
94     let length_hint: usize = (||{
95       let clength = get_header("Content-Length")?;
96       let clength = clength.parse().context("parse Content-Length")?;
97       Ok::<_,AE>(clength)
98     })().unwrap_or_else(
99       |e| { let _ = warnings.add(&e.wrap_err("parsing Content-Length")); 0 }
100     );
101
102     let mut body = req.into_body();
103     let initial = match read_limited_bytes(
104       METADATA_MAX_LEN, default(), length_hint, &mut body
105     ).await {
106       Ok(all) => all,
107       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
108       Err(ReadLimitedError::Hyper(e)) => throw!(e),
109     };
110
111     let boundary_finder = memmem::Finder::new(&boundary);
112     let mut boundary_iter = boundary_finder.find_iter(&initial);
113
114     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
115     else if let Some(start) = boundary_iter.next() { start + boundary.len() }
116     else { throw!(anyhow!("initial boundary not found")) };
117
118     let comp = multipart::process_boundary
119       (&mut warnings, &initial[start..], PartName::m)?
120       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
121
122     if comp.name != PartName::m { throw!(anyhow!(
123       r#"first multipart component must be name="m""#
124     )) }
125
126     let mut meta = MetadataFieldIterator::new(comp.payload);
127
128     let client: ClientName = meta.need_parse().context("client addr")?;
129
130     let mut hmac_got = [0; HMAC_L];
131     let (client_time, hmac_got_l) = (||{
132       let token: &str = meta.need_next().context(r#"find in "m""#)?;
133       let (time_t, hmac_b64) = token.split_once(' ')
134         .ok_or_else(|| anyhow!("split"))?;
135       let time_t = u64::from_str_radix(time_t, 16).context("parse time_t")?;
136       let l = io::copy(
137         &mut base64::read::DecoderReader::new(&mut hmac_b64.as_bytes(),
138                                               BASE64_CONFIG),
139         &mut &mut hmac_got[..]
140       ).context("parse b64 token")?;
141       let l = l.try_into()?;
142       Ok::<_,AE>((time_t, l))
143     })().context("token")?;
144     let hmac_got = &hmac_got[0..hmac_got_l];
145
146     let client = all_clients.get(&client);
147
148     // We attempt to hide whether the client exists we don't try to
149     // hide the hash lookup computationgs, but we do try to hide the
150     // HMAC computation by always doing it.  We hope that the compiler
151     // doesn't produce a specialised implementation for the dummy
152     // secret value.
153     let client_exists = subtle::Choice::from(client.is_some() as u8);
154     let secret = client.map(|c| c.ic.secret.0.as_bytes());
155     let secret = secret.unwrap_or(&[0x55; HMAC_B][..]);
156     let client_time_s = format!("{:x}", client_time);
157     let hmac_exp = token_hmac(secret, client_time_s.as_bytes());
158     // We also definitely want a consttime memeq for the hmac value
159     let hmac_ok = hmac_got.ct_eq(&hmac_exp);
160     //dbg!(DumpHex(&hmac_exp), client.is_some());
161     //dbg!(DumpHex(hmac_got), hmac_ok, client_exists);
162     if ! bool::from(hmac_ok & client_exists) {
163       throw!(anyhow!("xxx should be a 403 error"));
164     }
165
166     let client = client.unwrap();
167     let now = time_t_now();
168     let chk_skew = |a: u64, b: u64, c_ahead_behind| {
169       if let Some(a_ahead) = a.checked_sub(b) {
170         if a_ahead > client.ic.max_clock_skew.as_secs() {
171           throw!(anyhow!("too much clock skew (client {} by {})",
172                          c_ahead_behind, a_ahead));
173         }
174       }
175       Ok::<_,AE>(())
176     };
177     chk_skew(client_time, now, "ahead")?;
178     chk_skew(now, client_time, "behind")?;
179
180     let initial_remaining = meta.remaining_bytes_len();
181
182     //eprintln!("boundary={:?} start={} name={:?} client={}",
183     // boundary, start, &comp.name, &client.ic);
184
185     let (reply_to, reply_recv) = tokio::sync::oneshot::channel();
186     let wreq = WebRequest {
187       initial,
188       initial_remaining,
189       length_hint,
190       boundary_finder: boundary_finder.into_owned(),
191       body,
192       warnings: mem::take(&mut warnings),
193       reply_to
194     };
195     trace!("{} request", &client.ic);
196
197     client.web.try_send(wreq)
198       .map_err(|_| anyhow!("client task shut down!"))?;
199
200     let reply: WebResponse = reply_recv.await?;
201     warnings = reply.warnings;
202
203     reply.data
204   }.await {
205     Ok(()) => {
206     },
207     Err(e) => {
208       eprintln!("error={}", e);
209     }
210   }
211
212   eprintln!("warnings={:?}", &warnings);
213
214   Ok(hyper::Response::new(hyper::Body::from("Hello World")))
215 }
216
217 #[allow(unused_variables)] // xxx
218 #[allow(unused_mut)] // xxx
219 async fn run_client(ic: Arc<InstanceConfig>,
220                     mut web: mpsc::Receiver<WebRequest>)
221                     -> Result<Void, AE>
222 {
223   struct Outstanding {
224     reply_to: tokio::sync::oneshot::Sender<WebResponse>,
225     max_requests_outstanding: u32,
226   }
227   let mut outstanding: VecDeque<Outstanding> = default();
228   let  downbound: VecDeque<(/*xxx*/)> = default();
229
230   let try_send_response = |
231     reply_to: tokio::sync::oneshot::Sender<WebResponse>,
232     response: WebResponse
233   | {
234     reply_to.send(response)
235       .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
236   };
237
238   loop {
239     if let Some(ret) = {
240       if ! downbound.is_empty() {
241         outstanding.pop_front()
242       } else if let Some((i,_)) = outstanding.iter().enumerate().find({
243         |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
244       }) {
245         Some(outstanding.remove(i).unwrap())
246       } else {
247         None
248       }
249     } {
250       let response = WebResponse {
251         data: Ok(()),
252         warnings: default(),
253       };
254
255       try_send_response(ret.reply_to, response);
256     }
257
258     select!{
259       req = web.recv() =>
260       {
261         let WebRequest {
262           initial, initial_remaining, length_hint, mut body,
263           boundary_finder,
264           reply_to, warnings,
265         } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
266
267         match async {
268
269           let whole_request = read_limited_bytes(
270             ic.max_batch_up.sat(),
271             initial,
272             length_hint,
273             &mut body
274           ).await.context("read request body")?;
275
276           let (meta, comps) =
277             multipart::ComponentIterator::resume_mid_component(
278               &whole_request[initial_remaining..],
279               boundary_finder
280             ).context("resume parsing body, after auth checks")?;
281
282           let mut meta = MetadataFieldIterator::new(&meta);
283 /*
284           macro_rules!(
285
286           let target_requests_outstanding = {
287             let server = ic.target_requests_outstanding;
288             let client: u32 = meta.need_parse()?;
289             if client != server {
290               throw!(anyhow!("mismatch: client={} != server={}",
291                              client, server));
292             }
293             Ok::<_,AE>(client)
294           }.context("target_requests_outstanding")?;
295
296           let http_timeout: u64 = {
297             let server = ic.http_timeout;
298             let client = Duration::from_secs(meta.need_parse()?);
299             if client > server {
300               throw!(anyhow!("mismatch: client={} > server={}",
301                              client, server));
302             }
303             Ok::<_,AE>(client)
304           }.context("http_timeout")?;
305
306           let max_batch_down = {
307             let server = ic.max_batch_down;
308             let client: u32 = meta.parse().context("max_batch_down")?;
309             let to_use = min(client, server);
310             Ok::<_,AE>(to_use)
311           }.context("max_batch_down")?;
312
313           let max_batch_up = {
314             let server = ic.max_batch_up;
315             let client = meta.parse().context("max_batch_up")?;
316             if client > server {
317               throw!(anyhow!("mismatch: client={} != server={}",
318                              client, server));
319             }
320               
321             throw!(anyhow!(
322  "target_requests_outstanding mismatch: client={} server={}",
323               target_requests_outstanding, 
324               ic.target_requests_outstanding
325             ))
326           }
327
328           if ic.
329 */
330           Ok::<_,AE>(())
331         }.await {
332           Ok(()) => outstanding.push_back(Outstanding {
333             reply_to: reply_to,
334             max_requests_outstanding: 42, // xxx
335           }),
336           Err(e) => {
337             try_send_response(reply_to, WebResponse {
338               data: Err(e),
339               warnings,
340             });
341           },
342         }
343       }
344     }
345   }
346   //Err(anyhow!("xxx"))
347 }
348
349 #[tokio::main]
350 async fn main() {
351   let opts = Opts::from_args();
352   let mut tasks: Vec<(
353     JoinHandle<AE>,
354     String,
355   )> = vec![];
356
357   let (global, ipif) = config::startup(
358     "hippotatd", LinkEnd::Server,
359     &opts.config, &opts.log, |ics|
360   {
361     let global = config::InstanceConfigGlobal::from(&ics);
362     let ipif = Ipif::start(&global.ipif, None)?;
363
364     let all_clients: AllClients = ics.into_iter().map(|ic| {
365       let ic = Arc::new(ic);
366
367       let (web_send, web_recv) = mpsc::channel(
368         5 // xxx should me max_requests_outstanding but that's
369           // marked client-only so needs rework
370       );
371
372       let ic_ = ic.clone();
373       tasks.push((tokio::spawn(async move {
374         run_client(ic_, web_recv).await.void_unwrap_err()
375       }), format!("client {}", &ic)));
376
377       (ic.link.client,
378        ClientHandles {
379          ic,
380          web: web_send,
381        })
382     }).collect();
383     let all_clients = Arc::new(all_clients);
384
385     for addr in &global.addrs {
386       let all_clients_ = all_clients.clone();
387       let make_service = hyper::service::make_service_fn(move |_conn| {
388         let all_clients_ = all_clients_.clone();
389         async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
390           handle(all_clients_.clone(), req)
391         }) ) } }
392       );
393
394       let addr = SocketAddr::new(*addr, global.port);
395       let server = hyper::Server::try_bind(&addr)
396         .context("bind")?
397         .http1_preserve_header_case(true)
398         .serve(make_service);
399       info!("listening on {}", &addr);
400       let task = tokio::task::spawn(async move {
401         match server.await {
402           Ok(()) => anyhow!("shut down?!"),
403           Err(e) => e.into(),
404         }
405       });
406       tasks.push((task, format!("http server {}", addr)));
407     }
408     
409     Ok((global, ipif))
410   });
411
412   let died = future::select_all(
413     tasks.iter_mut().map(|e| &mut e.0)
414   ).await;
415   error!("xxx {:?}", &died);
416
417   ipif.quitting(None).await;
418
419   dbg!(global);
420 }