Skip to content

Commit

Permalink
refactors from userprocess branch
Browse files Browse the repository at this point in the history
  • Loading branch information
F0903 committed Sep 12, 2024
1 parent df2b0a9 commit 61502a9
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 62 deletions.
10 changes: 5 additions & 5 deletions shared/src/pipe/client.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{Pipe, Result, LOGGER, PIPE_PATH_ROOT};
use crate::{
stream::{HandleStream, HandleStreamMode},
stream::{FileStreamMode, FileStream},
util::get_last_win32_err,
winstr::to_win32_wstr,
winstr::Win32String,
};
use windows::Win32::{
Storage::FileSystem::{
Expand All @@ -17,7 +17,7 @@ const RETRYING_ATTEMPTS: u32 = 15;

pub struct Client;

impl<S: HandleStreamMode> Pipe<Client, S> {
impl<S: FileStreamMode> Pipe<Client, S> {
pub fn create_client_retrying(name: &str) -> Result<Self> {
let mut first_error = None;
for _ in 0..RETRYING_ATTEMPTS {
Expand All @@ -40,7 +40,7 @@ impl<S: HandleStreamMode> Pipe<Client, S> {
}

pub fn create_client(name: &str) -> Result<Self> {
let pipe_name = to_win32_wstr(&format!("{}{}", PIPE_PATH_ROOT, name));
let pipe_name = Win32String::from_str(&format!("{}{}", PIPE_PATH_ROOT, name));
let access_rights = S::as_generic_access_rights();
LOGGER.debug(format!(
"Got following access rights for client pipe: {}",
Expand All @@ -65,7 +65,7 @@ impl<S: HandleStreamMode> Pipe<Client, S> {
unsafe { SetNamedPipeHandleState(pipe, Some(&PIPE_READMODE_MESSAGE), None, None)? };

Ok(Self {
stream: HandleStream::create(pipe),
stream: FileStream::create(pipe),
mode: std::marker::PhantomData,
})
}
Expand Down
12 changes: 6 additions & 6 deletions shared/src/pipe/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pub use server::Server;

use crate::{
logging::Logger,
stream::{HandleStream, HandleStreamMode},
stream::{FileStream, FileStreamMode},
};
use std::{
fmt::Debug,
Expand All @@ -22,8 +22,8 @@ pub const PIPE_NAME: &str = "AutoPowerProxy";

static LOGGER: Logger = Logger::new("pipe", "autopower_shared");

pub struct Pipe<M, S: HandleStreamMode> {
stream: HandleStream<S>,
pub struct Pipe<M, S: FileStreamMode> {
stream: FileStream<S>,
mode: std::marker::PhantomData<M>,
}

Expand Down Expand Up @@ -63,8 +63,8 @@ impl<M> std::io::Write for Pipe<M, stream::Write> {
}
}

impl<M, S: HandleStreamMode> Pipe<M, S> {
pub fn get_stream(&self) -> &HandleStream<S> {
impl<M, S: FileStreamMode> Pipe<M, S> {
pub fn get_stream(&self) -> &FileStream<S> {
&self.stream
}

Expand All @@ -74,7 +74,7 @@ impl<M, S: HandleStreamMode> Pipe<M, S> {
}
}

impl<M, S: HandleStreamMode> Drop for Pipe<M, S> {
impl<M, S: FileStreamMode> Drop for Pipe<M, S> {
fn drop(&mut self) {
LOGGER.debug("Dropping pipe...");
self.close().unwrap();
Expand Down
10 changes: 5 additions & 5 deletions shared/src/pipe/server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use super::{Pipe, Result, PIPE_BUFFER_SIZE, PIPE_PATH_ROOT};
use crate::{
stream::{HandleStream, HandleStreamMode},
stream::{FileStreamMode, FileStream},
util::get_last_win32_err,
winstr::to_win32_wstr,
winstr::Win32String,
};
use windows::Win32::{
Security::{
Expand All @@ -18,7 +18,7 @@ use windows::Win32::{

pub struct Server;

impl<S: HandleStreamMode> Pipe<Server, S> {
impl<S: FileStreamMode> Pipe<Server, S> {
fn get_security_descriptor() -> Result<SECURITY_DESCRIPTOR> {
let mut security_desc = SECURITY_DESCRIPTOR::default();
let p_security_desc =
Expand All @@ -40,7 +40,7 @@ impl<S: HandleStreamMode> Pipe<Server, S> {
lpSecurityDescriptor: (&mut security_desc as *mut SECURITY_DESCRIPTOR).cast(),
};

let pipe_name = to_win32_wstr(&format!("{}{}", PIPE_PATH_ROOT, name));
let pipe_name = Win32String::from_str(&format!("{}{}", PIPE_PATH_ROOT, name));
let pipe = unsafe {
CreateNamedPipeW(
pipe_name.get_const(),
Expand All @@ -59,7 +59,7 @@ impl<S: HandleStreamMode> Pipe<Server, S> {
}

Ok(Self {
stream: HandleStream::create(pipe),
stream: FileStream::create(pipe),
mode: std::marker::PhantomData,
})
}
Expand Down
8 changes: 4 additions & 4 deletions shared/src/stream/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ use windows::Win32::{

use crate::Result;

pub trait HandleStreamMode {
pub trait FileStreamMode {
fn as_generic_access_rights() -> u32;
fn as_pipe_access_rights() -> FILE_FLAGS_AND_ATTRIBUTES;
}

pub struct HandleStream<M: HandleStreamMode> {
pub struct FileStream<M: FileStreamMode> {
handle: HANDLE,
mode: std::marker::PhantomData<M>,
}

impl<M: HandleStreamMode> HandleStream<M> {
impl<M: FileStreamMode> FileStream<M> {
pub fn get_raw_handle(&self) -> HANDLE {
self.handle
}
Expand All @@ -39,7 +39,7 @@ impl<M: HandleStreamMode> HandleStream<M> {
}
}

impl<M: HandleStreamMode> Drop for HandleStream<M> {
impl<M: FileStreamMode> Drop for FileStream<M> {
fn drop(&mut self) {
self.close().unwrap();
}
Expand Down
8 changes: 4 additions & 4 deletions shared/src/stream/reader.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::logging::Logger;

use super::{HandleStream, HandleStreamMode};
use super::{FileStream, FileStreamMode};
use windows::Win32::{
Foundation::GENERIC_READ,
Storage::FileSystem::{ReadFile, PIPE_ACCESS_INBOUND},
Expand All @@ -9,7 +9,7 @@ use windows::Win32::{
static LOGGER: Logger = Logger::new("stream_reader", "autopower_shared");

pub struct Read;
impl HandleStreamMode for Read {
impl FileStreamMode for Read {
fn as_generic_access_rights() -> u32 {
GENERIC_READ.0
}
Expand All @@ -19,9 +19,9 @@ impl HandleStreamMode for Read {
}
}

impl HandleStream<Read> {}
impl FileStream<Read> {}

impl std::io::Read for HandleStream<Read> {
impl std::io::Read for FileStream<Read> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let mut bytes_read = 0;
LOGGER.debug("Reading from file handle... (blocking)");
Expand Down
8 changes: 4 additions & 4 deletions shared/src/stream/writer.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::{HandleStream, HandleStreamMode};
use super::{FileStreamMode, FileStream};
use windows::Win32::{
Foundation::GENERIC_WRITE,
Storage::FileSystem::{WriteFile, PIPE_ACCESS_OUTBOUND},
};

pub struct Write;
impl HandleStreamMode for Write {
impl FileStreamMode for Write {
fn as_generic_access_rights() -> u32 {
GENERIC_WRITE.0
}
Expand All @@ -15,9 +15,9 @@ impl HandleStreamMode for Write {
}
}

impl HandleStream<Write> {}
impl FileStream<Write> {}

impl std::io::Write for HandleStream<Write> {
impl std::io::Write for FileStream<Write> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
let mut bytes_written = 0;
unsafe { WriteFile(self.handle, Some(buf), Some(&mut bytes_written), None)? };
Expand Down
10 changes: 5 additions & 5 deletions shared/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use std::{ffi::OsStr, path::PathBuf};
use std::{ffi::OsString, os::windows::ffi::OsStringExt, path::PathBuf};

use windows::{
core::PWSTR,
Win32::{
Foundation::GetLastError,
System::{
Diagnostics::Debug::{FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM},
LibraryLoader::GetModuleFileNameA,
LibraryLoader::GetModuleFileNameW,
},
},
};
Expand All @@ -33,17 +33,17 @@ pub fn get_last_win32_err() -> super::Result<String> {
pub fn get_process_exe_path() -> super::Result<PathBuf> {
let mut buf = [0; 512];
unsafe {
let count = GetModuleFileNameA(None, &mut buf);
let count = GetModuleFileNameW(None, &mut buf);
let count_usize = count as usize;
if count_usize == buf.len() {
return Err("Process path is too long!".into());
}
if buf[count_usize] != b'\0' {
if buf[count_usize] != 0 {
return Err(
"Process path buffer did not end with a null terminator, possible overflow.".into(),
);
}
let os_str = OsStr::from_encoded_bytes_unchecked(&buf[0..(count_usize)]);
let os_str = OsString::from_wide(&buf[0..(count_usize)]);
Ok(PathBuf::from(os_str))
}
}
58 changes: 44 additions & 14 deletions shared/src/winstr.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,40 @@
use std::{ffi::OsStr, os::windows::ffi::OsStrExt, path::PathBuf};

use windows::core::{HSTRING, PCWSTR, PWSTR};

pub struct Win32StrPtr<T> {
fn get_nullterminated_utf16_from_utf8(input: &str) -> Vec<u16> {
input
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>()
}

pub fn to_h_string(input: &str) -> super::Result<HSTRING> {
let data = get_nullterminated_utf16_from_utf8(input);
let str = HSTRING::from_wide(&data)?;
Ok(str)
}

pub struct Win32String<T> {
data: Vec<T>,
}

impl Win32StrPtr<u16> {
impl Win32String<u16> {
pub fn from_osstr(input: &OsStr) -> Win32String<u16> {
let mut buf = Vec::new();
buf.extend(input.encode_wide());
Self::from_buffer(buf)
}

pub fn from_str(input: &str) -> Win32String<u16> {
let data = get_nullterminated_utf16_from_utf8(input);
Self::from_buffer(data)
}

pub fn push(&mut self, input: impl Into<Win32String<u16>>) {
self.data.extend(input.into().data);
}

pub fn get_mut(&mut self) -> PWSTR {
PWSTR(self.data.as_ptr() as *mut u16)
}
Expand All @@ -18,20 +48,20 @@ impl Win32StrPtr<u16> {
}
}

fn get_nullterminated_utf16_from_utf8(input: &str) -> Vec<u16> {
input
.encode_utf16()
.chain(std::iter::once(0))
.collect::<Vec<_>>()
impl From<&str> for Win32String<u16> {
fn from(value: &str) -> Self {
Self::from_str(value)
}
}

pub fn to_win32_wstr(input: &str) -> Win32StrPtr<u16> {
let data = get_nullterminated_utf16_from_utf8(input);
Win32StrPtr::from_buffer(data)
impl From<&OsStr> for Win32String<u16> {
fn from(value: &OsStr) -> Self {
Self::from_osstr(value)
}
}

pub fn to_h_string(input: &str) -> super::Result<HSTRING> {
let data = get_nullterminated_utf16_from_utf8(input);
let str = HSTRING::from_wide(&data)?;
Ok(str)
impl From<PathBuf> for Win32String<u16> {
fn from(value: PathBuf) -> Self {
Self::from_osstr(value.as_os_str())
}
}
11 changes: 0 additions & 11 deletions src/services/handler_data.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,8 @@
use std::ffi::c_void;

use autopower_shared::logging::Logger;

//DEBUG REMOVE
static LOGGER: Logger = Logger::new("tmp_debug_handler_data", "autopower");

pub struct HandlerData {
pub event_type: u32,
pub event_data: *mut c_void,
}
unsafe impl Send for HandlerData {}
unsafe impl Sync for HandlerData {}

impl Drop for HandlerData {
fn drop(&mut self) {
LOGGER.debug("dropping HandlerData...")
}
}
4 changes: 2 additions & 2 deletions src/services/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ mod power_service;

pub use power_service::PowerService;

use autopower_shared::{logging::Logger, winstr::to_win32_wstr};
use autopower_shared::{logging::Logger, winstr::Win32String};
use windows::{
core::PWSTR,
Win32::System::Services::{StartServiceCtrlDispatcherW, SERVICE_TABLE_ENTRYW},
Expand All @@ -24,7 +24,7 @@ pub fn start<S: WindowsService>() -> Result<()> {
}));

LOGGER.debug("Starting setup...");
let mut service_name = to_win32_wstr(S::get_name());
let mut service_name = Win32String::from_str(S::get_name());
LOGGER.debug(format!("Service name is: {}", unsafe {
service_name.get_const().display()
}));
Expand Down
4 changes: 2 additions & 2 deletions src/services/power_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::proxy::Proxy;
use autopower_shared::{
logging::Logger,
proxy_command::{PowerConfigSelection, ProxyCommand},
winstr::to_win32_wstr,
winstr::Win32String,
};
use std::{ffi::c_void, mem::ManuallyDrop};
use windows::{
Expand Down Expand Up @@ -195,7 +195,7 @@ impl WindowsService for PowerService {
Logger::set_panic_hook(&LOGGER);

let me: &'static mut Self = Box::leak(Box::new(Self::new()));
let service_name = to_win32_wstr(SERVICE_NAME);
let service_name = Win32String::from_str(SERVICE_NAME);
me.status_handle = Some(
match RegisterServiceCtrlHandlerExW(
service_name.get_const(),
Expand Down

0 comments on commit 61502a9

Please sign in to comment.