wrest 0.5.5

Async HTTP client for Windows backed by WinHTTP, with a reqwest-compatible API
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
//! WinHTTP session, request, query, and I/O wrappers.

use super::{check_win32_bool, last_win32_error, to_wide};
use crate::{Error, error::ContextError, util::wide_to_string};
use windows_sys::Win32::{Foundation::GetLastError, Networking::WinHttp::*};

/// Raw handle type used by WinHTTP (`*mut c_void`).
pub(crate) type RawWinHttpHandle = *mut core::ffi::c_void;

/// Map a WinHTTP handle-returning call to `Result`.
fn check_winhttp_handle(handle: RawWinHttpHandle) -> Result<RawWinHttpHandle, Error> {
    if !handle.is_null() {
        Ok(handle)
    } else {
        Err(last_win32_error())
    }
}

// ---------------------------------------------------------------------------
// WinHTTP session
// ---------------------------------------------------------------------------

/// `WinHttpOpen` -- create a new WinHTTP session handle.
pub(crate) fn winhttp_open_session(
    user_agent: &str,
    access_type: u32,
    proxy: Option<&str>,
    flags: u32,
) -> Result<RawWinHttpHandle, Error> {
    let ua = to_wide(user_agent);
    let proxy_wide = proxy.map(to_wide);
    let proxy_ptr = proxy_wide.as_ref().map_or(std::ptr::null(), |w| w.as_ptr());
    let h = unsafe { WinHttpOpen(ua.as_ptr(), access_type, proxy_ptr, std::ptr::null(), flags) };
    check_winhttp_handle(h)
}

/// `WinHttpCloseHandle`.
pub(crate) fn close_winhttp_handle(handle: RawWinHttpHandle) {
    // Guard: most WinHTTP functions, including `WinHttpCloseHandle`,
    // trigger a STATUS_ACCESS_VIOLATION when passed a null handle
    // instead of returning an error code.  Always check before calling.
    if !handle.is_null() {
        unsafe {
            WinHttpCloseHandle(handle);
        }
    }
}

/// `WinHttpSetStatusCallback` -- install a status callback on a handle.
///
/// Returns `Err` if WinHTTP returns `WINHTTP_INVALID_STATUS_CALLBACK`
/// (the sentinel function pointer with all bits set).
pub(crate) fn winhttp_set_status_callback(
    handle: RawWinHttpHandle,
    callback: WINHTTP_STATUS_CALLBACK,
    notification_flags: u32,
) -> Result<(), Error> {
    unsafe {
        let prev = WinHttpSetStatusCallback(handle, callback, notification_flags, 0);
        // WINHTTP_INVALID_STATUS_CALLBACK is ((WINHTTP_STATUS_CALLBACK)(-1)) in C.
        // windows-sys represents WINHTTP_STATUS_CALLBACK as Option<fn>,
        // so the sentinel is Some(fn-with-all-bits-set).
        let is_invalid = match prev {
            Some(f) => (f as usize) == usize::MAX,
            None => false,
        };
        if is_invalid {
            Err(super::last_win32_error())
        } else {
            Ok(())
        }
    }
}

/// `WinHttpSetTimeouts`.
pub(crate) fn winhttp_set_timeouts(
    handle: RawWinHttpHandle,
    resolve_ms: i32,
    connect_ms: i32,
    send_ms: i32,
    receive_ms: i32,
) -> Result<(), Error> {
    unsafe {
        check_win32_bool(WinHttpSetTimeouts(handle, resolve_ms, connect_ms, send_ms, receive_ms))
    }
}

// ---------------------------------------------------------------------------
// WinHttpSetOption -- typed helpers
// ---------------------------------------------------------------------------

/// `WinHttpSetOption` with a `u32` value.
pub(crate) fn winhttp_set_option_u32(
    handle: RawWinHttpHandle,
    option: u32,
    value: u32,
) -> Result<(), Error> {
    unsafe {
        check_win32_bool(WinHttpSetOption(
            handle,
            option,
            &value as *const u32 as *const core::ffi::c_void,
            std::mem::size_of::<u32>() as u32,
        ))
    }
}

