Debian Codegraph @

libs/gst/helpers/ptp/io.rs

raw
1 // GStreamer
2 //
3 // Copyright (C) 2015-2023 Sebastian Dröge <[email protected]>
4 //
5 // This Source Code Form is subject to the terms of the Mozilla Public License, v2.0.
6 // If a copy of the MPL was not distributed with this file, You can obtain one at
7 // <https://mozilla.org/MPL/2.0/>.
8 //
9 // SPDX-License-Identifier: MPL-2.0
10
11 use std::net::UdpSocket;
12
13 #[derive(Debug, PartialEq, Eq, Clone, Copy)]
14 pub enum SocketType {
15 EventSocket,
16 GeneralSocket,
17 }
18
19 /// Result of polling the inputs of the `Poll`.
20 ///
21 /// Note that reading from the sockets is non-blocking but reading from stdin is blocking so
22 /// special care has to be taken to only read as much as is available.
23 pub struct PollResult<'a> {
24 ready_sockets: &'a [(usize, SocketType, &'a UdpSocket)],
25 sockets: &'a [(UdpSocket, UdpSocket)],
26 stdin: Option<&'a Stdin>,
27 stdout: &'a Stdout,
28 }
29
30 impl<'a> PollResult<'a> {
31 /// Returns the sockets that are currently ready for reading.
32 pub fn ready_sockets(&self) -> &[(usize, SocketType, &UdpSocket)] {
33 self.ready_sockets
34 }
35
36 /// Returns the event socket.
37 pub fn event_socket(&self, idx: usize) -> &UdpSocket {
38 &self.sockets[idx].0
39 }
40
41 /// Returns the general socket.
42 pub fn general_socket(&self, idx: usize) -> &UdpSocket {
43 &self.sockets[idx].1
44 }
45
46 /// Returns standard input if there is data to read.
47 pub fn stdin(&self) -> Option<&Stdin> {
48 self.stdin
49 }
50
51 /// Returns standard output.
52 pub fn stdout(&self) -> &Stdout {
53 self.stdout
54 }
55 }
56
57 #[cfg(unix)]
58 mod imp {
59 use super::{PollResult, SocketType};
60
61 use std::{
62 io::{self, Read, Write},
63 mem,
64 net::UdpSocket,
65 os::unix::io::{AsRawFd, RawFd},
66 };
67
68 use crate::{bail, error::Error, ffi::unix::*};
69
70 /// Inputs and outputs, and allowing to poll the inputs for available data.
71 ///
72 /// This carries the event/general UDP socket and stdin/stdout.
73 pub struct Poll {
74 sockets: Vec<(UdpSocket, UdpSocket)>,
75 stdin: Stdin,
76 stdout: Stdout,
77 pollfd: Vec<pollfd>,
78 results_cache: Vec<(usize, SocketType, &'static UdpSocket)>,
79 }
80
81 #[cfg(test)]
82 /// A file descriptor pair representing a pipe for testing purposes.
83 pub struct Pipe {
84 pub read: i32,
85 pub write: i32,
86 }
87
88 #[cfg(test)]
89 impl Pipe {
90 fn new() -> io::Result<Self> {
91 // SAFETY: Requires two integers to be passed in and creates the read
92 // and write end of a pipe.
93 unsafe {
94 let mut fds = std::mem::MaybeUninit::<[i32; 2]>::uninit();
95 let res = pipe(fds.as_mut_ptr() as *mut i32);
96 if res == 0 {
97 let fds = fds.assume_init();
98 Ok(Pipe {
99 read: fds[0],
100 write: fds[1],
101 })
102 } else {
103 Err(io::Error::last_os_error())
104 }
105 }
106 }
107 }
108
109 #[cfg(test)]
110 impl Drop for Pipe {
111 fn drop(&mut self) {
112 // SAFETY: Only ever created with valid fds
113 unsafe {
114 close(self.read);
115 close(self.write);
116 }
117 }
118 }
119
120 #[cfg(test)]
121 impl Read for &Pipe {
122 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
123 // SAFETY: read() requires a valid fd and a mutable buffer with the given size.
124 // The fd is valid by construction as is the buffer.
125 //
126 // read() will return the number of bytes read or a negative value on errors.
127 let res = unsafe { read(self.read, buf.as_mut_ptr(), buf.len()) };
128
129 if res < 0 {
130 Err(std::io::Error::last_os_error())
131 } else {
132 Ok(res as usize)
133 }
134 }
135 }
136
137 #[cfg(test)]
138 impl Write for Pipe {
139 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
140 // SAFETY: write() requires a valid fd and a mutable buffer with the given size.
141 // The fd is valid by construction as is the buffer.
142 //
143 // write() will return the number of bytes written or a negative value on errors.
144 let res = unsafe { write(self.write, buf.as_ptr(), buf.len()) };
145
146 if res == -1 {
147 Err(std::io::Error::last_os_error())
148 } else {
149 Ok(res as usize)
150 }
151 }
152
153 fn flush(&mut self) -> io::Result<()> {
154 Ok(())
155 }
156 }
157
158 impl Poll {
159 /// Name of the input based on the `struct pollfd` index.
160 fn fd_name(idx: usize, len: usize) -> &'static str {
161 match idx {
162 i if i == len - 1 => "stdin",
163 i if i % 2 == 0 => "event socket",
164 i if i % 2 == 1 => "general socket",
165 _ => unreachable!(),
166 }
167 }
168
169 /// Create a new `Poll` instance from the pairs of sockets.
170 pub fn new(sockets: Vec<(UdpSocket, UdpSocket)>) -> Result<Self, Error> {
171 let stdin = Stdin::acquire();
172 let stdout = Stdout::acquire();
173 let n_sockets = sockets.len();
174
175 Ok(Self {
176 sockets,
177 stdin,
178 stdout,
179 pollfd: Vec::with_capacity(n_sockets * 2 + 1),
180 results_cache: Vec::with_capacity(n_sockets * 2),
181 })
182 }
183
184 #[cfg(test)]
185 /// Create a new `Poll` instance for testing purposes.
186 ///
187 /// The returned `Pipe`s are for stdin and stdout.
188 pub fn new_test(
189 event_socket: UdpSocket,
190 general_socket: UdpSocket,
191 ) -> Result<(Self, Pipe, Pipe), Error> {
192 let stdin = Pipe::new().unwrap();
193 let stdout = Pipe::new().unwrap();
194
195 Ok((
196 Self {
197 sockets: vec![(event_socket, general_socket)],
198 stdin: Stdin(stdin.read),
199 stdout: Stdout(stdout.write),
200 pollfd: Vec::with_capacity(3),
201 results_cache: Vec::with_capacity(2),
202 },
203 stdin,
204 stdout,
205 ))
206 }
207
208 /// Reference to the event socket.
209 #[allow(unused)]
210 pub fn event_socket(&self, iface: usize) -> &UdpSocket {
211 &self.sockets[iface].0
212 }
213
214 /// Reference to the general socket.
215 #[allow(unused)]
216 pub fn general_socket(&self, iface: usize) -> &UdpSocket {
217 &self.sockets[iface].1
218 }
219
220 /// Reference to stdin for reading.
221 #[allow(unused)]
222 pub fn stdin(&self) -> &Stdin {
223 &self.stdin
224 }
225
226 /// Reference to stdout for writing.
227 pub fn stdout(&self) -> &Stdout {
228 &self.stdout
229 }
230
231 /// Poll the event socket, general socket and stdin for available data to read.
232 ///
233 /// This blocks until at least one input has data available.
234 pub fn poll<'a>(&'a mut self) -> Result<PollResult<'a>, Error> {
235 self.pollfd.clear();
236 for (event_socket, general_socket) in &self.sockets {
237 self.pollfd.push(pollfd {
238 fd: event_socket.as_raw_fd(),
239 events: POLLIN,
240 revents: 0,
241 });
242 self.pollfd.push(pollfd {
243 fd: general_socket.as_raw_fd(),
244 events: POLLIN,
245 revents: 0,
246 });
247 }
248
249 self.pollfd.push(pollfd {
250 fd: self.stdin.0,
251 events: POLLIN,
252 revents: 0,
253 });
254
255 // SAFETY: Polls the given pollfds above and requires a valid number to be passed.
256 // A negative timeout means that it will wait until at least one of the pollfds is
257 // ready.
258 //
259 // Will return -1 on error, otherwise the number of ready pollfds. This can never be
260 // zero as a non-empty set of pollfds is passed.
261 //
262 // On EINTR polling should be retried.
263 unsafe {
264 loop {
265 let res = poll(self.pollfd[..].as_mut_ptr(), self.pollfd.len() as _, -1);
266 if res == -1 {
267 let err = std::io::Error::last_os_error();
268 if err.kind() == std::io::ErrorKind::Interrupted {
269 continue;
270 }
271 bail!(source: err, "Failed polling");
272 }
273 assert_ne!(res, 0);
274 break;
275 }
276 }
277
278 // Check for errors or hangup first
279 for (idx, pfd) in self.pollfd.iter().enumerate() {
280 if pfd.revents & (POLLERR | POLLNVAL) != 0 {
281 bail!(
282 "Poll error on {} for interface {}",
283 Self::fd_name(idx, self.pollfd.len()),
284 idx / 2
285 );
286 }
287
288 if pfd.revents & POLLHUP != 0 {
289 bail!(
290 "Hang up during polling on {} for interface {}",
291 Self::fd_name(idx, self.pollfd.len()),
292 idx / 2
293 );
294 }
295 }
296
297 self.results_cache.clear();
298 // SAFETY: References have the same memory representation independent of lifetime
299 let ready_sockets = unsafe {
300 mem::transmute::<
301 &mut Vec<(usize, SocketType, &'static UdpSocket)>,
302 &mut Vec<(usize, SocketType, &'a UdpSocket)>,
303 >(&mut self.results_cache)
304 };
305
306 for (idx, pfd) in self.pollfd.iter().enumerate() {
307 if pfd.revents & POLLIN != 0 {
308 if idx == self.pollfd.len() - 1 {
309 break;
310 }
311 if idx % 2 == 0 {
312 ready_sockets.push((
313 idx / 2,
314 SocketType::EventSocket,
315 &self.sockets[idx / 2].0,
316 ));
317 } else {
318 ready_sockets.push((
319 idx / 2,
320 SocketType::GeneralSocket,
321 &self.sockets[idx / 2].1,
322 ));
323 }
324 }
325 }
326
327 Ok(PollResult {
328 ready_sockets: &*ready_sockets,
329 sockets: &self.sockets,
330 stdin: if self.pollfd[self.pollfd.len() - 1].revents & POLLIN != 0 {
331 Some(&self.stdin)
332 } else {
333 None
334 },
335 stdout: &self.stdout,
336 })
337 }
338 }
339
340 /// Raw, unbuffered handle to `stdin`.
341 ///
342 /// This implements the `Read` trait for reading.
343 pub struct Stdin(RawFd);
344
345 impl Stdin {
346 fn acquire() -> Self {
347 Stdin(STDIN_FILENO)
348 }
349 }
350
351 impl Read for Stdin {
352 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
353 <&Stdin as Read>::read(&mut &*self, buf)
354 }
355 }
356
357 impl Read for &Stdin {
358 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
359 // SAFETY: read() requires a valid fd and a mutable buffer with the given size.
360 // The fd is valid by construction as is the buffer.
361 //
362 // read() will return the number of bytes read or a negative value on errors.
363 let res = unsafe { read(self.0, buf.as_mut_ptr(), buf.len()) };
364
365 if res < 0 {
366 Err(std::io::Error::last_os_error())
367 } else {
368 Ok(res as usize)
369 }
370 }
371 }
372
373 /// Raw, unbuffered handle to `stdout`.
374 ///
375 /// This implements the `Write` trait for writing.
376 pub struct Stdout(RawFd);
377
378 impl Stdout {
379 fn acquire() -> Self {
380 Stdout(STDOUT_FILENO)
381 }
382 }
383
384 impl Write for Stdout {
385 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
386 <&Stdout as Write>::write(&mut &*self, buf)
387 }
388
389 fn flush(&mut self) -> io::Result<()> {
390 <&Stdout as Write>::flush(&mut &*self)
391 }
392 }
393
394 impl Write for &Stdout {
395 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
396 // SAFETY: write() requires a valid fd and a mutable buffer with the given size.
397 // The fd is valid by construction as is the buffer.
398 //
399 // write() will return the number of bytes written or a negative value on errors.
400 let res = unsafe { write(self.0, buf.as_ptr(), buf.len()) };
401
402 if res == -1 {
403 Err(std::io::Error::last_os_error())
404 } else {
405 Ok(res as usize)
406 }
407 }
408
409 fn flush(&mut self) -> io::Result<()> {
410 Ok(())
411 }
412 }
413
414 /// Raw, unbuffered handle to `stderr`.
415 ///
416 /// This implements the `Write` trait for writing and is implemented as a singleton to allow
417 /// usage from everywhere at any time for logging purposes.
418 ///
419 /// This does not implement any locking so usage from multiple threads at once will likely
420 /// cause interleaved output.
421 pub struct Stderr(RawFd);
422
423 impl Stderr {
424 #[cfg(not(test))]
425 pub fn acquire() -> Self {
426 Stderr(STDERR_FILENO)
427 }
428 }
429
430 impl Write for Stderr {
431 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
432 <&Stderr as Write>::write(&mut &*self, buf)
433 }
434
435 fn flush(&mut self) -> io::Result<()> {
436 <&Stderr as Write>::flush(&mut &*self)
437 }
438 }
439
440 impl Write for &Stderr {
441 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
442 // SAFETY: write() requires a valid fd and a mutable buffer with the given size.
443 // The fd is valid by construction as is the buffer.
444 //
445 // write() will return the number of bytes written or a negative value on errors.
446 let res = unsafe { write(self.0, buf.as_ptr(), buf.len()) };
447
448 if res == -1 {
449 Err(std::io::Error::last_os_error())
450 } else {
451 Ok(res as usize)
452 }
453 }
454
455 fn flush(&mut self) -> io::Result<()> {
456 Ok(())
457 }
458 }
459 }
460
461 #[cfg(windows)]
462 mod imp {
463 use super::{PollResult, SocketType};
464
465 use std::{
466 cmp,
467 io::{self, Read, Write},
468 mem,
469 net::UdpSocket,
470 os::windows::{io::AsRawSocket, raw::HANDLE},
471 ptr,
472 sync::{Arc, Condvar, Mutex},
473 thread,
474 };
475
476 use crate::{
477 bail,
478 error::{Context, Error},
479 ffi::windows::*,
480 };
481
482 /// Inputs and outputs, and allowing to poll the inputs for available data.
483 ///
484 /// This carries the event/general UDP socket and stdin/stdout.
485 pub struct Poll {
486 sockets: Vec<(UdpSocket, UdpSocket)>,
487 events: Vec<(EventHandle, EventHandle)>,
488 stdin: Stdin,
489 stdout: Stdout,
490 handles: Vec<HANDLE>,
491 results_cache: Vec<(usize, SocketType, &'static UdpSocket)>,
492 }
493
494 /// Helper struct for a WSA event.
495 struct EventHandle(HANDLE);
496
497 impl EventHandle {
498 fn new() -> io::Result<Self> {
499 // SAFETY: WSACreateEvent() returns 0 on error or otherwise a valid WSA event
500 // that has to be closed again later.
501 unsafe {
502 let event = WSACreateEvent();
503 if event.is_null() || event == INVALID_HANDLE_VALUE {
504 Err(io::Error::from_raw_os_error(WSAGetLastError()))
505 } else {
506 Ok(EventHandle(event))
507 }
508 }
509 }
510 }
511
512 impl Drop for EventHandle {
513 fn drop(&mut self) {
514 // SAFETY: The event is valid by construction and dropped at most once, so can be
515 // safely closed here..
516 //
517 // The return value is intentionally ignored as nothing else can be done
518 // on errors anyway.
519 unsafe {
520 let _ = WSACloseEvent(self.0);
521 }
522 }
523 }
524
525 #[cfg(test)]
526 pub struct Pipe {
527 read: HANDLE,
528 write: HANDLE,
529 }
530
531 #[cfg(test)]
532 impl Drop for Pipe {
533 fn drop(&mut self) {
534 // SAFETY: Both handles are by construction valid up there.
535 unsafe {
536 CloseHandle(self.read);
537 CloseHandle(self.write);
538 }
539 }
540 }
541
542 #[cfg(test)]
543 impl Pipe {
544 fn new() -> io::Result<Self> {
545 // SAFETY: On success returns a non-zero integer and stores read/write handles in the
546 // two out pointers, which will have to be closed again later.
547 unsafe {
548 let mut readpipe = mem::MaybeUninit::uninit();
549 let mut writepipe = mem::MaybeUninit::uninit();
550
551 let res = CreatePipe(
552 readpipe.as_mut_ptr(),
553 writepipe.as_mut_ptr(),
554 ptr::null_mut(),
555 0,
556 );
557
558 if res != 0 {
559 Ok(Self {
560 read: readpipe.assume_init(),
561 write: writepipe.assume_init(),
562 })
563 } else {
564 Err(io::Error::last_os_error())
565 }
566 }
567 }
568 }
569
570 #[cfg(test)]
571 impl Read for &Pipe {
572 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
573 // SAFETY: Reads the given number of bytes into the buffer from the stdin handle.
574 unsafe {
575 let mut lpnumberofbytesread = mem::MaybeUninit::uninit();
576 let res = ReadFile(
577 self.read,
578 buf.as_mut_ptr(),
579 cmp::min(buf.len() as u32, u32::MAX) as u32,
580 lpnumberofbytesread.as_mut_ptr(),
581 ptr::null_mut(),
582 );
583
584 if res == 0 {
585 Err(io::Error::last_os_error())
586 } else {
587 Ok(lpnumberofbytesread.assume_init() as usize)
588 }
589 }
590 }
591 }
592
593 #[cfg(test)]
594 impl Write for Pipe {
595 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
596 // SAFETY: Writes the given number of bytes to stdout or at most u32::MAX. On error
597 // zero is returned, otherwise the number of bytes written is set accordingly and
598 // returned.
599 unsafe {
600 let mut lpnumberofbyteswritten = mem::MaybeUninit::uninit();
601 let res = WriteFile(
602 self.write,
603 buf.as_ptr(),
604 cmp::min(buf.len() as u32, u32::MAX) as u32,
605 lpnumberofbyteswritten.as_mut_ptr(),
606 ptr::null_mut(),
607 );
608
609 if res == 0 {
610 Err(io::Error::last_os_error())
611 } else {
612 Ok(lpnumberofbyteswritten.assume_init() as usize)
613 }
614 }
615 }
616
617 fn flush(&mut self) -> io::Result<()> {
618 Ok(())
619 }
620 }
621
622 impl Poll {
623 /// Internal constructor.
624 pub fn new_internal(
625 sockets: Vec<(UdpSocket, UdpSocket)>,
626 stdin: Stdin,
627 stdout: Stdout,
628 ) -> Result<Self, Error> {
629 // Create event objects for the readability of the sockets.
630 let events = sockets
631 .iter()
632 .map(|(_event_socket, _general_socket)| -> Result<_, Error> {
633 Ok((
634 EventHandle::new().context("Failed creating WSA event")?,
635 EventHandle::new().context("Failed creating WSA event")?,
636 ))
637 })
638 .collect::<Result<Vec<_>, Error>>()?;
639
640 for ((event_socket, general_socket), (event_socket_event, general_socket_event)) in
641 Iterator::zip(sockets.iter(), events.iter())
642 {
643 // SAFETY: WSAEventSelect() requires a valid socket and WSA event, which are both
644 // passed here, and the bitflag of events that should be selected for.
645 //
646 // On error a non-zero value is returned.
647 unsafe {
648 if WSAEventSelect(event_socket.as_raw_socket(), event_socket_event.0, FD_READ)
649 != 0
650 {
651 bail!(
652 source: io::Error::from_raw_os_error(WSAGetLastError()),
653 "Failed selecting for read events on event socket"
654 );
655 }
656
657 if WSAEventSelect(
658 general_socket.as_raw_socket(),
659 general_socket_event.0,
660 FD_READ,
661 ) != 0
662 {
663 bail!(
664 source: io::Error::from_raw_os_error(WSAGetLastError()),
665 "Failed selecting for read events on general socket"
666 );
667 }
668 }
669 }
670
671 let n_sockets = sockets.len();
672
673 Ok(Self {
674 sockets,
675 events,
676 stdin,
677 stdout,
678 handles: Vec::with_capacity(n_sockets * 2 + 1),
679 results_cache: Vec::with_capacity(1),
680 })
681 }
682
683 /// Create a new `Poll` instance from the two sockets.
684 pub fn new(sockets: Vec<(UdpSocket, UdpSocket)>) -> Result<Self, Error> {
685 let stdin = Stdin::acquire().context("Failure acquiring stdin handle")?;
686 let stdout = Stdout::acquire().context("Failed acquiring stdout handle")?;
687
688 Self::new_internal(sockets, stdin, stdout)
689 }
690
691 #[cfg(test)]
692 /// Create a new `Poll` instance for testing purposes.
693 ///
694 /// The returned `Pipe`s are for stdin and stdout.
695 pub fn new_test(
696 event_socket: UdpSocket,
697 general_socket: UdpSocket,
698 ) -> Result<(Self, Pipe, Pipe), Error> {
699 let stdin_pipe = Pipe::new().unwrap();
700 let stdout_pipe = Pipe::new().unwrap();
701
702 let stdin =
703 Stdin::from_handle(stdin_pipe.read).context("Failure acquiring stdin handle")?;
704 let stdout =
705 Stdout::from_handle(stdout_pipe.write).context("Failed acquiring stdout handle")?;
706
707 let poll = Self::new_internal(vec![(event_socket, general_socket)], stdin, stdout)?;
708
709 Ok((poll, stdin_pipe, stdout_pipe))
710 }
711
712 /// Reference to the event socket.
713 #[allow(unused)]
714 pub fn event_socket(&self, iface: usize) -> &UdpSocket {
715 &self.sockets[iface].0
716 }
717
718 /// Reference to the general socket.
719 #[allow(unused)]
720 pub fn general_socket(&self, iface: usize) -> &UdpSocket {
721 &self.sockets[iface].1
722 }
723
724 /// Reference to stdin for reading.
725 #[allow(unused)]
726 pub fn stdin(&self) -> &Stdin {
727 &self.stdin
728 }
729
730 /// Reference to stdout for writing.
731 pub fn stdout(&self) -> &Stdout {
732 &self.stdout
733 }
734
735 /// Poll the event socket, general socket and stdin for available data to read.
736 ///
737 /// This blocks until at least one input has data available.
738 pub fn poll<'a>(&'a mut self) -> Result<PollResult<'a>, Error> {
739 self.handles.clear();
740
741 for (event_socket_event, general_socket_event) in &self.events {
742 self.handles.push(event_socket_event.0);
743 self.handles.push(general_socket_event.0);
744 }
745
746 self.handles.push(
747 // If stdin is a pipe then we use the signalling event, otherwise stdin itself.
748 if let Some(ref thread_state) = self.stdin.thread_state {
749 thread_state.event
750 } else {
751 self.stdin.handle
752 },
753 );
754
755 // If stdin is a pipe and currently no data is pending on it then signal
756 // the reading thread to try reading one byte and blocking for that long.
757 if let Some(ref mut thread_state) = self.stdin.thread_state {
758 let mut guard = thread_state.buffer.lock().unwrap();
759 if !guard.buffer_filled && !guard.fill_buffer {
760 guard.fill_buffer = true;
761 // SAFETY: The thread's event is valid by construction until the thread
762 // is stopped, and can be reset at any time.
763 unsafe {
764 ResetEvent(thread_state.event);
765 }
766 thread_state.buffer_cond.notify_one();
767 }
768 }
769
770 // SAFETY: Wait for the socket/stdin objects to become ready. This requires a valid
771 // array of valid handles and the corresponding length, whether it should wait for all
772 // handles (no), and a timeout (infinity).
773 //
774 // On error u32::MAX is returned, otherwise an index into the array of handles is
775 // returned for the handle that became ready.
776 let res = unsafe {
777 let res = WaitForMultipleObjects(
778 self.handles.len() as _,
779 self.handles[..].as_ptr(),
780 0,
781 u32::MAX,
782 );
783 if res == u32::MAX {
784 bail!(
785 source: io::Error::from_raw_os_error(WSAGetLastError()),
786 "Failed waiting for events"
787 );
788 }
789
790 assert!(
791 (0..self.handles.len()).contains(&(res as usize)),
792 "Unexpected WaitForMultipleObjects() return value {}",
793 res,
794 );
795
796 res as usize
797 };
798
799 self.results_cache.clear();
800 // SAFETY: References have the same memory representation independent of lifetime
801 let ready_sockets = unsafe {
802 mem::transmute::<
803 &mut Vec<(usize, SocketType, &'static UdpSocket)>,
804 &mut Vec<(usize, SocketType, &'a UdpSocket)>,
805 >(&mut self.results_cache)
806 };
807
808 // For the sockets, enumerate the events that woke up the waiting, collect any errors
809 // and reset the event objects.
810 if res < self.handles.len() - 1 {
811 let (socket, event) = if res % 2 == 0 {
812 (&self.sockets[res / 2].0, &self.events[res / 2].0)
813 } else {
814 (&self.sockets[res / 2].1, &self.events[res / 2].1)
815 };
816
817 // SAFETY: Requires a valid socket and event, which is given by construction here.
818 // The passed in memory for the network events will be filled if no error happens,
819 // and the function returns a non-zero value if an error has happened.
820 let networkevents = unsafe {
821 let mut networkevents = mem::MaybeUninit::uninit();
822 if WSAEnumNetworkEvents(
823 socket.as_raw_socket(),
824 event.0,
825 networkevents.as_mut_ptr(),
826 ) != 0
827 {
828 bail!(
829 source: io::Error::from_raw_os_error(WSAGetLastError()),
830 "Failed enumerating network events on {} socket for interface {}",
831 if res % 2 == 0 { "event" } else { "general" },
832 res / 2,
833 );
834 }
835
836 networkevents.assume_init()
837 };
838
839 if networkevents.ierrorcode[FD_READ_BIT] != 0 {
840 bail!(
841 source: io::Error::from_raw_os_error(networkevents.ierrorcode[FD_READ_BIT]),
842 "Error on {} socket for interface {} while waiting for events",
843 if res == 0 { "event" } else { "general" },
844 res / 2,
845 );
846 }
847
848 // FIXME: This seems to happen every now and then although it shouldn't, and in
849 // that case a packet always seems to be queued up on the socket. As the sockets
850 // are non-blocking it also wouldn't be a problem otherwise, so let's just log this
851 // here and ignore it.
852 if networkevents.lnetworkevents & FD_READ == 0 {
853 debug!(
854 "Socket {} woke up but has neither an error nor a FD_READ event",
855 res
856 );
857 }
858 ready_sockets.push((
859 res / 2,
860 if res % 2 == 0 {
861 SocketType::EventSocket
862 } else {
863 SocketType::GeneralSocket
864 },
865 socket,
866 ));
867 }
868
869 Ok(PollResult {
870 ready_sockets: &*ready_sockets,
871 sockets: &self.sockets,
872 stdin: if res == self.handles.len() - 1 {
873 Some(&self.stdin)
874 } else {
875 None
876 },
877 stdout: &self.stdout,
878 })
879 }
880 }
881
882 /// Raw, unbuffered handle to `stdin`.
883 ///
884 /// This implements the `Read` trait for reading.
885 pub struct Stdin {
886 handle: HANDLE,
887 thread_state: Option<Arc<StdinThreadState>>,
888 join_handle: Option<thread::JoinHandle<()>>,
889 }
890
891 struct StdinThreadState {
892 buffer: Mutex<StdinBuffer>,
893 buffer_cond: Condvar,
894 event: HANDLE,
895 handle: HANDLE,
896 }
897
898 unsafe impl Send for StdinThreadState {}
899 unsafe impl Sync for StdinThreadState {}
900
901 struct StdinBuffer {
902 buffer: [u8; 1],
903 error: Option<io::Error>,
904 buffer_filled: bool,
905 fill_buffer: bool,
906 shutdown: bool,
907 }
908
909 impl Drop for Stdin {
910 fn drop(&mut self) {
911 // If stdin was a pipe and a thread was started to check for read-readiness
912 // then stop this thread now and release its resources.
913 if let Some(ref thread_state) = self.thread_state {
914 let mut guard = thread_state.buffer.lock().unwrap();
915 guard.shutdown = true;
916 thread_state.buffer_cond.notify_one();
917 drop(guard);
918 let _ = self.join_handle.take().unwrap().join();
919
920 // SAFETY: The thread is stopped now so the event is not used by anything else
921 // anymore and can safely be closed now.
922 //
923 // The return value is explicitly ignored because nothing can be done on error
924 // anyway.
925 unsafe {
926 let _ = CloseHandle(thread_state.event);
927 }
928 }
929 }
930 }
931
932 impl Stdin {
933 fn acquire() -> Result<Self, Error> {
934 // SAFETY: GetStdHandle returns a borrowed handle, or 0 if none is set or -1 if an
935 // error has happened.
936 let handle = unsafe {
937 let handle = GetStdHandle(STD_INPUT_HANDLE);
938 if handle.is_null() {
939 bail!("No stdin handle set");
940 } else if handle == INVALID_HANDLE_VALUE {
941 bail!(source: io::Error::last_os_error(), "Can't get stdin handle");
942 }
943
944 handle
945 };
946
947 Self::from_handle(handle)
948 }
949
950 fn from_handle(handle: HANDLE) -> Result<Self, Error> {
951 // SAFETY: GetFileType() is safe to call on any valid handle.
952 let type_ = unsafe { GetFileType(handle) };
953
954 if type_ == FILE_TYPE_CHAR {
955 // Set the console to raw mode and flush any pending input.
956 //
957 // SAFETY: Calling this on non-console handles will cause an error but otherwise
958 // have no negative effects. We can safely change the console mode here as nothing
959 // else is accessing the console.
960 unsafe {
961 let _ = SetConsoleMode(handle, 0);
962 let _ = FlushConsoleInputBuffer(handle);
963 }
964
965 Ok(Stdin {
966 handle,
967 thread_state: None,
968 join_handle: None,
969 })
970 } else if type_ == FILE_TYPE_PIPE {
971 // XXX: Because g_spawn() creates the overridden pipes with _pipe(), they're
972 // 1. Full duplex, so WaitForMultipleObjects() always considers them ready as you can write
973 // 2. Not overlapped so only synchronous IO can be used
974 // To work around this we're creating a thread here that just reads synchronously
975 // from stdin to signal ready-ness.
976
977 // SAFETY: Creating an event handle with all-zero parameters is valid and on error
978 // a NULL handle will be returned. Otherwise a valid event handle is returned that
979 // needs to be closed again later, which happens as part of the StdinThreadState
980 // Drop implementation.
981 let event = unsafe {
982 let event = CreateEventA(ptr::null(), 0, 0, ptr::null());
983 if event.is_null() {
984 bail!(
985 source: io::Error::last_os_error(),
986 "Failed creating event handle"
987 );
988 }
989
990 event
991 };
992 let thread_state = Arc::new(StdinThreadState {
993 buffer: Mutex::new(StdinBuffer {
994 buffer: [0],
995 error: None,
996 buffer_filled: false,
997 fill_buffer: true,
998 shutdown: false,
999 }),
1000 buffer_cond: Condvar::new(),
1001 event,
1002 handle,
1003 });
1004
1005 let join_handle = thread::spawn({
1006 let thread_state = thread_state.clone();
1007 move || Self::stdin_readiness_thread(&thread_state)
1008 });
1009
1010 Ok(Stdin {
1011 handle,
1012 thread_state: Some(thread_state),
1013 join_handle: Some(join_handle),
1014 })
1015 } else {
1016 bail!("unhandled stdin handle type {:x}", type_);
1017 }
1018 }
1019
1020 /// Thread function to signal readiness of stdin.
1021 ///
1022 /// This thread tries to read a single byte and buffers it, then signals an event
1023 /// object and waits for reading to finish and a new call to `poll()` to
1024 /// start trying to read a single byte again.
1025 fn stdin_readiness_thread(thread_state: &StdinThreadState) {
1026 loop {
1027 let mut buffer = [0u8];
1028 // SAFETY: Reads one byte from the handle synchronously. Nothing else is currently
1029 // reading from the handle as this thread is waiting below on the condition
1030 // variable as long as a single byte was read already, and only wakes up again if a
1031 // full packet was read from stdin and the other thread is waiting on the event
1032 // handle again.
1033 let res = unsafe {
1034 let mut bytes_read = mem::MaybeUninit::uninit();
1035 let res = ReadFile(
1036 thread_state.handle,
1037 buffer[..].as_mut_ptr(),
1038 buffer.len() as u32,
1039 bytes_read.as_mut_ptr(),
1040 ptr::null_mut(),
1041 );
1042 if res == 0 {
1043 Err(io::Error::last_os_error())
1044 } else {
1045 Ok(bytes_read.assume_init())
1046 }
1047 };
1048
1049 let mut guard = thread_state.buffer.lock().unwrap();
1050 assert!(!guard.buffer_filled);
1051 assert!(guard.fill_buffer);
1052 if guard.shutdown {
1053 break;
1054 }
1055 guard.buffer_filled = true;
1056 guard.fill_buffer = false;
1057 match res {
1058 Err(err) => {
1059 guard.error = Some(err);
1060 }
1061 Ok(bytes_read) => {
1062 guard.buffer[0] = buffer[0];
1063 assert_eq!(bytes_read, 1);
1064 }
1065 }
1066
1067 // SAFETY: Signalling an event is valid from any thread at any time and the event
1068 // handle is valid by construction.
1069 unsafe {
1070 SetEvent(thread_state.event);
1071 }
1072 while !guard.shutdown && !guard.fill_buffer {
1073 guard = thread_state.buffer_cond.wait(guard).unwrap();
1074 }
1075 if guard.shutdown {
1076 break;
1077 }
1078 }
1079 }
1080 }
1081
1082 impl Read for Stdin {
1083 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1084 <&Stdin as Read>::read(&mut &*self, buf)
1085 }
1086 }
1087
1088 impl Read for &Stdin {
1089 fn read(&mut self, mut buf: &mut [u8]) -> io::Result<usize> {
1090 if buf.is_empty() {
1091 return Ok(0);
1092 }
1093
1094 // If a read byte is pending from the readiness signalling thread then
1095 // read that first here before reading any remaining data.
1096 let mut already_read = 0;
1097 if let Some(ref thread_state) = self.thread_state {
1098 let mut guard = thread_state.buffer.lock().unwrap();
1099 assert!(!guard.fill_buffer);
1100 if guard.buffer_filled {
1101 guard.buffer_filled = false;
1102 if let Some(err) = guard.error.take() {
1103 return Err(err);
1104 }
1105 buf[0] = guard.buffer[0];
1106 if buf.len() == 1 {
1107 return Ok(1);
1108 }
1109 buf = &mut buf[1..];
1110 already_read = 1;
1111 }
1112 }
1113
1114 // SAFETY: Reads the given number of bytes into the buffer from the stdin handle.
1115 // The other thread is not currently reading as checked above, and would only be
1116 // triggered to read again by this thread once poll() is called.
1117 unsafe {
1118 let mut lpnumberofbytesread = mem::MaybeUninit::uninit();
1119 let res = ReadFile(
1120 self.handle,
1121 buf.as_mut_ptr(),
1122 cmp::min(buf.len() as u32, u32::MAX) as u32,
1123 lpnumberofbytesread.as_mut_ptr(),
1124 ptr::null_mut(),
1125 );
1126
1127 if res == 0 {
1128 Err(io::Error::last_os_error())
1129 } else {
1130 Ok(lpnumberofbytesread.assume_init() as usize + already_read)
1131 }
1132 }
1133 }
1134 }
1135
1136 /// Raw, unbuffered handle to `stdout`.
1137 ///
1138 /// This implements the `Write` trait for writing.
1139 pub struct Stdout(HANDLE);
1140
1141 impl Stdout {
1142 fn acquire() -> Result<Self, Error> {
1143 // SAFETY: GetStdHandle returns a borrowed handle, or 0 if none is set or -1 if an
1144 // error has happened.
1145 let handle = unsafe {
1146 let handle = GetStdHandle(STD_OUTPUT_HANDLE);
1147 if handle.is_null() {
1148 bail!("No stdout handle set");
1149 } else if handle == INVALID_HANDLE_VALUE {
1150 bail!(
1151 source: io::Error::last_os_error(),
1152 "Can't get stdout handle"
1153 );
1154 }
1155
1156 handle
1157 };
1158
1159 Self::from_handle(handle)
1160 }
1161
1162 fn from_handle(handle: HANDLE) -> Result<Self, Error> {
1163 // SAFETY: GetFileType() is safe to call on any valid handle.
1164 let type_ = unsafe { GetFileType(handle) };
1165
1166 if type_ == FILE_TYPE_CHAR {
1167 // Set the console to raw mode.
1168 //
1169 // SAFETY: Calling this on non-console handles will cause an error but otherwise
1170 // have no negative effects. We can safely change the console mode here as nothing
1171 // else is accessing the console.
1172 unsafe {
1173 let _ = SetConsoleMode(handle, 0);
1174 }
1175 } else if type_ != FILE_TYPE_PIPE {
1176 bail!("Unsupported stdout handle type {:x}", type_);
1177 }
1178
1179 Ok(Stdout(handle))
1180 }
1181 }
1182
1183 impl Write for Stdout {
1184 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1185 <&Stdout as Write>::write(&mut &*self, buf)
1186 }
1187
1188 fn flush(&mut self) -> io::Result<()> {
1189 <&Stdout as Write>::flush(&mut &*self)
1190 }
1191 }
1192
1193 impl Write for &Stdout {
1194 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1195 // SAFETY: Writes the given number of bytes to stdout or at most u32::MAX. On error
1196 // zero is returned, otherwise the number of bytes written is set accordingly and
1197 // returned.
1198 unsafe {
1199 let mut lpnumberofbyteswritten = mem::MaybeUninit::uninit();
1200 let res = WriteFile(
1201 self.0,
1202 buf.as_ptr(),
1203 cmp::min(buf.len() as u32, u32::MAX) as u32,
1204 lpnumberofbyteswritten.as_mut_ptr(),
1205 ptr::null_mut(),
1206 );
1207
1208 if res == 0 {
1209 Err(io::Error::last_os_error())
1210 } else {
1211 Ok(lpnumberofbyteswritten.assume_init() as usize)
1212 }
1213 }
1214 }
1215
1216 fn flush(&mut self) -> io::Result<()> {
1217 Ok(())
1218 }
1219 }
1220
1221 /// Raw, unbuffered handle to `stderr`.
1222 ///
1223 /// This implements the `Write` trait for writing and is implemented as a singleton to allow
1224 /// usage from everywhere at any time for logging purposes.
1225 ///
1226 /// This does not implement any locking so usage from multiple threads at once will likely
1227 /// cause interleaved output.
1228 pub struct Stderr(HANDLE);
1229
1230 impl Stderr {
1231 #[cfg(not(test))]
1232 pub fn acquire() -> Self {
1233 use std::sync::Once;
1234
1235 struct SyncHandle(HANDLE);
1236 // SAFETY: This is a single-threaded application and even otherwise writing from
1237 // multiple threads at once to a pipe is safe and will only cause interleaved output.
1238 unsafe impl Send for SyncHandle {}
1239 unsafe impl Sync for SyncHandle {}
1240
1241 static mut STDERR: SyncHandle = SyncHandle(INVALID_HANDLE_VALUE);
1242 static STDERR_ONCE: Once = Once::new();
1243
1244 STDERR_ONCE.call_once(|| {
1245 // SAFETY: GetStdHandle returns a borrowed handle, or 0 if none is set or -1 if an
1246 // error has happened.
1247 let handle = unsafe {
1248 let handle = GetStdHandle(STD_ERROR_HANDLE);
1249 if handle.is_null() {
1250 return;
1251 } else if handle == INVALID_HANDLE_VALUE {
1252 return;
1253 }
1254
1255 handle
1256 };
1257
1258 // SAFETY: GetFileType() is safe to call on any valid handle.
1259 let type_ = unsafe { GetFileType(handle) };
1260
1261 if type_ == FILE_TYPE_CHAR {
1262 // Set the console to raw mode.
1263 //
1264 // SAFETY: Calling this on non-console handles will cause an error but otherwise
1265 // have no negative effects. We can safely change the console mode here as nothing
1266 // else is accessing the console.
1267 unsafe {
1268 let _ = SetConsoleMode(handle, 0);
1269 }
1270 } else if type_ != FILE_TYPE_PIPE {
1271 return;
1272 }
1273
1274 // SAFETY: Only accessed in this function and multiple mutable accesses are
1275 // prevented by the `Once`.
1276 unsafe {
1277 STDERR.0 = handle;
1278 }
1279 });
1280
1281 // SAFETY: Only accesses immutably here and all mutable accesses are serialized above
1282 // by the `Once`.
1283 Stderr(unsafe { STDERR.0 })
1284 }
1285 }
1286
1287 impl Write for Stderr {
1288 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1289 <&Stderr as Write>::write(&mut &*self, buf)
1290 }
1291
1292 fn flush(&mut self) -> io::Result<()> {
1293 <&Stderr as Write>::flush(&mut &*self)
1294 }
1295 }
1296
1297 impl Write for &Stderr {
1298 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1299 if self.0 == INVALID_HANDLE_VALUE {
1300 return Ok(buf.len());
1301 }
1302
1303 // SAFETY: Writes the given number of bytes to stderr or at most u32::MAX. On error
1304 // zero is returned, otherwise the number of bytes written is set accordingly and
1305 // returned.
1306 unsafe {
1307 let mut lpnumberofbyteswritten = mem::MaybeUninit::uninit();
1308 let res = WriteFile(
1309 self.0,
1310 buf.as_ptr(),
1311 cmp::min(buf.len() as u32, u32::MAX) as u32,
1312 lpnumberofbyteswritten.as_mut_ptr(),
1313 ptr::null_mut(),
1314 );
1315
1316 if res == 0 {
1317 Err(io::Error::last_os_error())
1318 } else {
1319 Ok(lpnumberofbyteswritten.assume_init() as usize)
1320 }
1321 }
1322 }
1323
1324 fn flush(&mut self) -> io::Result<()> {
1325 Ok(())
1326 }
1327 }
1328 }
1329
1330 // `Stderr` is not used when tests are enabled as no logging is performed to stderr.
1331 #[cfg_attr(test, allow(unused_imports))]
1332 pub use self::imp::Stderr;
1333 pub use self::imp::{Poll, Stdin, Stdout};
1334
1335 #[cfg(test)]
1336 mod test {
1337 #[test]
1338 fn test_poll() {
1339 use super::{Poll, SocketType};
1340
1341 use std::io::prelude::*;
1342
1343 let event_socket = std::net::UdpSocket::bind(std::net::SocketAddr::from((
1344 std::net::Ipv4Addr::LOCALHOST,
1345 0,
1346 )))
1347 .unwrap();
1348 let event_port = event_socket.local_addr().unwrap().port();
1349
1350 let general_socket = std::net::UdpSocket::bind(std::net::SocketAddr::from((
1351 std::net::Ipv4Addr::LOCALHOST,
1352 0,
1353 )))
1354 .unwrap();
1355 let general_port = general_socket.local_addr().unwrap().port();
1356
1357 let send_socket = std::net::UdpSocket::bind(std::net::SocketAddr::from((
1358 std::net::Ipv4Addr::LOCALHOST,
1359 0,
1360 )))
1361 .unwrap();
1362
1363 let (mut poll, mut stdin, _stdout) = Poll::new_test(event_socket, general_socket).unwrap();
1364
1365 let mut buf = [0u8; 4];
1366
1367 for _ in 0..10 {
1368 send_socket
1369 .send_to(&[1, 2, 3, 4], (std::net::Ipv4Addr::LOCALHOST, event_port))
1370 .unwrap();
1371 let res = poll.poll().unwrap();
1372 assert_eq!(res.ready_sockets().len(), 1);
1373 assert_eq!(res.ready_sockets()[0].0, 0);
1374 assert_eq!(res.ready_sockets()[0].1, SocketType::EventSocket);
1375 assert_eq!(res.ready_sockets()[0].2.recv(&mut buf).unwrap(), 4);
1376 assert_eq!(buf, [1, 2, 3, 4]);
1377
1378 send_socket
1379 .send_to(&[1, 2, 3, 4], (std::net::Ipv4Addr::LOCALHOST, general_port))
1380 .unwrap();
1381 let res = poll.poll().unwrap();
1382
1383 assert_eq!(res.ready_sockets().len(), 1);
1384 assert_eq!(res.ready_sockets()[0].0, 0);
1385 assert_eq!(res.ready_sockets()[0].1, SocketType::GeneralSocket);
1386 assert_eq!(res.ready_sockets()[0].2.recv(&mut buf).unwrap(), 4);
1387 assert_eq!(buf, [1, 2, 3, 4]);
1388
1389 stdin.write_all(&[1, 2, 3, 4]).unwrap();
1390 let res = poll.poll().unwrap();
1391 assert!(res.ready_sockets().is_empty());
1392 {
1393 let mut stdin = res.stdin();
1394 let stdin = stdin.as_mut().unwrap();
1395 stdin.read_exact(&mut buf).unwrap();
1396 assert_eq!(buf, [1, 2, 3, 4]);
1397 }
1398 }
1399
1400 drop(poll);
1401 }
1402 }