| 1 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 2 | use std::time::{Duration, Instant}; |
| 3 | |
| 4 | static ACTIVATION: AtomicBool = AtomicBool::new(false); |
| 5 | |
| 6 | const RETRY_INTERVAL: Duration = Duration::from_millis(200); |
| 7 | const RETRY_TIMEOUT: Duration = Duration::from_secs(15); |
| 8 | |
| 9 | #[derive(Debug, PartialEq, Eq)] |
| 10 | pub enum Claim { |
| 11 | Primary, |
| 12 | Forwarded, |
| 13 | } |
| 14 | |
| 15 | pub fn take_activation() -> bool { |
| 16 | ACTIVATION.swap(false, Ordering::AcqRel) |
| 17 | } |
| 18 | |
| 19 | pub fn claim(name: &str, wait_for_previous: bool) -> Claim { |
| 20 | let started = Instant::now(); |
| 21 | loop { |
| 22 | if platform::try_become_primary(name) { |
| 23 | return Claim::Primary; |
| 24 | } |
| 25 | if !wait_for_previous { |
| 26 | platform::notify_primary(name); |
| 27 | return Claim::Forwarded; |
| 28 | } |
| 29 | if started.elapsed() >= RETRY_TIMEOUT { |
| 30 | return Claim::Primary; |
| 31 | } |
| 32 | std::thread::sleep(RETRY_INTERVAL); |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | fn user_name() -> String { |
| 37 | std::env::var("USERNAME") |
| 38 | .or_else(|_| std::env::var("USER")) |
| 39 | .unwrap_or_default() |
| 40 | } |
| 41 | |
| 42 | #[cfg(windows)] |
| 43 | mod platform { |
| 44 | use std::fs::OpenOptions; |
| 45 | use std::sync::atomic::Ordering; |
| 46 | use std::time::Duration; |
| 47 | |
| 48 | use windows::Win32::Foundation::{ |
| 49 | ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError, |
| 50 | INVALID_HANDLE_VALUE, |
| 51 | }; |
| 52 | use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_INBOUND}; |
| 53 | use windows::Win32::System::Pipes::{ |
| 54 | ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS, |
| 55 | PIPE_TYPE_BYTE, PIPE_WAIT, |
| 56 | }; |
| 57 | use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow}; |
| 58 | use windows::core::PCWSTR; |
| 59 | |
| 60 | use super::{ACTIVATION, user_name}; |
| 61 | |
| 62 | const CONNECT_ATTEMPTS: u32 = 20; |
| 63 | const CONNECT_INTERVAL: Duration = Duration::from_millis(100); |
| 64 | |
| 65 | fn pipe_path(name: &str) -> String { |
| 66 | format!(r"\\.\pipe\{name}-{}", user_name()) |
| 67 | } |
| 68 | |
| 69 | pub fn try_become_primary(name: &str) -> bool { |
| 70 | let wide_path: Vec<u16> = pipe_path(name) |
| 71 | .encode_utf16() |
| 72 | .chain(std::iter::once(0)) |
| 73 | .collect(); |
| 74 | let handle = unsafe { |
| 75 | CreateNamedPipeW( |
| 76 | PCWSTR(wide_path.as_ptr()), |
| 77 | PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE, |
| 78 | PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, |
| 79 | 1, |
| 80 | 0, |
| 81 | 0, |
| 82 | 0, |
| 83 | None, |
| 84 | ) |
| 85 | }; |
| 86 | if handle == INVALID_HANDLE_VALUE { |
| 87 | let error = unsafe { GetLastError() }; |
| 88 | return error != ERROR_ACCESS_DENIED && error != ERROR_PIPE_BUSY; |
| 89 | } |
| 90 | let raw_handle = handle.0 as usize; |
| 91 | std::thread::spawn(move || { |
| 92 | let handle = windows::Win32::Foundation::HANDLE(raw_handle as *mut _); |
| 93 | loop { |
| 94 | let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok() |
| 95 | || matches!( |
| 96 | unsafe { GetLastError() }, |
| 97 | ERROR_PIPE_CONNECTED | ERROR_NO_DATA |
| 98 | ); |
| 99 | if connected { |
| 100 | ACTIVATION.store(true, Ordering::Release); |
| 101 | } else { |
| 102 | std::thread::sleep(CONNECT_INTERVAL); |
| 103 | } |
| 104 | let _ = unsafe { DisconnectNamedPipe(handle) }; |
| 105 | } |
| 106 | }); |
| 107 | true |
| 108 | } |
| 109 | |
| 110 | pub fn notify_primary(name: &str) { |
| 111 | let path = pipe_path(name); |
| 112 | let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) }; |
| 113 | for _ in 0..CONNECT_ATTEMPTS { |
| 114 | if OpenOptions::new().write(true).open(&path).is_ok() { |
| 115 | return; |
| 116 | } |
| 117 | std::thread::sleep(CONNECT_INTERVAL); |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | #[cfg(unix)] |
| 123 | mod platform { |
| 124 | use std::io::ErrorKind; |
| 125 | use std::os::unix::net::{UnixListener, UnixStream}; |
| 126 | use std::path::PathBuf; |
| 127 | use std::sync::atomic::Ordering; |
| 128 | |
| 129 | use super::{ACTIVATION, user_name}; |
| 130 | |
| 131 | pub(super) fn socket_path(name: &str) -> PathBuf { |
| 132 | let directory = std::env::var_os("XDG_RUNTIME_DIR") |
| 133 | .map(PathBuf::from) |
| 134 | .unwrap_or_else(std::env::temp_dir); |
| 135 | directory.join(format!("{name}-{}.sock", user_name())) |
| 136 | } |
| 137 | |
| 138 | enum Bound { |
| 139 | Listening(UnixListener), |
| 140 | Taken, |
| 141 | Unavailable, |
| 142 | } |
| 143 | |
| 144 | fn bind(path: &PathBuf) -> Bound { |
| 145 | match UnixListener::bind(path) { |
| 146 | Ok(listener) => Bound::Listening(listener), |
| 147 | Err(error) if error.kind() == ErrorKind::AddrInUse => { |
| 148 | if UnixStream::connect(path).is_ok() { |
| 149 | return Bound::Taken; |
| 150 | } |
| 151 | let _ = std::fs::remove_file(path); |
| 152 | UnixListener::bind(path).map_or(Bound::Unavailable, Bound::Listening) |
| 153 | } |
| 154 | Err(_) => Bound::Unavailable, |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | pub fn try_become_primary(name: &str) -> bool { |
| 159 | let listener = match bind(&socket_path(name)) { |
| 160 | Bound::Listening(listener) => listener, |
| 161 | Bound::Taken => return false, |
| 162 | Bound::Unavailable => return true, |
| 163 | }; |
| 164 | std::thread::spawn(move || { |
| 165 | for connection in listener.incoming() { |
| 166 | if connection.is_ok() { |
| 167 | ACTIVATION.store(true, Ordering::Release); |
| 168 | } |
| 169 | } |
| 170 | }); |
| 171 | true |
| 172 | } |
| 173 | |
| 174 | pub fn notify_primary(name: &str) { |
| 175 | let _ = UnixStream::connect(socket_path(name)); |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | #[cfg(test)] |
| 180 | mod tests { |
| 181 | use super::*; |
| 182 | |
| 183 | #[test] |
| 184 | fn second_claim_forwards_and_stale_socket_is_reclaimed() { |
| 185 | let name = format!("rusty-teams-test-{}", std::process::id()); |
| 186 | assert_eq!(claim(&name, false), Claim::Primary); |
| 187 | assert_eq!(claim(&name, false), Claim::Forwarded); |
| 188 | let started = Instant::now(); |
| 189 | while !take_activation() { |
| 190 | assert!(started.elapsed() < Duration::from_secs(1)); |
| 191 | std::thread::sleep(Duration::from_millis(10)); |
| 192 | } |
| 193 | assert!(!take_activation()); |
| 194 | |
| 195 | let stale_name = format!("{name}-stale"); |
| 196 | #[cfg(unix)] |
| 197 | { |
| 198 | let path = platform::socket_path(&stale_name); |
| 199 | drop(std::os::unix::net::UnixListener::bind(&path).unwrap()); |
| 200 | assert!(path.exists()); |
| 201 | } |
| 202 | assert_eq!(claim(&stale_name, false), Claim::Primary); |
| 203 | assert_eq!( |
| 204 | claim("missing-directory/rusty-teams", false), |
| 205 | Claim::Primary |
| 206 | ); |
| 207 | |
| 208 | #[cfg(unix)] |
| 209 | for leftover in [&name, &stale_name] { |
| 210 | let _ = std::fs::remove_file(platform::socket_path(leftover)); |
| 211 | } |
| 212 | } |
| 213 | } |