chiark / gitweb /
server: wip, identify cliient
[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     let nl = memchr::memchr2(b'\r', b'\n', comp.payload_start)
82       .ok_or_else(|| anyhow!("no newline in first metadata line?"))?;
83
84     let client = &comp.payload_start[0..nl];
85     let client = str::from_utf8(client).context("client addr utf-8")?;
86     let client: IpAddr = client.parse().context("client address")?;
87
88     eprintln!("boundary={:?} start={} name={:?} client={}",
89               boundary, start, &comp.name, client);
90
91     Ok::<_,AE>(())
92   }.await {
93     Ok(()) => {
94     },
95     Err(e) => {
96       eprintln!("error={}", e);
97     }
98   }
99
100   eprintln!("warnings={:?}", &warnings);
101
102   Ok(hyper::Response::new(hyper::Body::from("Hello World")))
103 }
104
105
106 #[tokio::main]
107 async fn main() {
108   let opts = Opts::from_args();
109   let mut hservers = vec![];
110   let (ics,(global,ipif)) = config::startup(
111     "hippotatd", LinkEnd::Server,
112     &opts.config, &opts.log, |ics|
113   {
114     let global = config::InstanceConfigGlobal::from(&ics);
115     let ipif = Ipif::start(&global.ipif, None)?;
116
117     let make_service = hyper::service::make_service_fn(|_conn| async {
118       Ok::<_, Infallible>(hyper::service::service_fn(handle))
119     });
120
121     for addr in &global.addrs {
122       let addr = SocketAddr::new(*addr, global.port);
123       let server = hyper::Server::try_bind(&addr)
124         .context("bind")?
125         .http1_preserve_header_case(true)
126         .serve(make_service);
127       info!("listening on {}", &addr);
128       let task = tokio::task::spawn(server);
129       hservers.push(task);
130     }
131
132     Ok((global, ipif))
133   });
134
135   let x = future::select_all(&mut hservers).await;
136   error!("xxx hserver {:?}", &x);
137
138   ipif.quitting(None).await;
139
140   dbg!(ics, global);
141 }