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