T2 checkpoint 9: iSCSI parameter negotiation + digest=None + SendTargets discovery

V2 mechanism port per assignment §4.3 ckpt 9 allowlist. Three
allowed mechanisms ported; nothing outside the allowlist is
introduced. The port discipline (mechanism-only, no V2 authority/
storage/auth) is preserved.

Why now: enables `iscsiadm -m discovery -t sendtargets` and a
real `iscsiadm -m node --login` to interoperate with the T2
target. L2-OS work on m01 (ckpt 11+) needs both; doing the port
once here keeps the ckpt-driven scope tight per the rule "port
the smallest required mechanism, not the directory".

Ports landed (all from weed/storage/blockvol/iscsi/):

core/frontend/iscsi/params.go (NEW)
  Text key=value parser/encoder + numeric/boolean negotiation
  helpers (RFC 7143 §6 + §13). CHAP helpers from V2 NOT ported
  — auth is T8.

core/frontend/iscsi/login.go (REWROTE the minimal stub)
  Full LoginNegotiator state machine: SecurityNeg → LoginOp →
  FullFeature with parameter exchange. NegotiableConfig captures
  the per-target profile (MaxRecv, MaxBurst, FirstBurst, R2T,
  ImmediateData, etc.) with DefaultNegotiableConfig() matching
  V2 sane defaults for Linux open-iscsi compat.
  Identity capture (InitiatorName/SessionType/TargetName);
  Normal sessions resolve TargetName via TargetResolver;
  Discovery sessions skip the resolver check per spec.
  Digest negotiation answers "None" for HeaderDigest /
  DataDigest (T2 explicitly does not implement digest verify;
  closure report won't claim digest security).

core/frontend/iscsi/discovery.go (NEW)
  HandleTextRequest implements SendTargets. Multi-value
  TargetName/TargetAddress encoding (the discovery exception to
  Params duplicate-key rule). TargetLister interface for the
  session to pull a live target list at request time.

core/frontend/iscsi/session.go (MOD)
  loginPhase replaced its 1-shot "buildLoginResponse" with the
  real negotiator loop (multi-round support). dispatch handles
  OpTextReq via HandleTextRequest. Discovery sessions reject
  SCSI commands (RFC 7143 §6.2). Session struct now carries
  NegotiableConfig + TargetResolver + TargetLister via newSession.

core/frontend/iscsi/target.go (MOD)
  TargetConfig: added IQN (now load-bearing — the resolver
  requires it for Normal-session login), PortalAddr (operator
  override for SendTargets advertised address), Negotiation.
  Target satisfies TargetResolver (HasTarget(name)==name==IQN)
  and TargetLister (single-target list).

core/frontend/iscsi/client_support_test.go (MOD)
  Test client now sends InitiatorName/SessionType/TargetName +
  digest negotiation params on login (the negotiator now
  enforces V2-compatible required fields). loginOptions struct
  lets tests opt into Discovery sessions or non-default identity.

NEW tests (sw-owned regression):

  params_test.go  10 tests:
    - encode/parse roundtrip preserves order
    - parse rejects malformed / empty key / duplicate key
    - parse skips trailing nul
    - Set replaces existing key in place
    - NegotiateNumber min(offered, ours) + clamp + non-numeric reject
    - NegotiateBool AND semantics + invalid value
    - BoolStr Yes/No

  login_test.go  7 tests:
    - DirectLoginOpToFullFeature: V2 "skip security" path used by
      our test client; identity captured, digests echoed None,
      TargetPortalGroupTag present (RFC 7143 §13.9).
    - MultiRound_SecurityThenLoginOp: 3-round flow that iscsiadm
      uses by default.
    - DiscoverySession_NoTargetCheck: Discovery skips resolver.
    - RejectMissingInitiatorName: status 0x02 detail 0x07.
    - RejectUnknownTargetName: status 0x02 detail 0x03 (NotFound).
    - OperationalNegotiation: MaxBurst min, FirstBurst min,
      InitialR2T OR semantics.
    - UnknownKey_NotUnderstood per RFC.

  discovery_test.go  5 tests:
    - EncodeDiscoveryTargets: 1 target, empty, omits empty Address.
    - HandleTextRequest: SendTargets All / by-name / no key.
    - TestT2Route_ISCSI_SendTargetsDiscovery: real in-process
      Discovery session over wire — login as Discovery, send
      SendTargets=All, verify TargetName + TargetAddress
      (loopback + portal-group tag) come back. iscsiadm-shaped
      end-to-end on the protocol layer (no OS initiator yet).

Tests green (no regressions):
  core/frontend/iscsi: 54 tests (was 31; +23 ckpt 9)
  core/frontend/nvme:  unchanged (26)
  All other packages:  unchanged.

Sign-off impact: T2A-iSCSI-provisional unchanged. Ckpt 9 is
preparation for L2-OS work; product-ready promotion remains
gated on L2-OS critical cells (i2/i3) running on m01.

Stop rule observed (§4.3): no port outside the allowlist;
no stale-path semantics weakening; no V2 authority/storage
introduction.
This commit is contained in:
wzcheng99 committed 2026-04-21 21:50:22 -07:00
1 parent e00d725cb5
commit 0d81c9bafc
9 files changed
+1312 -60

No files matched your search

@@ -26,7 +26,22 @@ type testClient struct {
tsih uint16
}
// loginOptions tunes the test client's login behavior. Defaults
// produce a single-round Normal-session login with the canonical
// test target name. Tests that need Discovery sessions or a
// custom TargetName override fields.
type loginOptions struct {
SessionType string // "" → "Normal"
TargetName string // "" → "iqn.2026-04.example.v3:v1"
InitiatorName string // "" → "iqn.2026-04.example.host:test"
}
func dialAndLogin(t *testing.T, addr string) *testClient {
t.Helper()
return dialAndLoginOpts(t, addr, loginOptions{})
}
func dialAndLoginOpts(t *testing.T, addr string, opts loginOptions) *testClient {
t.Helper()
conn, err := net.DialTimeout("tcp", addr, 5*time.Second)
if err != nil {
@@ -35,18 +50,43 @@ func dialAndLogin(t *testing.T, addr string) *testClient {
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
c := &testClient{conn: conn, cmdSN: 0, itt: 1}
// Send a single-round login request that transits straight
// to FullFeature. CSG=LoginOp, NSG=FullFeature, Transit=1.
if opts.SessionType == "" {
opts.SessionType = iscsi.SessionTypeNormal
}
if opts.InitiatorName == "" {
opts.InitiatorName = "iqn.2026-04.example.host:test"
}
if opts.TargetName == "" && opts.SessionType == iscsi.SessionTypeNormal {
opts.TargetName = "iqn.2026-04.example.v3:v1"
}
// Single-round login: CSG=LoginOp, NSG=FullFeature, Transit=1.
// Carries InitiatorName/SessionType/TargetName + minimal
// operational params. The negotiator handles the direct
// LoginOp jump (V2-compatible behavior).
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpLoginReq)
req.SetImmediate(true)
req.SetLoginStages(iscsi.StageLoginOp, iscsi.StageFullFeature)
req.SetLoginTransit(true)
// ISID: a fixed test identity (6 bytes).
req.SetISID([6]byte{0x02, 0x3d, 0x00, 0x00, 0x00, 0x01})
req.SetInitiatorTaskTag(c.itt)
c.itt++
req.SetCmdSN(c.cmdSN)
params := iscsi.NewParams()
params.Set("InitiatorName", opts.InitiatorName)
params.Set("SessionType", opts.SessionType)
if opts.TargetName != "" {
params.Set("TargetName", opts.TargetName)
}
params.Set("HeaderDigest", "None")
params.Set("DataDigest", "None")
params.Set("MaxRecvDataSegmentLength", "262144")
params.Set("InitialR2T", "Yes")
params.Set("ImmediateData", "Yes")
req.DataSegment = params.Encode()
if err := iscsi.WritePDU(conn, req); err != nil {
t.Fatalf("write login: %v", err)
}
@@ -0,0 +1,89 @@
package iscsi
// SendTargets discovery (RFC 7143 §12.3) — T2 ckpt 9 mechanism
// port. Adapted from weed/storage/blockvol/iscsi/discovery.go.
//
// Discovery is what `iscsiadm -m discovery -t sendtargets -p ADDR`
// uses: open a Discovery session, issue a Text Request with
// SendTargets=All, receive a list of TargetName=... +
// TargetAddress=... pairs, then logout. The volume host
// advertises only the target(s) it serves; multi-target /
// portal-group routing is later operator surface (T8+).
// DiscoveryTarget is one entry in a SendTargets response.
type DiscoveryTarget struct {
Name string // IQN, e.g. "iqn.2026-04.example.v3:v1"
Address string // "ip:port,portal-group", e.g. "127.0.0.1:3260,1"
}
// HandleTextRequest processes one Text Request PDU. Currently
// supports SendTargets only; other text-key requests return an
// empty response (RFC 7143 §6 allows this).
func HandleTextRequest(req *PDU, targets []DiscoveryTarget) *PDU {
resp := &PDU{}
resp.SetOpcode(OpTextResp)
resp.SetOpSpecific1(FlagF) // Final
resp.SetInitiatorTaskTag(req.InitiatorTaskTag())
resp.SetTargetTransferTag(0xFFFFFFFF) // no continuation
params, err := ParseParams(req.DataSegment)
if err != nil {
return resp
}
val, ok := params.Get("SendTargets")
if !ok {
return resp
}
// Discovery responses use multi-value encoding (TargetName
// + TargetAddress repeats per target), which our normal
// Params encoder rejects (duplicate keys). Use a dedicated
// emitter.
var matched []DiscoveryTarget
switch val {
case "All":
matched = targets
default:
for _, tgt := range targets {
if tgt.Name == val {
matched = append(matched, tgt)
break
}
}
}
if data := EncodeDiscoveryTargets(matched); len(data) > 0 {
resp.DataSegment = data
}
return resp
}
// EncodeDiscoveryTargets serializes a target list into
// SendTargets text format. Each target produces:
//
// TargetName=<iqn>\0TargetAddress=<addr>\0
//
// Repeated TargetName / TargetAddress keys are SPECIFIC to
// discovery responses (RFC 7143 §6.1 exception); normal
// negotiation rejects duplicates.
func EncodeDiscoveryTargets(targets []DiscoveryTarget) []byte {
if len(targets) == 0 {
return nil
}
var buf []byte
for _, tgt := range targets {
buf = append(buf, "TargetName="+tgt.Name+"\x00"...)
if tgt.Address != "" {
buf = append(buf, "TargetAddress="+tgt.Address+"\x00"...)
}
}
return buf
}
// TargetLister is the seam Target implements so the session
// layer can resolve the discovery list at request time. Returning
// the live list (rather than capturing it at session start) lets
// future multi-target hosts add/remove targets without
// reshuffling sessions.
type TargetLister interface {
ListTargets() []DiscoveryTarget
}
@@ -0,0 +1,165 @@
// Ownership: sw unit + component tests for SendTargets discovery.
// T2 ckpt 9 mechanism port from V2 discovery.go.
package iscsi_test
import (
"bytes"
"net"
"strings"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
"github.com/seaweedfs/seaweed-block/core/frontend/testback"
)
func TestEncodeDiscoveryTargets_OneTarget(t *testing.T) {
got := iscsi.EncodeDiscoveryTargets([]iscsi.DiscoveryTarget{
{Name: "iqn.example:t1", Address: "127.0.0.1:3260,1"},
})
want := "TargetName=iqn.example:t1\x00TargetAddress=127.0.0.1:3260,1\x00"
if string(got) != want {
t.Fatalf("got %q\nwant %q", got, want)
}
}
func TestEncodeDiscoveryTargets_Empty(t *testing.T) {
if got := iscsi.EncodeDiscoveryTargets(nil); got != nil {
t.Fatalf("nil input → %q, want nil", got)
}
}
func TestEncodeDiscoveryTargets_OmitsEmptyAddress(t *testing.T) {
got := iscsi.EncodeDiscoveryTargets([]iscsi.DiscoveryTarget{
{Name: "iqn.example:t1"},
})
if !bytes.Contains(got, []byte("TargetName=iqn.example:t1\x00")) {
t.Fatalf("missing TargetName: %q", got)
}
if bytes.Contains(got, []byte("TargetAddress=")) {
t.Fatalf("empty Address should not emit TargetAddress: %q", got)
}
}
func TestHandleTextRequest_SendTargetsAll(t *testing.T) {
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpTextReq)
p := iscsi.NewParams()
p.Set("SendTargets", "All")
req.DataSegment = p.Encode()
targets := []iscsi.DiscoveryTarget{
{Name: "iqn.a", Address: "1.1.1.1:3260,1"},
{Name: "iqn.b", Address: "1.1.1.2:3260,1"},
}
resp := iscsi.HandleTextRequest(req, targets)
if resp.Opcode() != iscsi.OpTextResp {
t.Fatalf("opcode=0x%02x want TextResp", resp.Opcode())
}
body := string(resp.DataSegment)
if !strings.Contains(body, "TargetName=iqn.a") || !strings.Contains(body, "TargetName=iqn.b") {
t.Fatalf("All did not emit both targets: %q", body)
}
}
func TestHandleTextRequest_SendTargetsByName(t *testing.T) {
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpTextReq)
p := iscsi.NewParams()
p.Set("SendTargets", "iqn.b")
req.DataSegment = p.Encode()
targets := []iscsi.DiscoveryTarget{
{Name: "iqn.a", Address: "1.1.1.1:3260,1"},
{Name: "iqn.b", Address: "1.1.1.2:3260,1"},
}
resp := iscsi.HandleTextRequest(req, targets)
body := string(resp.DataSegment)
if !strings.Contains(body, "TargetName=iqn.b") {
t.Fatalf("by-name did not emit iqn.b: %q", body)
}
if strings.Contains(body, "TargetName=iqn.a") {
t.Fatalf("by-name leaked iqn.a: %q", body)
}
}
func TestHandleTextRequest_NoSendTargets_EmptyResponse(t *testing.T) {
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpTextReq)
resp := iscsi.HandleTextRequest(req, []iscsi.DiscoveryTarget{
{Name: "iqn.a", Address: "1.1.1.1:3260,1"},
})
if len(resp.DataSegment) != 0 {
t.Fatalf("no SendTargets key → expected empty data, got %q", resp.DataSegment)
}
}
// Component-level: open a Discovery session against a real
// in-process Target, issue Text/SendTargets=All, verify the
// target's IQN comes back. This is the iscsiadm discovery
// pre-condition that ckpt 9 enables.
func TestT2Route_ISCSI_SendTargetsDiscovery(t *testing.T) {
rec := testback.NewRecordingBackend(frontend.Identity{
VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1,
})
prov := testback.NewStaticProvider(rec)
tg := iscsi.NewTarget(iscsi.TargetConfig{
Listen: "127.0.0.1:0",
IQN: "iqn.2026-04.example.v3:v1",
VolumeID: "v1",
Provider: prov,
})
addr, err := tg.Start()
if err != nil {
t.Fatalf("target Start: %v", err)
}
defer tg.Close()
cli := dialAndLoginOpts(t, addr, loginOptions{
SessionType: iscsi.SessionTypeDiscovery,
// No TargetName — Discovery sessions don't bind a target.
})
defer func() {
_ = cli.conn.Close()
}()
// Send Text/SendTargets=All over the established session.
req := &iscsi.PDU{}
req.SetOpcode(iscsi.OpTextReq)
req.SetOpSpecific1(iscsi.FlagF)
req.SetInitiatorTaskTag(cli.itt)
cli.itt++
req.SetCmdSN(cli.cmdSN)
cli.cmdSN++
tparams := iscsi.NewParams()
tparams.Set("SendTargets", "All")
req.DataSegment = tparams.Encode()
if err := iscsi.WritePDU(cli.conn, req); err != nil {
t.Fatalf("write Text req: %v", err)
}
_ = cli.conn.SetReadDeadline(time.Now().Add(5 * time.Second))
resp, err := iscsi.ReadPDU(cli.conn)
if err != nil {
t.Fatalf("read Text resp: %v", err)
}
if resp.Opcode() != iscsi.OpTextResp {
t.Fatalf("resp opcode=0x%02x want TextResp", resp.Opcode())
}
if !bytes.Contains(resp.DataSegment, []byte("TargetName=iqn.2026-04.example.v3:v1")) {
t.Fatalf("SendTargets did not include the target's IQN: %q", resp.DataSegment)
}
if !bytes.Contains(resp.DataSegment, []byte("TargetAddress=")) {
t.Fatalf("SendTargets missing TargetAddress: %q", resp.DataSegment)
}
// Verify the advertised address is loopback (matches our bind).
if !bytes.Contains(resp.DataSegment, []byte("127.0.0.1")) {
t.Fatalf("expected loopback in TargetAddress: %q", resp.DataSegment)
}
// Verify it includes the portal-group tag.
if !bytes.Contains(resp.DataSegment, []byte(",1")) {
t.Fatalf("expected portal-group tag '1': %q", resp.DataSegment)
}
_ = net.IPv4zero // silence unused-import linter if net needed elsewhere
}
+352 -42
View File
@@ -1,28 +1,38 @@
package iscsi
// Login negotiation — minimal T2 scope.
// iSCSI login negotiator — T2 ckpt 9 mechanism port.
//
// The V2 implementation does full parameter negotiation
// (MaxRecvDataSegmentLength, HeaderDigest, DataDigest, CHAP,
// etc.) because it needs to interop with OS initiators. For T2
// L1 (in-process component route), we only need a login that
// establishes a session so SCSI commands can flow. T2 L2-OS
// (real initiator) will extend this when the time comes; until
// then, we accept ANY login request with Transit=true and
// respond Success + NSG=FullFeature.
// Adapted from weed/storage/blockvol/iscsi/login.go per
// assignment §4.3 ckpt 9 allowlist:
// - parameter negotiation (MaxRecv, MaxBurst, FirstBurst,
// InitialR2T, ImmediateData, MaxConnections, etc.)
// - digest negotiation to None
// - SecurityNeg → LoginOp → FullFeature stage transitions
//
// The wire format is still real iSCSI login PDUs — just with
// negotiation collapsed into "accept and move on".
// Intentionally NOT ported from V2:
// - CHAP authentication (T8 security)
// - target redirects (multi-target operator surface, later)
// - CHAP method negotiation
//
// Production code path remains "consumer of authority truth":
// no V2 storage / authority bindings appear in this file.
import "errors"
import (
"errors"
"strconv"
)
// Login status class/detail (RFC 7143 §11.13).
const (
LoginStatusSuccess uint8 = 0x00
LoginStatusInitiatorErr uint8 = 0x02
LoginStatusTargetErr uint8 = 0x03
LoginDetailSuccess uint8 = 0x00
LoginDetailInitiatorError uint8 = 0x00
LoginDetailNotFound uint8 = 0x03
LoginDetailMissingParam uint8 = 0x07
LoginDetailTargetError uint8 = 0x00
)
// Errors surfaced during login.
@@ -31,44 +41,344 @@ var (
ErrLoginInvalidRequest = errors.New("iscsi: invalid login request")
)
// buildLoginResponse constructs a Login-Response PDU matching
// the request's ITT / CmdSN fields and granting success. If the
// request has Transit=true and its NSG is FullFeature, the
// response grants the transition; otherwise the response keeps
// the connection in login phase. Data segment is empty (no
// text params) — sufficient for the in-process L1 client.
func buildLoginResponse(req *PDU, tsih uint16) *PDU {
// LoginPhase tracks the negotiator's stage.
type LoginPhase int
const (
LoginPhaseStart LoginPhase = iota
LoginPhaseSecurity
LoginPhaseOperational
LoginPhaseDone
)
// SessionType constants — mirror what iscsiadm sets in the
// SessionType key during login.
const (
SessionTypeNormal = "Normal"
SessionTypeDiscovery = "Discovery"
)
// NegotiableConfig is the per-target negotiation profile. Sane
// defaults match common Linux initiator expectations.
type NegotiableConfig struct {
MaxRecvDataSegmentLength int
MaxBurstLength int
FirstBurstLength int
MaxConnections int
MaxOutstandingR2T int
DefaultTime2Wait int
DefaultTime2Retain int
InitialR2T bool
ImmediateData bool
DataPDUInOrder bool
DataSequenceInOrder bool
ErrorRecoveryLevel int
TargetPortalGroupTag int
TargetAlias string
}
// DefaultNegotiableConfig returns a profile that interoperates
// with typical Linux open-iscsi initiators. Values match V2
// DefaultTargetConfig where the field exists.
func DefaultNegotiableConfig() NegotiableConfig {
return NegotiableConfig{
MaxRecvDataSegmentLength: 262144, // 256 KiB
MaxBurstLength: 262144,
FirstBurstLength: 65536,
MaxConnections: 1,
MaxOutstandingR2T: 1,
DefaultTime2Wait: 2,
DefaultTime2Retain: 0,
InitialR2T: true,
ImmediateData: true,
DataPDUInOrder: true,
DataSequenceInOrder: true,
ErrorRecoveryLevel: 0,
TargetPortalGroupTag: 1,
}
}
// TargetResolver lets the negotiator validate target names
// against the set this server hosts. Discovery sessions skip
// the check; Normal sessions require a known TargetName.
type TargetResolver interface {
HasTarget(name string) bool
}
// LoginNegotiator drives the target side of login negotiation
// across one or many request/response rounds.
type LoginNegotiator struct {
config NegotiableConfig
phase LoginPhase
isid [6]byte
tsih uint16
targetOK bool
// Negotiated outputs (updated as keys are processed).
NegMaxRecvDataSegLen int
NegMaxBurstLength int
NegFirstBurstLength int
NegInitialR2T bool
NegImmediateData bool
InitiatorName string
TargetName string
SessionType string
}
// NewLoginNegotiator constructs a fresh negotiator using the
// given negotiation profile.
func NewLoginNegotiator(cfg NegotiableConfig) *LoginNegotiator {
return &LoginNegotiator{
config: cfg,
phase: LoginPhaseStart,
NegMaxRecvDataSegLen: cfg.MaxRecvDataSegmentLength,
NegMaxBurstLength: cfg.MaxBurstLength,
NegFirstBurstLength: cfg.FirstBurstLength,
NegInitialR2T: cfg.InitialR2T,
NegImmediateData: cfg.ImmediateData,
}
}
// Done returns true if negotiation has reached FullFeature.
func (ln *LoginNegotiator) Done() bool { return ln.phase == LoginPhaseDone }
// Phase returns the current login phase (for diagnostics).
func (ln *LoginNegotiator) Phase() LoginPhase { return ln.phase }
// HandleLoginPDU processes one login request and returns the
// response PDU. Caller writes the response and reads the next
// request until Done() returns true (or response carries a
// reject status).
func (ln *LoginNegotiator) HandleLoginPDU(req *PDU, resolver TargetResolver) *PDU {
resp := &PDU{}
resp.SetOpcode(OpLoginResp)
// Copy stages + transit back: target grants the transition
// the initiator requested (sketch §: minimal login).
resp.SetInitiatorTaskTag(req.InitiatorTaskTag())
resp.SetISID(req.ISID())
resp.SetTSIH(req.TSIH())
if req.Opcode() != OpLoginReq {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailInitiatorError)
return resp
}
csg := req.LoginCSG()
nsg := req.LoginNSG()
transit := req.LoginTransit()
params, err := ParseParams(req.DataSegment)
if err != nil {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailInitiatorError)
return resp
}
respParams := NewParams()
switch csg {
case StageSecurityNeg:
if ln.phase != LoginPhaseStart && ln.phase != LoginPhaseSecurity {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailInitiatorError)
return resp
}
ln.phase = LoginPhaseSecurity
if !ln.captureSessionIdentity(params, resolver, resp) {
return resp
}
ln.isid = req.ISID()
// No CHAP — accept AuthMethod=None.
respParams.Set("AuthMethod", "None")
if transit {
if nsg == StageLoginOp {
ln.phase = LoginPhaseOperational
} else if nsg == StageFullFeature {
ln.phase = LoginPhaseDone
}
}
case StageLoginOp:
// V2 allows direct jump to LoginOp when SecurityNeg was
// skipped. Same here: capture identity in this PDU if not
// done yet.
if ln.phase == LoginPhaseStart {
if !ln.captureSessionIdentity(params, resolver, resp) {
return resp
}
ln.isid = req.ISID()
} else if ln.phase != LoginPhaseSecurity && ln.phase != LoginPhaseOperational {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailInitiatorError)
return resp
}
ln.phase = LoginPhaseOperational
ln.negotiateOperational(params, respParams)
if transit && nsg == StageFullFeature {
ln.phase = LoginPhaseDone
}
default:
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailInitiatorError)
return resp
}
resp.SetLoginStages(csg, nsg)
resp.SetLoginTransit(req.LoginTransit())
// Set final bit (last Login-Response for this round).
if transit {
resp.SetLoginTransit(true)
}
resp.BHS[1] |= FlagF
// Copy ISID + ITT so the initiator can match.
resp.SetISID(req.ISID())
resp.SetInitiatorTaskTag(req.InitiatorTaskTag())
// TSIH: for a new session the target assigns it now.
resp.SetTSIH(tsih)
// StatSN (byte 24-27), ExpCmdSN (28-31), MaxCmdSN (32-35):
// target advances StatSN per response; ExpCmdSN/MaxCmdSN
// echo initiator CmdSN for now (no command queuing pre-FFP).
resp.SetStatSN(0)
resp.SetExpCmdSN(req.CmdSN() + 1)
resp.SetMaxCmdSN(req.CmdSN() + 32)
// Version-min / Version-max bytes 2-3 are zero (iSCSI v0).
// Status class / detail (byte 36 / 37): success.
resp.SetLoginStatus(LoginStatusSuccess, LoginDetailSuccess)
if ln.tsih == 0 {
ln.tsih = 1
}
resp.SetTSIH(ln.tsih)
tpgt := ln.config.TargetPortalGroupTag
if tpgt <= 0 {
tpgt = 1
}
respParams.Set("TargetPortalGroupTag", strconv.Itoa(tpgt))
if respParams.Len() > 0 {
resp.DataSegment = respParams.Encode()
}
return resp
}
// loginGrantsFullFeature reports whether a Login-Request asks
// (and our minimal negotiator accepts) to transit into Full
// Feature Phase. T2 scope: accept any request with Transit=true
// AND NSG=FullFeature.
func loginGrantsFullFeature(req *PDU) bool {
return req.LoginTransit() && req.LoginNSG() == StageFullFeature
// captureSessionIdentity extracts InitiatorName, SessionType,
// and (for Normal sessions) TargetName from the request params.
// Writes a reject into resp and returns false on missing
// required fields.
func (ln *LoginNegotiator) captureSessionIdentity(params *Params, resolver TargetResolver, resp *PDU) bool {
if name, ok := params.Get("InitiatorName"); ok {
ln.InitiatorName = name
} else if ln.InitiatorName == "" {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailMissingParam)
return false
}
if st, ok := params.Get("SessionType"); ok {
ln.SessionType = st
}
if ln.SessionType == "" {
ln.SessionType = SessionTypeNormal
}
if tn, ok := params.Get("TargetName"); ok {
// Normal sessions must name a target this server hosts.
// Discovery sessions skip the check (TargetName is "All"
// or absent for SendTargets).
if ln.SessionType == SessionTypeNormal {
if resolver == nil || !resolver.HasTarget(tn) {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailNotFound)
return false
}
}
ln.TargetName = tn
ln.targetOK = true
} else if ln.SessionType == SessionTypeNormal && !ln.targetOK {
setLoginReject(resp, LoginStatusInitiatorErr, LoginDetailMissingParam)
return false
}
return true
}
// negotiateOperational walks the request's operational params
// and writes responses into respParams.
func (ln *LoginNegotiator) negotiateOperational(req, resp *Params) {
req.Each(func(key, value string) {
switch key {
case "MaxRecvDataSegmentLength":
if v, err := NegotiateNumber(value, ln.config.MaxRecvDataSegmentLength, 512, 16777215); err == nil {
ln.NegMaxRecvDataSegLen = v
// V2 quirk preserved: declare OUR max in response,
// not the negotiated value, so the initiator knows
// our send-side limit. The negotiated value bounds
// what we can RECEIVE.
resp.Set(key, strconv.Itoa(ln.config.MaxRecvDataSegmentLength))
}
case "MaxBurstLength":
if v, err := NegotiateNumber(value, ln.config.MaxBurstLength, 512, 16777215); err == nil {
ln.NegMaxBurstLength = v
resp.Set(key, strconv.Itoa(v))
}
case "FirstBurstLength":
if v, err := NegotiateNumber(value, ln.config.FirstBurstLength, 512, 16777215); err == nil {
ln.NegFirstBurstLength = v
resp.Set(key, strconv.Itoa(v))
}
case "InitialR2T":
// OR semantics per RFC 7143: result is Yes if either
// party says Yes.
if value == "Yes" || ln.config.InitialR2T {
ln.NegInitialR2T = true
} else {
ln.NegInitialR2T = false
}
resp.Set(key, BoolStr(ln.NegInitialR2T))
case "ImmediateData":
if v, err := NegotiateBool(value, ln.config.ImmediateData); err == nil {
ln.NegImmediateData = v
resp.Set(key, BoolStr(v))
}
case "MaxConnections":
resp.Set(key, strconv.Itoa(ln.config.MaxConnections))
case "DataPDUInOrder":
resp.Set(key, BoolStr(ln.config.DataPDUInOrder))
case "DataSequenceInOrder":
resp.Set(key, BoolStr(ln.config.DataSequenceInOrder))
case "DefaultTime2Wait":
resp.Set(key, strconv.Itoa(ln.config.DefaultTime2Wait))
case "DefaultTime2Retain":
resp.Set(key, strconv.Itoa(ln.config.DefaultTime2Retain))
case "MaxOutstandingR2T":
resp.Set(key, strconv.Itoa(ln.config.MaxOutstandingR2T))
case "ErrorRecoveryLevel":
resp.Set(key, strconv.Itoa(ln.config.ErrorRecoveryLevel))
case "HeaderDigest":
// Always negotiate to None in T2 scope; digest
// verification is T8 security.
resp.Set(key, "None")
case "DataDigest":
resp.Set(key, "None")
case "TargetName", "InitiatorName", "SessionType", "AuthMethod":
// Already captured / declarative.
case "TargetAlias", "InitiatorAlias":
// Informational.
default:
resp.Set(key, "NotUnderstood")
}
})
if ln.config.TargetAlias != "" {
resp.Set("TargetAlias", ln.config.TargetAlias)
}
}
func setLoginReject(resp *PDU, class, detail uint8) {
resp.SetLoginStatus(class, detail)
resp.SetLoginTransit(false)
}
// LoginResult is the final negotiated state after Done()=true.
type LoginResult struct {
InitiatorName string
TargetName string
SessionType string
ISID [6]byte
TSIH uint16
MaxRecvDataSegLen int
MaxBurstLength int
FirstBurstLength int
InitialR2T bool
ImmediateData bool
}
// Result returns the final negotiated values.
func (ln *LoginNegotiator) Result() LoginResult {
return LoginResult{
InitiatorName: ln.InitiatorName,
TargetName: ln.TargetName,
SessionType: ln.SessionType,
ISID: ln.isid,
TSIH: ln.tsih,
MaxRecvDataSegLen: ln.NegMaxRecvDataSegLen,
MaxBurstLength: ln.NegMaxBurstLength,
FirstBurstLength: ln.NegFirstBurstLength,
InitialR2T: ln.NegInitialR2T,
ImmediateData: ln.NegImmediateData,
}
}
@@ -0,0 +1,229 @@
// Ownership: sw unit tests for the login negotiator. T2 ckpt 9
// scope: parameter negotiation, digest=None, multi-round
// SecurityNeg → LoginOp → FullFeature, target resolution,
// missing-required-field rejections.
package iscsi_test
import (
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
)
type fakeResolver struct{ names map[string]bool }
func (r *fakeResolver) HasTarget(name string) bool { return r.names[name] }
func mkLoginReq(csg, nsg uint8, transit bool, params *iscsi.Params) *iscsi.PDU {
p := &iscsi.PDU{}
p.SetOpcode(iscsi.OpLoginReq)
p.SetLoginStages(csg, nsg)
p.SetLoginTransit(transit)
p.SetISID([6]byte{0x02, 0x3d, 0, 0, 0, 1})
if params != nil {
p.DataSegment = params.Encode()
}
return p
}
// Single-round LoginOp → FullFeature, no SecurityNeg. Mirrors
// the V2 "skip security" path the in-process Go test client uses.
func TestLoginNegotiator_DirectLoginOpToFullFeature(t *testing.T) {
cfg := iscsi.DefaultNegotiableConfig()
neg := iscsi.NewLoginNegotiator(cfg)
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
params := iscsi.NewParams()
params.Set("InitiatorName", "iqn.example.host:1")
params.Set("SessionType", "Normal")
params.Set("TargetName", "iqn.example:t1")
params.Set("HeaderDigest", "None")
params.Set("DataDigest", "None")
params.Set("MaxRecvDataSegmentLength", "8192")
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
if resp.LoginStatusClass() != iscsi.LoginStatusSuccess {
t.Fatalf("status class=0x%02x detail=0x%02x want Success",
resp.LoginStatusClass(), resp.LoginStatusDetail())
}
if !neg.Done() {
t.Fatalf("Done()=false after Transit→FullFeature; phase=%v", neg.Phase())
}
got := neg.Result()
if got.InitiatorName != "iqn.example.host:1" || got.TargetName != "iqn.example:t1" {
t.Fatalf("captured identity wrong: %+v", got)
}
if got.SessionType != iscsi.SessionTypeNormal {
t.Fatalf("SessionType=%q want Normal", got.SessionType)
}
// Digest negotiation echoed back as None.
respParams, err := iscsi.ParseParams(resp.DataSegment)
if err != nil {
t.Fatalf("ParseParams resp: %v", err)
}
for _, k := range []string{"HeaderDigest", "DataDigest"} {
if v, ok := respParams.Get(k); !ok || v != "None" {
t.Fatalf("%s=%q,%v want None", k, v, ok)
}
}
if v, _ := respParams.Get("TargetPortalGroupTag"); v == "" {
t.Fatal("TargetPortalGroupTag missing in response (RFC 7143 §13.9 violation)")
}
}
// Two-round: SecurityNeg (no transit) → SecurityNeg→LoginOp transit →
// LoginOp→FullFeature transit. iscsiadm's default flow.
func TestLoginNegotiator_MultiRound_SecurityThenLoginOp(t *testing.T) {
neg := iscsi.NewLoginNegotiator(iscsi.DefaultNegotiableConfig())
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
// Round 1: SecurityNeg → SecurityNeg (no transit), declare identity.
r1Params := iscsi.NewParams()
r1Params.Set("InitiatorName", "iqn.example.host:1")
r1Params.Set("SessionType", "Normal")
r1Params.Set("TargetName", "iqn.example:t1")
r1Params.Set("AuthMethod", "None")
r1 := mkLoginReq(iscsi.StageSecurityNeg, iscsi.StageSecurityNeg, false, r1Params)
resp1 := neg.HandleLoginPDU(r1, resolver)
if resp1.LoginStatusClass() != iscsi.LoginStatusSuccess {
t.Fatalf("round 1 status=0x%02x", resp1.LoginStatusClass())
}
if neg.Done() {
t.Fatal("Done() too early after round 1")
}
// Round 2: SecurityNeg → LoginOp transit.
r2 := mkLoginReq(iscsi.StageSecurityNeg, iscsi.StageLoginOp, true, iscsi.NewParams())
resp2 := neg.HandleLoginPDU(r2, resolver)
if resp2.LoginStatusClass() != iscsi.LoginStatusSuccess {
t.Fatalf("round 2 status=0x%02x", resp2.LoginStatusClass())
}
if neg.Phase() != iscsi.LoginPhaseOperational {
t.Fatalf("phase=%v want Operational", neg.Phase())
}
// Round 3: LoginOp → FullFeature transit, with op params.
r3Params := iscsi.NewParams()
r3Params.Set("HeaderDigest", "None")
r3Params.Set("DataDigest", "None")
r3Params.Set("MaxRecvDataSegmentLength", "16384")
r3 := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, r3Params)
resp3 := neg.HandleLoginPDU(r3, resolver)
if resp3.LoginStatusClass() != iscsi.LoginStatusSuccess {
t.Fatalf("round 3 status=0x%02x", resp3.LoginStatusClass())
}
if !neg.Done() {
t.Fatalf("Done()=false after FullFeature transit")
}
}
// Discovery sessions skip the TargetName resolver check.
func TestLoginNegotiator_DiscoverySession_NoTargetCheck(t *testing.T) {
neg := iscsi.NewLoginNegotiator(iscsi.DefaultNegotiableConfig())
// Resolver is empty — Normal session would reject. Discovery
// must NOT consult the resolver.
resolver := &fakeResolver{names: map[string]bool{}}
params := iscsi.NewParams()
params.Set("InitiatorName", "iqn.example.host:1")
params.Set("SessionType", iscsi.SessionTypeDiscovery)
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
if resp.LoginStatusClass() != iscsi.LoginStatusSuccess {
t.Fatalf("Discovery login status=0x%02x detail=0x%02x",
resp.LoginStatusClass(), resp.LoginStatusDetail())
}
if neg.Result().SessionType != iscsi.SessionTypeDiscovery {
t.Fatalf("SessionType=%q", neg.Result().SessionType)
}
}
// Missing InitiatorName → reject with MissingParam.
func TestLoginNegotiator_RejectMissingInitiatorName(t *testing.T) {
neg := iscsi.NewLoginNegotiator(iscsi.DefaultNegotiableConfig())
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
params := iscsi.NewParams()
params.Set("SessionType", "Normal")
params.Set("TargetName", "iqn.example:t1")
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
if resp.LoginStatusClass() != iscsi.LoginStatusInitiatorErr {
t.Fatalf("status=0x%02x want InitiatorErr", resp.LoginStatusClass())
}
if resp.LoginStatusDetail() != iscsi.LoginDetailMissingParam {
t.Fatalf("detail=0x%02x want MissingParam (0x07)", resp.LoginStatusDetail())
}
}
// Normal session with unknown TargetName → reject with NotFound.
func TestLoginNegotiator_RejectUnknownTargetName(t *testing.T) {
neg := iscsi.NewLoginNegotiator(iscsi.DefaultNegotiableConfig())
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
params := iscsi.NewParams()
params.Set("InitiatorName", "iqn.example.host:1")
params.Set("SessionType", "Normal")
params.Set("TargetName", "iqn.example:wrong")
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
if resp.LoginStatusClass() != iscsi.LoginStatusInitiatorErr {
t.Fatalf("status=0x%02x want InitiatorErr", resp.LoginStatusClass())
}
if resp.LoginStatusDetail() != iscsi.LoginDetailNotFound {
t.Fatalf("detail=0x%02x want NotFound (0x03)", resp.LoginStatusDetail())
}
}
// Operational params get negotiated values back. MaxBurst /
// FirstBurst use min(); InitialR2T uses OR.
func TestLoginNegotiator_OperationalNegotiation(t *testing.T) {
cfg := iscsi.DefaultNegotiableConfig()
cfg.MaxBurstLength = 65536
cfg.FirstBurstLength = 32768
cfg.InitialR2T = false // ours says No
neg := iscsi.NewLoginNegotiator(cfg)
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
params := iscsi.NewParams()
params.Set("InitiatorName", "iqn.example.host:1")
params.Set("SessionType", "Normal")
params.Set("TargetName", "iqn.example:t1")
params.Set("MaxBurstLength", "131072") // bigger than ours
params.Set("FirstBurstLength", "16384") // smaller than ours
params.Set("InitialR2T", "Yes") // initiator says Yes → OR semantics
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
respParams, err := iscsi.ParseParams(resp.DataSegment)
if err != nil {
t.Fatalf("ParseParams: %v", err)
}
if v, _ := respParams.Get("MaxBurstLength"); v != "65536" {
t.Fatalf("MaxBurstLength=%q want 65536 (min(ours=65536, theirs=131072))", v)
}
if v, _ := respParams.Get("FirstBurstLength"); v != "16384" {
t.Fatalf("FirstBurstLength=%q want 16384 (min)", v)
}
if v, _ := respParams.Get("InitialR2T"); v != "Yes" {
t.Fatalf("InitialR2T=%q want Yes (OR semantics: theirs=Yes)", v)
}
}
// Unknown operational keys produce NotUnderstood per RFC.
func TestLoginNegotiator_UnknownKey_RespondsNotUnderstood(t *testing.T) {
neg := iscsi.NewLoginNegotiator(iscsi.DefaultNegotiableConfig())
resolver := &fakeResolver{names: map[string]bool{"iqn.example:t1": true}}
params := iscsi.NewParams()
params.Set("InitiatorName", "iqn.example.host:1")
params.Set("SessionType", "Normal")
params.Set("TargetName", "iqn.example:t1")
params.Set("X-Vendor-Extension", "shenanigans")
req := mkLoginReq(iscsi.StageLoginOp, iscsi.StageFullFeature, true, params)
resp := neg.HandleLoginPDU(req, resolver)
respParams, _ := iscsi.ParseParams(resp.DataSegment)
if v, _ := respParams.Get("X-Vendor-Extension"); v != "NotUnderstood" {
t.Fatalf("X-Vendor-Extension=%q want NotUnderstood", v)
}
}
+160
View File
@@ -0,0 +1,160 @@
package iscsi
// iSCSI text parameter encoding (RFC 7143 §6) +
// negotiation helpers (numeric / boolean per RFC 7143 §13).
//
// Ported from weed/storage/blockvol/iscsi/params.go per T2
// assignment §4.3 ckpt 9 allowlist (parameter negotiation
// mechanism only). CHAP / authentication helpers from V2 are
// intentionally NOT ported — auth is T8.
import (
"errors"
"fmt"
"strconv"
"strings"
)
var (
ErrMalformedParam = errors.New("iscsi: malformed parameter (missing '=')")
ErrEmptyKey = errors.New("iscsi: empty parameter key")
ErrDuplicateKey = errors.New("iscsi: duplicate parameter key")
)
// Params is an ordered list of iSCSI key-value parameters.
// Order matters during negotiation (RFC 7143 §6.1), so we use
// a slice rather than a map.
type Params struct {
items []paramItem
}
type paramItem struct {
key string
value string
}
// NewParams returns an empty Params.
func NewParams() *Params { return &Params{} }
// ParseParams decodes "Key=Value\0Key=Value\0..." from raw bytes.
// Trailing nulls / empty segments are ignored. Returns
// ErrDuplicateKey if the same key appears more than once
// (negotiation rule — duplicates are a protocol error).
func ParseParams(data []byte) (*Params, error) {
p := &Params{}
if len(data) == 0 {
return p, nil
}
seen := make(map[string]bool)
parts := strings.Split(string(data), "\x00")
for _, part := range parts {
if part == "" {
continue
}
idx := strings.IndexByte(part, '=')
if idx < 0 {
return nil, fmt.Errorf("%w: %q", ErrMalformedParam, part)
}
key := part[:idx]
if key == "" {
return nil, ErrEmptyKey
}
value := part[idx+1:]
if seen[key] {
return nil, fmt.Errorf("%w: %q", ErrDuplicateKey, key)
}
seen[key] = true
p.items = append(p.items, paramItem{key: key, value: value})
}
return p, nil
}
// Encode serializes parameters to "Key=Value\0" format.
func (p *Params) Encode() []byte {
if len(p.items) == 0 {
return nil
}
var b strings.Builder
for _, item := range p.items {
b.WriteString(item.key)
b.WriteByte('=')
b.WriteString(item.value)
b.WriteByte(0)
}
return []byte(b.String())
}
// Get returns the value for a key, or ("", false) if not present.
func (p *Params) Get(key string) (string, bool) {
for _, item := range p.items {
if item.key == key {
return item.value, true
}
}
return "", false
}
// Set adds or replaces a parameter.
func (p *Params) Set(key, value string) {
for i, item := range p.items {
if item.key == key {
p.items[i].value = value
return
}
}
p.items = append(p.items, paramItem{key: key, value: value})
}
// Len returns the number of parameters.
func (p *Params) Len() int { return len(p.items) }
// Each iterates over key-value pairs in order.
func (p *Params) Each(fn func(key, value string)) {
for _, item := range p.items {
fn(item.key, item.value)
}
}
// --- Negotiation helpers ---
// NegotiateNumber applies "smaller-of-two" semantics (RFC 7143
// §13 numeric negotiation). Clamps offered to [min, max] then
// returns min(offered, ours).
func NegotiateNumber(offered string, ours, min, max int) (int, error) {
v, err := strconv.Atoi(offered)
if err != nil {
return 0, fmt.Errorf("iscsi: invalid numeric value %q: %w", offered, err)
}
if v < min {
v = min
}
if v > max {
v = max
}
if ours < v {
return ours, nil
}
return v, nil
}
// NegotiateBool applies AND semantics (default per RFC 7143).
// Result is true only if both sides agree to true. Caller
// applies OR semantics for InitialR2T separately.
func NegotiateBool(offered string, ours bool) (bool, error) {
switch offered {
case "Yes":
return ours, nil
case "No":
return false, nil
default:
return false, fmt.Errorf("iscsi: invalid boolean value %q", offered)
}
}
// BoolStr renders Yes/No.
func BoolStr(v bool) string {
if v {
return "Yes"
}
return "No"
}
@@ -0,0 +1,165 @@
// Ownership: sw unit tests for parameter parsing/encoding +
// negotiation helpers. T2 ckpt 9 mechanism port from V2.
package iscsi_test
import (
"bytes"
"errors"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/iscsi"
)
func TestParams_RoundtripEncodeParse(t *testing.T) {
p := iscsi.NewParams()
p.Set("InitiatorName", "iqn.example.host:1")
p.Set("SessionType", "Normal")
p.Set("HeaderDigest", "None")
encoded := p.Encode()
out, err := iscsi.ParseParams(encoded)
if err != nil {
t.Fatalf("ParseParams: %v", err)
}
if out.Len() != 3 {
t.Fatalf("got %d params, want 3", out.Len())
}
for k, want := range map[string]string{
"InitiatorName": "iqn.example.host:1",
"SessionType": "Normal",
"HeaderDigest": "None",
} {
if v, ok := out.Get(k); !ok || v != want {
t.Errorf("Get(%q)=%q,%v want %q", k, v, ok, want)
}
}
}
func TestParams_ParseRejectsMissingEquals(t *testing.T) {
_, err := iscsi.ParseParams([]byte("KeyOnly\x00"))
if !errors.Is(err, iscsi.ErrMalformedParam) {
t.Fatalf("got %v, want ErrMalformedParam", err)
}
}
func TestParams_ParseRejectsEmptyKey(t *testing.T) {
_, err := iscsi.ParseParams([]byte("=value\x00"))
if !errors.Is(err, iscsi.ErrEmptyKey) {
t.Fatalf("got %v, want ErrEmptyKey", err)
}
}
func TestParams_ParseRejectsDuplicateKeys(t *testing.T) {
_, err := iscsi.ParseParams([]byte("K=a\x00K=b\x00"))
if !errors.Is(err, iscsi.ErrDuplicateKey) {
t.Fatalf("got %v, want ErrDuplicateKey", err)
}
}
func TestParams_ParseSkipsTrailingNul(t *testing.T) {
p, err := iscsi.ParseParams([]byte("K=v\x00\x00"))
if err != nil {
t.Fatalf("ParseParams: %v", err)
}
if p.Len() != 1 {
t.Fatalf("got %d, want 1", p.Len())
}
}
func TestParams_EncodeEmpty_ReturnsNil(t *testing.T) {
if got := iscsi.NewParams().Encode(); got != nil {
t.Fatalf("empty Encode = %v, want nil", got)
}
}
func TestParams_SetReplacesExisting(t *testing.T) {
p := iscsi.NewParams()
p.Set("K", "v1")
p.Set("K", "v2")
if v, _ := p.Get("K"); v != "v2" {
t.Fatalf("K=%q want v2", v)
}
if p.Len() != 1 {
t.Fatalf("Len=%d want 1 (no duplicate)", p.Len())
}
}
// V2 quirk preservation: Encode emits in insertion order so
// negotiation output matches the order keys were processed.
func TestParams_EncodePreservesInsertionOrder(t *testing.T) {
p := iscsi.NewParams()
p.Set("First", "1")
p.Set("Second", "2")
p.Set("Third", "3")
encoded := p.Encode()
idx1 := bytes.Index(encoded, []byte("First="))
idx2 := bytes.Index(encoded, []byte("Second="))
idx3 := bytes.Index(encoded, []byte("Third="))
if !(idx1 < idx2 && idx2 < idx3) {
t.Fatalf("order lost: idx=(%d,%d,%d)", idx1, idx2, idx3)
}
}
// Numeric negotiation rule: result is min(offered, ours), with
// offered clamped to [min, max].
func TestNegotiateNumber_Behaviors(t *testing.T) {
cases := []struct {
name string
offered string
ours, min, max int
want int
wantErr bool
}{
{"smaller_offer_wins", "1024", 8192, 512, 16777215, 1024, false},
{"smaller_ours_wins", "65536", 8192, 512, 16777215, 8192, false},
{"clamp_below_min", "100", 8192, 512, 16777215, 512, false},
{"clamp_above_max", "99999999", 8192, 512, 1024, 1024, false},
{"reject_non_numeric", "abc", 8192, 512, 16777215, 0, true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got, err := iscsi.NegotiateNumber(tc.offered, tc.ours, tc.min, tc.max)
if (err != nil) != tc.wantErr {
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
}
if !tc.wantErr && got != tc.want {
t.Fatalf("got %d want %d", got, tc.want)
}
})
}
}
// Boolean negotiation: AND semantics. (InitialR2T's OR semantics
// is enforced in negotiateOperational, not in NegotiateBool.)
func TestNegotiateBool_AndSemantics(t *testing.T) {
cases := []struct {
offered string
ours bool
want bool
wantErr bool
}{
{"Yes", true, true, false},
{"Yes", false, false, false},
{"No", true, false, false},
{"No", false, false, false},
{"yes", false, false, true}, // case-sensitive per RFC
{"", false, false, true},
}
for _, tc := range cases {
t.Run(tc.offered+"|"+iscsi.BoolStr(tc.ours), func(t *testing.T) {
got, err := iscsi.NegotiateBool(tc.offered, tc.ours)
if (err != nil) != tc.wantErr {
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
}
if !tc.wantErr && got != tc.want {
t.Fatalf("got %v want %v", got, tc.want)
}
})
}
}
func TestBoolStr_YesNo(t *testing.T) {
if iscsi.BoolStr(true) != "Yes" || iscsi.BoolStr(false) != "No" {
t.Fatal("BoolStr mismatch")
}
}
+64 -10
View File
@@ -45,6 +45,16 @@ type Session struct {
// StatSN advances per SCSI Response the target sends.
statSN uint32
// Negotiator drives multi-round login parameter exchange.
// negCfg + resolver + lister are injected by Target at
// construction so this layer stays unaware of the target's
// catalog. Discovery sessions don't reach the SCSI handler;
// they exit after the SendTargets exchange + Logout.
negCfg NegotiableConfig
resolver TargetResolver
lister TargetLister
negResult LoginResult
// Session lifetime.
closed atomic.Bool
}
@@ -57,12 +67,18 @@ type Logger interface {
}
// newSession builds a fresh session for the accepted conn.
func newSession(conn net.Conn, handler *SCSIHandler, logger Logger) *Session {
// negCfg/resolver/lister come from the Target. handler may be
// nil for Discovery-only sessions; the negotiator decides which
// path applies after login.
func newSession(conn net.Conn, handler *SCSIHandler, negCfg NegotiableConfig, resolver TargetResolver, lister TargetLister, logger Logger) *Session {
return &Session{
conn: conn,
handler: handler,
logger: logger,
state: SessionLogin,
conn: conn,
handler: handler,
logger: logger,
state: SessionLogin,
negCfg: negCfg,
resolver: resolver,
lister: lister,
}
}
@@ -78,6 +94,7 @@ func (s *Session) serve(ctx context.Context) error {
}
func (s *Session) loginPhase() error {
neg := NewLoginNegotiator(s.negCfg)
for s.state == SessionLogin {
pdu, err := ReadPDU(s.conn)
if err != nil {
@@ -87,14 +104,22 @@ func (s *Session) loginPhase() error {
return fmt.Errorf("%w: expected Login-Request, got %s",
ErrLoginInvalidRequest, OpcodeName(pdu.Opcode()))
}
resp := buildLoginResponse(pdu, s.tsih)
resp := neg.HandleLoginPDU(pdu, s.resolver)
if err := WritePDU(s.conn, resp); err != nil {
return err
}
if loginGrantsFullFeature(pdu) {
// If negotiator emitted a reject, the response status is
// non-Success; close the session after the reply.
if resp.LoginStatusClass() != LoginStatusSuccess {
return fmt.Errorf("login rejected: class=0x%02x detail=0x%02x",
resp.LoginStatusClass(), resp.LoginStatusDetail())
}
if neg.Done() {
s.state = SessionFullFeature
s.negResult = neg.Result()
if s.logger != nil {
s.logger.Printf("session: transit to FullFeature (ISID=%x)", pdu.ISID())
s.logger.Printf("session: FullFeature initiator=%q target=%q type=%q",
s.negResult.InitiatorName, s.negResult.TargetName, s.negResult.SessionType)
}
return nil
}
@@ -121,13 +146,23 @@ func (s *Session) fullFeatureLoop(ctx context.Context) error {
func (s *Session) dispatch(ctx context.Context, pdu *PDU) error {
switch pdu.Opcode() {
case OpSCSICmd:
// Discovery sessions reject SCSI commands per RFC 7143
// §6.2 — discovery is a control plane only. Reply with
// Reject so iscsiadm doesn't hang.
if s.negResult.SessionType == SessionTypeDiscovery {
return fmt.Errorf("SCSI command in Discovery session")
}
if s.handler == nil {
return fmt.Errorf("SCSI handler not configured for this session")
}
return s.handleSCSICmd(ctx, pdu)
case OpSCSIDataOut:
// In the minimal session, SCSI-Cmd carries immediate data
// for all writes (see handleSCSICmd). A stray Data-Out
// without a preceding R2T is a protocol error; reject
// rather than silently discard.
// without a preceding R2T is a protocol error.
return fmt.Errorf("unexpected Data-Out without R2T")
case OpTextReq:
return s.handleTextReq(pdu)
case OpLogoutReq:
return s.handleLogout(pdu)
case OpNOPOut:
@@ -137,6 +172,25 @@ func (s *Session) dispatch(ctx context.Context, pdu *PDU) error {
}
}
// handleTextReq services SendTargets discovery (RFC 7143 §12.3).
// Other text keys produce an empty Text-Response. Discovery
// sessions are the typical caller; Normal sessions are also
// allowed to issue Text Requests but T2's response set is the
// same.
func (s *Session) handleTextReq(req *PDU) error {
var targets []DiscoveryTarget
if s.lister != nil {
targets = s.lister.ListTargets()
}
resp := HandleTextRequest(req, targets)
// Text-Response advances StatSN like a SCSI-Response would.
s.statSN++
resp.SetStatSN(s.statSN)
resp.SetExpCmdSN(req.CmdSN() + 1)
resp.SetMaxCmdSN(req.CmdSN() + 32)
return WritePDU(s.conn, resp)
}
// handleSCSICmd processes a SCSI-Cmd PDU. For T2 scope:
// - WRITE(10): dataOut MUST be carried in the SCSI-Cmd's
// data segment (ImmediateData=true in the minimal negotiator).
+45 -5
View File
@@ -26,11 +26,16 @@ type TargetConfig struct {
Listen string
// IQN is the iSCSI Qualified Name advertised to initiators.
// Currently informational — T2 minimal login does not parse
// TargetName from login params. Will be used when login
// negotiation expands.
// Used as the SendTargets discovery list entry AND as the
// expected TargetName during Normal-session login.
IQN string
// PortalAddr is what we advertise in SendTargets responses
// (defaults to the actual bound listen address). Operators
// override when listen is 0.0.0.0/[::] but clients need a
// routable IP. Format: "host:port,portal-group-tag".
PortalAddr string
// VolumeID is handed to Provider.Open.
VolumeID string
@@ -42,6 +47,10 @@ type TargetConfig struct {
// T2 defaults from HandlerConfig.
Handler HandlerConfig
// Negotiation profile for login parameter exchange. Zero
// value = DefaultNegotiableConfig().
Negotiation NegotiableConfig
// Logger. Nil → log.Default wrapped for the session layer.
Logger *log.Logger
}
@@ -66,6 +75,9 @@ func NewTarget(cfg TargetConfig) *Target {
if lg == nil {
lg = log.Default()
}
if cfg.Negotiation == (NegotiableConfig{}) {
cfg.Negotiation = DefaultNegotiableConfig()
}
return &Target{
cfg: cfg,
logger: stdlogAdapter{l: lg},
@@ -73,6 +85,32 @@ func NewTarget(cfg TargetConfig) *Target {
}
}
// HasTarget satisfies TargetResolver: accepts the configured
// IQN. Future multi-target support extends this to a registry.
func (t *Target) HasTarget(name string) bool {
return t.cfg.IQN != "" && name == t.cfg.IQN
}
// ListTargets satisfies TargetLister for SendTargets discovery.
// Single-target host: emit our one IQN with the bound listen
// addr (or operator-supplied PortalAddr).
func (t *Target) ListTargets() []DiscoveryTarget {
if t.cfg.IQN == "" {
return nil
}
addr := t.cfg.PortalAddr
if addr == "" {
t.mu.Lock()
if t.ln != nil {
// Default portal group tag = 1 (matches Negotiation
// default) so iscsiadm recognizes the entry.
addr = t.ln.Addr().String() + ",1"
}
t.mu.Unlock()
}
return []DiscoveryTarget{{Name: t.cfg.IQN, Address: addr}}
}
// Start binds and spawns the accept loop in a goroutine.
// Returns the bound addr (useful when Listen is ":0").
func (t *Target) Start() (string, error) {
@@ -146,7 +184,9 @@ func (t *Target) handleConn(conn net.Conn) {
// Open a backend via the frontend.Provider. The Provider
// blocks until the projection is healthy or returns
// ErrNotReady. We pass our own ctx so target-shutdown
// cancels the wait.
// cancels the wait. Discovery sessions also call this so
// the frontend backend is ready by the time SCSI traffic
// could land — keeps the lifecycle uniform.
backend, err := t.cfg.Provider.Open(ctx, t.cfg.VolumeID)
if err != nil {
t.logger.Printf("iscsi: Provider.Open(%s): %v", t.cfg.VolumeID, err)
@@ -158,7 +198,7 @@ func (t *Target) handleConn(conn net.Conn) {
cfg.Backend = backend
handler := NewSCSIHandler(cfg)
sess := newSession(conn, handler, t.logger)
sess := newSession(conn, handler, t.cfg.Negotiation, t, t, t.logger)
if err := sess.serve(ctx); err != nil && !errors.Is(err, net.ErrClosed) {
t.logger.Printf("iscsi: session error (%s): %v", conn.RemoteAddr(), err)
}