Debian Codegraph @

src/sources/ping/pipe.rs

raw symbols SCIP
1 //! Pipe based implementation of the ping event source, using the pipe or pipe2
2 //! syscall. Sending a ping involves writing to one end of a pipe, and the other
3 //! end becoming readable is what wakes up the event loop.
4
5 use std::{os::unix::io::RawFd, sync::Arc};
6
7 use nix::fcntl::OFlag;
8 use nix::unistd::{close, read, write};
9
10 use super::{CloseOnDrop, PingError};
11 use crate::{
12 generic::Generic, EventSource, Interest, Mode, Poll, PostAction, Readiness, Token, TokenFactory,
13 };
14
15 #[cfg(target_os = "macos")]
16 #[inline]
17 fn make_ends() -> std::io::Result<(RawFd, RawFd)> {
18 // macOS does not have pipe2, but we can emulate the behavior of pipe2 by
19 // setting the flags after calling pipe.
20 use nix::{
21 fcntl::{fcntl, FcntlArg},
22 unistd::pipe,
23 };
24
25 let (read, write) = pipe()?;
26
27 let read_flags = OFlag::from_bits_truncate(fcntl(read, FcntlArg::F_GETFD)?)
28 | OFlag::O_CLOEXEC
29 | OFlag::O_NONBLOCK;
30 let write_flags = OFlag::from_bits_truncate(fcntl(write, FcntlArg::F_GETFD)?)
31 | OFlag::O_CLOEXEC
32 | OFlag::O_NONBLOCK;
33
34 fcntl(read, FcntlArg::F_SETFL(read_flags))?;
35 fcntl(write, FcntlArg::F_SETFL(write_flags))?;
36
37 Ok((read, write))
38 }
39
40 #[cfg(not(target_os = "macos"))]
41 #[inline]
42 fn make_ends() -> std::io::Result<(RawFd, RawFd)> {
43 Ok(nix::unistd::pipe2(OFlag::O_CLOEXEC | OFlag::O_NONBLOCK)?)
44 }
45
46 #[inline]
47 pub fn make_ping() -> std::io::Result<(Ping, PingSource)> {
48 let (read, write) = make_ends()?;
49
50 let source = PingSource {
51 pipe: Generic::new(read, Interest::READ, Mode::Level),
52 };
53 let ping = Ping {
54 pipe: Arc::new(CloseOnDrop(write)),
55 };
56 Ok((ping, source))
57 }
58
59 // Helper functions for the event source IO.
60
61 #[inline]
62 fn send_ping(fd: RawFd) -> std::io::Result<()> {
63 write(fd, &[0u8])?;
64 Ok(())
65 }
66
67 // The event source is simply a generic source with the FD of the read end of
68 // the pipe.
69 #[derive(Debug)]
70 pub struct PingSource {
71 pipe: Generic<RawFd>,
72 }
73
74 impl EventSource for PingSource {
75 type Event = ();
76 type Metadata = ();
77 type Ret = ();
78 type Error = PingError;
79
80 fn process_events<C>(
81 &mut self,
82 readiness: Readiness,
83 token: Token,
84 mut callback: C,
85 ) -> Result<PostAction, Self::Error>
86 where
87 C: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
88 {
89 self.pipe
90 .process_events(readiness, token, |_, &mut fd| {
91 let mut buf = [0u8; 32];
92 let mut read_something = false;
93 let mut action = PostAction::Continue;
94
95 loop {
96 match read(fd, &mut buf) {
97 Ok(0) => {
98 // The other end of the pipe was closed, mark ourselves
99 // for removal.
100 action = PostAction::Remove;
101 break;
102 }
103
104 // Got one or more pings.
105 Ok(_) => read_something = true,
106
107 // Nothing more to read.
108 Err(nix::errno::Errno::EAGAIN) => break,
109
110 // Propagate error.
111 Err(e) => return Err(e.into()),
112 }
113 }
114
115 if read_something {
116 callback((), &mut ());
117 }
118 Ok(action)
119 })
120 .map_err(|e| PingError(e.into()))
121 }
122
123 fn register(&mut self, poll: &mut Poll, token_factory: &mut TokenFactory) -> crate::Result<()> {
124 self.pipe.register(poll, token_factory)
125 }
126
127 fn reregister(
128 &mut self,
129 poll: &mut Poll,
130 token_factory: &mut TokenFactory,
131 ) -> crate::Result<()> {
132 self.pipe.reregister(poll, token_factory)
133 }
134
135 fn unregister(&mut self, poll: &mut Poll) -> crate::Result<()> {
136 self.pipe.unregister(poll)
137 }
138 }
139
140 impl Drop for PingSource {
141 fn drop(&mut self) {
142 if let Err(e) = close(self.pipe.file) {
143 log::warn!("[calloop] Failed to close read ping: {:?}", e);
144 }
145 }
146 }
147
148 // The sending end of the ping writes zeroes to the write end of the pipe.
149 #[derive(Clone, Debug)]
150 pub struct Ping {
151 pipe: Arc<CloseOnDrop>,
152 }
153
154 // The sending end of the ping writes zeroes to the write end of the pipe.
155 impl Ping {
156 /// Send a ping to the `PingSource`
157 pub fn ping(&self) {
158 if let Err(e) = send_ping(self.pipe.0) {
159 log::warn!("[calloop] Failed to write a ping: {:?}", e);
160 }
161 }
162 }