Files
seaweedfs/seaweed-block/core/frontend/iscsi/params.go
T
wzcheng99 0d81c9bafc 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.
2026-04-21 21:50:22 -07:00

161 lines
3.8 KiB
Go

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"
}