rsurl 0.0.2

A pure-Rust implementation of curl. Library, C FFI, and CLI for HTTP/HTTPS/FTP/FTPS.
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
//! Live HTTP/1.1 integration tests for rsurl.
//!
//! Each test spins up a single-shot [`TestServer`] in `common/`, points a
//! [`rsurl::Request`] at it, and asserts both directions of the wire.
//! No external network is touched.

mod common;

use std::time::Duration;

use common::{BodyMode, Request as SReq, Response as SResp, TestServer};

use rsurl::{CookieJar, Error, Request};

/// 200 OK with a Content-Length-framed body — the cheapest possible
/// round-trip.
#[test]
fn get_returns_body() {
    let server = TestServer::start(|_req: SReq| SResp::ok("hello"));
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.reason, "OK");
    assert_eq!(resp.body, b"hello");
}

/// HEAD must never carry a body even when the server advertises a length.
/// The presence of `Content-Length: 5` is the temptation; the client side
/// (`read_body`) is responsible for not reading those five bytes.
#[test]
fn head_has_no_body() {
    let server = TestServer::start(|_req: SReq| {
        // Lie about the body length: we send no body bytes, but
        // advertise 5. A HEAD-aware client must ignore the count.
        SResp {
            status: 200,
            reason: "OK".into(),
            headers: vec![("Content-Length".into(), "5".into())],
            body: Vec::new(),
            mode: BodyMode::CloseDelimited, // skip the auto-clen path
        }
    });
    let resp = Request::new("HEAD", &server.url("/"))
        .unwrap()
        .send()
        .unwrap();
    assert_eq!(resp.status, 200);
    assert!(resp.body.is_empty(), "HEAD body must be empty");
}

/// Three concrete chunks, no trailers — exercises the basic chunked
/// reader.
#[test]
fn chunked_encoding() {
    let server = TestServer::start(|_req: SReq| {
        SResp::ok(Vec::new()).mode(BodyMode::Chunked {
            chunks: vec![b"abc".to_vec(), b"defg".to_vec(), b"hi".to_vec()],
            trailers: vec![],
        })
    });
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, b"abcdefghi");
}

/// Chunked body with a trailer field after the terminator. Curl's reader
/// is supposed to drain trailers and not surface them as part of the
/// body or as an error.
#[test]
fn chunked_with_trailers() {
    let server = TestServer::start(|_req: SReq| {
        SResp::ok(Vec::new()).mode(BodyMode::Chunked {
            chunks: vec![b"hello ".to_vec(), b"world".to_vec()],
            trailers: vec![("X-Trailer".into(), "ignored".into())],
        })
    });
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, b"hello world");
}

/// Server advertises 100 bytes, sends 50, then closes. This must surface
/// as `Error::UnexpectedEof` — the client cannot silently truncate.
#[test]
fn content_length_mismatch_short() {
    let server = TestServer::start(|_req: SReq| SResp {
        status: 200,
        reason: "OK".into(),
        headers: vec![],
        body: vec![b'a'; 100],
        mode: BodyMode::ContentLengthShort {
            declared: 100,
            actual_len: 50,
        },
    });
    let err = Request::get(&server.url("/")).unwrap().send().unwrap_err();
    assert!(
        matches!(err, Error::UnexpectedEof),
        "expected UnexpectedEof, got {err:?}",
    );
}

/// No Content-Length, no Transfer-Encoding — the body runs until EOF
/// (Connection: close). rsurl has to read to EOF.
#[test]
fn close_delimited_body() {
    let server = TestServer::start(|_req: SReq| SResp {
        status: 200,
        reason: "OK".into(),
        headers: vec![],
        body: b"hello".to_vec(),
        mode: BodyMode::CloseDelimited,
    });
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, b"hello");
}

/// Round-trip a megabyte of pseudo-random bytes byte-for-byte. Uses a
/// fixed LCG so the test is deterministic and the failure message is
/// useful (no need for a checksum hash).
#[test]
fn large_body_1mb() {
    let payload: Vec<u8> = {
        let mut v = Vec::with_capacity(1 << 20);
        let mut state: u32 = 0x1234_5678;
        for _ in 0..(1 << 20) {
            // Numerical Recipes LCG — cheap and good enough for "is it
            // the same bytes I sent" tests.
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            v.push((state >> 24) as u8);
        }
        v
    };

    let payload_clone = payload.clone();
    let server = TestServer::start(move |_req: SReq| SResp::ok(payload_clone.clone()));
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body.len(), payload.len());
    assert!(resp.body == payload, "1 MiB body did not round-trip");
}

/// 204 No Content must complete cleanly with an empty body and no error
/// even though there is no `Content-Length` and no `Transfer-Encoding`.
#[test]
fn status_204_no_body() {
    let server = TestServer::start(|_req: SReq| SResp {
        status: 204,
        reason: "No Content".into(),
        headers: vec![],
        body: Vec::new(),
        mode: BodyMode::CloseDelimited,
    });
    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 204);
    assert_eq!(resp.reason, "No Content");
    assert!(resp.body.is_empty());
}

