ureq 3.4.2

Simple, safe HTTP client
Documentation
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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::Arc;
use std::{fmt, io, time};

use crate::config::Config;
use crate::unversioned::transport::time::Instant;
use crate::util::IoResultExt;
use crate::{Error, Timeout};

use super::ResolvedSocketAddrs;
use super::chain::Either;

use super::time::Duration;
use super::{Buffers, ConnectionDetails, Connector, LazyBuffers, NextTimeout, Transport};

#[derive(Default)]
/// Connector for regular TCP sockets.
pub struct TcpConnector(());

impl<In: Transport> Connector<In> for TcpConnector {
    type Out = Either<In, TcpTransport>;

    fn connect(
        &self,
        details: &ConnectionDetails,
        chained: Option<In>,
    ) -> Result<Option<Self::Out>, Error> {
        if chained.is_some() {
            // The chained connection overrides whatever we were to open here.
            // In the DefaultConnector chain this would be a SOCKS proxy connection.
            trace!("Skip");
            return Ok(chained.map(Either::A));
        }

        let config = &details.config;
        let stream = try_connect(
            &details.addrs,
            details.now,
            details.timeout,
            details.current_time.clone(),
            config,
        )?;

        let buffers = LazyBuffers::new(config.input_buffer_size(), config.output_buffer_size());
        let transport = TcpTransport::new(stream, buffers);

        Ok(Some(Either::B(transport)))
    }
}

fn try_connect(
    addrs: &ResolvedSocketAddrs,
    start: Instant,
    timeout: NextTimeout,
    current_time: Arc<dyn Fn() -> Instant + Send + Sync + 'static>,
    config: &Config,
) -> Result<TcpStream, Error> {
    try_connect_with(addrs, start, timeout, current_time, |addr, per_addr| {
        try_connect_single(addr, per_addr, config)
    })
}

fn try_connect_with<T>(
    addrs: &ResolvedSocketAddrs,
    start: Instant,
    timeout: NextTimeout,
    current_time: Arc<dyn Fn() -> Instant + Send + Sync + 'static>,
    mut connect: impl FnMut(SocketAddr, Option<Duration>) -> Result<T, Error>,
) -> Result<T, Error> {
    // The idea here is to give each attempt a budget of the total time to try.
    // For a host returning multiple addresses, we share the budget between them
    // using a geometric series that sums to exactly the total budget.
    //
    // Background: https://curl.se/mail/lib-2021-01/0037.html
    //
    // Example: Timeout is 10 seconds, and the host returns 4 addresses.
    //
    // Address 0: 5.33 seconds (53.3% of budget)
    // Address 1: 2.67 seconds (26.7% of budget)
    // Address 2: 1.33 seconds (13.3% of budget)
    // Address 3: 0.67 seconds (6.7% of budget)
    // Sum: 10.0 seconds
    //
    // For a single address, it gets the full budget (100%).
    // We cap the lowest to 10ms.
    //
    const MIN_PER_ADDRESS_TIMEOUT: Duration = Duration::from_millis(10);

    let num_addrs = addrs.len();

    // Pre-calculate the total weight for the geometric series.
    // For weights [1, 1/2, 1/4, 1/8, ...], the sum is 2 * (1 - 1/2^n)
    let total_weight = 2.0 * (1.0 - 0.5_f64.powi(num_addrs as i32));

    // Start with weight 1.0 for the first address, then halve for each subsequent.
    let mut weight = 1.0_f64;

    // The most recent per-address failure, so that a host whose every address
    // fails reports what actually happened instead of a synthesized refusal.
    let mut last_err: Option<Error> = None;

    for addr in addrs {
        // Calculate this address's timeout using geometric series.
        let per_addr = timeout.not_zero().map(|t| {
            let secs = t.as_secs_f64() * weight / total_weight;
            let timeout = Duration::from_millis((secs * 1000.0) as u64);
            timeout.max(MIN_PER_ADDRESS_TIMEOUT)
        });

        match connect(*addr, per_addr) {
            // First that connects
            Ok(v) => return Ok(v),
            // Intercept errors that concern only this address to try next addrs
            Err(Error::Io(e)) if is_addr_specific_error(&e) => {
                trace!("{} failed: {}", addr, e);
                last_err = Some(Error::Io(e));
                continue;
            }
            Err(e @ Error::Timeout(_)) => {
                // Check if we hit the overall global timeout for the connect.
                let elapsed = current_time().duration_since(start);
                if elapsed > timeout.after {
                    return Err(Error::Timeout(timeout.reason));
                }

                // We still got time to try the next address.
                last_err = Some(e);
            }
            // Other errors bail
            Err(e) => return Err(e),
        }

        // Halve the weight for the next address
        weight /= 2.0;
    }

    debug!("Failed to connect to any resolved address");
    Err(last_err.unwrap_or_else(|| {
        Error::Io(io::Error::new(
            io::ErrorKind::ConnectionRefused,
            "Connection refused",
        ))
    }))
}

