Spaces:
Sleeping
Sleeping
File size: 6,847 Bytes
7178525 42327ea 7178525 42327ea 7178525 | 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 | //! Скачивание файла по ссылке: лимит размера, таймаут, защита от обращений во внутреннюю сеть.
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::time::Duration;
use reqwest::{redirect, Client, Url};
#[derive(Debug, Clone)]
pub struct LoaderConfig {
pub max_bytes: usize,
pub timeout: Duration,
}
impl Default for LoaderConfig {
fn default() -> Self {
LoaderConfig {
max_bytes: 10 * 1024 * 1024,
timeout: Duration::from_millis(1500),
}
}
}
#[derive(Debug)]
pub enum LoadError {
InvalidUrl(String),
Forbidden(String),
Request(String),
Status(u16),
TooLarge(usize),
Timeout,
}
impl fmt::Display for LoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
LoadError::InvalidUrl(m) => write!(f, "некорректная ссылка: {m}"),
LoadError::Forbidden(m) => write!(f, "ссылка запрещена: {m}"),
LoadError::Request(m) => write!(f, "не удалось скачать файл: {m}"),
LoadError::Status(c) => write!(f, "сервер ответил кодом {c}"),
LoadError::TooLarge(n) => write!(f, "файл больше {n} байт"),
LoadError::Timeout => write!(f, "превышено время ожидания при скачивании"),
}
}
}
impl std::error::Error for LoadError {}
fn is_public_v4(ip: Ipv4Addr) -> bool {
let o = ip.octets();
!(ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| ip.is_unspecified()
|| ip.is_broadcast()
|| ip.is_documentation()
|| o[0] == 0
|| (o[0] == 100 && (o[1] & 0xC0) == 64)) // 100.64.0.0/10
}
fn is_public_v6(ip: Ipv6Addr) -> bool {
if let Some(v4) = ip.to_ipv4_mapped() {
return is_public_v4(v4);
}
let s = ip.segments();
!(ip.is_loopback()
|| ip.is_unspecified()
|| (s[0] & 0xfe00) == 0xfc00 // fc00::/7
|| (s[0] & 0xffc0) == 0xfe80) // fe80::/10
}
/// Разрешён ли хост: только публичные адреса, без localhost и служебных зон.
/// DNS-имена, резолвящиеся во внутренние адреса, эта проверка не ловит.
pub fn host_allowed(url: &Url) -> bool {
if !matches!(url.scheme(), "http" | "https") {
return false;
}
let host = match url.host_str() {
Some(h) => h.trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase(),
None => return false,
};
if let Ok(ip) = host.parse::<IpAddr>() {
return match ip {
IpAddr::V4(v4) => is_public_v4(v4),
IpAddr::V6(v6) => is_public_v6(v6),
};
}
!(host == "localhost"
|| host.ends_with(".localhost")
|| host.ends_with(".local")
|| host.ends_with(".internal"))
}
/// Тело запроса → проверенный URL.
pub fn parse_url(text: &str) -> Result<Url, LoadError> {
let t = text.trim();
if t.is_empty() {
return Err(LoadError::InvalidUrl("пустое тело запроса, ожидается прямая ссылка".into()));
}
let url = Url::parse(t).map_err(|e| LoadError::InvalidUrl(e.to_string()))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(LoadError::InvalidUrl("поддерживаются только http и https".into()));
}
if !host_allowed(&url) {
return Err(LoadError::Forbidden("адрес локальный или служебный".into()));
}
Ok(url)
}
pub fn build_client(cfg: &LoaderConfig) -> Result<Client, reqwest::Error> {
let policy = redirect::Policy::custom(|attempt| {
if attempt.previous().len() >= 5 {
attempt.error("слишком много перенаправлений")
} else if !host_allowed(attempt.url()) {
attempt.error("перенаправление на запрещённый адрес")
} else {
attempt.follow()
}
});
Client::builder()
.timeout(cfg.timeout)
.connect_timeout(Duration::from_millis(1000))
.redirect(policy)
.user_agent("litematic-host/0.1")
.build()
}
fn map_err(e: reqwest::Error) -> LoadError {
if e.is_timeout() {
LoadError::Timeout
} else {
LoadError::Request(e.to_string())
}
}
/// Скачивает файл, не читая больше `cfg.max_bytes`.
pub async fn download(client: &Client, url: Url, cfg: &LoaderConfig) -> Result<Vec<u8>, LoadError> {
let mut resp = client.get(url).send().await.map_err(map_err)?;
if !resp.status().is_success() {
return Err(LoadError::Status(resp.status().as_u16()));
}
if let Some(len) = resp.content_length() {
if len > cfg.max_bytes as u64 {
return Err(LoadError::TooLarge(cfg.max_bytes));
}
}
let mut buf: Vec<u8> = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(map_err)? {
if buf.len() + chunk.len() > cfg.max_bytes {
return Err(LoadError::TooLarge(cfg.max_bytes));
}
buf.extend_from_slice(&chunk);
}
Ok(buf)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_public_urls() {
assert!(parse_url("https://example.com/a.litematic").is_ok());
assert!(parse_url(" http://8.8.8.8/x \n").is_ok());
assert!(parse_url("https://cdn.example.com/file?id=1&x=2").is_ok());
}
#[test]
fn rejects_bad_input() {
assert!(matches!(parse_url(""), Err(LoadError::InvalidUrl(_))));
assert!(matches!(parse_url(" "), Err(LoadError::InvalidUrl(_))));
assert!(matches!(parse_url("not a url"), Err(LoadError::InvalidUrl(_))));
assert!(matches!(parse_url("ftp://example.com/a"), Err(LoadError::InvalidUrl(_))));
assert!(matches!(parse_url("file:///etc/passwd"), Err(LoadError::InvalidUrl(_))));
}
#[test]
fn rejects_internal_hosts() {
for u in [
"http://localhost/x",
"http://foo.localhost/x",
"http://127.0.0.1:8080/x",
"http://10.0.0.1/",
"http://192.168.1.1/",
"http://172.16.0.1/",
"http://169.254.169.254/latest/meta-data",
"http://100.64.0.1/",
"http://0.0.0.0/",
"http://[::1]/",
"http://[fe80::1]/",
"http://[fd00::1]/",
"http://[::ffff:127.0.0.1]/",
"http://2130706433/",
"http://printer.local/",
] {
assert!(matches!(parse_url(u), Err(LoadError::Forbidden(_))), "{u}");
}
}
}
|