/// `WinHttpSetOption` with a `usize` value (used for `CONTEXT_VALUE`).
pub(crate) fn winhttp_set_option_usize(
    handle: RawWinHttpHandle,
    option: u32,
    value: usize,
) -> Result<(), Error> {
    unsafe {
        check_win32_bool(WinHttpSetOption(
            handle,
            option,
            &value as *const usize as *const core::ffi::c_void,
            std::mem::size_of::<usize>() as u32,
        ))
    }
}

/// `WinHttpSetOption(WINHTTP_OPTION_PROXY)` -- override to direct (no proxy).
pub(crate) fn winhttp_set_proxy_direct(handle: RawWinHttpHandle) -> Result<(), Error> {
    let info = WINHTTP_PROXY_INFO {
        dwAccessType: WINHTTP_ACCESS_TYPE_NO_PROXY,
        lpszProxy: std::ptr::null_mut(),
        lpszProxyBypass: std::ptr::null_mut(),
    };
    unsafe {
        check_win32_bool(WinHttpSetOption(
            handle,
            WINHTTP_OPTION_PROXY,
            &info as *const WINHTTP_PROXY_INFO as *const core::ffi::c_void,
            std::mem::size_of::<WINHTTP_PROXY_INFO>() as u32,
        ))
    }
}

/// `WinHttpSetOption(WINHTTP_OPTION_PROXY)` -- override to a named proxy.
///
/// Encodes the proxy URL to a null-terminated wide string internally so
/// the raw pointer in `WINHTTP_PROXY_INFO` cannot outlive its backing
/// buffer.
pub(crate) fn winhttp_set_proxy_named(
    handle: RawWinHttpHandle,
    proxy_url: &str,
) -> Result<(), Error> {
    let proxy_wide = to_wide(proxy_url);
    let info = WINHTTP_PROXY_INFO {
        dwAccessType: WINHTTP_ACCESS_TYPE_NAMED_PROXY,
        lpszProxy: proxy_wide.as_ptr() as *mut _,
        lpszProxyBypass: std::ptr::null_mut(),
    };
    unsafe {
        check_win32_bool(WinHttpSetOption(
            handle,
            WINHTTP_OPTION_PROXY,
            &info as *const WINHTTP_PROXY_INFO as *const core::ffi::c_void,
            std::mem::size_of::<WINHTTP_PROXY_INFO>() as u32,
        ))
    }
}

// ---------------------------------------------------------------------------
// WinHttpQueryOption / WinHttpQueryHeaders
// ---------------------------------------------------------------------------

/// `WinHttpQueryOption` reading a `u32` value.
///
/// Returns `None` if the option is not supported or the call fails.
pub(crate) fn winhttp_query_option_u32(handle: RawWinHttpHandle, option: u32) -> Option<u32> {
    let mut value: u32 = 0;
    let mut size = std::mem::size_of::<u32>() as u32;
    let ok =
        unsafe { WinHttpQueryOption(handle, option, &mut value as *mut u32 as *mut _, &mut size) };
    if ok != 0 { Some(value) } else { None }
}

/// `WinHttpQueryOption` reading a wide-string value (e.g. `WINHTTP_OPTION_URL`).
///
/// Uses the two-call pattern: first call queries the required buffer size,
/// second call fills the buffer.  Returns `None` if the option is not
/// supported or the call fails.
pub(crate) fn winhttp_query_option_url(handle: RawWinHttpHandle, option: u32) -> Option<String> {
    let mut size: u32 = 0;

    // First call: query required buffer size (in bytes).
    let ok = unsafe { WinHttpQueryOption(handle, option, std::ptr::null_mut(), &mut size) };
    if ok != 0 || size == 0 {
        // Succeeded with a null buffer or zero size -- unexpected for a URL.
        return None;
    }

    // Any error other than ERROR_INSUFFICIENT_BUFFER is a real failure.
    let err = unsafe { GetLastError() };
    if err != windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER {
        return None;
    }

    let len = size as usize / 2;
    let mut buf = vec![0u16; len];
    let ok = unsafe { WinHttpQueryOption(handle, option, buf.as_mut_ptr() as *mut _, &mut size) };
    if ok == 0 {
        return None;
    }

    let actual_len = size as usize / 2;
    buf.truncate(actual_len);
    // Trim trailing null if present.
    if buf.last() == Some(&0) {
        buf.pop();
    }
    Some(String::from_utf16_lossy(&buf))
}

