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