ureq 3.4.0

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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
#![allow(clippy::type_complexity)]

use std::cell::RefCell;
use std::io::Write;
use std::sync::mpsc::{self, Receiver, RecvTimeoutError};
use std::sync::{Arc, Mutex};
use std::{fmt, io, thread};

use http::{Method, Request, Uri};
use ureq_proto::parser::try_parse_request;

use crate::Error;
use crate::http;

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

#[derive(Default)]
pub(crate) struct TestConnector;

thread_local!(static HANDLERS: RefCell<Vec<TestHandler>> = const { RefCell::new(Vec::new()) });

impl<In: Transport> Connector<In> for TestConnector {
    type Out = Either<In, TestTransport>;

    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.
            trace!("Skip");
            return Ok(chained.map(Either::A));
        }
        let config = details.config;

        // Let ConnectProxyConnector handle the target connection. Its recursive
        // connection to the proxy uses a config without a proxy and is intercepted
        // by this connector, keeping the entire test in memory.
        let use_connect_proxy = config.connect_proxy_uri().is_some()
            && config
                .proxy()
                .is_some_and(|proxy| !proxy.is_no_proxy(details.uri));
        if use_connect_proxy {
            trace!("Defer to CONNECT proxy");
            return Ok(None);
        }

        let uri = details.uri.clone();
        debug!("Test uri: {}", uri);

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

        let (tx1, rx1) = mpsc::sync_channel(10);
        let (tx2, rx2) = mpsc::sync_channel(10);

        let mut handlers = HANDLERS.with(|h| (*h).borrow().clone());
        setup_default_handlers(&mut handlers);

        thread::spawn(|| test_run(uri, rx1, tx2, handlers));

        let transport = TestTransport {
            buffers,
            tx: tx1,
            rx: SyncReceiver(Mutex::new(rx2)),
            connected_tx: true,
            connected_rx: true,
        };

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

impl TestHandler {
    fn new(
        pattern: &'static str,
        handler: impl Fn(Uri, Request<()>, &mut dyn Write) -> io::Result<()> + Send + Sync + 'static,
    ) -> Self {
        TestHandler {
            pattern,
            handler: Handler::Http(Arc::new(handler)),
        }
    }

    #[cfg(feature = "_ring")]
    fn new_tls_tunnel(
        pattern: &'static str,
        handler: impl Fn(Uri, Request<()>, &mut dyn io::Read, &mut dyn Write) -> io::Result<()>
        + Send
        + Sync
        + 'static,
    ) -> Self {
        TestHandler {
            pattern,
            handler: Handler::TlsTunnel(Arc::new(handler)),
        }
    }
}

/// Helper for **_test** feature tests.
#[cfg(feature = "_test")]
#[doc(hidden)]
pub fn set_handler(pattern: &'static str, status: u16, headers: &[(&str, &str)], body: &[u8]) {
    // Convert headers to a big string
    let mut headers_s = String::new();
    for (k, v) in headers {
        headers_s.push_str(&format!("{}: {}\r\n", k, v));
    }

    // Convert body to an owned vec
    let body = body.to_vec();

    let handler = TestHandler::new(pattern, move |_uri, _req, w| {
        write!(
            w,
            "HTTP/1.1 {} OK\r\n\
            {}\
            \r\n",
            status, headers_s
        )?;
        w.write_all(&body)
    });

    HANDLERS.with(|h| (*h).borrow_mut().push(handler));
}

/// Helper for **_test** feature tests that need to inspect the request.
#[cfg(feature = "_test")]
#[doc(hidden)]
pub fn set_handler_cb(
    pattern: &'static str,
    status: u16,
    headers: &[(&str, &str)],
    body: &[u8],
    cb: impl Fn(&Request<()>) + Send + Sync + 'static,
) {
    // Convert headers to a big string
    let mut headers_s = String::new();
    for (k, v) in headers {
        headers_s.push_str(&format!("{}: {}\r\n", k, v));
    }

    // Convert body to an owned vec
    let body = body.to_vec();

    let handler = TestHandler::new(pattern, move |_uri, req, w| {
        // Run the request check (can panic if assertions fail)
        cb(&req);

        write!(
            w,
            "HTTP/1.1 {} OK\r\n\
            {}\
            \r\n",
            status, headers_s
        )?;
        w.write_all(&body)
    });

    HANDLERS.with(|h| (*h).borrow_mut().push(handler));
}

