Skip to main content

toolblox_lib/
multi_instance.rs

1//! Running several Roblox clients at once.
2//!
3//! On Windows, the bundled audited helper closes Roblox's singleton handles. On macOS, Roblox's
4//! single-instance semaphore name is removed and the player is started directly, because Launch
5//! Services refuses a second instance of a bundle with `LSMultipleInstancesProhibited`. The
6//! semaphore was identified by [multi-roblox-macos](https://github.com/Insadem/multi-roblox-macos)
7//! and [rororo-mac](https://github.com/estevanhernandez-stack-ed/rororo-mac).
8
9use std::collections::HashSet;
10use std::path::{Path, PathBuf};
11#[cfg(any(windows, target_os = "macos"))]
12use std::process::Command;
13
14#[cfg(windows)]
15use std::os::windows::process::CommandExt;
16
17/// Process creation flag that keeps console helpers from opening a window.
18#[cfg(windows)]
19const CREATE_NO_WINDOW: u32 = 0x08000000;
20
21/// The named event `RobloxPlayerBeta.exe` creates to refuse a second client.
22#[cfg(windows)]
23const ROBLOX_SINGLETON: &str = "ROBLOX_singletonEvent";
24
25#[cfg(windows)]
26#[link(name = "kernel32")]
27unsafe extern "system" {
28    fn CreateMutexW(
29        attributes: *const std::ffi::c_void,
30        initial_owner: i32,
31        name: *const u16,
32    ) -> *mut std::ffi::c_void;
33    fn CloseHandle(handle: *mut std::ffi::c_void) -> i32;
34}
35
36/// The handle of the mutex holding the Roblox singleton name, or 0.
37#[cfg(windows)]
38static SINGLETON_HANDLE: std::sync::Mutex<usize> = std::sync::Mutex::new(0);
39
40/// Creates a mutex under `name` and returns its handle. Returns `None` when the name is already
41/// taken by an object of another type, such as an event.
42#[cfg(windows)]
43fn hold_name(name: &str) -> Option<usize> {
44    let wide: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
45    // SAFETY: `wide` is NUL-terminated and outlives the call; null attributes are allowed.
46    let handle = unsafe { CreateMutexW(std::ptr::null(), 0, wide.as_ptr()) };
47    (!handle.is_null()).then_some(handle as usize)
48}
49
50/// Lets the next Roblox client open alongside running ones.
51///
52/// Holds Roblox's singleton name as a mutex, so clients started afterwards can't create the
53/// shared event and never signal or wait on each other. When a client already owns the event,
54/// the helper closes the handle of each process not yet in `cleared`, once, and the name is
55/// held after that. `cleared` drops IDs that have exited. Does nothing outside Windows.
56pub fn clear_new_roblox_instances(
57    helper: Option<&Path>,
58    cleared: &mut HashSet<u32>,
59) -> Result<(), String> {
60    #[cfg(not(windows))]
61    {
62        let _ = (helper, cleared);
63        Ok(())
64    }
65    #[cfg(windows)]
66    {
67        let mut held = SINGLETON_HANDLE
68            .lock()
69            .map_err(|_| "The multi-instance state is busy. Can you try again?".to_string())?;
70        if *held != 0 {
71            return Ok(());
72        }
73        if let Some(handle) = hold_name(ROBLOX_SINGLETON) {
74            *held = handle;
75            return Ok(());
76        }
77        close_singleton_handles(helper, cleared)?;
78        match hold_name(ROBLOX_SINGLETON) {
79            Some(handle) => *held = handle,
80            None => {
81                log::warn!("Roblox's single-instance name couldn't be held after clearing it");
82                cleared.clear();
83            }
84        }
85        Ok(())
86    }
87}
88
89/// Releases the Roblox singleton name, so Roblox allows one client again. Does nothing when the
90/// name isn't held or outside Windows.
91pub fn release_roblox_singleton() {
92    #[cfg(windows)]
93    if let Ok(mut held) = SINGLETON_HANDLE.lock()
94        && *held != 0
95    {
96        // SAFETY: `held` is an open handle from `CreateMutexW`, closed only here.
97        unsafe { CloseHandle(*held as *mut std::ffi::c_void) };
98        *held = 0;
99    }
100}
101
102/// Runs the helper on Roblox processes not yet in `cleared`.
103#[cfg(windows)]
104fn close_singleton_handles(
105    helper: Option<&Path>,
106    cleared: &mut HashSet<u32>,
107) -> Result<(), String> {
108    let helper = helper.filter(|path| path.is_file()).ok_or_else(|| {
109        "The multi-instance helper isn't installed. Can you reinstall Toolblox?".to_string()
110    })?;
111    let running = crate::roblox_process::roblox_pids()?;
112    cleared.retain(|pid| running.contains(pid));
113    let new: Vec<_> = running.difference(cleared).copied().collect();
114    if new.is_empty() {
115        return Ok(());
116    }
117    let status = Command::new(helper)
118        .args(new.iter().map(u32::to_string))
119        .creation_flags(CREATE_NO_WINDOW)
120        .status()
121        .map_err(|_| "The multi-instance helper couldn't start. Can you try again?".to_string())?;
122    if !status.success() {
123        return Err("The multi-instance helper failed. Can you try again?".into());
124    }
125    cleared.extend(new);
126    Ok(())
127}
128
129/// The POSIX semaphore the macOS Roblox player uses to refuse a second client.
130#[cfg(target_os = "macos")]
131const ROBLOX_SEMAPHORE: &std::ffi::CStr = c"/RobloxPlayerUniq";
132
133/// The player executable inside `Roblox.app`.
134#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
135const PLAYER_EXECUTABLE: &str = "Contents/MacOS/RobloxPlayer";
136
137#[cfg(target_os = "macos")]
138unsafe extern "C" {
139    fn sem_unlink(name: *const std::ffi::c_char) -> std::ffi::c_int;
140}
141
142/// Removes a named semaphore. A semaphore that doesn't exist isn't an error. Processes that
143/// already opened it keep their handle.
144#[cfg(target_os = "macos")]
145fn unlink_semaphore(name: &std::ffi::CStr) -> Result<(), String> {
146    // SAFETY: `name` is a valid NUL-terminated string that outlives the call.
147    if unsafe { sem_unlink(name.as_ptr()) } == 0 {
148        return Ok(());
149    }
150    match std::io::Error::last_os_error().kind() {
151        std::io::ErrorKind::NotFound => Ok(()),
152        _ => Err("Roblox's single-instance lock couldn't be cleared. Can you try again?".into()),
153    }
154}
155
156/// Returns the first installed Roblox player under the given application folders.
157#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
158fn find_roblox_player(application_dirs: &[PathBuf]) -> Option<PathBuf> {
159    application_dirs
160        .iter()
161        .map(|dir| dir.join("Roblox.app").join(PLAYER_EXECUTABLE))
162        .find(|path| path.is_file())
163}
164
165/// Builds the command that starts the player with a join URI, the same arguments Roblox's own
166/// launcher passes.
167#[cfg(target_os = "macos")]
168fn player_command(player: &Path, uri: &str) -> Command {
169    use std::os::unix::process::CommandExt;
170
171    let mut command = Command::new(player);
172    command
173        .args(["-protocolString", uri])
174        .stdin(std::process::Stdio::null())
175        .stdout(std::process::Stdio::null())
176        .stderr(std::process::Stdio::null())
177        .process_group(0);
178    command
179}
180
181/// Starts a new Roblox client for a join URI alongside any running clients.
182///
183/// Removes Roblox's single-instance semaphore name before and after starting the player, so
184/// neither a running client nor the new one blocks the next. The URI holds a one-time ticket, so
185/// it must not be logged. Only supported on macOS.
186pub fn open_new_roblox_instance(uri: &str) -> Result<(), String> {
187    #[cfg(not(target_os = "macos"))]
188    {
189        let _ = uri;
190        Err("Starting a separate Roblox client isn't supported on this platform. Is this device running Windows or macOS?".into())
191    }
192    #[cfg(target_os = "macos")]
193    {
194        let mut application_dirs = vec![PathBuf::from("/Applications")];
195        if let Some(home) = std::env::var_os("HOME") {
196            application_dirs.push(PathBuf::from(home).join("Applications"));
197        }
198        let player = find_roblox_player(&application_dirs).ok_or_else(|| {
199            "Roblox wasn't found in the Applications folder. Is Roblox installed?".to_string()
200        })?;
201        unlink_semaphore(ROBLOX_SEMAPHORE)?;
202        let mut child = player_command(&player, uri)
203            .spawn()
204            .map_err(|_| "Roblox couldn't be started. Is Roblox installed?".to_string())?;
205        std::thread::spawn(move || child.wait());
206        unlink_semaphore(ROBLOX_SEMAPHORE)
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn roblox_player_is_found_in_the_first_folder_that_has_it() {
216        let first = tempfile::tempdir().unwrap();
217        let second = tempfile::tempdir().unwrap();
218        let dirs = [first.path().to_path_buf(), second.path().to_path_buf()];
219        assert_eq!(find_roblox_player(&dirs), None);
220
221        let player = second.path().join("Roblox.app").join(PLAYER_EXECUTABLE);
222        std::fs::create_dir_all(player.parent().unwrap()).unwrap();
223        std::fs::write(&player, b"").unwrap();
224        assert_eq!(find_roblox_player(&dirs), Some(player.clone()));
225
226        std::fs::create_dir_all(first.path().join("Roblox.app").join(PLAYER_EXECUTABLE)).unwrap();
227        assert_eq!(find_roblox_player(&dirs), Some(player));
228    }
229
230    #[cfg(windows)]
231    #[test]
232    fn held_name_blocks_an_event_with_the_same_name() {
233        unsafe extern "system" {
234            fn CreateEventW(
235                attributes: *const std::ffi::c_void,
236                manual_reset: i32,
237                initial_state: i32,
238                name: *const u16,
239            ) -> *mut std::ffi::c_void;
240        }
241        let create_event = |name: &str| {
242            let wide: Vec<u16> = name.encode_utf16().chain(Some(0)).collect();
243            // SAFETY: `wide` is NUL-terminated and outlives the call.
244            unsafe { CreateEventW(std::ptr::null(), 0, 0, wide.as_ptr()) }
245        };
246        // SAFETY: each handle is open and closed once.
247        let close = |handle: *mut std::ffi::c_void| unsafe { CloseHandle(handle) };
248
249        let held = format!("tbx-held-{}", std::process::id());
250        let first = hold_name(&held).unwrap();
251        let second = hold_name(&held).unwrap();
252        assert!(create_event(&held).is_null());
253        close(first as _);
254        close(second as _);
255        let event = create_event(&held);
256        assert!(!event.is_null());
257        close(event);
258
259        let taken = format!("tbx-taken-{}", std::process::id());
260        let event = create_event(&taken);
261        assert!(!event.is_null());
262        assert_eq!(hold_name(&taken), None);
263        close(event);
264        close(hold_name(&taken).unwrap() as _);
265    }
266
267    #[cfg(target_os = "macos")]
268    #[test]
269    fn player_receives_the_uri_as_one_protocol_string_argument() {
270        let uri = "roblox-player:1+launchmode:play+gameinfo:ticket +placelauncherurl:x";
271        let command = player_command(Path::new("/Applications/Roblox.app/x"), uri);
272        let args: Vec<_> = command.get_args().collect();
273        assert_eq!(args, ["-protocolString", uri]);
274    }
275
276    #[cfg(target_os = "macos")]
277    #[test]
278    fn missing_semaphore_unlinks_without_error() {
279        let name = format!("/tbx-test-{}\0", std::process::id());
280        let name = std::ffi::CStr::from_bytes_with_nul(name.as_bytes()).unwrap();
281        assert_eq!(unlink_semaphore(name), Ok(()));
282    }
283
284    #[cfg(target_os = "macos")]
285    #[test]
286    fn existing_semaphore_is_removed_by_name() {
287        unsafe extern "C" {
288            fn sem_open(name: *const std::ffi::c_char, flags: std::ffi::c_int, ...) -> isize;
289            fn sem_close(semaphore: isize) -> std::ffi::c_int;
290        }
291        const O_CREAT: std::ffi::c_int = 0x200;
292        const SEM_FAILED: isize = -1;
293        let name = format!("/tbx-live-{}\0", std::process::id());
294        let name = std::ffi::CStr::from_bytes_with_nul(name.as_bytes()).unwrap();
295        // SAFETY: `name` is NUL-terminated and the variadic mode and value match `sem_open`.
296        let created = unsafe { sem_open(name.as_ptr(), O_CREAT, 0o600 as std::ffi::c_uint, 0) };
297        assert_ne!(created, SEM_FAILED);
298        assert_eq!(unlink_semaphore(name), Ok(()));
299        // SAFETY: `name` is NUL-terminated; opening without `O_CREAT` takes no variadic values.
300        let reopened = unsafe { sem_open(name.as_ptr(), 0) };
301        assert_eq!(reopened, SEM_FAILED);
302        // SAFETY: `created` is an open semaphore from `sem_open`.
303        unsafe { sem_close(created) };
304    }
305}