/// Whether a failed connect concerns only the address tried, meaning the next
/// resolved address might still succeed.
///
/// `ConnectionRefused` means this address answered and said no. The
/// unreachable/unavailable kinds mean the local network stack rejected this
/// address at routing level without asking anything: the typical case is a
/// host whose resolver returns IPv6 addresses first but which has no IPv6
/// route, where the AAAA connect fails instantly while the A record would
/// have worked (#1184). Browsers and curl mask that condition by moving on to
/// the next address, which is the behavior matched here.
fn is_addr_specific_error(e: &io::Error) -> bool {
    // On Windows, a VPN or firewall can surface the blocked address family as
    // WSAEACCES, which maps to ErrorKind::PermissionDenied. Match the raw OS
    // error to retry this socket error without retrying every permission error (#1184).
    #[cfg(windows)]
    const WSAEACCES: i32 = 10013;
    #[cfg(windows)]
    if e.raw_os_error() == Some(WSAEACCES) {
        return true;
    }

    matches!(
        e.kind(),
        io::ErrorKind::ConnectionRefused
            | io::ErrorKind::HostUnreachable
            | io::ErrorKind::NetworkUnreachable
            | io::ErrorKind::AddrNotAvailable
    )
}

fn try_connect_single(
    addr: SocketAddr,
    per_addr: Option<Duration>,
    config: &Config,
) -> Result<TcpStream, Error> {
    trace!("Try connect TcpStream to {}", addr);

    let maybe_stream = if let Some(when) = per_addr {
        TcpStream::connect_timeout(&addr, *when)
    } else {
        TcpStream::connect(addr)
    }
    .normalize_would_block();

    let stream = match maybe_stream {
        Ok(v) => v,
        Err(e) if e.kind() == io::ErrorKind::TimedOut => {
            // The parent replaces this reason if the overall deadline has expired.
            return Err(Error::Timeout(Timeout::Connect));
        }
        Err(e) => return Err(e.into()),
    };

    if config.no_delay() {
        stream.set_nodelay(true)?;
    }

    debug!("Connected TcpStream to {}", addr);

    Ok(stream)
}

pub struct TcpTransport {
    stream: TcpStream,
    buffers: LazyBuffers,
    timeout_write: Option<Duration>,
    timeout_read: Option<Duration>,
}

impl TcpTransport {
    pub fn new(stream: TcpStream, buffers: LazyBuffers) -> TcpTransport {
        TcpTransport {
            stream,
            buffers,
            timeout_read: None,
            timeout_write: None,
        }
    }
}

// The goal here is to only cause a syscall to set the timeout if it's necessary.
fn maybe_update_timeout(
    timeout: NextTimeout,
    previous: &mut Option<Duration>,
    stream: &TcpStream,
    f: impl Fn(&TcpStream, Option<time::Duration>) -> io::Result<()>,
) -> io::Result<()> {
    let maybe_timeout = timeout.not_zero();

    if maybe_timeout != *previous {
        (f)(stream, maybe_timeout.map(|t| *t))?;
        *previous = maybe_timeout;
    }

    Ok(())
}

