]> git.scottworley.com Git - voter/blobdiff - src/main.rs
Release 0.2.4
[voter] / src / main.rs
index 15a1655de920522e2526191dc6cd47fd9dbf5c3e..303393c150dab17af457194ab9501d6865821d98 100644 (file)
@@ -1,6 +1,11 @@
+use rand::prelude::*;
+use std::collections::{HashMap, HashSet};
+use std::io::prelude::*;
 use std::path::{Path, PathBuf};
 
 const DATA_PATH: &str = "/var/lib/voter";
+const COOKIE_NAME: &[u8] = b"__Secure-id";
+const COOKIE_LENGTH: usize = 12;
 
 fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
     let invalid_path = || cgi::text_response(404, "Invalid path");
@@ -24,19 +29,248 @@ fn validate_path(path: &str) -> Result<PathBuf, cgi::Response> {
     Ok(dir)
 }
 
+fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
+    // Expect exactly one cookie, exactly as we generate it.
+    let cookie = request
+        .headers()
+        .get(cgi::http::header::COOKIE)
+        .map(|c| c.as_bytes())
+        .and_then(|c| c.strip_prefix(COOKIE_NAME))
+        .and_then(|c| c.strip_prefix(b"="))
+        .ok_or_else(|| cgi::text_response(400, "Invalid cookie"))?;
+    if cookie.len() != COOKIE_LENGTH || cookie.contains(&b' ') || cookie.contains(&b';') {
+        Err(cgi::text_response(400, "Invalid cookie"))
+    } else {
+        Ok(cookie)
+    }
+}
+
+fn tally_votes(dir: PathBuf) -> std::io::Result<HashMap<String, HashSet<String>>> {
+    let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
+    if let Ok(vfile) = std::fs::File::open(dir.join("votes")) {
+        for liner in std::io::BufReader::new(vfile).lines() {
+            let line = liner?;
+            if let Some((voter, datum)) = line.split_once(' ') {
+                if voter.len() == COOKIE_LENGTH {
+                    if let Some((vote, candidate)) = datum.split_once(' ') {
+                        if vote == "0" {
+                            if let Some(entry) = tally.get_mut(candidate) {
+                                entry.remove(voter);
+                            }
+                        } else if vote == "1" {
+                            tally
+                                .entry(candidate.to_owned())
+                                .or_default()
+                                .insert(voter.to_owned());
+                        }
+                    }
+                }
+            }
+        }
+    }
+    Ok(tally)
+}
+
+fn make_random_id() -> [u8; COOKIE_LENGTH] {
+    let mut id = [0; COOKIE_LENGTH];
+    for i in 0..COOKIE_LENGTH {
+        while !(b'A'..=b'Z').contains(&id[i])
+            && !(b'a'..=b'z').contains(&id[i])
+            && !(b'0'..=b'9').contains(&id[i])
+        {
+            id[i] = random()
+        }
+    }
+    id
+}
+
+fn set_cookie(mut response: cgi::Response, path: &str) -> Result<cgi::Response, cgi::Response> {
+    response.headers_mut().append(
+        cgi::http::header::SET_COOKIE,
+        cgi::http::header::HeaderValue::from_bytes(
+            &[
+                COOKIE_NAME,
+                b"=",
+                &make_random_id(),
+                b"; Secure HttpOnly SameSite=Strict Max-Age=30000000 Path=",
+                path.as_bytes(),
+            ]
+            .concat(),
+        )
+        .map_err(|_| cgi::text_response(503, "Couldn't make cookie"))?,
+    );
+    Ok(response)
+}
+
+const HTML_HEADER: &str = "<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset=\"utf-8\">
+    <title>Vote!</title>
+    <style>
+      th { font-size: 70%; text-align: left }
+      input { transform: scale(1.5) }
+      div { animation: 2s infinite linear spin }
+      @keyframes spin {
+        from { transform:rotate(0) }
+        to { transform:rotate(1turn) }
+      }
+    </style>
+    <script>
+      window.onload = function() {
+        for (cb of document.getElementsByTagName('input')) {
+          cb.addEventListener('click', (function(cb) {
+            return function() {
+              cb.style.display = 'none'
+              const spin = document.createElement('div')
+              spin.appendChild(document.createTextNode('⏳'))
+              cb.parentElement.insertBefore(spin, cb)
+
+              const req = new XMLHttpRequest()
+              req.addEventListener('load', function(e) {
+                cb.parentElement.removeChild(cb.previousElementSibling)
+                if (req.status == 200) {
+                    cb.style.display = ''
+                    const delta = cb.checked ? 1 : -1
+                    const count_td = cb.parentElement.previousElementSibling
+                    count_td.textContent = parseInt(count_td.textContent) + delta
+                } else {
+                   cb.parentElement.insertBefore(document.createTextNode('❗'), cb)
+                }
+              })
+              req.open('PUT', window.location.href)
+              req.send((cb.checked ? 1 : 0) + ' ' + cb.parentElement.nextElementSibling.innerHTML)
+            }
+          })(cb))
+          cb.disabled = false
+        }
+      }
+      function num_cmp(a, b) {
+        return parseInt(b.textContent) - parseInt(a.textContent)
+      }
+      function str_cmp(a, b) {
+        if (a.textContent < b.textContent) return -1
+        if (a.textContent > b.textContent) return 1
+        return 0
+      }
+      function checked_cmp(a, b) {
+        vs = [a, b].map(x => {
+          const v = x.children[0].checked + 0
+          return isNaN(v) ? -1 : v
+        })
+        return vs[1] - vs[0]
+      }
+      function sort_table(col, cmp) {
+        const rows = Array.from(document.getElementsByTagName('tr'))
+        rows.shift()
+        rows.sort((a, b) => cmp(a.children[col], b.children[col]))
+        for (row of rows) {
+          row.parentElement.appendChild(row)
+        }
+      }
+    </script>
+  </head>
+  <body>
+    <table>
+      <tr>
+        <th onclick='sort_table(0, num_cmp)'>Count</th>
+        <th onclick='sort_table(1, checked_cmp)'>Vote</th>
+        <th onclick='sort_table(2, str_cmp)'>Candidate</th>
+      </tr>";
+const HTML_FOOTER: &str = "
+    </table>
+  </body>
+</html>";
+
+fn supports(tally: &HashMap<String, HashSet<String>>, me: &str, candidate: &str) -> bool {
+    tally
+        .get(candidate)
+        .map(|supporters| supporters.contains(me))
+        .unwrap_or(false)
+}
+
 fn prompt_for_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
