net-io 0.8.0

Network IO substrate for Rust: TCP, UDP and local-socket listeners, connection lifecycle, limits, graceful drain, PROXY protocol, and a TLS seam. Protocol-free and dependency-free.
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
//! Windows named pipes.
//!
//! A pipe has no readiness and cannot join `WSAPoll`, so `PipeStream` gives the
//! connection core what it expects from a non-blocking socket: `read` and `write`
//! run overlapped against an internal buffer and report `WouldBlock` while the
//! kernel still holds it, and `wait` waits on the operation's event and the wake
//! channel's. Those buffers appear on first use; the reactor reads and writes
//! through its completion port and never allocates them.
//!
//! Every operation's `OVERLAPPED` and buffer live in an allocation of their own,
//! reached only through a raw pointer (the kernel writes them while the operation
//! runs, so no Rust reference may cover them then) and released only after the
//! operation has ended (`Drop`). A kill cancels through `CancelIoEx`.
//!
//! References: Microsoft Learn, "Named Pipes", `CreateNamedPipeW`,
//! `ConnectNamedPipe`, `CreateFileW`, `WaitNamedPipeW`, `GetOverlappedResult`,
//! `ConvertStringSecurityDescriptorToSecurityDescriptorW`. Constants and layouts
//! are checked against `windows-sys` by the tests below.

use std::cell::Cell;
use std::ffi::c_void;
use std::io::{self, IoSlice};
use std::mem::ManuallyDrop;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
use std::ptr::NonNull;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant};

use super::windows::{CancelIoEx, Overlapped, Wake};
use super::{Interest, Ready, Sock, poll_millis};

type Handle = *mut c_void;

const PIPE_ACCESS_DUPLEX: u32 = 3;
const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000;
const FILE_FLAG_FIRST_PIPE_INSTANCE: u32 = 0x0008_0000;
const PIPE_TYPE_BYTE: u32 = 0;
const PIPE_READMODE_BYTE: u32 = 0;
const PIPE_WAIT: u32 = 0;
const PIPE_REJECT_REMOTE_CLIENTS: u32 = 8;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const OPEN_EXISTING: u32 = 3;
const SECURITY_SQOS_PRESENT: u32 = 0x0010_0000;
/// `SECURITY_IDENTIFICATION`: the impersonation level, 1, shifted into place.
const SECURITY_IDENTIFICATION: u32 = 1 << 16;
const SDDL_REVISION_1: u32 = 1;
const TOKEN_QUERY: u32 = 8;
const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;
const TOKEN_USER_CLASS: i32 = 1;
#[cfg(test)]
const TOKEN_OWNER_CLASS: i32 = 4;
/// `SE_KERNEL_OBJECT`: a handle to any kernel object, a pipe included.
const SE_KERNEL_OBJECT: i32 = 6;
const OWNER_SECURITY_INFORMATION: u32 = 1;
const WAIT_TIMEOUT: u32 = 258;
const WAIT_FAILED: u32 = 0xFFFF_FFFF;
const INFINITE: u32 = 0xFFFF_FFFF;

const ERROR_FILE_NOT_FOUND: i32 = 2;
const ERROR_ACCESS_DENIED: i32 = 5;
const ERROR_BROKEN_PIPE: i32 = 109;
const ERROR_SEM_TIMEOUT: i32 = 121;
const ERROR_PIPE_BUSY: i32 = 231;
const ERROR_NO_DATA: i32 = 232;
const ERROR_PIPE_CONNECTED: i32 = 535;
const ERROR_OPERATION_ABORTED: i32 = 995;
const ERROR_IO_INCOMPLETE: i32 = 996;
const ERROR_IO_PENDING: i32 = 997;

/// The bytes one direction keeps in user space.
const BUFFER: usize = 16 * 1024;
/// How long one close waits at most for bytes still in flight.
const CLOSE_FLUSH_MS: u32 = 1_000;
/// What the closes of one thread may wait in all: a credit of [`CLOSE_FLUSH_MS`]
/// that comes back at one tenth of the time passed (100 ms a second). A close
/// whose client reads waits microseconds and gives back what it did not use;
/// clients that never read cost a thread one second, then 10% of its time at
/// most, and the closes past that drop their unsent bytes as a reset would.
const FLUSH_CREDIT_US: u64 = CLOSE_FLUSH_MS as u64 * 1_000;

thread_local! {
    /// The flush credit of this thread in microseconds, and when it was last taken.
    static FLUSH_CREDIT: Cell<Option<(u64, Instant)>> = const { Cell::new(None) };
}

/// Takes what this thread's next close may wait for its flush, in microseconds.
fn take_flush_credit(now: Instant) -> u64 {
    FLUSH_CREDIT
        .try_with(|credit| {
            let (left, at) = credit.get().unwrap_or((FLUSH_CREDIT_US, now));
            let back = u64::try_from(now.saturating_duration_since(at).as_micros() / 10)
                .unwrap_or(u64::MAX);
            let left = left.saturating_add(back).min(FLUSH_CREDIT_US);
            credit.set(Some((0, now)));
            left
        })
        .unwrap_or(0)
}

/// Gives back what a close did not wait of what it took.
fn return_flush_credit(unused: u64) {
    let _ = FLUSH_CREDIT.try_with(|credit| {
        if let Some((left, at)) = credit.get() {
            credit.set(Some((left.saturating_add(unused).min(FLUSH_CREDIT_US), at)));
        }
    });
}

#[repr(C)]
struct SecurityAttributes {
    length: u32,
    descriptor: *mut c_void,
    inherit: i32,
}

