1use std::env;
5use std::ffi::{OsStr, OsString};
6use std::fs;
7use std::io::{self, Read, Write};
8use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
9use std::os::unix::ffi::{OsStrExt, OsStringExt};
10use std::os::unix::fs::PermissionsExt;
11use std::os::unix::net::{UnixListener, UnixStream};
12use std::path::{Path, PathBuf};
13use std::thread::{self, JoinHandle};
14use std::time::{Duration, SystemTime};
15
16use winit::event_loop::EventLoopProxy;
17
18use super::Event;
19use super::split::Axis;
20
21const IO_TIMEOUT: Duration = Duration::from_secs(2);
22const MAX_MESSAGE_BYTES: usize = 64 * 1024;
23const MAX_ARGS: usize = 256;
24
25#[derive(Clone, Debug, PartialEq, Eq)]
26pub enum IpcCommand {
27 NewTab {
28 working_directory: Option<PathBuf>,
29 title: Option<String>,
30 command: Option<Vec<OsString>>,
31 },
32 Split {
33 axis: Axis,
34 working_directory: Option<PathBuf>,
35 },
36 SetTheme(String),
37 ReloadConfig,
38 SaveConfig,
39}
40
41pub(super) struct IpcServer {
42 socket_path: PathBuf,
43 wake_write: Option<OwnedFd>,
44 thread: Option<JoinHandle<()>>,
45}
46
47impl IpcServer {
48 pub(super) fn start(proxy: EventLoopProxy<Event>) -> Option<Self> {
49 let dir = runtime_dir()?;
50 if let Err(error) = ensure_secure_dir(&dir) {
51 log::debug!("Could not prepare IPC runtime directory: {error}");
52 return None;
53 }
54 let socket_path = dir.join(format!("ipc-{}.sock", std::process::id()));
55 let _ = fs::remove_file(&socket_path);
56
57 let listener = match UnixListener::bind(&socket_path) {
58 Ok(listener) => listener,
59 Err(error) => {
60 log::debug!("Could not bind IPC socket: {error}");
61 return None;
62 }
63 };
64 let _ = fs::set_permissions(&socket_path, fs::Permissions::from_mode(0o600));
65 if listener.set_nonblocking(true).is_err() {
66 let _ = fs::remove_file(&socket_path);
67 return None;
68 }
69
70 let Ok((wake_read, wake_write)) = create_wake_pipe() else {
71 let _ = fs::remove_file(&socket_path);
72 return None;
73 };
74
75 let thread = match thread::Builder::new()
76 .name("lune-ipc".into())
77 .spawn(move || run_listener(listener, wake_read, proxy))
78 {
79 Ok(thread) => thread,
80 Err(error) => {
81 log::warn!("Could not start IPC listener thread: {error}");
82 let _ = fs::remove_file(&socket_path);
83 return None;
84 }
85 };
86
87 log::debug!("IPC socket listening at {}", socket_path.display());
88 Some(Self {
89 socket_path,
90 wake_write: Some(wake_write),
91 thread: Some(thread),
92 })
93 }
94
95 pub(super) fn socket_path(&self) -> &Path {
96 &self.socket_path
97 }
98}
99
100impl Drop for IpcServer {
101 fn drop(&mut self) {
102 if let Some(wake) = self.wake_write.take() {
103 let byte = [1u8; 1];
104 let _ = unsafe { libc::write(wake.as_raw_fd(), byte.as_ptr().cast(), byte.len()) };
106 }
107 if let Some(thread) = self.thread.take() {
108 let _ = thread.join();
109 }
110 let _ = fs::remove_file(&self.socket_path);
111 }
112}
113
114pub fn list_sockets() -> Vec<PathBuf> {
115 let Some(dir) = runtime_dir() else {
116 return Vec::new();
117 };
118 let Ok(entries) = fs::read_dir(&dir) else {
119 return Vec::new();
120 };
121 let mut sockets: Vec<(SystemTime, PathBuf)> = Vec::new();
122 for entry in entries.flatten() {
123 let path = entry.path();
124 let Some(name) = path.file_name().and_then(|n| n.to_str()) else {
125 continue;
126 };
127 if !(name.starts_with("ipc-") && name.ends_with(".sock")) {
128 continue;
129 }
130 if UnixStream::connect(&path).is_ok() {
131 let mtime = entry
132 .metadata()
133 .and_then(|meta| meta.modified())
134 .unwrap_or(SystemTime::UNIX_EPOCH);
135 sockets.push((mtime, path));
136 } else {
137 let _ = fs::remove_file(&path);
139 }
140 }
141 sockets.sort_by_key(|a| std::cmp::Reverse(a.0));
142 sockets.into_iter().map(|(_, path)| path).collect()
143}
144
145pub fn send_command(socket: Option<&Path>, command: &IpcCommand) -> Result<(), String> {
146 let target = if let Some(path) = socket {
147 path.to_path_buf()
148 } else if let Some(env_path) = env::var_os("LUNE_IPC_SOCKET")
149 .filter(|value| !value.is_empty())
150 .map(PathBuf::from)
151 .filter(|path| path.exists())
152 {
153 env_path
154 } else {
155 list_sockets()
156 .into_iter()
157 .next()
158 .ok_or_else(|| "no running Lune window found".to_owned())?
159 };
160
161 send_to_socket(&target, command)
162}
163
164fn send_to_socket(path: &Path, command: &IpcCommand) -> Result<(), String> {
165 let mut stream = UnixStream::connect(path)
166 .map_err(|error| format!("could not connect to {}: {error}", path.display()))?;
167 let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
168 let _ = stream.set_write_timeout(Some(IO_TIMEOUT));
169
170 let frame = encode_command(command)?;
171 stream
172 .write_all(&frame)
173 .map_err(|error| format!("failed to send IPC command: {error}"))?;
174 let _ = stream.shutdown(std::net::Shutdown::Write);
175
176 let mut reply = String::new();
177 stream
178 .take(1024)
179 .read_to_string(&mut reply)
180 .map_err(|error| format!("failed to read IPC response: {error}"))?;
181 let line = reply.lines().next().unwrap_or("");
182 if line == "OK" {
183 Ok(())
184 } else if let Some(err) = line.strip_prefix("ERR ") {
185 Err(err.to_owned())
186 } else {
187 Err("unexpected IPC response from Lune window".to_owned())
188 }
189}
190
191fn run_listener(listener: UnixListener, wake_read: OwnedFd, proxy: EventLoopProxy<Event>) {
192 let mut fds = [
193 libc::pollfd {
194 fd: listener.as_raw_fd(),
195 events: libc::POLLIN,
196 revents: 0,
197 },
198 libc::pollfd {
199 fd: wake_read.as_raw_fd(),
200 events: libc::POLLIN,
201 revents: 0,
202 },
203 ];
204 loop {
205 fds[0].revents = 0;
206 fds[1].revents = 0;
207 let ready = unsafe { libc::poll(fds.as_mut_ptr(), 2, -1) };
209 if ready < 0 {
210 if io::Error::last_os_error().kind() == io::ErrorKind::Interrupted {
211 continue;
212 }
213 break;
214 }
215 if fds[1].revents != 0 {
216 break;
217 }
218 if fds[0].revents & libc::POLLIN != 0 {
219 loop {
220 match listener.accept() {
221 Ok((stream, _)) => handle_client(stream, &proxy),
222 Err(error) if error.kind() == io::ErrorKind::WouldBlock => break,
223 Err(_) => return,
224 }
225 }
226 }
227 }
228}
229
230fn handle_client(mut stream: UnixStream, proxy: &EventLoopProxy<Event>) {
231 let _ = stream.set_read_timeout(Some(IO_TIMEOUT));
232 let _ = stream.set_write_timeout(Some(IO_TIMEOUT));
233
234 let mut raw = Vec::new();
235 if Read::by_ref(&mut stream)
236 .take((MAX_MESSAGE_BYTES + 1) as u64)
237 .read_to_end(&mut raw)
238 .is_err()
239 {
240 return;
241 }
242 if raw.len() > MAX_MESSAGE_BYTES {
243 let _ = stream.write_all(b"ERR message too large\n");
244 return;
245 }
246 match decode_command(&raw) {
247 Ok(command) => {
248 if proxy.send_event(Event::IpcCommand(command)).is_ok() {
249 let _ = stream.write_all(b"OK\n");
250 } else {
251 let _ = stream.write_all(b"ERR window is closing\n");
252 }
253 }
254 Err(error) => {
255 let _ = writeln!(stream, "ERR {error}");
256 }
257 }
258}
259
260fn runtime_dir() -> Option<PathBuf> {
261 let base = env::var_os("XDG_RUNTIME_DIR").filter(|value| !value.is_empty())?;
262 let path = PathBuf::from(base);
263 path.is_absolute().then(|| path.join("lune"))
264}
265
266fn ensure_secure_dir(dir: &Path) -> io::Result<()> {
267 fs::create_dir_all(dir)?;
268 fs::set_permissions(dir, fs::Permissions::from_mode(0o700))
269}
270
271fn create_wake_pipe() -> io::Result<(OwnedFd, OwnedFd)> {
272 let mut fds = [-1; 2];
273 if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) } != 0 {
275 return Err(io::Error::last_os_error());
276 }
277 let read_fd = unsafe { OwnedFd::from_raw_fd(fds[0]) };
279 let write_fd = unsafe { OwnedFd::from_raw_fd(fds[1]) };
281 Ok((read_fd, write_fd))
282}
283
284fn push_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
285 out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
286 out.extend_from_slice(bytes);
287}
288
289fn push_opt_os(out: &mut Vec<u8>, value: Option<&OsStr>) {
290 match value {
291 Some(v) => {
292 out.push(1);
293 push_bytes(out, v.as_bytes());
294 }
295 None => out.push(0),
296 }
297}
298
299fn encode_command(command: &IpcCommand) -> Result<Vec<u8>, String> {
300 let mut out = Vec::with_capacity(128);
301 out.push(1); match command {
303 IpcCommand::NewTab {
304 working_directory,
305 title,
306 command,
307 } => {
308 out.push(1);
309 push_opt_os(&mut out, working_directory.as_deref().map(Path::as_os_str));
310 push_opt_os(&mut out, title.as_deref().map(OsStr::new));
311 match command {
312 Some(args) => {
313 if args.len() > MAX_ARGS {
314 return Err("too many command arguments".into());
315 }
316 out.push(1);
317 out.extend_from_slice(&(args.len() as u32).to_le_bytes());
318 for arg in args {
319 push_bytes(&mut out, arg.as_bytes());
320 }
321 }
322 None => out.push(0),
323 }
324 }
325 IpcCommand::Split {
326 axis,
327 working_directory,
328 } => {
329 out.push(2);
330 out.push(match axis {
331 Axis::Columns => 0,
332 Axis::Rows => 1,
333 });
334 push_opt_os(&mut out, working_directory.as_deref().map(Path::as_os_str));
335 }
336 IpcCommand::SetTheme(name) => {
337 out.push(3);
338 push_bytes(&mut out, name.as_bytes());
339 }
340 IpcCommand::ReloadConfig => {
341 out.push(4);
342 }
343 IpcCommand::SaveConfig => {
344 out.push(5);
345 }
346 }
347 if out.len() > MAX_MESSAGE_BYTES {
348 return Err("IPC message exceeds size limit".into());
349 }
350 Ok(out)
351}
352
353fn take_u8(input: &mut &[u8]) -> Result<u8, String> {
354 let (&first, rest) = input
355 .split_first()
356 .ok_or_else(|| "truncated IPC message".to_owned())?;
357 *input = rest;
358 Ok(first)
359}
360
361fn take_u32(input: &mut &[u8]) -> Result<u32, String> {
362 if input.len() < 4 {
363 return Err("truncated IPC integer".into());
364 }
365 let (head, rest) = input.split_at(4);
366 *input = rest;
367 Ok(u32::from_le_bytes(head.try_into().unwrap()))
368}
369
370fn take_bytes<'a>(input: &mut &'a [u8]) -> Result<&'a [u8], String> {
371 let len = take_u32(input)? as usize;
372 if len > input.len() {
373 return Err("truncated IPC payload".into());
374 }
375 let (head, rest) = input.split_at(len);
376 *input = rest;
377 Ok(head)
378}
379
380fn take_opt_os(input: &mut &[u8]) -> Result<Option<OsString>, String> {
381 match take_u8(input)? {
382 0 => Ok(None),
383 1 => Ok(Some(OsString::from_vec(take_bytes(input)?.to_vec()))),
384 _ => Err("invalid optional field tag".into()),
385 }
386}
387
388fn decode_command(mut input: &[u8]) -> Result<IpcCommand, String> {
389 let version = take_u8(&mut input)?;
390 if version != 1 {
391 return Err(format!("unsupported IPC version {version}"));
392 }
393 let kind = take_u8(&mut input)?;
394 let command = match kind {
395 1 => {
396 let working_directory = take_opt_os(&mut input)?.map(PathBuf::from);
397 let title = match take_opt_os(&mut input)? {
398 Some(raw) => Some(
399 raw.into_string()
400 .map_err(|_| "tab title must be valid UTF-8".to_owned())?,
401 ),
402 None => None,
403 };
404 let command = match take_u8(&mut input)? {
405 0 => None,
406 1 => {
407 let count = take_u32(&mut input)? as usize;
408 if count > MAX_ARGS {
409 return Err("too many command arguments".into());
410 }
411 let mut args = Vec::with_capacity(count);
412 for _ in 0..count {
413 args.push(OsString::from_vec(take_bytes(&mut input)?.to_vec()));
414 }
415 Some(args)
416 }
417 _ => return Err("invalid command tag".into()),
418 };
419 IpcCommand::NewTab {
420 working_directory,
421 title,
422 command,
423 }
424 }
425 2 => {
426 let axis = match take_u8(&mut input)? {
427 0 => Axis::Columns,
428 1 => Axis::Rows,
429 _ => return Err("invalid split axis".into()),
430 };
431 let working_directory = take_opt_os(&mut input)?.map(PathBuf::from);
432 IpcCommand::Split {
433 axis,
434 working_directory,
435 }
436 }
437 3 => {
438 let name = std::str::from_utf8(take_bytes(&mut input)?)
439 .map_err(|_| "theme name must be valid UTF-8".to_owned())?
440 .to_owned();
441 IpcCommand::SetTheme(name)
442 }
443 4 => IpcCommand::ReloadConfig,
444 5 => IpcCommand::SaveConfig,
445 _ => return Err("unknown IPC command".into()),
446 };
447 if !input.is_empty() {
448 return Err("trailing bytes in IPC message".into());
449 }
450 Ok(command)
451}
452
453#[cfg(test)]
454mod tests {
455 use super::*;
456
457 #[test]
458 fn encodes_and_decodes_all_ipc_commands() {
459 let cases = [
460 IpcCommand::NewTab {
461 working_directory: Some(PathBuf::from("/tmp/dir with spaces")),
462 title: Some("Build".into()),
463 command: Some(vec![OsString::from("sh"), OsString::from("-c")]),
464 },
465 IpcCommand::Split {
466 axis: Axis::Rows,
467 working_directory: None,
468 },
469 IpcCommand::SetTheme("tokyo-night".into()),
470 IpcCommand::ReloadConfig,
471 IpcCommand::SaveConfig,
472 ];
473 for command in cases {
474 let wire = encode_command(&command).unwrap();
475 let decoded = decode_command(&wire).unwrap();
476 assert_eq!(decoded, command);
477 }
478 }
479}