• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 The Chromium OS Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 use super::constants::*;
6 use super::evdev::{grab_evdev, ungrab_evdev};
7 use super::virtio_input_event;
8 use super::InputError;
9 use super::Result;
10 use data_model::DataInit;
11 use std::collections::VecDeque;
12 use std::io::Read;
13 use std::io::Write;
14 use std::mem::size_of;
15 use std::os::unix::io::{AsRawFd, RawFd};
16 use sys_util::{error, warn};
17 
18 #[derive(Copy, Clone, Debug, Default)]
19 #[repr(C)]
20 pub struct input_event {
21     timestamp_fields: [u64; 2],
22     pub type_: u16,
23     pub code: u16,
24     pub value: u32,
25 }
26 // Safe because it only has data and has no implicit padding.
27 unsafe impl DataInit for input_event {}
28 
29 impl input_event {
30     const EVENT_SIZE: usize = size_of::<input_event>();
31 
from_virtio_input_event(other: &virtio_input_event) -> input_event32     fn from_virtio_input_event(other: &virtio_input_event) -> input_event {
33         input_event {
34             timestamp_fields: [0, 0],
35             type_: other.type_.into(),
36             code: other.code.into(),
37             value: other.value.into(),
38         }
39     }
40 }
41 
42 /// Encapsulates a socket or device node into an abstract event source, providing a common
43 /// interface.
44 /// It supports read and write operations to provide and accept events just like an event device
45 /// node would, except that it handles virtio_input_event instead of input_event structures.
46 /// It's necessary to call receive_events() before events are available for read.
47 pub trait EventSource: Read + Write + AsRawFd {
48     /// Perform any necessary initialization before receiving and sending events from/to the source.
init(&mut self) -> Result<()>49     fn init(&mut self) -> Result<()> {
50         Ok(())
51     }
52     /// Perform any necessary cleanup when the device will no longer be used.
finalize(&mut self) -> Result<()>53     fn finalize(&mut self) -> Result<()> {
54         Ok(())
55     }
56 
57     /// Receive events from the source, filters them and stores them in a queue for future
58     /// consumption by reading from this object. Returns the number of new non filtered events
59     /// received. This function may block waiting for events to be available.
receive_events(&mut self) -> Result<usize>60     fn receive_events(&mut self) -> Result<usize>;
61     /// Returns the number of received events that have not been filtered or consumed yet.
available_events_count(&self) -> usize62     fn available_events_count(&self) -> usize;
63 }
64 
65 // Try to read 16 events at a time to match what the linux guest driver does.
66 const READ_BUFFER_SIZE: usize = 16 * size_of::<input_event>();
67 
68 // The read buffer needs to be aligned to the alignment of input_event, which is aligned as u64
69 #[repr(align(8))]
70 pub struct ReadBuffer {
71     buffer: [u8; READ_BUFFER_SIZE],
72 }
73 
74 /// Encapsulates implementation details common to all kinds of event sources.
75 pub struct EventSourceImpl<T> {
76     source: T,
77     queue: VecDeque<virtio_input_event>,
78     read_buffer: ReadBuffer,
79     // The read index accounts for incomplete events read previously.
80     read_idx: usize,
81 }
82 
83 // Reads input events from the source.
84 // Events are originally read as input_event structs and converted to virtio_input_event internally.
85 impl<T: Read> EventSourceImpl<T> {
read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>86     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
87         let mut bytes = 0usize;
88         for evt_slice in buf.chunks_exact_mut(virtio_input_event::EVENT_SIZE) {
89             match self.queue.pop_front() {
90                 None => {
91                     break;
92                 }
93                 Some(evt) => {
94                     evt_slice.copy_from_slice(evt.as_slice());
95                     bytes += evt_slice.len();
96                 }
97             }
98         }
99         Ok(bytes)
100     }
101 }
102 
103 // Writes input events to the source.
104 // Events come as virtio_input_event structs and are converted to input_event internally.
105 impl<T: Write> EventSourceImpl<T> {
write<F: Fn(&virtio_input_event) -> bool>( &mut self, buf: &[u8], event_filter: F, ) -> std::io::Result<usize>106     fn write<F: Fn(&virtio_input_event) -> bool>(
107         &mut self,
108         buf: &[u8],
109         event_filter: F,
110     ) -> std::io::Result<usize> {
111         for evt_slice in buf.chunks_exact(virtio_input_event::EVENT_SIZE) {
112             // Don't use from_slice() here, the buffer is not guaranteed to be properly aligned.
113             let mut vio_evt = virtio_input_event::new(0, 0, 0);
114             vio_evt.as_mut_slice().copy_from_slice(evt_slice);
115             if !event_filter(&vio_evt) {
116                 continue;
117             }
118             let evt = input_event::from_virtio_input_event(&vio_evt);
119             self.source.write_all(evt.as_slice())?;
120         }
121 
122         let len = buf.len() - buf.len() % virtio_input_event::EVENT_SIZE;
123         Ok(len)
124     }
125 
flush(&mut self) -> std::io::Result<()>126     fn flush(&mut self) -> std::io::Result<()> {
127         self.source.flush()
128     }
129 }
130 
131 impl<T: AsRawFd> EventSourceImpl<T> {
as_raw_fd(&self) -> RawFd132     fn as_raw_fd(&self) -> RawFd {
133         self.source.as_raw_fd()
134     }
135 }
136 
137 impl<T> EventSourceImpl<T>
138 where
139     T: Read + Write,
140 {
141     // Receive events from the source and store them in a queue, unless they should be filtered out.
receive_events<F: Fn(&input_event) -> bool>(&mut self, event_filter: F) -> Result<usize>142     fn receive_events<F: Fn(&input_event) -> bool>(&mut self, event_filter: F) -> Result<usize> {
143         let read = self
144             .source
145             .read(&mut self.read_buffer.buffer[self.read_idx..])
146             .map_err(InputError::EventsReadError)?;
147         let buff_size = read + self.read_idx;
148 
149         for evt_slice in self.read_buffer.buffer[..buff_size].chunks_exact(input_event::EVENT_SIZE)
150         {
151             let input_evt = match input_event::from_slice(evt_slice) {
152                 Some(x) => x,
153                 None => {
154                     // This shouldn't happen because all slices (even the last one) are guaranteed
155                     // to have the correct size and be properly aligned.
156                     error!(
157                         "Failed converting a slice of sice {} to input_event",
158                         evt_slice.len()
159                     );
160                     // Skipping the event here effectively means no events will be received, because
161                     // if from_slice fails once it will fail always.
162                     continue;
163                 }
164             };
165             if !event_filter(&input_evt) {
166                 continue;
167             }
168             let vio_evt = virtio_input_event::from_input_event(input_evt);
169             self.queue.push_back(vio_evt);
170         }
171 
172         let remainder = buff_size % input_event::EVENT_SIZE;
173         // If there is an incomplete event at the end of the buffer, it needs to be moved to the
174         // beginning and the next read operation must write right after it.
175         if remainder != 0 {
176             warn!("read incomplete event from source");
177             // The copy should only happen if there is at least one complete event in the buffer,
178             // otherwise source and destination would be the same.
179             if buff_size != remainder {
180                 let (des, src) = self.read_buffer.buffer.split_at_mut(buff_size - remainder);
181                 des[..remainder].copy_from_slice(src);
182             }
183         }
184         self.read_idx = remainder;
185 
186         let received_events = buff_size / input_event::EVENT_SIZE;
187 
188         Ok(received_events)
189     }
190 
available_events(&self) -> usize191     fn available_events(&self) -> usize {
192         self.queue.len()
193     }
194 
new(source: T) -> EventSourceImpl<T>195     fn new(source: T) -> EventSourceImpl<T> {
196         EventSourceImpl {
197             source,
198             queue: VecDeque::new(),
199             read_buffer: ReadBuffer {
200                 buffer: [0u8; READ_BUFFER_SIZE],
201             },
202             read_idx: 0,
203         }
204     }
205 }
206 
207 /// Encapsulates a (unix) socket as an event source.
208 pub struct SocketEventSource<T> {
209     evt_source_impl: EventSourceImpl<T>,
210 }
211 
212 impl<T> SocketEventSource<T>
213 where
214     T: Read + Write + AsRawFd,
215 {
new(source: T) -> SocketEventSource<T>216     pub fn new(source: T) -> SocketEventSource<T> {
217         SocketEventSource {
218             evt_source_impl: EventSourceImpl::new(source),
219         }
220     }
221 }
222 
223 impl<T: Read> Read for SocketEventSource<T> {
read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>224     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
225         self.evt_source_impl.read(buf)
226     }
227 }
228 
229 impl<T> Write for SocketEventSource<T>
230 where
231     T: Read + Write + AsRawFd,
232 {
write(&mut self, buf: &[u8]) -> std::io::Result<usize>233     fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
234         self.evt_source_impl.write(buf, |_evt| true)
235     }
236 
flush(&mut self) -> std::io::Result<()>237     fn flush(&mut self) -> std::io::Result<()> {
238         self.evt_source_impl.flush()
239     }
240 }
241 
242 impl<T: AsRawFd> AsRawFd for SocketEventSource<T> {
as_raw_fd(&self) -> RawFd243     fn as_raw_fd(&self) -> RawFd {
244         self.evt_source_impl.as_raw_fd()
245     }
246 }
247 
248 impl<T> EventSource for SocketEventSource<T>
249 where
250     T: Read + Write + AsRawFd,
251 {
init(&mut self) -> Result<()>252     fn init(&mut self) -> Result<()> {
253         Ok(())
254     }
255 
finalize(&mut self) -> Result<()>256     fn finalize(&mut self) -> Result<()> {
257         ungrab_evdev(self)
258     }
259 
receive_events(&mut self) -> Result<usize>260     fn receive_events(&mut self) -> Result<usize> {
261         self.evt_source_impl.receive_events(|_evt| true)
262     }
263 
available_events_count(&self) -> usize264     fn available_events_count(&self) -> usize {
265         self.evt_source_impl.available_events()
266     }
267 }
268 
269 /// Encapsulates an event device node as an event source
270 pub struct EvdevEventSource<T> {
271     evt_source_impl: EventSourceImpl<T>,
272 }
273 
274 impl<T> EvdevEventSource<T>
275 where
276     T: Read + Write + AsRawFd,
277 {
new(source: T) -> EvdevEventSource<T>278     pub fn new(source: T) -> EvdevEventSource<T> {
279         EvdevEventSource {
280             evt_source_impl: EventSourceImpl::new(source),
281         }
282     }
283 }
284 
285 impl<T: Read> Read for EvdevEventSource<T> {
read(&mut self, buf: &mut [u8]) -> std::io::Result<usize>286     fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
287         self.evt_source_impl.read(buf)
288     }
289 }
290 
291 impl<T> Write for EvdevEventSource<T>
292 where
293     T: Read + Write + AsRawFd,
294 {
write(&mut self, buf: &[u8]) -> std::io::Result<usize>295     fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
296         self.evt_source_impl.write(buf, |evt| {
297             // Miscellaneous events produced by the device are sent back to it by the kernel input
298             // subsystem, but because these events are handled by the host kernel as well as the
299             // guest the device would get them twice. Which would prompt the device to send the
300             // event to the guest again entering an infinite loop.
301             evt.type_ != EV_MSC
302         })
303     }
304 
flush(&mut self) -> std::io::Result<()>305     fn flush(&mut self) -> std::io::Result<()> {
306         self.evt_source_impl.flush()
307     }
308 }
309 
310 impl<T: AsRawFd> AsRawFd for EvdevEventSource<T> {
as_raw_fd(&self) -> RawFd311     fn as_raw_fd(&self) -> RawFd {
312         self.evt_source_impl.as_raw_fd()
313     }
314 }
315 
316 impl<T> EventSource for EvdevEventSource<T>
317 where
318     T: Read + Write + AsRawFd,
319 {
init(&mut self) -> Result<()>320     fn init(&mut self) -> Result<()> {
321         grab_evdev(self)
322     }
323 
finalize(&mut self) -> Result<()>324     fn finalize(&mut self) -> Result<()> {
325         ungrab_evdev(self)
326     }
327 
receive_events(&mut self) -> Result<usize>328     fn receive_events(&mut self) -> Result<usize> {
329         self.evt_source_impl.receive_events(|_evt| true)
330     }
331 
available_events_count(&self) -> usize332     fn available_events_count(&self) -> usize {
333         self.evt_source_impl.available_events()
334     }
335 }
336 
337 #[cfg(test)]
338 mod tests {
339     use crate::virtio::input::event_source::input_event;
340     use crate::virtio::input::event_source::EventSourceImpl;
341     use crate::virtio::input::virtio_input_event;
342     use data_model::{DataInit, Le16, Le32};
343     use std::cmp::min;
344     use std::io::Read;
345     use std::io::Write;
346     use std::mem::size_of;
347 
348     struct SourceMock {
349         events: Vec<u8>,
350     }
351 
352     impl SourceMock {
new(evts: &Vec<input_event>) -> SourceMock353         fn new(evts: &Vec<input_event>) -> SourceMock {
354             let mut events: Vec<u8> = vec![];
355             for evt in evts {
356                 for byte in evt.as_slice() {
357                     events.push(byte.clone());
358                 }
359             }
360             SourceMock { events }
361         }
362     }
363 
364     impl Read for SourceMock {
read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error>365         fn read(&mut self, buf: &mut [u8]) -> std::result::Result<usize, std::io::Error> {
366             let copy_size = min(buf.len(), self.events.len());
367             buf[..copy_size].copy_from_slice(&self.events[..copy_size]);
368             Ok(copy_size)
369         }
370     }
371     impl Write for SourceMock {
write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error>372         fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> {
373             Ok(buf.len())
374         }
375 
flush(&mut self) -> std::result::Result<(), std::io::Error>376         fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
377             Ok(())
378         }
379     }
380 
381     #[test]
empty_new()382     fn empty_new() {
383         let mut source = EventSourceImpl::new(SourceMock::new(&vec![]));
384         assert_eq!(
385             source.available_events(),
386             0,
387             "zero events should be available"
388         );
389         let mut buffer = [0u8, 80];
390         assert_eq!(
391             source.read(&mut buffer).unwrap(),
392             0,
393             "zero events should be read"
394         );
395     }
396 
397     #[test]
empty_receive()398     fn empty_receive() {
399         let mut source = EventSourceImpl::new(SourceMock::new(&vec![]));
400         assert_eq!(
401             source.receive_events(|_| true).unwrap(),
402             0,
403             "zero events should be received"
404         );
405         let mut buffer = [0u8, 80];
406         assert_eq!(
407             source.read(&mut buffer).unwrap(),
408             0,
409             "zero events should be read"
410         );
411     }
412 
instantiate_input_events(count: usize) -> Vec<input_event>413     fn instantiate_input_events(count: usize) -> Vec<input_event> {
414         let mut ret: Vec<input_event> = Vec::with_capacity(count);
415         for idx in 0..count {
416             ret.push(input_event {
417                 timestamp_fields: [0, 0],
418                 type_: 3 * (idx as u16) + 1,
419                 code: 3 * (idx as u16) + 2,
420                 value: 3 * (idx as u32) + 3,
421             });
422         }
423         ret
424     }
425 
assert_events_match(e1: &virtio_input_event, e2: &input_event)426     fn assert_events_match(e1: &virtio_input_event, e2: &input_event) {
427         assert_eq!(e1.type_, Le16::from(e2.type_), "type should match");
428         assert_eq!(e1.code, Le16::from(e2.code), "code should match");
429         assert_eq!(e1.value, Le32::from(e2.value), "value should match");
430     }
431 
432     #[test]
partial_read()433     fn partial_read() {
434         let evts = instantiate_input_events(4usize);
435         let mut source = EventSourceImpl::new(SourceMock::new(&evts));
436         assert_eq!(
437             source.receive_events(|_| true).unwrap(),
438             evts.len(),
439             "should receive all events"
440         );
441         let mut evt = virtio_input_event {
442             type_: Le16::from(0),
443             code: Le16::from(0),
444             value: Le32::from(0),
445         };
446         assert_eq!(
447             source.read(evt.as_mut_slice()).unwrap(),
448             virtio_input_event::EVENT_SIZE,
449             "should read a single event"
450         );
451         assert_events_match(&evt, &evts[0]);
452     }
453 
454     #[test]
exact_read()455     fn exact_read() {
456         const EVENT_COUNT: usize = 4;
457         let evts = instantiate_input_events(EVENT_COUNT);
458         let mut source = EventSourceImpl::new(SourceMock::new(&evts));
459         assert_eq!(
460             source.receive_events(|_| true).unwrap(),
461             evts.len(),
462             "should receive all events"
463         );
464         let mut vio_evts = [0u8; EVENT_COUNT * size_of::<virtio_input_event>()];
465         assert_eq!(
466             source.read(&mut vio_evts).unwrap(),
467             EVENT_COUNT * virtio_input_event::EVENT_SIZE,
468             "should read all events"
469         );
470 
471         let mut chunks = vio_evts.chunks_exact(virtio_input_event::EVENT_SIZE);
472         for idx in 0..EVENT_COUNT {
473             let evt = virtio_input_event::from_slice(chunks.next().unwrap()).unwrap();
474             assert_events_match(&evt, &evts[idx]);
475         }
476     }
477 
478     #[test]
over_read()479     fn over_read() {
480         const EVENT_COUNT: usize = 4;
481         let evts = instantiate_input_events(EVENT_COUNT);
482         let mut source = EventSourceImpl::new(SourceMock::new(&evts));
483         assert_eq!(
484             source.receive_events(|_| true).unwrap(),
485             evts.len(),
486             "should receive all events"
487         );
488         let mut vio_evts = [0u8; 2 * EVENT_COUNT * size_of::<virtio_input_event>()];
489         assert_eq!(
490             source.read(&mut vio_evts).unwrap(),
491             EVENT_COUNT * virtio_input_event::EVENT_SIZE,
492             "should only read available events"
493         );
494 
495         let mut chunks = vio_evts.chunks_exact(virtio_input_event::EVENT_SIZE);
496         for idx in 0..EVENT_COUNT {
497             let evt = virtio_input_event::from_slice(chunks.next().unwrap()).unwrap();
498             assert_events_match(&evt, &evts[idx]);
499         }
500     }
501 
502     #[test]
incomplete_read()503     fn incomplete_read() {
504         const EVENT_COUNT: usize = 4;
505         let evts = instantiate_input_events(EVENT_COUNT);
506         let mut source = EventSourceImpl::new(SourceMock::new(&evts));
507         assert_eq!(
508             source.receive_events(|_| true).unwrap(),
509             evts.len(),
510             "should receive all events"
511         );
512         let mut vio_evts = [0u8; 3];
513         assert_eq!(
514             source.read(&mut vio_evts).unwrap(),
515             0,
516             "shouldn't read incomplete events"
517         );
518     }
519 }
520