#[link(name = "kernel32")]
unsafe extern "system" {
    fn CreateNamedPipeW(
        name: *const u16,
        open_mode: u32,
        pipe_mode: u32,
        max_instances: u32,
        out_size: u32,
        in_size: u32,
        default_timeout: u32,
        attributes: *const SecurityAttributes,
    ) -> Handle;
    fn ConnectNamedPipe(pipe: Handle, overlapped: *mut Overlapped) -> i32;
    fn DisconnectNamedPipe(pipe: Handle) -> i32;
    fn CreateFileW(
        name: *const u16,
        access: u32,
        share: u32,
        attributes: *const SecurityAttributes,
        disposition: u32,
        flags: u32,
        template: Handle,
    ) -> Handle;
    fn WaitNamedPipeW(name: *const u16, timeout: u32) -> i32;
    fn GetNamedPipeClientProcessId(pipe: Handle, pid: *mut u32) -> i32;
    fn GetNamedPipeServerProcessId(pipe: Handle, pid: *mut u32) -> i32;
    fn ReadFile(
        file: Handle,
        buffer: *mut u8,
        len: u32,
        read: *mut u32,
        overlapped: *mut Overlapped,
    ) -> i32;
    fn WriteFile(
        file: Handle,
        buffer: *const u8,
        len: u32,
        written: *mut u32,
        overlapped: *mut Overlapped,
    ) -> i32;
    fn GetOverlappedResult(
        file: Handle,
        overlapped: *const Overlapped,
        transferred: *mut u32,
        wait: i32,
    ) -> i32;
    fn CreateEventW(
        attributes: *const c_void,
        manual: i32,
        initial: i32,
        name: *const u16,
    ) -> Handle;
    fn WaitForMultipleObjects(count: u32, handles: *const Handle, all: i32, ms: u32) -> u32;
    fn WaitForSingleObject(handle: Handle, ms: u32) -> u32;
    fn GetCurrentProcess() -> Handle;
    fn OpenProcess(access: u32, inherit: i32, pid: u32) -> Handle;
    fn GetProcessTimes(
        process: Handle,
        creation: *mut FileTime,
        exit: *mut FileTime,
        kernel: *mut FileTime,
        user: *mut FileTime,
    ) -> i32;
    fn LocalFree(memory: *mut c_void) -> *mut c_void;
}

#[link(name = "advapi32")]
unsafe extern "system" {
    fn OpenProcessToken(process: Handle, access: u32, token: *mut Handle) -> i32;
    fn GetTokenInformation(
        token: Handle,
        class: i32,
        info: *mut c_void,
        len: u32,
        returned: *mut u32,
    ) -> i32;
    fn ConvertSidToStringSidW(sid: *mut c_void, text: *mut *mut u16) -> i32;
    fn GetSecurityInfo(
        handle: Handle,
        object: i32,
        info: u32,
        owner: *mut *mut c_void,
        group: *mut *mut c_void,
        dacl: *mut *mut c_void,
        sacl: *mut *mut c_void,
        descriptor: *mut *mut c_void,
    ) -> u32;
    fn ConvertStringSecurityDescriptorToSecurityDescriptorW(
        text: *const u16,
        revision: u32,
        descriptor: *mut *mut c_void,
        size: *mut u32,
    ) -> i32;
}

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

/// `\\.\pipe\<name>`, terminated.
pub(crate) fn pipe_path(name: &str) -> Vec<u16> {
    wide(&format!(r"\\.\pipe\{name}"))
}

fn is_invalid(h: Handle) -> bool {
    h.is_null() || h as isize == -1
}

fn event() -> io::Result<OwnedHandle> {
    // SAFETY: no attributes, no name; a manual-reset event, not signaled.
    let raw = unsafe { CreateEventW(std::ptr::null(), 1, 0, std::ptr::null()) };
    if raw.is_null() {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `raw` was just returned, is open, and has no other owner.
    Ok(unsafe { OwnedHandle::from_raw_handle(raw) })
}

/// The result of an operation that may still run: `None` while it does.
///
/// # Safety
///
/// `overlapped` belongs to an operation started on `file`, and both are live.
unsafe fn result_of(file: Handle, overlapped: *const Overlapped) -> io::Result<Option<usize>> {
    let mut moved = 0u32;
    // SAFETY: by this function's contract; `moved` is written during the call.
    let ok = unsafe { GetOverlappedResult(file, overlapped, &raw mut moved, 0) };
    if ok != 0 {
        return Ok(Some(moved as usize));
    }
    let e = io::Error::last_os_error();
    match e.raw_os_error() {
        Some(ERROR_IO_INCOMPLETE) => Ok(None),
        _ => Err(e),
    }
}

/// What the kernel writes while an operation of one direction runs: its
/// `OVERLAPPED` and its buffer.
#[repr(C)]
struct Shared {
    overlapped: Overlapped,
    buf: [u8; BUFFER],
}

/// One direction of a stream. `shared` is reached only through raw pointers:
/// while `pending`, the kernel may write it at any moment, and the code reads it
/// only after the operation's result says it ended.
struct Side {
    shared: NonNull<Shared>,
    event: OwnedHandle,
    pending: bool,
    at: usize,
    len: usize,
    eof: bool,
}

// SAFETY: `shared` is owned by this side alone, as a `Box` would be (made in
// `new`, freed in `Drop`), and is touched only through `&mut Side` or by the
// kernel for the operation this side started; nothing in it is tied to a thread.
unsafe impl Send for Side {}

impl Drop for Side {
    fn drop(&mut self) {
        // SAFETY: `shared` came from `Box::leak` in `new` and is freed once, here.
        // A side is dropped only with no operation under way: `settle` waits for
        // every pending one to end before the sides go.
        drop(unsafe { Box::from_raw(self.shared.as_ptr()) });
    }
}

impl Side {
    fn new() -> io::Result<Side> {
        let event = event()?;
        let shared = Box::new(Shared {
            overlapped: Overlapped::default(),
            buf: [0; BUFFER],
        });
        Ok(Side {
            shared: NonNull::from(Box::leak(shared)),
            event,
            pending: false,
            at: 0,
            len: 0,
            eof: false,
        })
    }

    /// The operation's `OVERLAPPED`, as a pointer.
    fn overlapped(&self) -> *mut Overlapped {
        // SAFETY: `shared` is live as long as `self`; this makes a pointer to a
        // field, never a reference.
        unsafe { &raw mut (*self.shared.as_ptr()).overlapped }
    }

    /// The operation's buffer, as a pointer to its `BUFFER` bytes.
    fn buf(&self) -> *mut u8 {
        // SAFETY: as in `overlapped`.
        unsafe { (&raw mut (*self.shared.as_ptr()).buf).cast::<u8>() }
    }

    /// Prepares the `OVERLAPPED` for a new operation. Called only while none of
    /// this side is under way.
    fn arm(&mut self) -> *mut Overlapped {
        // The low bit of the event tells the kernel to queue no completion packet.
        // The handle may be on a reactor worker's completion port, and a packet for
        // an operation that lives in this side must never reach that port: the
        // stream waits on its own event. Handle values are multiples of four, so
        // the waits that read the field ignore the bit.
        let armed = Overlapped {
            event: self.event.as_raw_handle() as usize | 1,
            ..Overlapped::default()
        };
        let at = self.overlapped();
        // SAFETY: no operation of this side is under way, so nothing else writes
        // the field; the pointer is valid and aligned.
        unsafe { at.write(armed) };
        at
    }
}

/// Both directions. What the kernel holds an address of is in each side's own
/// allocation, so this box may be taken out of its place by `settle`.
struct Sides {
    read: Side,
    write: Side,
    /// The close drops what is unsent. Only a stream with IO under way has
    /// anything to drop, so the flag lives here, not in every stream.
    abortive: bool,
}

/// The instances of one pipe name this process holds: the spare and every server
/// end in use. A pipe exists while one of its instances is open, so while `live` is
/// above zero the name is ours. At zero another process may have created the name
/// since, and a new instance made without `FILE_FLAG_FIRST_PIPE_INSTANCE` would join
/// that pipe, with its security descriptor. Instances are made and closed under
/// this lock, so `live` never counts one that is already closed.
#[derive(Default)]
struct Instances {
    spare: Option<OwnedHandle>,
    live: usize,
}

type Held = Arc<Mutex<Instances>>;

fn hold(held: &Held) -> MutexGuard<'_, Instances> {
    held.lock().unwrap_or_else(PoisonError::into_inner)
}

