]> git.scottworley.com Git - voter/blame - src/main.rs
Spinning animation while vote request is processing
[voter] / src / main.rs
CommitLineData
dd0a1246 1use rand::prelude::*;
fbcdf3ed 2use std::io::prelude::*;
c8402f1c 3use std::path::{Path, PathBuf};
d1df2e73 4
c8402f1c 5const DATA_PATH: &str = "/var/lib/voter";
fbcdf3ed 6const COOKIE_NAME: &[u8] = b"__Secure-id";
ae9be1b6 7const COOKIE_LENGTH: usize = 12;
c8402f1c
SW
8
9fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
10 let invalid_path = || cgi::text_response(404, "Invalid path");
11 if path == "/" {
12 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.)"));
13 }
14 if path.contains("..") || !path.starts_with("/") {
15 return Err(invalid_path());
16 }
17 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
18 if !dir
19 .canonicalize()
20 .map_err(|_| invalid_path())?
21 .starts_with(DATA_PATH)
22 {
23 return Err(invalid_path());
24 }
25 if !dir.is_dir() {
26 return Err(invalid_path());
27 }
28 Ok(dir)
29}
30
fbcdf3ed
SW
31fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
32 // Expect exactly one cookie, exactly as we generate it.
33 let cookie = request
34 .headers()
35 .get(cgi::http::header::COOKIE)
36 .map(|c| c.as_bytes())
37 .and_then(|c| c.strip_prefix(COOKIE_NAME))
38 .and_then(|c| c.strip_prefix(b"="))
39 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
40 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
41 Err(cgi::text_response(400, "Invalid cookie"))
42 } else {
43 Ok(cookie)
44 }
45}
46
dd0a1246 47fn make_random_id() -> [u8; COOKIE_LENGTH] {
5a0934fa
SW
48 let mut id = [0; COOKIE_LENGTH];
49 for i in 0..COOKIE_LENGTH {
50 while !(b'A'..=b'Z').contains(&id[i])
51 && !(b'a'..=b'z').contains(&id[i])
52 && !(b'0'..=b'9').contains(&id[i])
53 {
54 id[i] = random()
55 }
56 }
57 id
dd0a1246
SW
58}
59
60fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
61 response.headers_mut().append(
62 cgi::http::header::SET_COOKIE,
63 cgi::http::header::HeaderValue::from_bytes(
64 &[
65 COOKIE_NAME,
66 b"=",
67 &make_random_id(),
68 b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
69 path.as_bytes(),
70 ]
71 .concat(),
72 )
73 .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
74 );
75 Ok(response)
76}
77
3a28e771 78const HTML_HEADER: &str = "<!DOCTYPE html>
f5e90a7e
SW
79<html>
80 <head>
3a28e771 81 <meta charset=\"utf-8\">
9e49b3f0 82 <title>Vote!</title>
f5e90a7e 83 <style>
9d82c13f 84 input { transform: scale(1.5) }
95432069
SW
85 div { animation: 2s infinite linear spin }
86 @keyframes spin {
87 from { transform:rotate(0) }
88 to { transform:rotate(1turn) }
89 }
f5e90a7e 90 </style>
9d82c13f
SW
91 <script>
92 window.onload = function() {
93 for (cb of document.getElementsByTagName('input')) {
95432069
SW
94 cb.addEventListener('click', (function(cb) {
95 return function() {
96 cb.style.display = 'none'
97 const spin = document.createElement('div')
98 spin.appendChild(document.createTextNode('⏳'))
99 cb.parentElement.insertBefore(spin, cb)
100 }
101 })(cb))
9d82c13f
SW
102 cb.disabled = false
103 }
104 }
105 </script>
f5e90a7e
SW
106 </head>
107 <body>
108 <table>";
109const HTML_FOOTER: &str = "
110 </table>
111 </body>
112</html>";
113
c8402f1c 114fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
dd0a1246 115 let voter = get_voter(&request);
381eeda5
SW
116 let cfile = std::fs::File::open(dir.join("candidates"))
117 .map_err(|_| cgi::text_response(503, "No candidates"))?;
118 let mut response = cgi::html_response(
119 200,
f5e90a7e
SW
120 std::iter::once(Ok(HTML_HEADER.to_owned()))
121 .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
9d82c13f
SW
122 rc.map(|c| {
123 format!("<tr><td><input type=\"checkbox\" disabled></td><td>{c}</td></tr>")
124 })
f5e90a7e
SW
125 }))
126 .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
381eeda5
SW
127 .collect::<std::io::Result<String>>()
128 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
129 );
dd0a1246
SW
130 if voter.is_err() {
131 response = set_cookie(response, request.uri().path())?
132 }
133 Ok(response)
c8402f1c
SW
134}
135
fbcdf3ed
SW
136fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
137 let datum = [voter, b" ", vote, b"\n"].concat();
138 let vpath = dir.join("votes");
139 let vfile = std::fs::File::options()
140 .append(true)
141 .create(true)
142 .open(vpath)?;
143 let mut vlock = fd_lock::RwLock::new(vfile);
144 vlock.write()?.write(&datum)?;
145 Ok(())
146}
147
c8402f1c 148fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
fbcdf3ed
SW
149 let body = request.body();
150 // Valid votes look like "0 foo" or "1 bar"
151 if body.len() < 3
152 || (body[0] != b'0' && body[0] != b'1')
153 || body[1] != b' '
154 || body.contains(&b'\n')
155 {
156 return Err(cgi::text_response(415, "Invalid vote"));
157 }
158 write_vote(dir, &get_voter(&request)?, body)
159 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
160 Ok(cgi::text_response(200, "Vote recorded"))
161}
162
163fn strip_body(mut response: cgi::Response) -> cgi::Response {
164 response.body_mut().clear();
165 response
c8402f1c
SW
166}
167
168fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
169 let dir = validate_path(request.uri().path())?;
170 match request.method() {
fbcdf3ed 171 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
c8402f1c 172 &cgi::http::Method::GET => prompt_for_vote(dir, request),
fbcdf3ed 173 &cgi::http::Method::PUT => record_vote(dir, request),
c8402f1c
SW
174 _ => Err(cgi::text_response(405, "Huh?")),
175 }
176}
177
178fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
179 match respond(request) {
180 Ok(result) => result,
181 Err(error) => error,
182 }
d1df2e73
SW
183}
184
c8402f1c 185cgi::cgi_main! { respond_or_report_error }