summaryrefslogtreecommitdiff
path: root/src/main.rs
blob: ffa18920912c07449798503febbe3f38a11b8961 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
pub mod argparse;

use std::collections::HashMap;
use std::io::{self, prelude::*};
use std::net::{IpAddr, TcpListener, TcpStream};
use std::process::ExitCode;
use std::sync::{
	Arc,
	atomic::{AtomicBool, Ordering},
};
use std::thread::sleep;
use std::time::Duration;

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Flag {
	Help,
	Version,
}

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
enum Param {
	Port,
	Address,
	Timeout,
	MaxConnections,
}

fn print_version() {
	println!(
		"{} v. {}",
		env!("CARGO_PKG_NAME"),
		env!("CARGO_PKG_VERSION")
	);
}

fn print_doc() {
	print_version();
	println!("{}", include_str!("../README.txt"));
}

#[derive(Debug)]
struct ConnectionSettings {
	timeout: u32,
	buffer: [u8; 1024],
}

const SLEEP_MS_PER_ROUND: u32 = 50;

impl ConnectionSettings {
	/// handle this connection as much as possible *without blocking*
	#[must_use]
	fn handle_connection(&mut self, addr: IpAddr, conn: &mut Connection) -> bool {
		let buffer = &mut self.buffer;
		conn.age_ms += SLEEP_MS_PER_ROUND;
		if conn.age_ms > self.timeout * 1000 {
			return false;
		}
		if conn.state < 4 {
			let n = match conn.stream.read(buffer) {
				Ok(n) => n,
				Err(e) if e.kind() == io::ErrorKind::WouldBlock => 0,
				Err(e) => {
					eprintln!("WARNING: error reading from connection: {e}");
					return false;
				}
			};
			for &c in &buffer[..n] {
				if c != b'\r' && c != b'\n' {
					continue;
				}
				let expected = if conn.state % 2 == 0 { b'\r' } else { b'\n' };
				if c == expected {
					conn.state += 1;
					if conn.state == 4 {
						break;
					}
				}
			}
		}
		if conn.state == 4 {
			// 90B is more than long enough for our response
			write!(
				&mut buffer[..90],
				"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n{addr}\n\0"
			)
			.expect("?? writing address to buffer failed??");
			let length = buffer[..90]
				.iter()
				.position(|&c| c == 0)
				.expect("?? no null byte even though we just wrote one??");
			match conn
				.stream
				.write(&buffer[usize::from(conn.written)..length])
			{
				Ok(n) => {
					conn.written += n as u8;
					if conn.written >= length as u8 {
						// hooray! done sending response
						return false;
					}
				}
				Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
					// keep connection around
				}
				Err(e) => {
					eprintln!("WARNING: error writing to connection: {e}");
					return false;
				}
			}
		}
		true
	}
}

#[derive(Debug)]
struct Connection {
	stream: TcpStream,
	/// rough time connection has been around in milliseconds
	age_ms: u32,
	/// number of characters out of \r\n\r\n (end of HTTP headers) that we have
	state: u8,
	/// number of characters of address which have been written
	written: u8,
}

fn try_main() -> Result<(), Box<dyn std::error::Error>> {
	let args = argparse::parse_args(
		&HashMap::from_iter([("--help", Flag::Help), ("--version", Flag::Version)]),
		&HashMap::from([
			("--port", Param::Port),
			("--address", Param::Address),
			("--timeout", Param::Timeout),
			("--max-connections", Param::MaxConnections),
		]),
	)?;
	if args.is_set(Flag::Help) {
		print_doc();
		return Ok(());
	}
	if args.is_set(Flag::Version) {
		print_version();
		return Ok(());
	}
	let addr = args.get(Param::Address).unwrap_or("0.0.0.0");
	let port = args.get(Param::Port).unwrap_or("80");
	let port = port
		.parse::<u16>()
		.map_err(|_| format!("Invalid port: {port}"))?;
	let timeout = args.get(Param::Timeout).unwrap_or("15");
	let timeout = timeout
		.parse::<u32>()
		.map_err(|_| format!("Invalid timeout: {timeout}"))?;
	let max_connections = args.get(Param::MaxConnections).unwrap_or("32");
	let max_connections = max_connections
		.parse::<u32>()
		.map_err(|_| format!("Invalid max connections: {max_connections}"))?;

	let listener = TcpListener::bind((addr, port))
		.map_err(|e| format!("Couldn't bind on {addr}:{port}: {e}"))?;

	let interrupted = Arc::new(AtomicBool::new(false));
	let handler_interrupted = interrupted.clone();
	if let Err(e) = ctrlc::set_handler(move || {
		handler_interrupted.store(true, Ordering::Relaxed);
	}) {
		eprintln!("Warning: Couldn't set SIGINT/TERM handler: {e}");
	}
	listener
		.set_nonblocking(true)
		.map_err(|e| format!("Couldn't set socket to non-blocking: {e}"))?;

	let was_interrupted = || interrupted.load(Ordering::Relaxed);
	let mut connections: HashMap<IpAddr, Connection> = HashMap::new();
	let mut settings = ConnectionSettings {
		timeout,
		buffer: [0; 1024],
	};

	'outer: while !was_interrupted() {
		sleep(Duration::from_millis(SLEEP_MS_PER_ROUND.into())); // don't busy loop
		while (connections.len() as u32) < max_connections {
			match listener.accept() {
				Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
					if was_interrupted() {
						break 'outer;
					}
					break;
				}
				Err(e) => eprintln!("Warning: accept() failed: {e}"),
				Ok((stream, source_addr)) => {
					if let Err(e) = stream.set_nonblocking(true) {
						eprintln!(
							"WARNING: dropping connection because set_nonblocking failed: {e}"
						);
						continue;
					}
					// if there was another connection from this address, it gets
					// unceremoniously dropped. too bad.
					connections.insert(
						source_addr.ip(),
						Connection {
							stream,
							age_ms: 0,
							written: 0,
							state: Default::default(),
						},
					);
				}
			}
		}
		connections.retain(|addr, conn| settings.handle_connection(*addr, conn));
	}
	Ok(())
}

fn main() -> ExitCode {
	if let Err(e) = try_main() {
		eprintln!("Error: {e}");
		return ExitCode::FAILURE;
	}
	ExitCode::SUCCESS
}