/// The server reflects every received request header back in the body
/// so the client side can inspect what was actually put on the wire.
/// Locks in: User-Agent default, Accept: */*, Host, and the *absence* of
/// `Connection: close` (HTTP/1.1's default is keep-alive — see the
/// connection-pool work in `src/pool.rs`).
#[test]
fn request_headers_propagate() {
    let server = TestServer::start(|req: SReq| {
        let mut body = Vec::new();
        for (k, v) in &req.headers {
            body.extend_from_slice(k.as_bytes());
            body.extend_from_slice(b": ");
            body.extend_from_slice(v.as_bytes());
            body.push(b'\n');
        }
        SResp::ok(body)
    });
    let resp = Request::get(&server.url("/probe")).unwrap().send().unwrap();
    let text = String::from_utf8(resp.body).expect("ascii reflected headers");

    let expected_ua = concat!("User-Agent: rsurl/", env!("CARGO_PKG_VERSION"));
    assert!(text.contains(expected_ua), "missing default UA in: {text}");
    assert!(text.contains("Accept: */*\n"), "missing Accept in: {text}");
    let expected_host = format!("Host: {}\n", server.addr);
    assert!(
        text.contains(&expected_host),
        "missing/wrong Host in: {text}",
    );
    assert!(
        !text.to_ascii_lowercase().contains("connection: close"),
        "must not advertise Connection: close (keep-alive is the HTTP/1.1 default): {text}",
    );
}

/// A caller-supplied User-Agent overrides the default, but does not
/// duplicate it on the wire.
#[test]
fn custom_user_agent_overrides() {
    let server = TestServer::start(|req: SReq| {
        let ua = req.header("User-Agent").unwrap_or("").to_string();
        SResp::ok(ua)
    });
    let resp = Request::get(&server.url("/"))
        .unwrap()
        .header("User-Agent", "test/1")
        .send()
        .unwrap();
    assert_eq!(resp.body, b"test/1");
    // And the default must not also appear (write_request has an
    // `have_ua` guard — this locks it in).
    let default_ua = concat!("rsurl/", env!("CARGO_PKG_VERSION"));
    assert!(
        !resp
            .body
            .windows(default_ua.len())
            .any(|w| w == default_ua.as_bytes()),
        "default UA leaked alongside the override",
    );
}

/// POST with a body must auto-set Content-Length and the server must
/// receive the exact bytes.
#[test]
fn post_with_body_sets_content_length() {
    let server = TestServer::start(|req: SReq| {
        assert_eq!(req.method, "POST");
        assert_eq!(req.header("Content-Length"), Some("5"));
        assert_eq!(req.body, b"hello");
        SResp::ok("ack")
    });
    let resp = Request::new("POST", &server.url("/echo"))
        .unwrap()
        .body("hello".as_bytes().to_vec())
        .send()
        .unwrap();
    assert_eq!(resp.body, b"ack");
}

/// Lock in the curl-style `-v` trace format produced by `send_traced`:
/// `> ` lines for the request bytes actually put on the wire, `< ` lines
/// for the response status & headers, and a connection-state epilogue
/// (either "Connection kept alive (pooled)" when the response is reusable
/// or "Connection closed" when it isn't).
#[test]
fn verbose_trace_format() {
    let server = TestServer::start(|_req: SReq| SResp::ok("hi"));

    let mut trace = Vec::new();
    let resp = Request::get(&server.url("/"))
        .unwrap()
        .send_traced(&mut trace)
        .unwrap();
    assert_eq!(resp.body, b"hi");

    let t = String::from_utf8(trace).expect("trace should be utf-8");
    assert!(
        t.contains("> GET / HTTP/1.1"),
        "missing request line in:\n{t}"
    );
    assert!(
        t.contains("< HTTP/1.1 200"),
        "missing response status in:\n{t}",
    );
    assert!(
        t.contains("* Connection kept alive (pooled)") || t.contains("* Connection closed"),
        "missing connection-state epilogue in:\n{t}",
    );
}

/// rsurl sends `Accept-Encoding: gzip, deflate` by default and must
/// transparently decode a `Content-Encoding: gzip` response. The header
/// is also expected to be **stripped** from the returned `Response`, so
/// downstream consumers don't think the body is still compressed.
#[test]
fn gzip_response_is_decoded() {
    let plain = b"hello compressed world".to_vec();
    let gz = compcol::vec::compress_to_vec::<compcol::gzip::Gzip>(&plain).unwrap();

    let plain_for_server = plain.clone();
    let gz_for_server = gz.clone();
    let server = TestServer::start(move |req: SReq| {
        // Confirm the client actually advertised compression — we are
        // exercising the default-on Accept-Encoding writer too.
        let ae = req.header("Accept-Encoding").unwrap_or("");
        assert!(ae.contains("gzip"), "Accept-Encoding missing gzip: {ae:?}");
        let _ = plain_for_server; // captured for clarity; not used here
        SResp::ok(gz_for_server.clone()).header("Content-Encoding", "gzip")
    });

    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, plain, "body should be the decoded plaintext");
    // Stale framing headers must be gone after decode.
    assert!(
        !resp
            .headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("content-encoding")),
        "Content-Encoding leaked through: {:?}",
        resp.headers,
    );
    assert!(
        !resp
            .headers
            .iter()
            .any(|(k, _)| k.eq_ignore_ascii_case("content-length")),
        "stale Content-Length leaked through: {:?}",
        resp.headers,
    );
}

