commit dfa5dbd9717bef356b532cb1525d412e02c04076
parent 5d187a47fc23490b0b000e61ff03c34e851793e4
Author: Matt Brubeck <mbrubeck@limpet.net>
Date: Tue, 22 Dec 2020 13:52:24 -0800
Use getopts for option parsing
Diffstat:
4 files changed, 66 insertions(+), 21 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
@@ -7,6 +7,7 @@ dependencies = [
"async-std",
"async-tls",
"env_logger",
+ "getopts",
"log",
"mime_guess",
"once_cell",
@@ -292,6 +293,15 @@ dependencies = [
]
[[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"
source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -600,6 +610,12 @@ dependencies = [
]
[[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"
source = "registry+https://github.com/rust-lang/crates.io-index"
diff --git 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
@@ -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 <addr:port> <content_dir> <cert_file> <key_file> [<domain>]`. 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 `<domain>` 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
@@ -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<T = ()> = std::result::Result<T, Box<dyn Error + Send + Sync>>;
+type Result<T = (), E = Box<dyn Error + Send + Sync>> = std::result::Result<T, E>;
static ARGS: Lazy<Args> = Lazy::new(|| {
- args().unwrap_or_else(|| {
- eprintln!("usage: agate <addr:port> <dir> <cert> <key> [<domain to check>]");
+ 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<Host>,
+ hostname: Option<Host>,
}
-fn args() -> Option<Args> {
- 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<Args> {
+ let args: Vec<String> = 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<String, String> {
+ 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<R: Read + Unpin>(
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"));
}
}