Skip to content

Commit

Permalink
Fixed a bunch of lints
Browse files Browse the repository at this point in the history
  • Loading branch information
pacmancoder committed Sep 2, 2024
1 parent 22f9a9f commit d0a6d57
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 33 deletions.
30 changes: 16 additions & 14 deletions crates/win-api-wrappers/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,7 +572,9 @@ impl ProcessEntry32Iterator {

// SAFETY: It is safe to zero out the structure as it is a simple POD type.
let mut process_entry: PROCESSENTRY32W = unsafe { mem::zeroed() };
process_entry.dwSize = mem::size_of::<PROCESSENTRY32W>().try_into().unwrap();
process_entry.dwSize = mem::size_of::<PROCESSENTRY32W>()
.try_into()
.expect("BUG: PROCESSENTRY32W size always fits in u32");

Ok(ProcessEntry32Iterator {
snapshot_handle,
Expand Down Expand Up @@ -625,7 +627,7 @@ impl ProcessEntry {
.szExeFile
.iter()
.position(|&c| c == 0)
.ok_or(anyhow!("Executable name null terminator not found"))?;
.ok_or_else(|| anyhow!("Executable name null terminator not found"))?;

let name = String::from_utf16(&self.0.szExeFile[..exe_name_length])
.map_err(|_| anyhow!("Invalid executable name UTF16 encoding"))?;
Expand All @@ -650,18 +652,15 @@ impl ProcessEnvironment {

impl Drop for ProcessEnvironment {
fn drop(&mut self) {
match self {
ProcessEnvironment::OsDefined(block) => {
// SAFETY: `block` is checked to be valid before free.
unsafe {
if !block.is_null() {
if let Err(err) = DestroyEnvironmentBlock(*block) {
warn!(%err, "Failed to destroy environment block");
}
if let ProcessEnvironment::OsDefined(block) = self {
// SAFETY: `block` is checked to be valid before free.
unsafe {
if !block.is_null() {
if let Err(err) = DestroyEnvironmentBlock(*block) {
warn!(%err, "Failed to destroy environment block");
}
};
}
_ => {}
}
};
}
}
}
Expand Down Expand Up @@ -689,10 +688,11 @@ pub fn create_process_as_user(
let mut environment: *mut c_void = ptr::null_mut();

if let Some(token) = token {
// SAFETY: Allocated memory will be freed by `ProcessEnvironment` destructor.
unsafe { CreateEnvironmentBlock(&mut environment, token.handle().raw(), false) }?;
}

ProcessEnvironment::OsDefined(environment as *const _)
ProcessEnvironment::OsDefined(environment.cast_const())
};

let mut command_line = command_line
Expand Down Expand Up @@ -743,6 +743,7 @@ pub fn create_process_as_user(

/// Starts new process in the specified session. Note that this function requires the current
/// process to have `SYSTEM`-level permissions. Use with caution.
#[allow(clippy::too_many_arguments)]
pub fn create_process_in_session(
session_id: u32,
application_name: Option<&Path>,
Expand Down Expand Up @@ -841,6 +842,7 @@ fn terminate_process_by_name_impl(process_name: &str, session_id: Option<u32>) -

match process {
Ok(process) => {
// SAFETY: `OpenProcess` ensures that the handle is valid.
unsafe {
if let Err(err) = TerminateProcess(process, 1) {
warn!(process_name, session_id, %err, "TerminateProcess failed");
Expand Down
4 changes: 2 additions & 2 deletions crates/win-api-wrappers/src/security/privilege.rs
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,11 @@ impl<'a> ScopedPrivileges<'a> {
}

pub fn token(&self) -> &Token {
&self.token
self.token
}

pub fn token_mut(&mut self) -> &mut Token {
&mut self.token
self.token
}
}

Expand Down
7 changes: 4 additions & 3 deletions devolutions-agent/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ mod win {
use std::{env, fs};

pub(super) fn embed_version_rc() {
let out_dir = env::var("OUT_DIR").unwrap();
let out_dir = env::var("OUT_DIR").expect("BUG: failed to get OUT_DIR");
let version_rc_file = format!("{}/version.rc", out_dir);
let version_rc_data = generate_version_rc();
fs::write(&version_rc_file, version_rc_data).unwrap();
fs::write(&version_rc_file, version_rc_data).expect("BUG: failed to write version.rc");

embed_resource::compile(&version_rc_file, embed_resource::NONE);
embed_resource::compile("resources.rc", embed_resource::NONE);
Expand All @@ -23,7 +23,8 @@ mod win {
let company_name = "Devolutions Inc.";
let legal_copyright = format!("Copyright 2020-2024 {}", company_name);

let version_number = env::var("CARGO_PKG_VERSION").unwrap() + ".0";
let mut version_number = env::var("CARGO_PKG_VERSION").expect("BUG: failed to get CARGO_PKG_VERSION");
version_number.push_str(".0");
let version_commas = version_number.replace('.', ",");
let file_description = output_name;
let file_version = version_number.clone();
Expand Down
1 change: 1 addition & 0 deletions devolutions-agent/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,6 +262,7 @@ pub mod dto {
pub enabled: bool,
}

#[allow(clippy::derivable_impls)] // Just to be explicit about the default values of the config.
impl Default for SessionHostConf {
fn default() -> Self {
Self { enabled: false }
Expand Down
16 changes: 10 additions & 6 deletions devolutions-agent/src/session_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,13 @@ impl Task for SessionManager {
}
AgentServiceEvent::SessionLogoff(id) => {
info!(%id, "Session logged off");
ctx.write().await.get_session_mut(&id).map(|session| {
if let Some(mut session) = ctx.write().await.get_session_mut(&id) {
// When a user logs off, host process will be stopped by the system;
// Console sessions could be reused for different users, therefore
// we should not remove the session from the list, but mark it as
// not yet ready (host will be started as soon as new user logs in).
session.set_host_ready(false);
});
}
}
_ => {
continue;
Expand All @@ -225,16 +225,16 @@ impl Task for SessionManager {

/// Starts Devolutions Host process in the target session.
fn try_start_host_process(ctx: &mut SessionManagerCtx, session: &Session) -> anyhow::Result<()> {
match ctx.get_session_mut(&session) {
match ctx.get_session_mut(session) {
Some(gw_session) => {
if is_host_running_in_session(&session)? {
if is_host_running_in_session(session)? {
gw_session.set_host_ready(true);
return Ok(());
}

info!(%session, "Starting host process in session");

match start_host_process(&session) {
match start_host_process(session) {
Ok(()) => {
info!(%session, "Host process started in session");
gw_session.set_host_ready(true);
Expand Down Expand Up @@ -285,7 +285,11 @@ fn start_host_process(session: &Session) -> anyhow::Result<()> {
let mut startup_info = StartupInfo::default();

// Run with GUI access
startup_info.show_window = SW_SHOW.0 as u16;
// NOTE: silent clippy warning, just to be more explicit about `show_window` value
#[allow(clippy::field_reassign_with_default)]
{
startup_info.show_window = u16::try_from(SW_SHOW.0).expect("BUG: SW_SHOW always fit u16");
}
startup_info.flags = STARTF_USESHOWWINDOW;
startup_info.desktop = WideString::from("WinSta0\\Default");

Expand Down
7 changes: 4 additions & 3 deletions devolutions-host/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ mod win {
use std::{env, fs};

pub(super) fn embed_version_rc() {
let out_dir = env::var("OUT_DIR").unwrap();
let out_dir = env::var("OUT_DIR").expect("BUG: failed to get OUT_DIR");
let version_rc_file = format!("{}/version.rc", out_dir);
let version_rc_data = generate_version_rc();
fs::write(&version_rc_file, version_rc_data).unwrap();
fs::write(&version_rc_file, version_rc_data).expect("BUG: failed to write version.rc");

embed_resource::compile(&version_rc_file, embed_resource::NONE);
}
Expand All @@ -22,7 +22,8 @@ mod win {
let company_name = "Devolutions Inc.";
let legal_copyright = format!("Copyright 2020-2024 {}", company_name);

let version_number = env::var("CARGO_PKG_VERSION").unwrap() + ".0";
let mut version_number = env::var("CARGO_PKG_VERSION").expect("BUG: failed to get CARGO_PKG_VERSION");
version_number.push_str(".0");
let version_commas = version_number.replace('.', ",");
let file_description = output_name;
let file_version = version_number.clone();
Expand Down
16 changes: 12 additions & 4 deletions devolutions-host/src/dvc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ pub fn loop_dvc(config: ConfHandle) {
info!("DVC loop finished");
}

#[allow(clippy::multiple_unsafe_ops_per_block)]
#[allow(clippy::undocumented_unsafe_blocks)]
fn open_virtual_channel(channel_name: &str) -> windows::core::Result<HANDLE> {
unsafe {
let channel_name_wide = PCSTR::from_raw(channel_name.as_ptr());
Expand Down Expand Up @@ -76,6 +78,8 @@ fn open_virtual_channel(channel_name: &str) -> windows::core::Result<HANDLE> {
}
}

#[allow(clippy::multiple_unsafe_ops_per_block)]
#[allow(clippy::undocumented_unsafe_blocks)]
fn write_virtual_channel_message(h_file: HANDLE, cb_size: u32, buffer: *const u8) -> windows::core::Result<()> {
unsafe {
let buffer_slice = std::slice::from_raw_parts(buffer, cb_size as usize);
Expand All @@ -86,6 +90,10 @@ fn write_virtual_channel_message(h_file: HANDLE, cb_size: u32, buffer: *const u8

#[allow(clippy::cast_possible_wrap)]
#[allow(clippy::cast_ptr_alignment)]
#[allow(clippy::ptr_offset_with_cast)]
#[allow(clippy::cast_possible_truncation)]
#[allow(clippy::multiple_unsafe_ops_per_block)]
#[allow(clippy::undocumented_unsafe_blocks)]
fn handle_virtual_channel(h_file: HANDLE) -> windows::core::Result<()> {
unsafe {
let mut read_buffer = [0u8; CHANNEL_PDU_LENGTH];
Expand All @@ -111,22 +119,22 @@ fn handle_virtual_channel(h_file: HANDLE) -> windows::core::Result<()> {
if let Err(e) = result {
if GetLastError() == WIN32_ERROR(ERROR_IO_PENDING.0) {
let _dw_status = WaitForSingleObject(h_event, INFINITE);
if !GetOverlappedResult(h_file, &mut overlapped, &mut dw_read, false).is_ok() {
if GetOverlappedResult(h_file, &overlapped, &mut dw_read, false).is_err() {
return Err(windows::core::Error::from_win32());
}
} else {
return Err(e);
}
}

println!("read {} bytes", dw_read);
info!("read {} bytes", dw_read);

let packet_size = dw_read as usize - std::mem::size_of::<CHANNEL_PDU_HEADER>();
let p_data = read_buffer
.as_ptr()
.offset(std::mem::size_of::<CHANNEL_PDU_HEADER>() as isize) as *const u8;
.offset(std::mem::size_of::<CHANNEL_PDU_HEADER>() as isize);

println!(
info!(
">> {}",
std::str::from_utf8(std::slice::from_raw_parts(p_data, packet_size)).unwrap_or("Invalid UTF-8")
);
Expand Down
2 changes: 1 addition & 1 deletion devolutions-host/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Start the program without a console window.
// It has no effect on platforms other than Windows.
#![windows_subsystem = "windows"]
#![cfg_attr(windows, windows_subsystem = "windows")]

#[macro_use]
extern crate tracing;
Expand Down

0 comments on commit d0a6d57

Please sign in to comment.