iscsi-client-rs 0.0.9

A pure-Rust iSCSI initiator library
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! This module defines the state machine for the iSCSI SCSI Write command.
//! It includes the states, context, and transitions for handling the write
//! operation.

// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2012-2025 Andrei Maltsev

use std::{
    marker::PhantomData,
    pin::Pin,
    sync::{
        Arc,
        atomic::{AtomicU32, Ordering},
    },
};

use anyhow::{Context, Result, anyhow, bail};
use tokio_util::sync::CancellationToken;
use tracing::debug;

use crate::{
    cfg::enums::YesNo,
    client::client::ClientConnection,
    models::{
        command::{
            common::{ResponseCode, ScsiStatus, TaskAttribute},
            request::{ScsiCommandRequest, ScsiCommandRequestBuilder},
            response::ScsiCommandResponse,
        },
        common::{BasicHeaderSegment, Builder, HEADER_LEN, SendingData},
        data::{
            request::{ScsiDataOut, ScsiDataOutBuilder},
            sense_data::SenseData,
        },
        data_fromat::{PduRequest, PduResponse},
        ready_2_transfer::response::ReadyToTransfer,
    },
    state_machine::common::{StateMachine, StateMachineCtx, Transition},
};

/// This structure represents the context for a SCSI Write operation.
#[derive(Debug)]
pub struct WriteCtx<'a> {
    _lt: PhantomData<&'a ()>,

    /// The client connection.
    pub conn: Arc<ClientConnection>,
    /// The Logical Unit Number.
    pub lun: u64,
    /// The Initiator Task Tag.
    pub itt: u32,
    /// The Command Sequence Number.
    pub cmd_sn: Arc<AtomicU32>,
    /// The Expected Status Sequence Number.
    pub exp_stat_sn: Arc<AtomicU32>,

    /// The SCSI Command Descriptor Block.
    pub cdb: [u8; 16],
    /// The data to be written.
    pub payload: Vec<u8>,
    /// A buffer for the BHS.
    pub buf: [u8; HEADER_LEN],

    /// The number of bytes that have been sent.
    pub sent_bytes: usize,
    /// The total number of bytes to be sent.
    pub total_bytes: usize,

    /// The last received command response.
    pub last_response: Option<PduResponse<ScsiCommandResponse>>,
    state: Option<WriteStates>,
}

#[allow(clippy::too_many_arguments)]
impl<'a> WriteCtx<'a> {
    /// Creates a new `WriteCtx` for a SCSI Write operation.
    pub fn new(
        conn: Arc<ClientConnection>,
        lun: u64,
        itt: Arc<AtomicU32>,
        cmd_sn: Arc<AtomicU32>,
        exp_stat_sn: Arc<AtomicU32>,
        cdb: [u8; 16],
        payload: impl Into<Vec<u8>>,
    ) -> Self {
        Self {
            conn,
            lun,
            itt: itt.fetch_add(1, Ordering::SeqCst),
            cmd_sn,
            exp_stat_sn,
            cdb,
            payload: payload.into(),
            buf: [0u8; HEADER_LEN],
            sent_bytes: 0,
            total_bytes: 0,
            last_response: None,
            state: Some(WriteStates::Start(Start)),
            _lt: PhantomData,
        }
    }

    /// Sends the SCSI Write command.
    async fn send_write_command(&mut self) -> Result<()> {
        let cmd_sn = self.cmd_sn.fetch_add(1, Ordering::SeqCst);
        let esn = self.exp_stat_sn.load(Ordering::SeqCst);

        self.total_bytes = self.payload.len();

        let header = ScsiCommandRequestBuilder::new()
            .lun(self.lun)
            .initiator_task_tag(self.itt)
            .cmd_sn(cmd_sn)
            .exp_stat_sn(esn)
            .expected_data_transfer_length(self.total_bytes as u32)
            .scsi_descriptor_block(&self.cdb)
            .write()
            .task_attribute(TaskAttribute::Simple);

        header.header.to_bhs_bytes(&mut self.buf)?;
        let pdu = PduRequest::<ScsiCommandRequest>::new_request(self.buf, &self.conn.cfg);
        self.conn.send_request(self.itt, pdu).await?;

        Ok(())
    }

    /// Receives a Ready To Transfer (R2T) PDU.
    async fn recv_r2t(&self, itt: u32) -> Result<PduResponse<ReadyToTransfer>> {
        let r2t: PduResponse<ReadyToTransfer> = self.conn.read_response(itt).await?;
        let header = r2t.header_view()?;
        self.exp_stat_sn
            .store(header.stat_sn.get().wrapping_add(1), Ordering::SeqCst);
        Ok(r2t)
    }

