use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
pub type Seen = (String, Option<String>);
pub struct Server {
pub host: String,
seen: Arc<Mutex<Vec<Seen>>>,
stop: Arc<AtomicBool>,
thread: Option<JoinHandle<()>>,
}
pub fn basic(user: &str, password: &str) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let bytes = format!("{user}:{password}").into_bytes();
let mut out = String::from("Basic ");
for chunk in bytes.chunks(3) {
let n = chunk
.iter()
.enumerate()
.fold(0u32, |acc, (i, b)| acc | (u32::from(*b) << (16 - 8 * i)));
for i in 0..4 {
if i <= chunk.len() {
out.push(char::from(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize]));
} else {
out.push('=');
}
}
}
out
}
fn handle(
stream: &TcpStream,
routes: &HashMap<String, Vec<u8>>,
want: Option<&str>,
seen: &Mutex<Vec<Seen>>,
) {
let mut reader = BufReader::new(stream);
let mut line = String::new();
let mut auth = None;
if reader.read_line(&mut line).is_err() {
return;
}
let path = line.split_whitespace().nth(1).unwrap_or("/").to_owned();
loop {
let mut header = String::new();
if reader.read_line(&mut header).unwrap_or(0) <= 2 {
break;
}
if let Some((name, value)) = header.trim_end().split_once(':')
&& name.eq_ignore_ascii_case("authorization")
{
auth = Some(value.trim().to_owned());
}
}
seen.lock()
.expect("seen lock")
.push((path.clone(), auth.clone()));
let response = match routes.get(&path) {
Some(body) if want.is_none() || want == auth.as_deref() => {
let head = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);
[head.into_bytes(), body.clone()].concat()
}
Some(_) => b"HTTP/1.1 401 Unauthorized\r\nWWW-Authenticate: Basic realm=\"stub\"\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
None => b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_vec(),
};
let mut stream = stream;
stream.write_all(&response).expect("write response");
}
impl Server {
pub fn start(routes: HashMap<String, Vec<u8>>, want: Option<String>) -> Self {
let listener = TcpListener::bind("127.0.0.1:0").expect("bind");
let host = listener.local_addr().expect("addr").to_string();
let seen = Arc::new(Mutex::new(Vec::new()));
let stop = Arc::new(AtomicBool::new(false));
let thread = {
let (seen, stop) = (Arc::clone(&seen), Arc::clone(&stop));
let (routes, want) = (Arc::new(routes), Arc::new(want));
thread::spawn(move || {
for stream in listener.incoming() {
if stop.load(Ordering::SeqCst) {
break;
}
let Ok(stream) = stream else { continue };
let (routes, want, seen) =
(Arc::clone(&routes), Arc::clone(&want), Arc::clone(&seen));
thread::spawn(move || handle(&stream, &routes, want.as_deref(), &seen));
}
})
};
Self {
host,
seen,
stop,
thread: Some(thread),
}
}
pub fn authorizations(&self, path: &str) -> Vec<Option<String>> {
self.seen
.lock()
.expect("seen lock")
.iter()
.filter(|(p, _)| p == path)
.map(|(_, a)| a.clone())
.collect()
}
}
impl Drop for Server {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
if TcpStream::connect(&self.host).is_ok()
&& let Some(thread) = self.thread.take()
{
thread.join().expect("server thread");
}
}
}