1 // voter: A simple CGI vote recorder, approval-voting-style
3 // This program is free software: you can redistribute it and/or modify it
4 // under the terms of the GNU Affero General Public License as published
5 // by the Free Software Foundation, version 3.
8 use std::collections::{HashMap, HashSet};
9 use std::io::prelude::*;
10 use std::path::{Path, PathBuf};
12 const DATA_PATH: &str = "/var/lib/voter";
13 const COOKIE_NAME: &[u8] = b"__Secure-id";
14 const COOKIE_LENGTH: usize = 12;
16 fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
17 let invalid_path = || cgi::text_response(404, "Invalid path");
19 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.)"));
21 if path.contains("..") || !path.starts_with('/') {
22 return Err(invalid_path());
24 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
27 .map_err(|_| invalid_path())?
28 .starts_with(DATA_PATH)
30 return Err(invalid_path());
33 return Err(invalid_path());
38 fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
39 // Expect exactly one cookie, exactly as we generate it.
42 .get(cgi::http::header::COOKIE)
43 .map(cgi::http::HeaderValue::as_bytes)
44 .and_then(|c| c.strip_prefix(COOKIE_NAME))
45 .and_then(|c| c.strip_prefix(b"="))
46 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
47 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
48 Err(cgi::text_response(400, "Invalid cookie"))
54 fn tally_votes(dir: &Path) -> std::io::Result<HashMap<String, HashSet<String>>> {
55 let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
56 match std::fs::File::open(dir.to_owned().join("votes")) {
57 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(tally),
60 for liner in std::io::BufReader::new(vfile).lines() {
62 if let Some((voter, datum)) = line.split_once(' ') {
63 if voter.len() == COOKIE_LENGTH {
64 if let Some((vote, candidate)) = datum.split_once(' ') {
66 if let Some(entry) = tally.get_mut(candidate) {
69 } else if vote == "1" {
71 .entry(candidate.to_owned())
73 .insert(voter.to_owned());
84 fn read_elim_list(dir: &Path) -> std::io::Result<HashSet<String>> {
85 match std::fs::File::open(dir.join("eliminated")) {
86 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(HashSet::new()),
88 Ok(elimfile) => std::io::BufReader::new(elimfile).lines().collect(),
92 fn valid_id_char(c: u8) -> bool {
93 c.is_ascii_alphanumeric()
96 fn make_random_id() -> [u8; COOKIE_LENGTH] {
97 let mut id = [0; COOKIE_LENGTH];
99 while !valid_id_char(*c) {
106 fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
107 response.headers_mut().append(
108 cgi::http::header::SET_COOKIE,
109 cgi::http::header::HeaderValue::from_bytes(
114 b"; Secure; HttpOnly; SameSite=Strict; Max-Age=30000000; Path=",
119 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
124 const HTML_HEADER: &str = "<!DOCTYPE html>
127 <meta charset=\"utf-8\">
130 th { font-size: 70%; text-align: left }
131 input { transform: scale(1.5) }
132 .eliminated { text-decoration: line-through; }
133 div { animation: 2s infinite linear spin }
135 from { transform:rotate(0) }
136 to { transform:rotate(1turn) }
140 window.onload = function() {
141 for (cb of document.getElementsByTagName('input')) {
142 if (cb.parentElement.parentElement.classList.contains('eliminated'))
144 cb.addEventListener('click', (function(cb) {
146 cb.style.display = 'none'
147 const spin = document.createElement('div')
148 spin.appendChild(document.createTextNode('⏳'))
149 cb.parentElement.insertBefore(spin, cb)
151 const req = new XMLHttpRequest()
152 req.addEventListener('load', function(e) {
153 cb.parentElement.removeChild(cb.previousElementSibling)
154 if (req.status == 200) {
155 cb.style.display = ''
156 const delta = cb.checked ? 1 : -1
157 const count_td = cb.parentElement.previousElementSibling
158 count_td.textContent = parseInt(count_td.textContent) + delta
160 cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
163 req.open('PUT', window.location.href)
164 req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
170 function num_cmp(a, b) {
171 return parseInt(b.textContent) - parseInt(a.textContent)
173 function str_cmp(a, b) {
174 if (a.textContent < b.textContent) return -1
175 if (a.textContent > b.textContent) return 1
178 function checked_cmp(a, b) {
179 vs = [a, b].map(x => {
180 const v = x.children[0].checked + 0
181 return isNaN(v) ? -1 : v
185 function sort_table(col, cmp) {
186 const rows = Array.from(document.getElementsByTagName('tr'))
188 rows.sort((a, b) => cmp(a.children[col], b.children[col]))
190 row.parentElement.appendChild(row)
198 <th onclick='sort_table(0, num_cmp)'>Count</th>
199 <th onclick='sort_table(1, checked_cmp)'>Vote</th>
200 <th onclick='sort_table(2, str_cmp)'>Candidate</th>
202 const HTML_FOOTER: &str = "
207 fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
210 .map_or(false, |supporters| supporters.contains(me))
213 fn prompt_for_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
214 let voter = get_voter(request);
215 let me = if let Ok(id) = voter {
216 std::str::from_utf8(id).ok()
220 let tally = tally_votes(dir).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
222 read_elim_list(dir).map_err(|_| cgi::text_response(503, "Couldn't read eliminations"))?;
223 let cfile = std::fs::File::open(dir.join("candidates"))
224 .map_err(|_| cgi::text_response(503, "No candidates"))?;
225 let mut response = cgi::html_response(
227 std::iter::once(Ok(HTML_HEADER.to_owned()))
228 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
230 let count = tally.get(&c).map_or(0, std::collections::HashSet::len);
231 let checked = if me.map_or(false, |me| supports(&tally, me, &c)) {
236 let class = if elim.contains(&c) { "eliminated" } else { "" };
238 "<tr class=\"{class}\">
240 <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
246 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
247 .collect::<std::io::Result<String>>()
248 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
251 response = set_cookie(response, request.uri().path())?;
256 fn write_vote(dir: &Path, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
257 let datum = [voter, b" ", vote, b"\n"].concat();
258 let vpath = dir.join("votes");
259 let vfile = std::fs::File::options()
263 let mut vlock = fd_lock::RwLock::new(vfile);
264 vlock.write()?.write_all(&datum)?;
268 fn record_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
269 let body = request.body();
270 // Valid votes look like "0 foo" or "1 bar"
272 || (body[0] != b'0' && body[0] != b'1')
274 || body.contains(&b'\n')
276 return Err(cgi::text_response(415, "Invalid vote"));
279 read_elim_list(dir).map_err(|_| cgi::text_response(503, "Couldn't read eliminations"))?;
281 std::str::from_utf8(&body[2..]).map_err(|_| cgi::text_response(415, "Vote not UTF-8"))?,
283 return Err(cgi::text_response(403, "Candidate eliminated"));
285 write_vote(dir, get_voter(request)?, body)
286 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
287 Ok(cgi::text_response(200, "Vote recorded"))
290 fn strip_body(mut response: cgi::Response) -> cgi::Response {
291 response.body_mut().clear();
295 fn respond(request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
296 let dir = validate_path(request.uri().path())?;
297 match *request.method() {
298 cgi::http::Method::HEAD => prompt_for_vote(&dir, request).map(strip_body),
299 cgi::http::Method::GET => prompt_for_vote(&dir, request),
300 cgi::http::Method::PUT => record_vote(&dir, request),
301 _ => Err(cgi::text_response(405, "Huh?")),
305 fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
306 match respond(&request) {
307 Ok(result) => result,
312 cgi::cgi_main! { respond_or_report_error }