#[derive(Clone)]
struct TestHandler {
    pattern: &'static str,
    handler: Handler,
}

#[derive(Clone)]
enum Handler {
    Http(Arc<dyn Fn(Uri, Request<()>, &mut dyn Write) -> io::Result<()> + Sync + Send>),
    #[cfg(feature = "_ring")]
    TlsTunnel(
        Arc<
            dyn Fn(Uri, Request<()>, &mut dyn io::Read, &mut dyn Write) -> io::Result<()>
                + Sync
                + Send,
        >,
    ),
}

fn test_run(
    uri: Uri,
    rx: Receiver<Vec<u8>>,
    tx: mpsc::SyncSender<Vec<u8>>,
    handlers: Vec<TestHandler>,
) {
    let mut reader = SaneBufReader(Some(RxRead(rx)), vec![]);
    let mut writer = TxWrite(tx);
    let uri_s = uri.to_string();

    let req = loop {
        let input = reader.fill_buf().expect("test fill_buf");
        let maybe = try_parse_request::<100>(input).expect("test parse request");
        if let Some((amount, req)) = maybe {
            reader.consume(amount);
            break req;
        } else {
            continue;
        }
    };

    for handler in handlers {
        if uri_s.contains(handler.pattern) {
            match handler.handler {
                Handler::Http(handler) => {
                    handler(uri, req, &mut writer).expect("test handler to not fail")
                }
                #[cfg(feature = "_ring")]
                Handler::TlsTunnel(handler) => handler(uri, req, &mut reader, &mut writer)
                    .expect("test TLS tunnel handler to not fail"),
            }
            return;
        }
    }

    panic!("test server unhandled url: {}", uri);
}

