chiark / gitweb /
multipart: process_boundary: Rename, and better docs
[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 async fn run_client(ic: Arc<InstanceConfig>,
219                     mut web: mpsc::Receiver<WebRequest>)
220                     -> Result<Void, AE>
221 {
222   struct Outstanding {
223     reply_to: tokio::sync::oneshot::Sender<WebResponse>,
224     max_requests_outstanding: u32,
225   }
226   let mut outstanding: VecDeque<Outstanding> = default();
227   let  downbound: VecDeque<(/*xxx*/)> = default();
228
229   let try_send_response = |
230     reply_to: tokio::sync::oneshot::Sender<WebResponse>,
231     response: WebResponse
232   | {
233     reply_to.send(response)
234       .unwrap_or_else(|_: WebResponse| () /* oh dear */ /* xxx trace? */);
235   };
236
237   loop {
238     if let Some(ret) = {
239       if ! downbound.is_empty() {
240         outstanding.pop_front()
241       } else if let Some((i,_)) = outstanding.iter().enumerate().find({
242         |(_,o)| outstanding.len() > o.max_requests_outstanding.sat()
243       }) {
244         Some(outstanding.remove(i).unwrap())
245       } else {
246         None
247       }
248     } {
249       let response = WebResponse {
250         data: Ok(()),
251         warnings: default(),
252       };
253
254       try_send_response(ret.reply_to, response);
255     }
256
257     select!{
258       req = web.recv() =>
259       {
260         let WebRequest {
261           initial, initial_remaining, length_hint, mut body,
262           boundary_finder,
263           reply_to, warnings,
264         } = req.ok_or_else(|| anyhow!("webservers all shut down!"))?;
265
266         match async {
267
268           let whole_request = read_limited_bytes(
269             ic.max_batch_up.sat(),
270             initial,
271             length_hint,
272             &mut body
273           ).await.context("read request body")?;
274
275           dbg!(whole_request.len());
276
277 /*          
278
279           multipart::ComponentIterator::resume_mid_component(
280             &initial[initial_remaining..],
281   */          
282
283           Ok::<_,AE>(())
284         }.await {
285           Ok(()) => outstanding.push_back(Outstanding {
286             reply_to: reply_to,
287             max_requests_outstanding: 42, // xxx
288           }),
289           Err(e) => {
290             try_send_response(reply_to, WebResponse {
291               data: Err(e),
292               warnings,
293             });
294           },
295         }
296       }
297     }
298   }
299   //Err(anyhow!("xxx"))
300 }
301
302 #[tokio::main]
303 async fn main() {
304   let opts = Opts::from_args();
305   let mut tasks: Vec<(
306     JoinHandle<AE>,
307     String,
308   )> = vec![];
309
310   let (global, ipif) = config::startup(
311     "hippotatd", LinkEnd::Server,
312     &opts.config, &opts.log, |ics|
313   {
314     let global = config::InstanceConfigGlobal::from(&ics);
315     let ipif = Ipif::start(&global.ipif, None)?;
316
317     let all_clients: AllClients = ics.into_iter().map(|ic| {
318       let ic = Arc::new(ic);
319
320       let (web_send, web_recv) = mpsc::channel(
321         5 // xxx should me max_requests_outstanding but that's
322           // marked client-only so needs rework
323       );
324
325       let ic_ = ic.clone();
326       tasks.push((tokio::spawn(async move {
327         run_client(ic_, web_recv).await.void_unwrap_err()
328       }), format!("client {}", &ic)));
329
330       (ic.link.client,
331        ClientHandles {
332          ic,
333          web: web_send,
334        })
335     }).collect();
336     let all_clients = Arc::new(all_clients);
337
338     for addr in &global.addrs {
339       let all_clients_ = all_clients.clone();
340       let make_service = hyper::service::make_service_fn(move |_conn| {
341         let all_clients_ = all_clients_.clone();
342         async { Ok::<_, Void>( hyper::service::service_fn(move |req| {
343           handle(all_clients_.clone(), req)
344         }) ) } }
345       );
346
347       let addr = SocketAddr::new(*addr, global.port);
348       let server = hyper::Server::try_bind(&addr)
349         .context("bind")?
350         .http1_preserve_header_case(true)
351         .serve(make_service);
352       info!("listening on {}", &addr);
353       let task = tokio::task::spawn(async move {
354         match server.await {
355           Ok(()) => anyhow!("shut down?!"),
356           Err(e) => e.into(),
357         }
358       });
359       tasks.push((task, format!("http server {}", addr)));
360     }
361     
362     Ok((global, ipif))
363   });
364
365   let died = future::select_all(
366     tasks.iter_mut().map(|e| &mut e.0)
367   ).await;
368   error!("xxx {:?}", &died);
369
370   ipif.quitting(None).await;
371
372   dbg!(global);
373 }