/// Same wire shape but with `deflate` (zlib-wrapped, RFC 9110 form).
#[test]
fn deflate_response_is_decoded() {
    let plain = b"deflate body".to_vec();
    let z = compcol::vec::compress_to_vec::<compcol::zlib::Zlib>(&plain).unwrap();

    let z_for_server = z.clone();
    let server = TestServer::start(move |_req: SReq| {
        SResp::ok(z_for_server.clone()).header("Content-Encoding", "deflate")
    });

    let resp = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(resp.body, plain);
}

/// Sanity: a request to a closed port surfaces as an I/O error rather
/// than panicking. Picks a non-privileged port that's almost certainly
/// closed by getting one from the kernel and immediately releasing it.
#[test]
fn connect_refused_is_io_error() {
    // Bind, capture the port, then drop the listener so the port is
    // (almost certainly) free. Race-prone in theory, fine in practice
    // for a test that just needs *some* port nothing is listening on.
    let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind to grab a free port");
    let addr = listener.local_addr().unwrap();
    drop(listener);

    let url = format!("http://{addr}/");
    // Tighten the connect timeout so a stray accept in CI can't make
    // this test wait 30 s.
    let err = Request::get(&url)
        .unwrap()
        .connect_timeout(Duration::from_secs(2))
        .send()
        .unwrap_err();
    assert!(
        matches!(err, Error::Io(_)),
        "expected Error::Io, got {err:?}",
    );
}

/// Set-Cookie on a 200 response populates the jar.
#[test]
fn set_cookie_lands_in_jar() {
    let server =
        TestServer::start(|_req: SReq| SResp::ok("ok").header("Set-Cookie", "sid=abc; Path=/"));
    let mut jar = CookieJar::new();
    let resp = Request::get(&server.url("/"))
        .unwrap()
        .send_with_jar(&mut jar)
        .unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(jar.len(), 1, "expected one cookie, jar={jar:?}");
    let url = rsurl::Url::parse(&server.url("/")).unwrap();
    assert_eq!(jar.cookie_header(&url).as_deref(), Some("sid=abc"));
}

/// A 302 with Set-Cookie sets a cookie, and the chased follow-up GET must
/// carry that cookie in its request header.
#[test]
fn cookie_traverses_redirect_chain() {
    use std::sync::{Arc, Mutex};
    // Shared slot the /home handler writes the Cookie header value into,
    // so the test body can assert what was sent on hop #2.
    let observed: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
    let obs_for_handler = Arc::clone(&observed);

    let server = TestServer::start(move |req: SReq| {
        if req.path == "/start" {
            // Issue a cookie and redirect.
            SResp::status(302)
                .header("Set-Cookie", "sid=abc; Path=/")
                .header("Location", "/home")
        } else if req.path == "/home" {
            // Capture whatever Cookie: header arrived on the second hop.
            let got = req
                .headers
                .iter()
                .find(|(k, _)| k.eq_ignore_ascii_case("cookie"))
                .map(|(_, v)| v.clone());
            *obs_for_handler.lock().unwrap() = got;
            SResp::ok("welcome")
        } else {
            SResp::status(404)
        }
    });

    let mut jar = CookieJar::new();
    let resp = Request::get(&server.url("/start"))
        .unwrap()
        .follow_redirects(true)
        .send_with_jar(&mut jar)
        .unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, b"welcome");
    let cookie_seen = observed.lock().unwrap().clone();
    assert_eq!(
        cookie_seen.as_deref(),
        Some("sid=abc"),
        "expected sid=abc on the redirected hop, got {cookie_seen:?}",
    );
}

/// `send_with_jar` without any Set-Cookie response leaves the jar empty
/// and never inserts a stray `Cookie:` request header.
#[test]
fn jar_is_empty_when_server_sets_no_cookie() {
    use std::sync::{Arc, Mutex};
    let observed: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
    let obs = Arc::clone(&observed);
    let server = TestServer::start(move |req: SReq| {
        let got = req
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("cookie"))
            .map(|(_, v)| v.clone());
        *obs.lock().unwrap() = got;
        SResp::ok("ok")
    });
    let mut jar = CookieJar::new();
    let resp = Request::get(&server.url("/"))
        .unwrap()
        .send_with_jar(&mut jar)
        .unwrap();
    assert_eq!(resp.status, 200);
    assert!(jar.is_empty(), "jar should be empty");
    assert!(
        observed.lock().unwrap().is_none(),
        "should not have sent any Cookie: header"
    );
}