/// `WinHttpQueryHeaders` reading a numeric value (e.g. status code).
pub(crate) fn winhttp_query_header_u32(
    handle: RawWinHttpHandle,
    info_level: u32,
) -> Result<u32, Error> {
    let mut value: u32 = 0;
    let mut size = std::mem::size_of::<u32>() as u32;
    let mut index: u32 = 0;
    unsafe {
        check_win32_bool(WinHttpQueryHeaders(
            handle,
            info_level,
            std::ptr::null(),
            &mut value as *mut u32 as *mut _,
            &mut size,
            &mut index,
        ))?;
    }
    Ok(value)
}

/// `WinHttpQueryHeaders` reading the raw header block as a `String`.
///
/// Uses the two-call pattern (query size, then fill buffer).
pub(crate) fn winhttp_query_raw_headers(handle: RawWinHttpHandle) -> Result<String, Error> {
    let mut size: u32 = 0;
    let mut index: u32 = 0;

    // First call -- query required buffer size.  Expected to fail with
    // ERROR_INSUFFICIENT_BUFFER and populate `size`.
    let ok = unsafe {
        WinHttpQueryHeaders(
            handle,
            WINHTTP_QUERY_RAW_HEADERS_CRLF,
            std::ptr::null(),
            std::ptr::null_mut(),
            &mut size,
            &mut index,
        )
    };

    if ok != 0 {
        // Succeeded with a null buffer -- means there are no headers.
        return Ok(String::new());
    }

    // Any error other than ERROR_INSUFFICIENT_BUFFER is unexpected.
    let err = unsafe { GetLastError() };
    if err != windows_sys::Win32::Foundation::ERROR_INSUFFICIENT_BUFFER {
        return Err(Error::from_win32(err));
    }

    if size == 0 {
        return Ok(String::new());
    }

    let len = size as usize / 2;
    let mut buf = vec![0u16; len];
    index = 0;

    unsafe {
        check_win32_bool(WinHttpQueryHeaders(
            handle,
            WINHTTP_QUERY_RAW_HEADERS_CRLF,
            std::ptr::null(),
            buf.as_mut_ptr() as *mut _,
            &mut size,
            &mut index,
        ))?;
    }

    // Trim to the actual length returned (may be shorter than the buffer).
    let actual_len = size as usize / 2;
    buf.truncate(actual_len);

    // Lossy conversion is appropriate here: HTTP headers are ASCII per
    // RFC 9110 §5.5, and WinHTTP produces well-formed UTF-16 for them.
    // An unpaired surrogate would require a WinHTTP bug or memory
    // corruption -- U+FFFD replacement is harmless compared to failing
    // the entire response.
    Ok(String::from_utf16_lossy(&buf))
}

/// `WinHttpQueryHeaders` reading a short wide-string value into a
/// fixed-size stack buffer, returned as an `Option<String>`.
pub(crate) fn winhttp_query_header_string(
    handle: RawWinHttpHandle,
    info_level: u32,
) -> Option<String> {
    let mut buf = [0u16; 16];
    let mut size = (buf.len() * 2) as u32;
    let mut index: u32 = 0;
    let ok = unsafe {
        WinHttpQueryHeaders(
            handle,
            info_level,
            std::ptr::null(),
            buf.as_mut_ptr() as *mut _,
            &mut size,
            &mut index,
        )
    };
    if ok != 0 {
        let len = size as usize / 2;
        // Lossy: HTTP headers are ASCII (RFC 9110 §5.5); see
        // `query_raw_headers` for rationale.
        buf.get(..len).map(String::from_utf16_lossy)
    } else {
        None
    }
}

// ---------------------------------------------------------------------------
// Connection / request
// ---------------------------------------------------------------------------

/// `WinHttpConnect` -- open a connection to a server.
pub(crate) fn winhttp_connect(
    session: RawWinHttpHandle,
    host: &str,
    port: u16,
) -> Result<RawWinHttpHandle, Error> {
    let host_wide = to_wide(host);
    let h = unsafe { WinHttpConnect(session, host_wide.as_ptr(), port, 0) };
    check_winhttp_handle(h)
}

