day-part-http 0.7.6

Declarative app development API using native UI toolkits
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
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

// ---------------------------------------------------------------------------
// Windows: WinHTTP (winhttp.dll), the system HTTP stack, as the transport beneath the portable
// client: automatic proxy and PAC (WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY), schannel TLS with the
// Windows certificate stores (enterprise and AD roots included), HTTP/2 where the system offers
// it. Every symbol is resolved at run time from winhttp.dll and crypt32.dll, so a missing library
// degrades to `Unsupported` instead of failing to load the process.
//
// One asynchronous session per client (WINHTTP_FLAG_ASYNC): WinHTTP's own thread pool drives each
// exchange and reports through one status callback, so no Rust thread is parked behind a request.
// Redirects come back to the client (WINHTTP_OPTION_REDIRECT_POLICY never), cookies stay with the
// client (WINHTTP_DISABLE_COOKIES), and a body is read only while the client's demand lasts: one
// WinHttpReadData at a time, the next one started by the completion or by a later grant. Uploads
// go out through WinHttpWriteData in pieces, reporting progress, with chunked framing written here
// when the length is unknown. WebSockets upgrade a request (WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET)
// and then run on WinHTTP's WebSocket calls, receiving only while demand lasts.
//
// Closing a handle is WinHTTP's cancellation from any thread. Each handle carries a boxed context
// that STATUS_HANDLE_CLOSING, the handle's last notification, frees.
// ---------------------------------------------------------------------------

#![allow(non_snake_case, clippy::upper_case_acronyms)]

use std::cell::UnsafeCell;
use std::collections::VecDeque;
use std::ffi::c_void;
use std::fmt::Write as _;
use std::io::Read;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock};
use std::time::{Duration, Instant};

use crate::client::{
    Answer, Capabilities, Completion, Event, Events, Head, Message, Metrics, Prepared,
    PreparedBody, QuestionId, Socket, Transfer, Transport, TransportConfig, WsEvent, WsEvents,
};
use crate::{HttpError, Identity, Tier};

pub const TIER: Tier = Tier::NativeStack;

type HINTERNET = *mut c_void;
type DWORD = u32;
type BOOL = i32;
type LPCWSTR = *const u16;

const WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY: DWORD = 4;
const WINHTTP_FLAG_ASYNC: DWORD = 0x1000_0000;
const WINHTTP_FLAG_SECURE: DWORD = 0x0080_0000;
const WINHTTP_ADDREQ_FLAG_ADD: DWORD = 0x2000_0000;
const WINHTTP_QUERY_STATUS_CODE: DWORD = 19;
const WINHTTP_QUERY_RAW_HEADERS_CRLF: DWORD = 22;
const WINHTTP_QUERY_FLAG_NUMBER: DWORD = 0x2000_0000;
/// `WINHTTP_IGNORE_REQUEST_TOTAL_LENGTH`: the length travels in a header, or the body is chunked.
const IGNORE_TOTAL_LENGTH: DWORD = 0;

// WINHTTP_OPTION_* (winhttp.h)
const OPTION_CONTEXT_VALUE: DWORD = 45;
const OPTION_CLIENT_CERT_CONTEXT: DWORD = 47;
const OPTION_DISABLE_FEATURE: DWORD = 63;
const OPTION_MAX_CONNS_PER_SERVER: DWORD = 73;
const OPTION_MAX_CONNS_PER_1_0_SERVER: DWORD = 74;
const OPTION_REDIRECT_POLICY: DWORD = 88;
const OPTION_UPGRADE_TO_WEB_SOCKET: DWORD = 114;
const OPTION_ENABLE_HTTP_PROTOCOL: DWORD = 133;
const OPTION_HTTP_PROTOCOL_USED: DWORD = 134;
const REDIRECT_POLICY_NEVER: DWORD = 0;
const DISABLE_COOKIES: DWORD = 1;
const PROTOCOL_FLAG_HTTP2: DWORD = 0x1;
const PROTOCOL_FLAG_HTTP3: DWORD = 0x2;

// WINHTTP_CALLBACK_STATUS_* (winhttp.h): the notifications the transport acts on.
const WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS: DWORD = 0xFFFF_FFFF;
const STATUS_HANDLE_CLOSING: DWORD = 0x0000_0800;
const STATUS_SENDREQUEST_COMPLETE: DWORD = 0x0040_0000;
const STATUS_HEADERS_AVAILABLE: DWORD = 0x0002_0000;
const STATUS_READ_COMPLETE: DWORD = 0x0008_0000;
const STATUS_REQUEST_ERROR: DWORD = 0x0020_0000;
const STATUS_WRITE_COMPLETE: DWORD = 0x0010_0000;
const STATUS_CLOSE_COMPLETE: DWORD = 0x0200_0000;
/// `WINHTTP_INVALID_STATUS_CALLBACK`: what `WinHttpSetStatusCallback` returns on failure.
const INVALID_STATUS_CALLBACK: usize = usize::MAX;

// WINHTTP_WEB_SOCKET_BUFFER_TYPE
const WS_BINARY_MESSAGE: u32 = 0;
const WS_BINARY_FRAGMENT: u32 = 1;
const WS_UTF8_MESSAGE: u32 = 2;
const WS_UTF8_FRAGMENT: u32 = 3;
const WS_CLOSE: u32 = 4;

// ERROR_WINHTTP_* (winhttp.h; 12000-base)
const E_TIMEOUT: DWORD = 12002;
const E_INVALID_URL: DWORD = 12005;
const E_UNRECOGNIZED_SCHEME: DWORD = 12006;
const E_NAME_NOT_RESOLVED: DWORD = 12007;
const E_OPERATION_CANCELLED: DWORD = 12017;
const E_CANNOT_CONNECT: DWORD = 12029;
const E_CONNECTION_ERROR: DWORD = 12030;
const SECURE_ERRORS: [DWORD; 7] = [12037, 12038, 12044, 12045, 12057, 12157, 12175];

// crypt32.dll
const PKCS12_NO_PERSIST_KEY: DWORD = 0x0000_8000;
const ENCODING_X509_PKCS7: DWORD = 0x0001_0001;
const CERT_FIND_ANY: DWORD = 0;
const CERT_FIND_HAS_PRIVATE_KEY: DWORD = 0x0015_0000;

/// How much one read, write or WebSocket receive moves.
const PIECE: usize = 64 << 10;

/// The status callback the session installs (`WINHTTP_STATUS_CALLBACK`).
type StatusCallback = unsafe extern "system" fn(HINTERNET, usize, DWORD, *mut c_void, DWORD);

/// `WINHTTP_ASYNC_RESULT`, what `STATUS_REQUEST_ERROR` points at.
// Laid out for the C side, which reads fields Rust never does.
#[allow(dead_code)]
#[repr(C)]
struct AsyncResult {
    result: usize,
    error: DWORD,
}

/// `WINHTTP_WEB_SOCKET_STATUS`, what a WebSocket receive or send completion points at.
#[repr(C)]
struct WsStatus {
    bytes: DWORD,
    buffer_type: u32,
}

/// `CERT_CONTEXT`, whose size `WINHTTP_OPTION_CLIENT_CERT_CONTEXT` takes.
// Laid out for the C side, which reads fields Rust never does.
#[allow(dead_code)]
#[repr(C)]
struct CertContext {
    encoding: DWORD,
    encoded: *const u8,
    encoded_len: DWORD,
    info: *const c_void,
    store: *mut c_void,
}

/// `CRYPT_DATA_BLOB`.
// Laid out for the C side, which reads fields Rust never does.
#[allow(dead_code)]
#[repr(C)]
struct DataBlob {
    len: DWORD,
    data: *const u8,
}

