ipmi 0.1.2

IPMI v2.0 RMCP+ client library (async-first + optional blocking) with session authentication, integrity and confidentiality.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;

use crate::client::core::ClientCore;
use crate::commands::{
    ChassisControlCommand, Command, GetChannelAuthCapabilities, GetChassisStatus, GetDeviceId,
    GetSelfTestResults, GetSystemGuid,
};
use crate::crypto::SecretBytes;
use crate::error::{Error, Result};
use crate::session::establish_session_async;
use crate::transport::AsyncTransport;
use crate::transport::tokio::UdpTransport;
use crate::types::{
    ChannelAuthCapabilities, ChassisControl, ChassisStatus, DeviceId, PrivilegeLevel, RawResponse,
    SelfTestResult, SystemGuid,
};

/// A tokio-based IPMI v2.0 RMCP+ client.
#[derive(Clone)]
pub struct Client {
    inner: Arc<tokio::sync::Mutex<Inner>>,
    managed_session_id: u32,
    remote_session_id: u32,
}

struct Inner {
    transport: Box<dyn AsyncTransport + Send>,
    core: ClientCore,
}

/// Builder for [`Client`].
#[derive(Debug)]
pub struct ClientBuilder {
    target: SocketAddr,
    username: Option<Vec<u8>>,
    password: Option<SecretBytes>,
    bmc_key: Option<SecretBytes>,
    privilege_level: PrivilegeLevel,
    timeout: Duration,
    retries: u32,
}

impl ClientBuilder {
    /// Create a new builder.
    pub fn new(target: SocketAddr) -> Self {
        Self {
            target,
            username: None,
            password: None,
            bmc_key: None,
            privilege_level: PrivilegeLevel::Administrator,
            timeout: Duration::from_secs(1),
            retries: 3,
        }
    }

    /// Set the username (bytes).
    ///
    /// IPMI usernames are ASCII in most deployments, but the protocol treats them as raw bytes.
    pub fn username_bytes(mut self, username: impl Into<Vec<u8>>) -> Self {
        self.username = Some(username.into());
        self
    }

    /// Set the username (UTF-8 string). This is a convenience wrapper around [`Self::username_bytes`].
    pub fn username(mut self, username: impl AsRef<str>) -> Self {
        self.username = Some(username.as_ref().as_bytes().to_vec());
        self
    }

    /// Set the password (bytes).
    pub fn password_bytes(mut self, password: impl Into<Vec<u8>>) -> Self {
        self.password = Some(SecretBytes::new(password.into()));
        self
    }

    /// Set the password (UTF-8 string). This is a convenience wrapper around [`Self::password_bytes`].
    pub fn password(mut self, password: impl AsRef<str>) -> Self {
        self.password = Some(SecretBytes::new(password.as_ref().as_bytes().to_vec()));
        self
    }

    /// Set the optional BMC key (`Kg`) for "two-key" logins.
    ///
    /// If not set, the password key is used ("one-key" login), which is common in many BMC default configs.
    pub fn bmc_key_bytes(mut self, kg: impl Into<Vec<u8>>) -> Self {
        self.bmc_key = Some(SecretBytes::new(kg.into()));
        self
    }

    /// Set the optional BMC key (`Kg`) for "two-key" logins (UTF-8 string).
    pub fn bmc_key(mut self, kg: impl AsRef<str>) -> Self {
        self.bmc_key = Some(SecretBytes::new(kg.as_ref().as_bytes().to_vec()));
        self
    }

    /// Set requested session privilege level.
    pub fn privilege_level(mut self, level: PrivilegeLevel) -> Self {
        self.privilege_level = level;
        self
    }

    /// Set UDP read timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Set number of send attempts per request (including the first attempt).
    pub fn retries(mut self, attempts: u32) -> Self {
        self.retries = attempts;
        self
    }

    /// Establish the session and build the [`Client`].
    pub async fn build(self) -> Result<Client> {
        let username = self
            .username
            .ok_or(Error::Protocol("username is required"))?;
        let password = self
            .password
            .ok_or(Error::Protocol("password is required"))?;

        if username.len() > 16 {
            return Err(Error::InvalidArgument(
                "username longer than 16 bytes is not widely supported",
            ));
        }

        let transport: Box<dyn AsyncTransport + Send> =
            Box::new(UdpTransport::connect(self.target, self.timeout, self.retries).await?);

        let session = establish_session_async(
            &*transport,
            &username,
            &password,
            self.bmc_key.as_ref(),
            self.privilege_level,
        )
        .await?;

        let managed_session_id = session.managed_session_id;
        let remote_session_id = session.remote_session_id;

        Ok(Client {
            inner: Arc::new(tokio::sync::Mutex::new(Inner {
                transport,
                core: ClientCore::new(session),
            })),
            managed_session_id,
            remote_session_id,
        })
    }
}