fn setup_default_handlers(handlers: &mut Vec<TestHandler>) {
    fn maybe_add(handler: TestHandler, handlers: &mut Vec<TestHandler>) {
        let already_declared = handlers.iter().any(|h| h.pattern == handler.pattern);
        if !already_declared {
            handlers.push(handler);
        }
    }

    maybe_add(
        TestHandler::new("www.google.com", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: text/html;charset=ISO-8859-1\r\n\
                set-cookie: AEC=AVYB7cpadYFS8ZgaioQ17NnxHl1QcSQ_2aH2WEIg1KGDXD5kjk2HhpGVhfk; \
                    expires=Mon, 14-Apr-2050 17:23:39 GMT; path=/; domain=.google.com; \
                    Secure; HttpOnly; SameSite=lax\r\n\
                set-cookie: __Secure-ENID=23.SE=WaDe-mOBoV2nk-IwHr73boNt6dYcjzQh1X_k8zv2UmUXBL\
                    m80a3pzLJyx1N1NOqBxDDOR8OJyvuNYw5phFf0VnbqzVtcKPijo2FY8O_vymzyc7x2VwFhGlgU\
                    WXSWYinjWL7Zvz_EOcA4kfnEXweW5ZDzLrvaLuBIrz5CA_-454AMIXpDiZAVPChCawbkzMptAr\
                    lMTikkon2EQVXsicqq1XnrMEMPZR5Ld2JC6lpBM8A; expires=Sun, 16-Nov-2050 09:41:57 \
                    GMT; path=/; domain=.google.com; Secure; HttpOnly; SameSite=lax\r\n\
                \r\n\
                ureq test server here"
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("example.com", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: text/html;charset=UTF-8\r\n\
                \r\n\
                ureq test server here"
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/bytes/100", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/octet-stream\r\n\
                Content-Length: 100\r\n\
                \r\n"
            )?;
            write!(w, "{}", "1".repeat(100))
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/bytes/200000000", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/octet-stream\r\n\
                Content-Length: 100\r\n\
                \r\n"
            )?;
            // We don't actually want 200MB of data in memory.
            write!(w, "{}", "1".repeat(100))
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/get", |_uri, req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_GET.len()
            )?;
            if req.method() != Method::HEAD {
                w.write_all(HTTPBIN_GET.as_bytes())?;
            }
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/?query=foo", |_uri, req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_GET.len()
            )?;
            if req.method() != Method::HEAD {
                w.write_all(HTTPBIN_GET.as_bytes())?;
            }
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/head", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_GET.len()
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/put", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_PUT.len()
            )?;
            w.write_all(HTTPBIN_PUT.as_bytes())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/post", |_uri, req, w| {
            // Check if there's an x-verify-content-type header to verify against
            if let Some(expected_ct) = req.headers().get("x-verify-content-type") {
                let expected_ct_str = expected_ct.to_str().unwrap();
                let actual_ct = req.headers().get("content-type");

                match actual_ct {
                    Some(ct) => {
                        let actual_ct_str = ct.to_str().unwrap();
                        if expected_ct_str.starts_with("multipart/form-data") {
                            // For multipart, just check it starts with the expected prefix
                            assert!(
                                actual_ct_str.starts_with("multipart/form-data; boundary="),
                                "Expected multipart/form-data with boundary, got: {}",
                                actual_ct_str
                            );
                        } else {
                            assert_eq!(
                                actual_ct_str, expected_ct_str,
                                "Content-Type mismatch: expected '{}', got '{}'",
                                expected_ct_str, actual_ct_str
                            );
                        }
                    }
                    None => panic!(
                        "Expected Content-Type '{}' but no Content-Type header found",
                        expected_ct_str
                    ),
                }
            }

            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                    Content-Type: application/json\r\n\
                    Content-Length: {}\r\n\
                    \r\n",
                HTTPBIN_PUT.len()
            )?;
            w.write_all(HTTPBIN_PUT.as_bytes())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/delete", |_uri, _req, w| {
            write!(w, "HTTP/1.1 200 OK\r\n\r\ndeleted\n")
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/robots.txt", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: text/plain\r\n\
                Content-Length: 30\r\n\
                \r\n\
                User-agent: *\n\
                Disallow: /deny\n"
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/json", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_JSON.len()
            )?;
            w.write_all(HTTPBIN_JSON.as_bytes())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/redirect-to", |uri, _req, w| {
            let location = uri.query().unwrap();
            assert!(location.starts_with("url="));
            let location = &location[4..];
            let location = percent_encoding::percent_decode_str(location)
                .decode_utf8()
                .unwrap();
            write!(
                w,
                "HTTP/1.1 302 FOUND\r\n\
                Location: {}\r\n\
                Content-Length: 22\r\n\
                Connection: close\r\n\
                \r\n\
                You've been redirected\
                ",
                location
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/partial-redirect", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 302 OK\r\n\
                Location: /get\r\n\
                set-cookie: AEC=AVYB7cpadYFS8ZgaioQ17NnxHl1QcSQ_2aH2WEIg1KGDXD5kjk2HhpGVhfk; \
                    expires=Mon, 14-Apr-2050 17:23:39 GMT; path=/; domain=.google.com; \
                    Secure; HttpOnly; SameSite=lax\r\n\
                " // deliberately omit final \r\n
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/cookie-test", |_uri, req, w| {
            let mut all: Vec<_> = req
                .headers()
                .get_all("cookie")
                .iter()
                .map(|c| c.to_str().unwrap())
                .collect();

            all.sort();

            assert_eq!(all, ["a=1;b=2"]);

            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                content-length: 2\r\n\
                \r\n\
                ok",
            )
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/connect-proxy", |_uri, req, w| {
            assert_eq!(req.uri(), "httpbin.org:80");
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                \r\n\
                HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_GET.len()
            )?;
            w.write_all(HTTPBIN_GET.as_bytes())?;
            Ok(())
        }),
        handlers,
    );

    #[cfg(feature = "_ring")]
    maybe_add(
        TestHandler::new_tls_tunnel("https-connect-proxy", |_uri, req, reader, writer| {
            use rustls::{ServerConfig, ServerConnection, StreamOwned};
            use rustls_pki_types::pem::PemObject;
            use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivateSec1KeyDer};

            assert_eq!(req.method(), Method::CONNECT);
            assert_eq!(req.uri(), "example.com:443");

            write!(writer, "HTTP/1.1 200 Connection established\r\n\r\n")?;
            writer.flush()?;

            let cert = CertificateDer::from_pem_slice(include_bytes!("testdata/cert.pem"))
                .expect("valid test certificate");
            let key = PrivateSec1KeyDer::from_pem_slice(include_bytes!("testdata/key.pem"))
                .expect("valid test key");
            let provider = Arc::new(rustls::crypto::ring::default_provider());
            let config = ServerConfig::builder_with_provider(provider)
                .with_safe_default_protocol_versions()
                .expect("default TLS versions")
                .with_no_client_auth()
                .with_single_cert(vec![cert], PrivateKeyDer::Sec1(key))
                .expect("matching test certificate and key");
            let connection = ServerConnection::new(Arc::new(config)).expect("TLS server");
            let socket = TestDuplex { reader, writer };
            let mut stream = StreamOwned::new(connection, socket);

            let mut request_bytes = Vec::new();
            loop {
                let mut input = [0_u8; 1024];
                let amount = io::Read::read(&mut stream, &mut input)?;
                if amount == 0 {
                    return Err(io::Error::new(
                        io::ErrorKind::UnexpectedEof,
                        "TLS client closed before sending a request",
                    ));
                }
                request_bytes.extend_from_slice(&input[..amount]);
                if request_bytes.windows(4).any(|v| v == b"\r\n\r\n") {
                    break;
                }
            }

            let (_, request) = try_parse_request::<100>(&request_bytes)
                .expect("valid HTTP request through TLS tunnel")
                .expect("complete HTTP request through TLS tunnel");
            assert_eq!(request.method(), Method::GET);
            assert_eq!(request.uri(), "/through-https-proxy");

            write!(
                stream,
                "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok"
            )?;
            stream.flush()
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/fnord", |_uri, req, w| {
            assert_eq!(req.method().as_str(), "FNORD");

            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Content-Type: application/json\r\n\
                Content-Length: {}\r\n\
                \r\n",
                HTTPBIN_GET.len()
            )?;
            if req.method() != Method::HEAD {
                w.write_all(HTTPBIN_GET.as_bytes())?;
            }
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/1chunk-abort", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Transfer-Encoding: chunked\r\n\
                \r\n\
                2\r\n\
                OK\r\n\
                0\r\n<hangup>",
            )?;
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/2chunk-abort", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Transfer-Encoding: chunked\r\n\
                \r\n\
                2\r\n\
                OK\r\n\
                0\r\n\
                \r<hangup>", // missing \n
            )?;
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/3chunk-abort", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Transfer-Encoding: chunked\r\n\
                \r\n\
                2\r\n\
                OK\r\n\
                0\r\n\
                \r\n<hangup>",
            )?;
            Ok(())
        }),
        handlers,
    );

    maybe_add(
        TestHandler::new("/4chunk-abort", |_uri, _req, w| {
            write!(
                w,
                "HTTP/1.1 200 OK\r\n\
                Transfer-Encoding: chunked\r\n\
                \r\n\
                2\r\n\
                OK\r\n\
                0\r\n\
                \r\n",
            )?;
            Ok(())
        }),
        handlers,
    );

    #[cfg(feature = "charset")]
    {
        let (cow, _, _) =
            encoding_rs::WINDOWS_1252.encode("HTTP/1.1 302 Déplacé Temporairement\r\n\r\n");
        let bytes = cow.to_vec();

        maybe_add(
            TestHandler::new("/non-ascii-reason", move |_uri, _req, w| {
                w.write_all(&bytes)?;
                Ok(())
            }),
            handlers,
        );
    }
}

