~zethra/stargazer

ref: 0976fac2bf22fd51bb7886e5e953841362336770 stargazer/src/get_file.rs -rw-r--r-- 5.3 KiB
0976fac2 — Ben Aaron Goldberg logger: log date+time 2 months ago
                                                                                
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
// stargazer - A Gemini Server
// Copyright (C) 2021 Ben Aaron Goldberg <ben@benaaron.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::dir_list;
use crate::error::{Context, ErrorConv, GemError, Result};
use crate::router::StaticRoute;
use async_fs::File;
use async_net::TcpStream;
use async_rustls::server::TlsStream;
use blocking::unblock;
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use percent_encoding::percent_decode_str;
use std::{ffi::OsString, path::Path};

// const DEFAULT_MIME: &str = "text/plain";
const DEFAULT_MIME: &str = "application/octet-stream";
const GMI_MIME: &str = "text/gemini";

#[derive(Debug, PartialEq, Eq)]
enum PathType {
    Dir,
    File,
}

pub async fn get_file<'a>(
    static_route: &'static StaticRoute,
    path: &'a str,
    lang: &'a Option<String>,
    charset: &'a Option<String>,
    stream: &'a mut TlsStream<TcpStream>,
) -> Result<()> {
    let path_str = path;
    let os_str = parse_path(path)?;
    let path = static_route.root.join(Path::new(&os_str));
    log::debug!("Requested file path: {}", path.display());

    let (path, path_type, mut mime_type) = unblock(move || {
        if !path.exists() {
            return Err(GemError::NotFound);
        }

        if path.is_dir() {
            let index_path = path.join(&static_route.index);
            if index_path.exists() {
                let mime_type = get_mime_type(&index_path);
                return Ok((index_path, PathType::File, mime_type));
            }
            Ok((path, PathType::Dir, GMI_MIME.to_owned()))
        } else {
            let mime_type = get_mime_type(&path);
            Ok((path, PathType::File, mime_type))
        }
    })
    .await?;

    if path_type == PathType::Dir && !static_route.auto_index {
        return Err(GemError::NotFound);
    }
    // TODO show I be doing this?
    if path_type == PathType::Dir && !path_str.ends_with('/') {
        let mut new_path = path_str.to_owned();
        new_path.push('/');
        return Err(GemError::Redirect(new_path));
    }

    // Add lang or charset to mime_type
    match (lang, charset) {
        (Some(lang), _) if mime_type == GMI_MIME => {
            mime_type.push_str("; lang=");
            mime_type.push_str(&lang);
        }
        (_, Some(charset)) if mime_type.starts_with("text/") => {
            mime_type.push_str("; charset=");
            mime_type.push_str(&charset);
        }
        _ => {}
    }

    let mut buf = [0u8; 4096];
    let mut file = File::open(&path)
        .await
        .with_context(|| format!("Error opening file: {}", path.display()))?;

    stream.write_all(b"20 ").await.into_io_error()?;
    stream
        .write_all(mime_type.as_bytes())
        .await
        .into_io_error()?;
    stream.write_all(b"\r\n").await.into_io_error()?;
    match path_type {
        PathType::File => loop {
            let bytes_read = file.read(&mut buf).await.with_context(|| {
                format!("Error reading from file: {}", path.display())
            })?;
            if bytes_read == 0 {
                break;
            }
            stream
                .write_all(&buf[..bytes_read])
                .await
                .context("Error writing output")
                .into_io_error()?;
        },
        PathType::Dir => {
            dir_list::gen(&path, stream).await?;
        }
    }

    Ok(())
}

#[cfg(unix)]
pub fn parse_path(percent_encoded: &str) -> Result<OsString> {
    let mut bytes: Vec<u8> = percent_decode_str(percent_encoded).collect();
    // Remove leading slashes if present
    while !bytes.is_empty() && bytes[0] == b'/' {
        bytes.remove(0);
    }

    // TODO windows support
    use std::os::unix::ffi::OsStringExt;
    Ok(OsString::from_vec(bytes))
}

#[cfg(not(unix))]
pub fn parse_path(percent_encoded: &str) -> Result<OsString> {
    let mut bytes: Vec<u8> = percent_decode_str(percent_encoded).collect();
    // Remove leading slash if present
    while !bytes.is_empty() && bytes[0] == b'/' {
        bytes.remove(0);
    }

    use std::ffi::OsStr;
    Ok(OsStr::new(
        std::str::from_utf8(&bytes).context("File path is not valid UTF-8")?,
    )
    .to_owned())
}

fn get_mime_type(path: &Path) -> String {
    if let Some(ext) = path.extension() {
        match ext.to_str() {
            Some(ext) => {
                if ext == "gmi" || ext == "gemini" {
                    GMI_MIME.to_owned()
                } else {
                    mime_guess::from_ext(ext)
                        .first_raw()
                        .map(|s| s.to_owned())
                        .unwrap_or_else(|| DEFAULT_MIME.to_owned())
                }
            }
            None => DEFAULT_MIME.to_owned(),
        }
    } else {
        DEFAULT_MIME.to_owned()
    }
}