Skip to main content

teloxide_core/
net.rs

1//! Network-specific API.
2
3use std::{io, time::Duration};
4
5pub use self::download::{download_file, download_file_stream, Download};
6
7pub(crate) use self::{
8    request::{request_json, request_multipart},
9    telegram_response::TelegramResponse,
10};
11
12mod download;
13mod request;
14mod telegram_response;
15
16/// The default Telegram API URL.
17pub const TELEGRAM_API_URL: &str = "https://api.telegram.org";
18
19pub(super) const REQUEST_TIMEOUT: Duration = Duration::from_secs(17);
20
21/// Constructs a network client from the `TELOXIDE_PROXY` environmental
22/// variable.
23///
24/// This function passes the value of `TELOXIDE_PROXY` into
25/// [`reqwest::Proxy::all`], if it exists, otherwise returns the default
26/// client.
27///
28/// ## Note
29///
30/// The created client will have safe settings, meaning that it will be able to
31/// work in long time durations, see the [issue 223].
32///
33/// [`reqwest::Proxy::all`]: https://docs.rs/reqwest/latest/reqwest/struct.Proxy.html#method.all
34/// [issue 223]: https://github.com/teloxide/teloxide/issues/223
35///
36/// ## Panics
37///
38/// If `TELOXIDE_PROXY` exists, but isn't correct url.
39#[must_use]
40pub fn client_from_env() -> reqwest::Client {
41    use reqwest::Proxy;
42
43    const TELOXIDE_PROXY: &str = "TELOXIDE_PROXY";
44
45    let builder = default_reqwest_settings();
46
47    match std::env::var(TELOXIDE_PROXY).ok() {
48        Some(proxy) => builder.proxy(Proxy::all(proxy).expect("reqwest::Proxy creation failed")),
49        None => builder,
50    }
51    .build()
52    .expect("creating reqwest::Client")
53}
54
55/// Returns a reqwest client builder with default settings.
56///
57/// Client built from default settings is supposed to work over long time
58/// durations, see the [issue 223].
59///
60/// The current settings are:
61///  - A connection timeout of 5 seconds.
62///  - A timeout of 17 seconds.
63///  - `tcp_nodelay` is on.
64///  - Referer headers and cross-origin redirects are disabled.
65///
66/// ## Notes
67///
68/// 1. The settings may change in the future.
69/// 2. Long polling uses a per-request timeout based on the Telegram timeout.
70/// 3. If you alter the current settings listed above, your bot will not be
71///    guaranteed to work over long time durations.
72///
73/// [issue 223]: https://github.com/teloxide/teloxide/issues/223
74pub fn default_reqwest_settings() -> reqwest::ClientBuilder {
75    reqwest::Client::builder()
76        .connect_timeout(Duration::from_secs(5))
77        .timeout(REQUEST_TIMEOUT)
78        .tcp_nodelay(true)
79        .referer(false)
80        .redirect(reqwest::redirect::Policy::custom(|attempt| {
81            if attempt.previous().len() >= 10 {
82                return attempt.error("too many redirects");
83            }
84            if attempt.previous().first().is_some_and(|url| url.origin() == attempt.url().origin())
85            {
86                attempt.follow()
87            } else {
88                attempt.error("cross-origin redirect blocked")
89            }
90        }))
91}
92
93/// Creates URL for making HTTPS requests. See the [Telegram documentation].
94///
95/// [Telegram documentation]: https://core.telegram.org/bots/api#making-requests
96fn method_url(base: reqwest::Url, token: &str, method_name: &str) -> reqwest::Url {
97    let mut url = base;
98    {
99        let mut segments = url.path_segments_mut().expect("base URL cannot be a cannot-be-a-base");
100        segments.pop_if_empty().push(&format!("bot{token}"));
101        segments.push(method_name);
102    }
103    url
104}
105
106/// Creates URL for downloading a file. See the [Telegram documentation].
107///
108/// [Telegram documentation]: https://core.telegram.org/bots/api#file
109fn file_url(mut base: reqwest::Url, token: &str, file_path: &str) -> io::Result<reqwest::Url> {
110    let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "invalid Telegram file path");
111    if file_path.contains(['\\', ':'])
112        || file_path.chars().any(char::is_control)
113        || file_path.split('/').any(|part| matches!(part, "" | "." | ".."))
114    {
115        return Err(invalid());
116    }
117    base.path_segments_mut()
118        .map_err(|()| invalid())?
119        .pop_if_empty()
120        .push("file")
121        .push(&format!("bot{token}"))
122        .extend(file_path.split('/'));
123    Ok(base)
124}
125
126#[cfg(test)]
127mod tests {
128    use crate::net::*;
129
130    #[test]
131    fn method_url_test() {
132        let url = method_url(
133            reqwest::Url::parse(TELEGRAM_API_URL).unwrap(),
134            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
135            "methodName",
136        );
137
138        assert_eq!(
139            url.as_str(),
140            "https://api.telegram.org/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/methodName"
141        );
142    }
143
144    #[test]
145    fn method_url_with_custom_url_test() {
146        let url = method_url(
147            reqwest::Url::parse("https://example.com/telegram/").unwrap(),
148            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
149            "methodName",
150        );
151
152        assert_eq!(
153	    url.as_str(),
154	    "https://example.com/telegram/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/methodName"
155	);
156    }
157
158    #[test]
159    fn file_url_test() {
160        let url = file_url(
161            reqwest::Url::parse(TELEGRAM_API_URL).unwrap(),
162            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
163            "photos/file_12.jpg",
164        )
165        .unwrap();
166
167        assert_eq!(
168            url.as_str(),
169            "https://api.telegram.org/file/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/photos/file_12.jpg"
170        );
171    }
172
173    #[test]
174    fn file_url_with_custom_url_test() {
175        let url = file_url(
176            reqwest::Url::parse("https://example.com/telegram/").unwrap(),
177            "535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao",
178            "photos/file_12.jpg",
179        )
180        .unwrap();
181
182        assert_eq!(
183	    url.as_str(),
184	    "https://example.com/telegram/file/bot535362388:AAF7-g0gYncWnm5IyfZlpPRqRRv6kNAGlao/photos/file_12.jpg"
185	);
186    }
187
188    fn reply_server(
189        responses: Vec<String>,
190    ) -> (reqwest::Url, std::thread::JoinHandle<Vec<String>>) {
191        use std::{
192            io::{BufRead, BufReader, Write},
193            net::TcpListener,
194        };
195        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
196        let url = format!("http://{}/prefix/", listener.local_addr().unwrap()).parse().unwrap();
197        let server = std::thread::spawn(move || {
198            responses
199                .into_iter()
200                .map(|response| {
201                    let (mut conn, _) = listener.accept().unwrap();
202                    conn.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
203                    let mut reader = BufReader::new(&mut conn);
204                    let mut headers = String::new();
205                    loop {
206                        let start = headers.len();
207                        if reader.read_line(&mut headers).unwrap() == 0
208                            || &headers[start..] == "\r\n"
209                        {
210                            break;
211                        }
212                    }
213                    conn.write_all(response.as_bytes()).unwrap();
214                    headers
215                })
216                .collect()
217        });
218        (url, server)
219    }
220
221    #[tokio::test]
222    async fn default_redirects_never_send_referer_or_cross_origin() {
223        use futures::TryStreamExt;
224        let client = default_reqwest_settings().build().unwrap();
225        let (url, server) = reply_server(vec![
226            "HTTP/1.1 302 Found\r\nLocation: /other\r\nContent-Length: 0\r\nConnection: \
227             close\r\n\r\n"
228                .to_owned(),
229            "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_owned(),
230        ]);
231        let body = download_file_stream(&client, url, "secret-token", "photos/file_12.jpg")
232            .try_collect::<Vec<_>>()
233            .await
234            .unwrap();
235        assert_eq!(body.concat(), b"ok");
236        let headers = server.join().unwrap();
237        assert!(headers[0].starts_with("GET /prefix/file/botsecret-token/photos/file_12.jpg "));
238        assert!(headers[1].starts_with("GET /other "));
239        assert!(!headers[1].to_ascii_lowercase().contains("referer:"));
240
241        let other = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
242        other.set_nonblocking(true).unwrap();
243        let (url, server) = reply_server(vec![format!(
244            "HTTP/1.1 302 Found\r\nLocation: http://{}/botsecret-token\r\nContent-Length: \
245             0\r\nConnection: close\r\n\r\n",
246            other.local_addr().unwrap()
247        )]);
248        let err = download_file_stream(&client, url, "secret-token", "photos/file_12.jpg")
249            .try_collect::<Vec<_>>()
250            .await
251            .unwrap_err();
252        assert!(!format!("{err} {err:?}").contains("secret-token"));
253        assert!(
254            matches!(err, crate::DownloadError::Network(error) if error.is_redirect() && error.url().is_none())
255        );
256        assert_eq!(other.accept().unwrap_err().kind(), io::ErrorKind::WouldBlock);
257        server.join().unwrap();
258    }
259
260    #[test]
261    fn special_download_paths_are_not_url_components() {
262        for path in [
263            "",
264            "/etc/passwd",
265            "photos/../etc",
266            "photos/./foo",
267            "photos//foo",
268            "https://other/file",
269            "C:\\photo.jpg",
270        ] {
271            assert!(file_url(TELEGRAM_API_URL.parse().unwrap(), "token", path).is_err(), "{path}");
272        }
273        let url =
274            file_url(TELEGRAM_API_URL.parse().unwrap(), "token", "photos/%2e%2e?q#f").unwrap();
275        assert_eq!(url.path(), "/file/bottoken/photos/%252e%252e%3Fq%23f");
276    }
277
278    #[tokio::test]
279    async fn long_poll_hint_overrides_the_client_timeout() {
280        use crate::{payloads::GetUpdatesSetters, requests::Requester, Bot};
281        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
282        let url = format!("http://{}", listener.local_addr().unwrap()).parse().unwrap();
283        let server = std::thread::spawn(move || {
284            use std::io::{BufRead, BufReader, Write};
285            let (mut conn, _) = listener.accept().unwrap();
286            conn.set_read_timeout(Some(Duration::from_secs(2))).unwrap();
287            let mut reader = BufReader::new(&mut conn);
288            loop {
289                let mut line = String::new();
290                if reader.read_line(&mut line).unwrap() == 0 || line == "\r\n" {
291                    break;
292                }
293            }
294            std::thread::sleep(Duration::from_millis(100));
295            let body = r#"{"ok":true,"result":[]}"#;
296            write!(
297                conn,
298                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
299                body.len()
300            )
301            .unwrap();
302        });
303        let client = default_reqwest_settings().timeout(Duration::from_millis(20)).build().unwrap();
304        let bot = Bot::with_client("poll-token", client).set_api_url(url);
305        assert!(bot.get_updates().timeout(1).await.unwrap().is_empty());
306        server.join().unwrap();
307    }
308}