/// `WinHttpOpenRequest`.
pub(crate) fn winhttp_open_request(
    connect: RawWinHttpHandle,
    method: &str,
    path: &str,
    secure: bool,
) -> Result<RawWinHttpHandle, Error> {
    let method_wide = to_wide(method);
    let path_wide = to_wide(path);
    let flags = if secure { WINHTTP_FLAG_SECURE } else { 0 };
    let h = unsafe {
        WinHttpOpenRequest(
            connect,
            method_wide.as_ptr(),
            path_wide.as_ptr(),
            std::ptr::null(),
            std::ptr::null(),
            std::ptr::null(),
            flags,
        )
    };
    check_winhttp_handle(h)
}

/// `WinHttpAddRequestHeaders` -- append a single header line.
pub(crate) fn winhttp_add_request_header(
    handle: RawWinHttpHandle,
    header_line: &str,
) -> Result<(), Error> {
    let wide: Vec<u16> = header_line.encode_utf16().collect();
    unsafe {
        check_win32_bool(WinHttpAddRequestHeaders(
            handle,
            wide.as_ptr(),
            wide.len() as u32,
            WINHTTP_ADDREQ_FLAG_ADD | WINHTTP_ADDREQ_FLAG_REPLACE,
        ))
    }
}

/// `WinHttpSetCredentials` -- set proxy Basic-auth credentials.
pub(crate) fn winhttp_set_proxy_credentials(
    handle: RawWinHttpHandle,
    username: &str,
    password: &str,
) -> Result<(), Error> {
    let user = to_wide(username);
    let pass = to_wide(password);
    unsafe {
        check_win32_bool(WinHttpSetCredentials(
            handle,
            WINHTTP_AUTH_TARGET_PROXY,
            WINHTTP_AUTH_SCHEME_BASIC,
            user.as_ptr(),
            pass.as_ptr(),
            std::ptr::null_mut(),
        ))
    }
}

// ---------------------------------------------------------------------------
// Async I/O -- send / receive / read / write
// ---------------------------------------------------------------------------

/// `WinHttpSendRequest`.
///
/// `body_ptr` and `body_len` specify optional inline body data.
/// Both are 0 / null when there is no inline body.
pub(crate) fn winhttp_send_request(
    handle: RawWinHttpHandle,
    body_ptr: *const std::ffi::c_void,
    body_len: u32,
    total_content_len: u32,
) -> Result<(), Error> {
    unsafe {
        check_win32_bool(WinHttpSendRequest(
            handle,
            std::ptr::null(),
            0,
            body_ptr,
            body_len,
            total_content_len,
            0,
        ))
    }
}

/// `WinHttpReceiveResponse`.
pub(crate) fn winhttp_receive_response(handle: RawWinHttpHandle) -> Result<(), Error> {
    unsafe { check_win32_bool(WinHttpReceiveResponse(handle, std::ptr::null_mut())) }
}

/// `WinHttpReadData`.
pub(crate) fn winhttp_read_data(
    handle: RawWinHttpHandle,
    buf: *mut std::ffi::c_void,
    buf_len: u32,
) -> Result<(), Error> {
    unsafe { check_win32_bool(WinHttpReadData(handle, buf, buf_len, std::ptr::null_mut())) }
}

/// `WinHttpWriteData`.
pub(crate) fn winhttp_write_data(
    handle: RawWinHttpHandle,
    buf: *const std::ffi::c_void,
    len: u32,
) -> Result<(), Error> {
    unsafe { check_win32_bool(WinHttpWriteData(handle, buf, len, std::ptr::null_mut())) }
}

// ---------------------------------------------------------------------------
// URL parsing
// ---------------------------------------------------------------------------

/// Result of [`winhttp_crack_url`].
#[derive(Debug)]
pub(crate) struct CrackedUrl {
    pub scheme: String,
    pub host: String,
    pub port: u16,
    pub path: String,
    pub extra: String,
}