-    Err(cgi::text_response(503, "Not Implemented"))
+    let voter = get_voter(&request);
+    let me = if let Ok(id) = voter {
+        std::str::from_utf8(id).ok()
+    } else {
+        None
+    };
+    let tally =
+        tally_votes(dir.clone()).map_err(|_| cgi::text_response(503, "Couldn't tally votes"))?;
+    let cfile = std::fs::File::open(dir.join("candidates"))
+        .map_err(|_| cgi::text_response(503, "No candidates"))?;
+    let mut response = cgi::html_response(
+        200,
+        std::iter::once(Ok(HTML_HEADER.to_owned()))
+            .chain(std::io::BufReader::new(cfile).lines().map(|rc| {
+                rc.map(|c| {
+                    let count = tally
+                        .get(&c)
+                        .map(|supporters| supporters.len())
+                        .unwrap_or(0);
+                    let checked = if me.map(|me| supports(&tally, me, &c)).unwrap_or(false) {
+                        "checked"
+                    } else {
+                        ""
+                    };
+                    format!(
+                        "<tr>
+                        <td>{count}</td>
+                        <td><input type=\"checkbox\" autocomplete=\"off\" {checked} disabled></td>
+                        <td>{c}</td>
+                        </tr>"
+                    )
+                })
+            }))
+            .chain(std::iter::once(Ok(HTML_FOOTER.to_owned())))
+            .collect::<std::io::Result<String>>()
+            .map_err(|_| cgi::text_response(503, "Missing candidates"))?,
+    );
+    if voter.is_err() {
+        response = set_cookie(response, request.uri().path())?
+    }
+    Ok(response)
+}
+
+fn write_vote(dir: PathBuf, voter: &[u8], vote: &[u8]) -> std::io::Result<()> {
+    let datum = [voter, b" ", vote, b"\n"].concat();
+    let vpath = dir.join("votes");
+    let vfile = std::fs::File::options()
+        .append(true)
+        .create(true)
+        .open(vpath)?;
+    let mut vlock = fd_lock::RwLock::new(vfile);
+    vlock.write()?.write(&datum)?;
+    Ok(())
 }
 
 fn record_vote(dir: PathBuf, request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
-    Err(cgi::text_response(503, "Not Implemented"))
+    let body = request.body();
+    // Valid votes look like "0 foo" or "1 bar"
+    if body.len() < 3
+        || (body[0] != b'0' && body[0] != b'1')
+        || body[1] != b' '
+        || body.contains(&b'\n')
+    {
+        return Err(cgi::text_response(415, "Invalid vote"));
+    }
+    write_vote(dir, &get_voter(&request)?, body)
+        .map_err(|_| cgi::text_response(503, "Couldn't record vote"))?;
+    Ok(cgi::text_response(200, "Vote recorded"))
+}
+
+fn strip_body(mut response: cgi::Response) -> cgi::Response {
+    response.body_mut().clear();
+    response
 }
 
 fn respond(request: cgi::Request) -> Result<cgi::Response, cgi::Response> {
     let dir = validate_path(request.uri().path())?;
     match request.method() {
+        &cgi::http::Method::HEAD => prompt_for_vote(dir, request).map(strip_body),
         &cgi::http::Method::GET => prompt_for_vote(dir, request),
-        &cgi::http::Method::POST => record_vote(dir, request),
+        &cgi::http::Method::PUT => record_vote(dir, request),
         _ => Err(cgi::text_response(405, "Huh?")),
     }
 }