    /// Sends a window of data to the target.
    async fn send_data(
        &mut self,
        itt: u32,
        ttt: u32,
        offset: usize,
        len: usize,
    ) -> Result<usize> {
        let mut next_data_sn = 0;
        if len == 0 {
            bail!("Refuse to send Data-Out with zero length");
        }
        let end = offset
            .checked_add(len)
            .ok_or_else(|| anyhow!("offset+len overflow"))?;
        if end > self.payload.len() {
            bail!(
                "Data window [{offset}..{end}) exceeds payload {}",
                self.payload.len()
            );
        }

        let mrdsl = self.peer_mrdsl();
        if mrdsl == 0 {
            bail!("MRDSL is zero");
        }
        let to_send_total = len;

        let mut sent = 0usize;
        while sent < to_send_total {
            let take = (to_send_total - sent).min(mrdsl);
            let off = offset + sent;
            let last_chunk_in_window = sent + take == to_send_total;

            let header = ScsiDataOutBuilder::new()
                .lun(self.lun)
                .initiator_task_tag(itt)
                .target_transfer_tag(ttt)
                .exp_stat_sn(self.exp_stat_sn.load(Ordering::SeqCst))
                .buffer_offset(off as u32)
                .data_sn(next_data_sn);

            header.header.to_bhs_bytes(self.buf.as_mut_slice())?;

            let mut pdu =
                PduRequest::<ScsiDataOut>::new_request(self.buf, &self.conn.cfg);

            let header = pdu.header_view_mut()?;

            if last_chunk_in_window {
                header.set_final_bit();
            } else {
                header.set_continue_bit();
            }

            pdu.append_data(&self.payload[off..off + take]);

            self.conn.send_request(itt, pdu).await?;

            next_data_sn = next_data_sn.wrapping_add(1);
            sent += take;
        }

        Ok(sent)
    }

    /// Waits for the final SCSI response and validates it.
    async fn wait_scsi_response(&mut self, itt: u32) -> Result<()> {
        let rsp: PduResponse<ScsiCommandResponse> = self.conn.read_response(itt).await?;
        let header = rsp.header_view()?;
        self.exp_stat_sn
            .store(header.stat_sn.get().wrapping_add(1), Ordering::SeqCst);

        if header.response.decode()? != ResponseCode::CommandCompleted {
            bail!("WRITE failed: response={:?}", header.response);
        }
        if header.status.decode()? != ScsiStatus::Good {
            let sense = SenseData::parse(rsp.data()?)?;
            bail!("WRITE failed: {:?}", sense);
        }

        self.last_response = Some(rsp);

        Ok(())
    }

    /// Returns whether the peer expects an initial R2T.
    #[inline]
    fn peer_initial_r2t(&self) -> bool {
        self.conn.cfg.login.write_flow.initial_r2t == YesNo::Yes
    }

    /// Returns whether the peer accepts immediate data.
    #[inline]
    fn peer_immediate_data(&self) -> bool {
        self.conn.cfg.login.write_flow.immediate_data == YesNo::Yes
    }

    /// Returns the peer's first burst length.
    #[inline]
    fn peer_first_burst(&self) -> usize {
        self.conn.cfg.login.flow.first_burst_length as usize
    }

    /// Returns the peer's maximum burst length.
    #[inline]
    fn peer_max_burst(&self) -> usize {
        self.conn.cfg.login.flow.max_burst_length as usize
    }

    /// Returns the peer's maximum receive data segment length.
    #[inline]
    fn peer_mrdsl(&self) -> usize {
        self.conn.cfg.login.flow.max_recv_data_segment_length as usize
    }

    /// Sends the SCSI Write command with immediate data.
    async fn send_write_cmd_with_immediate(&mut self, imm_len: usize) -> Result<()> {
        let cmd_sn = self.cmd_sn.fetch_add(1, Ordering::SeqCst);
        let esn = self.exp_stat_sn.load(Ordering::SeqCst);
        self.total_bytes = self.payload.len();

        let header = ScsiCommandRequestBuilder::new()
            .lun(self.lun)
            .initiator_task_tag(self.itt)
            .cmd_sn(cmd_sn)
            .exp_stat_sn(esn)
            .expected_data_transfer_length(self.total_bytes as u32)
            .scsi_descriptor_block(&self.cdb)
            .write()
            .task_attribute(TaskAttribute::Simple);

        header.header.to_bhs_bytes(&mut self.buf)?;
        let mut pdu =
            PduRequest::<ScsiCommandRequest>::new_request(self.buf, &self.conn.cfg);

        if imm_len > 0 {
            pdu.append_data(&self.payload[0..imm_len]);
        }

        self.conn.send_request(self.itt, pdu).await?;
        self.sent_bytes = imm_len;
        Ok(())
    }