/// `WinHttpCrackUrl` -- parse a URL into its components.
///
/// Accepts the URL *without* a fragment (caller should strip `#...` first).
pub(crate) fn winhttp_crack_url(url: &str) -> Result<CrackedUrl, Error> {
    // Guard: `WinHttpCrackUrl` with `dwUrlLength = 0` triggers a
    // STATUS_ACCESS_VIOLATION inside winhttp.dll rather than returning
    // an error code.  Catch this before calling into the OS.
    if url.is_empty() {
        return Err(Error::builder("invalid URL: (empty)".to_owned()));
    }
    let wide: Vec<u16> = url.encode_utf16().collect();

    let mut scheme_buf = vec![0u16; 16];
    let mut host_buf = vec![0u16; 2048];
    let mut path_buf = vec![0u16; 8192];
    let mut extra_buf = vec![0u16; 8192];

    let mut components = URL_COMPONENTS {
        dwStructSize: std::mem::size_of::<URL_COMPONENTS>() as u32,
        lpszScheme: scheme_buf.as_mut_ptr(),
        dwSchemeLength: scheme_buf.len() as u32,
        lpszHostName: host_buf.as_mut_ptr(),
        dwHostNameLength: host_buf.len() as u32,
        lpszUrlPath: path_buf.as_mut_ptr(),
        dwUrlPathLength: path_buf.len() as u32,
        lpszExtraInfo: extra_buf.as_mut_ptr(),
        dwExtraInfoLength: extra_buf.len() as u32,
        nScheme: 0,
        nPort: 0,
        lpszUserName: std::ptr::null_mut(),
        dwUserNameLength: 0,
        lpszPassword: std::ptr::null_mut(),
        dwPasswordLength: 0,
    };

    unsafe {
        check_win32_bool(WinHttpCrackUrl(
            wide.as_ptr(),
            wide.len() as u32,
            // No flags -- preserve percent-encoding as-is.
            // ICU_ESCAPE would double-encode: %3d → %253d.
            // ICU_DECODE would decode: %3d → =.
            // Neither is correct for URLs which are already encoded.
            0,
            &mut components,
        ))
        .map_err(|e| Error::builder(ContextError::new(format!("invalid URL: {url}"), e)))?;
    }

    Ok(CrackedUrl {
        scheme: wide_to_string(scheme_buf.as_ptr(), components.dwSchemeLength)?,
        host: wide_to_string(host_buf.as_ptr(), components.dwHostNameLength)?,
        port: components.nPort,
        path: wide_to_string(path_buf.as_ptr(), components.dwUrlPathLength)?,
        extra: wide_to_string(extra_buf.as_ptr(), components.dwExtraInfoLength)?,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn winhttp_crack_url_table() {
        let cases: &[(&str, &str, &str, u16, &str, &str, &str)] = &[
            (
                "https://example.com/path?q=1",
                "https",
                "example.com",
                443,
                "/path",
                "?q=1",
                "simple HTTPS",
            ),
            (
                "http://localhost:8080/api/v1",
                "http",
                "localhost",
                8080,
                "/api/v1",
                "",
                "HTTP with port",
            ),
            // WinHTTP returns an empty path when no path component is present.
            (
                "https://example.com",
                "https",
                "example.com",
                443,
                "",
                "",
                "root without trailing slash",
            ),
            ("http://example.com:80/", "http", "example.com", 80, "/", "", "explicit port 80"),
        ];

        for &(url, scheme, host, port, path, extra, label) in cases {
            let result = winhttp_crack_url(url)
                .unwrap_or_else(|e| panic!("winhttp_crack_url({label}): {e}"));
            assert_eq!(result.scheme, scheme, "{label}: scheme");
            assert_eq!(result.host, host, "{label}: host");
            assert_eq!(result.port, port, "{label}: port");
            assert_eq!(result.path, path, "{label}: path");
            assert_eq!(result.extra, extra, "{label}: extra");
        }
    }

    #[test]
    fn winhttp_crack_url_long_query_string() {
        let long_query = "a=".to_owned() + &"x".repeat(4000);
        let url = format!("https://example.com/search?{long_query}");
        let result = winhttp_crack_url(&url).unwrap();
        assert_eq!(result.path, "/search");
        assert!(result.extra.len() > 4000);
    }

    #[test]
    fn winhttp_crack_url_errors_table() {
        let cases: &[(&str, &str)] = &[("", "empty"), ("not a url at all", "garbage input")];

        for &(input, label) in cases {
            let err = winhttp_crack_url(input).expect_err(&format!("{label}: should fail"));
            assert!(err.is_builder(), "{label}: expected builder error");
        }
    }
}