impl Client {
    /// Create a [`ClientBuilder`].
    pub fn builder(target: SocketAddr) -> ClientBuilder {
        ClientBuilder::new(target)
    }

    /// Execute a typed command (single request/response).
    pub async fn execute<C: Command>(&self, command: C) -> Result<C::Output> {
        let request_data = command.request_data();
        let response = self.send_raw(C::NETFN, C::CMD, &request_data).await?;
        command.parse_response(response)
    }

    /// Send a raw IPMI request and return the raw response.
    pub async fn send_raw(&self, netfn: u8, cmd: u8, data: &[u8]) -> Result<RawResponse> {
        let start = Instant::now();
        let result = {
            let mut inner = self.inner.lock().await;
            send_raw_locked(&mut inner, netfn, cmd, data).await
        };
        let elapsed = start.elapsed();
        match &result {
            Ok(resp) => {
                crate::observe::record_ok("async", netfn, cmd, elapsed, resp.completion_code)
            }
            Err(err) => crate::observe::record_err("async", netfn, cmd, elapsed, err),
        }
        result
    }

    /// Convenience wrapper for `Get Device ID` (App NetFn, cmd 0x01).
    pub async fn get_device_id(&self) -> Result<DeviceId> {
        self.execute(GetDeviceId).await
    }

    /// Convenience wrapper for `Get Self Test Results` (App NetFn, cmd 0x04).
    pub async fn get_self_test_results(&self) -> Result<SelfTestResult> {
        self.execute(GetSelfTestResults).await
    }

    /// Convenience wrapper for `Get System GUID` (App NetFn, cmd 0x37).
    pub async fn get_system_guid(&self) -> Result<SystemGuid> {
        self.execute(GetSystemGuid).await
    }

    /// Convenience wrapper for `Get Chassis Status` (Chassis NetFn, cmd 0x01).
    pub async fn get_chassis_status(&self) -> Result<ChassisStatus> {
        self.execute(GetChassisStatus).await
    }

    /// Run `Chassis Control` (Chassis NetFn, cmd 0x02).
    pub async fn chassis_control(&self, control: ChassisControl) -> Result<()> {
        self.execute(ChassisControlCommand { control }).await
    }

    /// Convenience wrapper for `Get Channel Authentication Capabilities`
    /// (App NetFn, cmd 0x38).
    pub async fn get_channel_auth_capabilities(
        &self,
        channel: u8,
        privilege: PrivilegeLevel,
    ) -> Result<ChannelAuthCapabilities> {
        let cmd = GetChannelAuthCapabilities::new(channel, privilege);
        match self.execute(cmd).await {
            Ok(caps) => Ok(caps),
            Err(Error::CompletionCode { .. }) => self.execute(cmd.without_v2_data()).await,
            Err(e) => Err(e),
        }
    }

    /// Return the managed system (BMC) session ID (SIDC).
    pub fn managed_session_id(&self) -> u32 {
        self.managed_session_id
    }

    /// Return the remote console session ID (SIDM).
    pub fn remote_session_id(&self) -> u32 {
        self.remote_session_id
    }

    /// Close the active RMCP+ session (App NetFn, cmd 0x3C).
    ///
    /// This is a best-effort operation. If the BMC does not respond (timeout) the client still
    /// transitions to a locally closed state and will reject further requests.
    pub async fn close_session(&self) -> Result<()> {
        const NETFN_APP: u8 = 0x06;
        const CMD_CLOSE_SESSION: u8 = 0x3C;

        let mut inner = self.inner.lock().await;
        if inner.core.is_closed() {
            return Ok(());
        }

        let session_id = inner.core.managed_session_id_bytes_le();
        let start = Instant::now();
        let result = send_raw_locked(&mut inner, NETFN_APP, CMD_CLOSE_SESSION, &session_id).await;
        let elapsed = start.elapsed();
        match &result {
            Ok(resp) => crate::observe::record_ok(
                "async",
                NETFN_APP,
                CMD_CLOSE_SESSION,
                elapsed,
                resp.completion_code,
            ),
            Err(err) => {
                crate::observe::record_err("async", NETFN_APP, CMD_CLOSE_SESSION, elapsed, err)
            }
        }

        match result {
            Ok(resp) => {
                if resp.completion_code != 0x00 && resp.completion_code != 0x87 {
                    inner.core.mark_closed();
                    return Err(Error::CompletionCode {
                        completion_code: resp.completion_code,
                    });
                }
                inner.core.mark_closed();
                Ok(())
            }
            Err(Error::Timeout) => {
                inner.core.mark_closed();
                Ok(())
            }
            Err(e) => {
                inner.core.mark_closed();
                Err(e)
            }
        }
    }