/// When `-x` is set against a plain-HTTP URL, rsurl must:
///   * connect to the proxy address, not the origin,
///   * send the request line in absolute-URI form per RFC 9112 §3.2.2,
///   * preserve `Host:` as the origin authority.
#[test]
fn plain_http_via_proxy_uses_absolute_form() {
    let proxy = TestServer::start(|req: SReq| {
        // Echo the request line (built from method + path) and the Host
        // header so the test can assert exactly what hit the wire.
        let host = req
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("host"))
            .map(|(_, v)| v.clone())
            .unwrap_or_default();
        let body = format!("{} {}\nHost: {host}\n", req.method, req.path);
        SResp::ok(body)
    });
    // Origin URL — we never actually connect to it; the proxy claims to
    // be the intermediary, so the test's TestServer (the proxy) gets the
    // bytes. Use a host name DNS will not resolve so a regression that
    // skips the proxy fails loudly rather than silently hitting the
    // network.
    let origin = "http://origin.invalid/some/path?q=1";
    let resp = Request::get(origin)
        .unwrap()
        .proxy(proxy.url("").trim_end_matches('/'))
        .unwrap()
        .send()
        .unwrap();
    let text = String::from_utf8(resp.body).unwrap();
    assert!(
        text.contains("GET http://origin.invalid/some/path?q=1\n"),
        "absolute-form request line missing: {text}",
    );
    assert!(
        text.contains("Host: origin.invalid\n"),
        "Host should be the origin's authority, not the proxy's: {text}",
    );
}

/// `--proxy-user` (or credentials in the proxy URL) must land in a
/// `Proxy-Authorization: Basic <b64>` header for plain HTTP proxying.
#[test]
fn plain_http_via_proxy_with_creds() {
    use std::sync::{Arc, Mutex};
    let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
    let cap2 = Arc::clone(&captured);
    let proxy = TestServer::start(move |req: SReq| {
        let pa = req
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("proxy-authorization"))
            .map(|(_, v)| v.clone());
        *cap2.lock().unwrap() = pa;
        SResp::ok("ok")
    });
    let proxy_url = format!("http://alice:hunter2@{}", proxy.addr);
    Request::get("http://origin.invalid/")
        .unwrap()
        .proxy(&proxy_url)
        .unwrap()
        .send()
        .unwrap();
    let got = captured.lock().unwrap().clone();
    // base64("alice:hunter2") = "YWxpY2U6aHVudGVyMg=="
    assert_eq!(got.as_deref(), Some("Basic YWxpY2U6aHVudGVyMg=="));
}

/// `--noproxy` matches the target host → connection goes direct.
/// We assert this by pointing `proxy()` at a *closed* port and verifying
/// the request still succeeds: only a direct connection to the real
/// origin (the TestServer) can have served it.
#[test]
fn noproxy_bypasses_proxy() {
    let origin = TestServer::start(|_req| SResp::ok("direct"));
    // Reserve a port and immediately release it so the proxy "endpoint"
    // is almost certainly closed; the same trick used by
    // `connect_refused_is_io_error`.
    let l = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
    let closed = l.local_addr().unwrap();
    drop(l);

    let resp = Request::get(&origin.url("/"))
        .unwrap()
        .proxy(&format!("http://{closed}"))
        .unwrap()
        .no_proxy(["127.0.0.1"])
        .connect_timeout(Duration::from_secs(2))
        .send()
        .unwrap();
    assert_eq!(resp.status, 200);
    assert_eq!(resp.body, b"direct");
}

/// Two consecutive plain-HTTP requests to the same authority share a single
/// TCP connection via the pool. We assert this with the server's
/// `accept_count` — the second request must NOT trigger another accept.
#[test]
fn pool_reuses_plain_http_connection() {
    use std::sync::atomic::Ordering;
    let server = TestServer::start_keepalive(|_req: SReq| SResp::ok("ok"));

    let r1 = Request::get(&server.url("/first")).unwrap().send().unwrap();
    assert_eq!(r1.status, 200);

    // Give the worker a beat to park the bufreader before the second call.
    std::thread::sleep(Duration::from_millis(30));

    let r2 = Request::get(&server.url("/second"))
        .unwrap()
        .send()
        .unwrap();
    assert_eq!(r2.status, 200);

    let accepted = server.accept_count.load(Ordering::SeqCst);
    assert_eq!(
        accepted, 1,
        "second request should have reused the pooled connection, got {accepted} accepts",
    );
}

/// If a server sends `Connection: close`, the connection must NOT be parked.
/// The next request goes out on a fresh socket.
#[test]
fn pool_skips_when_response_says_close() {
    use std::sync::atomic::Ordering;
    let server =
        TestServer::start_keepalive(|_req: SReq| SResp::ok("ok").header("Connection", "close"));

    let _ = Request::get(&server.url("/a")).unwrap().send().unwrap();
    std::thread::sleep(Duration::from_millis(30));
    let _ = Request::get(&server.url("/b")).unwrap().send().unwrap();

    let accepted = server.accept_count.load(Ordering::SeqCst);
    assert_eq!(
        accepted, 2,
        "Connection: close should disable reuse, got {accepted} accepts",
    );
}

/// Close-delimited responses (no Content-Length, no chunked, server closes
/// the socket to signal end of body) must also NOT be parked: by definition
/// the connection is gone.
#[test]
fn pool_skips_close_delimited_response() {
    use std::sync::atomic::Ordering;
    let server = TestServer::start_keepalive(|_req: SReq| {
        SResp::ok("body-bytes").mode(BodyMode::CloseDelimited)
    });
    let _ = Request::get(&server.url("/a")).unwrap().send().unwrap();
    std::thread::sleep(Duration::from_millis(30));
    let _ = Request::get(&server.url("/b")).unwrap().send().unwrap();
    assert_eq!(server.accept_count.load(Ordering::SeqCst), 2);
}

