]> git.scottworley.com Git - voter/blob - src/main.rs
8c94be10909277a1c271c0ecd856e7f04b118730
[voter] / src / main.rs
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
7 use rand::prelude::*;
8 use std::collections::{HashMap, HashSet};
9 use std::io::prelude::*;
10 use std::path::{Path, PathBuf};
11
12 const DATA_PATH: &str = "/var/lib/voter";
13 const COOKIE_NAME: &[u8] = b"__Secure-id";
14 const COOKIE_LENGTH: usize = 12;
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
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(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"))
49 } else {
50 Ok(cookie)
51 }
52 }
53
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),
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());
74 }
75 }
76 }
77 }
78 }
79 Ok(tally)
80 }
81 }
82 }
83
84 fn valid_id_char(c: u8) -> bool {
85 c.is_ascii_alphanumeric()
86 }
87
88 fn make_random_id() -> [u8; COOKIE_LENGTH] {
89 let mut id = [0; COOKIE_LENGTH];
90 for c in &mut id {
91 while !valid_id_char(*c) {
92 *c = random();
93 }
94 }
95 id
96 }
97
98 fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
99 response.headers_mut().append(
100 cgi::http::header::SET_COOKIE,
101 cgi::http::header::HeaderValue::from_bytes(
102 &[
103 COOKIE_NAME,
104 b"=",
105 &make_random_id(),
106 b"; Secure; HttpOnly; SameSite=Strict; Max-Age=30000000; Path=",
107 path.as_bytes(),
108 ]
109 .concat(),
110 )
111 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
112 );
113 Ok(response)
114 }
115
116 const HTML_HEADER: &str = "<!DOCTYPE html>
117 <html>
118 <head>
119 <meta charset=\"utf-8\">
120 <title>Vote!</title>
121 <style>
122 th { font-size: 70%; text-align: left }
123 input { transform: scale(1.5) }
124 div { animation: 2s infinite linear spin }
125 @keyframes spin {
126 from { transform:rotate(0) }
127 to { transform:rotate(1turn) }
128 }
129 </style>
130 <script>
131 window.onload = function() {
132 for (cb of document.getElementsByTagName('input')) {
133 cb.addEventListener('click', (function(cb) {
134 return function() {
135 cb.style.display = 'none'
136 const spin = document.createElement('div')
137 spin.appendChild(document.createTextNode('⏳'))
138 cb.parentElement.insertBefore(spin, cb)
139
140 const req = new XMLHttpRequest()
141 req.addEventListener('load', function(e) {
142 cb.parentElement.removeChild(cb.previousElementSibling)
143 if (req.status == 200) {
144 cb.style.display = ''
145 const delta = cb.checked ? 1 : -1
146 const count_td = cb.parentElement.previousElementSibling
147 count_td.textContent = parseInt(count_td.textContent) + delta
148 } else {
149 cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
150 }
151 })
152 req.open('PUT', window.location.href)
153 req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
154 }
155 })(cb))
156 cb.disabled = false
157 }
158 }
159 function num_cmp(a, b) {
160 return parseInt(b.textContent) - parseInt(a.textContent)
161 }
162 function str_cmp(a, b) {
163 if (a.textContent < b.textContent) return -1
164 if (a.textContent > b.textContent) return 1
165 return 0
166 }
167 function checked_cmp(a, b) {
168 vs = [a, b].map(x => {
169 const v = x.children[0].checked + 0
170 return isNaN(v) ? -1 : v
171 })
172 return vs[1] - vs[0]
173 }
174 function sort_table(col, cmp) {
175 const rows = Array.from(document.getElementsByTagName('tr'))
176 rows.shift()
177 rows.sort((a, b) => cmp(a.children[col], b.children[col]))
178 for (row of rows) {
179 row.parentElement.appendChild(row)
180 }
181 }
182 </script>
183 </head>
184 <body>
185 <table>
186 <tr>
187 <th onclick='sort_table(0, num_cmp)'>Count</th>
188 <th onclick='sort_table(1, checked_cmp)'>Vote</th>
189 <th onclick='sort_table(2, str_cmp)'>Candidate</th>
190 </tr>";
191 const HTML_FOOTER: &str = "
192 </table>
193 </body>
194 </html>";
195
196 fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
197 tally
198 .get(candidate)
199 .map_or(false, |supporters| supporters.contains(me))
200 }
201
202 fn prompt_for_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
203 let voter = get_voter(request);
204 let me = if let Ok(id) = voter {
205 std::str::from_utf8(id).ok()
206 } else {
207 None
208 };
209 let tally = tally_votes(dir).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
210 let cfile = std::fs::File::open(dir.join("candidates"))
211 .map_err(|_| cgi::text_response(503, "No candidates"))?;
212 let mut response = cgi::html_response(
213 200,
214 std::iter::once(Ok(HTML_HEADER.to_owned()))
215 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
216 rc.map(|c| {
217 let count = tally.get(&c).map_or(0, std::collections::HashSet::len);
218 let checked = if me.map_or(false, |me| supports(&tally, me, &c)) {
219 "checked"
220 } else {
221 ""
222 };
223 format!(
224 "<tr>
225 <td>{count}</td>
226 <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
227 <td>{c}</td>
228 </tr>"
229 )
230 })
231 }))
232 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
233 .collect::<std::io::Result<String>>()
234 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
235 );
236 if voter.is_err() {
237 response = set_cookie(response, request.uri().path())?;
238 }
239 Ok(response)
240 }
241
242 fn write_vote(dir: &Path, 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_all(&datum)?;
251 Ok(())
252 }
253
254 fn record_vote(dir: &Path, request: &cgi::Request) -> Result<cgi::Response, cgi::Response> {
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
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() {
277 cgi::http::Method::HEAD => prompt_for_vote(&dir, request).map(strip_body),
278 cgi::http::Method::GET => prompt_for_vote(&dir, request),
279 cgi::http::Method::PUT => record_vote(&dir, request),
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 }
289 }
290
291 cgi::cgi_main! { respond_or_report_error }