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