/// If the server kills a parked connection between requests, the client
/// must silently dial a fresh socket — not surface a stale-connection EOF.
/// We simulate this by giving the server a tiny idle timeout and ensuring
/// the second request still succeeds.
#[test]
fn pool_retries_when_pooled_connection_is_stale() {
    use std::sync::atomic::Ordering;
    // start_keepalive's worker loops until parse_request fails. We make it
    // fail by closing our end after the first response — but we control
    // both endpoints. Trick: have the handler return a body, then the
    // worker stays in keep-alive loop waiting on read with a 5s timeout.
    // Instead we use a dedicated server that drops the socket after one
    // response (the default `start`). The client pools the bufreader,
    // server has gone away, second request hits EOF → retries fresh.
    let server = TestServer::start(|_req: SReq| SResp::ok("once"));

    let r1 = Request::get(&server.url("/")).unwrap().send().unwrap();
    assert_eq!(r1.body, b"once");
    // The pool has the now-dead bufreader.
    std::thread::sleep(Duration::from_millis(30));

    // Second request: must NOT fail. The pool entry is stale, the client
    // detects this on first read and reconnects transparently.
    let r2 = Request::get(&server.url("/"))
        .unwrap()
        .connect_timeout(Duration::from_secs(2))
        .send()
        .unwrap();
    assert_eq!(r2.body, b"once");
    // Two TCP accepts — one per request — because the single-shot server
    // closes after the first response, so the pool's parked entry was dead
    // by the time the second request tried to reuse it.
    assert_eq!(server.accept_count.load(Ordering::SeqCst), 2);
}

// ---------------------------------------------------------------------------
// CLI subprocess tests for the curl-parity body flags
// ---------------------------------------------------------------------------
//
// These spawn the actual `rsurl` binary against an in-process test server.
// The binary path comes from `CARGO_BIN_EXE_rsurl`, set automatically by
// Cargo for integration tests on a crate that declares a `[[bin]]` target.
// We need a subprocess (rather than calling code directly) because the CLI
// flag-parsing layer is the unit under test here.

/// `(method, content_type, body_bytes)` captured from one request.
type CapturedRequest = (String, Option<String>, Vec<u8>);
type CapturedSlot = std::sync::Arc<std::sync::Mutex<Option<CapturedRequest>>>;

/// Helper: take ownership of the next captured request body sent by the
/// in-process server. Blocks until the handler has run.
fn capture_one_request() -> (TestServer, CapturedSlot) {
    use std::sync::{Arc, Mutex};
    let slot: CapturedSlot = Arc::new(Mutex::new(None));
    let slot2 = Arc::clone(&slot);
    let server = TestServer::start(move |req: SReq| {
        let ct = req
            .headers
            .iter()
            .find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
            .map(|(_, v)| v.clone());
        *slot2.lock().unwrap() = Some((req.method.clone(), ct, req.body.clone()));
        SResp::ok("ok")
    });
    (server, slot)
}

/// `rsurl --data-binary @file` must transmit the file bytes verbatim,
/// including CRLF and bare LF — those are the bytes curl preserves under
/// `--data-binary` (and would strip under `-d`).
#[test]
fn cli_data_binary_at_file_keeps_newlines() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut tmp = std::env::temp_dir();
    tmp.push(format!("rsurl-data-binary-{}.bin", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp).unwrap();
        f.write_all(b"a\r\nb\n").unwrap();
    }

    let arg = format!("@{}", tmp.display());
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["--data-binary", &arg, &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&tmp);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    assert_eq!(
        got.1.as_deref(),
        Some("application/x-www-form-urlencoded"),
        "default Content-Type for --data-binary should match -d"
    );
    assert_eq!(got.2, b"a\r\nb\n", "CRLF/LF must survive --data-binary");
}

/// Drive every documented sub-form of `--data-urlencode` and assert the
/// joined body is exactly what curl would emit: `content` and `=content`
/// percent-encode the bytes; `name=content` keeps the name plain and
/// encodes only the value; `@file` / `name@file` read the file then encode.
#[test]
fn cli_data_urlencode_all_five_forms() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut tmp = std::env::temp_dir();
    tmp.push(format!("rsurl-urlencode-{}.txt", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp).unwrap();
        // Bytes that exercise the encoder: space → '+', '&' → "%26".
        f.write_all(b"x y&z").unwrap();
    }
    let at = format!("@{}", tmp.display());
    let name_at = format!("g@{}", tmp.display());

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args([
            "--data-urlencode",
            "hello world",
            "--data-urlencode",
            "=raw value",
            "--data-urlencode",
            "k=v with space",
            "--data-urlencode",
            &at,
            "--data-urlencode",
            &name_at,
            &server.url("/post"),
        ])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&tmp);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    let body = String::from_utf8(got.2).expect("ascii body");
    // Joined left-to-right with '&', each part the curl-canonical encoding.
    // file content "x y&z" → "x+y%26z".
    assert_eq!(
        body, "hello+world&raw+value&k=v+with+space&x+y%26z&g=x+y%26z",
        "every --data-urlencode sub-form must match curl's encoding"
    );
}

