Debian Codegraph @

debian/rust-vendor/mio/src/sys/windows/named_pipe.rs

raw
1 use std::ffi::OsStr;
2 use std::io::{self, Read, Write};
3 use std::os::windows::io::{AsRawHandle, FromRawHandle, RawHandle};
4 use std::sync::atomic::Ordering::{Relaxed, SeqCst};
5 use std::sync::atomic::{AtomicBool, AtomicUsize};
6 use std::sync::{Arc, Mutex};
7 use std::{fmt, mem, slice};
8
9 use windows_sys::Win32::Foundation::{
10 ERROR_BROKEN_PIPE, ERROR_IO_INCOMPLETE, ERROR_IO_PENDING, ERROR_MORE_DATA, ERROR_NO_DATA,
11 ERROR_PIPE_CONNECTED, ERROR_PIPE_LISTENING, HANDLE, INVALID_HANDLE_VALUE,
12 };
13 use windows_sys::Win32::Storage::FileSystem::{
14 ReadFile, WriteFile, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, PIPE_ACCESS_DUPLEX,
15 };
16 use windows_sys::Win32::System::Pipes::{
17 ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_TYPE_BYTE,
18 PIPE_UNLIMITED_INSTANCES,
19 };
20 use windows_sys::Win32::System::IO::{
21 CancelIoEx, GetOverlappedResult, OVERLAPPED, OVERLAPPED_ENTRY,
22 };
23
24 use crate::event::Source;
25 use crate::sys::windows::iocp::{CompletionPort, CompletionStatus};
26 use crate::sys::windows::{Event, Handle, Overlapped};
27 use crate::Registry;
28 use crate::{Interest, Token};
29
30 /// Non-blocking windows named pipe.
31 ///
32 /// This structure internally contains a `HANDLE` which represents the named
33 /// pipe, and also maintains state associated with the mio event loop and active
34 /// I/O operations that have been scheduled to translate IOCP to a readiness
35 /// model.
36 ///
37 /// Note, IOCP is a *completion* based model whereas mio is a *readiness* based
38 /// model. To bridge this, `NamedPipe` performs internal buffering. Writes are
39 /// written to an internal buffer and the buffer is submitted to IOCP. IOCP
40 /// reads are submitted using internal buffers and `NamedPipe::read` reads from
41 /// this internal buffer.
42 ///
43 /// # Trait implementations
44 ///
45 /// The `Read` and `Write` traits are implemented for `NamedPipe` and for
46 /// `&NamedPipe`. This represents that a named pipe can be concurrently read and
47 /// written to and also can be read and written to at all. Typically a named
48 /// pipe needs to be connected to a client before it can be read or written,
49 /// however.
50 ///
51 /// Note that for I/O operations on a named pipe to succeed then the named pipe
52 /// needs to be associated with an event loop. Until this happens all I/O
53 /// operations will return a "would block" error.
54 ///
55 /// # Managing connections
56 ///
57 /// The `NamedPipe` type supports a `connect` method to connect to a client and
58 /// a `disconnect` method to disconnect from that client. These two methods only
59 /// work once a named pipe is associated with an event loop.
60 ///
61 /// The `connect` method will succeed asynchronously and a completion can be
62 /// detected once the object receives a writable notification.
63 ///
64 /// # Named pipe clients
65 ///
66 /// Currently to create a client of a named pipe server then you can use the
67 /// `OpenOptions` type in the standard library to create a `File` that connects
68 /// to a named pipe. Afterwards you can use the `into_raw_handle` method coupled
69 /// with the `NamedPipe::from_raw_handle` method to convert that to a named pipe
70 /// that can operate asynchronously. Don't forget to pass the
71 /// `FILE_FLAG_OVERLAPPED` flag when opening the `File`.
72 pub struct NamedPipe {
73 inner: Arc<Inner>,
74 }
75
76 /// # Notes
77 ///
78 /// The memory layout of this structure must be fixed as the
79 /// `ptr_from_*_overlapped` methods depend on it, see the `ptr_from` test.
80 #[repr(C)]
81 struct Inner {
82 // NOTE: careful modifying the order of these three fields, the `ptr_from_*`
83 // methods depend on the layout!
84 connect: Overlapped,
85 read: Overlapped,
86 write: Overlapped,
87 event: Overlapped,
88 // END NOTE.
89 handle: Handle,
90 connecting: AtomicBool,
91 io: Mutex<Io>,
92 pool: Mutex<BufferPool>,
93 }
94
95 // SAFETY: `Handles`s are, in general, not thread-safe. However, we only used `Handle`s for
96 // resources that are thread-safe in `Inner`.
97 unsafe impl Send for Inner {}
98
99 // SAFETY: `Handles`s are, in general, not thread-safe. However, we only used `Handle`s for
100 // resources that are thread-safe in `Inner`.
101 unsafe impl Sync for Inner {}
102
103 impl Inner {
104 /// Converts a pointer to `Inner.connect` to a pointer to `Inner`.
105 ///
106 /// # Unsafety
107 ///
108 /// Caller must ensure `ptr` is pointing to `Inner.connect`.
109 unsafe fn ptr_from_conn_overlapped(ptr: *mut OVERLAPPED) -> *const Inner {
110 // `connect` is the first field, so the pointer are the same.
111 ptr.cast()
112 }
113
114 /// Same as [`ptr_from_conn_overlapped`] but for `Inner.read`.
115 unsafe fn ptr_from_read_overlapped(ptr: *mut OVERLAPPED) -> *const Inner {
116 // `read` is after `connect: Overlapped`.
117 (ptr as *mut Overlapped).wrapping_sub(1) as *const Inner
118 }
119
120 /// Same as [`ptr_from_conn_overlapped`] but for `Inner.write`.
121 unsafe fn ptr_from_write_overlapped(ptr: *mut OVERLAPPED) -> *const Inner {
122 // `write` is after `connect: Overlapped` and `read: Overlapped`.
123 (ptr as *mut Overlapped).wrapping_sub(2) as *const Inner
124 }
125
126 /// Same as [`ptr_from_conn_overlapped`] but for `Inner.event`.
127 unsafe fn ptr_from_event_overlapped(ptr: *mut OVERLAPPED) -> *const Inner {
128 // `event` is after `connect: Overlapped`, `read: Overlapped`, and `write: Overlapped`.
129 (ptr as *mut Overlapped).wrapping_sub(3) as *const Inner
130 }
131
132 /// Issue a connection request with the specified overlapped operation.
133 ///
134 /// This function will issue a request to connect a client to this server,
135 /// returning immediately after starting the overlapped operation.
136 ///
137 /// If this function immediately succeeds then `Ok(true)` is returned. If
138 /// the overlapped operation is enqueued and pending, then `Ok(false)` is
139 /// returned. Otherwise an error is returned indicating what went wrong.
140 ///
141 /// # Unsafety
142 ///
143 /// This function is unsafe because the kernel requires that the
144 /// `overlapped` pointer is valid until the end of the I/O operation. The
145 /// kernel also requires that `overlapped` is unique for this I/O operation
146 /// and is not in use for any other I/O.
147 ///
148 /// To safely use this function callers must ensure that this pointer is
149 /// valid until the I/O operation is completed, typically via completion
150 /// ports and waiting to receive the completion notification on the port.
151 pub unsafe fn connect_overlapped(&self, overlapped: *mut OVERLAPPED) -> io::Result<bool> {
152 if ConnectNamedPipe(self.handle.raw(), overlapped) != 0 {
153 return Ok(true);
154 }
155
156 let err = io::Error::last_os_error();
157
158 match err.raw_os_error().map(|e| e as u32) {
159 Some(ERROR_PIPE_CONNECTED) => Ok(true),
160 Some(ERROR_NO_DATA) => Ok(true),
161 Some(ERROR_IO_PENDING) => Ok(false),
162 _ => Err(err),
163 }
164 }
165
166 /// Disconnects this named pipe from any connected client.
167 pub fn disconnect(&self) -> io::Result<()> {
168 if unsafe { DisconnectNamedPipe(self.handle.raw()) } == 0 {
169 Err(io::Error::last_os_error())
170 } else {
171 Ok(())
172 }
173 }
174
175 /// Issues an overlapped read operation to occur on this pipe.
176 ///
177 /// This function will issue an asynchronous read to occur in an overlapped
178 /// fashion, returning immediately. The `buf` provided will be filled in
179 /// with data and the request is tracked by the `overlapped` function
180 /// provided.
181 ///
182 /// If the operation succeeds immediately, `Ok(Some(n))` is returned where
183 /// `n` is the number of bytes read. If an asynchronous operation is
184 /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred
185 /// it is returned.
186 ///
187 /// When this operation completes (or if it completes immediately), another
188 /// mechanism must be used to learn how many bytes were transferred (such as
189 /// looking at the filed in the IOCP status message).
190 ///
191 /// # Unsafety
192 ///
193 /// This function is unsafe because the kernel requires that the `buf` and
194 /// `overlapped` pointers to be valid until the end of the I/O operation.
195 /// The kernel also requires that `overlapped` is unique for this I/O
196 /// operation and is not in use for any other I/O.
197 ///
198 /// To safely use this function callers must ensure that the pointers are
199 /// valid until the I/O operation is completed, typically via completion
200 /// ports and waiting to receive the completion notification on the port.
201 pub unsafe fn read_overlapped(
202 &self,
203 buf: &mut [u8],
204 overlapped: *mut OVERLAPPED,
205 ) -> io::Result<Option<usize>> {
206 let len = std::cmp::min(buf.len(), u32::MAX as usize) as u32;
207 let res = ReadFile(
208 self.handle.raw(),
209 buf.as_mut_ptr() as *mut _,
210 len,
211 std::ptr::null_mut(),
212 overlapped,
213 );
214 if res == 0 {
215 let err = io::Error::last_os_error();
216 if err.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
217 return Err(err);
218 }
219 }
220
221 let mut bytes = 0;
222 let res = GetOverlappedResult(self.handle.raw(), overlapped, &mut bytes, 0);
223 if res == 0 {
224 let err = io::Error::last_os_error();
225 if err.raw_os_error() == Some(ERROR_IO_INCOMPLETE as i32) {
226 Ok(None)
227 } else {
228 Err(err)
229 }
230 } else {
231 Ok(Some(bytes as usize))
232 }
233 }
234
235 /// Issues an overlapped write operation to occur on this pipe.
236 ///
237 /// This function will issue an asynchronous write to occur in an overlapped
238 /// fashion, returning immediately. The `buf` provided will be filled in
239 /// with data and the request is tracked by the `overlapped` function
240 /// provided.
241 ///
242 /// If the operation succeeds immediately, `Ok(Some(n))` is returned where
243 /// `n` is the number of bytes written. If an asynchronous operation is
244 /// enqueued, then `Ok(None)` is returned. Otherwise if an error occurred
245 /// it is returned.
246 ///
247 /// When this operation completes (or if it completes immediately), another
248 /// mechanism must be used to learn how many bytes were transferred (such as
249 /// looking at the filed in the IOCP status message).
250 ///
251 /// # Unsafety
252 ///
253 /// This function is unsafe because the kernel requires that the `buf` and
254 /// `overlapped` pointers to be valid until the end of the I/O operation.
255 /// The kernel also requires that `overlapped` is unique for this I/O
256 /// operation and is not in use for any other I/O.
257 ///
258 /// To safely use this function callers must ensure that the pointers are
259 /// valid until the I/O operation is completed, typically via completion
260 /// ports and waiting to receive the completion notification on the port.
261 pub unsafe fn write_overlapped(
262 &self,
263 buf: &[u8],
264 overlapped: *mut OVERLAPPED,
265 ) -> io::Result<Option<usize>> {
266 let len = std::cmp::min(buf.len(), u32::MAX as usize) as u32;
267 let res = WriteFile(
268 self.handle.raw(),
269 buf.as_ptr() as *const _,
270 len,
271 std::ptr::null_mut(),
272 overlapped,
273 );
274 if res == 0 {
275 let err = io::Error::last_os_error();
276 if err.raw_os_error() != Some(ERROR_IO_PENDING as i32) {
277 return Err(err);
278 }
279 }
280
281 let mut bytes = 0;
282 let res = GetOverlappedResult(self.handle.raw(), overlapped, &mut bytes, 0);
283 if res == 0 {
284 let err = io::Error::last_os_error();
285 if err.raw_os_error() == Some(ERROR_IO_INCOMPLETE as i32) {
286 Ok(None)
287 } else {
288 Err(err)
289 }
290 } else {
291 Ok(Some(bytes as usize))
292 }
293 }
294
295 /// Calls the `GetOverlappedResult` function to get the result of an
296 /// overlapped operation for this handle.
297 ///
298 /// This function takes the `OVERLAPPED` argument which must have been used
299 /// to initiate an overlapped I/O operation, and returns either the
300 /// successful number of bytes transferred during the operation or an error
301 /// if one occurred.
302 ///
303 /// # Unsafety
304 ///
305 /// This function is unsafe as `overlapped` must have previously been used
306 /// to execute an operation for this handle, and it must also be a valid
307 /// pointer to an `Overlapped` instance.
308 #[inline]
309 unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<usize> {
310 let mut transferred = 0;
311 let r = GetOverlappedResult(self.handle.raw(), overlapped, &mut transferred, 0);
312 if r == 0 {
313 Err(io::Error::last_os_error())
314 } else {
315 Ok(transferred as usize)
316 }
317 }
318 }
319
320 #[test]
321 fn ptr_from() {
322 use std::mem::ManuallyDrop;
323 use std::ptr;
324
325 let pipe = unsafe { ManuallyDrop::new(NamedPipe::from_raw_handle(ptr::null_mut())) };
326 let inner: &Inner = &pipe.inner;
327 assert_eq!(
328 inner as *const Inner,
329 unsafe { Inner::ptr_from_conn_overlapped(&inner.connect as *const _ as *mut OVERLAPPED) },
330 "`ptr_from_conn_overlapped` incorrect"
331 );
332 assert_eq!(
333 inner as *const Inner,
334 unsafe { Inner::ptr_from_read_overlapped(&inner.read as *const _ as *mut OVERLAPPED) },
335 "`ptr_from_read_overlapped` incorrect"
336 );
337 assert_eq!(
338 inner as *const Inner,
339 unsafe { Inner::ptr_from_write_overlapped(&inner.write as *const _ as *mut OVERLAPPED) },
340 "`ptr_from_write_overlapped` incorrect"
341 );
342 }
343
344 struct Io {
345 // Uniquely identifies the selector associated with this named pipe
346 cp: Option<Arc<CompletionPort>>,
347 // Token used to identify events
348 token: Option<Token>,
349 read: State,
350 write: State,
351 connect_error: Option<io::Error>,
352 }
353
354 #[derive(Debug)]
355 enum State {
356 None,
357 Pending(Vec<u8>, usize),
358 Ok(Vec<u8>, usize),
359 Err(io::Error),
360 }
361
362 // Odd tokens are for named pipes
363 static NEXT_TOKEN: AtomicUsize = AtomicUsize::new(1);
364
365 fn would_block() -> io::Error {
366 io::ErrorKind::WouldBlock.into()
367 }
368
369 impl NamedPipe {
370 /// Creates a new named pipe at the specified `addr` given a "reasonable
371 /// set" of initial configuration options.
372 pub fn new<A: AsRef<OsStr>>(addr: A) -> io::Result<NamedPipe> {
373 use std::os::windows::ffi::OsStrExt;
374 let name: Vec<_> = addr.as_ref().encode_wide().chain(Some(0)).collect();
375
376 // Safety: syscall
377 let h = unsafe {
378 CreateNamedPipeW(
379 name.as_ptr(),
380 PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED,
381 PIPE_TYPE_BYTE,
382 PIPE_UNLIMITED_INSTANCES,
383 65536,
384 65536,
385 0,
386 std::ptr::null_mut(),
387 )
388 };
389
390 if h == INVALID_HANDLE_VALUE {
391 Err(io::Error::last_os_error())
392 } else {
393 // Safety: nothing actually unsafe about this. The trait fn includes
394 // `unsafe`.
395 Ok(unsafe { Self::from_raw_handle(h as RawHandle) })
396 }
397 }
398
399 /// Attempts to call `ConnectNamedPipe`, if possible.
400 ///
401 /// This function will attempt to connect this pipe to a client in an
402 /// asynchronous fashion. If the function immediately establishes a
403 /// connection to a client then `Ok(())` is returned. Otherwise if a
404 /// connection attempt was issued and is now in progress then a "would
405 /// block" error is returned.
406 ///
407 /// When the connection is finished then this object will be flagged as
408 /// being ready for a write, or otherwise in the writable state.
409 ///
410 /// # Errors
411 ///
412 /// This function will return a "would block" error if the pipe has not yet
413 /// been registered with an event loop, if the connection operation has
414 /// previously been issued but has not yet completed, or if the connect
415 /// itself was issued and didn't finish immediately.
416 ///
417 /// Normal I/O errors from the call to `ConnectNamedPipe` are returned
418 /// immediately.
419 pub fn connect(&self) -> io::Result<()> {
420 // "Acquire the connecting lock" or otherwise just make sure we're the
421 // only operation that's using the `connect` overlapped instance.
422 if self.inner.connecting.swap(true, SeqCst) {
423 return Err(would_block());
424 }
425
426 // If `connect_overlapped` does not complete immediately then we need
427 // to pass a reference to `self.inner` to the completion handler.
428 // We need to increase the reference count here because `connect_done`
429 // could be called as soon as we call `connect_overlapped`.
430 let inner_for_completion = self.inner.clone();
431
432 // Now that we've flagged ourselves in the connecting state, issue the
433 // connection attempt. Afterwards interpret the return value and set
434 // internal state accordingly.
435 let res = unsafe {
436 let overlapped = self.inner.connect.as_ptr() as *mut _;
437 self.inner.connect_overlapped(overlapped)
438 };
439
440 match res {
441 // The connection operation finished immediately, so let's schedule
442 // reads/writes and such.
443 Ok(true) => {
444 self.inner.connecting.store(false, SeqCst);
445 Inner::post_register(&self.inner, None);
446 Ok(())
447 }
448
449 // If the overlapped operation was successful and didn't finish
450 // immediately then we forget a copy of the arc we hold
451 // internally. This ensures that when the completion status comes
452 // in for the I/O operation finishing it'll have a reference
453 // associated with it and our data will still be valid. The
454 // `connect_done` function will "reify" this forgotten pointer to
455 // drop the refcount on the other side.
456 Ok(false) => {
457 mem::forget(inner_for_completion);
458 Err(would_block())
459 }
460
461 Err(e) => {
462 self.inner.connecting.store(false, SeqCst);
463 Err(e)
464 }
465 }
466 }
467
468 /// Takes any internal error that has happened after the last I/O operation
469 /// which hasn't been retrieved yet.
470 ///
471 /// This is particularly useful when detecting failed attempts to `connect`.
472 /// After a completed `connect` flags this pipe as writable then callers
473 /// must invoke this method to determine whether the connection actually
474 /// succeeded. If this function returns `None` then a client is connected,
475 /// otherwise it returns an error of what happened and a client shouldn't be
476 /// connected.
477 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
478 Ok(self.inner.io.lock().unwrap().connect_error.take())
479 }
480
481 /// Disconnects this named pipe from a connected client.
482 ///
483 /// This function will disconnect the pipe from a connected client, if any,
484 /// transitively calling the `DisconnectNamedPipe` function.
485 ///
486 /// After a `disconnect` is issued, then a `connect` may be called again to
487 /// connect to another client.
488 pub fn disconnect(&self) -> io::Result<()> {
489 self.inner.disconnect()
490 }
491 }
492
493 impl FromRawHandle for NamedPipe {
494 unsafe fn from_raw_handle(handle: RawHandle) -> NamedPipe {
495 NamedPipe {
496 inner: Arc::new(Inner {
497 handle: Handle::new(handle as HANDLE),
498 connect: Overlapped::new(connect_done),
499 connecting: AtomicBool::new(false),
500 read: Overlapped::new(read_done),
501 write: Overlapped::new(write_done),
502 event: Overlapped::new(event_done),
503 io: Mutex::new(Io {
504 cp: None,
505 token: None,
506 read: State::None,
507 write: State::None,
508 connect_error: None,
509 }),
510 pool: Mutex::new(BufferPool::with_capacity(2)),
511 }),
512 }
513 }
514 }
515
516 impl Read for NamedPipe {
517 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
518 <&NamedPipe as Read>::read(&mut &*self, buf)
519 }
520 }
521
522 impl Write for NamedPipe {
523 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
524 <&NamedPipe as Write>::write(&mut &*self, buf)
525 }
526
527 fn flush(&mut self) -> io::Result<()> {
528 <&NamedPipe as Write>::flush(&mut &*self)
529 }
530 }
531
532 impl<'a> Read for &'a NamedPipe {
533 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
534 let mut state = self.inner.io.lock().unwrap();
535
536 if state.token.is_none() {
537 return Err(would_block());
538 }
539
540 match mem::replace(&mut state.read, State::None) {
541 // In theory not possible with `token` checked above,
542 // but return would block for now.
543 State::None => Err(would_block()),
544
545 // A read is in flight, still waiting for it to finish
546 State::Pending(buf, amt) => {
547 state.read = State::Pending(buf, amt);
548 Err(would_block())
549 }
550
551 // We previously read something into `data`, try to copy out some
552 // data. If we copy out all the data schedule a new read and
553 // otherwise store the buffer to get read later.
554 State::Ok(data, cur) => {
555 let n = {
556 let mut remaining = &data[cur..];
557 remaining.read(buf)?
558 };
559 let next = cur + n;
560 if next != data.len() {
561 state.read = State::Ok(data, next);
562 } else {
563 self.inner.put_buffer(data);
564 Inner::schedule_read(&self.inner, &mut state, None);
565 }
566 Ok(n)
567 }
568
569 // Looks like an in-flight read hit an error, return that here while
570 // we schedule a new one.
571 State::Err(e) => {
572 Inner::schedule_read(&self.inner, &mut state, None);
573 if e.raw_os_error() == Some(ERROR_BROKEN_PIPE as i32) {
574 Ok(0)
575 } else {
576 Err(e)
577 }
578 }
579 }
580 }
581 }
582
583 impl<'a> Write for &'a NamedPipe {
584 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
585 // Make sure there's no writes pending
586 let mut io = self.inner.io.lock().unwrap();
587
588 if io.token.is_none() {
589 return Err(would_block());
590 }
591
592 match io.write {
593 State::None => {}
594 State::Err(_) => match mem::replace(&mut io.write, State::None) {
595 State::Err(e) => return Err(e),
596 // `io` is locked, so this branch is unreachable
597 _ => unreachable!(),
598 },
599 // any other state should be handled in `write_done`
600 _ => {
601 return Err(would_block());
602 }
603 }
604
605 // Move `buf` onto the heap and fire off the write
606 let mut owned_buf = self.inner.get_buffer();
607 owned_buf.extend(buf);
608 match Inner::maybe_schedule_write(&self.inner, owned_buf, 0, &mut io)? {
609 // Some bytes are written immediately
610 Some(n) => Ok(n),
611 // Write operation is enqueued for whole buffer
612 None => Ok(buf.len()),
613 }
614 }
615
616 fn flush(&mut self) -> io::Result<()> {
617 Ok(())
618 }
619 }
620
621 impl Source for NamedPipe {
622 fn register(&mut self, registry: &Registry, token: Token, _: Interest) -> io::Result<()> {
623 let mut io = self.inner.io.lock().unwrap();
624
625 io.check_association(registry, false)?;
626
627 if io.token.is_some() {
628 return Err(io::Error::new(
629 io::ErrorKind::AlreadyExists,
630 "I/O source already registered with a `Registry`",
631 ));
632 }
633
634 if io.cp.is_none() {
635 let selector = registry.selector();
636
637 io.cp = Some(selector.clone_port());
638
639 let inner_token = NEXT_TOKEN.fetch_add(2, Relaxed) + 2;
640 selector.inner.cp.add_handle(inner_token, self)?;
641 }
642
643 io.token = Some(token);
644 drop(io);
645
646 Inner::post_register(&self.inner, None);
647
648 Ok(())
649 }
650
651 fn reregister(&mut self, registry: &Registry, token: Token, _: Interest) -> io::Result<()> {
652 let mut io = self.inner.io.lock().unwrap();
653
654 io.check_association(registry, true)?;
655
656 io.token = Some(token);
657 drop(io);
658
659 Inner::post_register(&self.inner, None);
660
661 Ok(())
662 }
663
664 fn deregister(&mut self, registry: &Registry) -> io::Result<()> {
665 let mut io = self.inner.io.lock().unwrap();
666
667 io.check_association(registry, true)?;
668
669 if io.token.is_none() {
670 return Err(io::Error::new(
671 io::ErrorKind::NotFound,
672 "I/O source not registered with `Registry`",
673 ));
674 }
675
676 io.token = None;
677 Ok(())
678 }
679 }
680
681 impl AsRawHandle for NamedPipe {
682 fn as_raw_handle(&self) -> RawHandle {
683 self.inner.handle.raw() as RawHandle
684 }
685 }
686
687 impl fmt::Debug for NamedPipe {
688 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
689 self.inner.handle.fmt(f)
690 }
691 }
692
693 impl Drop for NamedPipe {
694 fn drop(&mut self) {
695 // Cancel pending reads/connects, but don't cancel writes to ensure that
696 // everything is flushed out.
697 unsafe {
698 if self.inner.connecting.load(SeqCst) {
699 drop(cancel(&self.inner.handle, &self.inner.connect));
700 }
701
702 let io = self.inner.io.lock().unwrap();
703 if let State::Pending(..) = io.read {
704 drop(cancel(&self.inner.handle, &self.inner.read));
705 }
706 }
707 }
708 }
709
710 impl Inner {
711 /// Schedules a read to happen in the background, executing an overlapped
712 /// operation.
713 ///
714 /// This function returns `true` if either of the following conditions are met:
715 /// * A normal error happens
716 /// * The read is scheduled in the background
717 /// * Data is already available to be read (ERROR_MORE_DATA)
718 ///
719 /// If the pipe is no longer connected (ERROR_PIPE_LISTENING) then `false` is
720 /// returned and no read is scheduled.
721 fn schedule_read(me: &Arc<Inner>, io: &mut Io, events: Option<&mut Vec<Event>>) -> bool {
722 // Check to see if a read is already scheduled/completed
723 match io.read {
724 State::None => {}
725 _ => return true,
726 }
727
728 // Allocate a buffer and schedule the read.
729 let mut buf = me.get_buffer();
730 let e = unsafe {
731 let overlapped = me.read.as_ptr() as *mut _;
732 let slice = slice::from_raw_parts_mut(buf.as_mut_ptr(), buf.capacity());
733 me.read_overlapped(slice, overlapped)
734 };
735
736 match e {
737 // See `NamedPipe::connect` above for the rationale behind `forget`
738 Ok(_) => {
739 io.read = State::Pending(buf, 0); // 0 is ignored on read side
740 mem::forget(me.clone());
741 true
742 }
743
744 // If ERROR_PIPE_LISTENING happens then it's not a real read error,
745 // we just need to wait for a connect.
746 Err(ref e) if e.raw_os_error() == Some(ERROR_PIPE_LISTENING as i32) => false,
747
748 // If ERROR_MORE_DATA is returned, it means the slice of unused capacity of the
749 // buffer provided is less than the amount of data available to be read. So
750 // prioritize draining the buffer before scheduling a new read.
751 //
752 // Return `true` to indicate that an overlapped read was scheduled "successfully",
753 // without actually scheduling it. Instead, update `io.read` to `State::Ok(buf, 0)`
754 // to ensure that the next `std::io::Read::read` call is presented still with the
755 // unread data to read from.
756 Err(ref e) if e.raw_os_error() == Some(ERROR_MORE_DATA as i32) => {
757 io.read = State::Ok(buf, 0);
758 mem::forget(me.clone());
759 true
760 }
761
762 // If some other error happened, though, we're now readable to give
763 // out the error.
764 Err(e) => {
765 io.read = State::Err(e);
766 io.notify_readable(me, events);
767 true
768 }
769 }
770 }
771
772 /// Maybe schedules overlapped write operation.
773 ///
774 /// * `None` means that overlapped operation was enqueued
775 /// * `Some(n)` means that `n` bytes was immediately written.
776 /// Note, that `write_done` will fire anyway to clean up the state.
777 fn maybe_schedule_write(
778 me: &Arc<Inner>,
779 buf: Vec<u8>,
780 pos: usize,
781 io: &mut Io,
782 ) -> io::Result<Option<usize>> {
783 // Very similar to `schedule_read` above, just done for the write half.
784 let e = unsafe {
785 let overlapped = me.write.as_ptr() as *mut _;
786 me.write_overlapped(&buf[pos..], overlapped)
787 };
788
789 // See `connect` above for the rationale behind `forget`
790 match e {
791 // `n` bytes are written immediately
792 Ok(Some(n)) => {
793 io.write = State::Ok(buf, pos);
794 mem::forget(me.clone());
795 Ok(Some(n))
796 }
797 // write operation is enqueued
798 Ok(None) => {
799 io.write = State::Pending(buf, pos);
800 mem::forget(me.clone());
801 Ok(None)
802 }
803 Err(e) => Err(e),
804 }
805 }
806
807 fn schedule_write(
808 me: &Arc<Inner>,
809 buf: Vec<u8>,
810 pos: usize,
811 io: &mut Io,
812 events: Option<&mut Vec<Event>>,
813 ) {
814 match Inner::maybe_schedule_write(me, buf, pos, io) {
815 Ok(Some(_)) => {
816 // immediate result will be handled in `write_done`,
817 // so we'll reinterpret the `Ok` state
818 let state = mem::replace(&mut io.write, State::None);
819 io.write = match state {
820 State::Ok(buf, pos) => State::Pending(buf, pos),
821 // io is locked, so this branch is unreachable
822 _ => unreachable!(),
823 };
824 mem::forget(me.clone());
825 }
826 Ok(None) => (),
827 Err(e) => {
828 io.write = State::Err(e);
829 io.notify_writable(me, events);
830 }
831 }
832 }
833
834 fn post_register(me: &Arc<Inner>, mut events: Option<&mut Vec<Event>>) {
835 let mut io = me.io.lock().unwrap();
836 #[allow(clippy::needless_option_as_deref)]
837 if Inner::schedule_read(me, &mut io, events.as_deref_mut()) {
838 if let State::None = io.write {
839 io.notify_writable(me, events);
840 }
841 }
842 }
843
844 fn get_buffer(&self) -> Vec<u8> {
845 self.pool.lock().unwrap().get(4 * 1024)
846 }
847
848 fn put_buffer(&self, buf: Vec<u8>) {
849 self.pool.lock().unwrap().put(buf)
850 }
851 }
852
853 unsafe fn cancel(handle: &Handle, overlapped: &Overlapped) -> io::Result<()> {
854 let ret = CancelIoEx(handle.raw(), overlapped.as_ptr());
855 // `CancelIoEx` returns 0 on error:
856 // https://docs.microsoft.com/en-us/windows/win32/fileio/cancelioex-func
857 if ret == 0 {
858 Err(io::Error::last_os_error())
859 } else {
860 Ok(())
861 }
862 }
863
864 fn connect_done(status: &OVERLAPPED_ENTRY, events: Option<&mut Vec<Event>>) {
865 let status = CompletionStatus::from_entry(status);
866
867 // Acquire the `Arc<Inner>`. Note that we should be guaranteed that
868 // the refcount is available to us due to the `mem::forget` in
869 // `connect` above.
870 let me = unsafe { Arc::from_raw(Inner::ptr_from_conn_overlapped(status.overlapped())) };
871
872 // Flag ourselves as no longer using the `connect` overlapped instances.
873 let prev = me.connecting.swap(false, SeqCst);
874 assert!(prev, "NamedPipe was not previously connecting");
875
876 // Stash away our connect error if one happened
877 debug_assert_eq!(status.bytes_transferred(), 0);
878 unsafe {
879 match me.result(status.overlapped()) {
880 Ok(n) => debug_assert_eq!(n, 0),
881 Err(e) => me.io.lock().unwrap().connect_error = Some(e),
882 }
883 }
884
885 // We essentially just finished a registration, so kick off a
886 // read and register write readiness.
887 Inner::post_register(&me, events);
888 }
889
890 fn read_done(status: &OVERLAPPED_ENTRY, events: Option<&mut Vec<Event>>) {
891 let status = CompletionStatus::from_entry(status);
892
893 // Acquire the `FromRawArc<Inner>`. Note that we should be guaranteed that
894 // the refcount is available to us due to the `mem::forget` in
895 // `schedule_read` above.
896 let me = unsafe { Arc::from_raw(Inner::ptr_from_read_overlapped(status.overlapped())) };
897
898 let mut io = me.io.lock().unwrap();
899 let mut buf = match mem::replace(&mut io.read, State::None) {
900 State::Ok(buf, pos) => {
901 io.read = State::Ok(buf, pos);
902
903 // Flag readiness that we have undelivered data to be read.
904 io.notify_readable(&me, events);
905 return;
906 }
907 State::Pending(buf, _) => buf,
908 State::Err(e) => {
909 io.read = State::Err(e);
910
911 // Flag readiness that the error needs to be delivered.
912 io.notify_readable(&me, events);
913 return;
914 }
915 State::None => unreachable!(),
916 };
917 unsafe {
918 match me.result(status.overlapped()) {
919 Ok(n) => {
920 debug_assert_eq!(status.bytes_transferred() as usize, n);
921 buf.set_len(status.bytes_transferred() as usize);
922 io.read = State::Ok(buf, 0);
923 }
924 // This is non-fatal. The buffer was simply too small for the entire message.
925 // Deliver the bytes we got, and if the caller wants to read the rest of the
926 // message, they can initiate another read.
927 Err(e) if e.raw_os_error() == Some(ERROR_MORE_DATA as i32) => {
928 buf.set_len(status.bytes_transferred() as usize);
929 io.read = State::Ok(buf, 0);
930 }
931 Err(e) => {
932 debug_assert_eq!(status.bytes_transferred(), 0);
933 io.read = State::Err(e);
934 }
935 }
936 }
937
938 // Flag our readiness that we've got data.
939 io.notify_readable(&me, events);
940 }
941
942 fn write_done(status: &OVERLAPPED_ENTRY, events: Option<&mut Vec<Event>>) {
943 let status = CompletionStatus::from_entry(status);
944
945 // Acquire the `Arc<Inner>`. Note that we should be guaranteed that
946 // the refcount is available to us due to the `mem::forget` in
947 // `schedule_write` above.
948 let me = unsafe { Arc::from_raw(Inner::ptr_from_write_overlapped(status.overlapped())) };
949
950 // Make the state change out of `Pending`. If we wrote the entire buffer
951 // then we're writable again and otherwise we schedule another write.
952 let mut io = me.io.lock().unwrap();
953 let (buf, pos) = match mem::replace(&mut io.write, State::None) {
954 // `Ok` here means, that the operation was completed immediately
955 // `bytes_transferred` is already reported to a client.
956 // Hence, we don't reset the state to `Ok` but leave it in `None`.
957 State::Ok(..) => {
958 io.notify_writable(&me, events);
959 return;
960 }
961 State::Pending(buf, pos) => (buf, pos),
962 State::Err(e) => {
963 io.write = State::Err(e);
964
965 // Flag readiness that the error needs to be delivered.
966 io.notify_writable(&me, events);
967 return;
968 }
969 State::None => unreachable!(),
970 };
971
972 unsafe {
973 match me.result(status.overlapped()) {
974 Ok(n) => {
975 debug_assert_eq!(status.bytes_transferred() as usize, n);
976 let new_pos = pos + (status.bytes_transferred() as usize);
977 if new_pos == buf.len() {
978 me.put_buffer(buf);
979 io.notify_writable(&me, events);
980 } else {
981 Inner::schedule_write(&me, buf, new_pos, &mut io, events);
982 }
983 }
984 Err(e) => {
985 debug_assert_eq!(status.bytes_transferred(), 0);
986 io.write = State::Err(e);
987 io.notify_writable(&me, events);
988 }
989 }
990 }
991 }
992
993 fn event_done(status: &OVERLAPPED_ENTRY, events: Option<&mut Vec<Event>>) {
994 let status = CompletionStatus::from_entry(status);
995
996 // Acquire the `Arc<Inner>`. Note that we should be guaranteed that
997 // the refcount is available to us due to the `mem::forget` in
998 // `schedule_write` above.
999 let me = unsafe { Arc::from_raw(Inner::ptr_from_event_overlapped(status.overlapped())) };
1000
1001 let io = me.io.lock().unwrap();
1002
1003 // Make sure the I/O handle is still registered with the selector
1004 if io.token.is_some() {
1005 // This method is also called during `Selector::drop` to perform
1006 // cleanup. In this case, `events` is `None` and we don't need to track
1007 // the event.
1008 if let Some(events) = events {
1009 let mut ev = Event::from_completion_status(&status);
1010 // Reverse the `.data` alteration done in `schedule_event`. This
1011 // alteration was done so the selector recognized the event as one from
1012 // a named pipe.
1013 ev.data >>= 1;
1014 events.push(ev);
1015 }
1016 }
1017 }
1018
1019 impl Io {
1020 fn check_association(&self, registry: &Registry, required: bool) -> io::Result<()> {
1021 match self.cp {
1022 Some(ref cp) if !registry.selector().same_port(cp) => Err(io::Error::new(
1023 io::ErrorKind::AlreadyExists,
1024 "I/O source already registered with a different `Registry`",
1025 )),
1026 None if required => Err(io::Error::new(
1027 io::ErrorKind::NotFound,
1028 "I/O source not registered with `Registry`",
1029 )),
1030 _ => Ok(()),
1031 }
1032 }
1033
1034 fn notify_readable(&self, me: &Arc<Inner>, events: Option<&mut Vec<Event>>) {
1035 if let Some(token) = self.token {
1036 let mut ev = Event::new(token);
1037 ev.set_readable();
1038
1039 if let Some(events) = events {
1040 events.push(ev);
1041 } else {
1042 self.schedule_event(me, ev);
1043 }
1044 }
1045 }
1046
1047 fn notify_writable(&self, me: &Arc<Inner>, events: Option<&mut Vec<Event>>) {
1048 if let Some(token) = self.token {
1049 let mut ev = Event::new(token);
1050 ev.set_writable();
1051
1052 if let Some(events) = events {
1053 events.push(ev);
1054 } else {
1055 self.schedule_event(me, ev);
1056 }
1057 }
1058 }
1059
1060 fn schedule_event(&self, me: &Arc<Inner>, mut event: Event) {
1061 // Alter the token so that the selector will identify the IOCP event as
1062 // one for a named pipe. This will be reversed in `event_done`
1063 //
1064 // `data` for named pipes is an auto-incrementing counter. Because
1065 // `data` is `u64` we do not risk losing the most-significant bit
1066 // (unless a user creates 2^62 named pipes during the lifetime of the
1067 // process).
1068 event.data <<= 1;
1069 event.data += 1;
1070
1071 let completion_status =
1072 event.to_completion_status_with_overlapped(me.event.as_ptr() as *mut _);
1073
1074 match self.cp.as_ref().unwrap().post(completion_status) {
1075 Ok(_) => {
1076 // Increase the ref count of `Inner` for the completion event.
1077 mem::forget(me.clone());
1078 }
1079 Err(_) => {
1080 // Nothing to do here
1081 }
1082 }
1083 }
1084 }
1085
1086 struct BufferPool {
1087 pool: Vec<Vec<u8>>,
1088 }
1089
1090 impl BufferPool {
1091 fn with_capacity(cap: usize) -> BufferPool {
1092 BufferPool {
1093 pool: Vec::with_capacity(cap),
1094 }
1095 }
1096
1097 fn get(&mut self, default_cap: usize) -> Vec<u8> {
1098 self.pool
1099 .pop()
1100 .unwrap_or_else(|| Vec::with_capacity(default_cap))
1101 }
1102
1103 fn put(&mut self, mut buf: Vec<u8>) {
1104 if self.pool.len() < self.pool.capacity() {
1105 unsafe {
1106 buf.set_len(0);
1107 }
1108 self.pool.push(buf);
1109 }
1110 }
1111 }