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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
use humphrey::http::headers::ResponseHeader;
use humphrey::http::mime::MimeType;
use humphrey::http::{Request, Response, StatusCode};
use humphrey::App;

#[cfg(feature = "plugins")]
use crate::plugins::manager::PluginManager;
#[cfg(feature = "plugins")]
use crate::plugins::plugin::PluginLoadResult;

use crate::cache::Cache;
use crate::config::{BlacklistMode, Config};
use crate::logger::Logger;
use crate::route::try_find_path;
use crate::server::proxy::pipe;

use std::fs::File;
use std::io::{Read, Write};
use std::net::TcpStream;
use std::sync::{Arc, RwLock};
use std::thread::spawn;

/// Represents the application state.
/// Includes the target directory, cache state, and the logger.
#[derive(Default)]
pub struct AppState {
    pub directory: String,
    pub cache_limit: usize,
    pub cache: RwLock<Cache>,
    pub websocket_proxy: Option<String>,
    pub blacklist: Vec<String>,
    pub blacklist_mode: BlacklistMode,
    pub logger: Logger,
    #[cfg(feature = "plugins")]
    plugin_manager: RwLock<PluginManager>,
}

impl From<&Config> for AppState {
    fn from(config: &Config) -> Self {
        Self {
            directory: config.directory.as_ref().unwrap().clone(),
            cache_limit: config.cache_limit,
            cache: RwLock::new(Cache::from(config)),
            websocket_proxy: config.websocket_proxy.clone(),
            blacklist: config.blacklist.clone(),
            blacklist_mode: config.blacklist_mode.clone(),
            logger: Logger::from(config),
            #[cfg(feature = "plugins")]
            plugin_manager: RwLock::new(PluginManager::default()),
        }
    }
}

/// Main function for the static server.
pub fn main(config: Config) {
    let app: App<AppState> = App::new_with_config(config.threads, AppState::from(&config))
        .with_connection_condition(verify_connection)
        .with_websocket_handler(websocket_handler)
        .with_route("/*", file_handler_wrapper);

    let addr = format!("{}:{}", config.address, config.port);

    let state = app.get_state();
    let logger = &state.logger;
    logger.info("Starting static server");

    #[cfg(feature = "plugins")]
    {
        if let Ok(plugins_count) = load_plugins(&config, state) {
            logger.info(&format!("Loaded {} plugins", plugins_count))
        } else {
            return;
        }
    };

    logger.info(&format!("Running at {}", addr));
    logger.debug(&format!("Configuration: {:?}", &config));

    app.run(addr).unwrap();
}

/// Verifies that the client is allowed to connect by checking with the blacklist config.
fn verify_connection(stream: &mut TcpStream, state: Arc<AppState>) -> bool {
    if let Ok(address) = stream.peer_addr() {
        let address = address.ip().to_string();
        if state.blacklist_mode == BlacklistMode::Block && state.blacklist.contains(&address) {
            state.logger.warn(&format!(
                "{}: Blacklisted IP attempted to connect",
                &address
            ));
            return false;
        }
    } else {
        state.logger.warn("Corrupted stream attempted to connect");
        return false;
    }

    true
}

#[cfg(feature = "plugins")]
fn file_handler_wrapper(mut request: Request, state: Arc<AppState>) -> Response {
    let plugins = state.plugin_manager.read().unwrap();

    let mut response = plugins
        .on_request(&mut request, state.clone()) // If the plugin overrides the response, return it
        .unwrap_or_else(|| file_handler(request, state.clone())); // If no plugin overrides the response, generate it in the normal way

    // Pass the response to plugins before it is sent to the client
    plugins.on_response(&mut response, state.clone());

    response
}

#[cfg(not(feature = "plugins"))]
fn file_handler_wrapper(request: Request, state: Arc<AppState>) -> Response {
    file_handler(request, state)
}