/// `-d a=1 -d b=2 -d c=3` concatenates with `&` exactly the way curl does;
/// each repetition appends one more form value. This is the canonical
/// "I'd rather repeat the flag than escape an ampersand on the shell line"
/// idiom.
#[test]
fn cli_multiple_d_join_with_ampersand() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-d", "a=1", "-d", "b=2", "-d", "c=3", &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    assert_eq!(got.2, b"a=1&b=2&c=3");
}

// ---------------------------------------------------------------------------
// CLI subprocess tests for -F / --form, --form-string, -T / --upload-file
// ---------------------------------------------------------------------------

/// Pull the boundary string out of `multipart/form-data; boundary=…`.
fn extract_boundary(ct: &str) -> String {
    let lc = ct.to_ascii_lowercase();
    let prefix = "boundary=";
    let i = lc.find(prefix).expect("boundary= in Content-Type");
    let mut rest = &ct[i + prefix.len()..];
    if let Some(stripped) = rest.strip_prefix('"') {
        rest = stripped;
        let end = rest.find('"').expect("closing quote on boundary");
        rest[..end].to_string()
    } else {
        // Boundary runs until the next ';' or end-of-line.
        let end = rest.find(';').unwrap_or(rest.len());
        rest[..end].trim().to_string()
    }
}

/// Locate one multipart part by `name="<name>"` and return the slice from
/// after that line's CRLF through the part's terminating CRLF (excluding the
/// trailing `--<boundary>` glue). Tests then split header / body inside that.
fn find_part<'a>(body: &'a [u8], boundary: &str, needle: &str) -> &'a [u8] {
    let sep = format!("--{boundary}\r\n");
    let term = format!("--{boundary}--");
    let body_str =
        std::str::from_utf8(body).expect("multipart body should be UTF-8 in these tests");
    // Find the right part by scanning. Split on the leading boundary; each
    // chunk is one part (the first chunk is empty, before the first boundary).
    let mut chunks = body_str.split(&sep);
    let _ = chunks.next(); // skip the empty preamble
    for chunk in chunks {
        if chunk.contains(needle) {
            // Strip everything from the terminating boundary onward.
            let end = chunk.find(&term).unwrap_or(chunk.len());
            // Also strip the trailing CRLF before the boundary.
            let mut end_no_crlf = end;
            if end_no_crlf >= 2 && &chunk[end_no_crlf - 2..end_no_crlf] == "\r\n" {
                end_no_crlf -= 2;
            }
            // Also handle "--boundary" form (no leading \r\n separator
            // because we split on "--boundary\r\n" already). The actual
            // close marker for an interior part is "\r\n--boundary".
            return &chunk.as_bytes()[..end_no_crlf];
        }
    }
    panic!("no part matched: {needle:?}");
}

/// `-F name=@path` uploads the file's bytes as a multipart part, with
/// `Content-Disposition` carrying the basename as `filename=` and a
/// default `Content-Type: application/octet-stream`.
#[test]
fn cli_form_part_with_at_file_uploads_bytes() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut tmp = std::env::temp_dir();
    tmp.push(format!("rsurl-form-{}.bin", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp).unwrap();
        f.write_all(b"PAYLOAD-BYTES").unwrap();
    }
    let basename = tmp.file_name().unwrap().to_string_lossy().into_owned();
    let arg = format!("upload=@{}", tmp.display());

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-F", &arg, &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&tmp);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    let ct = got.1.expect("Content-Type set");
    assert!(
        ct.starts_with("multipart/form-data; boundary="),
        "got Content-Type: {ct}"
    );
    let boundary = extract_boundary(&ct);
    let part = find_part(&got.2, &boundary, "name=\"upload\"");
    let part_str = std::str::from_utf8(part).expect("ascii part headers");
    let expected_disposition =
        format!("Content-Disposition: form-data; name=\"upload\"; filename=\"{basename}\"\r\n");
    assert!(
        part_str.contains(&expected_disposition),
        "missing disposition in part: {part_str}"
    );
    assert!(
        part_str.contains("Content-Type: application/octet-stream\r\n"),
        "missing default Content-Type in part: {part_str}"
    );
    assert!(
        part.ends_with(b"\r\n\r\nPAYLOAD-BYTES"),
        "part body should end with the uploaded bytes; got: {part_str}"
    );
}

/// `--form-string name=@notafile` must put the literal string `@notafile`
/// in the part value — no file read, no `@` magic, no `;modifier` parsing.
#[test]
fn cli_form_string_treats_at_as_literal() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args([
            "--form-string",
            "field=@notafile;type=ignored",
            &server.url("/post"),
        ])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    let ct = got.1.expect("Content-Type set");
    let boundary = extract_boundary(&ct);
    let part = find_part(&got.2, &boundary, "name=\"field\"");
    let s = std::str::from_utf8(part).unwrap();
    // No filename promotion, no Content-Type defaulting, value is the
    // literal — `;type=ignored` is part of the bytes, not a modifier.
    assert!(
        !s.contains("filename="),
        "literal form-string must not become an upload: {s}"
    );
    assert!(!s.contains("Content-Type:"), "no auto Content-Type: {s}");
    assert!(
        s.ends_with("\r\n\r\n@notafile;type=ignored"),
        "literal value must appear verbatim: {s}"
    );
}

