]> git.scottworley.com Git - voter/blame - src/main.rs
Preserve visibility of users' votes across page refresh
[voter] / src / main.rs
CommitLineData
dd0a1246 1use rand::prelude::*;
75cfd491 2use std::collections::{HashMap, HashSet};
fbcdf3ed 3use std::io::prelude::*;
c8402f1c 4use std::path::{Path, PathBuf};
d1df2e73 5
c8402f1c 6const DATA_PATH: &str = "/var/lib/voter";
fbcdf3ed 7const COOKIE_NAME: &[u8] = b"__Secure-id";
ae9be1b6 8const COOKIE_LENGTH: usize = 12;
c8402f1c
SW
9
10fn 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
32fn 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
48fn tally_votes(dir: PathBuf) -> std::io::Result<HashMap<String, HashSet<String>>> {
49 let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
50 let 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());
65 }
66 }
67 }
68 }
69 }
70 Ok(tally)
71}
72
dd0a1246 73fn make_random_id() -> [u8; COOKIE_LENGTH] {
5a0934fa
SW
74 let mut id = [0; COOKIE_LENGTH];
75 for i in 0..COOKIE_LENGTH {
76 while !(b'A'..=b'Z').contains(&id[i])
77 && !(b'a'..=b'z').contains(&id[i])
78 && !(b'0'..=b'9').contains(&id[i])
79 {
80 id[i] = random()
81 }
82 }
83 id
dd0a1246
SW
84}
85
86fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
87 response.headers_mut().append(
88 cgi::http::header::SET_COOKIE,
89 cgi::http::header::HeaderValue::from_bytes(
90 &[
91 COOKIE_NAME,
92 b"=",
93 &make_random_id(),
94 b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
95 path.as_bytes(),
96 ]
97 .concat(),
98 )
99 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
100 );
101 Ok(response)
102}
103
3a28e771 104const HTML_HEADER: &str = "<!DOCTYPE html>
f5e90a7e
SW
105<html>
106 <head>
3a28e771 107 <meta charset=\"utf-8\">
9e49b3f0 108 <title>Vote!</title>
f5e90a7e 109 <style>
9d82c13f 110 input { transform: scale(1.5) }
95432069
SW
111 div { animation: 2s infinite linear spin }
112 @keyframes spin {
113 from { transform:rotate(0) }
114 to { transform:rotate(1turn) }
115 }
f5e90a7e 116 </style>
9d82c13f
SW
117 <script>
118 window.onload = function() {
119 for (cb of document.getElementsByTagName('input')) {
95432069
SW
120 cb.addEventListener('click', (function(cb) {
121 return function() {
122 cb.style.display = 'none'
123 const spin = document.createElement('div')
124 spin.appendChild(document.createTextNode('⏳'))
125 cb.parentElement.insertBefore(spin, cb)
f724d95f
SW
126
127 const req = new XMLHttpRequest()
128 req.addEventListener('load', function(e) {
129 cb.parentElement.removeChild(cb.previousElementSibling)
130 if (req.status == 200) {
131 cb.style.display = ''
132 } else {
133 cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
134 }
135 })
136 req.open('PUT', window.location.href)
75cfd491 137 req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
95432069
SW
138 }
139 })(cb))
9d82c13f
SW
140 cb.disabled = false
141 }
142 }
143 </script>
f5e90a7e
SW
144 </head>
145 <body>
146 <table>";
147const HTML_FOOTER: &str = "
148 </table>
149 </body>
150</html>";
151
75cfd491
SW
152fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
153 tally
154 .get(candidate)
155 .map(|supporters| supporters.contains(me))
156 .unwrap_or(false)
157}
158
c8402f1c 159fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
dd0a1246 160 let voter = get_voter(&request);
75cfd491
SW
161 let me = if let Ok(id) = voter {
162 std::str::from_utf8(id).ok()
163 } else {
164 None
165 };
166 let tally =
167 tally_votes(dir.clone()).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
381eeda5
SW
168 let cfile = std::fs::File::open(dir.join("candidates"))
169 .map_err(|_| cgi::text_response(503, "No candidates"))?;
170 let mut response = cgi::html_response(
171 200,
f5e90a7e
SW
172 std::iter::once(Ok(HTML_HEADER.to_owned()))
173 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
9d82c13f 174 rc.map(|c| {
75cfd491
SW
175 let checked = if me.map(|me| supports(&tally, me, &c)).unwrap_or(false) {
176 "checked"
177 } else {
178 ""
179 };
180 format!(
181 "<tr>
182 <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
183 <td>{c}</td>
184 </tr>"
185 )
9d82c13f 186 })
f5e90a7e
SW
187 }))
188 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
381eeda5
SW
189 .collect::<std::io::Result<String>>()
190 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
191 );
dd0a1246
SW
192 if voter.is_err() {
193 response = set_cookie(response, request.uri().path())?
194 }
195 Ok(response)
c8402f1c
SW
196}
197
fbcdf3ed
SW
198fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
199 let datum = [voter, b" ", vote, b"\n"].concat();
200 let vpath = dir.join("votes");
201 let vfile = std::fs::File::options()
202 .append(true)
203 .create(true)
204 .open(vpath)?;
205 let mut vlock = fd_lock::RwLock::new(vfile);
206 vlock.write()?.write(&datum)?;
207 Ok(())
208}
209
c8402f1c 210fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
fbcdf3ed
SW
211 let body = request.body();
212 // Valid votes look like "0 foo" or "1 bar"
213 if body.len() < 3
214 || (body[0] != b'0' && body[0] != b'1')
215 || body[1] != b' '
216 || body.contains(&b'\n')
217 {
218 return Err(cgi::text_response(415, "Invalid vote"));
219 }
220 write_vote(dir, &get_voter(&request)?, body)
221 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
222 Ok(cgi::text_response(200, "Vote recorded"))
223}
224
225fn strip_body(mut response: cgi::Response) -> cgi::Response {
226 response.body_mut().clear();
227 response
c8402f1c
SW
228}
229
230fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
231 let dir = validate_path(request.uri().path())?;
232 match request.method() {
fbcdf3ed 233 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
c8402f1c 234 &cgi::http::Method::GET => prompt_for_vote(dir, request),
fbcdf3ed 235 &cgi::http::Method::PUT => record_vote(dir, request),
c8402f1c
SW
236 _ => Err(cgi::text_response(405, "Huh?")),
237 }
238}
239
240fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
241 match respond(request) {
242 Ok(result) => result,
243 Err(error) => error,
244 }
d1df2e73
SW
245}
246
c8402f1c 247cgi::cgi_main! { respond_or_report_error }