use core::ffi::c_void;
use core::fmt;
use core::ptr;
use std::io;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use std::thread;
use std::time::Duration;
use crate::{Client, Encoding, Version, WindowHandle, encoding, host, sys, worker};
const WM_MCOMMAND: u32 = sys::WM_USER + 200;
const WM_MEVALUATE: u32 = sys::WM_USER + 201;
const METHOD_EDITBOX: u16 = 1;
const METHOD_PLAIN_TEXT: u16 = 2;
const METHOD_FLOOD_PROTECTION: u16 = 4;
const METHOD_UNICODE: u16 = 8;
const METHOD_EXTENDED_ERRORS: u16 = 16;
const ERROR_DISABLED: usize = 64;
const MAP_BYTES: usize = 64 * 1024;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(5);
const V5_9: Version = Version::new(5, 90);
const V6_2: Version = Version::new(6, 20);
const V7_33: Version = Version::new(7, 33);
#[derive(Debug)]
#[non_exhaustive]
pub enum SendError {
Unsupported(&'static str),
NoWindow,
InvalidText,
TooLong {
len: usize,
max: usize,
},
Busy,
Exiting,
Timeout,
Disabled,
Failed {
code: Option<u32>,
},
System(io::Error),
}
impl fmt::Display for SendError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unsupported(why) => write!(f, "not supported by this mIRC version: {why}"),
Self::NoWindow => f.write_str("no mIRC window to send to"),
Self::InvalidText => f.write_str("text contains a NUL character"),
Self::TooLong { len, max } => write!(f, "text is {len} units long; the most is {max}"),
Self::Busy => f.write_str("mIRC's mapped file is in use by another program"),
Self::Exiting => f.write_str("mIRC is exiting"),
Self::Timeout => f.write_str("mIRC didn't answer in time"),
Self::Disabled => f.write_str("SendMessage is disabled in mIRC"),
Self::Failed { code: Some(code) } => write!(f, "mIRC reported a failure (code {code})"),
Self::Failed { code: None } => f.write_str("mIRC reported a failure"),
Self::System(error) => write!(f, "Windows error: {error}"),
}
}
}
impl std::error::Error for SendError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::System(error) => Some(error),
_ => None,
}
}
}
pub fn command(text: &str) -> Result<(), SendError> {
Command::new(text).send()
}
pub fn evaluate(text: &str) -> Result<String, SendError> {
Evaluate::new(text).send()
}
#[derive(Clone, Debug)]
#[must_use = "a Command does nothing until you call send()"]
pub struct Command {
text: String,
options: Options,
plain_text: bool,
flood_protection: bool,
}
impl Command {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
options: Options::default(),
plain_text: false,
flood_protection: false,
}
}
pub fn window(mut self, window: WindowHandle) -> Self {
self.options.window = Some(window);
self
}
pub fn plain_text(mut self) -> Self {
self.plain_text = true;
self
}
pub fn flood_protection(mut self) -> Self {
self.flood_protection = true;
self
}
pub fn event_id(mut self, event_id: u16) -> Self {
self.options.event_id = Some(event_id);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.options.timeout = timeout;
self
}
pub fn send(&self) -> Result<(), SendError> {
let mut method = METHOD_EDITBOX;
if self.plain_text {
method |= METHOD_PLAIN_TEXT;
}
if self.flood_protection {
method |= METHOD_FLOOD_PROTECTION;
}
let text = command_text(&self.text, self.plain_text);
send(WM_MCOMMAND, method, &text, &self.options, false).map(drop)
}
}
fn command_text(text: &str, plain_text: bool) -> std::borrow::Cow<'_, str> {
if plain_text || text.starts_with('/') {
text.into()
} else {
format!("/{text}").into()
}
}
#[derive(Clone, Debug)]
#[must_use = "an Evaluate does nothing until you call send()"]
pub struct Evaluate {
text: String,
options: Options,
}
impl Evaluate {
pub fn new(text: impl Into<String>) -> Self {
Self {
text: text.into(),
options: Options::default(),
}
}
pub fn window(mut self, window: WindowHandle) -> Self {
self.options.window = Some(window);
self
}
pub fn event_id(mut self, event_id: u16) -> Self {
self.options.event_id = Some(event_id);
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.options.timeout = timeout;
self
}
pub fn send(&self) -> Result<String, SendError> {
send(WM_MEVALUATE, 0, &self.text, &self.options, true).map(Option::unwrap_or_default)
}
}
#[derive(Clone, Debug)]
struct Options {
window: Option<WindowHandle>,
event_id: Option<u16>,
timeout: Duration,
}
impl Default for Options {
fn default() -> Self {
Self {
window: None,
event_id: None,
timeout: DEFAULT_TIMEOUT,
}
}
}
fn send(
message: u32,
method: u16,
text: &str,
options: &Options,
read_result: bool,
) -> Result<Option<String>, SendError> {
let host = host();
let version = host.version();
if version < V5_9 {
return Err(SendError::Unsupported(
"SendMessage needs mIRC 5.9 or later",
));
}
if options.event_id.is_some() && version < V7_33 {
return Err(SendError::Unsupported(
"an event context needs mIRC 7.33 or later",
));
}
let window = options.window.unwrap_or(host.main_window());
if window.is_null() {
return Err(SendError::NoWindow);
}
if !window.is_current_thread() && worker::is_exiting() {
return Err(SendError::Exiting);
}
let unicode = version >= Version::V7_0;
let text_encoding = if unicode {
Encoding::Utf16
} else {
Encoding::Ansi
};
let capacity = MAP_BYTES / text_encoding.unit_size();
check_text(text, text_encoding, capacity)?;
let extended_errors = version >= V7_33 && host.client() == Client::Mirc;
let mut method = method;
if unicode {
method |= METHOD_UNICODE;
}
if extended_errors {
method |= METHOD_EXTENDED_ERRORS;
}
let (mapping, index) = Mapping::acquire(version >= V6_2)?;
unsafe { encoding::write(text, mapping.view, capacity, text_encoding) };
let reply = mapping.send(
window,
message,
wparam(method, options.event_id),
index,
options.timeout,
)?;
outcome(reply, extended_errors)?;
Ok(read_result.then(|| unsafe { encoding::read(mapping.view, capacity, text_encoding) }))
}
fn check_text(text: &str, text_encoding: Encoding, capacity: usize) -> Result<(), SendError> {
if text.contains('\0') {
return Err(SendError::InvalidText);
}
let len = encoding::encoded_len(text, text_encoding).ok_or(SendError::InvalidText)?;
let max = capacity - 1; if len > max {
return Err(SendError::TooLong { len, max });
}
Ok(())
}
fn wparam(method: u16, event_id: Option<u16>) -> usize {
(u32::from(event_id.unwrap_or(0)) << 16 | u32::from(method)) as usize
}
fn outcome(reply: usize, extended_errors: bool) -> Result<(), SendError> {
if extended_errors {
match reply {
0 => Ok(()),
code if code & ERROR_DISABLED != 0 => Err(SendError::Disabled),
code => Err(SendError::Failed {
code: Some(code as u32),
}),
}
} else if reply != 0 {
Ok(())
} else {
Err(SendError::Failed { code: None })
}
}
fn next_index() -> u32 {
static SEED: OnceLock<u32> = OnceLock::new();
static NEXT: AtomicU32 = AtomicU32::new(0);
let seed = *SEED.get_or_init(|| {
let (ticks, pid) = unsafe { (sys::GetTickCount64(), sys::GetCurrentProcessId()) };
(ticks as u32) ^ pid.rotate_left(16) ^ (ptr::from_ref(&NEXT) as usize as u32)
});
index_from(seed.wrapping_add(NEXT.fetch_add(1, Ordering::Relaxed)))
}
fn index_from(n: u32) -> u32 {
1 + n % (i32::MAX as u32)
}
static SINGLE_NAME: Mutex<()> = Mutex::new(());
struct Mapping {
handle: *mut c_void,
view: *mut c_void,
_turn: Option<MutexGuard<'static, ()>>,
}
impl Mapping {
fn acquire(numbered: bool) -> Result<(Self, u32), SendError> {
if numbered {
for _ in 0..64 {
let index = next_index();
if let Some(mapping) = Self::create_new(&format!("mIRC{index}"))? {
return Ok((mapping, index));
}
}
return Err(SendError::Busy);
}
let turn = SINGLE_NAME.lock().unwrap_or_else(PoisonError::into_inner);
for attempt in 0..50 {
if let Some(mut mapping) = Self::create_new("mIRC")? {
mapping._turn = Some(turn);
return Ok((mapping, 0));
}
if attempt < 49 {
thread::sleep(Duration::from_millis(10));
}
}
Err(SendError::Busy)
}
fn create_new(name: &str) -> Result<Option<Self>, SendError> {
let wide: Vec<u16> = name.encode_utf16().chain([0]).collect();
let (handle, error) = unsafe {
let handle = sys::CreateFileMappingW(
sys::INVALID_HANDLE_VALUE,
ptr::null(),
sys::PAGE_READWRITE,
0,
MAP_BYTES as u32,
wide.as_ptr(),
);
(handle, sys::GetLastError())
};
const ERROR_ACCESS_DENIED: u32 = 5;
if handle.is_null() {
return if error == ERROR_ACCESS_DENIED {
Ok(None)
} else {
Err(SendError::System(io::Error::from_raw_os_error(
error as i32,
)))
};
}
if error == sys::ERROR_ALREADY_EXISTS {
unsafe { sys::CloseHandle(handle) };
return Ok(None);
}
let view = unsafe {
sys::MapViewOfFile(
handle,
sys::FILE_MAP_READ | sys::FILE_MAP_WRITE,
0,
0,
MAP_BYTES,
)
};
if view.is_null() {
let error = io::Error::last_os_error();
unsafe { sys::CloseHandle(handle) };
return Err(SendError::System(error));
}
Ok(Some(Self {
handle,
view,
_turn: None,
}))
}
fn send(
&self,
window: WindowHandle,
message: u32,
wparam: usize,
index: u32,
timeout: Duration,
) -> Result<usize, SendError> {
let timeout_ms = u32::try_from(timeout.as_millis()).unwrap_or(u32::MAX);
let mut reply = 0usize;
let sent = unsafe {
sys::SendMessageTimeoutW(
window.as_raw(),
message,
wparam,
index as isize,
sys::SMTO_BLOCK | sys::SMTO_ABORTIFHUNG | sys::SMTO_ERRORONEXIT,
timeout_ms,
&mut reply,
)
};
if sent == 0 {
let error = unsafe { sys::GetLastError() };
return Err(match error {
0 | sys::ERROR_TIMEOUT => SendError::Timeout,
sys::ERROR_INVALID_WINDOW_HANDLE => SendError::NoWindow,
_ => SendError::System(io::Error::from_raw_os_error(error as i32)),
});
}
Ok(reply)
}
}
impl Drop for Mapping {
fn drop(&mut self) {
unsafe {
sys::UnmapViewOfFile(self.view);
sys::CloseHandle(self.handle);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashSet;
#[test]
fn wparam_puts_the_event_id_in_the_high_word() {
assert_eq!(wparam(METHOD_EDITBOX, None), 1);
assert_eq!(
wparam(METHOD_EDITBOX | METHOD_UNICODE, Some(0x1234)),
0x1234_0009
);
assert_eq!(wparam(0, Some(u16::MAX)), 0xFFFF_0000);
}
#[test]
fn commands_get_a_leading_slash() {
assert_eq!(command_text("echo -a hi", false), "/echo -a hi");
assert_eq!(command_text("/echo -a hi", false), "/echo -a hi");
assert_eq!(command_text("//echo -a $me", false), "//echo -a $me");
assert_eq!(command_text("hello there", true), "hello there");
}
#[test]
fn replies_are_read_by_version() {
assert!(outcome(1, false).is_ok());
assert!(matches!(
outcome(0, false),
Err(SendError::Failed { code: None })
));
assert!(outcome(0, true).is_ok());
assert!(matches!(
outcome(1, true),
Err(SendError::Failed { code: Some(1) })
));
assert!(matches!(
outcome(1 | 8, true),
Err(SendError::Failed { code: Some(9) })
));
assert!(matches!(outcome(1 | 64, true), Err(SendError::Disabled)));
}
#[test]
fn text_that_would_be_cut_short_is_rejected() {
assert!(check_text("echo hi", Encoding::Utf16, 100).is_ok());
assert!(matches!(
check_text("a\0b", Encoding::Utf16, 100),
Err(SendError::InvalidText)
));
assert!(check_text(&"a".repeat(99), Encoding::Utf16, 100).is_ok());
assert!(matches!(
check_text(&"a".repeat(100), Encoding::Utf16, 100),
Err(SendError::TooLong { len: 100, max: 99 })
));
assert!(matches!(
check_text(&"🦀".repeat(50), Encoding::Utf16, 100),
Err(SendError::TooLong { len: 100, max: 99 })
));
}
#[test]
fn mapped_file_numbers_are_positive_and_unique() {
assert_eq!(index_from(0), 1);
assert_eq!(index_from(i32::MAX as u32 - 1), i32::MAX as u32);
assert_eq!(index_from(i32::MAX as u32), 1);
let indexes: HashSet<u32> = (0..10_000).map(|_| next_index()).collect();
assert_eq!(indexes.len(), 10_000);
assert!(indexes.iter().all(|&n| (1..=i32::MAX as u32).contains(&n)));
}
#[test]
fn mapped_files_are_created_exclusively() {
let name = format!("mirust-test-{}", unsafe { sys::GetCurrentProcessId() });
let first = Mapping::create_new(&name)
.unwrap()
.expect("name should be free");
assert!(
Mapping::create_new(&name).unwrap().is_none(),
"second create must see it in use"
);
drop(first);
assert!(
Mapping::create_new(&name).unwrap().is_some(),
"free again once released"
);
}
#[test]
fn unsupported_without_sendmessage() {
assert!(matches!(command("echo hi"), Err(SendError::Unsupported(_))));
assert!(matches!(
evaluate("$version"),
Err(SendError::Unsupported(_))
));
}
}