RustPrinter / src /loader.rs
JustKozrhik's picture
Upload 12 files
42327ea verified
Raw History Blame Contribute Delete
6.85 kB
//! Скачивание файла по ссылке: лимит размера, таймаут, защита от обращений во внутреннюю сеть.
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}");
}
}
}