2 use std::collections::{HashMap, HashSet};
3 use std::io::prelude::*;
4 use std::path::{Path, PathBuf};
6 const DATA_PATH: &str = "/var/lib/voter";
7 const COOKIE_NAME: &[u8] = b"__Secure-id";
8 const COOKIE_LENGTH: usize = 12;
10 fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
11 let invalid_path = || cgi::text_response(404, "Invalid path");
13 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.)"));
15 if path.contains("..") || !path.starts_with("/") {
16 return Err(invalid_path());
18 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
21 .map_err(|_| invalid_path())?
22 .starts_with(DATA_PATH)
24 return Err(invalid_path());
27 return Err(invalid_path());
32 fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
33 // Expect exactly one cookie, exactly as we generate it.
36 .get(cgi::http::header::COOKIE)
37 .map(|c| c.as_bytes())
38 .and_then(|c| c.strip_prefix(COOKIE_NAME))
39 .and_then(|c| c.strip_prefix(b"="))
40 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
41 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
42 Err(cgi::text_response(400, "Invalid cookie"))
48 fn tally_votes(dir: PathBuf) -> std::io::Result<HashMap<String, HashSet<String>>> {
49 let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
50 let vfile = std::fs::File::open(dir.join("votes"))?;
51 for liner in std::io::BufReader::new(vfile).lines() {
53 if let Some((voter, datum)) = line.split_once(' ') {
54 if voter.len() == COOKIE_LENGTH {
55 if let Some((vote, candidate)) = datum.split_once(' ') {
57 if let Some(entry) = tally.get_mut(candidate) {
60 } else if vote == "1" {
62 .entry(candidate.to_owned())
64 .insert(voter.to_owned());
73 fn make_random_id() -> [u8; COOKIE_LENGTH] {
74 let mut id = [0; COOKIE_LENGTH];
75 for i in 0..COOKIE_LENGTH {
76 while !(b'A'..=b'Z').contains(&id[i])
77 && !(b'a'..=b'z').contains(&id[i])
78 && !(b'0'..=b'9').contains(&id[i])
86 fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
87 response.headers_mut().append(
88 cgi::http::header::SET_COOKIE,
89 cgi::http::header::HeaderValue::from_bytes(
94 b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
99 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
104 const HTML_HEADER: &str = "<!DOCTYPE html>
107 <meta charset=\"utf-8\">
110 th { font-size: 70%; text-align: left }
111 input { transform: scale(1.5) }
112 div { animation: 2s infinite linear spin }
114 from { transform:rotate(0) }
115 to { transform:rotate(1turn) }
119 window.onload = function() {
120 for (cb of document.getElementsByTagName('input')) {
121 cb.addEventListener('click', (function(cb) {
123 cb.style.display = 'none'
124 const spin = document.createElement('div')
125 spin.appendChild(document.createTextNode('⏳'))
126 cb.parentElement.insertBefore(spin, cb)
128 const req = new XMLHttpRequest()
129 req.addEventListener('load', function(e) {
130 cb.parentElement.removeChild(cb.previousElementSibling)
131 if (req.status == 200) {
132 cb.style.display = ''
133 const delta = cb.checked ? 1 : -1
134 const count_td = cb.parentElement.previousElementSibling
135 count_td.textContent = parseInt(count_td.textContent) + delta
137 cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
140 req.open('PUT', window.location.href)
141 req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
156 const HTML_FOOTER: &str = "
161 fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
164 .map(|supporters| supporters.contains(me))
168 fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
169 let voter = get_voter(&request);
170 let me = if let Ok(id) = voter {
171 std::str::from_utf8(id).ok()
176 tally_votes(dir.clone()).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
177 let cfile = std::fs::File::open(dir.join("candidates"))
178 .map_err(|_| cgi::text_response(503, "No candidates"))?;
179 let mut response = cgi::html_response(
181 std::iter::once(Ok(HTML_HEADER.to_owned()))
182 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
186 .map(|supporters| supporters.len())
188 let checked = if me.map(|me| supports(&tally, me, &c)).unwrap_or(false) {
196 <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
202 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
203 .collect::<std::io::Result<String>>()
204 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
207 response = set_cookie(response, request.uri().path())?
212 fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
213 let datum = [voter, b" ", vote, b"\n"].concat();
214 let vpath = dir.join("votes");
215 let vfile = std::fs::File::options()
219 let mut vlock = fd_lock::RwLock::new(vfile);
220 vlock.write()?.write(&datum)?;
224 fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
225 let body = request.body();
226 // Valid votes look like "0 foo" or "1 bar"
228 || (body[0] != b'0' && body[0] != b'1')
230 || body.contains(&b'\n')
232 return Err(cgi::text_response(415, "Invalid vote"));
234 write_vote(dir, &get_voter(&request)?, body)
235 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
236 Ok(cgi::text_response(200, "Vote recorded"))
239 fn strip_body(mut response: cgi::Response) -> cgi::Response {
240 response.body_mut().clear();
244 fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
245 let dir = validate_path(request.uri().path())?;
246 match request.method() {
247 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
248 &cgi::http::Method::GET => prompt_for_vote(dir, request),
249 &cgi::http::Method::PUT => record_vote(dir, request),
250 _ => Err(cgi::text_response(405, "Huh?")),
254 fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
255 match respond(request) {
256 Ok(result) => result,
261 cgi::cgi_main! { respond_or_report_error }