struct Api {
    open: unsafe extern "system" fn(LPCWSTR, DWORD, LPCWSTR, LPCWSTR, DWORD) -> HINTERNET,
    connect: unsafe extern "system" fn(HINTERNET, LPCWSTR, u16, DWORD) -> HINTERNET,
    open_request: unsafe extern "system" fn(
        HINTERNET,
        LPCWSTR,
        LPCWSTR,
        LPCWSTR,
        LPCWSTR,
        *const LPCWSTR,
        DWORD,
    ) -> HINTERNET,
    set_timeouts: unsafe extern "system" fn(HINTERNET, i32, i32, i32, i32) -> BOOL,
    set_option: unsafe extern "system" fn(HINTERNET, DWORD, *const c_void, DWORD) -> BOOL,
    query_option: unsafe extern "system" fn(HINTERNET, DWORD, *mut c_void, *mut DWORD) -> BOOL,
    add_headers: unsafe extern "system" fn(HINTERNET, LPCWSTR, DWORD, DWORD) -> BOOL,
    send: unsafe extern "system" fn(
        HINTERNET,
        LPCWSTR,
        DWORD,
        *const c_void,
        DWORD,
        DWORD,
        usize,
    ) -> BOOL,
    write_data: unsafe extern "system" fn(HINTERNET, *const c_void, DWORD, *mut DWORD) -> BOOL,
    receive: unsafe extern "system" fn(HINTERNET, *mut c_void) -> BOOL,
    query_headers: unsafe extern "system" fn(
        HINTERNET,
        DWORD,
        LPCWSTR,
        *mut c_void,
        *mut DWORD,
        *mut DWORD,
    ) -> BOOL,
    read_data: unsafe extern "system" fn(HINTERNET, *mut c_void, DWORD, *mut DWORD) -> BOOL,
    close: unsafe extern "system" fn(HINTERNET) -> BOOL,
    set_status_callback:
        unsafe extern "system" fn(HINTERNET, Option<StatusCallback>, DWORD, usize) -> usize,
    /// The WebSocket calls, present since Windows 8.
    ws: Option<WsApi>,
}

struct WsApi {
    complete_upgrade: unsafe extern "system" fn(HINTERNET, usize) -> HINTERNET,
    send: unsafe extern "system" fn(HINTERNET, u32, *const c_void, DWORD) -> DWORD,
    receive:
        unsafe extern "system" fn(HINTERNET, *mut c_void, DWORD, *mut DWORD, *mut u32) -> DWORD,
    close: unsafe extern "system" fn(HINTERNET, u16, *const c_void, DWORD) -> DWORD,
    query_close_status:
        unsafe extern "system" fn(HINTERNET, *mut u16, *mut c_void, DWORD, *mut DWORD) -> DWORD,
}

struct Crypt {
    pfx_import: unsafe extern "system" fn(*const DataBlob, LPCWSTR, DWORD) -> *mut c_void,
    find_certificate: unsafe extern "system" fn(
        *mut c_void,
        DWORD,
        DWORD,
        DWORD,
        *const c_void,
        *const CertContext,
    ) -> *const CertContext,
    free_certificate: unsafe extern "system" fn(*const CertContext) -> BOOL,
    close_store: unsafe extern "system" fn(*mut c_void, DWORD) -> BOOL,
}

// SAFETY: function pointers into system libraries that stay loaded for the life of the process.
unsafe impl Send for Api {}
unsafe impl Sync for Api {}
unsafe impl Send for Crypt {}
unsafe impl Sync for Crypt {}

unsafe extern "system" {
    fn LoadLibraryW(name: LPCWSTR) -> *mut c_void;
    fn GetProcAddress(module: *mut c_void, name: *const u8) -> *mut c_void;
    fn GetLastError() -> DWORD;
}

fn wide(s: &str) -> Vec<u16> {
    s.encode_utf16().chain(std::iter::once(0)).collect()
}

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
    m.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}

/// Look a symbol up as a function pointer.
///
/// # Safety
/// `T` must be the pointer type matching the symbol's signature.
unsafe fn symbol<T: Copy>(library: *mut c_void, name: &str) -> Option<T> {
    if std::mem::size_of::<T>() != std::mem::size_of::<*mut c_void>() {
        return None;
    }
    let name: Vec<u8> = name.bytes().chain(std::iter::once(0)).collect();
    // SAFETY: a module handle LoadLibraryW returned and a NUL-terminated name.
    let address = unsafe { GetProcAddress(library, name.as_ptr()) };
    if address.is_null() {
        return None;
    }
    // SAFETY: same size, and the caller names the symbol's true type.
    Some(unsafe { std::mem::transmute_copy::<*mut c_void, T>(&address) })
}

fn api() -> Option<&'static Api> {
    static API: OnceLock<Option<Api>> = OnceLock::new();
    API.get_or_init(|| {
        // SAFETY: a system library name; a missing library returns null.
        let lib = unsafe { LoadLibraryW(wide("winhttp.dll").as_ptr()) };
        if lib.is_null() {
            return None;
        }
        // SAFETY: each symbol is looked up as its documented signature.
        unsafe {
            let ws = (|| {
                Some(WsApi {
                    complete_upgrade: symbol(lib, "WinHttpWebSocketCompleteUpgrade")?,
                    send: symbol(lib, "WinHttpWebSocketSend")?,
                    receive: symbol(lib, "WinHttpWebSocketReceive")?,
                    close: symbol(lib, "WinHttpWebSocketClose")?,
                    query_close_status: symbol(lib, "WinHttpWebSocketQueryCloseStatus")?,
                })
            })();
            Some(Api {
                open: symbol(lib, "WinHttpOpen")?,
                connect: symbol(lib, "WinHttpConnect")?,
                open_request: symbol(lib, "WinHttpOpenRequest")?,
                set_timeouts: symbol(lib, "WinHttpSetTimeouts")?,
                set_option: symbol(lib, "WinHttpSetOption")?,
                query_option: symbol(lib, "WinHttpQueryOption")?,
                add_headers: symbol(lib, "WinHttpAddRequestHeaders")?,
                send: symbol(lib, "WinHttpSendRequest")?,
                write_data: symbol(lib, "WinHttpWriteData")?,
                receive: symbol(lib, "WinHttpReceiveResponse")?,
                query_headers: symbol(lib, "WinHttpQueryHeaders")?,
                read_data: symbol(lib, "WinHttpReadData")?,
                close: symbol(lib, "WinHttpCloseHandle")?,
                set_status_callback: symbol(lib, "WinHttpSetStatusCallback")?,
                ws,
            })
        }
    })
    .as_ref()
}

fn crypt() -> Option<&'static Crypt> {
    static CRYPT: OnceLock<Option<Crypt>> = OnceLock::new();
    CRYPT
        .get_or_init(|| {
            // SAFETY: a system library name; a missing library returns null.
            let lib = unsafe { LoadLibraryW(wide("crypt32.dll").as_ptr()) };
            if lib.is_null() {
                return None;
            }
            // SAFETY: each symbol is looked up as its documented signature.
            unsafe {
                Some(Crypt {
                    pfx_import: symbol(lib, "PFXImportCertStore")?,
                    find_certificate: symbol(lib, "CertFindCertificateInStore")?,
                    free_certificate: symbol(lib, "CertFreeCertificateContext")?,
                    close_store: symbol(lib, "CertCloseStore")?,
                })
            }
        })
        .as_ref()
}

/// What WinHTTP offers on this system; nothing when winhttp.dll does not load.
pub(crate) fn capabilities() -> Capabilities {
    let Some(api) = api() else {
        return Capabilities::default();
    };
    let websockets = api.ws.is_some();
    Capabilities {
        streaming: true,
        upload_streaming: true,
        upload_progress: true,
        manual_redirects: true,
        auth_questions: false,
        native_auth_schemes: false,
        server_trust: false,
        client_identity: crypt().is_some(),
        platform_cookies: false,
        platform_cache: false,
        metrics: true,
        websockets,
        websocket_ping: false,
        websocket_headers: websockets,
        wait_for_connectivity: false,
    }
}

/// The transport for one client: an asynchronous session with the client's settings.
pub(crate) fn transport(config: &TransportConfig) -> Arc<dyn Transport> {
    Arc::new(WinTransport {
        session: Session::open(config),
        identity: config.identity.as_ref().map(ClientCert::import),
    })
}

