]>
Commit | Line | Data |
---|---|---|
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 | 7 | use rand::prelude::*; |
75cfd491 | 8 | use std::collections::{HashMap, HashSet}; |
fbcdf3ed | 9 | use std::io::prelude::*; |
c8402f1c | 10 | use std::path::{Path, PathBuf}; |
d1df2e73 | 11 | |
c8402f1c | 12 | const DATA_PATH: &str = "/var/lib/voter"; |
fbcdf3ed | 13 | const COOKIE_NAME: &[u8] = b"__Secure-id"; |
ae9be1b6 | 14 | const COOKIE_LENGTH: usize = 12; |
c8402f1c SW |
15 | |
16 | fn 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 | } | |
21 | if path.contains("..") || !path.starts_with("/") { | |
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 |
38 | fn 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) | |
43 | .map(|c| c.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")) | |
49 | } else { | |
50 | Ok(cookie) | |
51 | } | |
52 | } | |
53 | ||
75cfd491 SW |
54 | fn tally_votes(dir: PathBuf) -> std::io::Result<HashMap<String, HashSet<String>>> { |
55 | let mut tally: HashMap<String, HashSet<String>> = HashMap::new(); | |
6f4c1824 SW |
56 | if let Ok(vfile) = std::fs::File::open(dir.join("votes")) { |
57 | for liner in std::io::BufReader::new(vfile).lines() { | |
58 | let line = liner?; | |
59 | if let Some((voter, datum)) = line.split_once(' ') { | |
60 | if voter.len() == COOKIE_LENGTH { | |
61 | if let Some((vote, candidate)) = datum.split_once(' ') { | |
62 | if vote == "0" { | |
63 | if let Some(entry) = tally.get_mut(candidate) { | |
64 | entry.remove(voter); | |
65 | } | |
66 | } else if vote == "1" { | |
67 | tally | |
68 | .entry(candidate.to_owned()) | |
69 | .or_default() | |
70 | .insert(voter.to_owned()); | |
75cfd491 | 71 | } |
75cfd491 SW |
72 | } |
73 | } | |
74 | } | |
75 | } | |
76 | } | |
77 | Ok(tally) | |
78 | } | |
79 | ||
dd0a1246 | 80 | fn make_random_id() -> [u8; COOKIE_LENGTH] { |
5a0934fa SW |
81 | let mut id = [0; COOKIE_LENGTH]; |
82 | for i in 0..COOKIE_LENGTH { | |
83 | while !(b'A'..=b'Z').contains(&id[i]) | |
84 | && !(b'a'..=b'z').contains(&id[i]) | |
85 | && !(b'0'..=b'9').contains(&id[i]) | |
86 | { | |
87 | id[i] = random() | |
88 | } | |
89 | } | |
90 | id | |
dd0a1246 SW |
91 | } |
92 | ||
93 | fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> { | |
94 | response.headers_mut().append( | |
95 | cgi::http::header::SET_COOKIE, | |
96 | cgi::http::header::HeaderValue::from_bytes( | |
97 | &[ | |
98 | COOKIE_NAME, | |
99 | b"=", | |
100 | &make_random_id(), | |
cf23c41d | 101 | b"; Secure; HttpOnly; SameSite=Strict; Max-Age=30000000; Path=", |
dd0a1246 SW |
102 | path.as_bytes(), |
103 | ] | |
104 | .concat(), | |
105 | ) | |
106 | .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?, | |
107 | ); | |
108 | Ok(response) | |
109 | } | |
110 | ||
3a28e771 | 111 | const HTML_HEADER: &str = "<!DOCTYPE html> |
f5e90a7e SW |
112 | <html> |
113 | <head> | |
3a28e771 | 114 | <meta charset=\"utf-8\"> |
9e49b3f0 | 115 | <title>Vote!</title> |
f5e90a7e | 116 | <style> |
3a49148b | 117 | th { font-size: 70%; text-align: left } |
9d82c13f | 118 | input { transform: scale(1.5) } |
95432069 SW |
119 | div { animation: 2s infinite linear spin } |
120 | @keyframes spin { | |
121 | from { transform:rotate(0) } | |
122 | to { transform:rotate(1turn) } | |
123 | } | |
f5e90a7e | 124 | </style> |
9d82c13f SW |
125 | <script> |
126 | window.onload = function() { | |
127 | for (cb of document.getElementsByTagName('input')) { | |
95432069 SW |
128 | cb.addEventListener('click', (function(cb) { |
129 | return function() { | |
130 | cb.style.display = 'none' | |
131 | const spin = document.createElement('div') | |
132 | spin.appendChild(document.createTextNode('⏳')) | |
133 | cb.parentElement.insertBefore(spin, cb) | |
f724d95f SW |
134 | |
135 | const req = new XMLHttpRequest() | |
136 | req.addEventListener('load', function(e) { | |
137 | cb.parentElement.removeChild(cb.previousElementSibling) | |
138 | if (req.status == 200) { | |
139 | cb.style.display = '' | |
6ae24e6d SW |
140 | const delta = cb.checked ? 1 : -1 |
141 | const count_td = cb.parentElement.previousElementSibling | |
142 | count_td.textContent = parseInt(count_td.textContent) + delta | |
f724d95f SW |
143 | } else { |
144 | cb.parentElement.insertBefore(document.createTextNode('❗'), cb) | |
145 | } | |
146 | }) | |
147 | req.open('PUT', window.location.href) | |
75cfd491 | 148 | req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML) |
95432069 SW |
149 | } |
150 | })(cb)) | |
9d82c13f SW |
151 | cb.disabled = false |
152 | } | |
153 | } | |
ea1ace7d SW |
154 | function num_cmp(a, b) { |
155 | return parseInt(b.textContent) - parseInt(a.textContent) | |
156 | } | |
157 | function str_cmp(a, b) { | |
158 | if (a.textContent < b.textContent) return -1 | |
159 | if (a.textContent > b.textContent) return 1 | |
160 | return 0 | |
161 | } | |
162 | function checked_cmp(a, b) { | |
163 | vs = [a, b].map(x => { | |
164 | const v = x.children[0].checked + 0 | |
165 | return isNaN(v) ? -1 : v | |
166 | }) | |
167 | return vs[1] - vs[0] | |
168 | } | |
169 | function sort_table(col, cmp) { | |
170 | const rows = Array.from(document.getElementsByTagName('tr')) | |
171 | rows.shift() | |
172 | rows.sort((a, b) => cmp(a.children[col], b.children[col])) | |
173 | for (row of rows) { | |
174 | row.parentElement.appendChild(row) | |
175 | } | |
176 | } | |
9d82c13f | 177 | </script> |
f5e90a7e SW |
178 | </head> |
179 | <body> | |
3a49148b SW |
180 | <table> |
181 | <tr> | |
ea1ace7d SW |
182 | <th onclick='sort_table(0, num_cmp)'>Count</th> |
183 | <th onclick='sort_table(1, checked_cmp)'>Vote</th> | |
184 | <th onclick='sort_table(2, str_cmp)'>Candidate</th> | |
3a49148b | 185 | </tr>"; |
f5e90a7e SW |
186 | const HTML_FOOTER: &str = " |
187 | </table> | |
188 | </body> | |
189 | </html>"; | |
190 | ||
75cfd491 SW |
191 | fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool { |
192 | tally | |
193 | .get(candidate) | |
194 | .map(|supporters| supporters.contains(me)) | |
195 | .unwrap_or(false) | |
196 | } | |
197 | ||
c8402f1c | 198 | fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> { |
dd0a1246 | 199 | let voter = get_voter(&request); |
75cfd491 SW |
200 | let me = if let Ok(id) = voter { |
201 | std::str::from_utf8(id).ok() | |
202 | } else { | |
203 | None | |
204 | }; | |
205 | let tally = | |
206 | tally_votes(dir.clone()).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?; | |
381eeda5 SW |
207 | let cfile = std::fs::File::open(dir.join("candidates")) |
208 | .map_err(|_| cgi::text_response(503, "No candidates"))?; | |
209 | let mut response = cgi::html_response( | |
210 | 200, | |
f5e90a7e SW |
211 | std::iter::once(Ok(HTML_HEADER.to_owned())) |
212 | .chain(std::io::BufReader::new(cfile).lines().map(|rc| { | |
9d82c13f | 213 | rc.map(|c| { |
05232d49 SW |
214 | let count = tally |
215 | .get(&c) | |
216 | .map(|supporters| supporters.len()) | |
217 | .unwrap_or(0); | |
75cfd491 SW |
218 | let checked = if me.map(|me| supports(&tally, me, &c)).unwrap_or(false) { |
219 | "checked" | |
220 | } else { | |
221 | "" | |
222 | }; | |
223 | format!( | |
224 | "<tr> | |
05232d49 | 225 | <td>{count}</td> |
75cfd491 SW |
226 | <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td> |
227 | <td>{c}</td> | |
228 | </tr>" | |
229 | ) | |
9d82c13f | 230 | }) |
f5e90a7e SW |
231 | })) |
232 | .chain(std::iter::once(Ok(HTML_FOOTER.to_owned()))) | |
381eeda5 SW |
233 | .collect::<std::io::Result<String>>() |
234 | .map_err(|_| cgi::text_response(503, "Missing candidates"))?, | |
235 | ); | |
dd0a1246 SW |
236 | if voter.is_err() { |
237 | response = set_cookie(response, request.uri().path())? | |
238 | } | |
239 | Ok(response) | |
c8402f1c SW |
240 | } |
241 | ||
fbcdf3ed SW |
242 | fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> { |
243 | let datum = [voter, b" ", vote, b"\n"].concat(); | |
244 | let vpath = dir.join("votes"); | |
245 | let vfile = std::fs::File::options() | |
246 | .append(true) | |
247 | .create(true) | |
248 | .open(vpath)?; | |
249 | let mut vlock = fd_lock::RwLock::new(vfile); | |
250 | vlock.write()?.write(&datum)?; | |
251 | Ok(()) | |
252 | } | |
253 | ||
c8402f1c | 254 | fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> { |
fbcdf3ed SW |
255 | let body = request.body(); |
256 | // Valid votes look like "0 foo" or "1 bar" | |
257 | if body.len() < 3 | |
258 | || (body[0] != b'0' && body[0] != b'1') | |
259 | || body[1] != b' ' | |
260 | || body.contains(&b'\n') | |
261 | { | |
262 | return Err(cgi::text_response(415, "Invalid vote")); | |
263 | } | |
264 | write_vote(dir, &get_voter(&request)?, body) | |
265 | .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?; | |
266 | Ok(cgi::text_response(200, "Vote recorded")) | |
267 | } | |
268 | ||
269 | fn strip_body(mut response: cgi::Response) -> cgi::Response { | |
270 | response.body_mut().clear(); | |
271 | response | |
c8402f1c SW |
272 | } |
273 | ||
274 | fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> { | |
275 | let dir = validate_path(request.uri().path())?; | |
276 | match request.method() { | |
fbcdf3ed | 277 | &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body), |
c8402f1c | 278 | &cgi::http::Method::GET => prompt_for_vote(dir, request), |
fbcdf3ed | 279 | &cgi::http::Method::PUT => record_vote(dir, request), |
c8402f1c SW |
280 | _ => Err(cgi::text_response(405, "Huh?")), |
281 | } | |
282 | } | |
283 | ||
284 | fn respond_or_report_error(request: cgi::Request) -> cgi::Response { | |
285 | match respond(request) { | |
286 | Ok(result) => result, | |
287 | Err(error) => error, | |
288 | } | |
d1df2e73 SW |
289 | } |
290 | ||
c8402f1c | 291 | cgi::cgi_main! { respond_or_report_error } |