const HTTPBIN_GET: &str = r#"
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Host": "httpbin.org",
    "User-Agent": "ureq/yeah",
    "X-Amzn-Trace-Id": "Root=1-6692ea70-181d2b331d51fb157521fba0"
  },
  "origin": "1.2.3.4",
  "url": "http://httpbin.org/get"
}"#;

const HTTPBIN_PUT: &str = r#"
{
  "args": {},
  "data": "foo",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Content-Length": "3",
    "Content-Type": "application/octet-stream",
    "Host": "httpbin.org",
    "User-Agent": "curl/8.6.0",
    "X-Amzn-Trace-Id": "Root=1-6692eb75-0335ed3376385cc01144a4b6"
  },
  "json": null,
  "origin": "1.2.3.4",
  "url": "http://httpbin.org/put"
}"#;

const HTTPBIN_JSON: &str = r#"
{
  "slideshow": {
    "author": "Yours Truly",
    "date": "date of publication",
    "slides": [
      {
        "title": "Wake up to WonderWidgets!",
        "type": "all"
      },
      {
        "items": [
          "Why <em>WonderWidgets</em> are great",
          "Who <em>buys</em> WonderWidgets"
        ],
        "title": "Overview",
        "type": "all"
      }
    ],
    "title": "Sample Slide Show"
  }
}"#;

struct RxRead(Receiver<Vec<u8>>);

