1 use std::{
2     ffi::CString,
3     os::unix::{
4         io::{FromRawFd, IntoRawFd},
5         net::UnixStream,
6     },
7     sync::Arc,
8 };
9 
10 use crate::{
11     core_interfaces::{WL_CALLBACK_INTERFACE, WL_DISPLAY_INTERFACE, WL_REGISTRY_INTERFACE},
12     protocol::{
13         check_for_signature, same_interface, same_interface_or_anonymous, AllowNull, Argument,
14         ArgumentType, Interface, Message, ObjectInfo, ProtocolError, ANONYMOUS_INTERFACE,
15         INLINE_ARGS,
16     },
17     types::server::{DisconnectReason, InvalidId},
18 };
19 
20 use smallvec::SmallVec;
21 
22 use crate::rs::{
23     map::{Object, ObjectMap},
24     socket::{BufferedSocket, Socket},
25     wire::MessageParseError,
26 };
27 
28 use super::{
29     registry::Registry, ClientData, ClientId, Credentials, Data, GlobalHandler, GlobalId, Handle,
30     ObjectData, ObjectId, UninitObjectData,
31 };
32 
33 type ArgSmallVec = SmallVec<[Argument<ObjectId>; INLINE_ARGS]>;
34 
35 #[repr(u32)]
36 #[allow(dead_code)]
37 pub(crate) enum DisplayError {
38     InvalidObject = 0,
39     InvalidMethod = 1,
40     NoMemory = 2,
41     Implementation = 3,
42 }
43 
44 #[derive(Debug)]
45 pub(crate) struct Client<D> {
46     socket: BufferedSocket,
47     pub(crate) map: ObjectMap<Data<D>>,
48     debug: bool,
49     last_serial: u32,
50     pub(crate) id: ClientId,
51     pub(crate) killed: bool,
52     pub(crate) data: Arc<dyn ClientData<D>>,
53 }
54 
55 impl<D> Client<D> {
next_serial(&mut self) -> u3256     fn next_serial(&mut self) -> u32 {
57         self.last_serial = self.last_serial.wrapping_add(1);
58         self.last_serial
59     }
60 }
61 
62 impl<D> Client<D> {
new( stream: UnixStream, id: ClientId, debug: bool, data: Arc<dyn ClientData<D>>, ) -> Self63     pub(crate) fn new(
64         stream: UnixStream,
65         id: ClientId,
66         debug: bool,
67         data: Arc<dyn ClientData<D>>,
68     ) -> Self {
69         let socket = BufferedSocket::new(unsafe { Socket::from_raw_fd(stream.into_raw_fd()) });
70         let mut map = ObjectMap::new();
71         map.insert_at(
72             1,
73             Object {
74                 interface: &WL_DISPLAY_INTERFACE,
75                 version: 1,
76                 data: Data { user_data: Arc::new(DumbObjectData), serial: 0 },
77             },
78         )
79         .unwrap();
80 
81         data.initialized(id.clone());
82 
83         Client { socket, map, debug, id, killed: false, last_serial: 0, data }
84     }
85 
create_object( &mut self, interface: &'static Interface, version: u32, user_data: Arc<dyn ObjectData<D>>, ) -> ObjectId86     pub(crate) fn create_object(
87         &mut self,
88         interface: &'static Interface,
89         version: u32,
90         user_data: Arc<dyn ObjectData<D>>,
91     ) -> ObjectId {
92         let serial = self.next_serial();
93         let id = self.map.server_insert_new(Object {
94             interface,
95             version,
96             data: Data { serial, user_data },
97         });
98         ObjectId { id, serial, client_id: self.id.clone(), interface }
99     }
100 
object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId>101     pub(crate) fn object_info(&self, id: ObjectId) -> Result<ObjectInfo, InvalidId> {
102         let object = self.get_object(id.clone())?;
103         Ok(ObjectInfo { id: id.id, interface: object.interface, version: object.version })
104     }
105 
106     pub(crate) fn send_event(
107         &mut self,
108         Message { sender_id: object_id, opcode, args }: Message<ObjectId>,
109         pending_destructors: Option<&mut Vec<super::handle::PendingDestructor<D>>>,
110     ) -> Result<(), InvalidId> {
111         if self.killed {
112             return Ok(());
113         }
114         let object = self.get_object(object_id.clone())?;
115 
116         let message_desc = match object.interface.events.get(opcode as usize) {
117             Some(msg) => msg,
118             None => {
119                 panic!(
120                     "Unknown opcode {} for object {}@{}.",
121                     opcode, object.interface.name, object_id.id
122                 );
123             }
124         };
125 
126         if !check_for_signature(message_desc.signature, &args) {
127             panic!(
128                 "Unexpected signature for event {}@{}.{}: expected {:?}, got {:?}.",
129                 object.interface.name,
130                 object_id.id,
131                 message_desc.name,
132                 message_desc.signature,
133                 args
134             );
135         }
136 
137         if self.debug {
138             crate::rs::debug::print_send_message(
139                 object.interface.name,
140                 object_id.id,
141                 message_desc.name,
142                 &args,
143             );
144         }
145 
146         let mut msg_args = SmallVec::with_capacity(args.len());
147         let mut arg_interfaces = message_desc.arg_interfaces.iter();
148         for (i, arg) in args.into_iter().enumerate() {
149             msg_args.push(match arg {
150                 Argument::Array(a) => Argument::Array(a),
151                 Argument::Int(i) => Argument::Int(i),
152                 Argument::Uint(u) => Argument::Uint(u),
153                 Argument::Str(s) => Argument::Str(s),
154                 Argument::Fixed(f) => Argument::Fixed(f),
155                 Argument::Fd(f) => Argument::Fd(f),
156                 Argument::NewId(o) => {
157                     if o.id != 0 {
158                         if o.client_id != self.id {
159                             panic!("Attempting to send an event with objects from wrong client.")
160                         }
161                         let object = self.get_object(o.clone())?;
162                         let child_interface = match message_desc.child_interface {
163                             Some(iface) => iface,
164                             None => panic!("Trying to send event {}@{}.{} which creates an object without specifying its interface, this is unsupported.", object_id.interface.name, object_id.id, message_desc.name),
165                         };
166                         if !same_interface(child_interface, object.interface) {
167                             panic!("Event {}@{}.{} expects a newid argument of interface {} but {} was provided instead.", object.interface.name, object_id.id, message_desc.name, child_interface.name, object.interface.name);
168                         }
169                     } else if !matches!(message_desc.signature[i], ArgumentType::NewId(AllowNull::Yes)) {
170                         panic!("Request {}@{}.{} expects an non-null newid argument.", object.interface.name, object_id.id, message_desc.name);
171                     }
172                     Argument::Object(o.id)
173                 },
174                 Argument::Object(o) => {
175                     if o.id != 0 {
176                         if o.client_id != self.id {
177                             panic!("Attempting to send an event with objects from wrong client.")
178                         }
179                         let object = self.get_object(o.clone())?;
180                         let next_interface = arg_interfaces.next().unwrap();
181                         if !same_interface_or_anonymous(next_interface, object.interface) {
182                             panic!("Event {}@{}.{} expects an object argument of interface {} but {} was provided instead.", object.interface.name, object_id.id, message_desc.name, next_interface.name, object.interface.name);
183                         }
184                     } else if !matches!(message_desc.signature[i], ArgumentType::Object(AllowNull::Yes)) {
185                             panic!("Request {}@{}.{} expects an non-null object argument.", object.interface.name, object_id.id, message_desc.name);
186                     }
187                     Argument::Object(o.id)
188                 }
189             });
190         }
191 
192         let msg = Message { sender_id: object_id.id, opcode, args: msg_args };
193 
194         if self.socket.write_message(&msg).is_err() {
195             self.kill(DisconnectReason::ConnectionClosed);
196         }
197 
198         // Handle destruction if relevant
199         if message_desc.is_destructor {
200             self.map.remove(object_id.id);
201             if let Some(vec) = pending_destructors {
202                 vec.push((object.data.user_data.clone(), self.id.clone(), object_id.clone()));
203             }
204             self.send_delete_id(object_id);
205         }
206 
207         Ok(())
208     }
209 
send_delete_id(&mut self, object_id: ObjectId)210     pub(crate) fn send_delete_id(&mut self, object_id: ObjectId) {
211         let msg = message!(1, 1, [Argument::Uint(object_id.id)]);
212         if self.socket.write_message(&msg).is_err() {
213             self.kill(DisconnectReason::ConnectionClosed);
214         }
215         self.map.remove(object_id.id);
216     }
217 
get_object_data( &self, id: ObjectId, ) -> Result<Arc<dyn ObjectData<D>>, InvalidId>218     pub(crate) fn get_object_data(
219         &self,
220         id: ObjectId,
221     ) -> Result<Arc<dyn ObjectData<D>>, InvalidId> {
222         let object = self.get_object(id)?;
223         Ok(object.data.user_data)
224     }
225 
set_object_data( &mut self, id: ObjectId, data: Arc<dyn ObjectData<D>>, ) -> Result<(), InvalidId>226     pub(crate) fn set_object_data(
227         &mut self,
228         id: ObjectId,
229         data: Arc<dyn ObjectData<D>>,
230     ) -> Result<(), InvalidId> {
231         self.map
232             .with(id.id, |objdata| {
233                 if objdata.data.serial != id.serial {
234                     Err(InvalidId)
235                 } else {
236                     objdata.data.user_data = data;
237                     Ok(())
238                 }
239             })
240             .unwrap_or(Err(InvalidId))
241     }
242 
post_display_error(&mut self, code: DisplayError, message: CString)243     pub(crate) fn post_display_error(&mut self, code: DisplayError, message: CString) {
244         self.post_error(
245             ObjectId {
246                 id: 1,
247                 interface: &WL_DISPLAY_INTERFACE,
248                 client_id: self.id.clone(),
249                 serial: 0,
250             },
251             code as u32,
252             message,
253         )
254     }
255 
post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString)256     pub(crate) fn post_error(&mut self, object_id: ObjectId, error_code: u32, message: CString) {
257         let converted_message = message.to_string_lossy().into();
258         // errors are ignored, as the client will be killed anyway
259         let _ = self.send_event(
260             message!(
261                 ObjectId {
262                     id: 1,
263                     interface: &WL_DISPLAY_INTERFACE,
264                     client_id: self.id.clone(),
265                     serial: 0
266                 },
267                 0, // wl_display.error
268                 [
269                     Argument::Object(object_id.clone()),
270                     Argument::Uint(error_code),
271                     Argument::Str(Box::new(message)),
272                 ],
273             ),
274             // wl_display.error is not a destructor, this argument will not be used
275             None,
276         );
277         let _ = self.flush();
278         self.kill(DisconnectReason::ProtocolError(ProtocolError {
279             code: error_code,
280             object_id: object_id.id,
281             object_interface: object_id.interface.name.into(),
282             message: converted_message,
283         }));
284     }
285 
286     #[cfg(target_os = "linux")]
get_credentials(&self) -> Credentials287     pub(crate) fn get_credentials(&self) -> Credentials {
288         use std::os::unix::io::AsRawFd;
289         let creds = nix::sys::socket::getsockopt(
290             self.socket.as_raw_fd(),
291             nix::sys::socket::sockopt::PeerCredentials,
292         )
293         .expect("getsockopt failed!?");
294         Credentials { pid: creds.pid(), uid: creds.uid(), gid: creds.gid() }
295     }
296 
297     #[cfg(not(target_os = "linux"))]
298     // for now this only works on linux
get_credentials(&self) -> Credentials299     pub(crate) fn get_credentials(&self) -> Credentials {
300         Credentials { pid: 0, uid: 0, gid: 0 }
301     }
302 
kill(&mut self, reason: DisconnectReason)303     pub(crate) fn kill(&mut self, reason: DisconnectReason) {
304         self.killed = true;
305         self.data.disconnected(self.id.clone(), reason);
306     }
307 
flush(&mut self) -> std::io::Result<()>308     pub(crate) fn flush(&mut self) -> std::io::Result<()> {
309         self.socket.flush()
310     }
311 
all_objects(&self) -> impl Iterator<Item = ObjectId> + '_312     pub(crate) fn all_objects(&self) -> impl Iterator<Item = ObjectId> + '_ {
313         let client_id = self.id.clone();
314         self.map.all_objects().map(move |(id, obj)| ObjectId {
315             id,
316             client_id: client_id.clone(),
317             interface: obj.interface,
318             serial: obj.data.serial,
319         })
320     }
321 
next_request(&mut self) -> std::io::Result<(Message<u32>, Object<Data<D>>)>322     pub(crate) fn next_request(&mut self) -> std::io::Result<(Message<u32>, Object<Data<D>>)> {
323         if self.killed {
324             return Err(nix::errno::Errno::EPIPE.into());
325         }
326         loop {
327             let map = &self.map;
328             let msg = match self.socket.read_one_message(|id, opcode| {
329                 map.find(id)
330                     .and_then(|o| o.interface.requests.get(opcode as usize))
331                     .map(|desc| desc.signature)
332             }) {
333                 Ok(msg) => msg,
334                 Err(MessageParseError::MissingData) | Err(MessageParseError::MissingFD) => {
335                     // need to read more data
336                     if let Err(e) = self.socket.fill_incoming_buffers() {
337                         if e.kind() != std::io::ErrorKind::WouldBlock {
338                             self.kill(DisconnectReason::ConnectionClosed);
339                         }
340                         return Err(e);
341                     }
342                     continue;
343                 }
344                 Err(MessageParseError::Malformed) => {
345                     self.kill(DisconnectReason::ConnectionClosed);
346                     return Err(nix::errno::Errno::EPROTO.into());
347                 }
348             };
349 
350             let obj = self.map.find(msg.sender_id).unwrap();
351             return Ok((msg, obj));
352         }
353     }
354 
get_object(&self, id: ObjectId) -> Result<Object<Data<D>>, InvalidId>355     fn get_object(&self, id: ObjectId) -> Result<Object<Data<D>>, InvalidId> {
356         let object = self.map.find(id.id).ok_or(InvalidId)?;
357         if object.data.serial != id.serial {
358             return Err(InvalidId);
359         }
360         Ok(object)
361     }
362 
object_for_protocol_id(&self, pid: u32) -> Result<ObjectId, InvalidId>363     pub(crate) fn object_for_protocol_id(&self, pid: u32) -> Result<ObjectId, InvalidId> {
364         let object = self.map.find(pid).ok_or(InvalidId)?;
365         Ok(ObjectId {
366             id: pid,
367             client_id: self.id.clone(),
368             serial: object.data.serial,
369             interface: object.interface,
370         })
371     }
372 
destroy_all_objects(&mut self, data: &mut D)373     fn destroy_all_objects(&mut self, data: &mut D) {
374         for (id, obj) in self.map.all_objects() {
375             obj.data.user_data.destroyed(
376                 data,
377                 self.id.clone(),
378                 ObjectId {
379                     id,
380                     serial: obj.data.serial,
381                     client_id: self.id.clone(),
382                     interface: obj.interface,
383                 },
384             );
385         }
386     }
387 
handle_display_request( &mut self, message: Message<u32>, registry: &mut Registry<D>, )388     pub(crate) fn handle_display_request(
389         &mut self,
390         message: Message<u32>,
391         registry: &mut Registry<D>,
392     ) {
393         match message.opcode {
394             // wl_display.sync(new id wl_callback)
395             0 => {
396                 if let [Argument::NewId(new_id)] = message.args[..] {
397                     let serial = self.next_serial();
398                     let callback_obj = Object {
399                         interface: &WL_CALLBACK_INTERFACE,
400                         version: 1,
401                         data: Data { user_data: Arc::new(DumbObjectData), serial },
402                     };
403                     if let Err(()) = self.map.insert_at(new_id, callback_obj) {
404                         self.post_display_error(
405                             DisplayError::InvalidObject,
406                             CString::new(format!("Invalid new_id: {}.", new_id)).unwrap(),
407                         );
408                         return;
409                     }
410                     let cb_id = ObjectId {
411                         id: new_id,
412                         client_id: self.id.clone(),
413                         serial,
414                         interface: &WL_CALLBACK_INTERFACE,
415                     };
416                     // send wl_callback.done(0) this callback does not have any meaningful destructor to run, we can ignore it
417                     self.send_event(message!(cb_id, 0, [Argument::Uint(0)]), None).unwrap();
418                 } else {
419                     unreachable!()
420                 }
421             }
422             // wl_display.get_registry(new id wl_registry)
423             1 => {
424                 if let [Argument::NewId(new_id)] = message.args[..] {
425                     let serial = self.next_serial();
426                     let registry_obj = Object {
427                         interface: &WL_REGISTRY_INTERFACE,
428                         version: 1,
429                         data: Data { user_data: Arc::new(DumbObjectData), serial },
430                     };
431                     let registry_id = ObjectId {
432                         id: new_id,
433                         serial,
434                         client_id: self.id.clone(),
435                         interface: &WL_REGISTRY_INTERFACE,
436                     };
437                     if let Err(()) = self.map.insert_at(new_id, registry_obj) {
438                         self.post_display_error(
439                             DisplayError::InvalidObject,
440                             CString::new(format!("Invalid new_id: {}.", new_id)).unwrap(),
441                         );
442                         return;
443                     }
444                     let _ = registry.new_registry(registry_id, self);
445                 } else {
446                     unreachable!()
447                 }
448             }
449             _ => {
450                 // unkown opcode, kill the client
451                 self.post_display_error(
452                     DisplayError::InvalidMethod,
453                     CString::new(format!(
454                         "Unknown opcode {} for interface wl_display.",
455                         message.opcode
456                     ))
457                     .unwrap(),
458                 );
459             }
460         }
461     }
462 
463     #[allow(clippy::type_complexity)]
handle_registry_request( &mut self, message: Message<u32>, registry: &mut Registry<D>, ) -> Option<(ClientId, GlobalId, ObjectId, Arc<dyn GlobalHandler<D>>)>464     pub(crate) fn handle_registry_request(
465         &mut self,
466         message: Message<u32>,
467         registry: &mut Registry<D>,
468     ) -> Option<(ClientId, GlobalId, ObjectId, Arc<dyn GlobalHandler<D>>)> {
469         match message.opcode {
470             // wl_registry.bind(uint name, str interface, uint version, new id)
471             0 => {
472                 if let [Argument::Uint(name), Argument::Str(ref interface_name), Argument::Uint(version), Argument::NewId(new_id)] =
473                     message.args[..]
474                 {
475                     if let Some((interface, global_id, handler)) =
476                         registry.check_bind(self, name, interface_name, version)
477                     {
478                         let serial = self.next_serial();
479                         let object = Object {
480                             interface,
481                             version,
482                             data: Data { serial, user_data: Arc::new(UninitObjectData) },
483                         };
484                         if let Err(()) = self.map.insert_at(new_id, object) {
485                             self.post_display_error(
486                                 DisplayError::InvalidObject,
487                                 CString::new(format!("Invalid new_id: {}.", new_id)).unwrap(),
488                             );
489                             return None;
490                         }
491                         Some((
492                             self.id.clone(),
493                             global_id,
494                             ObjectId { id: new_id, client_id: self.id.clone(), interface, serial },
495                             handler.clone(),
496                         ))
497                     } else {
498                         self.post_display_error(
499                             DisplayError::InvalidObject,
500                             CString::new(format!(
501                                 "Invalid binding of {} version {} for global {}.",
502                                 interface_name.to_string_lossy(),
503                                 version,
504                                 name
505                             ))
506                             .unwrap(),
507                         );
508                         None
509                     }
510                 } else {
511                     unreachable!()
512                 }
513             }
514             _ => {
515                 // unkown opcode, kill the client
516                 self.post_display_error(
517                     DisplayError::InvalidMethod,
518                     CString::new(format!(
519                         "Unknown opcode {} for interface wl_registry.",
520                         message.opcode
521                     ))
522                     .unwrap(),
523                 );
524                 None
525             }
526         }
527     }
528 
process_request( &mut self, object: &Object<Data<D>>, message: Message<u32>, ) -> Option<(ArgSmallVec, bool, Option<ObjectId>)>529     pub(crate) fn process_request(
530         &mut self,
531         object: &Object<Data<D>>,
532         message: Message<u32>,
533     ) -> Option<(ArgSmallVec, bool, Option<ObjectId>)> {
534         let message_desc = object.interface.requests.get(message.opcode as usize).unwrap();
535         // Convert the arguments and create the new object if applicable
536         let mut new_args = SmallVec::with_capacity(message.args.len());
537         let mut arg_interfaces = message_desc.arg_interfaces.iter();
538         let mut created_id = None;
539         for (i, arg) in message.args.into_iter().enumerate() {
540             new_args.push(match arg {
541                 Argument::Array(a) => Argument::Array(a),
542                 Argument::Int(i) => Argument::Int(i),
543                 Argument::Uint(u) => Argument::Uint(u),
544                 Argument::Str(s) => Argument::Str(s),
545                 Argument::Fixed(f) => Argument::Fixed(f),
546                 Argument::Fd(f) => Argument::Fd(f),
547                 Argument::Object(o) => {
548                     if o != 0 {
549                         // Lookup the object to make the appropriate Id
550                         let obj = match self.map.find(o) {
551                             Some(o) => o,
552                             None => {
553                                 self.post_display_error(
554                                     DisplayError::InvalidObject,
555                                     CString::new(format!("Unknown id: {}.", o)).unwrap()
556                                 );
557                                 return None;
558                             }
559                         };
560                         if let Some(next_interface) = arg_interfaces.next() {
561                             if !same_interface_or_anonymous(next_interface, obj.interface) {
562                                 self.post_display_error(
563                                     DisplayError::InvalidObject,
564                                     CString::new(format!(
565                                         "Invalid object {} in request {}.{}: expected {} but got {}.",
566                                         o,
567                                         object.interface.name,
568                                         message_desc.name,
569                                         next_interface.name,
570                                         obj.interface.name,
571                                     )).unwrap()
572                                 );
573                                 return None;
574                             }
575                         }
576                         Argument::Object(ObjectId { id: o, client_id: self.id.clone(), serial: obj.data.serial, interface: obj.interface })
577                     } else if matches!(message_desc.signature[i], ArgumentType::Object(AllowNull::Yes)) {
578                         Argument::Object(ObjectId { id: 0, client_id: self.id.clone(), serial: 0, interface: &ANONYMOUS_INTERFACE })
579                     } else {
580                         self.post_display_error(
581                             DisplayError::InvalidObject,
582                             CString::new(format!(
583                                 "Invalid null object in request {}.{}.",
584                                 object.interface.name,
585                                 message_desc.name,
586                             )).unwrap()
587                         );
588                         return None;
589                     }
590                 }
591                 Argument::NewId(new_id) => {
592                     // An object should be created
593                     let child_interface = match message_desc.child_interface {
594                         Some(iface) => iface,
595                         None => panic!("Received request {}@{}.{} which creates an object without specifying its interface, this is unsupported.", object.interface.name, message.sender_id, message_desc.name),
596                     };
597 
598                     let child_udata = Arc::new(UninitObjectData);
599 
600                     let child_obj = Object {
601                         interface: child_interface,
602                         version: object.version,
603                         data: Data {
604                             user_data: child_udata,
605                             serial: self.next_serial(),
606                         }
607                     };
608 
609                     let child_id = ObjectId { id: new_id, client_id: self.id.clone(), serial: child_obj.data.serial, interface: child_obj.interface };
610                     created_id = Some(child_id.clone());
611 
612                     if let Err(()) = self.map.insert_at(new_id, child_obj) {
613                         // abort parsing, this is an unrecoverable error
614                         self.post_display_error(
615                             DisplayError::InvalidObject,
616                             CString::new(format!("Invalid new_id: {}.", new_id)).unwrap()
617                         );
618                         return None;
619                     }
620 
621                     Argument::NewId(child_id)
622                 }
623             });
624         }
625 
626         Some((new_args, message_desc.is_destructor, created_id))
627     }
628 }
629 
630 struct DumbObjectData;
631 
632 impl<D> ObjectData<D> for DumbObjectData {
request( self: Arc<Self>, _handle: &mut Handle<D>, _data: &mut D, _client_id: ClientId, _msg: Message<ObjectId>, ) -> Option<Arc<dyn ObjectData<D>>>633     fn request(
634         self: Arc<Self>,
635         _handle: &mut Handle<D>,
636         _data: &mut D,
637         _client_id: ClientId,
638         _msg: Message<ObjectId>,
639     ) -> Option<Arc<dyn ObjectData<D>>> {
640         unreachable!()
641     }
642 
destroyed(&self, _: &mut D, _client_id: ClientId, _object_id: ObjectId)643     fn destroyed(&self, _: &mut D, _client_id: ClientId, _object_id: ObjectId) {}
644 }
645 
646 #[derive(Debug)]
647 pub(crate) struct ClientStore<D> {
648     clients: Vec<Option<Client<D>>>,
649     last_serial: u32,
650     debug: bool,
651 }
652 
653 impl<D> ClientStore<D> {
new(debug: bool) -> Self654     pub(crate) fn new(debug: bool) -> Self {
655         ClientStore { clients: Vec::new(), last_serial: 0, debug }
656     }
657 
create_client( &mut self, stream: UnixStream, data: Arc<dyn ClientData<D>>, ) -> ClientId658     pub(crate) fn create_client(
659         &mut self,
660         stream: UnixStream,
661         data: Arc<dyn ClientData<D>>,
662     ) -> ClientId {
663         let serial = self.next_serial();
664         // Find the next free place
665         let (id, place) = match self.clients.iter_mut().enumerate().find(|(_, c)| c.is_none()) {
666             Some((id, place)) => (id, place),
667             None => {
668                 self.clients.push(None);
669                 (self.clients.len() - 1, self.clients.last_mut().unwrap())
670             }
671         };
672 
673         let id = ClientId { id: id as u32, serial };
674 
675         *place = Some(Client::new(stream, id.clone(), self.debug, data));
676 
677         id
678     }
679 
get_client(&self, id: ClientId) -> Result<&Client<D>, InvalidId>680     pub(crate) fn get_client(&self, id: ClientId) -> Result<&Client<D>, InvalidId> {
681         match self.clients.get(id.id as usize) {
682             Some(&Some(ref client)) if client.id == id => Ok(client),
683             _ => Err(InvalidId),
684         }
685     }
686 
get_client_mut(&mut self, id: ClientId) -> Result<&mut Client<D>, InvalidId>687     pub(crate) fn get_client_mut(&mut self, id: ClientId) -> Result<&mut Client<D>, InvalidId> {
688         match self.clients.get_mut(id.id as usize) {
689             Some(&mut Some(ref mut client)) if client.id == id => Ok(client),
690             _ => Err(InvalidId),
691         }
692     }
693 
cleanup(&mut self, data: &mut D) -> SmallVec<[ClientId; 1]>694     pub(crate) fn cleanup(&mut self, data: &mut D) -> SmallVec<[ClientId; 1]> {
695         let mut cleaned = SmallVec::new();
696         for place in &mut self.clients {
697             if place.as_ref().map(|client| client.killed).unwrap_or(false) {
698                 // Remove the client from the store and flush it one last time before dropping it
699                 let mut client = place.take().unwrap();
700                 client.destroy_all_objects(data);
701                 let _ = client.flush();
702                 cleaned.push(client.id);
703             }
704         }
705         cleaned
706     }
707 
next_serial(&mut self) -> u32708     fn next_serial(&mut self) -> u32 {
709         self.last_serial = self.last_serial.wrapping_add(1);
710         self.last_serial
711     }
712 
clients_mut(&mut self) -> impl Iterator<Item = &mut Client<D>>713     pub(crate) fn clients_mut(&mut self) -> impl Iterator<Item = &mut Client<D>> {
714         self.clients.iter_mut().flat_map(|o| o.as_mut()).filter(|c| !c.killed)
715     }
716 
all_clients_id(&self) -> impl Iterator<Item = ClientId> + '_717     pub(crate) fn all_clients_id(&self) -> impl Iterator<Item = ClientId> + '_ {
718         self.clients
719             .iter()
720             .flat_map(|opt| opt.as_ref().filter(|c| !c.killed).map(|client| client.id.clone()))
721     }
722 }
723