/// Request handler for every request.
/// Attempts to open a given file relative to the binary and returns error 404 if not found.
fn file_handler(request: Request, state: Arc<AppState>) -> Response {
    // Return error 403 if the address was blacklisted
    if state
        .blacklist
        .contains(&request.address.origin_addr.to_string())
    {
        state.logger.warn(&format!(
            "{}: Blacklisted IP attempted to request {}",
            request.address, request.uri
        ));
        return Response::new(StatusCode::Forbidden)
            .with_header(ResponseHeader::ContentType, "text/html".into())
            .with_bytes(b"<h1>403 Forbidden</h1>".to_vec())
            .with_request_compatibility(&request)
            .with_generated_headers();
    }

    if state.cache_limit > 0 {
        let cache = state.cache.read().unwrap();
        if let Some(cached) = cache.get(&request.uri) {
            state.logger.info(&format!(
                "{}: 200 OK (cached) {}",
                request.address, request.uri
            ));
            return Response::new(StatusCode::OK)
                .with_header(ResponseHeader::ContentType, cached.mime_type.into())
                .with_bytes(cached.data.clone())
                .with_request_compatibility(&request)
                .with_generated_headers();
        }
        drop(cache);
    }

    if let Some(located) = try_find_path(&state.directory, &request.uri) {
        if located.was_redirected && request.uri.chars().last() != Some('/') {
            state.logger.info(&format!(
                "{}: 302 Moved Permanently {}",
                request.address, request.uri
            ));
            return Response::new(StatusCode::MovedPermanently)
                .with_header(ResponseHeader::Location, format!("{}/", &request.uri))
                .with_request_compatibility(&request)
                .with_generated_headers();
        }

        let file_extension = located
            .path
            .extension()
            .map(|s| s.to_str().unwrap())
            .unwrap_or("");

        let mime_type = MimeType::from_extension(file_extension);
        let mut contents: Vec<u8> = Vec::new();

        let mut file = File::open(located.path).unwrap();
        file.read_to_end(&mut contents).unwrap();

        if state.cache_limit >= contents.len() {
            let mut cache = state.cache.write().unwrap();
            cache.set(&request.uri, contents.clone(), mime_type);
            state.logger.debug(&format!("Cached route {}", request.uri));
        } else if state.cache_limit > 0 {
            state
                .logger
                .warn(&format!("Couldn't cache, cache too small {}", request.uri));
        }

        state
            .logger
            .info(&format!("{}: 200 OK {}", request.address, request.uri));
        Response::new(StatusCode::OK)
            .with_header(ResponseHeader::ContentType, mime_type.into())
            .with_bytes(contents)
            .with_request_compatibility(&request)
            .with_generated_headers()
    } else {
        state.logger.warn(&format!(
            "{}: 404 Not Found {}",
            request.address, request.uri
        ));
        Response::new(StatusCode::NotFound)
            .with_header(ResponseHeader::ContentType, "text/html".into())
            .with_bytes(b"<h1>404 Not Found</h1>".to_vec())
            .with_request_compatibility(&request)
            .with_generated_headers()
    }
}

fn websocket_handler(request: Request, mut source: TcpStream, state: Arc<AppState>) {
    let source_addr = source.peer_addr().unwrap().to_string();

    if let Some(address) = &state.websocket_proxy {
        let bytes: Vec<u8> = request.into();

        if let Ok(mut destination) = TcpStream::connect(address) {
            // The target was successfully connected to

            destination.write(&bytes).unwrap();

            let mut source_clone = source.try_clone().unwrap();
            let mut destination_clone = destination.try_clone().unwrap();
            state.logger.info(&format!(
                "{}: WebSocket connected, proxying data",
                source_addr
            ));

            // Pipe data in both directions
            let forward = spawn(move || pipe(&mut source, &mut destination));
            let backward = spawn(move || pipe(&mut destination_clone, &mut source_clone));

            // Log any errors
            if let Err(_) = forward.join().unwrap() {
                state.logger.error(&format!(
                    "{}: Error proxying WebSocket from client to target, connection closed",
                    source_addr
                ));
            }
            if let Err(_) = backward.join().unwrap() {
                state.logger.error(&format!(
                    "{}: Error proxying WebSocket from target to client, connection closed",
                    source_addr
                ));
            }

            state.logger.info(&format!(
                "{}: WebSocket session complete, connection closed",
                source_addr
            ));
        } else {
            state
                .logger
                .error(&format!("{}: Could not connect to WebSocket", source_addr));
        }
    } else {
        state.logger.warn(&format!(
            "{}: WebSocket connection attempted but no handler provided",
            source_addr
        ))
    }
}

#[cfg(feature = "plugins")]
fn load_plugins(config: &Config, state: &Arc<AppState>) -> Result<usize, ()> {
    let mut manager = state.plugin_manager.write().unwrap();

    for path in &config.plugin_libraries {
        unsafe {
            let app_state = state.clone();
            match manager.load_plugin(path, config, app_state) {
                PluginLoadResult::Ok(name) => {
                    state.logger.info(&format!("Initialised plugin {}", name));
                }
                PluginLoadResult::NonFatal(e) => {
                    state
                        .logger
                        .warn(&format!("Non-fatal plugin error from {}", path));
                    state.logger.warn(&format!("Error message: {}", e));
                    state.logger.warn("Ignoring this plugin");
                }
                PluginLoadResult::Fatal(e) => {
                    state
                        .logger
                        .error(&format!("Could not initialise plugin from {}", path));
                    state.logger.error(&format!("Error message: {}", e));

                    return Err(());
                }
            }
        }
    }

    Ok(manager.plugin_count())
}