1 // Copyright 2021 Ian Jackson and contributors to Hippotat
2 // SPDX-License-Identifier: GPL-3.0-or-later
3 // There is NO WARRANTY.
5 use hippotat::prelude::*;
7 #[derive(StructOpt,Debug)]
16 const METADATA_MAX_LEN: usize = MAX_OVERHEAD;
18 type AllClients = HashMap<ClientName, ClientHandles>;
20 struct ClientHandles {
21 ic: Arc<InstanceConfig>,
22 web: tokio::sync::mpsc::Sender<WebRequest>,
26 reply: tokio::sync::oneshot::Sender<()>,
32 req: hyper::Request<hyper::Body>
33 ) -> Result<hyper::Response<hyper::Body>, Infallible> {
34 if req.method() == Method::GET {
35 let mut resp = hyper::Response::new(hyper::Body::from("hippotat\r\n"));
36 resp.headers_mut().insert(
38 "text/plain; charset=US-ASCII".try_into().unwrap()
43 let mut warnings: Warnings = default();
47 let mkboundary = |b: &'_ _| format!("\n--{}", b).into_bytes();
48 let boundary = match (||{
49 let mut ctypes = req.headers().get_all("Content-Type").iter();
50 let t = ctypes.next().ok_or_else(|| anyhow!("missing Content-Type"))?;
51 if ctypes.next().is_some() { throw!(anyhow!("several Content-Type")) }
52 let t = t.to_str().context("interpret Content-Type as utf-8")?;
53 let t: mime::Mime = t.parse().context("parse Content-Type")?;
54 if t.type_() != "multipart" { throw!(anyhow!("not multipart/")) }
55 let b = mime::BOUNDARY;
56 let b = t.get_param(b).ok_or_else(|| anyhow!("missing boundary=..."))?;
57 if t.subtype() != "form-data" {
58 warnings.add(&"Content-Type not /form-data")?;
60 let b = mkboundary(b.as_str());
65 warnings.add(&e.wrap_err("guessing boundary"))?;
70 let mut body = req.into_body();
71 let initial = match read_limited_bytes(METADATA_MAX_LEN, &mut body).await {
73 Err(ReadLimitedError::Truncated { sofar,.. }) => sofar,
74 Err(ReadLimitedError::Hyper(e)) => throw!(e),
77 let finder = memmem::Finder::new(&boundary);
78 let mut find_iter = finder.find_iter(&initial);
80 let start = if initial.starts_with(&boundary[1..]) { boundary.len()-1 }
81 else if let Some(start) = find_iter.next() { start + boundary.len() }
82 else { throw!(anyhow!("initial boundary not found")) };
84 let comp = multipart::process_component
85 (&mut warnings, &initial[start..], PartName::m)?
86 .ok_or_else(|| anyhow!(r#"no "m" component"#))?;
88 if comp.name != PartName::m { throw!(anyhow!(
89 r#"first multipart component must be name="m""#
92 let nl = memchr::memchr2(b'\r', b'\n', comp.payload_start)
93 .ok_or_else(|| anyhow!("no newline in first metadata line?"))?;
95 let client = &comp.payload_start[0..nl];
96 let client = str::from_utf8(client).context("client addr utf-8")?;
97 let client: IpAddr = client.parse().context("client address")?;
99 eprintln!("boundary={:?} start={} name={:?} client={}",
100 boundary, start, &comp.name, client);
107 eprintln!("error={}", e);
111 eprintln!("warnings={:?}", &warnings);
113 Ok(hyper::Response::new(hyper::Body::from("Hello World")))
116 async fn run_client(_ic: Arc<InstanceConfig>, _web: mpsc::Receiver<WebRequest>)
124 let opts = Opts::from_args();
130 let (global, ipif) = config::startup(
131 "hippotatd", LinkEnd::Server,
132 &opts.config, &opts.log, |ics|
134 let global = config::InstanceConfigGlobal::from(&ics);
135 let ipif = Ipif::start(&global.ipif, None)?;
137 let _all_clients: AllClients = ics.into_iter().map(|ic| {
138 let ic = Arc::new(ic);
140 let (web_send, web_recv) = mpsc::channel(
141 5 // xxx should me max_requests_outstanding but that's
142 // marked client-only so needs rework
145 let ic_ = ic.clone();
146 tasks.push((tokio::spawn(async move {
147 run_client(ic_, web_recv).await.void_unwrap_err()
148 }), format!("client {}", &ic)));
157 let make_service = hyper::service::make_service_fn(|_conn| async {
158 Ok::<_, Infallible>(hyper::service::service_fn(handle))
161 for addr in &global.addrs {
162 let addr = SocketAddr::new(*addr, global.port);
163 let server = hyper::Server::try_bind(&addr)
165 .http1_preserve_header_case(true)
166 .serve(make_service);
167 info!("listening on {}", &addr);
168 let task = tokio::task::spawn(async move {
170 Ok(()) => anyhow!("shut down?!"),
174 tasks.push((task, format!("http server {}", addr)));
180 let died = future::select_all(
181 tasks.iter_mut().map(|e| &mut e.0)
183 error!("xxx {:?}", &died);
185 ipif.quitting(None).await;