use std::cell::RefCell;
use std::ffi::{CStr, OsStr};
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::os::fd::AsRawFd;
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use dispatch2::DispatchQueue;
use mitsuami_core::services::Reopen;
use objc2::MainThreadMarker;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplication, NSWindow};
type Reopened = Rc<dyn Fn(Reopen)>;
thread_local! {
static REOPENED: RefCell<Option<Reopened>> = const { RefCell::new(None) };
}
const TIMEOUT: Duration = Duration::from_secs(10);
const MAX_MESSAGE: u64 = 2 << 20;
pub(crate) fn claim(id: &str) -> bool {
let Some(dir) = user_dir() else {
eprintln!("mitsuami: {id} runs as its own instance, since it has no private folder to look for others in");
return true;
};
let path = socket_path(&dir, id);
let lock = match lock(&path.with_extension("lock")) {
Ok(lock) => lock,
Err(error) => {
eprintln!("mitsuami: {id} runs as its own instance, since it can't look for others: {error}");
return true;
}
};
match UnixStream::connect(&path) {
Ok(stream) => {
drop(lock);
if let Err(error) = hand_over(stream) {
eprintln!("mitsuami: couldn't hand this launch to the running {id}: {error}");
}
false
}
Err(_) => {
let _ = std::fs::remove_file(&path);
match UnixListener::bind(&path) {
Ok(listener) => {
_ = std::fs::set_permissions(&path, std::os::unix::fs::PermissionsExt::from_mode(0o600));
listen(listener);
}
Err(error) => {
eprintln!("mitsuami: {id} runs as its own instance, since it can't listen for others: {error}")
}
}
true
}
}
}
fn user_dir() -> Option<PathBuf> {
let mut buffer = [0u8; 1024];
let needed = unsafe { libc::confstr(libc::_CS_DARWIN_USER_DIR, buffer.as_mut_ptr().cast(), buffer.len()) };
if needed == 0 || needed > buffer.len() {
return None;
}
let dir = PathBuf::from(OsStr::from_bytes(CStr::from_bytes_until_nul(&buffer).ok()?.to_bytes()));
let meta = std::fs::symlink_metadata(&dir).ok()?;
let me = unsafe { libc::geteuid() };
(meta.is_dir() && meta.uid() == me && meta.mode() & 0o022 == 0).then_some(dir)
}
fn socket_path(dir: &std::path::Path, id: &str) -> PathBuf {
let path = dir.join(format!("{id}.instance"));
if path.as_os_str().len() < 100 { path } else { dir.join(format!("mitsuami-{:016x}.instance", fnv(id))) }
}
fn fnv(text: &str) -> u64 {
text.bytes().fold(0xcbf2_9ce4_8422_2325, |hash, byte| (hash ^ u64::from(byte)).wrapping_mul(0x100_0000_01b3))
}
fn lock(path: &std::path::Path) -> std::io::Result<File> {
let file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(false)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(path)?;
file.lock()?;
Ok(file)
}
fn same_user(stream: &UnixStream) -> bool {
let (mut uid, mut gid) = (0, 0);
let ok = unsafe { libc::getpeereid(stream.as_raw_fd(), &mut uid, &mut gid) } == 0;
ok && uid == unsafe { libc::geteuid() }
}
fn hand_over(mut stream: UnixStream) -> std::io::Result<()> {
if !same_user(&stream) {
return Err(std::io::Error::new(std::io::ErrorKind::PermissionDenied, "another user's process listens"));
}
stream.set_read_timeout(Some(TIMEOUT))?;
stream.set_write_timeout(Some(TIMEOUT))?;
let mut message = Vec::new();
let cwd = std::env::current_dir().map(|cwd| cwd.into_os_string()).unwrap_or_default();
for field in std::iter::once(cwd).chain(std::env::args_os().skip(1)) {
message.extend_from_slice(field.as_bytes());
message.push(0);
}
stream.write_all(&message)?;
stream.shutdown(std::net::Shutdown::Write)?;
let mut answer = [0u8; 1];
stream.read_exact(&mut answer)
}
fn listen(listener: UnixListener) {
std::thread::spawn(move || {
for stream in listener.incoming() {
let stream = match stream {
Ok(stream) => stream,
Err(_) => {
std::thread::sleep(Duration::from_millis(100));
continue;
}
};
if !same_user(&stream) {
continue;
}
_ = std::thread::Builder::new().spawn(move || receive(stream));
}
});
}
fn receive(mut stream: UnixStream) {
let deadline = std::time::Instant::now() + TIMEOUT;
let mut message = Vec::new();
let mut chunk = [0u8; 16 * 1024];
loop {
let Some(left) = deadline.checked_duration_since(std::time::Instant::now()).filter(|d| !d.is_zero()) else {
return;
};
if stream.set_read_timeout(Some(left)).is_err() {
return;
}
match stream.read(&mut chunk) {
Ok(0) => break,
Ok(n) if (message.len() + n) as u64 <= MAX_MESSAGE => message.extend_from_slice(&chunk[..n]),
Ok(_) => return,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
Err(_) => return,
}
}
let mut fields: Vec<String> =
message.split(|byte| *byte == 0).map(|field| String::from_utf8_lossy(field).into_owned()).collect();
fields.pop();
if fields.is_empty() {
return;
}
let cwd = fields.remove(0);
_ = stream.set_write_timeout(Some(TIMEOUT));
_ = stream.write_all(b"1");
DispatchQueue::main().exec_async(move || {
let cwd = (!cwd.is_empty()).then(|| PathBuf::from(cwd));
if let Some(mtm) = MainThreadMarker::new() {
bring_forward(mtm);
}
reopened(Reopen::new(fields, cwd, Vec::new()));
});
}
fn bring_forward(mtm: MainThreadMarker) {
let app = NSApplication::sharedApplication(mtm);
app.activate();
let main = |window: &Retained<NSWindow>| window.canBecomeMainWindow();
let window = app
.orderedWindows()
.iter()
.find(|window| main(window) && window.isVisible())
.or_else(|| app.windows().iter().find(|window| main(window) && window.isMiniaturized()));
if let Some(window) = window {
if window.isMiniaturized() {
window.deminiaturize(None);
}
window.makeKeyAndOrderFront(None);
}
}
pub(crate) fn connect(f: Reopened) {
REOPENED.with(|r| *r.borrow_mut() = Some(f));
}
pub(crate) fn reopened(reopen: Reopen) {
if let Some(f) = REOPENED.with(|r| r.borrow().clone()) {
f(reopen);
}
}