impl Instances {
    /// Closes an instance this process made.
    fn close(&mut self, handle: OwnedHandle) {
        drop(handle);
        self.live = self.live.saturating_sub(1);
    }

    /// Keeps `handle` as the spare, or closes it when there is one already.
    fn keep(&mut self, handle: OwnedHandle) {
        if self.spare.is_none() {
            self.spare = Some(handle);
        } else {
            self.close(handle);
        }
    }
}

/// A connected pipe, either end.
pub(crate) struct PipeStream {
    /// Closed in `Drop`, after the IO has ended, under the server's lock for a
    /// server end.
    handle: ManuallyDrop<OwnedHandle>,
    /// The server's instance count, for a server end.
    instances: Option<Held>,
    sides: Mutex<Option<Box<Sides>>>,
}

impl std::fmt::Debug for PipeStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PipeStream")
            .field("handle", &self.handle)
            .finish_non_exhaustive()
    }
}

impl PipeStream {
    /// A client end.
    pub(crate) fn new(handle: OwnedHandle) -> PipeStream {
        PipeStream {
            handle: ManuallyDrop::new(handle),
            instances: None,
            sides: Mutex::new(None),
        }
    }

    /// A server end, counted among `instances` until it closes.
    fn server_end(handle: OwnedHandle, instances: Held) -> PipeStream {
        PipeStream {
            handle: ManuallyDrop::new(handle),
            instances: Some(instances),
            sides: Mutex::new(None),
        }
    }

    pub(crate) fn raw(&self) -> RawHandle {
        self.handle.as_raw_handle()
    }