impl Transport for TcpTransport {
    fn buffers(&mut self) -> &mut dyn Buffers {
        &mut self.buffers
    }

    fn transmit_output(&mut self, amount: usize, timeout: NextTimeout) -> Result<(), Error> {
        maybe_update_timeout(
            timeout,
            &mut self.timeout_write,
            &self.stream,
            TcpStream::set_write_timeout,
        )?;

        let output = &self.buffers.output()[..amount];
        match self.stream.write_all(output).normalize_would_block() {
            Ok(v) => Ok(v),
            Err(e) if e.kind() == io::ErrorKind::TimedOut => Err(Error::Timeout(timeout.reason)),
            Err(e) => Err(e.into()),
        }?;

        Ok(())
    }

    fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, Error> {
        // Proceed to fill the buffers from the TcpStream
        maybe_update_timeout(
            timeout,
            &mut self.timeout_read,
            &self.stream,
            TcpStream::set_read_timeout,
        )?;

        let input = self.buffers.input_append_buf();
        let amount = match self.stream.read(input).normalize_would_block() {
            Ok(v) => Ok(v),
            Err(e) if e.kind() == io::ErrorKind::TimedOut => Err(Error::Timeout(timeout.reason)),
            Err(e) => Err(e.into()),
        }?;
        self.buffers.input_appended(amount);

        Ok(amount > 0)
    }

    fn is_open(&mut self) -> bool {
        probe_tcp_stream(&mut self.stream).unwrap_or(false)
    }
}

fn probe_tcp_stream(stream: &mut TcpStream) -> Result<bool, Error> {
    // Temporary do non-blocking IO
    stream.set_nonblocking(true)?;

    let mut buf = [0];
    match stream.read(&mut buf) {
        Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
            // This is the correct condition. There should be no waiting
            // bytes, and therefore reading would block
        }
        // Any bytes read means the server sent some garbage we didn't ask for
        Ok(_) => {
            debug!("Unexpected bytes from server. Closing connection");
            return Ok(false);
        }
        // Errors such as closed connection
        Err(_) => return Ok(false),
    };

    // Reset back to blocking
    stream.set_nonblocking(false)?;

    Ok(true)
}

impl fmt::Debug for TcpConnector {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TcpConnector").finish()
    }
}

impl fmt::Debug for TcpTransport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TcpTransport")
            .field("addr", &self.stream.peer_addr().ok())
            .finish()
    }
}

#[cfg(test)]
mod test {
    use super::*;

    // Script connect outcomes so routing failures and timeouts are deterministic.
    fn scripted_connect(
        outcomes: Vec<Result<(), Error>>,
        elapsed: Duration,
    ) -> (Result<(), Error>, usize) {
        let mut addrs = ResolvedSocketAddrs::from_fn(|_| SocketAddr::from(([0, 0, 0, 0], 0)));
        for i in 0..outcomes.len() {
            addrs.push(SocketAddr::from(([127, 0, 0, 1], 10000 + i as u16)));
        }
        let start = Instant::now();
        let mut outcomes = outcomes.into_iter();
        let mut attempts = 0;
        let result = try_connect_with(
            &addrs,
            start,
            NextTimeout {
                after: Duration::from_secs(10),
                reason: Timeout::Global,
            },
            Arc::new(move || start + elapsed),
            |addr, _| {
                assert_eq!(addr, addrs[attempts]);
                attempts += 1;
                outcomes.next().unwrap()
            },
        );
        (result, attempts)
    }

    fn io_error(kind: io::ErrorKind) -> Result<(), Error> {
        Err(io::Error::from(kind).into())
    }

    #[test]
    fn timeout_replaces_earlier_unreachable_error() {
        let (result, attempts) = scripted_connect(
            vec![
                io_error(io::ErrorKind::NetworkUnreachable),
                Err(Error::Timeout(Timeout::Connect)),
            ],
            Duration::from_secs(6),
        );
        assert_eq!(attempts, 2);
        assert!(matches!(result, Err(Error::Timeout(Timeout::Connect))));
    }

