1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
use std::{
collections::VecDeque,
io::{self, Read, Write},
os::unix::net::UnixStream,
sync::mpsc::{Receiver, RecvError, Sender, TryRecvError, channel},
thread,
};
use lunar_lib::{error, trace};
use crate::{
ConnectErrorKind, IpcActionError, IpcCommand, IpcHandleError, PacketType, PlayerEvent,
PlayerResponse,
daemon::{DaemonHandle, IpcRequest},
};
pub const SELENE_UNIX_SOCKET_PATH: &str = "/tmp/selene.sock";
pub(crate) struct UnixSocketHandle {
rx: Receiver<IpcRequest>,
stream: Option<UnixStream>,
}
impl DaemonHandle<IpcCommand, PlayerResponse> for UnixSocketHandle {
fn connect<F>(callback: Option<F>) -> Result<Sender<IpcRequest>, IpcHandleError>
where
Self: Sized,
F: FnMut(PlayerEvent) + Send + Sync + 'static,
{
trace!("Connecting to UnixSocketHandle");
let stream = UnixStream::connect(SELENE_UNIX_SOCKET_PATH).map_err(|err| {
let reason = match err.kind() {
io::ErrorKind::NotFound => ConnectErrorKind::DaemonNotRunning,
io::ErrorKind::ConnectionRefused => ConnectErrorKind::ConnectionRefused,
_ => ConnectErrorKind::Other(err),
};
IpcHandleError::FailedToConnect(reason)
})?;
let (tx, rx) = channel();
let handle = UnixSocketHandle {
rx,
stream: Some(stream),
};
thread::spawn(|| handle.run(callback));
Ok(tx)
}
fn reconnect(&mut self) -> bool {
let Ok(stream) = UnixStream::connect(SELENE_UNIX_SOCKET_PATH) else {
return false;
};
self.stream = Some(stream);
true
}
fn run<F>(mut self, mut callback: Option<F>) -> Result<(), IpcHandleError>
where
F: FnMut(PlayerEvent) + Send + Sync + 'static,
{
let mut queue: VecDeque<Sender<Result<PlayerResponse, IpcActionError>>> = VecDeque::new();
'stream_loop: loop {
let Some(stream) = &mut self.stream else {
// Loop until reconnected or dropped
loop {
match self.rx.recv() {
Ok(IpcRequest::Reconnect { callback }) => {
let success = self.reconnect();
let _ = callback.send(success);
if success {
continue 'stream_loop;
}
}
Ok(IpcRequest::Ipc {
command: _,
callback,
}) => {
let _ = callback.send(Err(IpcActionError::Disconnected));
}
Err(RecvError) => return Ok(()),
}
}
};
// Loop until all commands have been sent
// Break = Try to recieve responses
loop {
match self.rx.try_recv() {
// Reconnect attempt when already reconnected, just say it succeeded
Ok(IpcRequest::Reconnect { callback }) => {
let _ = callback.send(true);
}
// Command requested, send command
Ok(IpcRequest::Ipc { command, callback }) => {
let mut command_buf = Vec::new();
ciborium::into_writer(&command, &mut command_buf).unwrap();
let len = command_buf.len() as u32;
if stream.write_all(&len.to_be_bytes()).is_err() {
let _ = callback.send(Err(IpcActionError::Disconnected));
self.stream.take();
continue 'stream_loop;
};
if stream.write_all(&command_buf).is_err() {
let _ = callback.send(Err(IpcActionError::Disconnected));
self.stream.take();
continue 'stream_loop;
};
queue.push_back(callback);
}
// No commands in queue, break
Err(TryRecvError::Empty) => break,
// All senders disconnected, shutdown
Err(TryRecvError::Disconnected) => return Ok(()),
}
}
// Try to deserialize all packets in the stream
stream.set_nonblocking(true).unwrap();
let mut read = [0u8; 1];
match stream.read_exact(&mut read) {
// Packet read, there is data
Ok(()) => (),
// No packet, just break
Err(err) if matches!(err.kind(), io::ErrorKind::WouldBlock) => {
continue;
}
// Disconnected, continue and wait for reconnect
Err(err) if matches!(err.kind(), io::ErrorKind::UnexpectedEof) => {
self.stream.take();
continue 'stream_loop;
}
// Unexpected error
Err(err) => {
panic!("Ran into an unexpected error while reading from the stream: {err}")
}
}
let packet_type = PacketType::from(read[0]);
stream.set_nonblocking(false).unwrap();
let mut len_buf = [0u8; 4];
if stream.read_exact(&mut len_buf).is_err() {
self.stream.take();
continue 'stream_loop;
}
let packet_len = u32::from_be_bytes(len_buf) as usize;
let mut packet_buf = vec![0u8; packet_len];
if stream.read_exact(&mut packet_buf).is_err() {
self.stream.take();
continue 'stream_loop;
}
match packet_type {
// Unknown packet, do nothing and continue to the next main loop
PacketType::Unknown => {
continue;
}
// Response packet, send the response to the first item in the queue (FIFO) and continue to the next main loop
PacketType::PlayerResponse => {
if let Some(pop_front) = queue.pop_front() {
let response: Result<PlayerResponse, IpcActionError> =
match ciborium::from_reader(packet_buf.as_slice()) {
Ok(v) => v,
Err(err) => {
panic!("Daemon sent corrupted bytes: {err}")
}
};
let _ = pop_front.send(response);
} else {
error!(
"Daemon sent a 'PlayerResponse' packet when no response was expected"
)
}
continue;
}
// Event packet, send the event to the callback function and continue to the next main loop
PacketType::PlayerEvent => {
let event: PlayerEvent = match ciborium::from_reader(packet_buf.as_slice()) {
Ok(v) => v,
Err(err) => {
panic!("Daemon sent corrupted bytes: {err}")
}
};
if let Some(callback) = &mut callback {
callback(event);
}
continue;
}
}
}
}
}