impl io::Read for RxRead {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let v = match self.0.recv() {
            Ok(v) => v,
            Err(_) => return Ok(0), // remote side is gone
        };
        assert!(buf.len() >= v.len(), "{} > {}", buf.len(), v.len());
        let max = buf.len().min(v.len());
        buf[..max].copy_from_slice(&v[..]);
        Ok(max)
    }
}

struct TxWrite(mpsc::SyncSender<Vec<u8>>);

impl io::Write for TxWrite {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.0.send(buf.to_vec()).map_err(io::Error::other)?;
        Ok(buf.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

struct SaneBufReader<R: io::Read>(Option<R>, Vec<u8>);

impl<R: io::Read> io::Read for SaneBufReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if !self.1.is_empty() {
            let max = buf.len().min(self.1.len());
            buf[..max].copy_from_slice(&self.1[..max]);
            self.1.drain(..max);
            return Ok(max);
        }

        let Some(reader) = &mut self.0 else {
            return Ok(0);
        };
        reader.read(buf)
    }
}

impl<R: io::Read> SaneBufReader<R> {
    pub fn fill_buf(&mut self) -> io::Result<&[u8]> {
        let Some(reader) = &mut self.0 else {
            return Ok(&self.1);
        };

        let l = self.1.len();
        self.1.resize(l + 1024, 0);
        let buf = &mut self.1[l..];
        let n = reader.read(buf)?;
        if n == 0 {
            self.0 = None;
        }
        self.1.truncate(l + n);
        Ok(&self.1)
    }

    pub fn consume(&mut self, n: usize) {
        self.1.drain(..n);
    }
}

pub(crate) struct TestTransport {
    buffers: LazyBuffers,
    tx: mpsc::SyncSender<Vec<u8>>,
    rx: SyncReceiver<Vec<u8>>,
    connected_tx: bool,
    connected_rx: bool,
}

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

    fn transmit_output(&mut self, amount: usize, _timeout: NextTimeout) -> Result<(), Error> {
        let output = &self.buffers.output()[..amount];
        if self.tx.send(output.to_vec()).is_err() {
            self.connected_tx = false;
        }
        Ok(())
    }

    fn await_input(&mut self, timeout: NextTimeout) -> Result<bool, Error> {
        if !self.connected_rx {
            return Err(Error::Io(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "test server is not connected",
            )));
        }

        let input = self.buffers.input_append_buf();
        let mut buf = match self.rx.recv_timeout(timeout.after) {
            Ok(v) => v,
            Err(RecvTimeoutError::Timeout) => return Err(Error::Timeout(timeout.reason)),
            Err(RecvTimeoutError::Disconnected) => {
                trace!("Test server disconnected");
                self.connected_rx = false;
                return Err(Error::Io(io::Error::new(
                    io::ErrorKind::UnexpectedEof,
                    "test server disconnected",
                )));
            }
        };

        let maybe_hangup = buf
            .windows(HANGUP.len())
            .enumerate()
            .find(|(_, w)| *w == HANGUP)
            .map(|(pos, _)| pos);

        if let Some(pos) = maybe_hangup {
            debug!("TEST: Found <hangup>");
            buf.drain(pos..);
            self.connected_rx = false;
        }

        assert!(input.len() >= buf.len());
        let max = input.len().min(buf.len());
        input[..max].copy_from_slice(&buf[..]);
        self.buffers.input_appended(max);
        Ok(max > 0)
    }

    fn is_open(&mut self) -> bool {
        self.connected_tx
    }

    fn is_tls(&self) -> bool {
        // Pretend this is tls to not get TLS wrappers
        true
    }
}

const HANGUP: &[u8] = b"<hangup>";

#[cfg(feature = "_ring")]
struct TestDuplex<'a> {
    reader: &'a mut dyn io::Read,
    writer: &'a mut dyn Write,
}

#[cfg(feature = "_ring")]
impl io::Read for TestDuplex<'_> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.reader.read(buf)
    }
}

#[cfg(feature = "_ring")]
impl Write for TestDuplex<'_> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.writer.write(buf)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.writer.flush()
    }
}

// Workaround for std::mpsc::Receiver not being Sync
struct SyncReceiver<T>(Mutex<Receiver<T>>);

impl<T> SyncReceiver<T> {
    fn recv_timeout(&self, timeout: Duration) -> Result<T, RecvTimeoutError> {
        let lock = self.0.lock().unwrap();
        lock.recv_timeout(*timeout)
    }
}

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

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