]> git.scottworley.com Git - voter/blob - src/main.rs
Simpler make_random_id()
[voter] / src / main.rs
1 use rand::prelude::*;
2 use std::io::prelude::*;
3 use std::path::{Path, PathBuf};
4
5 const DATA_PATH: &str = "/var/lib/voter";
6 const COOKIE_NAME: &[u8] = b"__Secure-id";
7 const COOKIE_LENGTH: usize = 12;
8
9 fn 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
31 fn 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
47 fn make_random_id() -> [u8; COOKIE_LENGTH] {
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
58 }
59
60 fn 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
78 fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
79 let voter = get_voter(&request);
80 let cfile = std::fs::File::open(dir.join("candidates"))
81 .map_err(|_| cgi::text_response(503, "No candidates"))?;
82 let mut response = cgi::html_response(
83 200,
84 std::iter::once(Ok("<html><body><table>".to_owned()))
85 .chain(
86 std::io::BufReader::new(cfile)
87 .lines()
88 .map(|rc| rc.map(|c| format!("<tr><td>{c}</td></tr>"))),
89 )
90 .chain(std::iter::once(Ok("</table></body></html>".to_owned())))
91 .collect::<std::io::Result<String>>()
92 .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
93 );
94 if voter.is_err() {
95 response = set_cookie(response, request.uri().path())?
96 }
97 Ok(response)
98 }
99
100 fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
101 let datum = [voter, b" ", vote, b"\n"].concat();
102 let vpath = dir.join("votes");
103 let vfile = std::fs::File::options()
104 .append(true)
105 .create(true)
106 .open(vpath)?;
107 let mut vlock = fd_lock::RwLock::new(vfile);
108 vlock.write()?.write(&datum)?;
109 Ok(())
110 }
111
112 fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
113 let body = request.body();
114 // Valid votes look like "0 foo" or "1 bar"
115 if body.len() < 3
116 || (body[0] != b'0' && body[0] != b'1')
117 || body[1] != b' '
118 || body.contains(&b'\n')
119 {
120 return Err(cgi::text_response(415, "Invalid vote"));
121 }
122 write_vote(dir, &get_voter(&request)?, body)
123 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
124 Ok(cgi::text_response(200, "Vote recorded"))
125 }
126
127 fn strip_body(mut response: cgi::Response) -> cgi::Response {
128 response.body_mut().clear();
129 response
130 }
131
132 fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
133 let dir = validate_path(request.uri().path())?;
134 match request.method() {
135 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
136 &cgi::http::Method::GET => prompt_for_vote(dir, request),
137 &cgi::http::Method::PUT => record_vote(dir, request),
138 _ => Err(cgi::text_response(405, "Huh?")),
139 }
140 }
141
142 fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
143 match respond(request) {
144 Ok(result) => result,
145 Err(error) => error,
146 }
147 }
148
149 cgi::cgi_main! { respond_or_report_error }