/// All three modifiers should pass through to the part: `;type=` sets the
/// Content-Type, `;filename=` overrides the basename, `;headers=@file`
/// injects extra header lines.
#[test]
fn cli_form_extras_type_filename_headers() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut payload = std::env::temp_dir();
    payload.push(format!("rsurl-form-payload-{}.txt", std::process::id()));
    std::fs::write(&payload, b"DATA").unwrap();

    let mut hdrs = std::env::temp_dir();
    hdrs.push(format!("rsurl-form-hdrs-{}.txt", std::process::id()));
    {
        let mut f = std::fs::File::create(&hdrs).unwrap();
        f.write_all(b"X-Custom: yes\r\nX-Other: 42\r\n").unwrap();
    }

    let arg = format!(
        "f=@{};type=application/json;filename=other.json;headers=@{}",
        payload.display(),
        hdrs.display()
    );
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-F", &arg, &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&payload);
    let _ = std::fs::remove_file(&hdrs);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    let ct = got.1.expect("Content-Type set");
    let boundary = extract_boundary(&ct);
    let part = find_part(&got.2, &boundary, "name=\"f\"");
    let s = std::str::from_utf8(part).unwrap();
    assert!(
        s.contains("name=\"f\"; filename=\"other.json\"\r\n"),
        "filename override missing: {s}"
    );
    assert!(
        s.contains("Content-Type: application/json\r\n"),
        "type modifier missing: {s}"
    );
    assert!(
        s.contains("X-Custom: yes\r\n"),
        "header injection missing: {s}"
    );
    assert!(
        s.contains("X-Other: 42\r\n"),
        "header injection missing: {s}"
    );
    assert!(s.ends_with("\r\n\r\nDATA"), "body bytes wrong: {s}");
}

/// `-T file` PUTs the file's bytes as the request body with
/// `Content-Type: application/octet-stream`.
#[test]
fn cli_upload_file_uses_put_and_octet_stream() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut tmp = std::env::temp_dir();
    tmp.push(format!("rsurl-upload-{}.bin", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp).unwrap();
        // Bytes that include CR/LF/NUL to prove no stripping happens.
        f.write_all(b"AAA\r\nBBB\n\0CCC").unwrap();
    }
    let path = tmp.to_string_lossy().into_owned();
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-T", &path, &server.url("/put")])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&tmp);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "PUT");
    assert_eq!(got.1.as_deref(), Some("application/octet-stream"));
    assert_eq!(got.2, b"AAA\r\nBBB\n\0CCC");
}

/// `-T` plus a non-HTTP URL is a usage error (exit code 2) and mentions
/// the flag in the message so the user knows what to fix.
#[test]
fn cli_upload_file_rejects_non_http() {
    use std::process::Command;
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-T", "/etc/hostname", "ftp://example.invalid/foo"])
        .output()
        .expect("spawn rsurl");
    let code = out.status.code();
    assert_eq!(code, Some(2), "expected exit code 2, got {code:?}");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(err.contains("-T"), "stderr should mention -T: {err}");
}

/// Combining `-F` and `-d` (or `-T` and either) must be rejected with a
/// usage error rather than silently building something nonsensical.
#[test]
fn cli_form_and_data_are_mutually_exclusive() {
    use std::process::Command;
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-d", "a=1", "-F", "b=2", "http://127.0.0.1:1/post"])
        .output()
        .expect("spawn rsurl");
    assert_eq!(out.status.code(), Some(2), "expected exit 2");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        err.contains("mutually exclusive"),
        "stderr should explain conflict: {err}"
    );
}

/// `-d` and `-T` are mutually exclusive too — same exit-2 path.
#[test]
fn cli_data_and_upload_are_mutually_exclusive() {
    use std::process::Command;
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-d", "a=1", "-T", "/etc/hostname", "http://127.0.0.1:1/x"])
        .output()
        .expect("spawn rsurl");
    assert_eq!(out.status.code(), Some(2), "expected exit 2");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        err.contains("mutually exclusive"),
        "stderr should explain conflict: {err}"
    );
}

/// `-F` and `-T` are mutually exclusive too — same exit-2 path.
#[test]
fn cli_form_and_upload_are_mutually_exclusive() {
    use std::process::Command;
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-F", "x=y", "-T", "/etc/hostname", "http://127.0.0.1:1/x"])
        .output()
        .expect("spawn rsurl");
    assert_eq!(out.status.code(), Some(2), "expected exit 2");
    let err = String::from_utf8_lossy(&out.stderr).into_owned();
    assert!(
        err.contains("mutually exclusive"),
        "stderr should explain conflict: {err}"
    );
}