    /// Sends an unsolicited window of data.
    async fn send_unsolicited_window(
        &mut self,
        offset: usize,
        len: usize,
    ) -> Result<usize> {
        let mrdsl = self.peer_mrdsl();
        if len == 0 {
            return Ok(0);
        }
        if offset + len > self.payload.len() {
            bail!(
                "unsolicited window [{offset}..{}) exceeds payload {}",
                offset + len,
                self.payload.len()
            );
        }

        let mut next_data_sn = 0u32;
        let mut sent = 0usize;
        while sent < len {
            let take = (len - sent).min(mrdsl);
            let off = offset + sent;
            let last = sent + take == len;

            let header = ScsiDataOutBuilder::new()
                .lun(self.lun)
                .initiator_task_tag(self.itt)
                .target_transfer_tag(u32::MAX)
                .exp_stat_sn(self.exp_stat_sn.load(Ordering::SeqCst))
                .buffer_offset(off as u32)
                .data_sn(next_data_sn);

            header.header.to_bhs_bytes(self.buf.as_mut_slice())?;

            let mut pdu =
                PduRequest::<ScsiDataOut>::new_request(self.buf, &self.conn.cfg);
            {
                let h = pdu.header_view_mut()?;
                h.set_data_length_bytes(take as u32);
                if last {
                    h.set_final_bit();
                } else {
                    h.set_continue_bit();
                }
            }
            pdu.append_data(&self.payload[off..off + take]);
            self.conn.send_request(self.itt, pdu).await?;

            next_data_sn = next_data_sn.wrapping_add(1);
            sent += take;
        }
        Ok(sent)
    }
}

/// Represents the initial state of a write operation.
#[derive(Debug)]
pub struct Start;

/// Represents the state of waiting for a Ready To Transfer (R2T) PDU.
#[derive(Debug)]
pub struct WaitR2T;

/// Represents the final state of a write operation.
#[derive(Debug)]
pub struct Finish;

/// Defines the possible states for a SCSI Write operation state machine.
#[derive(Debug)]
pub enum WriteStates {
    /// The initial state.
    Start(Start),
    /// Waiting for an R2T PDU.
    WaitR2T(WaitR2T),
    /// The final state.
    Finish(Finish),
}

pub type WriteStep = Transition<WriteStates, Result<()>>;

/// IssueCmd
///
/// 1) Send SCSI Command (WRITE) with *no* data in the command PDU.
/// 2) If payload is empty → go straight to waiting for SCSI Response. Otherwise
///    → wait for R2T.
impl<'ctx> StateMachine<WriteCtx<'ctx>, WriteStep> for Start {
    type StepResult<'a>
        = Pin<Box<dyn Future<Output = WriteStep> + Send + 'a>>
    where
        Self: 'a,
        WriteCtx<'ctx>: 'a;

    fn step<'a>(&'a self, ctx: &'a mut WriteCtx<'ctx>) -> Self::StepResult<'a> {
        Box::pin(async move {
            ctx.total_bytes = ctx.payload.len();

            let use_immediate = !ctx.peer_initial_r2t() && ctx.peer_immediate_data();
            if use_immediate && ctx.total_bytes > 0 {
                let fbl = ctx
                    .peer_first_burst()
                    .min(ctx.peer_max_burst())
                    .min(ctx.total_bytes);
                let imm_len = fbl.min(ctx.peer_mrdsl());
                if let Err(e) = ctx.send_write_cmd_with_immediate(imm_len).await {
                    return Transition::Done(Err(e));
                }

                if fbl > imm_len {
                    match ctx.send_unsolicited_window(imm_len, fbl - imm_len).await {
                        Ok(s) => {
                            ctx.sent_bytes += s;
                        },
                        Err(e) => return Transition::Done(Err(e)),
                    }
                }

                if ctx.sent_bytes >= ctx.total_bytes {
                    Transition::Next(WriteStates::Finish(Finish), Ok(()))
                } else {
                    Transition::Next(WriteStates::WaitR2T(WaitR2T), Ok(()))
                }
            } else {
                if let Err(e) = ctx.send_write_command().await {
                    return Transition::Done(Err(e));
                }
                if ctx.total_bytes == 0 {
                    Transition::Next(WriteStates::Finish(Finish), Ok(()))
                } else {
                    Transition::Next(WriteStates::WaitR2T(WaitR2T), Ok(()))
                }
            }
        })
    }
}