/// Minimal URL split: (secure, host, port, path and query). `ws` and `wss` map onto `http` and
/// `https`. IPv6 literals and userinfo are not taken (docs/http.md).
fn split_url(url: &str) -> Result<(bool, String, u16, String), HttpError> {
    let bad = || HttpError::BadUrl(url.to_string());
    let (secure, rest) = [
        ("https://", true),
        ("wss://", true),
        ("http://", false),
        ("ws://", false),
    ]
    .iter()
    .find_map(|(scheme, secure)| {
        (url.len() >= scheme.len() && url[..scheme.len()].eq_ignore_ascii_case(scheme))
            .then(|| (*secure, &url[scheme.len()..]))
    })
    .ok_or_else(bad)?;
    let (authority, path) = match rest.find(['/', '?']) {
        Some(i) if rest.as_bytes()[i] == b'?' => (&rest[..i], format!("/{}", &rest[i..])),
        Some(i) => (&rest[..i], rest[i..].to_string()),
        None => (rest, "/".to_string()),
    };
    let path = path.split('#').next().unwrap_or("/").to_string();
    if authority.is_empty() || authority.contains('@') || authority.contains('[') {
        return Err(bad());
    }
    let (host, port) = match authority.rsplit_once(':') {
        Some((h, p)) => (h.to_string(), p.parse::<u16>().map_err(|_| bad())?),
        None => (authority.to_string(), if secure { 443 } else { 80 }),
    };
    Ok((secure, host, port, path))
}

fn map_error(code: DWORD) -> HttpError {
    match code {
        E_TIMEOUT => HttpError::Timeout,
        E_OPERATION_CANCELLED => HttpError::Cancelled,
        E_NAME_NOT_RESOLVED => HttpError::Dns,
        E_CANNOT_CONNECT | E_CONNECTION_ERROR => HttpError::Connect,
        E_INVALID_URL | E_UNRECOGNIZED_SCHEME => HttpError::BadUrl(format!("winhttp {code}")),
        c if SECURE_ERRORS.contains(&c) => HttpError::Tls(format!("winhttp secure failure {c}")),
        c => HttpError::Io(format!("winhttp error {c}")),
    }
}

/// The last error WinHTTP recorded on this thread.
fn last_error() -> HttpError {
    // SAFETY: reads this thread's last-error value.
    map_error(unsafe { GetLastError() })
}

fn set_dword(api: &Api, handle: HINTERNET, option: DWORD, value: DWORD) -> bool {
    // SAFETY: a DWORD option reads `size_of::<DWORD>()` bytes from the pointer for the call.
    unsafe {
        (api.set_option)(
            handle,
            option,
            (&raw const value).cast(),
            std::mem::size_of::<DWORD>() as DWORD,
        ) != 0
    }
}

/// One asynchronous session: a client's exchanges share its connection pool, and each keeps it
/// alive until its own handles are gone.
struct Session {
    api: &'static Api,
    handle: HINTERNET,
}

// SAFETY: an HINTERNET is an opaque handle WinHTTP documents as usable from any thread.
unsafe impl Send for Session {}
unsafe impl Sync for Session {}

impl Session {
    fn open(config: &TransportConfig) -> Result<Arc<Session>, HttpError> {
        let api = api().ok_or(HttpError::Unsupported)?;
        // SAFETY: NUL-terminated agent string; null proxy name and bypass for automatic proxy.
        let handle = unsafe {
            (api.open)(
                wide("day-part-http").as_ptr(),
                WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
                std::ptr::null(),
                std::ptr::null(),
                WINHTTP_FLAG_ASYNC,
            )
        };
        if handle.is_null() {
            return Err(last_error());
        }
        let session = Arc::new(Session { api, handle });
        // Every handle opened under the session inherits the callback.
        // SAFETY: a live session handle and a callback that lives for the whole process.
        let previous = unsafe {
            (api.set_status_callback)(
                handle,
                Some(on_status),
                WINHTTP_CALLBACK_FLAG_ALL_NOTIFICATIONS,
                0,
            )
        };
        if previous == INVALID_STATUS_CALLBACK {
            return Err(last_error());
        }
        // HTTP/2 arrived in Windows 10 1607; an older system keeps HTTP/1.1.
        set_dword(
            api,
            handle,
            OPTION_ENABLE_HTTP_PROTOCOL,
            PROTOCOL_FLAG_HTTP2,
        );
        if let Some(limit) = config.max_per_host {
            set_dword(api, handle, OPTION_MAX_CONNS_PER_SERVER, limit.max(1));
            set_dword(api, handle, OPTION_MAX_CONNS_PER_1_0_SERVER, limit.max(1));
        }
        Ok(session)
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // SAFETY: the last reference to the session; every exchange under it is gone.
        unsafe { (self.api.close)(self.handle) };
    }
}

/// A client identity, imported once per client and kept for its exchanges.
struct ClientCert {
    crypt: &'static Crypt,
    store: *mut c_void,
    context: *const CertContext,
}

// SAFETY: a certificate context and store are immutable once imported; crypt32 documents both
// as usable from any thread.
unsafe impl Send for ClientCert {}
unsafe impl Sync for ClientCert {}

impl ClientCert {
    fn import(identity: &Identity) -> Result<Arc<ClientCert>, HttpError> {
        let crypt = crypt().ok_or(HttpError::Unsupported)?;
        let blob = DataBlob {
            len: DWORD::try_from(identity.pkcs12.len())
                .map_err(|_| HttpError::Tls("the client identity is too large".into()))?,
            data: identity.pkcs12.as_ptr(),
        };
        let password = wide(&identity.password);
        // SAFETY: the blob points at bytes that outlive the call; the password is NUL-terminated.
        let mut store = unsafe {
            (crypt.pfx_import)(&raw const blob, password.as_ptr(), PKCS12_NO_PERSIST_KEY)
        };
        if store.is_null() && identity.password.is_empty() {
            // An archive without a password may expect none rather than an empty one.
            // SAFETY: as above, with no password.
            store = unsafe {
                (crypt.pfx_import)(&raw const blob, std::ptr::null(), PKCS12_NO_PERSIST_KEY)
            };
        }
        if store.is_null() {
            // SAFETY: reads this thread's last-error value.
            let code = unsafe { GetLastError() };
            return Err(HttpError::Tls(format!(
                "the client identity could not be read ({code})"
            )));
        }
        let find = |kind: DWORD| {
            // SAFETY: an open store; a null previous context starts the search.
            unsafe {
                (crypt.find_certificate)(
                    store,
                    ENCODING_X509_PKCS7,
                    0,
                    kind,
                    std::ptr::null(),
                    std::ptr::null(),
                )
            }
        };
        let mut context = find(CERT_FIND_HAS_PRIVATE_KEY);
        if context.is_null() {
            context = find(CERT_FIND_ANY);
        }
        if context.is_null() {
            // SAFETY: the store this function opened.
            unsafe { (crypt.close_store)(store, 0) };
            return Err(HttpError::Tls(
                "the client identity holds no certificate".into(),
            ));
        }
        Ok(Arc::new(ClientCert {
            crypt,
            store,
            context,
        }))
    }
}

impl Drop for ClientCert {
    fn drop(&mut self) {
        // SAFETY: the context and store this value imported; WinHTTP holds its own references.
        unsafe {
            (self.crypt.free_certificate)(self.context);
            (self.crypt.close_store)(self.store, 0);
        }
    }
}

struct WinTransport {
    session: Result<Arc<Session>, HttpError>,
    identity: Option<Result<Arc<ClientCert>, HttpError>>,
}

impl WinTransport {
    /// The session and identity an exchange needs, or why it cannot start.
    fn parts(&self) -> Result<(Arc<Session>, Option<Arc<ClientCert>>), HttpError> {
        let session = self.session.clone()?;
        let cert = match &self.identity {
            None => None,
            Some(identity) => Some(identity.clone()?),
        };
        Ok((session, cert))
    }
}

