Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: fix some Clippy lints #1068

Merged
merged 13 commits into from
Oct 25, 2024
Merged
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ tracing-appender = { git = "https://github.com/CBenoit/tracing.git", rev = "4209
# == Safer unsafe == #
unsafe_op_in_unsafe_fn = "warn"
invalid_reference_casting = "warn"
pointer_structural_match = "warn"

# == Style, readability == #
elided_lifetimes_in_paths = "warn" # https://quinedot.github.io/rust-learning/dont-hide.html
Expand Down
2 changes: 1 addition & 1 deletion crates/devolutions-pedm-shared/src/policy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ impl Id {
let pat = Regex::new(ID_PATTERN)?;

pat.is_match(&id)
.then(|| Id(id))
.then_some(Id(id))
.ok_or_else(|| anyhow::anyhow!("Invalid ID"))
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/network-scanner/src/interfaces/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ impl From<ipconfig::Adapter> for NetworkInterface {
.prefixes()
.iter()
.map(|(ip, prefix)| super::InterfaceAddress {
ip: ip.clone(),
ip: *ip,
prefixlen: *prefix,
})
.collect(),
Expand Down
3 changes: 2 additions & 1 deletion crates/network-scanner/src/mdns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,9 @@ pub fn mdns_query_scan(
while let Ok(service_event) = receiver.recv_async().await {
debug!(?service_event);
if let ServiceEvent::ServiceResolved(msg) = service_event {
let fullname = msg.get_fullname();
let (device_name, protocol) =
parse_fullname(msg.get_fullname()).unwrap_or((msg.get_fullname().to_owned(), None));
parse_fullname(fullname).unwrap_or_else(|| (fullname.to_owned(), None));

let port = msg.get_port();

Expand Down
1 change: 1 addition & 0 deletions crates/transport/src/copy_bidirectional.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! Vendored code from:
//! - https://github.com/tokio-rs/tokio/blob/1f6fc55917f971791d76dc91cce795e656c0e0d3/tokio/src/io/util/copy.rs
//! - https://github.com/tokio-rs/tokio/blob/1f6fc55917f971791d76dc91cce795e656c0e0d3/tokio/src/io/util/copy_bidirectional.rs
//!
//! It is modified to allow us setting the `CopyBuffer` size instead of hardcoding 8k.
//! See <https://github.com/tokio-rs/tokio/issues/6454>.

Expand Down
2 changes: 1 addition & 1 deletion devolutions-agent/src/updater/detect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::updater::{Product, UpdaterError};
const GATEWAY_UPDATE_CODE: &str = "{db3903d6-c451-4393-bd80-eb9f45b90214}";

/// Get the installed version of a product.
pub fn get_installed_product_version(product: Product) -> Result<Option<DateVersion>, UpdaterError> {
pub(crate) fn get_installed_product_version(product: Product) -> Result<Option<DateVersion>, UpdaterError> {
match product {
Product::Gateway => get_instaled_product_version_winreg(GATEWAY_UPDATE_CODE),
}
Expand Down
2 changes: 1 addition & 1 deletion devolutions-agent/src/updater/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use thiserror::Error;
use crate::updater::Product;

#[derive(Debug, Error)]
pub enum UpdaterError {
pub(crate) enum UpdaterError {
#[error("queried `{product}` artifact hash has invalid format: `{hash}`")]
HashEncoding { product: Product, hash: String },
#[error("integrity check for downloaded `{product}` artifact has failed, expected hash: `{expected_hash}`, actual hash: `{actual_hash}`")]
Expand Down
2 changes: 1 addition & 1 deletion devolutions-agent/src/updater/integrity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use sha2::{Digest as _, Sha256};
use crate::updater::{UpdaterCtx, UpdaterError};

/// Validate the hash of downloaded artifact (Hash should be provided in encoded hex string).
pub fn validate_artifact_hash(ctx: &UpdaterCtx, data: &[u8], hash: &str) -> Result<(), UpdaterError> {
pub(crate) fn validate_artifact_hash(ctx: &UpdaterCtx, data: &[u8], hash: &str) -> Result<(), UpdaterError> {
let expected_hash_bytes = hex::decode(hash).map_err(|_| UpdaterError::HashEncoding {
product: ctx.product,
hash: hash.to_owned(),
Expand Down
12 changes: 6 additions & 6 deletions devolutions-agent/src/updater/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use tokio::io::AsyncWriteExt;
use crate::updater::UpdaterError;

/// Download binary file to memory
pub async fn download_binary(url: &str) -> Result<Vec<u8>, UpdaterError> {
pub(crate) async fn download_binary(url: &str) -> Result<Vec<u8>, UpdaterError> {
info!(%url, "Downloading file from network...");

let body = reqwest::get(url)
Expand All @@ -22,13 +22,13 @@ pub async fn download_binary(url: &str) -> Result<Vec<u8>, UpdaterError> {
}

/// Download UTF-8 file to memory
pub async fn download_utf8(url: &str) -> Result<String, UpdaterError> {
pub(crate) async fn download_utf8(url: &str) -> Result<String, UpdaterError> {
let bytes = download_binary(url).await?;
String::from_utf8(bytes).map_err(|_| UpdaterError::Utf8)
}

/// Save data to a temporary file
pub async fn save_to_temp_file(data: &[u8], extension: Option<&str>) -> Result<Utf8PathBuf, UpdaterError> {
pub(crate) async fn save_to_temp_file(data: &[u8], extension: Option<&str>) -> Result<Utf8PathBuf, UpdaterError> {
let uuid = uuid::Uuid::new_v4();

let file_name = match extension {
Expand All @@ -49,12 +49,12 @@ pub async fn save_to_temp_file(data: &[u8], extension: Option<&str>) -> Result<U
}

/// Mark file to be removed on next reboot.
pub fn remove_file_on_reboot(file_path: &Utf8Path) -> Result<(), UpdaterError> {
pub(crate) fn remove_file_on_reboot(file_path: &Utf8Path) -> Result<(), UpdaterError> {
remove_file_on_reboot_impl(file_path)
}

#[cfg(windows)]
pub fn remove_file_on_reboot_impl(file_path: &Utf8Path) -> Result<(), UpdaterError> {
pub(crate) fn remove_file_on_reboot_impl(file_path: &Utf8Path) -> Result<(), UpdaterError> {
use windows::core::HSTRING;
use windows::Win32::Storage::FileSystem::{MoveFileExW, MOVEFILE_DELAY_UNTIL_REBOOT};

Expand All @@ -70,7 +70,7 @@ pub fn remove_file_on_reboot_impl(file_path: &Utf8Path) -> Result<(), UpdaterErr
}

#[cfg(not(windows))]
pub fn impl_remove_file_on_reboot_impl(_file_path: &Utf8Path) -> Result<(), UpdaterError> {
pub(crate) fn impl_remove_file_on_reboot_impl(_file_path: &Utf8Path) -> Result<(), UpdaterError> {
// NOTE: On UNIX-like platforms /tmp folder is used which is cleared by OS automatically.
Ok(())
}
12 changes: 6 additions & 6 deletions devolutions-agent/src/updater/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ use package::{install_package, validate_package};
use productinfo::DEVOLUTIONS_PRODUCTINFO_URL;
use security::set_file_dacl;

pub use error::UpdaterError;
pub use product::Product;
pub(crate) use error::UpdaterError;
pub(crate) use product::Product;

const UPDATE_JSON_WATCH_INTERVAL: Duration = Duration::from_secs(3);

Expand All @@ -48,12 +48,12 @@ struct UpdateOrder {
hash: String,
}

pub struct UpdaterTask {
pub(crate) struct UpdaterTask {
conf_handle: ConfHandle,
}

impl UpdaterTask {
pub fn new(conf_handle: ConfHandle) -> Self {
pub(crate) fn new(conf_handle: ConfHandle) -> Self {
Self { conf_handle }
}
}
Expand All @@ -71,7 +71,7 @@ impl Task for UpdaterTask {
let update_file_path = init_update_json().await?;

let file_change_notification = Arc::new(tokio::sync::Notify::new());
let file_change_tx = file_change_notification.clone();
let file_change_tx = Arc::clone(&file_change_notification);

let mut notify_debouncer =
notify_debouncer_mini::new_debouncer(UPDATE_JSON_WATCH_INTERVAL, move |result| match result {
Expand Down Expand Up @@ -169,7 +169,7 @@ async fn update_product(conf: ConfHandle, product: Product, order: UpdateOrder)

install_package(&ctx, &package_path)
.await
.context("Failed to install package")?;
.context("failed to install package")?;

info!(%product, "Product updated to v{target_version}!");

Expand Down
4 changes: 2 additions & 2 deletions devolutions-agent/src/updater/package.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ const DEVOLUTIONS_CERT_THUMBPRINTS: &[&str] = &[
"8db5a43bb8afe4d2ffb92da9007d8997a4cc4e13",
];

pub async fn install_package(ctx: &UpdaterCtx, path: &Utf8Path) -> Result<(), UpdaterError> {
pub(crate) async fn install_package(ctx: &UpdaterCtx, path: &Utf8Path) -> Result<(), UpdaterError> {
match ctx.product {
Product::Gateway => install_msi(ctx, path).await,
}
Expand Down Expand Up @@ -100,7 +100,7 @@ fn ensure_enough_rights() -> Result<(), UpdaterError> {
Ok(())
}

pub fn validate_package(ctx: &UpdaterCtx, path: &Utf8Path) -> Result<(), UpdaterError> {
pub(crate) fn validate_package(ctx: &UpdaterCtx, path: &Utf8Path) -> Result<(), UpdaterError> {
match ctx.product {
Product::Gateway => validate_msi(ctx, path),
}
Expand Down
8 changes: 4 additions & 4 deletions devolutions-agent/src/updater/product.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::updater::productinfo::GATEWAY_PRODUCT_ID;

/// Product IDs to track updates for
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Product {
pub(crate) enum Product {
Gateway,
}

Expand All @@ -31,19 +31,19 @@ impl FromStr for Product {
}

impl Product {
pub fn get_update_info(self, update_json: &UpdateJson) -> Option<ProductUpdateInfo> {
pub(crate) fn get_update_info(self, update_json: &UpdateJson) -> Option<ProductUpdateInfo> {
match self {
Product::Gateway => update_json.gateway.clone(),
}
}

pub const fn get_productinfo_id(self) -> &'static str {
pub(crate) const fn get_productinfo_id(self) -> &'static str {
match self {
Product::Gateway => GATEWAY_PRODUCT_ID,
}
}

pub const fn get_package_extension(self) -> &'static str {
pub(crate) const fn get_package_extension(self) -> &'static str {
match self {
Product::Gateway => "msi",
}
Expand Down
6 changes: 3 additions & 3 deletions devolutions-agent/src/updater/productinfo/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ use std::str::FromStr;
use crate::updater::UpdaterError;

#[derive(Debug, Clone, Default)]
pub struct ProductInfo {
pub(crate) struct ProductInfo {
pub version: String,
pub hash: String,
pub url: String,
}

pub struct ProductInfoDb {
pub(crate) struct ProductInfoDb {
pub records: HashMap<String, ProductInfo>,
}

Expand Down Expand Up @@ -51,7 +51,7 @@ impl FromStr for ProductInfoDb {

impl ProductInfoDb {
/// Get product information by product ID
pub fn get(&self, product_id: &str) -> Option<&ProductInfo> {
pub(crate) fn get(&self, product_id: &str) -> Option<&ProductInfo> {
self.records.get(product_id)
}
}
Expand Down
8 changes: 4 additions & 4 deletions devolutions-agent/src/updater/productinfo/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
mod db;

pub const DEVOLUTIONS_PRODUCTINFO_URL: &str = "https://devolutions.net/productinfo.htm";
pub(crate) const DEVOLUTIONS_PRODUCTINFO_URL: &str = "https://devolutions.net/productinfo.htm";

#[cfg(windows)]
pub const GATEWAY_PRODUCT_ID: &str = "Gatewaybin";
pub(crate) const GATEWAY_PRODUCT_ID: &str = "Gatewaybin";
#[cfg(not(windows))]
pub const GATEWAY_PRODUCT_ID: &str = "GatewaybinDebX64";
pub(crate) const GATEWAY_PRODUCT_ID: &str = "GatewaybinDebX64";

pub use db::ProductInfoDb;
pub(crate) use db::ProductInfoDb;
4 changes: 2 additions & 2 deletions devolutions-agent/src/updater/security.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,10 @@ use crate::updater::UpdaterError;
/// - NETWORK SERVICE: Write, Read (Allow Devolutions Gateway service to update the file)
/// - Administrators: Full control
/// - Users: Read
pub const UPDATE_JSON_DACL: &str = "D:PAI(A;;FA;;;SY)(A;;0x1201bf;;;NS)(A;;FA;;;BA)(A;;FR;;;BU)";
pub(crate) const UPDATE_JSON_DACL: &str = "D:PAI(A;;FA;;;SY)(A;;0x1201bf;;;NS)(A;;FA;;;BA)(A;;FR;;;BU)";

/// Set DACL (Discretionary Access Control List) on a specified file.
pub fn set_file_dacl(file_path: &Utf8Path, acl: &str) -> Result<(), UpdaterError> {
pub(crate) fn set_file_dacl(file_path: &Utf8Path, acl: &str) -> Result<(), UpdaterError> {
use windows::core::HSTRING;
use windows::Win32::Foundation::{LocalFree, ERROR_SUCCESS, FALSE, HLOCAL};
use windows::Win32::Security::Authorization::{
Expand Down
4 changes: 2 additions & 2 deletions devolutions-agent/src/updater/uuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const UUID_ALPHABET: &[char] = &[
/// for upgrade code table.
///
/// e.g.: `{82318d3c-811f-4d5d-9a82-b7c31b076755}` => `C3D81328F118D5D4A9287B3CB1707655`
pub fn uuid_to_reversed_hex(uuid: &str) -> Result<String, UpdaterError> {
pub(crate) fn uuid_to_reversed_hex(uuid: &str) -> Result<String, UpdaterError> {
const IGNORED_CHARS: &[char] = &['-', '{', '}'];

let hex_chars = uuid
Expand Down Expand Up @@ -48,7 +48,7 @@ pub fn uuid_to_reversed_hex(uuid: &str) -> Result<String, UpdaterError> {
/// Converts reversed hex UUID back to standard Windows Registry format (upper case letters).
///
/// e.g.: `C3D81328F118D5D4A9287B3CB1707655` => `{82318d3c-811f-4d5d-9a82-b7c31b076755}`
pub fn reversed_hex_to_uuid(mut hex: &str) -> Result<String, UpdaterError> {
pub(crate) fn reversed_hex_to_uuid(mut hex: &str) -> Result<String, UpdaterError> {
if hex.len() != 32 || hex.chars().any(|ch| !UUID_ALPHABET.contains(&ch)) {
return Err(UpdaterError::Uuid { uuid: hex.to_string() });
}
Expand Down
2 changes: 1 addition & 1 deletion devolutions-gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ fn main() -> anyhow::Result<()> {
.context("failed to register service")?;
} else {
let conf_handle = ConfHandle::init().context("unable to initialize configuration")?;
let mut service = GatewayService::load(conf_handle).context("Service loading failed")?;
let mut service = GatewayService::load(conf_handle).context("service loading failed")?;

service
.start()
Expand Down
11 changes: 2 additions & 9 deletions devolutions-session/src/dvc.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
//! WIP: This file is copied from MSRDPEX project

use crate::config::ConfHandle;
use windows::core::PCSTR;
use windows::Win32::Foundation::{
DuplicateHandle, GetLastError, DUPLICATE_SAME_ACCESS, ERROR_IO_PENDING, HANDLE, WIN32_ERROR,
Expand All @@ -15,16 +14,10 @@ use windows::Win32::System::IO::{GetOverlappedResult, OVERLAPPED};

const CHANNEL_PDU_LENGTH: usize = 1024;

pub fn loop_dvc(config: ConfHandle) {
if !config.get_conf().debug.enable_unstable {
debug!("DVC loop is disabled");
return;
}

pub fn loop_dvc() {
info!("Starting DVC loop");

let channel_name = "DvcSample";
match open_virtual_channel(channel_name) {
match open_virtual_channel("DvcSample") {
Ok(h_file) => {
info!("Virtual channel opened");

Expand Down
6 changes: 2 additions & 4 deletions devolutions-session/src/log.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::config::ConfHandle;
use crate::config::Conf;
use devolutions_log::{LoggerGuard, StaticLogConfig};

pub(crate) struct SessionLog;
Expand All @@ -9,9 +9,7 @@ impl StaticLogConfig for SessionLog {
const LOG_FILE_PREFIX: &'static str = "session";
}

pub fn init_log(config: ConfHandle) -> LoggerGuard {
let conf = config.get_conf();

pub fn init_log(conf: &Conf) -> LoggerGuard {
devolutions_log::init::<SessionLog>(
&conf.log_file,
conf.verbosity_profile.to_log_filter(),
Expand Down
16 changes: 12 additions & 4 deletions devolutions-session/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,17 +17,25 @@ use std::sync::mpsc;
fn main() -> anyhow::Result<()> {
// Ensure per-user data dir exists.

std::fs::create_dir_all(get_data_dir()).context("Failed to create data directory")?;
std::fs::create_dir_all(get_data_dir()).context("failed to create data directory")?;

let config = ConfHandle::init().context("Failed to initialize configuration")?;
let conf = ConfHandle::init()
.context("failed to initialize configuration")?
.get_conf();

let _logger_guard = init_log(config.clone());
let _logger_guard = init_log(&conf);

info!("Starting Devolutions Session");

// TMP: Copy-paste from MSRDPEX project for testing purposes.
#[cfg(windows)]
loop_dvc(config);
{
if conf.debug.enable_unstable {
loop_dvc();
} else {
debug!("DVC loop is disabled");
}
}

let (shutdown_tx, shutdown_rx) = mpsc::channel();

Expand Down
Loading
Loading