/// WaitR2T
///
/// Await an R2T. Compute the data window (offset,len) safely,
/// then move to SendWindow. We assume sequential windows.
impl<'ctx> StateMachine<WriteCtx<'ctx>, WriteStep> for WaitR2T {
    type StepResult<'a>
        = Pin<Box<dyn Future<Output = WriteStep> + Send + 'a>>
    where
        Self: 'a,
        WriteCtx<'ctx>: 'a;

    fn step<'a>(&'a self, ctx: &'a mut WriteCtx<'ctx>) -> Self::StepResult<'a> {
        Box::pin(async move {
            let itt = ctx.itt;
            let r2t = match ctx.recv_r2t(itt).await {
                Ok(v) => v,
                Err(e) => return Transition::Done(Err(e)),
            };
            let h = match r2t.header_view() {
                Ok(h) => h,
                Err(e) => {
                    return Transition::Done(Err(anyhow!(
                        "failed read ReadyToTransfer: {e}"
                    )));
                },
            };

            let ttt = h.target_transfer_tag.get();
            let offset = h.buffer_offset.get() as usize;
            let want = h.desired_data_transfer_length.get() as usize;

            if offset >= ctx.payload.len() {
                return Transition::Done(Err(anyhow!(
                    "R2T buffer_offset {} beyond payload {}",
                    offset,
                    ctx.payload.len()
                )));
            }
            let remaining = ctx.payload.len() - offset;
            let len = want.min(remaining);
            if len == 0 {
                return Transition::Done(Err(anyhow!(
                    "R2T window has zero DesiredDataTransferLength (offset={offset}, \
                     want={want})"
                )));
            }

            let sent = match ctx.send_data(itt, ttt, offset, len).await {
                Ok(x) => x,
                Err(e) => return Transition::Done(Err(e)),
            };
            ctx.sent_bytes = ctx.sent_bytes.saturating_add(sent);

            if ctx.sent_bytes >= ctx.total_bytes {
                Transition::Next(WriteStates::Finish(Finish), Ok(()))
            } else {
                Transition::Stay(Ok(()))
            }
        })
    }
}

/// WaitResp
///
/// Final step: wait for SCSI Command Response and validate GOOD status.
impl<'ctx> StateMachine<WriteCtx<'ctx>, WriteStep> for Finish {
    type StepResult<'a>
        = Pin<Box<dyn Future<Output = WriteStep> + Send + 'a>>
    where
        Self: 'a,
        WriteCtx<'ctx>: 'a;

    fn step<'a>(&'a self, ctx: &'a mut WriteCtx<'ctx>) -> Self::StepResult<'a> {
        Box::pin(async move {
            let itt = ctx.itt;
            match ctx.wait_scsi_response(itt).await {
                Ok(()) => Transition::Done(Ok(())),
                Err(e) => Transition::Done(Err(e)),
            }
        })
    }
}

/// Represents the outcome of a completed SCSI Write operation.
#[derive(Debug)]
pub struct WriteOutcome {
    /// The final SCSI Command Response.
    pub last_response: PduResponse<ScsiCommandResponse>,
    /// The number of bytes that were sent.
    pub sent_bytes: usize,
    /// The total number of bytes that were intended to be sent.
    pub total_bytes: usize,
}

impl<'ctx> StateMachineCtx<WriteCtx<'ctx>, WriteOutcome> for WriteCtx<'ctx> {
    async fn execute(&mut self, _cancel: &CancellationToken) -> Result<WriteOutcome> {
        debug!("Loop WRITE");

        loop {
            let state = self.state.take().context("state must be set WriteCtx")?;
            let tr = match &state {
                WriteStates::Start(s) => s.step(self).await,
                WriteStates::WaitR2T(s) => s.step(self).await,
                WriteStates::Finish(s) => s.step(self).await,
            };

            match tr {
                Transition::Next(next, r) => {
                    r?;
                    self.state = Some(next);
                },
                Transition::Stay(Ok(_)) => {
                    self.state = Some(match state {
                        WriteStates::Start(_) => WriteStates::Start(Start),
                        WriteStates::WaitR2T(_) => WriteStates::WaitR2T(WaitR2T),
                        WriteStates::Finish(_) => WriteStates::Finish(Finish),
                    });
                },
                Transition::Stay(Err(e)) => return Err(e),
                Transition::Done(r) => {
                    r?;
                    return Ok(WriteOutcome {
                        last_response: self
                            .last_response
                            .take()
                            .ok_or_else(|| anyhow!("no last response in ctx"))?,
                        sent_bytes: self.sent_bytes,
                        total_bytes: self.total_bytes,
                    });
                },
            }
        }
    }
}