impl Transport for WinTransport {
    fn capabilities(&self) -> Capabilities {
        capabilities()
    }

    fn start(&self, prepared: Prepared, events: Events) -> Arc<dyn Transfer> {
        match self
            .parts()
            .and_then(|(session, cert)| Exchange::begin(session, cert, prepared, events.clone()))
        {
            Ok(exchange) => exchange,
            Err(error) => {
                events(Event::Failed(error));
                Arc::new(Dead)
            }
        }
    }

    fn websocket(&self, prepared: Prepared, events: WsEvents) -> Arc<dyn Socket> {
        let opened = self.parts().and_then(|(session, cert)| {
            let api: &'static Api = session.api;
            let ws = api.ws.as_ref().ok_or(HttpError::Unsupported)?;
            WsConn::begin(session.clone(), ws, cert, prepared, events.clone())
        });
        match opened {
            Ok(socket) => socket,
            Err(error) => {
                events(WsEvent::Failed(error));
                Arc::new(Dead)
            }
        }
    }
}

/// The grip on an exchange or WebSocket that never started.
struct Dead;

impl Transfer for Dead {
    fn demand(&self, _chunks: u32) {}
    fn answer(&self, _id: QuestionId, _answer: Answer) {}
    fn cancel(&self) {}
}

impl Socket for Dead {
    fn send(&self, _message: Message, done: Completion) {
        done(Err(HttpError::Unsupported));
    }
    fn ping(&self, done: Completion) {
        done(Err(HttpError::Unsupported));
    }
    fn close(&self, _code: u16, _reason: &str) {}
    fn demand(&self, _messages: u32) {}
}

/// What one handle's notifications reach. Boxed, and its address is the handle's context value;
/// `STATUS_HANDLE_CLOSING` frees it.
enum Context {
    Exchange(Arc<Exchange>),
    /// The request a WebSocket upgrades.
    Upgrade(Arc<WsConn>),
    /// The WebSocket handle the upgrade returned.
    Socket(Arc<WsConn>),
}

impl Context {
    fn into_raw(self) -> usize {
        Box::into_raw(Box::new(self)) as usize
    }
}

/// Give a request handle its context. On failure the box is freed here, since no notification
/// will carry it.
fn attach(api: &Api, request: HINTERNET, context: Context) -> Result<usize, HttpError> {
    let raw = context.into_raw();
    // SAFETY: a pointer-sized option read from a live local for the call.
    let ok = unsafe {
        (api.set_option)(
            request,
            OPTION_CONTEXT_VALUE,
            (&raw const raw).cast(),
            std::mem::size_of::<usize>() as DWORD,
        )
    };
    if ok == 0 {
        let error = last_error();
        // SAFETY: the box made above, which WinHTTP never received.
        drop(unsafe { Box::from_raw(raw as *mut Context) });
        return Err(error);
    }
    Ok(raw)
}

/// The session's status callback, on one of WinHTTP's threads. `context` is 0 for the session and
/// connection handles, whose notifications carry nothing the transport acts on.
unsafe extern "system" fn on_status(
    handle: HINTERNET,
    context: usize,
    status: DWORD,
    info: *mut c_void,
    info_len: DWORD,
) {
    if context == 0 {
        return;
    }
    let raw = context as *mut Context;
    if status == STATUS_HANDLE_CLOSING {
        // SAFETY: boxed by `Context::into_raw`, and no notification follows this one.
        let context = unsafe { Box::from_raw(raw) };
        match *context {
            Context::Exchange(exchange) => exchange.closed(),
            Context::Upgrade(conn) => conn.request_closed(),
            Context::Socket(conn) => conn.socket_closed(),
        }
        return;
    }
    // SAFETY: the box stays alive until STATUS_HANDLE_CLOSING above.
    let context = unsafe { &*raw };
    // SAFETY: WinHTTP documents `info` per notification; each handler reads only that shape.
    let error = || {
        if info.is_null() {
            E_CONNECTION_ERROR
        } else {
            unsafe { (*(info as *const AsyncResult)).error }
        }
    };
    match context {
        Context::Exchange(exchange) => match status {
            STATUS_SENDREQUEST_COMPLETE => exchange.write_next(),
            STATUS_WRITE_COMPLETE => exchange.written(),
            STATUS_HEADERS_AVAILABLE => exchange.head(),
            STATUS_READ_COMPLETE => exchange.read(info_len as usize),
            STATUS_REQUEST_ERROR => exchange.fail(map_error(error())),
            _ => {}
        },
        Context::Upgrade(conn) => match status {
            STATUS_SENDREQUEST_COMPLETE => conn.receive_response(),
            STATUS_HEADERS_AVAILABLE => conn.upgrade(),
            STATUS_REQUEST_ERROR => conn.fail(map_error(error())),
            _ => {}
        },
        Context::Socket(conn) => {
            let ws_status = || {
                // SAFETY: a WebSocket completion points at a WINHTTP_WEB_SOCKET_STATUS.
                (!info.is_null()).then(|| unsafe { &*(info as *const WsStatus) })
            };
            match status {
                STATUS_READ_COMPLETE => match ws_status() {
                    Some(s) => conn.received(s.bytes as usize, s.buffer_type),
                    None => conn.fail(HttpError::Io("the WebSocket receive failed".into())),
                },
                STATUS_WRITE_COMPLETE => conn.sent(),
                STATUS_CLOSE_COMPLETE => conn.close_complete(handle),
                STATUS_REQUEST_ERROR => conn.request_error(error()),
                _ => {}
            }
        }
    }
}

/// A connection and request handle, before a context owns them.
struct Opened {
    connection: HINTERNET,
    request: HINTERNET,
}

impl Opened {
    fn close(&self, api: &Api) {
        // SAFETY: handles this exchange opened and no context owns yet.
        unsafe {
            (api.close)(self.request);
            (api.close)(self.connection);
        }
    }
}

/// Open a request with the transport's fixed options: the idle bound, redirects and cookies left
/// to the client, the client identity, and the request headers.
fn open_request(
    session: &Session,
    cert: Option<&ClientCert>,
    method: &str,
    url: &str,
    headers: &[(String, String)],
    idle: Duration,
) -> Result<Opened, HttpError> {
    let api = session.api;
    let (secure, host, port, path) = split_url(url)?;
    // SAFETY: a live session handle and NUL-terminated strings that outlive each call.
    unsafe {
        let connection = (api.connect)(session.handle, wide(&host).as_ptr(), port, 0);
        if connection.is_null() {
            return Err(last_error());
        }
        let request = (api.open_request)(
            connection,
            wide(method).as_ptr(),
            wide(&path).as_ptr(),
            std::ptr::null(),
            std::ptr::null(),
            std::ptr::null(),
            if secure { WINHTTP_FLAG_SECURE } else { 0 },
        );
        if request.is_null() {
            let error = last_error();
            (api.close)(connection);
            return Err(error);
        }
        let opened = Opened {
            connection,
            request,
        };
        let ms = i32::try_from(idle.as_millis()).unwrap_or(i32::MAX).max(1);
        (api.set_timeouts)(request, ms, ms, ms, ms);
        set_dword(api, request, OPTION_REDIRECT_POLICY, REDIRECT_POLICY_NEVER);
        set_dword(api, request, OPTION_DISABLE_FEATURE, DISABLE_COOKIES);
        match cert {
            Some(cert) => {
                (api.set_option)(
                    request,
                    OPTION_CLIENT_CERT_CONTEXT,
                    cert.context.cast(),
                    std::mem::size_of::<CertContext>() as DWORD,
                );
            }
            // WINHTTP_NO_CLIENT_CERT_CONTEXT: a server that asks for a certificate gets none,
            // and answers as it does to any client without one.
            None => {
                (api.set_option)(request, OPTION_CLIENT_CERT_CONTEXT, std::ptr::null(), 0);
            }
        }
        if !headers.is_empty() {
            let joined = headers.iter().fold(String::new(), |mut block, (k, v)| {
                let _ = write!(block, "{k}: {v}\r\n");
                block
            });
            let joined = wide(&joined);
            // A length of -1 takes the whole NUL-terminated string.
            if (api.add_headers)(
                request,
                joined.as_ptr(),
                DWORD::MAX,
                WINHTTP_ADDREQ_FLAG_ADD,
            ) == 0
            {
                let error = last_error();
                opened.close(api);
                return Err(error);
            }
        }
        Ok(opened)
    }
}

