iscsi-client-rs 0.0.6

A pure-Rust iSCSI initiator library and CLI
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2012-2025 Andrei Maltsev

use core::fmt;

use anyhow::{Result, anyhow, bail};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

/// The status classes as per RFC 3720 ยง11.11.1
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StatusClass {
    /// target accepted the request
    Success = 0,
    /// initiator must follow TargetAddress
    Redirection = 1,
    /// mistake on initiator side; do not retry
    InitiatorError = 2,
    /// target temporarily cannot fulfil; may retry
    TargetError = 3,
    Unknown(u8),
}

impl From<u8> for StatusClass {
    fn from(b: u8) -> Self {
        match b {
            0 => StatusClass::Success,
            1 => StatusClass::Redirection,
            2 => StatusClass::InitiatorError,
            3 => StatusClass::TargetError,
            other => StatusClass::Unknown(other),
        }
    }
}
impl From<StatusClass> for u8 {
    fn from(class: StatusClass) -> Self {
        match class {
            StatusClass::Success => 0x00,
            StatusClass::Redirection => 0x01,
            StatusClass::InitiatorError => 0x02,
            StatusClass::TargetError => 0x03,
            StatusClass::Unknown(v) => v,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone)]
pub enum StatusDetail {
    Success(SuccessDetail),
    Redirection(RedirectionDetail),
    InitiatorErr(InitiatorErrorDetail),
    TargetErr(TargetErrorDetail),
}

#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum SuccessDetail {
    CmdCompletedNormally = 0x00,
}

impl TryFrom<u8> for SuccessDetail {
    type Error = anyhow::Error;

    fn try_from(raw: u8) -> Result<Self> {
        match raw {
            0x00 => Ok(SuccessDetail::CmdCompletedNormally),
            other => Err(anyhow!("unknown Success detail code: {:#02x}", other)),
        }
    }
}

#[repr(u8)]
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum RedirectionDetail {
    TargetRedirected = 0x01,
}

impl TryFrom<u8> for RedirectionDetail {
    type Error = anyhow::Error;

    fn try_from(raw: u8) -> Result<Self> {
        match raw {
            0x01 => Ok(RedirectionDetail::TargetRedirected),
            other => Err(anyhow!("unknown Redirection detail code: {:#02x}", other)),
        }
    }
}

/// Status-Detail for Status-Class = 0x02 (Initiator Error)
/// (ัะผ. IANA iSCSI Parameters: Login Response Status Codes โ†’ Status-Detail for
/// Status-Class=0x02)
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InitiatorErrorDetail {
    /// 0x00 โ€” Initiator error (ะพะฑั‰ะฐั ะพัˆะธะฑะบะฐ ะธะฝะธั†ะธะฐะปะธะทะฐั‚ะพั€ะฐ)
    InitiatorError = 0x00,
    /// 0x01 โ€” Authentication failure
    AuthFailed = 0x01,
    /// 0x02 โ€” Authorization failure
    AuthzFailed = 0x02,
    /// 0x03 โ€” Not found (ะฝะฐะฟั€ะธะผะตั€, ัƒะบะฐะทะฐะฝะฝั‹ะน ะฟะฐั€ะฐะผะตั‚ั€ ะพั‚ััƒั‚ัั‚ะฒัƒะตั‚)
    NotFound = 0x03,
    /// 0x04 โ€” Target removed
    TargetRemoved = 0x04,
    /// 0x05 โ€” Unsupported version
    UnsupportedVersion = 0x05,
    /// 0x06 โ€” Too many connections
    TooManyConnections = 0x06,
    /// 0x07 โ€” Missing parameter
    MissingParameter = 0x07,
    /// 0x08 โ€” Can't include in session
    CantIncludeInSession = 0x08,
    /// 0x09 โ€” Session type not supported
    SessionTypeNotSupported = 0x09,
    /// 0x0a โ€” Session does not exist
    SessionDoesNotExist = 0x0a,
    /// 0x0b โ€” Invalid during login
    InvalidDuringLogin = 0x0b,
    /// 0x0cโ€“0xff โ€” RESERVATED
    Reserved(u8),
}

impl TryFrom<u8> for InitiatorErrorDetail {
    type Error = anyhow::Error;

    fn try_from(byte: u8) -> Result<Self> {
        match byte {
            0x00 => Ok(InitiatorErrorDetail::InitiatorError),
            0x01 => Ok(InitiatorErrorDetail::AuthFailed),
            0x02 => Ok(InitiatorErrorDetail::AuthzFailed),
            0x03 => Ok(InitiatorErrorDetail::NotFound),
            0x04 => Ok(InitiatorErrorDetail::TargetRemoved),
            0x05 => Ok(InitiatorErrorDetail::UnsupportedVersion),
            0x06 => Ok(InitiatorErrorDetail::TooManyConnections),
            0x07 => Ok(InitiatorErrorDetail::MissingParameter),
            0x08 => Ok(InitiatorErrorDetail::CantIncludeInSession),
            0x09 => Ok(InitiatorErrorDetail::SessionTypeNotSupported),
            0x0a => Ok(InitiatorErrorDetail::SessionDoesNotExist),
            0x0b => Ok(InitiatorErrorDetail::InvalidDuringLogin),
            other => Err(anyhow!("unknown InitiatorErrorDetail: 0x{:02x}", other)),
        }
    }
}

