chiark / gitweb /
server: wip
[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 async fn handle(
19 //    context: (),
20 //    addr: SocketAddr,
21     req: hyper::Request<hyper::Body>
22 ) -> Result<hyper::Response<hyper::Body>, Infallible> {
23   if req.method() == Method::GET {
24     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
25     resp.headers_mut().insert(
26       "Content-Type",
27       "text/plain; charset=US-ASCII".try_into().unwrap()
28     );
29     return Ok(resp)
30   }
31
32   let mut warnings: Warnings = default();
33
34   match async {
35
36     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
37     let boundary = match (||{
38       let mut ctypes = req.headers().get_all("Content-Type").iter();
39       let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
40       if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
41       let t = t.to_str().context("interpret Content-Type as utf-8")?;
42       let t: mime::Mime = t.parse().context("parse Content-Type")?;
43       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
44       let b = mime::BOUNDARY;
45       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
46       if t.subtype() != "form-data" {
47         warnings.add(&"Content-Type not /form-data")?;
48       }
49       let b = mkboundary(b.as_str());
50       Ok::<_,AE>(b)
51     })() {
52       Ok(y) => y,
53       Err(e) => {
54         warnings.add(&e.wrap_err("guessing boundary"))?;
55         mkboundary("b")
56       },
57     };
58
59     let mut body = req.into_body();
60     let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
61       Ok(all) => all,
62       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
63       Err(ReadLimitedError::Hyper(e)) => throw!(e),
64     };
65
66     let finder = memmem::Finder::new(&boundary);
67     let mut find_iter = finder.find_iter(&initial);
68
69     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
70     else if let Some(start) = find_iter.next() { start + boundary.len() }
71     else { throw!(anyhow!("initial boundary not found")) };
72
73     let comp = multipart::process_component
74       (&mut warnings, &initial[start..], PartName::m)?
75       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
76
77     if comp.name != PartName::m { throw!(anyhow!(
78       r#"first multipart component must be name="m""#
79     )) }
80
81     eprintln!("boundary={:?} initial={:?} start={} comp={:?}",
82               boundary, initial, start, &comp);
83
84     Ok::<_,AE>(())
85   }.await {
86     Ok(()) => {
87     },
88     Err(e) => {
89       eprintln!("error={}", e);
90     }
91   }
92
93   eprintln!("warnings={:?}", &warnings);
94
95   Ok(hyper::Response::new(hyper::Body::from("Hello World")))
96 }
97
98
99 #[tokio::main]
100 async fn main() {
101   let opts = Opts::from_args();
102   let mut hservers = vec![];
103   let (ics,(global,ipif)) = config::startup(
104     "hippotatd", LinkEnd::Server,
105     &opts.config, &opts.log, |ics|
106   {
107     let global = config::InstanceConfigGlobal::from(&ics);
108     let ipif = Ipif::start(&global.ipif, None)?;
109
110     let make_service = hyper::service::make_service_fn(|_conn| async {
111       Ok::<_, Infallible>(hyper::service::service_fn(handle))
112     });
113
114     for addr in &global.addrs {
115       let addr = SocketAddr::new(*addr, global.port);
116       let server = hyper::Server::try_bind(&addr)
117         .context("bind")?
118         .http1_preserve_header_case(true)
119         .serve(make_service);
120       info!("listening on {}", &addr);
121       let task = tokio::task::spawn(server);
122       hservers.push(task);
123     }
124
125     Ok((global, ipif))
126   });
127
128   let x = future::select_all(&mut hservers).await;
129   error!("xxx hserver {:?}", &x);
130
131   ipif.quitting(None).await;
132
133   dbg!(ics, global);
134 }