/// The response head once WinHTTP has it: the numeric status and the raw headers
/// (`"HTTP/1.1 200 OK\r\nK: V\r\n…"`, first line dropped).
fn read_head(api: &Api, request: HINTERNET) -> Result<(u16, Vec<(String, String)>), HttpError> {
    let mut status: DWORD = 0;
    let mut len = std::mem::size_of::<DWORD>() as DWORD;
    // SAFETY: a numeric query writes one DWORD into `status`.
    let ok = unsafe {
        (api.query_headers)(
            request,
            WINHTTP_QUERY_STATUS_CODE | WINHTTP_QUERY_FLAG_NUMBER,
            std::ptr::null(),
            (&raw mut status).cast(),
            &raw mut len,
            std::ptr::null_mut(),
        )
    };
    if ok == 0 {
        return Err(last_error());
    }
    let mut headers = Vec::new();
    let mut bytes: DWORD = 0;
    // SAFETY: a null buffer asks for the size in bytes.
    unsafe {
        (api.query_headers)(
            request,
            WINHTTP_QUERY_RAW_HEADERS_CRLF,
            std::ptr::null(),
            std::ptr::null_mut(),
            &raw mut bytes,
            std::ptr::null_mut(),
        )
    };
    if bytes > 0 {
        let mut buf = vec![0u16; (bytes as usize).div_ceil(2)];
        // SAFETY: `buf` holds `bytes` bytes of UTF-16.
        let ok = unsafe {
            (api.query_headers)(
                request,
                WINHTTP_QUERY_RAW_HEADERS_CRLF,
                std::ptr::null(),
                buf.as_mut_ptr().cast(),
                &raw mut bytes,
                std::ptr::null_mut(),
            )
        };
        if ok != 0 {
            let raw = String::from_utf16_lossy(&buf[..(bytes as usize / 2).min(buf.len())]);
            for line in raw.lines().skip(1) {
                if let Some((k, v)) = line.split_once(':') {
                    headers.push((k.trim().to_string(), v.trim().to_string()));
                }
            }
        }
    }
    Ok((u16::try_from(status).unwrap_or(0), headers))
}

fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_str())
}

// ---------------------------------------------------------------------------
// Exchanges
// ---------------------------------------------------------------------------

/// Where an upload's bytes come from.
enum Source {
    None,
    Bytes { data: Arc<Vec<u8>>, at: usize },
    File(std::fs::File),
    Stream(Box<dyn Read + Send>),
}

fn read_some(reader: &mut dyn Read, buf: &mut [u8]) -> Result<usize, HttpError> {
    loop {
        match reader.read(buf) {
            Ok(n) => return Ok(n),
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(e) => return Err(HttpError::Io(e.to_string())),
        }
    }
}

/// A request body on its way out, one piece per `WinHttpWriteData`.
struct Upload {
    source: Source,
    /// Body bytes still to send, when the length is known.
    remaining: Option<u64>,
    total: Option<u64>,
    chunked: bool,
    finished: bool,
    sent: u64,
    /// The piece in flight, kept alive until `STATUS_WRITE_COMPLETE`, and the body bytes it carries
    /// (a chunk's framing is not body).
    out: Vec<u8>,
    out_body: usize,
}

impl Upload {
    /// Fill `out` with the next piece; `false` once the body is out.
    fn next(&mut self) -> Result<bool, HttpError> {
        if self.finished {
            return Ok(false);
        }
        let limit = self.remaining.map_or(PIECE, |r| {
            usize::try_from(r.min(PIECE as u64)).unwrap_or(PIECE)
        });
        let mut data = vec![0u8; limit];
        let n = if limit == 0 {
            0
        } else {
            match &mut self.source {
                Source::None => 0,
                Source::Bytes { data: bytes, at } => {
                    let n = (bytes.len() - *at).min(limit);
                    data[..n].copy_from_slice(&bytes[*at..*at + n]);
                    *at += n;
                    n
                }
                Source::File(file) => read_some(file, &mut data)?,
                Source::Stream(reader) => read_some(reader.as_mut(), &mut data)?,
            }
        };
        data.truncate(n);
        if let Some(remaining) = &mut self.remaining {
            if n == 0 && *remaining > 0 {
                return Err(HttpError::Io(
                    "the request body ended before its declared length".into(),
                ));
            }
            *remaining -= n as u64;
        }
        self.out_body = n;
        if n == 0 {
            self.finished = true;
            if !self.chunked {
                return Ok(false);
            }
            self.out = b"0\r\n\r\n".to_vec();
        } else if self.chunked {
            let mut framed = format!("{n:X}\r\n").into_bytes();
            framed.extend_from_slice(&data);
            framed.extend_from_slice(b"\r\n");
            self.out = framed;
        } else {
            self.out = data;
        }
        Ok(true)
    }
}

struct ExState {
    events: Option<Events>,
    head: bool,
    reading: bool,
    demand: u32,
    closing: bool,
    first_byte: Option<Duration>,
    received: u64,
    /// The body length the head declared. WinHTTP ends a body cut short by a closed connection
    /// like a complete one, with a read of zero bytes, so `read` holds that read to this length.
    expected: Option<u64>,
}

/// One HTTP exchange: its handles, its upload, and the reads its demand allows.
struct Exchange {
    session: Arc<Session>,
    _identity: Option<Arc<ClientCert>>,
    connection: HINTERNET,
    request: HINTERNET,
    url: String,
    /// A HEAD request, whose `Content-Length` describes a body that never follows.
    head_only: bool,
    started: Instant,
    /// Filled by the one read in flight; `ExState::reading` keeps everything else away from it.
    buffer: UnsafeCell<Box<[u8]>>,
    state: Mutex<ExState>,
    upload: Mutex<Upload>,
}

// SAFETY: WinHTTP handles are usable from any thread. The read buffer is written only by the read
// in flight and read only by that read's completion, and `ExState::reading`, taken under the lock,
// admits one read at a time.
unsafe impl Send for Exchange {}
unsafe impl Sync for Exchange {}