/// iSCSI Login Status-Detail codes for Status-Class = TargetError (0x03)
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TargetErrorDetail {
    /// (0x00) Target is busy, please retry later
    TargetBusy = 0x00,
    /// (0x01) Targetโ€™s protected area is busy
    TargetProtectedAreaBusy = 0x01,
    /// (0x02) Target cannot currently allocate requested resource
    TargetResourceUnavailable = 0x02,
    /// (0x03) Target encountered an internal error
    TargetInternalError = 0x03,
    /// (0x04โ€“0xFE) Vendor-specific error
    VendorSpecific(u8),
    /// (0xFF) Reserved
    Reserved(u8),
}

impl TryFrom<u8> for TargetErrorDetail {
    type Error = anyhow::Error;

    fn try_from(raw: u8) -> Result<Self, Self::Error> {
        let detail = match raw {
            0x00 => TargetErrorDetail::TargetBusy,
            0x01 => TargetErrorDetail::TargetProtectedAreaBusy,
            0x02 => TargetErrorDetail::TargetResourceUnavailable,
            0x03 => TargetErrorDetail::TargetInternalError,
            0x04..=0xFE => TargetErrorDetail::VendorSpecific(raw),
            0xFF => TargetErrorDetail::Reserved(raw),
        };
        Ok(detail)
    }
}

impl TryFrom<(StatusClass, u8)> for StatusDetail {
    type Error = anyhow::Error;

    fn try_from((class, raw): (StatusClass, u8)) -> Result<Self> {
        Ok(match class {
            StatusClass::Success => StatusDetail::Success(SuccessDetail::try_from(raw)?),
            StatusClass::Redirection => {
                StatusDetail::Redirection(RedirectionDetail::try_from(raw)?)
            },
            StatusClass::InitiatorError => {
                StatusDetail::InitiatorErr(InitiatorErrorDetail::try_from(raw)?)
            },
            StatusClass::TargetError => {
                StatusDetail::TargetErr(TargetErrorDetail::try_from(raw)?)
            },
            _ => bail!("invalid class"),
        })
    }
}

impl From<InitiatorErrorDetail> for u8 {
    fn from(detail: InitiatorErrorDetail) -> Self {
        match detail {
            InitiatorErrorDetail::InitiatorError => 0x00,
            InitiatorErrorDetail::AuthFailed => 0x01,
            InitiatorErrorDetail::AuthzFailed => 0x02,
            InitiatorErrorDetail::NotFound => 0x03,
            InitiatorErrorDetail::TargetRemoved => 0x04,
            InitiatorErrorDetail::UnsupportedVersion => 0x05,
            InitiatorErrorDetail::TooManyConnections => 0x06,
            InitiatorErrorDetail::MissingParameter => 0x07,
            InitiatorErrorDetail::CantIncludeInSession => 0x08,
            InitiatorErrorDetail::SessionTypeNotSupported => 0x09,
            InitiatorErrorDetail::SessionDoesNotExist => 0x0A,
            InitiatorErrorDetail::InvalidDuringLogin => 0x0B,
            InitiatorErrorDetail::Reserved(v) => v,
        }
    }
}

impl From<TargetErrorDetail> for u8 {
    fn from(detail: TargetErrorDetail) -> Self {
        match detail {
            TargetErrorDetail::TargetBusy => 0x00,
            TargetErrorDetail::TargetProtectedAreaBusy => 0x01,
            TargetErrorDetail::TargetResourceUnavailable => 0x02,
            TargetErrorDetail::TargetInternalError => 0x03,
            TargetErrorDetail::VendorSpecific(v) => v,
            TargetErrorDetail::Reserved(v) => v,
        }
    }
}

impl From<StatusDetail> for u8 {
    fn from(detail: StatusDetail) -> Self {
        match detail {
            StatusDetail::Success(inner) => inner as u8,
            StatusDetail::Redirection(inner) => inner as u8,
            StatusDetail::InitiatorErr(inner) => inner.into(),
            StatusDetail::TargetErr(inner) => inner.into(),
        }
    }
}

/// Wire-safe, zero-copy wrapper for **Status-Class** (1 byte on the wire).
#[repr(transparent)]
#[derive(
    Copy, Clone, PartialEq, Eq, Default, FromBytes, IntoBytes, KnownLayout, Immutable,
)]
pub struct RawStatusClass(u8);

