From dfa5dbd9717bef356b532cb1525d412e02c04076 Mon Sep 17 00:00:00 2001 From: Matt Brubeck Date: Tue, 22 Dec 2020 13:52:24 -0800 Subject: [PATCH] Use getopts for option parsing --- Cargo.lock | 16 ++++++++++++++++ Cargo.toml | 1 + README.md | 15 +++++++++------ src/main.rs | 55 ++++++++++++++++++++++++++++++++++++++--------------- 4 files changed, 66 insertions(+), 21 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7a5e317..26d9d31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,6 +7,7 @@ dependencies = [ "async-std", "async-tls", "env_logger", + "getopts", "log", "mime_guess", "once_cell", @@ -291,6 +292,15 @@ dependencies = [ "waker-fn", ] +[[package]] +name = "getopts" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" +dependencies = [ + "unicode-width", +] + [[package]] name = "gloo-timers" version = "0.2.1" @@ -599,6 +609,12 @@ dependencies = [ "tinyvec", ] +[[package]] +name = "unicode-width" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" + [[package]] name = "unicode-xid" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 8363442..ede54f1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ edition = "2018" async-tls = { version = "0.11.0", default-features = false, features = ["server"] } async-std = "1.5" env_logger = { version = "0.8", default-features = false, features = ["atty", "humantime", "termcolor"] } +getopts = "0.2.21" log = "0.4" mime_guess = "2.0" once_cell = "1.4" diff --git a/README.md b/README.md index cb8f998..e95f9c7 100644 --- a/README.md +++ b/README.md @@ -27,21 +27,24 @@ openssl req -x509 -newkey rsa:4096 -keyout key.rsa -out cert.pem \ -days 3650 -nodes -subj "/CN=example.com" ``` -3. Run the server. The command line arguments are `agate []`. For example, to listen on the standard Gemini port (1965) on all interfaces: +3. Run the server. You can use the following arguments to specify the locations of the content directory, certificate and key files, IP address and port to listen on, and (optionally) a domain that will be used to validate request URLs: ``` -agate 0.0.0.0:1965 path/to/content/ cert.pem key.rsa +agate --content path/to/content/ \ + --key key.rsa \ + --cert cert.pem \ + --addr 0.0.0.0:1965 \ + --hostname example.com ``` -Agate will check that the port part of the requested URL matches the port specified in the 1st argument. -If `` is specified, agate will also check that the host part of the requested URL matches this domain. +All of the command-line arguments are optional. Run `agate --help` to see the default values used when arguments are omitted. When a client requests the URL `gemini://example.com/foo/bar`, Agate will respond with the file at `path/to/content/foo/bar`. If there is a directory at that path, Agate will look for a file named `index.gmi` inside that directory. -Optionally, set a log level via the `AGATE_LOG` environment variable. Logging is powered by the [env_logger crate](https://crates.io/crates/env_logger): +To enable console logging, set a log level via the `AGATE_LOG` environment variable. Logging is powered by the [env_logger crate](https://crates.io/crates/env_logger): ``` -AGATE_LOG=info 0.0.0.0:1965 path/to/content/ cert.pem key.rsa +AGATE_LOG=info agate --content path/to/content/ ``` [Gemini]: https://gemini.circumlunar.space/ diff --git a/src/main.rs b/src/main.rs index 8475228..7fe7361 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use rustls::{ internal::pemfile::{certs, pkcs8_private_keys}, NoClientAuth, ServerConfig, }; -use std::{error::Error, ffi::OsStr, fs::File, io::BufReader, marker::Unpin, sync::Arc}; +use std::{error::Error, ffi::OsStr, fs::File, io::BufReader, marker::Unpin, path::Path, sync::Arc}; use url::{Host, Url}; fn main() -> Result { @@ -30,11 +30,11 @@ fn main() -> Result { }) } -type Result = std::result::Result>; +type Result> = std::result::Result; static ARGS: Lazy = Lazy::new(|| { - args().unwrap_or_else(|| { - eprintln!("usage: agate []"); + args().unwrap_or_else(|s| { + eprintln!("{}", s); std::process::exit(1); }) }); @@ -44,20 +44,45 @@ struct Args { content_dir: String, cert_file: String, key_file: String, - domain: Option, + hostname: Option, } -fn args() -> Option { - let mut args = std::env::args().skip(1); - Some(Args { - sock_addr: args.next()?, - content_dir: args.next()?, - cert_file: args.next()?, - key_file: args.next()?, - domain: args.next().and_then(|s| Host::parse(&s).ok()), +fn args() -> Result { + let args: Vec = std::env::args().collect(); + let mut opts = getopts::Options::new(); + opts.optopt("", "content", "Root of the content directory (default ./content)", "DIR"); + opts.optopt("", "cert", "TLS certificate PEM file (default ./cert.pem)", "FILE"); + opts.optopt("", "key", "PKCS8 private key file (default ./key.rsa)", "FILE"); + opts.optopt("", "addr", "Address to listen on (default 0.0.0.0:1965)", "IP:PORT"); + opts.optopt("", "hostname", "Domain name of this Gemini server (optional)", "NAME"); + opts.optflag("h", "help", "print this help menu"); + + let usage = opts.usage(&format!("Usage: {} FILE [options]", &args[0])); + let matches = opts.parse(&args[1..]).map_err(|f| f.to_string())?; + if matches.opt_present("h") { + Err(usage)?; + } + let hostname = match matches.opt_str("hostname") { + Some(s) => Some(Host::parse(&s)?), + None => None, + }; + Ok(Args { + sock_addr: matches.opt_get_default("addr", "0.0.0.0:1965".into())?, + content_dir: check_path(matches.opt_get_default("content", "content".into())?)?, + cert_file: check_path(matches.opt_get_default("cert", "cert.pem".into())?)?, + key_file: check_path(matches.opt_get_default("key", "key.rsa".into())?)?, + hostname, }) } +fn check_path(s: String) -> Result { + if Path::new(&s).exists() { + Ok(s) + } else { + Err(format!("No such file: {}", s)) + } +} + /// Handle a single client session (request + response). async fn handle_request(stream: TcpStream) -> Result { // Perform handshake. @@ -131,8 +156,8 @@ async fn parse_request( return Err((53, "unsupported URL scheme")); } // TODO: Can be simplified by https://github.com/servo/rust-url/pull/651 - if let (Some(Host::Domain(domain)), Some(Host::Domain(host))) = (&ARGS.domain, url.host()) { - if domain != host { + if let (Some(Host::Domain(expected)), Some(Host::Domain(host))) = (url.host(), &ARGS.hostname) { + if host != expected { return Err((53, "proxy request refused")); } }