impl Exchange {
    #[expect(
        clippy::needless_pass_by_value,
        reason = "the exchange takes over its caller's shares of the session and identity"
    )]
    fn begin(
        session: Arc<Session>,
        identity: Option<Arc<ClientCert>>,
        prepared: Prepared,
        events: Events,
    ) -> Result<Arc<Exchange>, HttpError> {
        let api = session.api;
        let mut headers: Vec<(String, String)> = prepared
            .headers
            .iter()
            .filter(|(k, _)| {
                !k.eq_ignore_ascii_case("content-length")
                    && !k.eq_ignore_ascii_case("transfer-encoding")
            })
            .cloned()
            .collect();
        let length = match &prepared.body {
            PreparedBody::Empty => Some(0),
            PreparedBody::Bytes(data) => Some(data.len() as u64),
            PreparedBody::File { len, .. } => Some(*len),
            PreparedBody::Stream { len, .. } => *len,
        };
        let source = match prepared.body {
            PreparedBody::Empty => Source::None,
            PreparedBody::Bytes(data) => Source::Bytes { data, at: 0 },
            PreparedBody::File { path, .. } => {
                Source::File(std::fs::File::open(&path).map_err(|e| HttpError::Io(e.to_string()))?)
            }
            PreparedBody::Stream { reader, .. } => {
                Source::Stream(reader.take().ok_or_else(|| {
                    HttpError::Io("the request body stream was already sent".into())
                })?)
            }
        };
        // WinHttpSendRequest takes a 32-bit length: a longer body declares its own, and a body of
        // unknown length goes out chunked, framed by `Upload::next`.
        let total_length = if let Some(n) = length {
            DWORD::try_from(n).unwrap_or_else(|_| {
                headers.push(("Content-Length".into(), n.to_string()));
                IGNORE_TOTAL_LENGTH
            })
        } else {
            headers.push(("Transfer-Encoding".into(), "chunked".into()));
            IGNORE_TOTAL_LENGTH
        };
        let opened = open_request(
            &session,
            identity.as_deref(),
            &prepared.method,
            &prepared.url,
            &headers,
            prepared.timeout_idle,
        )?;
        let exchange = Arc::new(Exchange {
            session: session.clone(),
            _identity: identity,
            connection: opened.connection,
            request: opened.request,
            url: prepared.url,
            head_only: prepared.method.eq_ignore_ascii_case("HEAD"),
            started: Instant::now(),
            buffer: UnsafeCell::new(vec![0u8; PIECE].into_boxed_slice()),
            state: Mutex::new(ExState {
                events: Some(events),
                head: false,
                reading: false,
                demand: 0,
                closing: false,
                first_byte: None,
                received: 0,
                expected: None,
            }),
            upload: Mutex::new(Upload {
                source,
                remaining: length,
                total: length,
                chunked: length.is_none(),
                finished: false,
                sent: 0,
                out: Vec::new(),
                out_body: 0,
            }),
        });
        let context = match attach(api, exchange.request, Context::Exchange(exchange.clone())) {
            Ok(context) => context,
            Err(error) => {
                opened.close(api);
                return Err(error);
            }
        };
        // SAFETY: a live request handle with its context; the body follows through
        // WinHttpWriteData once the send completes.
        let ok = unsafe {
            (api.send)(
                exchange.request,
                std::ptr::null(),
                0,
                std::ptr::null(),
                0,
                total_length,
                context,
            )
        };
        if ok == 0 {
            exchange.fail(last_error());
        }
        Ok(exchange)
    }

    fn api(&self) -> &'static Api {
        self.session.api
    }

    fn emit(&self, event: Event) {
        let events = lock(&self.state).events.clone();
        if let Some(events) = events {
            events(event);
        }
    }

    /// Write the next piece of the body, or ask for the response once the body is out.
    fn write_next(&self) {
        if lock(&self.state).events.is_none() {
            return;
        }
        let piece = {
            let mut upload = lock(&self.upload);
            upload
                .next()
                .map(|more| more.then(|| (upload.out.as_ptr(), upload.out.len())))
        };
        match piece {
            Ok(Some((data, len))) => {
                // SAFETY: the piece stays in `Upload::out`, untouched, until STATUS_WRITE_COMPLETE;
                // a piece is at most `PIECE` bytes and framing.
                let ok = unsafe {
                    (self.api().write_data)(
                        self.request,
                        data.cast(),
                        len as DWORD,
                        std::ptr::null_mut(),
                    )
                };
                if ok == 0 {
                    self.fail(last_error());
                }
            }
            Ok(None) => self.receive_response(),
            Err(error) => self.fail(error),
        }
    }

    fn written(&self) {
        let (sent, total, body) = {
            let mut upload = lock(&self.upload);
            upload.sent += upload.out_body as u64;
            (upload.sent, upload.total, upload.out_body)
        };
        if body > 0 {
            self.emit(Event::Sent { sent, total });
        }
        self.write_next();
    }

    fn receive_response(&self) {
        // SAFETY: a live request handle whose request went out; the reserved argument is null.
        if unsafe { (self.api().receive)(self.request, std::ptr::null_mut()) } == 0 {
            self.fail(last_error());
        }
    }

    fn head(&self) {
        let (status, headers) = match read_head(self.api(), self.request) {
            Ok(head) => head,
            Err(error) => return self.fail(error),
        };
        // An encoded body's declared length is not the length the reader receives.
        let expected_length = match header(&headers, "content-encoding") {
            Some(encoding) if !encoding.eq_ignore_ascii_case("identity") => None,
            _ => header(&headers, "content-length").and_then(|v| v.trim().parse().ok()),
        };
        {
            let mut st = lock(&self.state);
            st.head = true;
            st.first_byte = Some(self.started.elapsed());
            let bodiless = self.head_only || matches!(status, 100..=199 | 204 | 304);
            st.expected = expected_length.filter(|_| !bodiless);
        }
        self.emit(Event::Head(Head {
            status,
            headers,
            url: self.url.clone(),
            expected_length,
        }));
        self.pump();
    }

    /// Start a read when the head is in, demand remains and none is in flight.
    fn pump(&self) {
        {
            let mut st = lock(&self.state);
            if st.events.is_none() || !st.head || st.reading || st.demand == 0 {
                return;
            }
            st.reading = true;
        }
        // SAFETY: `reading` keeps every other read, and every reader of the buffer, away until
        // this read completes.
        let ok = unsafe {
            (self.api().read_data)(
                self.request,
                (*self.buffer.get()).as_mut_ptr().cast(),
                PIECE as DWORD,
                std::ptr::null_mut(),
            )
        };
        if ok == 0 {
            self.fail(last_error());
        }
    }

    fn read(&self, n: usize) {
        if n == 0 {
            let short = {
                let mut st = lock(&self.state);
                st.reading = false;
                let received = st.received;
                st.expected
                    .filter(|&want| received < want)
                    .map(|want| (received, want))
            };
            if let Some((received, want)) = short {
                return self.fail(HttpError::Io(format!(
                    "the connection closed after {received} of {want} body bytes"
                )));
            }
            return self.finish();
        }
        // SAFETY: the read that just completed wrote `n` bytes, and `reading` is still set.
        let buffer: &[u8] = unsafe { &*self.buffer.get() };
        let chunk = buffer[..n.min(PIECE)].to_vec();
        {
            let mut st = lock(&self.state);
            st.reading = false;
            st.demand = st.demand.saturating_sub(1);
            st.received += n as u64;
        }
        self.emit(Event::Chunk(chunk));
        self.pump();
    }

    fn finish(&self) {
        let (events, first_byte, received) = {
            let mut st = lock(&self.state);
            (st.events.take(), st.first_byte, st.received)
        };
        let Some(events) = events else {
            return;
        };
        let sent = lock(&self.upload).sent;
        events(Event::Metrics(Metrics {
            first_byte,
            total: Some(self.started.elapsed()),
            protocol: self.protocol(),
            bytes_sent: Some(sent),
            bytes_received: Some(received),
            ..Metrics::default()
        }));
        events(Event::End);
        self.close();
    }

    fn protocol(&self) -> Option<String> {
        let mut flags: DWORD = 0;
        let mut len = std::mem::size_of::<DWORD>() as DWORD;
        // SAFETY: a DWORD option query into a live local.
        let ok = unsafe {
            (self.api().query_option)(
                self.request,
                OPTION_HTTP_PROTOCOL_USED,
                (&raw mut flags).cast(),
                &raw mut len,
            )
        };
        (ok != 0).then(|| {
            if flags & PROTOCOL_FLAG_HTTP3 != 0 {
                "h3".to_string()
            } else if flags & PROTOCOL_FLAG_HTTP2 != 0 {
                "h2".to_string()
            } else {
                "http/1.1".to_string()
            }
        })
    }

    fn fail(&self, error: HttpError) {
        let events = lock(&self.state).events.take();
        if let Some(events) = events {
            events(Event::Failed(error));
        }
        self.close();
    }

    /// Close the request handle once. Its last notification frees the context.
    fn close(&self) {
        {
            let mut st = lock(&self.state);
            if st.closing {
                return;
            }
            st.closing = true;
        }
        // SAFETY: the request handle, closed exactly once; closing cancels whatever is pending.
        unsafe { (self.api().close)(self.request) };
    }

    /// `STATUS_HANDLE_CLOSING`: the request handle is gone.
    fn closed(&self) {
        let events = lock(&self.state).events.take();
        if let Some(events) = events {
            events(Event::Failed(HttpError::Io("the request closed".into())));
        }
        // SAFETY: the connection handle this exchange opened, whose request is gone.
        unsafe { (self.api().close)(self.connection) };
    }
}

