Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split project into multiple files #32

Merged
merged 5 commits into from Feb 13, 2019
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
167 changes: 167 additions & 0 deletions src/args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
use crate::auth;
use crate::config;
use crate::listing;
use clap::{crate_authors, crate_description, crate_name, crate_version};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::PathBuf;

const ROUTE_ALPHABET: [char; 16] = [
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f',
];

fn is_valid_path(path: String) -> Result<(), String> {
let path_to_check = PathBuf::from(path);
if path_to_check.is_file() || path_to_check.is_dir() {
return Ok(());
}
Err(String::from(
"Path either doesn't exist or is not a regular file or a directory",
))
}

fn is_valid_port(port: String) -> Result<(), String> {
port.parse::<u16>()
.and(Ok(()))
.or_else(|e| Err(e.to_string()))
}

fn is_valid_interface(interface: String) -> Result<(), String> {
interface
.parse::<IpAddr>()
.and(Ok(()))
.or_else(|e| Err(e.to_string()))
}

fn is_valid_auth(auth: String) -> Result<(), String> {
auth.find(':')
.ok_or_else(|| "Correct format is username:password".to_owned())
.map(|_| ())
}

pub fn parse_args() -> config::MiniserveConfig {
use clap::{App, AppSettings, Arg};

let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.global_setting(AppSettings::ColoredHelp)
.arg(
Arg::with_name("verbose")
.short("v")
.long("verbose")
.help("Be verbose, includes emitting access logs"),
)
.arg(
Arg::with_name("PATH")
.required(false)
.validator(is_valid_path)
.help("Which path to serve"),
)
.arg(
Arg::with_name("port")
.short("p")
.long("port")
.help("Port to use")
.validator(is_valid_port)
.required(false)
.default_value("8080")
.takes_value(true),
)
.arg(
Arg::with_name("interfaces")
.short("i")
.long("if")
.help("Interface to listen on")
.validator(is_valid_interface)
.required(false)
.takes_value(true)
.multiple(true),
)
.arg(
Arg::with_name("auth")
.short("a")
.long("auth")
.validator(is_valid_auth)
.help("Set authentication (username:password)")
.takes_value(true),
)
.arg(
Arg::with_name("random-route")
.long("random-route")
.help("Generate a random 6-hexdigit route"),
)
.arg(
Arg::with_name("sort")
.short("s")
.long("sort")
.possible_values(&["natural", "alpha", "dirsfirst"])
.default_value("natural")
.help("Sort files"),
)
.arg(
Arg::with_name("reverse")
.long("reverse")
.help("Reverse sorting order"),
)
.arg(
Arg::with_name("no-symlinks")
.short("P")
.long("no-symlinks")
.help("Do not follow symbolic links"),
)
.get_matches();

let verbose = matches.is_present("verbose");
let no_symlinks = matches.is_present("no-symlinks");
let path = matches.value_of("PATH");
let port = matches.value_of("port").unwrap().parse().unwrap();
let interfaces = if let Some(interfaces) = matches.values_of("interfaces") {
interfaces.map(|x| x.parse().unwrap()).collect()
} else {
vec![
IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0)),
IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)),
]
};
let auth = if let Some(auth_split) = matches.value_of("auth").map(|x| x.splitn(2, ':')) {
let auth_vec = auth_split.collect::<Vec<&str>>();
if auth_vec.len() == 2 {
Some(auth::BasicAuthParams {
username: auth_vec[0].to_owned(),
password: auth_vec[1].to_owned(),
})
} else {
None
}
} else {
None
};

let random_route = if matches.is_present("random-route") {
Some(nanoid::custom(6, &ROUTE_ALPHABET))
} else {
None
};

let sort_method = matches
.value_of("sort")
.unwrap()
.parse::<listing::SortingMethods>()
.unwrap();

let reverse_sort = matches.is_present("reverse");

config::MiniserveConfig {
verbose,
path: PathBuf::from(path.unwrap_or(".")),
port,
interfaces,
auth,
path_explicitly_chosen: path.is_some(),
no_symlinks,
random_route,
sort_method,
reverse_sort,
}
}
77 changes: 77 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use actix_web::http::header;
use actix_web::middleware::{Middleware, Response};
use actix_web::{HttpRequest, HttpResponse, Result};

