ipmi_rs/app/auth/
get_session_challenge.rs1use std::num::NonZeroU32;
2
3use crate::connection::{CompletionCode, IpmiCommand, Message, NetFn, ParseResponseError};
4
5use super::{AuthError, AuthType};
6
7#[derive(Debug, Clone, Copy)]
8pub struct SessionChallenge {
9 pub temporary_session_id: NonZeroU32,
10 pub challenge_string: [u8; 16],
11}
12
13#[derive(Debug, Clone, Copy, PartialEq)]
14pub struct GetSessionChallenge {
15 auth_type: AuthType,
16 username: [u8; 16],
17}
18
19impl GetSessionChallenge {
20 pub fn new(auth_type: AuthType, username: Option<&str>) -> Option<Self> {
21 let bytes = username.map(|u| u.as_bytes()).unwrap_or(&[]);
22 if bytes.len() > 16 {
23 return None;
24 }
25
26 let mut username = [0u8; 16];
27 username[..bytes.len()].copy_from_slice(bytes);
28
29 Some(Self {
30 auth_type,
31 username,
32 })
33 }
34
35 pub fn auth_type(&self) -> AuthType {
36 self.auth_type
37 }
38
39 pub fn username(&self) -> &str {
40 let end = self.username.iter().take_while(|v| **v != 0).count();
41 unsafe { core::str::from_utf8_unchecked(&self.username[..end]) }
42 }
43}
44
45impl From<GetSessionChallenge> for Message {
46 fn from(value: GetSessionChallenge) -> Message {
47 let mut data = vec![0u8; 17];
48
49 data[0] = value.auth_type.into();
50 data[1..].copy_from_slice(&value.username);
51
52 Message::new_request(NetFn::App, 0x39, data)
53 }
54}
55
56impl IpmiCommand for GetSessionChallenge {
57 type Output = SessionChallenge;
58
59 type Error = AuthError;
60
61 fn parse_response(
62 completion_code: CompletionCode,
63 data: &[u8],
64 ) -> Result<Self::Output, ParseResponseError<Self::Error>> {
65 Self::check_cc_success(completion_code)?;
66
67 if data.len() != 20 {
68 return Err(ParseResponseError::NotEnoughData);
69 }
70
71 let temporary_session_id =
72 NonZeroU32::try_from(u32::from_le_bytes(data[0..4].try_into().unwrap()))
73 .map_err(|_| AuthError::InvalidZeroSession)?;
74
75 let challenge_string = data[4..20].try_into().unwrap();
76
77 Ok(SessionChallenge {
78 temporary_session_id,
79 challenge_string,
80 })
81 }
82}