impl Transfer for Exchange {
    fn demand(&self, chunks: u32) {
        {
            let mut st = lock(&self.state);
            st.demand = st.demand.saturating_add(chunks);
        }
        self.pump();
    }

    fn answer(&self, _id: QuestionId, _answer: Answer) {}

    fn cancel(&self) {
        let events = lock(&self.state).events.take();
        if let Some(events) = events {
            events(Event::Failed(HttpError::Cancelled));
        }
        self.close();
    }
}

// ---------------------------------------------------------------------------
// WebSockets
// ---------------------------------------------------------------------------

/// The longest close reason the protocol carries.
const CLOSE_REASON_MAX: usize = 123;

struct WsState {
    events: Option<WsEvents>,
    socket: HINTERNET,
    open: bool,
    request_closing: bool,
    socket_closing: bool,
    /// The app started the closing handshake: the close completion reports the peer's answer.
    closing: bool,
    demand: u32,
    receiving: bool,
    message: Vec<u8>,
    queue: VecDeque<(u32, Vec<u8>, Completion)>,
    /// The message in flight, kept alive until `STATUS_WRITE_COMPLETE`, and its completion.
    sending: Vec<u8>,
    sending_done: Option<Completion>,
}

/// What a completed receive amounts to.
enum Received {
    More,
    Message(Message),
    Close,
}

/// One WebSocket: the request that upgrades, then the socket handle the upgrade returns.
struct WsConn {
    session: Arc<Session>,
    ws: &'static WsApi,
    _identity: Option<Arc<ClientCert>>,
    connection: HINTERNET,
    request: HINTERNET,
    /// Filled by the one receive in flight; `WsState::receiving` keeps everything else away.
    buffer: UnsafeCell<Box<[u8]>>,
    state: Mutex<WsState>,
}

// SAFETY: as for `Exchange`: WinHTTP handles are usable from any thread, and
// `WsState::receiving`, taken under the lock, admits one receive at a time into the buffer.
unsafe impl Send for WsConn {}
unsafe impl Sync for WsConn {}

fn refuse(waiting: Vec<Completion>) {
    for done in waiting {
        done(Err(HttpError::Io("the WebSocket is closed".into())));
    }
}