impl RawStatusClass {
    #[inline]
    pub const fn raw(self) -> u8 {
        self.0
    }

    #[inline]
    pub const fn from_raw(v: u8) -> Self {
        Self(v)
    }

    /// Infallible decode: unknown values map to `StatusClass::Unknown(v)`.
    #[inline]
    pub fn decode(self) -> StatusClass {
        StatusClass::from(self.0)
    }

    /// Encode from the rich enum into the wire byte.
    #[inline]
    pub fn encode(&mut self, c: StatusClass) {
        self.0 = u8::from(c);
    }

    #[inline]
    pub const fn is_known(self) -> bool {
        matches!(self.0, 0..=3)
    }
}

impl From<RawStatusClass> for StatusClass {
    #[inline]
    fn from(r: RawStatusClass) -> Self {
        r.decode()
    }
}
impl From<StatusClass> for RawStatusClass {
    #[inline]
    fn from(c: StatusClass) -> Self {
        Self(u8::from(c))
    }
}

impl fmt::Debug for RawStatusClass {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "RawStatusClass({:?})", self.decode())
    }
}

/// Wire-safe, zero-copy wrapper for **Status-Detail** (1 byte on the wire).
///
/// Note: decoding requires the corresponding `StatusClass` to interpret the
/// byte.
#[repr(transparent)]
#[derive(
    Copy, Clone, PartialEq, Eq, Default, FromBytes, IntoBytes, KnownLayout, Immutable,
)]
pub struct RawStatusDetail(u8);

impl RawStatusDetail {
    #[inline]
    pub const fn raw(self) -> u8 {
        self.0
    }

    #[inline]
    pub const fn from_raw(v: u8) -> Self {
        Self(v)
    }

    /// Decode using the provided `StatusClass`.
    #[inline]
    pub fn decode_with_class(self, class: StatusClass) -> Result<StatusDetail> {
        match class {
            StatusClass::Success => {
                Ok(StatusDetail::Success(SuccessDetail::try_from(self.0)?))
            },
            StatusClass::Redirection => Ok(StatusDetail::Redirection(
                RedirectionDetail::try_from(self.0)?,
            )),
            StatusClass::InitiatorError => Ok(StatusDetail::InitiatorErr(
                InitiatorErrorDetail::try_from(self.0)?,
            )),
            StatusClass::TargetError => Ok(StatusDetail::TargetErr(
                TargetErrorDetail::try_from(self.0)?,
            )),
            StatusClass::Unknown(v) => {
                bail!("cannot decode Status-Detail for unknown Status-Class {v:#04x}")
            },
        }
    }

    /// Encode from the typed `StatusDetail` into the wire byte.
    #[inline]
    pub fn encode(&mut self, d: StatusDetail) {
        self.0 = u8::from(d);
    }
}

impl fmt::Debug for RawStatusDetail {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "RawStatusDetail(0x{:02x})", self.0)
    }
}

/// Small helper to handle the (Class, Detail) pair together.
#[derive(Copy, Clone, PartialEq, Eq, FromBytes, IntoBytes, KnownLayout, Immutable)]
#[repr(C)]
pub struct RawStatusPair {
    pub class: RawStatusClass,
    pub detail: RawStatusDetail,
}

impl Default for RawStatusPair {
    fn default() -> Self {
        Self::new()
    }
}

impl RawStatusPair {
    #[inline]
    pub fn new() -> Self {
        Self {
            class: RawStatusClass::default(),
            detail: RawStatusDetail::default(),
        }
    }

    /// Decode both class and detail together.
    #[inline]
    pub fn decode(self) -> Result<(StatusClass, StatusDetail)> {
        let class = self.class.decode();
        let detail = self.detail.decode_with_class(class)?;
        Ok((class, detail))
    }

    /// Encode from typed values.
    #[inline]
    pub fn encode(&mut self, class: StatusClass, detail: StatusDetail) -> Result<()> {
        // sanity check: detail must match class (optional, but helps catch bugs)
        match (class, &detail) {
            (StatusClass::Success, StatusDetail::Success(_))
            | (StatusClass::Redirection, StatusDetail::Redirection(_))
            | (StatusClass::InitiatorError, StatusDetail::InitiatorErr(_))
            | (StatusClass::TargetError, StatusDetail::TargetErr(_)) => {},
            _ => bail!("StatusDetail does not match StatusClass"),
        }
        self.class.encode(class);
        self.detail.encode(detail);
        Ok(())
    }
}

impl fmt::Debug for RawStatusPair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.decode() {
            Ok((c, d)) => write!(f, "RawStatusPair({:?}, {:?})", c, d),
            Err(_) => write!(
                f,
                "RawStatusPair(class={:?}, detail=0x{:02x})",
                self.class.decode(),
                self.detail.raw()
            ),
        }
    }
}