JustKozrhik commited on
Commit
6a093f6
·
verified ·
1 Parent(s): 86f1e72

Delete src/src/loader.rs

Browse files
Files changed (1) hide show
  1. src/src/loader.rs +0 -199
src/src/loader.rs DELETED
@@ -1,199 +0,0 @@
1
- //! Скачивание файла по ссылке: лимит размера, таймаут, защита от обращений во внутреннюю сеть.
2
-
3
- use std::fmt;
4
- use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
5
- use std::time::Duration;
6
-
7
- use reqwest::{redirect, Client, Url};
8
-
9
- #[derive(Debug, Clone)]
10
- pub struct LoaderConfig {
11
- pub max_bytes: usize,
12
- pub timeout: Duration,
13
- }
14
-
15
- impl Default for LoaderConfig {
16
- fn default() -> Self {
17
- LoaderConfig {
18
- max_bytes: 10 * 1024 * 1024,
19
- timeout: Duration::from_millis(1500),
20
- }
21
- }
22
- }
23
-
24
- #[derive(Debug)]
25
- pub enum LoadError {
26
- InvalidUrl(String),
27
- Forbidden(String),
28
- Request(String),
29
- Status(u16),
30
- TooLarge(usize),
31
- Timeout,
32
- }
33
-
34
- impl fmt::Display for LoadError {
35
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36
- match self {
37
- LoadError::InvalidUrl(m) => write!(f, "некорректная ссылка: {m}"),
38
- LoadError::Forbidden(m) => write!(f, "ссылка запрещена: {m}"),
39
- LoadError::Request(m) => write!(f, "не удалось скачать файл: {m}"),
40
- LoadError::Status(c) => write!(f, "сервер ответил кодом {c}"),
41
- LoadError::TooLarge(n) => write!(f, "файл больше {n} байт"),
42
- LoadError::Timeout => write!(f, "превышено время ожидания при скачивании"),
43
- }
44
- }
45
- }
46
-
47
- impl std::error::Error for LoadError {}
48
-
49
- fn is_public_v4(ip: Ipv4Addr) -> bool {
50
- let o = ip.octets();
51
- !(ip.is_loopback()
52
- || ip.is_private()
53
- || ip.is_link_local()
54
- || ip.is_unspecified()
55
- || ip.is_broadcast()
56
- || ip.is_documentation()
57
- || o[0] == 0
58
- || (o[0] == 100 && (o[1] & 0xC0) == 64)) // 100.64.0.0/10
59
- }
60
-
61
- fn is_public_v6(ip: Ipv6Addr) -> bool {
62
- if let Some(v4) = ip.to_ipv4_mapped() {
63
- return is_public_v4(v4);
64
- }
65
- let s = ip.segments();
66
- !(ip.is_loopback()
67
- || ip.is_unspecified()
68
- || (s[0] & 0xfe00) == 0xfc00 // fc00::/7
69
- || (s[0] & 0xffc0) == 0xfe80) // fe80::/10
70
- }
71
-
72
- /// Разрешён ли хост: только публичные адреса, без localhost и служебных зон.
73
- /// DNS-имена, резолвящиеся во внутренние адреса, эта проверка не ловит.
74
- pub fn host_allowed(url: &Url) -> bool {
75
- if !matches!(url.scheme(), "http" | "https") {
76
- return false;
77
- }
78
- let host = match url.host_str() {
79
- Some(h) => h.trim_start_matches('[').trim_end_matches(']').to_ascii_lowercase(),
80
- None => return false,
81
- };
82
- if let Ok(ip) = host.parse::<IpAddr>() {
83
- return match ip {
84
- IpAddr::V4(v4) => is_public_v4(v4),
85
- IpAddr::V6(v6) => is_public_v6(v6),
86
- };
87
- }
88
- !(host == "localhost"
89
- || host.ends_with(".localhost")
90
- || host.ends_with(".local")
91
- || host.ends_with(".internal"))
92
- }
93
-
94
- /// Тело запроса → проверенный URL.
95
- pub fn parse_url(text: &str) -> Result<Url, LoadError> {
96
- let t = text.trim();
97
- if t.is_empty() {
98
- return Err(LoadError::InvalidUrl("пустое тело запроса, ожидается прямая ссылка".into()));
99
- }
100
- let url = Url::parse(t).map_err(|e| LoadError::InvalidUrl(e.to_string()))?;
101
- if !matches!(url.scheme(), "http" | "https") {
102
- return Err(LoadError::InvalidUrl("поддерживаются только http и https".into()));
103
- }
104
- if !host_allowed(&url) {
105
- return Err(LoadError::Forbidden("адрес локальный или служебный".into()));
106
- }
107
- Ok(url)
108
- }
109
-
110
- pub fn build_client(cfg: &LoaderConfig) -> Result<Client, reqwest::Error> {
111
- let policy = redirect::Policy::custom(|attempt| {
112
- if attempt.previous().len() >= 5 {
113
- attempt.error("слишком много перенаправлений")
114
- } else if !host_allowed(attempt.url()) {
115
- attempt.error("перенаправление на запрещённый адрес")
116
- } else {
117
- attempt.follow()
118
- }
119
- });
120
- Client::builder()
121
- .timeout(cfg.timeout)
122
- .connect_timeout(Duration::from_millis(1000))
123
- .redirect(policy)
124
- .user_agent("litematic-host/0.1")
125
- .build()
126
- }
127
-
128
- fn map_err(e: reqwest::Error) -> LoadError {
129
- if e.is_timeout() {
130
- LoadError::Timeout
131
- } else {
132
- LoadError::Request(e.to_string())
133
- }
134
- }
135
-
136
- /// Скачивает файл, не читая больше `cfg.max_bytes`.
137
- pub async fn download(client: &Client, url: Url, cfg: &LoaderConfig) -> Result<Vec<u8>, LoadError> {
138
- let mut resp = client.get(url).send().await.map_err(map_err)?;
139
- if !resp.status().is_success() {
140
- return Err(LoadError::Status(resp.status().as_u16()));
141
- }
142
- if let Some(len) = resp.content_length() {
143
- if len > cfg.max_bytes as u64 {
144
- return Err(LoadError::TooLarge(cfg.max_bytes));
145
- }
146
- }
147
- let mut buf: Vec<u8> = Vec::new();
148
- while let Some(chunk) = resp.chunk().await.map_err(map_err)? {
149
- if buf.len() + chunk.len() > cfg.max_bytes {
150
- return Err(LoadError::TooLarge(cfg.max_bytes));
151
- }
152
- buf.extend_from_slice(&chunk);
153
- }
154
- Ok(buf)
155
- }
156
-
157
- #[cfg(test)]
158
- mod tests {
159
- use super::*;
160
-
161
- #[test]
162
- fn accepts_public_urls() {
163
- assert!(parse_url("https://example.com/a.litematic").is_ok());
164
- assert!(parse_url(" http://8.8.8.8/x \n").is_ok());
165
- assert!(parse_url("https://cdn.example.com/file?id=1&x=2").is_ok());
166
- }
167
-
168
- #[test]
169
- fn rejects_bad_input() {
170
- assert!(matches!(parse_url(""), Err(LoadError::InvalidUrl(_))));
171
- assert!(matches!(parse_url(" "), Err(LoadError::InvalidUrl(_))));
172
- assert!(matches!(parse_url("not a url"), Err(LoadError::InvalidUrl(_))));
173
- assert!(matches!(parse_url("ftp://example.com/a"), Err(LoadError::InvalidUrl(_))));
174
- assert!(matches!(parse_url("file:///etc/passwd"), Err(LoadError::InvalidUrl(_))));
175
- }
176
-
177
- #[test]
178
- fn rejects_internal_hosts() {
179
- for u in [
180
- "http://localhost/x",
181
- "http://foo.localhost/x",
182
- "http://127.0.0.1:8080/x",
183
- "http://10.0.0.1/",
184
- "http://192.168.1.1/",
185
- "http://172.16.0.1/",
186
- "http://169.254.169.254/latest/meta-data",
187
- "http://100.64.0.1/",
188
- "http://0.0.0.0/",
189
- "http://[::1]/",
190
- "http://[fe80::1]/",
191
- "http://[fd00::1]/",
192
- "http://[::ffff:127.0.0.1]/",
193
- "http://2130706433/",
194
- "http://printer.local/",
195
- ] {
196
- assert!(matches!(parse_url(u), Err(LoadError::Forbidden(_))), "{u}");
197
- }
198
- }
199
- }