impl WsConn {
    #[expect(
        clippy::needless_pass_by_value,
        reason = "the connection takes over its caller's shares of the session and identity"
    )]
    fn begin(
        session: Arc<Session>,
        ws: &'static WsApi,
        identity: Option<Arc<ClientCert>>,
        prepared: Prepared,
        events: WsEvents,
    ) -> Result<Arc<WsConn>, HttpError> {
        let api = session.api;
        let mut headers = prepared.headers.clone();
        if !prepared.protocols.is_empty() {
            headers.push((
                "Sec-WebSocket-Protocol".into(),
                prepared.protocols.join(", "),
            ));
        }
        let opened = open_request(
            &session,
            identity.as_deref(),
            "GET",
            &prepared.url,
            &headers,
            prepared.timeout_idle,
        )?;
        // SAFETY: the upgrade option takes no buffer.
        let ok = unsafe {
            (api.set_option)(
                opened.request,
                OPTION_UPGRADE_TO_WEB_SOCKET,
                std::ptr::null(),
                0,
            )
        };
        if ok == 0 {
            let error = last_error();
            opened.close(api);
            return Err(error);
        }
        let conn = Arc::new(WsConn {
            session: session.clone(),
            ws,
            _identity: identity,
            connection: opened.connection,
            request: opened.request,
            buffer: UnsafeCell::new(vec![0u8; PIECE].into_boxed_slice()),
            state: Mutex::new(WsState {
                events: Some(events),
                socket: std::ptr::null_mut(),
                open: false,
                request_closing: false,
                socket_closing: false,
                closing: false,
                demand: 0,
                receiving: false,
                message: Vec::new(),
                queue: VecDeque::new(),
                sending: Vec::new(),
                sending_done: None,
            }),
        });
        let context = match attach(api, conn.request, Context::Upgrade(conn.clone())) {
            Ok(context) => context,
            Err(error) => {
                opened.close(api);
                return Err(error);
            }
        };
        // SAFETY: a live request handle with its context, and no body.
        let ok = unsafe {
            (api.send)(
                conn.request,
                std::ptr::null(),
                0,
                std::ptr::null(),
                0,
                0,
                context,
            )
        };
        if ok == 0 {
            conn.fail(last_error());
        }
        Ok(conn)
    }

    fn receive_response(&self) {
        // SAFETY: a live request handle whose request went out; the reserved argument is null.
        if unsafe { (self.session.api.receive)(self.request, std::ptr::null_mut()) } == 0 {
            self.fail(last_error());
        }
    }

    /// The upgrade response: a 101 becomes the socket, anything else a failure.
    fn upgrade(self: &Arc<Self>) {
        let (status, headers) = match read_head(self.session.api, self.request) {
            Ok(head) => head,
            Err(error) => return self.fail(error),
        };
        if status != 101 {
            return self.fail(HttpError::Io(format!(
                "the server answered {status} to the upgrade"
            )));
        }
        let protocol = header(&headers, "sec-websocket-protocol")
            .map(str::to_string)
            .filter(|p| !p.is_empty());
        let raw = Context::Socket(self.clone()).into_raw();
        // SAFETY: a request whose upgrade response arrived; the box becomes the socket's context.
        let socket = unsafe { (self.ws.complete_upgrade)(self.request, raw) };
        if socket.is_null() {
            let error = last_error();
            // SAFETY: no socket handle exists, so no notification carries the box.
            drop(unsafe { Box::from_raw(raw as *mut Context) });
            return self.fail(error);
        }
        let events = {
            let mut st = lock(&self.state);
            st.socket = socket;
            st.open = true;
            st.events.clone()
        };
        // The request handle has done its work; the socket runs on its own.
        self.close_request();
        let Some(events) = events else {
            // Closed while the upgrade completed.
            return self.close_socket();
        };
        events(WsEvent::Open { protocol });
        self.flush();
        self.pump();
    }

    /// Start a receive while the socket is open, demand remains and none is in flight.
    fn pump(&self) {
        let socket = {
            let mut st = lock(&self.state);
            if st.events.is_none()
                || !st.open
                || st.socket_closing
                || st.closing
                || st.receiving
                || st.demand == 0
            {
                return;
            }
            st.receiving = true;
            st.socket
        };
        // SAFETY: `receiving` keeps the buffer to this receive until it completes.
        let rc = unsafe {
            (self.ws.receive)(
                socket,
                (*self.buffer.get()).as_mut_ptr().cast(),
                PIECE as DWORD,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
            )
        };
        if rc != 0 {
            lock(&self.state).receiving = false;
            self.fail(map_error(rc));
        }
    }

    fn received(&self, n: usize, kind: u32) {
        let (events, got) = {
            let mut st = lock(&self.state);
            // SAFETY: the receive that just completed wrote `n` bytes, and `receiving` is still set.
            let buffer: &[u8] = unsafe { &*self.buffer.get() };
            let bytes = &buffer[..n.min(PIECE)];
            st.message.extend_from_slice(bytes);
            st.receiving = false;
            #[expect(
                clippy::match_same_arms,
                reason = "the fragment arm names the two frame types the catch-all would otherwise hide"
            )]
            let got = match kind {
                WS_BINARY_MESSAGE => {
                    Received::Message(Message::Binary(std::mem::take(&mut st.message)))
                }
                WS_UTF8_MESSAGE => {
                    let text = std::mem::take(&mut st.message);
                    Received::Message(Message::Text(String::from_utf8_lossy(&text).into_owned()))
                }
                WS_CLOSE => {
                    st.message.clear();
                    Received::Close
                }
                // A fragment: the rest of the message follows.
                WS_BINARY_FRAGMENT | WS_UTF8_FRAGMENT => Received::More,
                _ => Received::More,
            };
            if matches!(got, Received::Message(_)) {
                st.demand = st.demand.saturating_sub(1);
            }
            (st.events.clone(), got)
        };
        match got {
            Received::More => self.pump(),
            Received::Message(message) => {
                if let Some(events) = events {
                    events(WsEvent::Message(message));
                }
                self.pump();
            }
            Received::Close => self.peer_closed(),
        }
    }

    /// The peer's close frame: report it, then answer it so the closing handshake completes.
    fn peer_closed(&self) {
        let socket = lock(&self.state).socket;
        let (code, reason) = self.close_status(socket);
        self.closed_with(code, reason, false);
        // 1005, 1006 and 1015 describe a close; none may be sent in one.
        let answer = if matches!(code, 1005 | 1006 | 1015) {
            1000
        } else {
            code
        };
        // SAFETY: the open socket, with no reason.
        let rc = unsafe { (self.ws.close)(socket, answer, std::ptr::null(), 0) };
        if rc != 0 {
            self.close_socket();
        }
    }

    fn close_complete(&self, socket: HINTERNET) {
        let (code, reason) = self.close_status(socket);
        self.closed_with(code, reason, true);
    }

    fn close_status(&self, socket: HINTERNET) -> (u16, String) {
        let mut code: u16 = 1005;
        let mut reason = [0u8; CLOSE_REASON_MAX];
        let mut len: DWORD = 0;
        // SAFETY: a buffer of the protocol's longest reason, and live locals for the outputs.
        let rc = unsafe {
            (self.ws.query_close_status)(
                socket,
                &raw mut code,
                reason.as_mut_ptr().cast(),
                CLOSE_REASON_MAX as DWORD,
                &raw mut len,
            )
        };
        if rc != 0 {
            return (1005, String::new());
        }
        let len = (len as usize).min(CLOSE_REASON_MAX);
        (code, String::from_utf8_lossy(&reason[..len]).into_owned())
    }

    /// Report the close, refuse what waits to go out, and close the socket handle when asked.
    fn closed_with(&self, code: u16, reason: String, close_socket: bool) {
        let (events, waiting) = self.terminal();
        if let Some(events) = events {
            events(WsEvent::Closed { code, reason });
        }
        refuse(waiting);
        if close_socket {
            self.close_socket();
        }
    }

    /// Take the events, so nothing follows, and every send still waiting.
    fn terminal(&self) -> (Option<WsEvents>, Vec<Completion>) {
        let mut st = lock(&self.state);
        let mut waiting: Vec<Completion> = st.queue.drain(..).map(|(_, _, done)| done).collect();
        waiting.extend(st.sending_done.take());
        (st.events.take(), waiting)
    }

    fn sent(&self) {
        let done = lock(&self.state).sending_done.take();
        if let Some(done) = done {
            done(Ok(()));
        }
        self.flush();
    }

    /// Send the next queued message when the socket is open and none is in flight.
    fn flush(&self) {
        loop {
            let (socket, kind, data, len) = {
                let mut st = lock(&self.state);
                if st.events.is_none()
                    || !st.open
                    || st.socket_closing
                    || st.closing
                    || st.sending_done.is_some()
                {
                    return;
                }
                let Some((kind, bytes, done)) = st.queue.pop_front() else {
                    return;
                };
                let Ok(len) = DWORD::try_from(bytes.len()) else {
                    drop(st);
                    done(Err(HttpError::Io(
                        "the message is too large to send".into(),
                    )));
                    continue;
                };
                st.sending = bytes;
                st.sending_done = Some(done);
                (st.socket, kind, st.sending.as_ptr(), len)
            };
            // SAFETY: the message stays in `WsState::sending`, untouched, until
            // STATUS_WRITE_COMPLETE.
            let rc = unsafe { (self.ws.send)(socket, kind, data.cast(), len) };
            if rc == 0 {
                return;
            }
            let done = lock(&self.state).sending_done.take();
            if let Some(done) = done {
                done(Err(map_error(rc)));
            }
        }
    }

    /// `STATUS_REQUEST_ERROR` for the socket. Closing cancels the receive or send in flight, and
    /// `STATUS_CLOSE_COMPLETE` then reports the peer's close, so that cancellation is not a failure.
    fn request_error(&self, code: DWORD) {
        {
            let mut st = lock(&self.state);
            if st.closing && code == E_OPERATION_CANCELLED {
                st.receiving = false;
                return;
            }
        }
        self.fail(map_error(code));
    }

    fn fail(&self, error: HttpError) {
        let (events, waiting) = self.terminal();
        if let Some(events) = events {
            events(WsEvent::Failed(error));
        }
        refuse(waiting);
        self.close_request();
        self.close_socket();
    }

    fn close_request(&self) {
        {
            let mut st = lock(&self.state);
            if st.request_closing {
                return;
            }
            st.request_closing = true;
        }
        // SAFETY: the upgrade request handle, closed exactly once.
        unsafe { (self.session.api.close)(self.request) };
    }

    fn close_socket(&self) {
        let socket = {
            let mut st = lock(&self.state);
            if st.socket.is_null() || st.socket_closing {
                return;
            }
            st.socket_closing = true;
            st.socket
        };
        // SAFETY: the socket handle, closed exactly once.
        unsafe { (self.session.api.close)(socket) };
    }

    /// `STATUS_HANDLE_CLOSING` for the upgrade request.
    fn request_closed(&self) {
        if !lock(&self.state).socket.is_null() {
            return;
        }
        let (events, waiting) = self.terminal();
        if let Some(events) = events {
            events(WsEvent::Failed(HttpError::Io(
                "the WebSocket handshake ended".into(),
            )));
        }
        refuse(waiting);
        // SAFETY: the connection handle this socket opened; its request is gone and no socket
        // came of it.
        unsafe { (self.session.api.close)(self.connection) };
    }

    /// `STATUS_HANDLE_CLOSING` for the socket.
    fn socket_closed(&self) {
        let (events, waiting) = self.terminal();
        if let Some(events) = events {
            events(WsEvent::Closed {
                code: 1006,
                reason: String::new(),
            });
        }
        refuse(waiting);
        // SAFETY: the connection handle this socket opened; the socket is gone.
        unsafe { (self.session.api.close)(self.connection) };
    }
}

impl Socket for WsConn {
    fn send(&self, message: Message, done: Completion) {
        let (kind, bytes) = match message {
            Message::Text(text) => (WS_UTF8_MESSAGE, text.into_bytes()),
            Message::Binary(bytes) => (WS_BINARY_MESSAGE, bytes),
            Message::Close { code, reason } => {
                self.close(code, &reason);
                return done(Ok(()));
            }
        };
        {
            let mut st = lock(&self.state);
            if st.events.is_none() {
                drop(st);
                return done(Err(HttpError::Io("the WebSocket is closed".into())));
            }
            st.queue.push_back((kind, bytes, done));
        }
        self.flush();
    }

    fn ping(&self, done: Completion) {
        done(Err(HttpError::Unsupported));
    }

    fn close(&self, code: u16, reason: &str) {
        let socket = {
            let mut st = lock(&self.state);
            if st.events.is_none() || st.closing {
                return;
            }
            st.closing = st.open;
            st.open.then_some(st.socket)
        };
        let Some(socket) = socket else {
            // Before the upgrade: abandon the handshake.
            self.closed_with(code, reason.to_string(), false);
            return self.close_request();
        };
        let mut end = reason.len().min(CLOSE_REASON_MAX);
        while !reason.is_char_boundary(end) {
            end -= 1;
        }
        let data = if end == 0 {
            std::ptr::null()
        } else {
            reason.as_ptr().cast()
        };
        // SAFETY: the open socket and at most the protocol's longest reason, read for the call.
        let rc = unsafe { (self.ws.close)(socket, code, data, end as DWORD) };
        if rc != 0 {
            self.fail(map_error(rc));
        }
    }

    fn demand(&self, messages: u32) {
        {
            let mut st = lock(&self.state);
            st.demand = st.demand.saturating_add(messages);
        }
        self.pump();
    }
}