/// `-F name=<file` reads the file but emits it as a **form field**, not a
/// file upload: the part carries the file bytes as its value but has no
/// `filename=` attribute and no auto-defaulted `Content-Type`. This is the
/// behavioural distinction from `@file` and the reason `<` exists at all.
#[test]
fn cli_form_field_from_file_has_no_filename() {
    use std::io::Write;
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let mut tmp = std::env::temp_dir();
    tmp.push(format!("rsurl-lt-{}.txt", std::process::id()));
    {
        let mut f = std::fs::File::create(&tmp).unwrap();
        f.write_all(b"FIELD-VALUE").unwrap();
    }
    let arg = format!("note=<{}", tmp.display());
    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-F", &arg, &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    let _ = std::fs::remove_file(&tmp);
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    let ct = got.1.expect("Content-Type set");
    let boundary = extract_boundary(&ct);
    let part = find_part(&got.2, &boundary, "name=\"note\"");
    let s = std::str::from_utf8(part).unwrap();
    assert!(
        !s.contains("filename="),
        "FileAsField must not add filename=: {s}"
    );
    assert!(
        !s.contains("Content-Type:"),
        "FileAsField must not auto-set Content-Type: {s}"
    );
    assert!(
        s.ends_with("\r\n\r\nFIELD-VALUE"),
        "file bytes must arrive verbatim as field value: {s}"
    );
}

/// `--form-escape` switches name/filename encoding from backslash-escape
/// (the curl-historical default we already test) to RFC 7578 §4.2
/// percent-encoding, so `"` becomes `%22` on the wire.
#[test]
fn cli_form_escape_percent_encodes_name() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["--form-escape", "-F", "weird\"name=v", &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    let ct = got.1.expect("Content-Type set");
    let boundary = extract_boundary(&ct);
    // Match on the percent-encoded form because the raw `"` no longer
    // appears in the part header line.
    let part = find_part(&got.2, &boundary, "name=\"weird%22name\"");
    let s = std::str::from_utf8(part).unwrap();
    assert!(
        s.contains("name=\"weird%22name\""),
        "expected RFC 7578 %22 encoding, got: {s}"
    );
    assert!(
        !s.contains("\\\""),
        "must not also backslash-escape when --form-escape is on: {s}"
    );
}

/// Setting `;filename=` on an otherwise-literal `-F` part promotes it to
/// an upload shape: the wire part gains `filename="…"` *and* the default
/// `Content-Type: application/octet-stream`, matching curl's behaviour of
/// "this string is a tiny file, treat it as such".
#[test]
fn cli_form_literal_with_filename_modifier_becomes_upload() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["-F", "blob=hello;filename=hi.txt", &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    let ct = got.1.expect("Content-Type set");
    let boundary = extract_boundary(&ct);
    let part = find_part(&got.2, &boundary, "name=\"blob\"");
    let s = std::str::from_utf8(part).unwrap();
    assert!(
        s.contains("name=\"blob\"; filename=\"hi.txt\"\r\n"),
        ";filename= must promote literal to upload shape: {s}"
    );
    assert!(
        s.contains("Content-Type: application/octet-stream\r\n"),
        "promoted literal needs default octet-stream Content-Type: {s}"
    );
    assert!(
        s.ends_with("\r\n\r\nhello"),
        "promoted literal body must be the literal text: {s}"
    );
}

/// `--data-raw @notafile` must put the literal bytes `@notafile` on the
/// wire — no file read, no error. This is the whole point of `--data-raw`
/// vs `-d` (which would try to open `notafile` and fail).
#[test]
fn cli_data_raw_leaves_at_literal_on_wire() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args(["--data-raw", "@notafile", &server.url("/post")])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    assert_eq!(
        got.1.as_deref(),
        Some("application/x-www-form-urlencoded"),
        "--data-raw still defaults to form-urlencoded"
    );
    assert_eq!(
        got.2, b"@notafile",
        "--data-raw must put the literal `@` text on the wire"
    );
}

/// A user-supplied `Content-Type:` via `-H` must override the per-body
/// default (`application/x-www-form-urlencoded` for `-d`, `multipart/…`
/// for `-F`, `application/octet-stream` for `-T`). We check the `-d`
/// path because it's the most common; the same code path serves all
/// three, so this locks in the contract for everyone.
#[test]
fn cli_custom_content_type_header_overrides_default() {
    use std::process::Command;
    let (server, slot) = capture_one_request();

    let out = Command::new(env!("CARGO_BIN_EXE_rsurl"))
        .args([
            "-H",
            "Content-Type: application/json",
            "-d",
            r#"{"k":"v"}"#,
            &server.url("/post"),
        ])
        .output()
        .expect("spawn rsurl");
    assert!(
        out.status.success(),
        "rsurl exited non-zero: {:?}\nstderr: {}",
        out.status,
        String::from_utf8_lossy(&out.stderr)
    );

    let got = slot.lock().unwrap().clone().expect("handler ran");
    assert_eq!(got.0, "POST");
    assert_eq!(
        got.1.as_deref(),
        Some("application/json"),
        "explicit -H Content-Type must win over the per-flag default"
    );
    assert_eq!(got.2, br#"{"k":"v"}"#);
}