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