2 use std::io::prelude::*;
3 use std::path::{Path, PathBuf};
5 const DATA_PATH: &str = "/var/lib/voter";
6 const COOKIE_NAME: &[u8] = b"__Secure-id";
7 const COOKIE_LENGTH: usize = 12;
9 fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
10 let invalid_path = || cgi::text_response(404, "Invalid path");
12 return Err(cgi::text_response(404, "(This is the voting place. You should have been given a more specific URL for the specific thing you've been invited to vote on.)"));
14 if path.contains("..") || !path.starts_with("/") {
15 return Err(invalid_path());
17 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
20 .map_err(|_| invalid_path())?
21 .starts_with(DATA_PATH)
23 return Err(invalid_path());
26 return Err(invalid_path());
31 fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
32 // Expect exactly one cookie, exactly as we generate it.
35 .get(cgi::http::header::COOKIE)
36 .map(|c| c.as_bytes())
37 .and_then(|c| c.strip_prefix(COOKIE_NAME))
38 .and_then(|c| c.strip_prefix(b"="))
39 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
40 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
41 Err(cgi::text_response(400, "Invalid cookie"))
47 fn make_random_id() -> [u8; COOKIE_LENGTH] {
48 std::iter::from_fn(random)
50 (b'A'..=b'Z').contains(c) || (b'a'..=b'z').contains(c) || (b'0'..=b'9').contains(c)
58 fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
59 response.headers_mut().append(
60 cgi::http::header::SET_COOKIE,
61 cgi::http::header::HeaderValue::from_bytes(
66 b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
71 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
76 fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
77 let voter = get_voter(&request);
78 let cfile = std::fs::File::open(dir.join("candidates"))
79 .map_err(|_| cgi::text_response(503, "No candidates"))?;
80 let mut response = cgi::html_response(
82 std::iter::once(Ok("<html><body><table>".to_owned()))
84 std::io::BufReader::new(cfile)
86 .map(|rc| rc.map(|c| format!("<tr><td>{c}</td></tr>"))),
88 .chain(std::iter::once(Ok("</table></body></html>".to_owned())))
89 .collect::<std::io::Result<String>>()
90 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
93 response = set_cookie(response, request.uri().path())?
98 fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
99 let datum = [voter, b" ", vote, b"\n"].concat();
100 let vpath = dir.join("votes");
101 let vfile = std::fs::File::options()
105 let mut vlock = fd_lock::RwLock::new(vfile);
106 vlock.write()?.write(&datum)?;
110 fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
111 let body = request.body();
112 // Valid votes look like "0 foo" or "1 bar"
114 || (body[0] != b'0' && body[0] != b'1')
116 || body.contains(&b'\n')
118 return Err(cgi::text_response(415, "Invalid vote"));
120 write_vote(dir, &get_voter(&request)?, body)
121 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
122 Ok(cgi::text_response(200, "Vote recorded"))
125 fn strip_body(mut response: cgi::Response) -> cgi::Response {
126 response.body_mut().clear();
130 fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
131 let dir = validate_path(request.uri().path())?;
132 match request.method() {
133 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
134 &cgi::http::Method::GET => prompt_for_vote(dir, request),
135 &cgi::http::Method::PUT => record_vote(dir, request),
136 _ => Err(cgi::text_response(405, "Huh?")),
140 fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
141 match respond(request) {
142 Ok(result) => result,
147 cgi::cgi_main! { respond_or_report_error }