    #[test]
    fn addr_specific_failures_and_timeout_fall_back_to_success() {
        for failure in [
            io_error(io::ErrorKind::ConnectionRefused),
            io_error(io::ErrorKind::HostUnreachable),
            io_error(io::ErrorKind::NetworkUnreachable),
            io_error(io::ErrorKind::AddrNotAvailable),
            Err(Error::Timeout(Timeout::Connect)),
        ] {
            let (result, attempts) = scripted_connect(
                vec![failure, Ok(()), io_error(io::ErrorKind::PermissionDenied)],
                Duration::from_secs(1),
            );
            assert!(result.is_ok());
            assert_eq!(attempts, 2);
        }
    }

    #[test]
    fn last_io_error_replaces_timeout_and_preserves_details() {
        let (result, attempts) = scripted_connect(
            vec![
                Err(Error::Timeout(Timeout::Connect)),
                Err(io::Error::new(io::ErrorKind::HostUnreachable, "last address").into()),
            ],
            Duration::from_secs(1),
        );
        assert_eq!(attempts, 2);
        let Err(Error::Io(error)) = result else {
            panic!("expected last I/O error: {result:?}");
        };
        assert_eq!(error.kind(), io::ErrorKind::HostUnreachable);
        assert_eq!(error.to_string(), "last address");
    }

    #[test]
    fn all_timeouts_report_connect_timeout() {
        let (result, attempts) = scripted_connect(
            vec![
                Err(Error::Timeout(Timeout::Connect)),
                Err(Error::Timeout(Timeout::Connect)),
            ],
            Duration::from_secs(6),
        );
        assert_eq!(attempts, 2);
        assert!(matches!(result, Err(Error::Timeout(Timeout::Connect))));
    }

    #[test]
    fn overall_timeout_takes_precedence_and_stops_attempts() {
        let (result, attempts) = scripted_connect(
            vec![
                io_error(io::ErrorKind::NetworkUnreachable),
                Err(Error::Timeout(Timeout::Connect)),
                Ok(()),
            ],
            Duration::from_secs(11),
        );
        assert_eq!(attempts, 2);
        assert!(matches!(result, Err(Error::Timeout(Timeout::Global))));
    }

    #[test]
    fn other_io_errors_stop_attempts() {
        let (result, attempts) = scripted_connect(
            vec![io_error(io::ErrorKind::PermissionDenied), Ok(())],
            Duration::from_secs(1),
        );
        assert_eq!(attempts, 1);
        assert!(matches!(result, Err(Error::Io(e)) if e.kind() == io::ErrorKind::PermissionDenied));
    }

    #[test]
    fn empty_address_list_reports_refusal() {
        let (result, attempts) = scripted_connect(vec![], Duration::from_secs(0));
        assert_eq!(attempts, 0);
        assert!(
            matches!(result, Err(Error::Io(e)) if e.kind() == io::ErrorKind::ConnectionRefused)
        );
    }

    #[test]
    fn addr_specific_errors_try_the_next_addr() {
        for kind in [
            io::ErrorKind::ConnectionRefused,
            io::ErrorKind::HostUnreachable,
            io::ErrorKind::NetworkUnreachable,
            io::ErrorKind::AddrNotAvailable,
        ] {
            assert!(
                is_addr_specific_error(&io::Error::from(kind)),
                "{kind:?} should move on to the next address"
            );
        }
        for kind in [io::ErrorKind::TimedOut, io::ErrorKind::PermissionDenied] {
            assert!(
                !is_addr_specific_error(&io::Error::from(kind)),
                "{kind:?} should bail"
            );
        }
    }

    #[test]
    #[cfg(windows)]
    fn wsaeacces_tries_the_next_addr() {
        assert!(is_addr_specific_error(&io::Error::from_raw_os_error(10013)));
    }
}