]> git.scottworley.com Git - voter/blame - src/main.rs
Eliminated candidates UI
[voter] / src / main.rs
CommitLineData
302f399b
SW
1// voter: A simple CGI vote recorder, approval-voting-style
2//
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.
6
dd0a1246 7use rand::prelude::*;
75cfd491 8use std::collections::{HashMap, HashSet};
fbcdf3ed 9use std::io::prelude::*;
c8402f1c 10use std::path::{Path, PathBuf};
d1df2e73 11
c8402f1c 12const DATA_PATH: &str = "/var/lib/voter";
fbcdf3ed 13const COOKIE_NAME: &[u8] = b"__Secure-id";
ae9be1b6 14const COOKIE_LENGTH: usize = 12;
c8402f1c
SW
15
16fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
17 let invalid_path = || cgi::text_response(404, "Invalid path");
18 if 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.)"));
20 }
81333308 21 if path.contains("..") || !path.starts_with('/') {
c8402f1c
SW
22 return Err(invalid_path());
23 }
24 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
25 if !dir
26 .canonicalize()
27 .map_err(|_| invalid_path())?
28 .starts_with(DATA_PATH)
29 {
30 return Err(invalid_path());
31 }
32 if !dir.is_dir() {
33 return Err(invalid_path());
34 }
35 Ok(dir)
36}
37
fbcdf3ed
SW
38fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
39 // Expect exactly one cookie, exactly as we generate it.
40 let cookie = request
41 .headers()
42 .get(cgi::http::header::COOKIE)
518c108c 43 .map(cgi::http::HeaderValue::as_bytes)
fbcdf3ed
SW
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"))
49 } else {
50 Ok(cookie)
51 }
52}
53
971d76c7 54fn tally_votes(dir: &Path) -> std::io::Result<HashMap<String, HashSet<String>>> {
75cfd491 55 let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
8b8f8d14
SW
56 match std::fs::File::open(dir.to_owned().join("votes")) {
57 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(tally),
58 Err(e) => Err(e),
59 Ok(vfile) => {
60 for liner in std::io::BufReader::new(vfile).lines() {
61 let line = liner?;
62 if let Some((voter, datum)) = line.split_once(' ') {
63 if voter.len() == COOKIE_LENGTH {
64 if let Some((vote, candidate)) = datum.split_once(' ') {
65 if vote == "0" {
66 if let Some(entry) = tally.get_mut(candidate) {
67 entry.remove(voter);
68 }
69 } else if vote == "1" {
70 tally
71 .entry(candidate.to_owned())
72 .or_default()
73 .insert(voter.to_owned());
6f4c1824 74 }
75cfd491 75 }
75cfd491
SW
76 }
77 }
78 }
8b8f8d14 79 Ok(tally)
75cfd491
SW
80 }
81 }
75cfd491
SW
82}
83
82977580
SW
84fn 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()),
87 Err(e) => Err(e),
88 Ok(elimfile) => std::io::BufReader::new(elimfile).lines().collect(),
89 }
90}
91
971d76c7 92fn valid_id_char(c: u8) -> bool {
a5a841de 93 c.is_ascii_alphanumeric()
81333308
SW
94}
95
dd0a1246 96fn make_random_id() -> [u8; COOKIE_LENGTH] {
5a0934fa 97 let mut id = [0; COOKIE_LENGTH];
518c108c 98 for c in &mut id {
971d76c7
SW
99 while !valid_id_char(*c) {
100 *c = random();
5a0934fa
SW
101 }
102 }
103 id
dd0a1246
SW
104}
105
106fn 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(
110 &[
111 COOKIE_NAME,
112 b"=",
113 &make_random_id(),
cf23c41d 114 b"; Secure; HttpOnly; SameSite=Strict; Max-Age=30000000; Path=",
dd0a1246
SW
115 path.as_bytes(),
116 ]
117 .concat(),
118 )
119 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
120 );
121 Ok(response)
122}
123
3a28e771 124const HTML_HEADER: &str = "<!DOCTYPE html>
f5e90a7e
SW
125<html>
126 <head>
3a28e771 127 <meta charset=\"utf-8\">
9e49b3f0 128 <title>Vote!</title>
f5e90a7e 129 <style>
3a49148b 130 th { font-size: 70%; text-align: left }
9d82c13f 131 input { transform: scale(1.5) }
82977580 132 .eliminated { text-decoration: line-through; }
95432069
SW
133 div { animation: 2s infinite linear spin }
134 @keyframes spin {
135 from { transform:rotate(0) }
136 to { transform:rotate(1turn) }
137 }
f5e90a7e 138 </style>
9d82c13f
SW
139 <script>
140 window.onload = function() {
141 for (cb of document.getElementsByTagName('input')) {
82977580
SW
142 if (cb.parentElement.parentElement.classList.contains('eliminated'))
143 continue;
95432069
SW
144 cb.addEventListener('click', (function(cb) {
145 return function() {
146 cb.style.display = 'none'
147 const spin = document.createElement('div')
148 spin.appendChild(document.createTextNode('⏳'))
149 cb.parentElement.insertBefore(spin, cb)
f724d95f
SW
150
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 = ''
6ae24e6d
SW
156 const delta = cb.checked ? 1 : -1
157 const count_td = cb.parentElement.previousElementSibling
158 count_td.textContent = parseInt(count_td.textContent) + delta
f724d95f
SW
159 } else {
160 cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
161 }
162 })
163 req.open('PUT', window.location.href)
75cfd491 164 req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
95432069
SW
165 }
166 })(cb))
9d82c13f
SW
167 cb.disabled = false
168 }
169 }
ea1ace7d
SW
170 function num_cmp(a, b) {
171 return parseInt(b.textContent) - parseInt(a.textContent)
172 }
173 function str_cmp(a, b) {
174 if (a.textContent < b.textContent) return -1
175 if (a.textContent > b.textContent) return 1
176 return 0
177 }
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
182 })
183 return vs[1] - vs[0]
184 }
185 function sort_table(col, cmp) {
186 const rows = Array.from(document.getElementsByTagName('tr'))
187 rows.shift()
188 rows.sort((a, b) => cmp(a.children[col], b.children[col]))
189 for (row of rows) {
190 row.parentElement.appendChild(row)
191 }
192 }
9d82c13f 193 </script>
f5e90a7e
SW
194 </head>
195 <body>
3a49148b
SW
196 <table>
197 <tr>
ea1ace7d
SW
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>
3a49148b 201 </tr>";
f5e90a7e
SW
202const HTML_FOOTER: &str = "
203 </table>
204 </body>
205</html>";
206
75cfd491
SW
207fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
208 tally
209 .get(candidate)
518c108c 210 .map_or(false, |supporters| supporters.contains(me))
75cfd491
SW
211}
212
971d76c7
SW
213fn prompt_for_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
214 let voter = get_voter(request);
75cfd491
SW
215 let me = if let Ok(id) = voter {
216 std::str::from_utf8(id).ok()
217 } else {
218 None
219 };
971d76c7 220 let tally = tally_votes(dir).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
82977580
SW
221 let elim =
222 read_elim_list(dir).map_err(|_| cgi::text_response(503, "Couldn't read eliminations"))?;
381eeda5
SW
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(
226 200,
f5e90a7e
SW
227 std::iter::once(Ok(HTML_HEADER.to_owned()))
228 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
9d82c13f 229 rc.map(|c| {
518c108c
SW
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)) {
75cfd491
SW
232 "checked"
233 } else {
234 ""
235 };
82977580 236 let class = if elim.contains(&c) { "eliminated" } else { "" };
75cfd491 237 format!(
82977580 238 "<tr class=\"{class}\">
05232d49 239 <td>{count}</td>
75cfd491
SW
240 <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
241 <td>{c}</td>
242 </tr>"
243 )
9d82c13f 244 })
f5e90a7e
SW
245 }))
246 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
381eeda5
SW
247 .collect::<std::io::Result<String>>()
248 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
249 );
dd0a1246 250 if voter.is_err() {
971d76c7 251 response = set_cookie(response, request.uri().path())?;
dd0a1246
SW
252 }
253 Ok(response)
c8402f1c
SW
254}
255
971d76c7 256fn write_vote(dir: &Path, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
fbcdf3ed
SW
257 let datum = [voter, b" ", vote, b"\n"].concat();
258 let vpath = dir.join("votes");
259 let vfile = std::fs::File::options()
260 .append(true)
261 .create(true)
262 .open(vpath)?;
263 let mut vlock = fd_lock::RwLock::new(vfile);
81333308 264 vlock.write()?.write_all(&datum)?;
fbcdf3ed
SW
265 Ok(())
266}
267
971d76c7 268fn record_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
fbcdf3ed
SW
269 let body = request.body();
270 // Valid votes look like "0 foo" or "1 bar"
271 if body.len() < 3
272 || (body[0] != b'0' && body[0] != b'1')
273 || body[1] != b' '
274 || body.contains(&b'\n')
275 {
276 return Err(cgi::text_response(415, "Invalid vote"));
277 }
971d76c7 278 write_vote(dir, get_voter(request)?, body)
fbcdf3ed
SW
279 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
280 Ok(cgi::text_response(200, "Vote recorded"))
281}
282
283fn strip_body(mut response: cgi::Response) -> cgi::Response {
284 response.body_mut().clear();
285 response
c8402f1c
SW
286}
287
971d76c7 288fn respond(request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
c8402f1c 289 let dir = validate_path(request.uri().path())?;
81333308 290 match *request.method() {
971d76c7
SW
291 cgi::http::Method::HEAD => prompt_for_vote(&dir, request).map(strip_body),
292 cgi::http::Method::GET => prompt_for_vote(&dir, request),
293 cgi::http::Method::PUT => record_vote(&dir, request),
c8402f1c
SW
294 _ => Err(cgi::text_response(405, "Huh?")),
295 }
296}
297
298fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
971d76c7 299 match respond(&request) {
c8402f1c
SW
300 Ok(result) => result,
301 Err(error) => error,
302 }
d1df2e73
SW
303}
304
c8402f1c 305cgi::cgi_main! { respond_or_report_error }