aboutsummaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: 080124d1b96936fa45d5c377fdfb9f76edfcee99 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use actix_web::{fs, middleware, server, App};
use clap::crate_version;
use simplelog::{Config, LevelFilter, TermLogger};
use std::io::{self, Write};
use std::net::{IpAddr, Ipv4Addr, SocketAddr, ToSocketAddrs};
use std::thread;
use std::time::Duration;
use yansi::{Color, Paint};

mod args;
mod auth;
mod 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,
}

fn main() {
    if cfg!(windows) && !Paint::enable_windows_ascii() {
        Paint::disable();
    }

    let miniserve_config = args::parse_args();
    if miniserve_config.no_symlinks
        && miniserve_config
            .path
            .symlink_metadata()
            .expect("Can't get file metadata")
            .file_type()
            .is_symlink()
    {
        println!(
            "{error} The no-symlinks option cannot be used with a symlink path",
            error = Paint::red("error:").bold(),
        );
        return;
    }

    if miniserve_config.verbose {
        let _ = TermLogger::init(LevelFilter::Info, Config::default());
    }
    let sys = actix::System::new("miniserve");

    let inside_config = miniserve_config.clone();
    server::new(move || {
        App::with_state(inside_config.clone())
            .middleware(auth::Auth)
            .middleware(middleware::Logger::default())
            .configure(configure_app)
    })
    .bind(
        miniserve_config
            .interfaces
            .iter()
            .map(|interface| {
                format!(
                    "{interface}:{port}",
                    interface = &interface,
                    port = miniserve_config.port,
                )
                .to_socket_addrs()
                .unwrap()
                .next()
                .unwrap()
            })
            .collect::<Vec<SocketAddr>>()
            .as_slice(),
    )
    .expect("Couldn't bind server")
    .shutdown_timeout(0)
    .start();

    let interfaces = miniserve_config.interfaces.iter().map(|&interface| {
        if interface == IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)) {
            // If the interface is 0.0.0.0, we'll change it to localhost so that clicking the link will
            // also work on Windows. Why can't Windows interpret 0.0.0.0?
            String::from("localhost")
        } else if interface.is_ipv6() {
            // If the interface is IPv6 then we'll print it with brackets so that it is clickable.
            format!("[{}]", interface)
        } else {
            format!("{}", interface)
        }
    });

    let canon_path = miniserve_config.path.canonicalize().unwrap();
    let path_string = canon_path.to_string_lossy();

    println!(
        "{name} v{version}",
        name = Paint::new("miniserve").bold(),
        version = crate_version!()
    );
    if !miniserve_config.path_explicitly_chosen {
        println!("{info} miniserve has been invoked without an explicit path so it will serve the current directory.", info=Color::Blue.paint("Info:").bold());
        println!(
            "      Invoke with -h|--help to see options or invoke as `miniserve .` to hide this advice."
        );
        print!("Starting server in ");
        io::stdout().flush().unwrap();
        for c in "3… 2… 1… \n".chars() {
            print!("{}", c);
            io::stdout().flush().unwrap();
            thread::sleep(Duration::from_millis(500));
        }
    }
    let mut addresses = String::new();
    for interface in interfaces {
        if !addresses.is_empty() {
            addresses.push_str(", ");
        }
        addresses.push_str(&format!(
            "{}",
            Color::Green
                .paint(format!(
                    "http://{interface}:{port}",
                    interface = interface,
                    port = miniserve_config.port
                ))
                .bold()
        ));
        let random_route = miniserve_config.clone().random_route;
        if random_route.is_some() {
            addresses.push_str(&format!(
                "{}",
                Color::Green
                    .paint(format!(
                        "/{random_route}",
                        random_route = random_route.unwrap(),
                    ))
                    .bold()
            ));
        }
    }
    println!(
        "Serving path {path} at {addresses}",
        path = Color::Yellow.paint(path_string).bold(),
        addresses = addresses,
    );
    println!("Quit by pressing CTRL-C");

    let _ = sys.run();
}

pub fn configure_app(app: App<MiniserveConfig>) -> App<MiniserveConfig> {
    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))
    }
}