    /// A service-style grouping for App netfn commands.
    pub fn app(&self) -> AppService {
        AppService {
            client: self.clone(),
        }
    }

    /// A service-style grouping for Chassis netfn commands.
    pub fn chassis(&self) -> ChassisService {
        ChassisService {
            client: self.clone(),
        }
    }
}

async fn send_raw_locked(
    inner: &mut Inner,
    netfn: u8,
    cmd: u8,
    data: &[u8],
) -> Result<RawResponse> {
    let (rq_seq, packet) = inner.core.build_rmcpplus_ipmi_request(netfn, cmd, data)?;
    let response_bytes = inner.transport.send_recv(&packet).await?;
    inner
        .core
        .decode_rmcpplus_ipmi_response(netfn, cmd, rq_seq, &response_bytes)
}

/// App NetFn service.
#[derive(Clone)]
pub struct AppService {
    client: Client,
}

impl AppService {
    /// `Get Device ID` (App NetFn, cmd 0x01).
    pub async fn get_device_id(&self) -> Result<DeviceId> {
        self.client.get_device_id().await
    }

    /// `Get Self Test Results` (App NetFn, cmd 0x04).
    pub async fn get_self_test_results(&self) -> Result<SelfTestResult> {
        self.client.get_self_test_results().await
    }

    /// `Get System GUID` (App NetFn, cmd 0x37).
    pub async fn get_system_guid(&self) -> Result<SystemGuid> {
        self.client.get_system_guid().await
    }

    /// `Get Channel Authentication Capabilities` (App NetFn, cmd 0x38).
    pub async fn get_channel_auth_capabilities(
        &self,
        channel: u8,
        privilege: PrivilegeLevel,
    ) -> Result<ChannelAuthCapabilities> {
        self.client
            .get_channel_auth_capabilities(channel, privilege)
            .await
    }
}

/// Chassis NetFn service.
#[derive(Clone)]
pub struct ChassisService {
    client: Client,
}

impl ChassisService {
    /// `Get Chassis Status` (Chassis NetFn, cmd 0x01).
    pub async fn get_chassis_status(&self) -> Result<ChassisStatus> {
        self.client.get_chassis_status().await
    }

    /// `Chassis Control` (Chassis NetFn, cmd 0x02).
    pub async fn chassis_control(&self, control: ChassisControl) -> Result<()> {
        self.client.chassis_control(control).await
    }
}

#[cfg(test)]
mod tests {
    use core::future::Future;
    use core::pin::Pin;

    use super::*;

    use crate::session::Session;

    #[derive(Debug, Clone, Copy)]
    struct TimeoutAsyncTransport;

    impl AsyncTransport for TimeoutAsyncTransport {
        fn send_recv<'a>(
            &'a self,
            _request: &'a [u8],
        ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>>> + Send + 'a>> {
            Box::pin(async { Err(Error::Timeout) })
        }
    }

    fn dummy_session() -> Session {
        Session::new_test(0x11223344, 0x55667788, false, false)
    }

    #[tokio::test(flavor = "current_thread")]
    async fn close_session_timeout_marks_client_closed() {
        let session = dummy_session();
        let managed_session_id = session.managed_session_id;
        let remote_session_id = session.remote_session_id;
        let client = Client {
            inner: Arc::new(tokio::sync::Mutex::new(Inner {
                transport: Box::new(TimeoutAsyncTransport),
                core: ClientCore::new(session),
            })),
            managed_session_id,
            remote_session_id,
        };

        client.close_session().await.expect("close_session");

        let err = client
            .get_device_id()
            .await
            .expect_err("expected session-closed error");
        assert!(matches!(err, Error::Protocol("session is closed")));
    }
}