From 3acc35a899eb6c4a222a7c9862b1859d4a3f908c Mon Sep 17 00:00:00 2001 From: Michael Mullin Date: Sun, 23 Jan 2022 01:42:45 -0500 Subject: [PATCH] Add libmagic to better process mime_types on Linux Problem: serving files as application/application-octext-stream is annoying if the file is ASCII text Solution: When serving files on linux, libmagic can analyze the file to determine filetype when mime_guess has failed. Use libmagic to determine if a file is a plaintext file. Signed-off-by: Michael Mullin --- Cargo.toml | 3 +++ src/main.rs | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 4790cc3..e38e623 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,9 @@ htmlescape = "0.3.1" percent-encoding = "2.1.0" path-dedot = "1" +[target.'cfg(target_os="linux")'.dependencies] +magic = "*" + [features] default = ["tls"] tls = ["hyper-native-tls"] diff --git a/src/main.rs b/src/main.rs index 67f67ca..375fb71 100644 --- a/src/main.rs +++ b/src/main.rs @@ -893,7 +893,24 @@ impl MainHandler { } Method::Get => { // Set mime type - let mime = mime_types::from_path(path).first_or_octet_stream(); + //let mime = mime_types::from_path(path).first_or_octet_stream(); + let mime = if cfg!(target_os = "linux") { + mime_types::from_path(path).first_or_else(|| { + if let Ok(cookie) = magic::Cookie::open(magic::flags::MIME_TYPE) { + if cookie.load::<&str>(&[]).is_ok() { + if let Ok(val) = cookie.file(&path) { + if val == "text/plain" { + return mime_types::mime::TEXT_PLAIN; + } + } + } + } + mime_types::mime::APPLICATION_OCTET_STREAM + }) + } else { + mime_types::from_path(path).first_or_octet_stream() + }; + resp.headers .set_raw("content-type", vec![mime.to_string().into_bytes()]);