use crate::config;

pub struct Auth;

pub enum BasicAuthError {
Base64DecodeError,
InvalidUsernameFormat,
}

#[derive(Clone, Debug)]
pub struct BasicAuthParams {
pub username: String,
pub password: String,
}

/// Decode a HTTP basic auth string into a tuple of username and password.
pub fn parse_basic_auth(
authorization_header: &header::HeaderValue,
) -> Result<BasicAuthParams, BasicAuthError> {
let basic_removed = authorization_header.to_str().unwrap().replace("Basic ", "");
let decoded = base64::decode(&basic_removed).map_err(|_| BasicAuthError::Base64DecodeError)?;
let decoded_str = String::from_utf8_lossy(&decoded);
let strings: Vec<&str> = decoded_str.splitn(2, ':').collect();
if strings.len() != 2 {
return Err(BasicAuthError::InvalidUsernameFormat);
}
Ok(BasicAuthParams {
username: strings[0].to_owned(),
password: strings[1].to_owned(),
})
}

impl Middleware<config::MiniserveConfig> for Auth {
fn response(
&self,
req: &HttpRequest<config::MiniserveConfig>,
resp: HttpResponse,
) -> Result<Response> {
if let Some(ref required_auth) = req.state().auth {
if let Some(auth_headers) = req.headers().get(header::AUTHORIZATION) {
let auth_req = match parse_basic_auth(auth_headers) {
Ok(auth_req) => auth_req,
Err(BasicAuthError::Base64DecodeError) => {
return Ok(Response::Done(HttpResponse::BadRequest().body(format!(
"Error decoding basic auth base64: '{}'",
auth_headers.to_str().unwrap()
))));
}
Err(BasicAuthError::InvalidUsernameFormat) => {
return Ok(Response::Done(
HttpResponse::BadRequest().body("Invalid basic auth format"),
));
}
};
if auth_req.username != required_auth.username
|| auth_req.password != required_auth.password
{
let new_resp = HttpResponse::Forbidden().finish();
return Ok(Response::Done(new_resp));
}
} else {
let new_resp = HttpResponse::Unauthorized()
.header(
header::WWW_AUTHENTICATE,
header::HeaderValue::from_static("Basic realm=\"miniserve\""),
)
.finish();
return Ok(Response::Done(new_resp));
}
}
Ok(Response::Done(resp))
}
}
57 changes: 57 additions & 0 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use actix_web::{fs, App};
use std::net::IpAddr;

use crate::auth;
use crate::listing;

#[derive(Clone, Debug)]
pub struct MiniserveConfig {
pub verbose: bool,
pub path: std::path::PathBuf,
pub port: u16,
pub interfaces: Vec<IpAddr>,
pub auth: Option<auth::BasicAuthParams>,
pub path_explicitly_chosen: bool,
pub no_symlinks: bool,
pub random_route: Option<String>,
pub sort_method: listing::SortingMethods,
pub reverse_sort: bool,
}

pub fn configure_app(app: App<MiniserveConfig>) -> App<MiniserveConfig> {
This conversation was marked as resolved.
Show resolved Hide resolved
let s = {
let path = &app.state().path;
let no_symlinks = app.state().no_symlinks;
let random_route = app.state().random_route.clone();
let sort_method = app.state().sort_method;
let reverse_sort = app.state().reverse_sort;
if path.is_file() {
None
} else {
Some(
fs::StaticFiles::new(path)
.expect("Couldn't create path")
.show_files_listing()
.files_listing_renderer(move |dir, req| {
listing::directory_listing(
dir,
req,
no_symlinks,
random_route.clone(),
sort_method,
reverse_sort,
)
}),
)
}
};

let random_route = app.state().random_route.clone().unwrap_or_default();
let full_route = format!("/{}", random_route);

if let Some(s) = s {
app.handler(&full_route, s)
} else {
app.resource(&full_route, |r| r.f(listing::file_handler))
}
}