chiark / gitweb /
server: wip, all_clients plumbing
[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 struct WebRequest {
26   reply: tokio::sync::oneshot::Sender<()>,
27 }
28
29 async fn handle(
30   _all_clients: Arc<AllClients>,
31   req: hyper::Request<hyper::Body>
32 ) -> Result<hyper::Response<hyper::Body>, Infallible> {
33   if req.method() == Method::GET {
34     let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
35     resp.headers_mut().insert(
36       "Content-Type",
37       "text/plain; charset=US-ASCII".try_into().unwrap()
38     );
39     return Ok(resp)
40   }
41
42   let mut warnings: Warnings = default();
43
44   match async {
45
46     let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
47     let boundary = match (||{
48       let mut ctypes = req.headers().get_all("Content-Type").iter();
49       let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
50       if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
51       let t = t.to_str().context("interpret Content-Type as utf-8")?;
52       let t: mime::Mime = t.parse().context("parse Content-Type")?;
53       if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
54       let b = mime::BOUNDARY;
55       let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
56       if t.subtype() != "form-data" {
57         warnings.add(&"Content-Type not /form-data")?;
58       }
59       let b = mkboundary(b.as_str());
60       Ok::<_,AE>(b)
61     })() {
62       Ok(y) => y,
63       Err(e) => {
64         warnings.add(&e.wrap_err("guessing boundary"))?;
65         mkboundary("b")
66       },
67     };
68
69     let mut body = req.into_body();
70     let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
71       Ok(all) => all,
72       Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
73       Err(ReadLimitedError::Hyper(e)) => throw!(e),
74     };
75
76     let finder = memmem::Finder::new(&boundary);
77     let mut find_iter = finder.find_iter(&initial);
78
79     let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
80     else if let Some(start) = find_iter.next() { start + boundary.len() }
81     else { throw!(anyhow!("initial boundary not found")) };
82
83     let comp = multipart::process_component
84       (&mut warnings, &initial[start..], PartName::m)?
85       .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
86
87     if comp.name != PartName::m { throw!(anyhow!(
88       r#"first multipart component must be name="m""#
89     )) }
90
91     let nl = memchr::memchr2(b'\r', b'\n', comp.payload_start)
92       .ok_or_else(|| anyhow!("no newline in first metadata line?"))?;
93
94     let client = &comp.payload_start[0..nl];
95     let client = str::from_utf8(client).context("client addr utf-8")?;
96     let client: IpAddr = client.parse().context("client address")?;
97
98     
99
100     eprintln!("boundary={:?} start={} name={:?} client={}",
101               boundary, start, &comp.name, client);
102
103     Ok::<_,AE>(())
104   }.await {
105     Ok(()) => {
106     },
107     Err(e) => {
108       eprintln!("error={}", e);
109     }
110   }
111
112   eprintln!("warnings={:?}", &warnings);
113
114   Ok(hyper::Response::new(hyper::Body::from("Hello World")))
115 }
116
117 async fn run_client(_ic: Arc<InstanceConfig>, _web: mpsc::Receiver<WebRequest>)
118                     -> Result<Void, AE>
119 {
120   Err(anyhow!("xxx"))
121 }
122
123 #[tokio::main]
124 async fn main() {
125   let opts = Opts::from_args();
126   let mut tasks: Vec<(
127     JoinHandle<AE>,
128     String,
129   )> = vec![];
130
131   let (global, ipif) = config::startup(
132     "hippotatd", LinkEnd::Server,
133     &opts.config, &opts.log, |ics|
134   {
135     let global = config::InstanceConfigGlobal::from(&ics);
136     let ipif = Ipif::start(&global.ipif, None)?;
137
138     let all_clients: AllClients = ics.into_iter().map(|ic| {
139       let ic = Arc::new(ic);
140
141       let (web_send, web_recv) = mpsc::channel(
142         5 // xxx should me max_requests_outstanding but that's
143           // marked client-only so needs rework
144       );
145
146       let ic_ = ic.clone();
147       tasks.push((tokio::spawn(async move {
148         run_client(ic_, web_recv).await.void_unwrap_err()
149       }), format!("client {}", &ic)));
150
151       (ic.link.client,
152        ClientHandles {
153          ic,
154          web: web_send,
155        })
156     }).collect();
157     let all_clients = Arc::new(all_clients);
158
159     for addr in &global.addrs {
160       let all_clients_ = all_clients.clone();
161       let make_service = hyper::service::make_service_fn(
162         move |_conn| {
163           let all_clients_ = all_clients_.clone();
164           async move {
165             let all_clients_ = all_clients_.clone();
166             Ok::<_, Void>(hyper::service::service_fn(move |req| {
167               let all_clients_ = all_clients_.clone();
168               handle(all_clients_, req)
169             }))
170           }
171         }
172       );
173
174       let addr = SocketAddr::new(*addr, global.port);
175       let server = hyper::Server::try_bind(&addr)
176         .context("bind")?
177         .http1_preserve_header_case(true)
178         .serve(make_service);
179       info!("listening on {}", &addr);
180       let task = tokio::task::spawn(async move {
181         match server.await {
182           Ok(()) => anyhow!("shut down?!"),
183           Err(e) => e.into(),
184         }
185       });
186       tasks.push((task, format!("http server {}", addr)));
187     }
188     
189     Ok((global, ipif))
190   });
191
192   let died = future::select_all(
193     tasks.iter_mut().map(|e| &mut e.0)
194   ).await;
195   error!("xxx {:?}", &died);
196
197   ipif.quitting(None).await;
198
199   dbg!(global);
200 }