    /// The handle's number in a socket's clothing, for the code that keeps one
    /// number per connection. Winsock answers `WSAENOTSOCK` to it, so socket options
    /// fail cleanly; IO and waits never take this path.
    pub(crate) fn as_sock(&self) -> Sock<'_> {
        // SAFETY: the number stays valid as long as `self`, and is never -1.
        unsafe { Sock::borrow_raw(self.handle.as_raw_handle() as u64) }
    }

    fn with<T>(&self, f: impl FnOnce(&mut Sides) -> io::Result<T>) -> io::Result<T> {
        let mut guard = self.sides.lock().unwrap_or_else(PoisonError::into_inner);
        if guard.is_none() {
            *guard = Some(Box::new(Sides {
                read: Side::new()?,
                write: Side::new()?,
                abortive: false,
            }));
        }
        match guard.as_mut() {
            Some(sides) => f(sides),
            None => Err(io::Error::from(io::ErrorKind::OutOfMemory)),
        }
    }

    fn start_read(&self, s: &mut Side) -> io::Result<()> {
        let overlapped = s.arm();
        // SAFETY: the `OVERLAPPED` and the buffer are in `s.shared`, which outlives
        // the operation (`settle`, then `Drop`) and which no reference covers while
        // it runs; no operation of this side is under way; the handle is open.
        let ok = unsafe {
            ReadFile(
                self.raw(),
                s.buf(),
                BUFFER as u32,
                std::ptr::null_mut(),
                overlapped,
            )
        };
        if ok != 0 {
            s.pending = true;
            return Ok(());
        }
        let e = io::Error::last_os_error();
        match e.raw_os_error() {
            Some(ERROR_IO_PENDING) => {
                s.pending = true;
                Ok(())
            }
            Some(ERROR_BROKEN_PIPE) => {
                s.eof = true;
                Ok(())
            }
            _ => Err(e),
        }
    }

    /// Bytes read earlier, or `WouldBlock` with a read under way.
    pub(crate) fn read(&self, out: &mut [u8]) -> io::Result<usize> {
        self.with(|sides| {
            let s = &mut sides.read;
            loop {
                if s.at < s.len {
                    let n = (s.len - s.at).min(out.len());
                    // SAFETY: the read that filled the buffer has ended (`len` is
                    // set from its result and no new one starts until `at` reaches
                    // it), so the kernel no longer writes it; `at + n <= len`, at
                    // most `BUFFER`; `out` holds `n` bytes and is another object.
                    unsafe {
                        std::ptr::copy_nonoverlapping(s.buf().add(s.at), out.as_mut_ptr(), n);
                    }
                    s.at += n;
                    return Ok(n);
                }
                if s.eof {
                    return Ok(0);
                }
                if !s.pending {
                    self.start_read(s)?;
                    continue;
                }
                // SAFETY: the operation was started on this handle and lives in `s`.
                match unsafe { result_of(self.raw(), s.overlapped()) } {
                    Ok(None) => return Err(io::Error::from(io::ErrorKind::WouldBlock)),
                    Ok(Some(n)) => {
                        s.pending = false;
                        s.at = 0;
                        s.len = n;
                    }
                    Err(e) => {
                        s.pending = false;
                        match e.raw_os_error() {
                            Some(ERROR_BROKEN_PIPE) => s.eof = true,
                            // A kill cancelled it: the caller looks at the kill flag.
                            Some(ERROR_OPERATION_ABORTED) => {
                                return Err(io::Error::from(io::ErrorKind::WouldBlock));
                            }
                            _ => return Err(e),
                        }
                    }
                }
            }
        })
    }

    /// Copies up to one buffer's worth and starts writing it; like a socket's send
    /// buffer, a failure of those bytes surfaces on the next call. `WouldBlock` while
    /// the previous write runs.
    pub(crate) fn write(&self, data: &[u8]) -> io::Result<usize> {
        if data.is_empty() {
            return Ok(0);
        }
        self.with(|sides| {
            let s = &mut sides.write;
            if s.pending {
                // SAFETY: the operation was started on this handle and lives in `s`.
                match unsafe { result_of(self.raw(), s.overlapped()) } {
                    Ok(None) => return Err(io::Error::from(io::ErrorKind::WouldBlock)),
                    Ok(Some(_)) => s.pending = false,
                    Err(e) => {
                        s.pending = false;
                        return Err(e);
                    }
                }
            }
            let n = data.len().min(BUFFER);
            // SAFETY: no write of this side is under way (just checked), so the
            // kernel does not read the buffer; `n <= BUFFER`; `data` is another
            // object with at least `n` bytes.
            unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), s.buf(), n) };
            let overlapped = s.arm();
            // SAFETY: as in `start_read`.
            let ok = unsafe {
                WriteFile(
                    self.raw(),
                    s.buf(),
                    n as u32,
                    std::ptr::null_mut(),
                    overlapped,
                )
            };
            if ok == 0 {
                let e = io::Error::last_os_error();
                if e.raw_os_error() != Some(ERROR_IO_PENDING) {
                    return Err(e);
                }
            }
            s.pending = true;
            Ok(n)
        })
    }

    pub(crate) fn write_vectored(&self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
        match bufs.iter().find(|b| !b.is_empty()) {
            Some(b) => self.write(b),
            None => Ok(0),
        }
    }

    /// Waits for `interest`, the wake channel, or the timeout.
    pub(crate) fn wait(
        &self,
        interest: Interest,
        wake: Option<&Wake>,
        timeout: Option<Duration>,
    ) -> io::Result<Ready> {
        let event = self.with(|sides| match interest {
            Interest::Read => {
                let s = &mut sides.read;
                if !s.pending && s.at >= s.len && !s.eof {
                    self.start_read(s)?;
                }
                if !s.pending {
                    return Ok(None);
                }
                Ok(Some(s.event.as_raw_handle()))
            }
            Interest::Write => {
                let s = &sides.write;
                Ok(s.pending.then(|| s.event.as_raw_handle()))
            }
        })?;
        let Some(event) = event else {
            return Ok(Ready::Socket);
        };
        wait_for(event, wake, timeout)
    }

    /// Unread bytes are dropped at close, and nothing waits for a flush.
    pub(crate) fn set_abortive(&self) {
        let mut guard = self.sides.lock().unwrap_or_else(PoisonError::into_inner);
        if let Some(sides) = guard.as_mut() {
            sides.abortive = true;
        }
    }

    /// The process that created the pipe's server end.
    pub(crate) fn server_pid(&self) -> io::Result<u32> {
        let mut pid = 0u32;
        // SAFETY: the handle is open; `pid` is written during the call.
        if unsafe { GetNamedPipeServerProcessId(self.raw(), &raw mut pid) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(pid)
    }

    /// The owner of the pipe's security descriptor, as a string SID: the account
    /// (or, for an elevated administrator, the group) that created its first
    /// instance. Read from the handle, so it describes the pipe this end is
    /// connected to.
    pub(crate) fn owner_sid(&self) -> io::Result<String> {
        let mut owner: *mut c_void = std::ptr::null_mut();
        let mut descriptor: *mut c_void = std::ptr::null_mut();
        // SAFETY: the handle is open; `owner` and `descriptor` are written during the
        // call, and `owner` points into `descriptor`, which is freed below.
        let status = unsafe {
            GetSecurityInfo(
                self.raw(),
                SE_KERNEL_OBJECT,
                OWNER_SECURITY_INFORMATION,
                &raw mut owner,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                &raw mut descriptor,
            )
        };
        if status != 0 {
            return Err(io::Error::from_raw_os_error(status as i32));
        }
        let text = if owner.is_null() {
            Err(io::Error::from(io::ErrorKind::NotFound))
        } else {
            // SAFETY: `owner` points to a SID inside `descriptor`, still allocated.
            unsafe { sid_string(owner) }
        };
        // SAFETY: the call says to free the descriptor so.
        let _ = unsafe { LocalFree(descriptor) };
        text
    }

    /// The process that opened the pipe's client end.
    pub(crate) fn client_pid(&self) -> io::Result<u32> {
        let mut pid = 0u32;
        // SAFETY: the handle is open; `pid` is written during the call.
        if unsafe { GetNamedPipeClientProcessId(self.raw(), &raw mut pid) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(pid)
    }
}

impl Drop for PipeStream {
    fn drop(&mut self) {
        self.settle();
        // SAFETY: the handle is taken once, here, and nothing uses it after.
        let handle = unsafe { ManuallyDrop::take(&mut self.handle) };
        match &self.instances {
            Some(held) => hold(held).close(handle),
            None => drop(handle),
        }
    }
}

impl PipeStream {
    /// Ends the IO still under way, so the box can go.
    fn settle(&mut self) {
        let sides = self
            .sides
            .get_mut()
            .unwrap_or_else(PoisonError::into_inner)
            .take();
        let Some(sides) = sides else { return };
        let raw = self.handle.as_raw_handle();
        // Closing a pipe keeps what is already in it readable, so only a write the
        // kernel has not taken yet needs a moment, within this thread's credit.
        if sides.write.pending && !sides.abortive {
            let started = Instant::now();
            let credit = take_flush_credit(started);
            let ms = u32::try_from(credit / 1_000).unwrap_or(CLOSE_FLUSH_MS);
            if ms > 0 {
                // SAFETY: the event is open; the wait is bounded.
                let _ = unsafe { WaitForSingleObject(sides.write.event.as_raw_handle(), ms) };
            }
            let waited = u64::try_from(started.elapsed().as_micros()).unwrap_or(u64::MAX);
            return_flush_credit(credit.saturating_sub(waited));
        }
        if sides.read.pending || sides.write.pending {
            // SAFETY: the handle is open; a null `OVERLAPPED` means all of its operations.
            let _ = unsafe { CancelIoEx(raw, std::ptr::null_mut()) };
            for s in [&sides.read, &sides.write] {
                if s.pending {
                    let mut moved = 0u32;
                    // SAFETY: the operation was started on this handle; this waits for
                    // its end, so the box is released after the kernel lets go of it.
                    let _ = unsafe { GetOverlappedResult(raw, s.overlapped(), &raw mut moved, 1) };
                }
            }
        }
    }
}

fn wait_for(event: RawHandle, wake: Option<&Wake>, timeout: Option<Duration>) -> io::Result<Ready> {
    let handles = [event, wake.map_or(std::ptr::null_mut(), Wake::event_raw)];
    let count = if wake.is_some() { 2 } else { 1 };
    let ms = match poll_millis(timeout) {
        n if n < 0 => INFINITE,
        n => n.unsigned_abs(),
    };
    // SAFETY: `count` handles are open for the call.
    let ret = unsafe { WaitForMultipleObjects(count, handles.as_ptr(), 0, ms) };
    match ret {
        0 => Ok(Ready::Socket),
        1 => {
            if let Some(w) = wake {
                w.take();
            }
            Ok(Ready::Woken)
        }
        WAIT_TIMEOUT => Ok(Ready::TimedOut),
        WAIT_FAILED => Err(io::Error::last_os_error()),
        _ => Err(io::Error::other("unexpected wait result")),
    }
}

/// A security descriptor from SDDL text.
pub(crate) struct Descriptor(usize);

impl Descriptor {
    pub(crate) fn from_sddl(text: &str) -> io::Result<Descriptor> {
        let text = wide(text);
        let mut out: *mut c_void = std::ptr::null_mut();
        // SAFETY: `text` is terminated; `out` is written during the call.
        let ok = unsafe {
            ConvertStringSecurityDescriptorToSecurityDescriptorW(
                text.as_ptr(),
                SDDL_REVISION_1,
                &raw mut out,
                std::ptr::null_mut(),
            )
        };
        if ok == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(Descriptor(out as usize))
    }
}

impl Drop for Descriptor {
    fn drop(&mut self) {
        // SAFETY: the memory came from the conversion above, which says to free it so.
        let _ = unsafe { LocalFree(self.0 as *mut c_void) };
    }
}

/// A SID as text (`S-1-5-18`).
///
/// # Safety
///
/// `sid` points to a valid SID for the call.
unsafe fn sid_string(sid: *mut c_void) -> io::Result<String> {
    let mut text: *mut u16 = std::ptr::null_mut();
    // SAFETY: `sid` is valid by this function's contract; `text` is written.
    if unsafe { ConvertSidToStringSidW(sid, &raw mut text) } == 0 {
        return Err(io::Error::last_os_error());
    }
    let mut len = 0;
    // SAFETY: the string is terminated, per the conversion's contract.
    let out = unsafe {
        while *text.add(len) != 0 {
            len += 1;
        }
        String::from_utf16_lossy(std::slice::from_raw_parts(text, len))
    };
    // SAFETY: the conversion says to free it so.
    let _ = unsafe { LocalFree(text.cast()) };
    Ok(out)
}

/// `FILETIME`: 100 ns units since 1601, in two halves.
#[repr(C)]
#[derive(Default)]
struct FileTime {
    low: u32,
    high: u32,
}

/// A SID from this process's token: `TokenUser` or `TokenOwner`, whose structures
/// both start with the SID pointer.
fn token_sid(class: i32) -> io::Result<String> {
    // SAFETY: the current-process pseudo handle is always valid and needs no closing.
    unsafe { token_sid_of(GetCurrentProcess(), class) }
}

/// The user this process runs as, as a string SID.
pub(crate) fn current_user_sid() -> io::Result<String> {
    token_sid(TOKEN_USER_CLASS)
}

/// The user process `pid` runs as (a string SID) and when it started (100 ns
/// units since 1601, the system clock). Fails when this process may not query
/// it, for example a process of another user.
pub(crate) fn process_user_and_start(pid: u32) -> io::Result<(String, u64)> {
    // SAFETY: no handle is inherited; a null result is checked below.
    let raw = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
    if raw.is_null() {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `raw` was just returned, is open, and has no other owner.
    let process = unsafe { OwnedHandle::from_raw_handle(raw) };
    // SAFETY: the handle is open and was opened with the access the token needs.
    let user = unsafe { token_sid_of(process.as_raw_handle(), TOKEN_USER_CLASS) }?;
    let mut times = [
        FileTime::default(),
        FileTime::default(),
        FileTime::default(),
        FileTime::default(),
    ];
    let [created, exited, kernel, used] = &mut times;
    // SAFETY: the handle is open; the four structures are written during the call.
    let ok = unsafe { GetProcessTimes(process.as_raw_handle(), created, exited, kernel, used) };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    Ok((
        user,
        (u64::from(created.high) << 32) | u64::from(created.low),
    ))
}

/// A SID from `process`'s token.
///
/// # Safety
///
/// `process` is an open process handle with query access, or the current-process
/// pseudo handle.
unsafe fn token_sid_of(process: Handle, class: i32) -> io::Result<String> {
    let mut token: Handle = std::ptr::null_mut();
    // SAFETY: by this function's contract; `token` is written.
    if unsafe { OpenProcessToken(process, TOKEN_QUERY, &raw mut token) } == 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: `token` was just returned, is open, and has no other owner.
    let token = unsafe { OwnedHandle::from_raw_handle(token) };
    // The structure and its SID, aligned for the pointer it starts with.
    let mut info = [0usize; 32];
    let mut returned = 0u32;
    // SAFETY: `info` has room for the stated length; it is written during the call.
    let ok = unsafe {
        GetTokenInformation(
            token.as_raw_handle(),
            class,
            info.as_mut_ptr().cast(),
            size_of_val(&info) as u32,
            &raw mut returned,
        )
    };
    if ok == 0 {
        return Err(io::Error::last_os_error());
    }
    // SAFETY: the first word points to the SID, inside `info`, as the call filled it.
    unsafe { sid_string(info[0] as *mut c_void) }
}

/// This process's default owner for new objects, which a pipe it creates gets.
#[cfg(test)]
pub(crate) fn token_owner_sid() -> io::Result<String> {
    token_sid(TOKEN_OWNER_CLASS)
}

/// The SDDL that lets only the current user in (and the system, when asked).
pub(crate) fn owner_sddl(system: bool) -> io::Result<String> {
    let user = token_sid(TOKEN_USER_CLASS)?;
    let mut sddl = format!("D:P(A;;GA;;;{user})");
    if system {
        sddl.push_str("(A;;GA;;;SY)");
    }
    Ok(sddl)
}

/// What every instance of a pipe is created with.
pub(crate) struct PipeParams {
    pub(crate) max_instances: u8,
    pub(crate) inbound: u32,
    pub(crate) outbound: u32,
}

/// The server side of a pipe name.
pub(crate) struct PipeServer {
    path: Vec<u16>,
    descriptor: Descriptor,
    params: PipeParams,
    instances: Held,
}

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

impl Drop for PipeServer {
    fn drop(&mut self) {
        let mut held = hold(&self.instances);
        if let Some(spare) = held.spare.take() {
            held.close(spare);
        }
    }
}

/// The error for a name another process holds.
fn name_taken(e: io::Error) -> io::Error {
    io::Error::new(io::ErrorKind::AddrInUse, e)
}

impl PipeServer {
    /// Creates the first instance, which fails if the name is taken: another process
    /// that made it first owns it.
    pub(crate) fn create(
        name: &str,
        params: PipeParams,
        descriptor: Descriptor,
    ) -> io::Result<PipeServer> {
        let server = PipeServer {
            path: pipe_path(name),
            descriptor,
            params,
            instances: Held::default(),
        };
        {
            let mut held = hold(&server.instances);
            let first = server.instance(&mut held)?;
            held.spare = Some(first);
        }
        Ok(server)
    }

    /// A new instance, made under the lock. With no instance held it claims the name
    /// (`FILE_FLAG_FIRST_PIPE_INSTANCE`), and `ERROR_ACCESS_DENIED` or
    /// `ERROR_PIPE_BUSY` then mean another process owns it: `AddrInUse`.
    fn instance(&self, held: &mut Instances) -> io::Result<OwnedHandle> {
        let attributes = SecurityAttributes {
            length: size_of::<SecurityAttributes>() as u32,
            descriptor: self.descriptor.0 as *mut c_void,
            inherit: 0,
        };
        let first = held.live == 0;
        let open_mode = PIPE_ACCESS_DUPLEX
            | FILE_FLAG_OVERLAPPED
            | if first {
                FILE_FLAG_FIRST_PIPE_INSTANCE
            } else {
                0
            };
        // SAFETY: `path` is terminated; `attributes` and its descriptor live for the call.
        let raw = unsafe {
            CreateNamedPipeW(
                self.path.as_ptr(),
                open_mode,
                PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
                u32::from(self.params.max_instances),
                self.params.outbound,
                self.params.inbound,
                0,
                &raw const attributes,
            )
        };
        if is_invalid(raw) {
            let e = io::Error::last_os_error();
            return Err(match e.raw_os_error() {
                Some(ERROR_ACCESS_DENIED | ERROR_PIPE_BUSY) if first => name_taken(e),
                _ => e,
            });
        }
        held.live += 1;
        // SAFETY: `raw` was just returned, is open, and has no other owner.
        Ok(unsafe { OwnedHandle::from_raw_handle(raw) })
    }

    /// Waits for a client; `None` when `wake` fired first. The next instance exists
    /// before this returns, so a client never finds none, unless the instance cap is
    /// reached (with `max_instances(1)`, always): the name is then free once the
    /// connections close, and the next accept claims it again.
    pub(crate) fn accept(&self, wake: Option<&Wake>) -> io::Result<Option<PipeStream>> {
        loop {
            let handle = {
                let mut held = hold(&self.instances);
                match held.spare.take() {
                    Some(h) => h,
                    None => self.instance(&mut held)?,
                }
            };
            match self.connect(&handle, wake) {
                Ok(true) => {
                    let mut held = hold(&self.instances);
                    // `handle` is open, so this joins our own pipe.
                    if held.spare.is_none() {
                        if let Ok(next) = self.instance(&mut held) {
                            held.spare = Some(next);
                        }
                    }
                    drop(held);
                    return Ok(Some(PipeStream::server_end(handle, self.instances.clone())));
                }
                Ok(false) => {
                    hold(&self.instances).keep(handle);
                    return Ok(None);
                }
                // The client came and went before the call: this instance is spent.
                Err(e) if e.raw_os_error() == Some(ERROR_NO_DATA) => {
                    // SAFETY: the handle is open.
                    let _ = unsafe { DisconnectNamedPipe(handle.as_raw_handle()) };
                    hold(&self.instances).keep(handle);
                }
                Err(e) => {
                    // Keep the name: a fresh instance replaces this one while it is
                    // still open, and when none can be made this one stays.
                    let mut held = hold(&self.instances);
                    match self.instance(&mut held) {
                        Ok(next) => {
                            held.close(handle);
                            held.keep(next);
                        }
                        Err(_) => {
                            // SAFETY: the handle is open.
                            let _ = unsafe { DisconnectNamedPipe(handle.as_raw_handle()) };
                            held.keep(handle);
                        }
                    }
                    return Err(e);
                }
            }
        }
    }

    /// `true` once a client is connected to `handle`, `false` when `wake` fired.
    fn connect(&self, handle: &OwnedHandle, wake: Option<&Wake>) -> io::Result<bool> {
        let raw = handle.as_raw_handle();
        let ev = event()?;
        // No completion packet, as in `Side::arm`: this file never queues one.
        let mut overlapped = Overlapped {
            event: ev.as_raw_handle() as usize | 1,
            ..Overlapped::default()
        };
        // SAFETY: `overlapped` and `ev` outlive the operation: every path below waits
        // for its end before returning.
        if unsafe { ConnectNamedPipe(raw, &raw mut overlapped) } != 0 {
            return Ok(true);
        }
        let e = io::Error::last_os_error();
        match e.raw_os_error() {
            Some(ERROR_PIPE_CONNECTED) => return Ok(true),
            Some(ERROR_IO_PENDING) => {}
            _ => return Err(e),
        }
        let ready = wait_for(ev.as_raw_handle(), wake, None);
        if !matches!(ready, Ok(Ready::Socket)) {
            // SAFETY: the operation lives in `overlapped`, on this handle.
            let _ = unsafe { CancelIoEx(raw, (&raw mut overlapped).cast()) };
        }
        let mut moved = 0u32;
        // SAFETY: as above; this waits for the operation's end.
        let ok = unsafe { GetOverlappedResult(raw, &raw const overlapped, &raw mut moved, 1) };
        if ok != 0 {
            return Ok(true);
        }
        let e = io::Error::last_os_error();
        match e.raw_os_error() {
            Some(ERROR_OPERATION_ABORTED) => Ok(false),
            _ => Err(e),
        }
    }
}

/// Opens the client end: the server may identify this process, and no more. Waits
/// for a free instance up to `timeout`.
pub(crate) fn pipe_connect(name: &str, timeout: Duration) -> io::Result<PipeStream> {
    let path = pipe_path(name);
    let deadline = Instant::now() + timeout;
    loop {
        // SAFETY: `path` is terminated; no attributes, no template.
        let raw = unsafe {
            CreateFileW(
                path.as_ptr(),
                GENERIC_READ | GENERIC_WRITE,
                0,
                std::ptr::null(),
                OPEN_EXISTING,
                FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION,
                std::ptr::null_mut(),
            )
        };
        if !is_invalid(raw) {
            // SAFETY: `raw` was just returned, is open, and has no other owner.
            return Ok(PipeStream::new(unsafe {
                OwnedHandle::from_raw_handle(raw)
            }));
        }
        let e = io::Error::last_os_error();
        if e.raw_os_error() != Some(ERROR_PIPE_BUSY) {
            return Err(e);
        }
        let left = deadline.saturating_duration_since(Instant::now());
        if left.is_zero() {
            return Err(io::Error::from(io::ErrorKind::TimedOut));
        }
        let ms = u32::try_from(left.as_millis())
            .unwrap_or(u32::MAX - 1)
            .max(1);
        // SAFETY: `path` is terminated. A failure is looked at by the next open.
        if unsafe { WaitNamedPipeW(path.as_ptr(), ms) } == 0 {
            let e = io::Error::last_os_error();
            if e.raw_os_error() == Some(ERROR_SEM_TIMEOUT) {
                return Err(io::Error::from(io::ErrorKind::TimedOut));
            }
        }
    }
}

/// Whether `e` from a pipe open says nobody serves the name.
pub(crate) fn is_no_pipe(e: &io::Error) -> bool {
    e.raw_os_error() == Some(ERROR_FILE_NOT_FOUND)
}

/// Whether `e` from creating or accepting on a pipe says another process owns the
/// name.
pub(crate) fn is_name_taken(e: &io::Error) -> bool {
    e.kind() == io::ErrorKind::AddrInUse
}

#[cfg(test)]
mod tests {
    use super::*;
    use windows_sys::Win32::Foundation as wf;
    use windows_sys::Win32::Security as sec;
    use windows_sys::Win32::Storage::FileSystem as fs;
    use windows_sys::Win32::System::Pipes as pipes;

    #[test]
    fn test_constants_match_windows_sys() {
        assert_eq!(PIPE_ACCESS_DUPLEX, fs::PIPE_ACCESS_DUPLEX);
        assert_eq!(FILE_FLAG_OVERLAPPED, fs::FILE_FLAG_OVERLAPPED);
        assert_eq!(
            FILE_FLAG_FIRST_PIPE_INSTANCE,
            fs::FILE_FLAG_FIRST_PIPE_INSTANCE
        );
        assert_eq!(PIPE_TYPE_BYTE, pipes::PIPE_TYPE_BYTE);
        assert_eq!(PIPE_READMODE_BYTE, pipes::PIPE_READMODE_BYTE);
        assert_eq!(PIPE_WAIT, pipes::PIPE_WAIT);
        assert_eq!(
            PIPE_REJECT_REMOTE_CLIENTS,
            pipes::PIPE_REJECT_REMOTE_CLIENTS
        );
        assert_eq!(GENERIC_READ, wf::GENERIC_READ);
        assert_eq!(GENERIC_WRITE, wf::GENERIC_WRITE);
        assert_eq!(OPEN_EXISTING, fs::OPEN_EXISTING);
        assert_eq!(SECURITY_SQOS_PRESENT, fs::SECURITY_SQOS_PRESENT);
        assert_eq!(SECURITY_IDENTIFICATION, fs::SECURITY_IDENTIFICATION);
        assert_eq!(TOKEN_QUERY, sec::TOKEN_QUERY);
        assert_eq!(
            PROCESS_QUERY_LIMITED_INFORMATION,
            windows_sys::Win32::System::Threading::PROCESS_QUERY_LIMITED_INFORMATION
        );
        assert_eq!(
            size_of::<FileTime>(),
            size_of::<windows_sys::Win32::Foundation::FILETIME>()
        );
        assert_eq!(
            align_of::<FileTime>(),
            align_of::<windows_sys::Win32::Foundation::FILETIME>()
        );
        assert_eq!(TOKEN_USER_CLASS, sec::TokenUser);
        assert_eq!(TOKEN_OWNER_CLASS, sec::TokenOwner);
        assert_eq!(OWNER_SECURITY_INFORMATION, sec::OWNER_SECURITY_INFORMATION);
        assert_eq!(WAIT_TIMEOUT, wf::WAIT_TIMEOUT);
        assert_eq!(WAIT_FAILED, wf::WAIT_FAILED);
        assert_eq!(ERROR_FILE_NOT_FOUND as u32, wf::ERROR_FILE_NOT_FOUND);
        assert_eq!(ERROR_ACCESS_DENIED as u32, wf::ERROR_ACCESS_DENIED);
        assert_eq!(ERROR_BROKEN_PIPE as u32, wf::ERROR_BROKEN_PIPE);
        assert_eq!(ERROR_SEM_TIMEOUT as u32, wf::ERROR_SEM_TIMEOUT);
        assert_eq!(ERROR_PIPE_BUSY as u32, wf::ERROR_PIPE_BUSY);
        assert_eq!(ERROR_NO_DATA as u32, wf::ERROR_NO_DATA);
        assert_eq!(ERROR_PIPE_CONNECTED as u32, wf::ERROR_PIPE_CONNECTED);
        assert_eq!(ERROR_OPERATION_ABORTED as u32, wf::ERROR_OPERATION_ABORTED);
        assert_eq!(ERROR_IO_INCOMPLETE as u32, wf::ERROR_IO_INCOMPLETE);
        assert_eq!(ERROR_IO_PENDING as u32, wf::ERROR_IO_PENDING);
        assert_eq!(
            size_of::<SecurityAttributes>(),
            size_of::<sec::SECURITY_ATTRIBUTES>()
        );
    }

    /// Every function declared in this file against its `windows-sys` declaration.
    #[test]
    fn test_signatures_match_windows_sys() {
        use super::super::windows::abi::same_abi;
        use windows_sys::Win32::Security::Authorization as authz;
        use windows_sys::Win32::System::IO as io_sys;
        use windows_sys::Win32::System::Threading as th;
        same_abi!(
            CreateNamedPipeW,
            pipes::CreateNamedPipeW,
            _,
            _,
            _,
            _,
            _,
            _,
            _,
            _
        );
        same_abi!(ConnectNamedPipe, pipes::ConnectNamedPipe, _, _);
        same_abi!(DisconnectNamedPipe, pipes::DisconnectNamedPipe, _);
        same_abi!(CreateFileW, fs::CreateFileW, _, _, _, _, _, _, _);
        same_abi!(WaitNamedPipeW, pipes::WaitNamedPipeW, _, _);
        same_abi!(
            GetNamedPipeClientProcessId,
            pipes::GetNamedPipeClientProcessId,
            _,
            _
        );
        same_abi!(
            GetNamedPipeServerProcessId,
            pipes::GetNamedPipeServerProcessId,
            _,
            _
        );
        same_abi!(ReadFile, fs::ReadFile, _, _, _, _, _);
        same_abi!(WriteFile, fs::WriteFile, _, _, _, _, _);
        same_abi!(GetOverlappedResult, io_sys::GetOverlappedResult, _, _, _, _);
        same_abi!(CreateEventW, th::CreateEventW, _, _, _, _);
        same_abi!(
            WaitForMultipleObjects,
            th::WaitForMultipleObjects,
            _,
            _,
            _,
            _
        );
        same_abi!(WaitForSingleObject, th::WaitForSingleObject, _, _);
        same_abi!(GetCurrentProcess, th::GetCurrentProcess,);
        same_abi!(OpenProcess, th::OpenProcess, _, _, _);
        same_abi!(GetProcessTimes, th::GetProcessTimes, _, _, _, _, _);
        same_abi!(LocalFree, wf::LocalFree, _);
        same_abi!(OpenProcessToken, th::OpenProcessToken, _, _, _);
        same_abi!(GetTokenInformation, sec::GetTokenInformation, _, _, _, _, _);
        same_abi!(ConvertSidToStringSidW, authz::ConvertSidToStringSidW, _, _);
        same_abi!(
            GetSecurityInfo,
            authz::GetSecurityInfo,
            _,
            _,
            _,
            _,
            _,
            _,
            _,
            _
        );
        same_abi!(
            ConvertStringSecurityDescriptorToSecurityDescriptorW,
            authz::ConvertStringSecurityDescriptorToSecurityDescriptorW,
            _,
            _,
            _,
            _
        );
        assert_eq!(SE_KERNEL_OBJECT, authz::SE_KERNEL_OBJECT);
        assert_eq!(SDDL_REVISION_1, authz::SDDL_REVISION_1);
        assert_eq!(INFINITE, th::INFINITE);
        assert_eq!(
            std::mem::offset_of!(SecurityAttributes, descriptor),
            std::mem::offset_of!(sec::SECURITY_ATTRIBUTES, lpSecurityDescriptor)
        );
    }

    /// The owner a client reads is the creator's default owner for new objects.
    #[test]
    fn test_owner_sid_is_the_creators_default_owner() {
        let name = format!("net-io-sys-owner-{}", std::process::id());
        let params = PipeParams {
            max_instances: 1,
            inbound: 4096,
            outbound: 4096,
        };
        let sddl = owner_sddl(false).unwrap();
        let server =
            PipeServer::create(&name, params, Descriptor::from_sddl(&sddl).unwrap()).unwrap();
        let client = pipe_connect(&name, Duration::from_secs(1)).unwrap();
        let expected = token_owner_sid().unwrap();
        assert_eq!(client.owner_sid().unwrap(), expected);
        let accepted = server.accept(None).unwrap().unwrap();
        assert_eq!(accepted.owner_sid().unwrap(), expected);
    }

    /// A drain closes an idle connection, but a reply its owner already handed over
    /// (a write still under way) goes out whole.
    #[test]
    fn test_drain_leaves_a_pending_write_alone() {
        let name = format!("net-io-sys-drain-{}", std::process::id());
        let params = PipeParams {
            max_instances: 1,
            inbound: 1024,
            outbound: 1024,
        };
        let sddl = owner_sddl(false).unwrap();
        let server =
            PipeServer::create(&name, params, Descriptor::from_sddl(&sddl).unwrap()).unwrap();
        let client = pipe_connect(&name, Duration::from_secs(1)).unwrap();
        let stream = server.accept(None).unwrap().unwrap();
        // More than the pipe holds: the write stays in the kernel until read.
        assert_eq!(stream.write(&[5u8; BUFFER]).unwrap(), BUFFER);
        let slot = crate::sys::KillSlot::new();
        let generation = slot.install(stream.as_sock());
        slot.set_wake(Some(Arc::new(Wake::new().unwrap())));
        slot.set_idle(true);
        assert!(slot.drain_idle(generation));
        let (mut got, mut buf) = (0, [0u8; 4096]);
        let until = Instant::now() + Duration::from_secs(2);
        while got < BUFFER && Instant::now() < until {
            match client.read(&mut buf) {
                Ok(0) => break,
                Ok(n) => got += n,
                Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                    client
                        .wait(Interest::Read, None, Some(Duration::from_millis(100)))
                        .unwrap();
                }
                Err(e) => panic!("{e}"),
            }
        }
        assert_eq!(got, BUFFER, "the drain cut the reply short");
    }

    /// A server end with a write its client does not read, and the client.
    fn stalled_pair(tag: &str) -> (PipeStream, PipeStream) {
        let name = format!("net-io-sys-stall-{tag}-{}", std::process::id());
        let params = PipeParams {
            max_instances: 1,
            inbound: 1024,
            outbound: 1024,
        };
        let sddl = owner_sddl(false).unwrap();
        let server =
            PipeServer::create(&name, params, Descriptor::from_sddl(&sddl).unwrap()).unwrap();
        let client = pipe_connect(&name, Duration::from_secs(1)).unwrap();
        let stream = server.accept(None).unwrap().unwrap();
        // More than the pipe holds: the write stays in the kernel until read.
        assert_eq!(stream.write(&[5u8; BUFFER]).unwrap(), BUFFER);
        (stream, client)
    }

    /// Closes that wait for clients that do not read hold their thread a bounded
    /// time in total, not a second each; an abortive close does not wait at all.
    #[test]
    fn test_closes_nobody_reads_hold_a_thread_a_bounded_time() {
        let pairs: Vec<_> = (0..3).map(|i| stalled_pair(&i.to_string())).collect();
        let started = Instant::now();
        let mut clients = Vec::new();
        for (stream, client) in pairs {
            drop(stream);
            clients.push(client);
        }
        let took = started.elapsed();
        assert!(
            took < Duration::from_millis(1_600),
            "three closes took {took:?}"
        );
        let (stream, _client) = stalled_pair("abort");
        stream.set_abortive();
        let started = Instant::now();
        drop(stream);
        assert!(started.elapsed() < Duration::from_millis(200));
    }

    #[test]
    fn test_owner_sddl_parses() {
        let text = owner_sddl(true).unwrap();
        assert!(text.starts_with("D:P(A;;GA;;;S-1-"), "{text}");
        assert!(text.ends_with("(A;;GA;;;SY)"));
        Descriptor::from_sddl(&text).unwrap();
    }
}