1 use std::io::prelude::*;
2 use std::path::{Path, PathBuf};
4 const DATA_PATH: &str = "/var/lib/voter";
5 const COOKIE_NAME: &[u8] = b"__Secure-id";
6 const COOKIE_LENGTH: usize = 32;
8 fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
9 let invalid_path = || cgi::text_response(404, "Invalid path");
11 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 if path.contains("..") || !path.starts_with("/") {
14 return Err(invalid_path());
16 let dir = Path::new(&format!("{DATA_PATH}{path}")).to_path_buf();
19 .map_err(|_| invalid_path())?
20 .starts_with(DATA_PATH)
22 return Err(invalid_path());
25 return Err(invalid_path());
30 fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
31 // Expect exactly one cookie, exactly as we generate it.
34 .get(cgi::http::header::COOKIE)
35 .map(|c| c.as_bytes())
36 .and_then(|c| c.strip_prefix(COOKIE_NAME))
37 .and_then(|c| c.strip_prefix(b"="))
38 .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
39 if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
40 Err(cgi::text_response(400, "Invalid cookie"))
46 fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
47 Err(cgi::text_response(503, "Not Implemented"))
50 fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
51 let datum = [voter, b" ", vote, b"\n"].concat();
52 let vpath = dir.join("votes");
53 let vfile = std::fs::File::options()
57 let mut vlock = fd_lock::RwLock::new(vfile);
58 vlock.write()?.write(&datum)?;
62 fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
63 let body = request.body();
64 // Valid votes look like "0 foo" or "1 bar"
66 || (body[0] != b'0' && body[0] != b'1')
68 || body.contains(&b'\n')
70 return Err(cgi::text_response(415, "Invalid vote"));
72 write_vote(dir, &get_voter(&request)?, body)
73 .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
74 Ok(cgi::text_response(200, "Vote recorded"))
77 fn strip_body(mut response: cgi::Response) -> cgi::Response {
78 response.body_mut().clear();
82 fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
83 let dir = validate_path(request.uri().path())?;
84 match request.method() {
85 &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
86 &cgi::http::Method::GET => prompt_for_vote(dir, request),
87 &cgi::http::Method::PUT => record_vote(dir, request),
88 _ => Err(cgi::text_response(405, "Huh?")),
92 fn respond_or_report_error(request: cgi::Request) -> cgi::Response {
93 match respond(request) {
99 cgi::cgi_main! { respond_or_report_error }