diff --git a/src/codec/rle.rs b/src/codec/rle.rs index ab909d0..5af6c7d 100644 --- a/src/codec/rle.rs +++ b/src/codec/rle.rs @@ -31,7 +31,7 @@ fn process_plane(input: &mut dyn Read, width: u32, height: u32, output: &mut [u8 replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; - if (revcode <= 47) && (revcode >= 16) { + if (16..=47).contains(&revcode) { replen = revcode; collen = 0; } @@ -57,20 +57,20 @@ fn process_plane(input: &mut dyn Read, width: u32, height: u32, output: &mut [u8 replen = code & 0xf; collen = (code >> 4) & 0xf; revcode = (replen << 4) | collen; - if (revcode <= 47) && (revcode >= 16) { + if (16..=47).contains(&revcode) { replen = revcode; collen = 0; } while collen > 0 { x = input.read_u8()?; if x & 1 != 0{ - x = x >> 1; - x = x + 1; + x >>= 1; + x += 1; color = -(x as i32) as i8; } else { - x = x >> 1; + x >>= 1; color = x as i8; } x = (output[(last_line + (indexw * 4)) as usize] as i32 + color as i32) as u8; @@ -227,7 +227,7 @@ pub fn rle_16_decompress(input: &[u8], width: usize, mut height: usize, output: while count > 0 { if x >= width { - if height <= 0 { + if height == 0 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "error during decompress"))) } x = 0; @@ -331,7 +331,7 @@ pub fn rle_16_decompress(input: &[u8], width: usize, mut height: usize, output: pub fn rgb565torgb32(input: &[u16], width: usize, height: usize) -> Vec { - let mut result_32_bpp = vec![0 as u8; width as usize * height as usize * 4]; + let mut result_32_bpp = vec![0_u8; width as usize * height as usize * 4]; for i in 0..height { for j in 0..width { let index = (i * width + j) as usize; diff --git a/src/core/capability.rs b/src/core/capability.rs index b84d261..bd67fd5 100644 --- a/src/core/capability.rs +++ b/src/core/capability.rs @@ -187,8 +187,8 @@ pub fn ts_general_capability_set(extra_flags: Option) -> Capability { "updateCapabilityFlag" => Check::new(U16::LE(0)), "remoteUnshareFlag" => Check::new(U16::LE(0)), "generalCompressionLevel" => Check::new(U16::LE(0)), - "refreshRectSupport" => 0 as u8, - "suppressOutputSupport" => 0 as u8 + "refreshRectSupport" => 0_u8, + "suppressOutputSupport" => 0_u8 ] } } @@ -219,8 +219,8 @@ pub fn ts_bitmap_capability_set(preferred_bits_per_pixel: Option, desktop_w "pad2octets" => U16::LE(0), "desktopResizeFlag" => U16::LE(0), "bitmapCompressionFlag" => Check::new(U16::LE(0x0001)), - "highColorFlags" => Check::new(0 as u8), - "drawingFlags" => 0 as u8, + "highColorFlags" => Check::new(0_u8), + "drawingFlags" => 0_u8, "multipleRectangleSupport" => Check::new(U16::LE(0x0001)), "pad2octetsB" => U16::LE(0) ] @@ -253,7 +253,7 @@ pub fn ts_order_capability_set(order_flags: Option) -> Capability { Capability { cap_type: CapabilitySetType::CapstypeOrder, message: component![ - "terminalDescriptor" => vec![0 as u8; 16], + "terminalDescriptor" => vec![0_u8; 16], "pad4octetsA" => U32::LE(0), "desktopSaveXGranularity" => U16::LE(1), "desktopSaveYGranularity" => U16::LE(20), @@ -261,7 +261,7 @@ pub fn ts_order_capability_set(order_flags: Option) -> Capability { "maximumOrderLevel" => U16::LE(1), "numberFonts" => U16::LE(0), "orderFlags" => U16::LE(order_flags.unwrap_or(OrderFlag::NEGOTIATEORDERSUPPORT as u16)), - "orderSupport" => vec![0 as u8; 32], + "orderSupport" => vec![0_u8; 32], "textFlags" => U16::LE(0), "orderSupportExFlags" => U16::LE(0), "pad4octetsB" => U32::LE(0), @@ -375,7 +375,7 @@ pub fn ts_input_capability_set(input_flags: Option, keyboard_layout: Option "keyboardType" => U32::LE(KeyboardType::Ibm101102Keys as u32), "keyboardSubType" => U32::LE(0), "keyboardFunctionKey" => U32::LE(12), - "imeFileName" => vec![0 as u8; 64] + "imeFileName" => vec![0_u8; 64] ] } } diff --git a/src/core/client.rs b/src/core/client.rs index 0216a41..d7e5ee9 100644 --- a/src/core/client.rs +++ b/src/core/client.rs @@ -348,4 +348,10 @@ impl Connector { self.use_nla = use_nla; self } +} + +impl Default for Connector { + fn default() -> Self { + Self::new() + } } \ No newline at end of file diff --git a/src/core/event.rs b/src/core/event.rs index 73d3a1d..fd78b51 100644 --- a/src/core/event.rs +++ b/src/core/event.rs @@ -67,7 +67,7 @@ impl BitmapEvent { // 32 bpp is straight forward Ok( if self.is_compress { - let mut result = vec![0 as u8; self.width as usize * self.height as usize * 4]; + let mut result = vec![0_u8; self.width as usize * self.height as usize * 4]; rle_32_decompress(&self.data, self.width as u32, self.height as u32, &mut result)?; result } else { @@ -78,11 +78,11 @@ impl BitmapEvent { 16 => { // 16 bpp is more consumer let result_16bpp = if self.is_compress { - let mut result = vec![0 as u16; self.width as usize * self.height as usize * 2]; + let mut result = vec![0_u16; self.width as usize * self.height as usize * 2]; rle_16_decompress(&self.data, self.width as usize, self.height as usize, &mut result)?; result } else { - let mut result = vec![0 as u16; self.width as usize * self.height as usize]; + let mut result = vec![0_u16; self.width as usize * self.height as usize]; for i in 0..self.height { for j in 0..self.width { let src = (((self.height - i - 1) * self.width + j) * 2) as usize; diff --git a/src/core/gcc.rs b/src/core/gcc.rs index 188f312..894cbab 100644 --- a/src/core/gcc.rs +++ b/src/core/gcc.rs @@ -223,11 +223,11 @@ pub fn client_core_data(parameter: Option) -> Component { "sasSequence" => U16::LE(Sequence::RnsUdSasDel as u16), "kbdLayout" => U32::LE(client_parameter.layout as u32), "clientBuild" => U32::LE(3790), - "clientName" => client_name.to_string().to_unicode(), + "clientName" => client_name.to_unicode(), "keyboardType" => U32::LE(KeyboardType::Ibm101102Keys as u32), "keyboardSubType" => U32::LE(0), "keyboardFnKeys" => U32::LE(12), - "imeFileName" => vec![0 as u8; 64], + "imeFileName" => vec![0_u8; 64], "postBeta2ColorDepth" => U16::LE(ColorDepth::RnsUdColor8BPP as u16), "clientProductId" => U16::LE(1), "serialNumber" => U32::LE(0), @@ -240,8 +240,8 @@ pub fn client_core_data(parameter: Option) -> Component { ), "earlyCapabilityFlags" => U16::LE(CapabilityFlag::RnsUdCsSupportErrinfoPDU as u16), "clientDigProductId" => vec![0; 64], - "connectionType" => 0 as u8, - "pad1octet" => 0 as u8, + "connectionType" => 0_u8, + "pad1octet" => 0_u8, "serverSelectedProtocol" => U32::LE(client_parameter.server_selected_protocol) ] } @@ -352,7 +352,7 @@ pub fn read_conference_create_response(cc_response: &mut dyn Read) -> RdpResult< break; } - let mut buffer = vec![0 as u8; (cast!(DataType::U16, header["length"])? - header.length() as u16) as usize]; + let mut buffer = vec![0_u8; (cast!(DataType::U16, header["length"])? - header.length() as u16) as usize]; sub.read_exact(&mut buffer)?; match MessageType::from(cast!(DataType::U16, header["type"])?) { @@ -377,7 +377,7 @@ pub fn read_conference_create_response(cc_response: &mut dyn Read) -> RdpResult< // All section are important Ok(ServerData{ - channel_ids: cast!(DataType::Trame, result[&MessageType::ScNet]["channelIdArray"])?.into_iter().map(|x| cast!(DataType::U16, x).unwrap()).collect(), + channel_ids: cast!(DataType::Trame, result[&MessageType::ScNet]["channelIdArray"])?.iter().map(|x| cast!(DataType::U16, x).unwrap()).collect(), rdp_version: Version::from(cast!(DataType::U32, result[&MessageType::ScCore]["rdpVersion"])?) }) } \ No newline at end of file diff --git a/src/core/global.rs b/src/core/global.rs index 27f02ca..976a6cd 100644 --- a/src/core/global.rs +++ b/src/core/global.rs @@ -80,8 +80,8 @@ fn ts_demand_active_pdu() -> PDU { /// /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/4e9722c3-ad83-43f5-af5a-529f73d88b48 fn ts_confirm_active_pdu(share_id: Option, source: Option>, capabilities_set: Option>) -> PDU { - let default_capabilities_set = capabilities_set.unwrap_or(Array::new(|| capability_set(None))); - let default_source = source.unwrap_or(vec![]); + let default_capabilities_set = capabilities_set.unwrap_or_else(|| Array::new(|| capability_set(None))); + let default_source = source.unwrap_or_default(); PDU { pdu_type: PDUType::PdutypeConfirmactivepdu, message: component![ @@ -113,16 +113,16 @@ fn ts_deactivate_all_pdu() -> PDU { /// All Data PDU share the same layout fn share_data_header(share_id: Option, pdu_type_2: Option, message: Option>) -> PDU { - let default_message = message.unwrap_or(vec![]); + let default_message = message.unwrap_or_default(); PDU { pdu_type: PDUType::PdutypeDatapdu, message: component![ "shareId" => U32::LE(share_id.unwrap_or(0)), - "pad1" => 0 as u8, - "streamId" => 1 as u8, + "pad1" => 0_u8, + "streamId" => 1_u8, "uncompressedLength" => DynOption::new(U16::LE(default_message.length() as u16 + 18), | size | MessageOption::Size("payload".to_string(), size.inner() as usize - 18)), "pduType2" => pdu_type_2.unwrap_or(PDUType2::Pdutype2ArcStatusPdu) as u8, - "compressedType" => 0 as u8, + "compressedType" => 0_u8, "compressedLength" => U16::LE(0), "payload" => default_message ] @@ -133,7 +133,7 @@ fn share_data_header(share_id: Option, pdu_type_2: Option, messag /// This is the main PDU payload format /// It use the share control header to dispatch between all PDU fn share_control_header(pdu_type: Option, pdu_source: Option, message: Option>) -> Component { - let default_message = message.unwrap_or(vec![]); + let default_message = message.unwrap_or_default(); component![ "totalLength" => DynOption::new(U16::LE(default_message.length() as u16 + 6), |total| MessageOption::Size("pduMessage".to_string(), total.inner() as usize - 6)), "pduType" => U16::LE(pdu_type.unwrap_or(PDUType::PdutypeDemandactivepdu) as u16), @@ -277,7 +277,7 @@ fn ts_font_map_pdu() -> DataPDU { /// Send input event as slow path fn ts_input_pdu_data(events: Option>) -> DataPDU { - let default_events = events.unwrap_or(Array::new(|| ts_input_event(None, None))); + let default_events = events.unwrap_or_else(|| Array::new(|| ts_input_event(None, None))); DataPDU { pdu_type: PDUType2::Pdutype2Input, message: component![ @@ -293,7 +293,7 @@ fn ts_input_event(message_type: Option, data: Option>) - component![ "eventTime" => U32::LE(0), "messageType" => U16::LE(message_type.unwrap_or(InputEventType::InputEventMouse) as u16), - "slowPathInputData" => data.unwrap_or(vec![]) + "slowPathInputData" => data.unwrap_or_default() ] } @@ -371,15 +371,15 @@ pub fn ts_keyboard_event(flags: Option, key_code: Option) -> TSInputEv /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/a1c4caa8-00ed-45bb-a06e-5177473766d3 fn ts_fp_update() -> Component { component![ - "updateHeader" => DynOption::new(0 as u8, |header| { - if (header >> 4) & 0x2 as u8 == 0 as u8 { + "updateHeader" => DynOption::new(0_u8, |header| { + if (header >> 4) & 0x2_u8 == 0_u8 { MessageOption::SkipField("compressionFlags".to_string()) } else { MessageOption::None } }), - "compressionFlags" => 0 as u8, + "compressionFlags" => 0_u8, "size" => DynOption::new(U16::LE(0), | size | MessageOption::Size("updateData".to_string(), size.inner() as usize)), "updateData" => Vec::::new() ] @@ -469,7 +469,7 @@ fn ts_fp_update_bitmap() -> FastPathUpdate { message: component![ "header" => Check::new(U16::LE(FastPathUpdateType::FastpathUpdatetypeBitmap as u16)), "numberRectangles" => U16::LE(0), - "rectangles" => Array::new(|| ts_bitmap_data()) + "rectangles" => Array::new(ts_bitmap_data) ] } } @@ -489,7 +489,7 @@ fn ts_colorpointerattribute() -> FastPathUpdate { "lengthXorMask" => DynOption::new(U16::LE(0), |length| MessageOption::Size("xorMaskData".to_string(), length.inner() as usize)), "xorMaskData" => Vec::::new(), "andMaskData" => Vec::::new(), - "pad" => Some(0 as u8) + "pad" => Some(0_u8) ] } } @@ -602,7 +602,7 @@ impl Client { self.share_id = Some(cast!(DataType::U32, pdu.message["shareId"])?); return Ok(true) } - return Ok(false) + Ok(false) } /// Read server synchronize pdu @@ -696,7 +696,7 @@ impl Client { fn read_fast_path(&mut self, stream: &mut dyn Read, mut callback: T) -> RdpResult<()> where T: FnMut(RdpEvent) { // it could be have one or more fast path payload - let mut fp_messages = Array::new(|| ts_fp_update()); + let mut fp_messages = Array::new(ts_fp_update); fp_messages.read(stream)?; for fp_message in fp_messages.inner().iter() { diff --git a/src/core/license.rs b/src/core/license.rs index be2974d..0ffad78 100644 --- a/src/core/license.rs +++ b/src/core/license.rs @@ -68,7 +68,7 @@ pub enum StateTransition { /// https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rdpbcgr/73170ca2-5f82-4a2d-9d1b-b439f3d8dadc fn preamble() -> Component { component![ - "bMsgtype" => 0 as u8, + "bMsgtype" => 0_u8, "flag" => Check::new(Preambule::PreambleVersion30 as u8), "wMsgSize" => DynOption::new(U16::LE(0), |size| MessageOption::Size("message".to_string(), size.inner() as usize - 4)), "message" => Vec::::new() diff --git a/src/core/mcs.rs b/src/core/mcs.rs index 1c2439e..dfa4f72 100644 --- a/src/core/mcs.rs +++ b/src/core/mcs.rs @@ -3,7 +3,7 @@ use crate::core::tpkt; use crate::model::error::{RdpResult, Error, RdpError, RdpErrorKind}; use crate::core::gcc::{KeyboardLayout, client_core_data, ClientData, ServerData, client_security_data, client_network_data, block_header, write_conference_create_request, MessageType, read_conference_create_response, Version}; use crate::model::data::{Trame, to_vec, Message, DataType, U16}; -use crate::nla::asn1::{Sequence, ImplicitTag, OctetString, Enumerate, ASN1Type, Integer, to_der, from_ber}; +use crate::nla::asn1::{Sequence, ImplicitTag, OctetString, ASN1Type, to_der, from_ber}; use yasna::{Tag}; use std::io::{Write, Read, BufRead, Cursor}; use crate::core::per; @@ -45,13 +45,13 @@ fn domain_parameters(max_channel_ids: u32, maw_user_ids: u32, max_token_ids: u32 /// http://www.itu.int/rec/T-REC-T.125-199802-I/en page 25 fn connect_initial(user_data: Option) -> ImplicitTag { ImplicitTag::new(Tag::application(101), sequence![ - "callingDomainSelector" => vec![1 as u8] as OctetString, - "calledDomainSelector" => vec![1 as u8] as OctetString, + "callingDomainSelector" => vec![1_u8] as OctetString, + "calledDomainSelector" => vec![1_u8] as OctetString, "upwardFlag" => true, "targetParameters" => domain_parameters(34, 2, 0, 1, 0, 1, 0xffff, 2), "minimumParameters" => domain_parameters(1, 1, 1, 1, 0, 1, 0x420, 2), "maximumParameters" => domain_parameters(0xffff, 0xfc17, 0xffff, 1, 0, 1, 0xffff, 2), - "userData" => user_data.unwrap_or(Vec::new()) + "userData" => user_data.unwrap_or_default() ]) } @@ -59,10 +59,10 @@ fn connect_initial(user_data: Option) -> ImplicitTag { fn connect_response(user_data: Option) -> ImplicitTag { ImplicitTag::new(Tag::application(102), sequence![ - "result" => 0 as Enumerate, - "calledConnectId" => 0 as Integer, + "result" => 0_i64, + "calledConnectId" => 0_u32, "domainParameters" => domain_parameters(22, 3, 0, 1, 0, 1,0xfff8, 2), - "userData" => user_data.unwrap_or(Vec::new()) + "userData" => user_data.unwrap_or_default() ]) } @@ -75,7 +75,7 @@ fn mcs_pdu_header(pdu: Option, options: Option) -> u8 { /// Client -- attach_user_request -> Server /// Client <- attach_user_confirm -- Server fn read_attach_user_confirm(buffer: &mut dyn Read) -> RdpResult { - let mut confirm = trame![0 as u8, Vec::::new()]; + let mut confirm = trame![0_u8, Vec::::new()]; confirm.read(buffer)?; if cast!(DataType::U8, confirm[0])? >> 2 != mcs_pdu_header(Some(DomainMCSPDU::AttachUserConfirm), None) >> 2 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "MCS: unexpected header on recv_attach_user_confirm"))); @@ -85,7 +85,7 @@ fn read_attach_user_confirm(buffer: &mut dyn Read) -> RdpResult { if per::read_enumerates(&mut request)? != 0 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::RejectedByServer, "MCS: recv_attach_user_confirm user rejected by server"))); } - Ok(per::read_integer_16(1001, &mut request)?) + per::read_integer_16(1001, &mut request) } /// Create a session for the current user @@ -133,7 +133,7 @@ fn channel_join_request(user_id: Option, channel_id: Option) -> RdpRes /// Client -- channel_join_request -> Server /// Client <- channel_join_confirm -- Server fn read_channel_join_confirm(user_id: u16, channel_id: u16, buffer: &mut dyn Read) -> RdpResult { - let mut confirm = trame![0 as u8, Vec::::new()]; + let mut confirm = trame![0_u8, Vec::::new()]; confirm.read(buffer)?; if cast!(DataType::U8, confirm[0])? >> 2 != mcs_pdu_header(Some(DomainMCSPDU::ChannelJoinConfirm), None) >> 2 { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "MCS: unexpected header on read_channel_join_confirm"))); @@ -263,7 +263,7 @@ impl Client { mcs_pdu_header(Some(DomainMCSPDU::SendDataRequest), None), U16::BE(self.user_id.unwrap() - 1001), U16::BE(self.channel_ids[channel_name]), - 0x70 as u8, + 0x70_u8, per::write_length(message.length() as u16)?, message ]) @@ -301,7 +301,7 @@ impl Client { per::read_integer_16(1001, &mut payload)?; let channel_id = per::read_integer_16(0, &mut payload)?; - let channel = self.channel_ids.iter().find(|x| *x.1 == channel_id).ok_or(Error::RdpError(RdpError::new(RdpErrorKind::Unknown, "MCS: unknown channel")))?; + let channel = self.channel_ids.iter().find(|x| *x.1 == channel_id).ok_or_else(|| Error::RdpError(RdpError::new(RdpErrorKind::Unknown, "MCS: unknown channel")))?; per::read_enumerates(&mut payload)?; per::read_length(&mut payload)?; diff --git a/src/core/per.rs b/src/core/per.rs index b6bd5f2..9949b24 100644 --- a/src/core/per.rs +++ b/src/core/per.rs @@ -18,7 +18,7 @@ pub fn read_length(s: &mut dyn Read) -> RdpResult { let mut byte: u8 = 0; byte.read(s)?; if byte & 0x80 != 0 { - byte = byte & !0x80; + byte &= !0x80; let mut size = (byte as u16) << 8 ; byte.read(s)?; size += byte as u16; @@ -329,7 +329,7 @@ pub fn write_object_identifier(oid: &[u8], s: &mut dyn Write) ->RdpResult<()> { } trame![ - 5 as u8, + 5_u8, oid[0] << 4 | oid[1] & 0xF, oid[2], oid[3], @@ -349,7 +349,7 @@ pub fn write_object_identifier(oid: &[u8], s: &mut dyn Write) ->RdpResult<()> { /// ``` pub fn read_numeric_string(minimum: usize, s: &mut dyn Read) -> RdpResult> { let length = read_length(s)?; - let mut result = vec![0 as u8; length as usize + minimum + 1]; + let mut result = vec![0_u8; length as usize + minimum + 1]; result.read(s)?; Ok(result) } @@ -380,13 +380,13 @@ pub fn write_numeric_string(string: &[u8], minimum: usize, s: &mut dyn Write) - /// Read exactly a number of bytes pub fn read_padding(length: usize, s: &mut dyn Read) -> RdpResult<()> { let mut padding = vec![0; length]; - s.read(&mut padding)?; + s.read_exact(&mut padding)?; Ok(()) } /// Write length zero bytes pub fn write_padding(length: usize, s: &mut dyn Write) -> RdpResult<()> { - vec![0 as u8; length].write(s)?; + vec![0_u8; length].write(s)?; Ok(()) } @@ -406,10 +406,10 @@ pub fn read_octet_stream(octet_stream: &[u8], minimum: usize, s: &mut dyn Read) if length != octet_stream.len() { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "PER: source octet string have an invalid size"))); } - for i in 0..length { + for i in octet_stream.iter() { let mut c: u8 = 0; c.read(s)?; - if c != octet_stream[i] { + if c != *i { return Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidData, "PER: source octet string have an invalid char"))); } } diff --git a/src/core/tpkt.rs b/src/core/tpkt.rs index 909074f..30c236d 100644 --- a/src/core/tpkt.rs +++ b/src/core/tpkt.rs @@ -26,7 +26,7 @@ pub enum Action { fn tpkt_header(size: u16) -> Component { component![ "action" => Action::FastPathActionX224 as u8, - "flag" => 0 as u8, + "flag" => 0_u8, "size" => U16::BE(size + 4) ] } @@ -161,12 +161,10 @@ impl Client { Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(length as usize - 3)?))) } } - else { - if short_length < 2 { - Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "Invalid minimal size for TPKT"))) - } else { - Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(short_length as usize - 2)?))) - } + else if short_length < 2 { + Err(Error::RdpError(RdpError::new(RdpErrorKind::InvalidSize, "Invalid minimal size for TPKT"))) + } else { + Ok(Payload::FastPath(sec_flag, Cursor::new(self.transport.read(short_length as usize - 2)?))) } } } diff --git a/src/core/x224.rs b/src/core/x224.rs index ec2659d..b4ef517 100644 --- a/src/core/x224.rs +++ b/src/core/x224.rs @@ -77,7 +77,7 @@ fn x224_crq(len: u8, code: MessageType) -> Component { component! [ "len" => (len + 6) as u8, "code" => code as u8, - "padding" => trame! [U16::LE(0), U16::LE(0), 0 as u8] + "padding" => trame! [U16::LE(0), U16::LE(0), 0_u8] ] } @@ -103,9 +103,9 @@ fn x224_connection_pdu( /// X224 header fn x224_header() -> Component { component![ - "header" => 2 as u8, + "header" => 2_u8, "messageType" => MessageType::X224TPDUData as u8, - "separator" => Check::new(0x80 as u8) + "separator" => Check::new(0x80_u8) ] } diff --git a/src/model/data.rs b/src/model/data.rs index 5555e3d..6f50a91 100644 --- a/src/model/data.rs +++ b/src/model/data.rs @@ -543,7 +543,7 @@ impl Value { impl PartialEq for Value { /// Equality between all type fn eq(&self, other: &Self) -> bool { - return self.inner() == other.inner() + self.inner() == other.inner() } } @@ -805,12 +805,12 @@ impl Message for Check { impl Message for Vec { fn write(&self, writer: &mut dyn Write) -> RdpResult<()> { - writer.write(self)?; + writer.write_all(self)?; Ok(()) } fn read(&mut self, reader: &mut dyn Read) -> RdpResult<()> { - if self.len() == 0 { + if self.is_empty() { reader.read_to_end(self)?; } else { @@ -993,9 +993,10 @@ impl Message for Option { /// assert_eq!(s2.into_inner(), []) /// ``` fn write(&self, writer: &mut dyn Write) -> RdpResult<()> { - Ok(if let Some(value) = self { + if let Some(value) = self { value.write(writer)? - }) + }; + Ok(()) } /// Read an optional field @@ -1210,7 +1211,7 @@ mod test { #[test] fn test_data_u8_write() { let mut stream = Cursor::new(Vec::::new()); - let x = 1 as u8; + let x = 1_u8; x.write(&mut stream).unwrap(); assert_eq!(stream.get_ref().as_slice(), [1]) } diff --git a/src/model/link.rs b/src/model/link.rs index e6b5a8f..1e062eb 100644 --- a/src/model/link.rs +++ b/src/model/link.rs @@ -78,10 +78,11 @@ impl Stream { /// Shutdown the stream /// Only works when stream is a SSL stream pub fn shutdown(&mut self) -> RdpResult<()> { - Ok(match self { + match self { Stream::Ssl(e) => e.shutdown()?, _ => () - }) + }; + Ok(()) } } diff --git a/src/model/unicode.rs b/src/model/unicode.rs index 3729767..990dbf9 100644 --- a/src/model/unicode.rs +++ b/src/model/unicode.rs @@ -21,6 +21,6 @@ impl Unicode for String { let encode_char = U16::LE(c); encode_char.write(&mut result).unwrap(); } - return result.into_inner() + result.into_inner() } } \ No newline at end of file diff --git a/src/nla/asn1.rs b/src/nla/asn1.rs index aee8d5a..0069022 100644 --- a/src/nla/asn1.rs +++ b/src/nla/asn1.rs @@ -41,6 +41,12 @@ pub struct SequenceOf { factory: Option Box>> } +impl Default for SequenceOf { + fn default() -> Self { + Self::new() + } +} + impl SequenceOf { /// Create an empty sequenceof /// @@ -49,7 +55,7 @@ impl SequenceOf { /// use rdp::nla::asn1::SequenceOf; /// let so = SequenceOf::new(); /// ``` - pub fn new() -> Self{ + pub fn new() -> Self { SequenceOf { inner: Vec::new(), factory : None diff --git a/src/nla/ntlm.rs b/src/nla/ntlm.rs index 55a9cb8..c918f9a 100644 --- a/src/nla/ntlm.rs +++ b/src/nla/ntlm.rs @@ -63,7 +63,7 @@ fn version() -> Component { "ProductMajorVersion" => MajorVersion::WindowsMajorVersion6 as u8, "ProductMinorVersion" => MinorVersion::WindowsMinorVersion0 as u8, "ProductBuild" => U16::LE(6002), - "Reserved" => trame![U16::LE(0), 0 as u8], + "Reserved" => trame![U16::LE(0), 0_u8], "NTLMRevisionCurrent" => NTLMRevision::NtlmSspRevisionW2K3 as u8 ) } @@ -78,7 +78,7 @@ fn negotiate_message(flags: u32) -> Component { if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "DomainNameLen" => U16::LE(0), "DomainNameMaxLen" => U16::LE(0), @@ -104,7 +104,7 @@ fn challenge_message() -> Component { if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "ServerChallenge" => vec![0; 8], "Reserved" => vec![0; 8], @@ -153,7 +153,7 @@ fn authenticate_message(lm_challenge_response: &[u8], nt_challenge_response:&[u8 if node.inner() & (Negotiate::NtlmsspNegociateVersion as u32) == 0 { return MessageOption::SkipField("Version".to_string()) } - return MessageOption::None + MessageOption::None }), "Version" => version() ] , payload) @@ -237,7 +237,7 @@ fn read_target_info(data: &[u8]) -> RdpResult>> { result.insert(av_id, cast!(DataType::Slice, element["Value"])?.to_vec()); } - return Ok(result); + Ok(result) } /// Zero filled array @@ -292,13 +292,13 @@ fn md5(data: &[u8]) -> Vec { /// ```rust, ignore /// let encoded_string = unicode("foo".to_string()); /// ``` -fn unicode(data: &String) -> Vec { +fn unicode(data: &str) -> Vec { let mut result = Cursor::new(Vec::new()); for c in data.encode_utf16() { let encode_char = U16::LE(c); encode_char.write(&mut result).unwrap(); } - return result.into_inner() + result.into_inner() } /// Compute HMAC with MD5 hash algorithm @@ -325,8 +325,8 @@ fn hmac_md5(key: &[u8], data: &[u8]) -> Vec { /// ```rust, ignore /// let key = ntowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn ntowfv2(password: &String, user: &String, domain: &String) -> Vec { - hmac_md5(&md4(&unicode(password)), &unicode(&(user.to_uppercase() + &domain))) +fn ntowfv2(password: &str, user: &str, domain: &str) -> Vec { + hmac_md5(&md4(&unicode(password)), &unicode(&(user.to_uppercase() + domain))) } /// This function is used to compute init key of another hmac_md5 @@ -339,8 +339,8 @@ fn ntowfv2(password: &String, user: &String, domain: &String) -> Vec { /// ```rust, ignore /// let key = ntowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn ntowfv2_hash(hash: &[u8], user: &String, domain: &String) -> Vec { - hmac_md5(hash, &unicode(&(user.to_uppercase() + &domain))) +fn ntowfv2_hash(hash: &[u8], user: &str, domain: &str) -> Vec { + hmac_md5(hash, &unicode(&(user.to_uppercase() + domain))) } /// This function is used to compute init key of another hmac_md5 @@ -350,7 +350,7 @@ fn ntowfv2_hash(hash: &[u8], user: &String, domain: &String) -> Vec { /// ```rust, ignore /// let key = lmowfv2("hello123".to_string(), "user".to_string(), "domain".to_string()) /// ``` -fn lmowfv2(password: &String, user: &String, domain: &String) -> Vec { +fn lmowfv2(password: &String, user: &str, domain: &str) -> Vec { ntowfv2(password, user, domain) } @@ -375,7 +375,7 @@ fn compute_response_v2( let temp = [response_version.to_vec(), hi_response_version.to_vec(), z(6), time.to_vec(), client_challenge.to_vec(), z(4), server_name.to_vec()].concat(); let nt_proof_str = hmac_md5(response_key_nt, &[server_challenge.to_vec(), temp.clone()].concat()); - let nt_challenge_response = [nt_proof_str.clone(), temp.clone()].concat(); + let nt_challenge_response = [nt_proof_str.clone(), temp].concat(); let lm_challenge_response = [hmac_md5(response_key_lm, &[server_challenge.to_vec(), client_challenge.to_vec()].concat()), client_challenge.to_vec()].concat(); let session_base_key = hmac_md5(response_key_nt, &nt_proof_str); @@ -396,7 +396,7 @@ fn kx_key_v2(session_base_key: &[u8], _lm_challenge_response: &[u8], _server_cha fn rc4k(key: &[u8], plaintext: &[u8]) -> Vec { let mut result = vec![0; plaintext.len()]; let mut rc4_handle = Rc4::new(key); - rc4_handle.process(&plaintext, &mut result); + rc4_handle.process(plaintext, &mut result); result } @@ -523,7 +523,7 @@ impl AuthenticationProtocol for Ntlm { Negotiate::NtlmsspNegociateUnicode as u32 )); self.negotiate_message = Some(buffer.clone()); - return Ok(buffer) + Ok(buffer) } /// Read the server challenge @@ -560,11 +560,11 @@ impl AuthenticationProtocol for Ntlm { // generate client challenge let client_challenge = random(8); - let response = compute_response_v2(&self.response_key_nt, &self.response_key_lm, &server_challenge, &client_challenge, ×tamp, &target_name); + let response = compute_response_v2(&self.response_key_nt, &self.response_key_lm, server_challenge, &client_challenge, ×tamp, target_name); let nt_challenge_response = response.0; let lm_challenge_response = response.1; let session_base_key = response.2; - let key_exchange_key = kx_key_v2(&session_base_key, &lm_challenge_response, &server_challenge); + let key_exchange_key = kx_key_v2(&session_base_key, &lm_challenge_response, server_challenge); self.exported_session_key = Some(random(16)); let encrypted_random_session_key = rc4k(&key_exchange_key, self.exported_session_key.as_ref().unwrap()); @@ -683,7 +683,7 @@ impl GenericSecurityService for NTLMv2SecurityInterface { let mut encrypted_data = vec![0; data.len()]; self.encrypt.process(data, &mut encrypted_data); let signature = mac(&mut self.encrypt, &self.signing_key, self.seq_num, data); - self.seq_num = self.seq_num + 1; + self.seq_num += 1; Ok(to_vec(&trame![signature, encrypted_data])) } diff --git a/src/nla/rc4.rs b/src/nla/rc4.rs index 1197a2e..d18f528 100644 --- a/src/nla/rc4.rs +++ b/src/nla/rc4.rs @@ -6,7 +6,7 @@ pub struct Rc4 { impl Rc4 { pub fn new(key: &[u8]) -> Rc4 { - assert!(key.len() >= 1 && key.len() <= 256); + assert!(!key.is_empty() && key.len() <= 256); let mut rc4 = Rc4 { i: 0, j: 0, state: [0; 256] }; for (i, x) in rc4.state.iter_mut().enumerate() { *x = i as u8; @@ -22,8 +22,8 @@ impl Rc4 { self.i = self.i.wrapping_add(1); self.j = self.j.wrapping_add(self.state[self.i as usize]); self.state.swap(self.i as usize, self.j as usize); - let k = self.state[(self.state[self.i as usize].wrapping_add(self.state[self.j as usize])) as usize]; - k + + self.state[(self.state[self.i as usize].wrapping_add(self.state[self.j as usize])) as usize] } pub fn process(&mut self, input: &[u8], output: &mut [u8]) {