Home | History | Annotate | Line # | Download | only in iscsi
iscsi_text.c revision 1.6.2.1
      1 /*	$NetBSD: iscsi_text.c,v 1.6.2.1 2014/08/20 00:03:39 tls Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2005,2006,2011 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Wasabi Systems, Inc.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include "iscsi_globals.h"
     33 #include "base64.h"
     34 #include <sys/md5.h>
     35 #include <sys/cprng.h>
     36 
     37 /* define to send T_BIGNUM in hex format instead of base64 */
     38 /* #define ISCSI_HEXBIGNUMS */
     39 
     40 #define isdigit(x) ((x) >= '0' && (x) <= '9')
     41 #define toupper(x) ((x) & ~0x20)
     42 
     43 /*****************************************************************************/
     44 
     45 #define MAX_STRING   255	/* Maximum length of parameter value */
     46 #define MAX_LIST     4		/* Maximum number of list elements we'll ever send */
     47 
     48 /* Maximum number of negotiation parameters in the operational negotiation phase */
     49 /* 48 should be more than enough even with the target defining its own keys */
     50 #define MAX_NEG      48
     51 
     52 #define CHAP_CHALLENGE_LEN    32	/* Number of bytes to send in challenge */
     53 #define CHAP_MD5_SIZE         16	/* Number of bytes in MD5 hash */
     54 
     55 /*****************************************************************************/
     56 
     57 /* authentication states */
     58 
     59 typedef enum
     60 {
     61 	AUTH_INITIAL,				/* sending choice of algorithms */
     62 	AUTH_METHOD_SELECTED,		/* received choice, sending first parameter */
     63 	/* from here it's alg dependent */
     64 	AUTH_CHAP_ALG_SENT,			/* CHAP: Algorithm selected */
     65 	AUTH_CHAP_RSP_SENT,			/* CHAP: Response sent */
     66 	/* for all algorithms */
     67 	AUTH_DONE					/* in parameter negotiation stage */
     68 } auth_state_t;
     69 
     70 
     71 /* enumeration of all the keys we know, and a place for the ones we don't */
     72 
     73 typedef enum
     74 {
     75 	K_AuthMethod,
     76 	K_Auth_CHAP_Algorithm,
     77 	K_Auth_CHAP_Challenge,
     78 	K_Auth_CHAP_Identifier,
     79 	K_Auth_CHAP_Name,
     80 	K_Auth_CHAP_Response,
     81 	K_DataDigest,
     82 	K_DataPDUInOrder,
     83 	K_DataSequenceInOrder,
     84 	K_DefaultTime2Retain,
     85 	K_DefaultTime2Wait,
     86 	K_ErrorRecoveryLevel,
     87 	K_FirstBurstLength,
     88 	K_HeaderDigest,
     89 	K_IFMarker,
     90 	K_IFMarkInt,
     91 	K_ImmediateData,
     92 	K_InitialR2T,
     93 	K_InitiatorAlias,
     94 	K_InitiatorName,
     95 	K_MaxBurstLength,
     96 	K_MaxConnections,
     97 	K_MaxOutstandingR2T,
     98 	K_MaxRecvDataSegmentLength,
     99 	K_OFMarker,
    100 	K_OFMarkInt,
    101 	K_SendTargets,
    102 	K_SessionType,
    103 	K_TargetAddress,
    104 	K_TargetAlias,
    105 	K_TargetName,
    106 	K_TargetPortalGroupTag,
    107 	K_NotUnderstood
    108 } text_key_t;
    109 
    110 /* maximum known key */
    111 #define MAX_KEY   K_TargetPortalGroupTag
    112 
    113 
    114 #undef DEBOUT
    115 #define DEBOUT(x)	printf x
    116 
    117 
    118 
    119 /* value types */
    120 typedef enum
    121 {						/* Value is... */
    122 	T_NUM,					/* numeric */
    123 	T_BIGNUM,				/* large numeric */
    124 	T_STRING,				/* string */
    125 	T_YESNO,				/* boolean (Yes or No) */
    126 	T_AUTH,					/* authentication type (CHAP or None for now) */
    127 	T_DIGEST,				/* digest (None or CRC32C) */
    128 	T_RANGE,				/* numeric range */
    129 	T_SENDT,				/* send target options (ALL, target-name, empty) */
    130 	T_SESS					/* session type (Discovery or Normal) */
    131 } val_kind_t;
    132 
    133 
    134 /* table of negotiation key strings with value type and default */
    135 
    136 typedef struct
    137 {
    138 	const uint8_t *name;				/* the key name */
    139 	val_kind_t val;				/* the value type */
    140 	uint32_t defval;			/* default value */
    141 } key_entry_t;
    142 
    143 STATIC key_entry_t entries[] = {
    144 	{"AuthMethod", T_AUTH, 0},
    145 	{"CHAP_A", T_NUM, 5},
    146 	{"CHAP_C", T_BIGNUM, 0},
    147 	{"CHAP_I", T_NUM, 0},
    148 	{"CHAP_N", T_STRING, 0},
    149 	{"CHAP_R", T_BIGNUM, 0},
    150 	{"DataDigest", T_DIGEST, 0},
    151 	{"DataPDUInOrder", T_YESNO, 1},
    152 	{"DataSequenceInOrder", T_YESNO, 1},
    153 	{"DefaultTime2Retain", T_NUM, 20},
    154 	{"DefaultTime2Wait", T_NUM, 2},
    155 	{"ErrorRecoveryLevel", T_NUM, 0},
    156 	{"FirstBurstLength", T_NUM, 64 * 1024},
    157 	{"HeaderDigest", T_DIGEST, 0},
    158 	{"IFMarker", T_YESNO, 0},
    159 	{"IFMarkInt", T_RANGE, 2048},
    160 	{"ImmediateData", T_YESNO, 1},
    161 	{"InitialR2T", T_YESNO, 1},
    162 	{"InitiatorAlias", T_STRING, 0},
    163 	{"InitiatorName", T_STRING, 0},
    164 	{"MaxBurstLength", T_NUM, 256 * 1024},
    165 	{"MaxConnections", T_NUM, 1},
    166 	{"MaxOutstandingR2T", T_NUM, 1},
    167 	{"MaxRecvDataSegmentLength", T_NUM, 8192},
    168 	{"OFMarker", T_YESNO, 0},
    169 	{"OFMarkInt", T_RANGE, 2048},
    170 	{"SendTargets", T_SENDT, 0},
    171 	{"SessionType", T_SESS, 0},
    172 	{"TargetAddress", T_STRING, 0},
    173 	{"TargetAlias", T_STRING, 0},
    174 	{"TargetName", T_STRING, 0},
    175 	{"TargetPortalGroupTag", T_NUM, 0},
    176 	{NULL, T_STRING, 0}
    177 };
    178 
    179 /* a negotiation parameter: key and values (there may be more than 1 for lists) */
    180 typedef struct
    181 {
    182 	text_key_t key;				/* the key */
    183 	int list_num;				/* number of elements in list, doubles as */
    184 	/* data size for large numeric values */
    185 	union
    186 	{
    187 		uint32_t nval[MAX_LIST];	/* numeric or enumeration values */
    188 		uint8_t *sval;				/* string or data pointer */
    189 	} val;
    190 } negotiation_parameter_t;
    191 
    192 
    193 /* Negotiation state flags */
    194 #define NS_SENT      0x01		/* key was sent to target */
    195 #define NS_RECEIVED  0x02		/* key was received from target */
    196 
    197 typedef struct
    198 {
    199 	negotiation_parameter_t pars[MAX_NEG];	/* the parameters to send */
    200 	negotiation_parameter_t *cpar;			/* the last parameter set */
    201 	uint16_t num_pars;						/* number of parameters to send */
    202 	auth_state_t auth_state;				/* authentication state */
    203 	iscsi_auth_types_t auth_alg;			/* authentication algorithm */
    204 	uint8_t kflags[MAX_KEY + 2];			/* negotiation flags for each key */
    205 	uint8_t password[MAX_STRING + 1];		/* authentication secret */
    206 	uint8_t target_password[MAX_STRING + 1];	/* target authentication secret */
    207 	uint8_t user_name[MAX_STRING + 1];		/* authentication user ID */
    208 	uint8_t temp_buf[MAX_STRING + 1];		/* scratch buffer */
    209 
    210 	bool HeaderDigest;
    211 	bool DataDigest;
    212 	bool InitialR2T;
    213 	bool ImmediateData;
    214 	uint32_t ErrorRecoveryLevel;
    215 	uint32_t MaxRecvDataSegmentLength;
    216 	uint32_t MaxConnections;
    217 	uint32_t DefaultTime2Wait;
    218 	uint32_t DefaultTime2Retain;
    219 	uint32_t MaxBurstLength;
    220 	uint32_t FirstBurstLength;
    221 	uint32_t MaxOutstandingR2T;
    222 
    223 } negotiation_state_t;
    224 
    225 
    226 #define TX(state, key) (state->kflags [key] & NS_SENT)
    227 #define RX(state, key) (state->kflags [key] & NS_RECEIVED)
    228 
    229 /*****************************************************************************/
    230 
    231 
    232 STATIC void
    233 chap_md5_response(uint8_t *buffer, uint8_t identifier, uint8_t *secret,
    234 				  uint8_t *challenge, int challenge_size)
    235 {
    236 	MD5_CTX md5;
    237 
    238 	MD5Init(&md5);
    239 	MD5Update(&md5, &identifier, 1);
    240 	MD5Update(&md5, secret, strlen(secret));
    241 	MD5Update(&md5, challenge, challenge_size);
    242 	MD5Final(buffer, &md5);
    243 }
    244 
    245 
    246 /*****************************************************************************/
    247 
    248 /*
    249  * hexdig:
    250  *    Return value of hex digit.
    251  *    Note: a null character is acceptable, and returns 0.
    252  *
    253  *    Parameter:
    254  *          c     The character
    255  *
    256  *    Returns:    The value, -1 on error.
    257  */
    258 
    259 static __inline int
    260 hexdig(uint8_t c)
    261 {
    262 
    263 	if (!c) {
    264 		return 0;
    265 	}
    266 	if (isdigit(c)) {
    267 		return c - '0';
    268 	}
    269 	c = toupper(c);
    270 	if (c >= 'A' && c <= 'F') {
    271 		return c - 'A' + 10;
    272 	}
    273 	return -1;
    274 }
    275 
    276 /*
    277  * skiptozero:
    278  *    Skip to next zero character in buffer.
    279  *
    280  *    Parameter:
    281  *          buf      The buffer pointer
    282  *
    283  *    Returns:    The pointer to the character after the zero character.
    284  */
    285 
    286 static __inline uint8_t *
    287 skiptozero(uint8_t *buf)
    288 {
    289 
    290 	while (*buf) {
    291 		buf++;
    292 	}
    293 	return buf + 1;
    294 }
    295 
    296 
    297 /*
    298  * get_bignumval:
    299  *    Get a large numeric value.
    300  *    NOTE: Overwrites source string.
    301  *
    302  *    Parameter:
    303  *          buf      The buffer pointer
    304  *          par      The parameter
    305  *
    306  *    Returns:    The pointer to the next parameter, NULL on error.
    307  */
    308 
    309 STATIC uint8_t *
    310 get_bignumval(uint8_t *buf, negotiation_parameter_t *par)
    311 {
    312 	int val;
    313 	char c;
    314 	uint8_t *dp = buf;
    315 
    316 	par->val.sval = buf;
    317 
    318 	if (buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X')) {
    319 		buf += 2;
    320 		while ((c = *buf) != 0x0) {
    321 			buf++;
    322 			val = (hexdig(c) << 4) | hexdig(*buf);
    323 			if (val < 0) {
    324 				return NULL;
    325 			}
    326 			*dp++ = (uint8_t) val;
    327 			if (*buf) {
    328 				buf++;
    329 			}
    330 		}
    331 		buf++;
    332 		par->list_num = dp - par->val.sval;
    333 	} else if (buf[0] == '0' && (buf[1] == 'b' || buf[1] == 'B')) {
    334 		buf = base64_decode(&buf[2], par->val.sval, &par->list_num);
    335 	} else {
    336 		DEBOUT(("Ill-formatted large number <%s>\n", buf));
    337 		return NULL;
    338 	}
    339 
    340 	return buf;
    341 }
    342 
    343 
    344 /*
    345  * get_numval:
    346  *    Get a numeric value.
    347  *
    348  *    Parameter:
    349  *          buf      The buffer pointer
    350  *          pval     The pointer to the result.
    351  *
    352  *    Returns:    The pointer to the next parameter, NULL on error.
    353  */
    354 
    355 STATIC uint8_t *
    356 get_numval(uint8_t *buf, uint32_t *pval)
    357 {
    358 	uint32_t val = 0;
    359 	char c;
    360 
    361 	if (buf[0] == '0' && (buf[1] == 'x' || buf[1] == 'X')) {
    362 		buf += 2;
    363 		while (*buf && *buf != '~') {
    364 			int n;
    365 
    366 			if ((n = hexdig(*buf++)) < 0)
    367 				return NULL;
    368 			val = (val << 4) | n;
    369 		}
    370 	} else
    371 		while (*buf && *buf != '~') {
    372 			c = *buf++;
    373 			if (!isdigit(c))
    374 				return NULL;
    375 			val = val * 10 + (c - '0');
    376 		}
    377 
    378 	*pval = val;
    379 
    380 	return buf + 1;
    381 }
    382 
    383 
    384 /*
    385  * get_range:
    386  *    Get a numeric range.
    387  *
    388  *    Parameter:
    389  *          buf      The buffer pointer
    390  *          pval1    The pointer to the first result.
    391  *          pval2    The pointer to the second result.
    392  *
    393  *    Returns:    The pointer to the next parameter, NULL on error.
    394  */
    395 
    396 STATIC uint8_t *
    397 get_range(uint8_t *buf, uint32_t *pval1, uint32_t *pval2)
    398 {
    399 
    400 	if ((buf = get_numval(buf, pval1)) == NULL)
    401 		return NULL;
    402 	if (!*buf)
    403 		return NULL;
    404 	if ((buf = get_numval(buf, pval2)) == NULL)
    405 		return NULL;
    406 	return buf;
    407 }
    408 
    409 
    410 /*
    411  * get_ynval:
    412  *    Get a yes/no selection.
    413  *
    414  *    Parameter:
    415  *          buf      The buffer pointer
    416  *          pval     The pointer to the result.
    417  *
    418  *    Returns:    The pointer to the next parameter, NULL on error.
    419  */
    420 
    421 STATIC uint8_t *
    422 get_ynval(uint8_t *buf, uint32_t *pval)
    423 {
    424 
    425 	if (strcmp(buf, "Yes") == 0)
    426 		*pval = 1;
    427 	else if (strcmp(buf, "No") == 0)
    428 		*pval = 0;
    429 	else
    430 		return NULL;
    431 
    432 	return skiptozero(buf);
    433 }
    434 
    435 
    436 /*
    437  * get_digestval:
    438  *    Get a digest selection.
    439  *
    440  *    Parameter:
    441  *          buf      The buffer pointer
    442  *          pval     The pointer to the result.
    443  *
    444  *    Returns:    The pointer to the next parameter, NULL on error.
    445  */
    446 
    447 STATIC uint8_t *
    448 get_digestval(uint8_t *buf, uint32_t *pval)
    449 {
    450 
    451 	if (strcmp(buf, "CRC32C") == 0)
    452 		*pval = 1;
    453 	else if (strcmp(buf, "None") == 0)
    454 		*pval = 0;
    455 	else
    456 		return NULL;
    457 
    458 	return skiptozero(buf);
    459 }
    460 
    461 
    462 /*
    463  * get_authval:
    464  *    Get an authentication method.
    465  *
    466  *    Parameter:
    467  *          buf      The buffer pointer
    468  *          pval     The pointer to the result.
    469  *
    470  *    Returns:    The pointer to the next parameter, NULL on error.
    471  */
    472 
    473 STATIC uint8_t *
    474 get_authval(uint8_t *buf, uint32_t *pval)
    475 {
    476 
    477 	if (strcmp(buf, "None") == 0)
    478 		*pval = ISCSI_AUTH_None;
    479 	else if (strcmp(buf, "CHAP") == 0)
    480 		*pval = ISCSI_AUTH_CHAP;
    481 	else if (strcmp(buf, "KRB5") == 0)
    482 		*pval = ISCSI_AUTH_KRB5;
    483 	else if (strcmp(buf, "SRP") == 0)
    484 		*pval = ISCSI_AUTH_SRP;
    485 	else
    486 		return NULL;
    487 
    488 	return skiptozero(buf);
    489 }
    490 
    491 
    492 /*
    493  * get_strval:
    494  *    Get a string value (returns pointer to original buffer, not a copy).
    495  *
    496  *    Parameter:
    497  *          buf      The buffer pointer
    498  *          pval     The pointer to the result pointer.
    499  *
    500  *    Returns:    The pointer to the next parameter, NULL on error.
    501  */
    502 
    503 STATIC uint8_t *
    504 get_strval(uint8_t *buf, uint8_t **pval)
    505 {
    506 
    507 	if (strlen(buf) > MAX_STRING)
    508 		return NULL;
    509 
    510 	*pval = buf;
    511 
    512 	return skiptozero(buf);
    513 }
    514 
    515 
    516 /*
    517  * get_parameter:
    518  *    Analyze a key=value string.
    519  *    NOTE: The string is modified in the process.
    520  *
    521  *    Parameter:
    522  *          buf      The buffer pointer
    523  *          par      The parameter descriptor to be filled in
    524  *
    525  *    Returns:    The pointer to the next parameter, NULL on error.
    526  */
    527 
    528 STATIC uint8_t *
    529 get_parameter(uint8_t *buf, negotiation_parameter_t *par)
    530 {
    531 	uint8_t *bp = buf;
    532 	int i;
    533 
    534 	while (*bp && *bp != '=') {
    535 		bp++;
    536 	}
    537 	if (!*bp) {
    538 		DEBOUT(("get_parameter: Premature end of parameter\n"));
    539 		return NULL;
    540 	}
    541 
    542 	*bp++ = 0;
    543 
    544 	for (i = 0; i <= MAX_KEY; i++)
    545 		if (!strcmp(buf, entries[i].name))
    546 			break;
    547 
    548 	par->key = i;
    549 	par->list_num = 1;
    550 
    551 	if (i > MAX_KEY) {
    552 		DEBOUT(("get_parameter: unrecognized key <%s>\n", buf));
    553 		if (strlen(buf) > MAX_STRING) {
    554 			DEBOUT(("get_parameter: key name > MAX_STRING\n"));
    555 			return NULL;
    556 		}
    557 		par->val.sval = buf;
    558 		return skiptozero(bp);
    559 	}
    560 
    561 	DEB(10, ("get_par: key <%s>=%d, val=%d, ret %p\n",
    562 			buf, i, entries[i].val, bp));
    563 	DEB(10, ("get_par: value '%s'\n",bp));
    564 
    565 	switch (entries[i].val) {
    566 	case T_NUM:
    567 		bp = get_numval(bp, &par->val.nval[0]);
    568 		break;
    569 
    570 	case T_BIGNUM:
    571 		bp = get_bignumval(bp, par);
    572 		break;
    573 
    574 	case T_STRING:
    575 		bp = get_strval(bp, &par->val.sval);
    576 		break;
    577 
    578 	case T_YESNO:
    579 		bp = get_ynval(bp, &par->val.nval[0]);
    580 		break;
    581 
    582 	case T_AUTH:
    583 		bp = get_authval(bp, &par->val.nval[0]);
    584 		break;
    585 
    586 	case T_DIGEST:
    587 		bp = get_digestval(bp, &par->val.nval[0]);
    588 		break;
    589 
    590 	case T_RANGE:
    591 		bp = get_range(bp, &par->val.nval[0], &par->val.nval[1]);
    592 		break;
    593 
    594 	default:
    595 		/* Target sending any other types is wrong */
    596 		bp = NULL;
    597 		break;
    598 	}
    599 	return bp;
    600 }
    601 
    602 /*****************************************************************************/
    603 
    604 /*
    605  * my_strcpy:
    606  *    Replacement for strcpy that returns the end of the result string
    607  *
    608  *    Parameter:
    609  *          dest     The destination buffer pointer
    610  *          src      The source string
    611  *
    612  *    Returns:    A pointer to the terminating zero of the result.
    613  */
    614 
    615 static __inline unsigned
    616 my_strcpy(uint8_t *dest, const uint8_t *src)
    617 {
    618 	unsigned	cc;
    619 
    620 	for (cc = 0 ; (*dest = *src) != 0x0 ; cc++) {
    621 		dest++;
    622 		src++;
    623 	}
    624 	return cc;
    625 }
    626 
    627 /*
    628  * put_bignumval:
    629  *    Write a large numeric value.
    630  *    NOTE: Overwrites source string.
    631  *
    632  *    Parameter:
    633  *          buf      The buffer pointer
    634  *          par      The parameter
    635  *
    636  *    Returns:    The pointer to the next parameter, NULL on error.
    637  */
    638 
    639 STATIC unsigned
    640 put_bignumval(negotiation_parameter_t *par, uint8_t *buf)
    641 {
    642 #ifdef ISCSI_HEXBIGNUMS
    643 	int k, c;
    644 
    645 	my_strcpy(buf, "0x");
    646 	for (k=0; k<par->list_num; ++k) {
    647 		c = par->val.sval[k] >> 4;
    648 		buf[2+2*k] = c < 10 ? '0' + c : 'a' + (c-10);
    649 		c = par->val.sval[k] & 0xf;
    650 		buf[2+2*k+1] = c < 10 ? '0' + c : 'a' + (c-10);
    651 	}
    652 	buf[2+2*k] = '\0';
    653 
    654 	return 2+2*par->list_num;
    655 #else
    656 	return base64_encode(par->val.sval, par->list_num, buf);
    657 #endif
    658 }
    659 
    660 /*
    661  * put_parameter:
    662  *    Create a key=value string.
    663  *
    664  *    Parameter:
    665  *          buf      The buffer pointer
    666  *          par      The parameter descriptor
    667  *
    668  *    Returns:    The pointer to the next free buffer space, NULL on error.
    669  */
    670 
    671 STATIC unsigned
    672 put_parameter(uint8_t *buf, unsigned len, negotiation_parameter_t *par)
    673 {
    674 	int i;
    675 	unsigned	cc, cl;
    676 	const uint8_t *sp;
    677 
    678 	DEB(10, ("put_par: key <%s>=%d, val=%d\n",
    679 		entries[par->key].name, par->key, entries[par->key].val));
    680 
    681 	if (par->key > MAX_KEY) {
    682 		return snprintf(buf, len, "%s=NotUnderstood", par->val.sval);
    683 	}
    684 
    685 	cc = snprintf(buf, len, "%s=", entries[par->key].name);
    686 	if (cc >= len)
    687 		return len;
    688 
    689 	for (i = 0; i < par->list_num; i++) {
    690 		switch (entries[par->key].val) {
    691 		case T_NUM:
    692 			cl = snprintf(&buf[cc], len - cc, "%d",
    693 			               par->val.nval[i]);
    694 			break;
    695 
    696 		case T_BIGNUM:
    697 			cl = put_bignumval(par, &buf[cc]);
    698 			i = par->list_num;
    699 			break;
    700 
    701 		case T_STRING:
    702 			cl =  my_strcpy(&buf[cc], par->val.sval);
    703 			break;
    704 
    705 		case T_YESNO:
    706 			cl = my_strcpy(&buf[cc],
    707 				(par->val.nval[i]) ? "Yes" : "No");
    708 			break;
    709 
    710 		case T_AUTH:
    711 			switch (par->val.nval[i]) {
    712 			case ISCSI_AUTH_CHAP:
    713 				sp = "CHAP";
    714 				break;
    715 			case ISCSI_AUTH_KRB5:
    716 				sp = "KRB5";
    717 				break;
    718 			case ISCSI_AUTH_SRP:
    719 				sp = "SRP";
    720 				break;
    721 			default:
    722 				sp = "None";
    723 				break;
    724 			}
    725 			cl = my_strcpy(&buf[cc], sp);
    726 			break;
    727 
    728 		case T_DIGEST:
    729 			cl = my_strcpy(&buf[cc],
    730 				(par->val.nval[i]) ? "CRC32C" : "None");
    731 			break;
    732 
    733 		case T_RANGE:
    734 			if ((i + 1) >= par->list_num) {
    735 				cl = my_strcpy(&buf[cc], "Reject");
    736 			} else {
    737 				cl = snprintf(&buf[cc], len - cc,
    738 						"%d~%d", par->val.nval[i],
    739 						par->val.nval[i + 1]);
    740 				i++;
    741 			}
    742 			break;
    743 
    744 		case T_SENDT:
    745 			cl = my_strcpy(&buf[cc], par->val.sval);
    746 			break;
    747 
    748 		case T_SESS:
    749 			cl = my_strcpy(&buf[cc],
    750 				(par->val.nval[i]) ? "Normal" : "Discovery");
    751 			break;
    752 
    753 		default:
    754 			cl = 0;
    755 			/* We should't be here... */
    756 			DEBOUT(("Invalid type %d in put_parameter!\n",
    757 					entries[par->key].val));
    758 			break;
    759 		}
    760 
    761 		DEB(10, ("put_par: value '%s'\n",&buf[cc]));
    762 
    763 		cc += cl;
    764 		if (cc >= len)
    765 			return len;
    766 		if ((i + 1) < par->list_num) {
    767 			if (cc >= len)
    768 				return len;
    769 			buf[cc++] = ',';
    770 		}
    771 	}
    772 
    773 	if (cc >= len)
    774 		return len;
    775 	buf[cc] = 0x0;				/* make sure it's terminated */
    776 	return cc + 1;				/* return next place in list */
    777 }
    778 
    779 
    780 /*
    781  * put_par_block:
    782  *    Fill a parameter block
    783  *
    784  *    Parameter:
    785  *          buf      The buffer pointer
    786  *          pars     The parameter descriptor array
    787  *          n        The number of elements
    788  *
    789  *    Returns:    result from put_parameter (ptr to buffer, NULL on error)
    790  */
    791 
    792 static __inline unsigned
    793 put_par_block(uint8_t *buf, unsigned len, negotiation_parameter_t *pars, int n)
    794 {
    795 	unsigned	cc;
    796 	int i;
    797 
    798 	for (cc = 0, i = 0; i < n; i++) {
    799 		cc += put_parameter(&buf[cc], len - cc, pars++);
    800 		if (cc >= len) {
    801 			break;
    802 		}
    803 	}
    804 	return cc;
    805 }
    806 
    807 /*
    808  * parameter_size:
    809  *    Determine the size of a key=value string.
    810  *
    811  *    Parameter:
    812  *          par      The parameter descriptor
    813  *
    814  *    Returns:    The size of the resulting string.
    815  */
    816 
    817 STATIC int
    818 parameter_size(negotiation_parameter_t *par)
    819 {
    820 	int i, size;
    821 	char buf[24];	/* max. 2 10-digit numbers + sep. */
    822 
    823 	if (par->key > MAX_KEY) {
    824 		return strlen(par->val.sval) + 15;
    825 	}
    826 	/* count '=' and terminal zero */
    827 	size = strlen(entries[par->key].name) + 2;
    828 
    829 	for (i = 0; i < par->list_num; i++) {
    830 		switch (entries[par->key].val) {
    831 		case T_NUM:
    832 			size += snprintf(buf, sizeof(buf), "%d",
    833 					par->val.nval[i]);
    834 			break;
    835 
    836 		case T_BIGNUM:
    837 			/* list_num holds value size */
    838 #ifdef ISCSI_HEXBIGNUMS
    839 			size += 2 + 2*par->list_num;
    840 #else
    841 			size += base64_enclen(par->list_num);
    842 #endif
    843 			i = par->list_num;
    844 			break;
    845 
    846 		case T_STRING:
    847 		case T_SENDT:
    848 			size += strlen(par->val.sval);
    849 			break;
    850 
    851 		case T_YESNO:
    852 			size += (par->val.nval[i]) ? 3 : 2;
    853 			break;
    854 
    855 		case T_AUTH:
    856 			size += (par->val.nval[i] == ISCSI_AUTH_SRP) ? 3 : 4;
    857 			break;
    858 
    859 		case T_DIGEST:
    860 			size += (par->val.nval[i]) ? 6 : 4;
    861 			break;
    862 
    863 		case T_RANGE:
    864 			assert((i + 1) < par->list_num);
    865 			size += snprintf(buf, sizeof(buf), "%d~%d",
    866 				par->val.nval[i],
    867 							par->val.nval[i + 1]);
    868 			i++;
    869 			break;
    870 
    871 		case T_SESS:
    872 			size += (par->val.nval[i]) ? 6 : 9;
    873 			break;
    874 
    875 		default:
    876 			/* We should't be here... */
    877 			DEBOUT(("Invalid type %d in parameter_size!\n",
    878 					entries[par->key].val));
    879 			break;
    880 		}
    881 		if ((i + 1) < par->list_num) {
    882 			size++;
    883 		}
    884 	}
    885 
    886 	return size;
    887 }
    888 
    889 
    890 /*
    891  * total_size:
    892  *    Determine the size of a negotiation data block
    893  *
    894  *    Parameter:
    895  *          pars     The parameter descriptor array
    896  *          n        The number of elements
    897  *
    898  *    Returns:    The size of the block
    899  */
    900 
    901 static __inline int
    902 total_size(negotiation_parameter_t *pars, int n)
    903 {
    904 	int i, size;
    905 
    906 	for (i = 0, size = 0; i < n; i++) {
    907 		size += parameter_size(pars++);
    908 	}
    909 	return size;
    910 }
    911 
    912 /*****************************************************************************/
    913 
    914 
    915 /*
    916  * complete_pars:
    917  *    Allocate space for text parameters, translate parameter values into
    918  *    text.
    919  *
    920  *    Parameter:
    921  *          state    Negotiation state
    922  *          pdu      The transmit PDU
    923  *
    924  *    Returns:    0     On success
    925  *                > 0   (an ISCSI error code) if an error occurred.
    926  */
    927 
    928 STATIC int
    929 complete_pars(negotiation_state_t *state, pdu_t *pdu)
    930 {
    931 	int len;
    932 	uint8_t *bp;
    933 #ifdef ISCSI_TEST_MODE
    934 	test_pars_t *tp = pdu->connection->test_pars;
    935 	neg_desc_t *nd = NULL;
    936 #endif
    937 
    938 	len = total_size(state->pars, state->num_pars);
    939 
    940 #ifdef ISCSI_TEST_MODE
    941 	if (tp != NULL) {
    942 		while ((nd = TAILQ_FIRST(&pdu->connection->test_pars->negs)) != NULL &&
    943 			   nd->entry.state < state->auth_state) {
    944 			TAILQ_REMOVE(&tp->negs, nd, link);
    945 			free(nd, M_TEMP);
    946 		}
    947 		if (nd != NULL && nd->entry.state == state->auth_state) {
    948 			if (nd->entry.flags & ISCSITEST_NEGOPT_REPLACE)
    949 				len = 0;
    950 			len += nd->entry.size;
    951 		} else
    952 			nd = NULL;
    953 	}
    954 #endif
    955 
    956 	DEB(10, ("complete_pars: n=%d, len=%d\n", state->num_pars, len));
    957 
    958 	if ((bp = malloc(len, M_TEMP, M_WAITOK)) == NULL) {
    959 		DEBOUT(("*** Out of memory in complete_pars\n"));
    960 		return ISCSI_STATUS_NO_RESOURCES;
    961 	}
    962 	pdu->temp_data = bp;
    963 
    964 #ifdef ISCSI_TEST_MODE
    965 	if (nd == NULL || !(nd->entry.flags & ISCSITEST_NEGOPT_REPLACE))
    966 		if ((bp = put_par_block(pdu->temp_data, len,
    967 				state->pars, state->num_pars)) == NULL) {
    968 			DEBOUT(("Bad parameter in complete_pars\n"));
    969 			return ISCSI_STATUS_PARAMETER_INVALID;
    970 		}
    971 	if (nd != NULL) {
    972 		memcpy(bp, nd->entry.value, nd->entry.size);
    973 		TAILQ_REMOVE(&tp->negs, nd, link);
    974 		free(nd, M_TEMP);
    975 	}
    976 #else
    977 	if (put_par_block(pdu->temp_data, len, state->pars,
    978 			state->num_pars) == 0) {
    979 		DEBOUT(("Bad parameter in complete_pars\n"));
    980 		return ISCSI_STATUS_PARAMETER_INVALID;
    981 	}
    982 #endif
    983 
    984 	pdu->temp_data_len = len;
    985 	return 0;
    986 }
    987 
    988 
    989 /*
    990  * set_key_n:
    991  *    Initialize a key and its numeric value.
    992  *
    993  *    Parameter:
    994  *          state    Negotiation state
    995  *          key      The key
    996  *          val      The value
    997  */
    998 
    999 STATIC negotiation_parameter_t *
   1000 set_key_n(negotiation_state_t *state, text_key_t key, uint32_t val)
   1001 {
   1002 	negotiation_parameter_t *par;
   1003 
   1004 	if (state->num_pars >= MAX_NEG) {
   1005 		DEBOUT(("set_key_n: num_pars (%d) >= MAX_NEG (%d)\n",
   1006 				state->num_pars, MAX_NEG));
   1007 		return NULL;
   1008 	}
   1009 	par = &state->pars[state->num_pars];
   1010 	par->key = key;
   1011 	par->list_num = 1;
   1012 	par->val.nval[0] = val;
   1013 	state->num_pars++;
   1014 	state->kflags[key] |= NS_SENT;
   1015 
   1016 	return par;
   1017 }
   1018 
   1019 /*
   1020  * set_key_s:
   1021  *    Initialize a key and its string value.
   1022  *
   1023  *    Parameter:
   1024  *          state    Negotiation state
   1025  *          key      The key
   1026  *          val      The value
   1027  */
   1028 
   1029 STATIC negotiation_parameter_t *
   1030 set_key_s(negotiation_state_t *state, text_key_t key, uint8_t *val)
   1031 {
   1032 	negotiation_parameter_t *par;
   1033 
   1034 	if (state->num_pars >= MAX_NEG) {
   1035 		DEBOUT(("set_key_s: num_pars (%d) >= MAX_NEG (%d)\n",
   1036 				state->num_pars, MAX_NEG));
   1037 		return NULL;
   1038 	}
   1039 	par = &state->pars[state->num_pars];
   1040 	par->key = key;
   1041 	par->list_num = 1;
   1042 	par->val.sval = val;
   1043 	state->num_pars++;
   1044 	state->kflags[key] |= NS_SENT;
   1045 
   1046 	return par;
   1047 }
   1048 
   1049 
   1050 /*****************************************************************************/
   1051 
   1052 /*
   1053  * eval_parameter:
   1054  *    Evaluate a received negotiation value.
   1055  *
   1056  *    Parameter:
   1057  *          conn     The connection
   1058  *          state    The negotiation state
   1059  *          par      The parameter
   1060  *
   1061  *    Returns:    0 on success, else an ISCSI status value.
   1062  */
   1063 
   1064 STATIC int
   1065 eval_parameter(connection_t *conn, negotiation_state_t *state,
   1066 			   negotiation_parameter_t *par)
   1067 {
   1068 	uint32_t n = par->val.nval[0];
   1069 	size_t sz;
   1070 	text_key_t key = par->key;
   1071 	bool sent = (state->kflags[key] & NS_SENT) != 0;
   1072 
   1073 	state->kflags[key] |= NS_RECEIVED;
   1074 
   1075 	switch (key) {
   1076 		/*
   1077 		 *  keys connected to security negotiation
   1078 		 */
   1079 	case K_AuthMethod:
   1080 		if (n) {
   1081 			DEBOUT(("eval_par: AuthMethod nonzero (%d)\n", n));
   1082 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1083 		}
   1084 		break;
   1085 
   1086 	case K_Auth_CHAP_Algorithm:
   1087 	case K_Auth_CHAP_Challenge:
   1088 	case K_Auth_CHAP_Identifier:
   1089 	case K_Auth_CHAP_Name:
   1090 	case K_Auth_CHAP_Response:
   1091 		DEBOUT(("eval_par: Authorization Key in Operational Phase\n"));
   1092 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1093 
   1094 		/*
   1095 		 * keys we always send
   1096 		 */
   1097 	case K_DataDigest:
   1098 		state->DataDigest = n;
   1099 		if (!sent)
   1100 			set_key_n(state, key, n);
   1101 		break;
   1102 
   1103 	case K_HeaderDigest:
   1104 		state->HeaderDigest = n;
   1105 		if (!sent)
   1106 			set_key_n(state, key, n);
   1107 		break;
   1108 
   1109 	case K_ErrorRecoveryLevel:
   1110 		state->ErrorRecoveryLevel = n;
   1111 		if (!sent)
   1112 			set_key_n(state, key, n);
   1113 		break;
   1114 
   1115 	case K_ImmediateData:
   1116 		state->ImmediateData = n;
   1117 		if (!sent)
   1118 			set_key_n(state, key, n);
   1119 		break;
   1120 
   1121 	case K_InitialR2T:
   1122 		state->InitialR2T = n;
   1123 		if (!sent)
   1124 			set_key_n(state, key, n);
   1125 		break;
   1126 
   1127 	case K_MaxRecvDataSegmentLength:
   1128 		state->MaxRecvDataSegmentLength = n;
   1129 		/* this is basically declarative, not negotiated */
   1130 		/* (each side has its own value) */
   1131 		break;
   1132 
   1133 		/*
   1134 		 * keys we don't always send, so we may have to reflect the value
   1135 		 */
   1136 	case K_DefaultTime2Retain:
   1137 		state->DefaultTime2Retain = n = min(state->DefaultTime2Retain, n);
   1138 		if (!sent)
   1139 			set_key_n(state, key, n);
   1140 		break;
   1141 
   1142 	case K_DefaultTime2Wait:
   1143 		state->DefaultTime2Wait = n = min(state->DefaultTime2Wait, n);
   1144 		if (!sent)
   1145 			set_key_n(state, key, n);
   1146 		break;
   1147 
   1148 	case K_MaxConnections:
   1149 		if (state->MaxConnections)
   1150 			state->MaxConnections = n = min(state->MaxConnections, n);
   1151 		else
   1152 			state->MaxConnections = n;
   1153 
   1154 		if (!sent)
   1155 			set_key_n(state, key, n);
   1156 		break;
   1157 
   1158 	case K_MaxOutstandingR2T:
   1159 		state->MaxOutstandingR2T = n;
   1160 		if (!sent)
   1161 			set_key_n(state, key, n);
   1162 		break;
   1163 
   1164 	case K_FirstBurstLength:
   1165 		state->FirstBurstLength = n;
   1166 		if (!sent)
   1167 			set_key_n(state, key, n);
   1168 		break;
   1169 
   1170 	case K_MaxBurstLength:
   1171 		state->MaxBurstLength = n;
   1172 		if (!sent)
   1173 			set_key_n(state, key, n);
   1174 		break;
   1175 
   1176 	case K_IFMarker:
   1177 	case K_OFMarker:
   1178 		/* not (yet) supported */
   1179 		if (!sent)
   1180 			set_key_n(state, key, 0);
   1181 		break;
   1182 
   1183 	case K_IFMarkInt:
   1184 	case K_OFMarkInt:
   1185 		/* it's a range, and list_num will be 1, so this will reply "Reject" */
   1186 		if (!sent)
   1187 			set_key_n(state, key, 0);
   1188 		break;
   1189 
   1190 	case K_DataPDUInOrder:
   1191 	case K_DataSequenceInOrder:
   1192 		/* values are don't care */
   1193 		if (!sent)
   1194 			set_key_n(state, key, n);
   1195 		break;
   1196 
   1197 	case K_NotUnderstood:
   1198 		/* return "NotUnderstood" */
   1199 		set_key_s(state, key, par->val.sval);
   1200 		break;
   1201 
   1202 		/*
   1203 		 * Declarative keys (no response required)
   1204 		 */
   1205 	case K_TargetAddress:
   1206 		/* ignore for now... */
   1207 		break;
   1208 
   1209 	case K_TargetAlias:
   1210 		if (conn->login_par->is_present.TargetAlias) {
   1211 			copyoutstr(par->val.sval, conn->login_par->TargetAlias,
   1212 				ISCSI_STRING_LENGTH - 1, &sz);
   1213 			/* do anything with return code?? */
   1214 		}
   1215 		break;
   1216 
   1217 	case K_TargetPortalGroupTag:
   1218 		/* ignore for now... */
   1219 		break;
   1220 
   1221 	default:
   1222 		DEBOUT(("eval_par: Invalid parameter type %d\n", par->key));
   1223 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1224 	}
   1225 	return 0;
   1226 }
   1227 
   1228 /*****************************************************************************/
   1229 
   1230 
   1231 /*
   1232  * init_session_parameters:
   1233  *    Initialize session-related negotiation parameters from existing session
   1234  *
   1235  *    Parameter:
   1236  *          sess     The session
   1237  *          state    The negotiation state
   1238  */
   1239 
   1240 STATIC void
   1241 init_session_parameters(session_t *sess, negotiation_state_t *state)
   1242 {
   1243 
   1244 	state->ErrorRecoveryLevel = sess->ErrorRecoveryLevel;
   1245 	state->InitialR2T = sess->InitialR2T;
   1246 	state->ImmediateData = sess->ImmediateData;
   1247 	state->MaxConnections = sess->MaxConnections;
   1248 	state->DefaultTime2Wait = sess->DefaultTime2Wait;
   1249 	state->DefaultTime2Retain = sess->DefaultTime2Retain;
   1250 	state->MaxBurstLength = sess->MaxBurstLength;
   1251 	state->FirstBurstLength = sess->FirstBurstLength;
   1252 	state->MaxOutstandingR2T = sess->MaxOutstandingR2T;
   1253 }
   1254 
   1255 
   1256 
   1257 /*
   1258  * assemble_login_parameters:
   1259  *    Assemble the initial login negotiation parameters.
   1260  *
   1261  *    Parameter:
   1262  *          conn     The connection
   1263  *          ccb      The CCB for the login exchange
   1264  *          pdu      The PDU to use for sending
   1265  *
   1266  *    Returns:    < 0   if more security negotiation is required
   1267  *                0     if this is the last security negotiation block
   1268  *                > 0   (an ISCSI error code) if an error occurred.
   1269  */
   1270 
   1271 int
   1272 assemble_login_parameters(connection_t *conn, ccb_t *ccb, pdu_t *pdu)
   1273 {
   1274 	iscsi_login_parameters_t *par = conn->login_par;
   1275 	size_t sz;
   1276 	int rc, i, next;
   1277 	negotiation_state_t *state;
   1278 	negotiation_parameter_t *cpar;
   1279 
   1280 	state = malloc(sizeof(*state), M_TEMP, M_WAITOK | M_ZERO);
   1281 	if (state == NULL) {
   1282 		DEBOUT(("*** Out of memory in assemble_login_params\n"));
   1283 		return ISCSI_STATUS_NO_RESOURCES;
   1284 	}
   1285 	ccb->temp_data = state;
   1286 
   1287 	if (!iscsi_InitiatorName[0]) {
   1288 		DEBOUT(("No InitiatorName\n"));
   1289 		return ISCSI_STATUS_PARAMETER_MISSING;
   1290 	}
   1291 	set_key_s(state, K_InitiatorName, iscsi_InitiatorName);
   1292 
   1293 	if (iscsi_InitiatorAlias[0])
   1294 		set_key_s(state, K_InitiatorAlias, iscsi_InitiatorAlias);
   1295 
   1296 	conn->Our_MaxRecvDataSegmentLength =
   1297 		(par->is_present.MaxRecvDataSegmentLength)
   1298 		? par->MaxRecvDataSegmentLength : DEFAULT_MaxRecvDataSegmentLength;
   1299 
   1300 	/* setup some values for authentication */
   1301 	if (par->is_present.password)
   1302 		copyinstr(par->password, state->password, MAX_STRING, &sz);
   1303 	if (par->is_present.target_password)
   1304 		copyinstr(par->target_password, state->target_password,
   1305 			MAX_STRING, &sz);
   1306 	if (par->is_present.user_name)
   1307 		copyinstr(par->user_name, state->user_name, MAX_STRING, &sz);
   1308 	else
   1309 		strlcpy(state->user_name, iscsi_InitiatorName,
   1310 			sizeof(state->user_name));
   1311 
   1312 	next = TRUE;
   1313 
   1314 	set_key_n(state, K_SessionType,
   1315 			  par->login_type > ISCSI_LOGINTYPE_DISCOVERY);
   1316 
   1317 	cpar = set_key_n(state, K_AuthMethod, ISCSI_AUTH_None);
   1318 
   1319 	if (cpar != NULL && par->is_present.auth_info &&
   1320 		par->auth_info.auth_number > 0) {
   1321 		if (par->auth_info.auth_number > ISCSI_AUTH_OPTIONS) {
   1322 			DEBOUT(("Auth number too big in asm_login\n"));
   1323 			return ISCSI_STATUS_PARAMETER_INVALID;
   1324 		}
   1325 		cpar->list_num = par->auth_info.auth_number;
   1326 		for (i = 0; i < cpar->list_num; i++) {
   1327 			cpar->val.nval[i] = par->auth_info.auth_type[i];
   1328 			if (par->auth_info.auth_type[i])
   1329 				next = FALSE;
   1330 		}
   1331 	}
   1332 
   1333 	if (par->is_present.TargetName)
   1334 		copyinstr(par->TargetName, state->temp_buf, ISCSI_STRING_LENGTH - 1,
   1335 				  &sz);
   1336 	else {
   1337 		state->temp_buf[0] = 0;
   1338 		sz = 0;
   1339 	}
   1340 
   1341 	if ((!sz || !state->temp_buf[0]) &&
   1342 		par->login_type != ISCSI_LOGINTYPE_DISCOVERY) {
   1343 		DEBOUT(("No TargetName\n"));
   1344 		return ISCSI_STATUS_PARAMETER_MISSING;
   1345 	}
   1346 
   1347 	if (state->temp_buf[0]) {
   1348 		set_key_s(state, K_TargetName, state->temp_buf);
   1349 	}
   1350 
   1351 	if ((rc = complete_pars(state, pdu)) != 0)
   1352 		return rc;
   1353 
   1354 	return (next) ? 0 : -1;
   1355 }
   1356 
   1357 
   1358 /*
   1359  * assemble_security_parameters:
   1360  *    Assemble the security negotiation parameters.
   1361  *
   1362  *    Parameter:
   1363  *          conn     The connection
   1364  *          rx_pdu   The received login response PDU
   1365  *          tx_pdu   The transmit PDU
   1366  *
   1367  *    Returns:    < 0   if more security negotiation is required
   1368  *                0     if this is the last security negotiation block
   1369  *                > 0   (an ISCSI error code) if an error occurred.
   1370  */
   1371 
   1372 int
   1373 assemble_security_parameters(connection_t *conn, ccb_t *ccb, pdu_t *rx_pdu,
   1374 							 pdu_t *tx_pdu)
   1375 {
   1376 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1377 	iscsi_login_parameters_t *par = conn->login_par;
   1378 	negotiation_parameter_t rxp, *cpar;
   1379 	uint8_t *rxpars;
   1380 	int rc, next;
   1381 	uint8_t identifier = 0;
   1382 	uint8_t *challenge = NULL;
   1383 	int challenge_size = 0;
   1384 	uint8_t *response = NULL;
   1385 	int response_size = 0;
   1386 
   1387 	state->num_pars = 0;
   1388 	next = 0;
   1389 
   1390 	rxpars = (uint8_t *) rx_pdu->temp_data;
   1391 	if (rxpars == NULL) {
   1392 		DEBOUT(("No received parameters!\n"));
   1393 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1394 	}
   1395 	/* Note: There are always at least 2 extra bytes past temp_data_len */
   1396 	rxpars[rx_pdu->temp_data_len] = '\0';
   1397 	rxpars[rx_pdu->temp_data_len + 1] = '\0';
   1398 
   1399 	while (*rxpars) {
   1400 		if ((rxpars = get_parameter(rxpars, &rxp)) == NULL) {
   1401 			DEBOUT(("get_parameter returned error\n"));
   1402 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1403 		}
   1404 
   1405 		state->kflags[rxp.key] |= NS_RECEIVED;
   1406 
   1407 		switch (rxp.key) {
   1408 		case K_AuthMethod:
   1409 			if (state->auth_state != AUTH_INITIAL) {
   1410 				DEBOUT(("AuthMethod received, auth_state = %d\n",
   1411 						state->auth_state));
   1412 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1413 			}
   1414 
   1415 			/* Note: if the selection is None, we shouldn't be here,
   1416 			 * the target should have transited the state to op-neg.
   1417 			 */
   1418 			if (rxp.val.nval[0] != ISCSI_AUTH_CHAP) {
   1419 				DEBOUT(("AuthMethod isn't CHAP (%d)\n", rxp.val.nval[0]));
   1420 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1421 			}
   1422 
   1423 			state->auth_state = AUTH_METHOD_SELECTED;
   1424 			state->auth_alg = rxp.val.nval[0];
   1425 			break;
   1426 
   1427 		case K_Auth_CHAP_Algorithm:
   1428 			if (state->auth_state != AUTH_CHAP_ALG_SENT ||
   1429 				rxp.val.nval[0] != 5) {
   1430 				DEBOUT(("Bad algorithm, auth_state = %d, alg %d\n",
   1431 						state->auth_state, rxp.val.nval[0]));
   1432 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1433 			}
   1434 			break;
   1435 
   1436 		case K_Auth_CHAP_Challenge:
   1437 			if (state->auth_state != AUTH_CHAP_ALG_SENT || !rxp.list_num) {
   1438 				DEBOUT(("Bad Challenge, auth_state = %d, len %d\n",
   1439 						state->auth_state, rxp.list_num));
   1440 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1441 			}
   1442 			challenge = rxp.val.sval;
   1443 			challenge_size = rxp.list_num;
   1444 			break;
   1445 
   1446 		case K_Auth_CHAP_Identifier:
   1447 			if (state->auth_state != AUTH_CHAP_ALG_SENT) {
   1448 				DEBOUT(("Bad ID, auth_state = %d, id %d\n",
   1449 						state->auth_state, rxp.val.nval[0]));
   1450 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1451 			}
   1452 			identifier = (uint8_t) rxp.val.nval[0];
   1453 			break;
   1454 
   1455 		case K_Auth_CHAP_Name:
   1456 			if (state->auth_state != AUTH_CHAP_RSP_SENT) {
   1457 				DEBOUT(("Bad Name, auth_state = %d, name <%s>\n",
   1458 						state->auth_state, rxp.val.sval));
   1459 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1460 			}
   1461 			/* what do we do with the name?? */
   1462 			break;
   1463 
   1464 		case K_Auth_CHAP_Response:
   1465 			if (state->auth_state != AUTH_CHAP_RSP_SENT) {
   1466 				DEBOUT(("Bad Response, auth_state = %d, size %d\n",
   1467 						state->auth_state, rxp.list_num));
   1468 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1469 			}
   1470 			response = rxp.val.sval;
   1471 			response_size = rxp.list_num;
   1472 			if (response_size != CHAP_MD5_SIZE)
   1473 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1474 			break;
   1475 
   1476 		default:
   1477 			rc = eval_parameter(conn, state, &rxp);
   1478 			if (rc)
   1479 				return rc;
   1480 			break;
   1481 		}
   1482 	}
   1483 
   1484 	switch (state->auth_state) {
   1485 	case AUTH_INITIAL:
   1486 		DEBOUT(("Didn't receive Method\n"));
   1487 		return ISCSI_STATUS_NEGOTIATION_ERROR;
   1488 
   1489 	case AUTH_METHOD_SELECTED:
   1490 		set_key_n(state, K_Auth_CHAP_Algorithm, 5);
   1491 		state->auth_state = AUTH_CHAP_ALG_SENT;
   1492 		next = -1;
   1493 		break;
   1494 
   1495 	case AUTH_CHAP_ALG_SENT:
   1496 		if (!RX(state, K_Auth_CHAP_Algorithm) ||
   1497 			!RX(state, K_Auth_CHAP_Identifier) ||
   1498 			!RX(state, K_Auth_CHAP_Challenge)) {
   1499 			DEBOUT(("Didn't receive all parameters\n"));
   1500 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1501 		}
   1502 
   1503 		set_key_s(state, K_Auth_CHAP_Name, state->user_name);
   1504 
   1505 		chap_md5_response(state->temp_buf, identifier, state->password,
   1506 						  challenge, challenge_size);
   1507 
   1508 		cpar = set_key_s(state, K_Auth_CHAP_Response, state->temp_buf);
   1509 		if (cpar != NULL)
   1510 			cpar->list_num = CHAP_MD5_SIZE;
   1511 
   1512 		if (par->auth_info.mutual_auth) {
   1513 			if (!state->target_password[0]) {
   1514 				DEBOUT(("No target password with mutual authentication!\n"));
   1515 				return ISCSI_STATUS_PARAMETER_MISSING;
   1516 			}
   1517 
   1518 			cprng_strong(kern_cprng,
   1519 				     &state->temp_buf[CHAP_MD5_SIZE],
   1520 				     CHAP_CHALLENGE_LEN + 1, 0);
   1521 			set_key_n(state, K_Auth_CHAP_Identifier,
   1522 					  state->temp_buf[CHAP_MD5_SIZE]);
   1523 			cpar = set_key_s(state, K_Auth_CHAP_Challenge,
   1524 							 &state->temp_buf[CHAP_MD5_SIZE + 1]);
   1525 			if (cpar != NULL)
   1526 				cpar->list_num = CHAP_CHALLENGE_LEN;
   1527 			next = -1;
   1528 		}
   1529 		state->auth_state = AUTH_CHAP_RSP_SENT;
   1530 		break;
   1531 
   1532 	case AUTH_CHAP_RSP_SENT:
   1533 		/* we can only be here for mutual authentication */
   1534 		if (!par->auth_info.mutual_auth || response == NULL) {
   1535 			DEBOUT(("Mutual authentication not requested\n"));
   1536 			return ISCSI_STATUS_NEGOTIATION_ERROR;
   1537 		}
   1538 
   1539 		chap_md5_response(state->temp_buf,
   1540 				state->temp_buf[CHAP_MD5_SIZE],
   1541 				state->password,
   1542 				&state->temp_buf[CHAP_MD5_SIZE + 1],
   1543 				CHAP_CHALLENGE_LEN);
   1544 
   1545 		if (memcmp(state->temp_buf, response, response_size)) {
   1546 			DEBOUT(("Mutual authentication mismatch\n"));
   1547 			return ISCSI_STATUS_AUTHENTICATION_FAILED;
   1548 		}
   1549 		break;
   1550 
   1551 	default:
   1552 		break;
   1553 	}
   1554 
   1555 	complete_pars(state, tx_pdu);
   1556 
   1557 	return next;
   1558 }
   1559 
   1560 
   1561 /*
   1562  * set_first_opnegs:
   1563  *    Set the operational negotiation parameters we want to negotiate in
   1564  *    the first login request in op_neg phase.
   1565  *
   1566  *    Parameter:
   1567  *          conn     The connection
   1568  *          state    Negotiation state
   1569  */
   1570 
   1571 STATIC void
   1572 set_first_opnegs(connection_t *conn, negotiation_state_t *state)
   1573 {
   1574 	iscsi_login_parameters_t *lpar = conn->login_par;
   1575 	negotiation_parameter_t *cpar;
   1576 
   1577     /* Digests - suggest None,CRC32C unless the user forces a value */
   1578 	cpar = set_key_n(state, K_HeaderDigest,
   1579 					 (lpar->is_present.HeaderDigest) ? lpar->HeaderDigest : 0);
   1580 	if (cpar != NULL && !lpar->is_present.HeaderDigest) {
   1581 		cpar->list_num = 2;
   1582 		cpar->val.nval[1] = 1;
   1583 	}
   1584 
   1585 	cpar = set_key_n(state, K_DataDigest, (lpar->is_present.DataDigest)
   1586 		? lpar->DataDigest : 0);
   1587 	if (cpar != NULL && !lpar->is_present.DataDigest) {
   1588 		cpar->list_num = 2;
   1589 		cpar->val.nval[1] = 1;
   1590 	}
   1591 
   1592 	set_key_n(state, K_MaxRecvDataSegmentLength,
   1593 		conn->Our_MaxRecvDataSegmentLength);
   1594 	/* This is direction-specific, we may have a different default */
   1595 	state->MaxRecvDataSegmentLength =
   1596 		entries[K_MaxRecvDataSegmentLength].defval;
   1597 
   1598 	/* First connection only */
   1599 	if (!conn->session->TSIH) {
   1600 		state->ErrorRecoveryLevel =
   1601 			(lpar->is_present.ErrorRecoveryLevel) ? lpar->ErrorRecoveryLevel
   1602 												  : 2;
   1603 		/*
   1604 		   Negotiate InitialR2T to FALSE and ImmediateData to TRUE, should
   1605 		   be slightly more efficient than the default InitialR2T=TRUE.
   1606 		 */
   1607 		state->InitialR2T = FALSE;
   1608 		state->ImmediateData = TRUE;
   1609 
   1610 		/* We don't really care about this, so don't negotiate by default */
   1611 		state->MaxBurstLength = entries[K_MaxBurstLength].defval;
   1612 		state->FirstBurstLength = entries[K_FirstBurstLength].defval;
   1613 		state->MaxOutstandingR2T = entries[K_MaxOutstandingR2T].defval;
   1614 
   1615 #ifdef ISCSI_TEST_MODE
   1616 		if (conn->test_pars != NULL) {
   1617 			test_pars_t *tp = conn->test_pars;
   1618 
   1619 			if (tp->options & ISCSITEST_OVERRIDE_INITIALR2T)
   1620 				state->InitialR2T = TRUE;
   1621 			if (tp->options & ISCSITEST_OVERRIDE_IMMDATA)
   1622 				state->ImmediateData = FALSE;
   1623 
   1624 			if (tp->options & ISCSITEST_NEGOTIATE_MAXBURST) {
   1625 				state->MaxBurstLength = tp->maxburst_val;
   1626 				set_key_n(state, K_MaxBurstLength, state->MaxBurstLength);
   1627 			}
   1628 			if (tp->options & ISCSITEST_NEGOTIATE_FIRSTBURST) {
   1629 				state->FirstBurstLength = tp->firstburst_val;
   1630 				set_key_n(state, K_FirstBurstLength, state->FirstBurstLength);
   1631 			}
   1632 			if (tp->options & ISCSITEST_NEGOTIATE_R2T) {
   1633 				state->MaxOutstandingR2T = tp->r2t_val;
   1634 				set_key_n(state, K_MaxOutstandingR2T, state->MaxOutstandingR2T);
   1635 			}
   1636 		}
   1637 #endif
   1638 
   1639 		set_key_n(state, K_ErrorRecoveryLevel, state->ErrorRecoveryLevel);
   1640 		set_key_n(state, K_InitialR2T, state->InitialR2T);
   1641 		set_key_n(state, K_ImmediateData, state->ImmediateData);
   1642 
   1643 		if (lpar->is_present.MaxConnections) {
   1644 			state->MaxConnections = lpar->MaxConnections;
   1645 			set_key_n(state, K_MaxConnections, lpar->MaxConnections);
   1646 		}
   1647 
   1648 		if (lpar->is_present.DefaultTime2Wait)
   1649 			set_key_n(state, K_DefaultTime2Wait, lpar->DefaultTime2Wait);
   1650 		else
   1651 			state->DefaultTime2Wait = entries[K_DefaultTime2Wait].defval;
   1652 
   1653 		if (lpar->is_present.DefaultTime2Retain)
   1654 			set_key_n(state, K_DefaultTime2Retain, lpar->DefaultTime2Retain);
   1655 		else
   1656 			state->DefaultTime2Retain = entries[K_DefaultTime2Retain].defval;
   1657 	} else
   1658 		init_session_parameters(conn->session, state);
   1659 
   1660 	DEBC(conn, 10, ("SetFirstOpnegs: recover=%d, MRDSL=%d\n",
   1661 		conn->recover, state->MaxRecvDataSegmentLength));
   1662 }
   1663 
   1664 
   1665 /*
   1666  * assemble_negotiation_parameters:
   1667  *    Assemble any negotiation parameters requested by the other side.
   1668  *
   1669  *    Parameter:
   1670  *          conn     The connection
   1671  *          ccb      The login ccb
   1672  *          rx_pdu   The received login response PDU
   1673  *          tx_pdu   The transmit PDU
   1674  *
   1675  *    Returns:    0     On success
   1676  *                > 0   (an ISCSI error code) if an error occurred.
   1677  */
   1678 
   1679 int
   1680 assemble_negotiation_parameters(connection_t *conn, ccb_t *ccb, pdu_t *rx_pdu,
   1681 							    pdu_t *tx_pdu)
   1682 {
   1683 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1684 	negotiation_parameter_t rxp;
   1685 	uint8_t *rxpars;
   1686 	int rc;
   1687 
   1688 	state->num_pars = 0;
   1689 
   1690 	DEBC(conn, 10, ("AsmNegParams: connState=%d, MRDSL=%d\n",
   1691 		conn->state, state->MaxRecvDataSegmentLength));
   1692 
   1693 	if (conn->state == ST_SEC_NEG) {
   1694 		conn->state = ST_OP_NEG;
   1695 		set_first_opnegs(conn, state);
   1696 	}
   1697 
   1698 	rxpars = (uint8_t *) rx_pdu->temp_data;
   1699 	if (rxpars != NULL) {
   1700 		/* Note: There are always at least 2 extra bytes past temp_data_len */
   1701 		rxpars[rx_pdu->temp_data_len] = '\0';
   1702 		rxpars[rx_pdu->temp_data_len + 1] = '\0';
   1703 
   1704 		while (*rxpars) {
   1705 			if ((rxpars = get_parameter(rxpars, &rxp)) == NULL)
   1706 				return ISCSI_STATUS_NEGOTIATION_ERROR;
   1707 
   1708 			rc = eval_parameter(conn, state, &rxp);
   1709 			if (rc)
   1710 				return rc;
   1711 		}
   1712 	}
   1713 
   1714 	if (tx_pdu == NULL)
   1715 		return 0;
   1716 
   1717 	complete_pars(state, tx_pdu);
   1718 
   1719 	return 0;
   1720 }
   1721 
   1722 /*
   1723  * init_text_parameters:
   1724  *    Initialize text negotiation.
   1725  *
   1726  *    Parameter:
   1727  *          conn     The connection
   1728  *          tx_pdu   The transmit PDU
   1729  *
   1730  *    Returns:    0     On success
   1731  *                > 0   (an ISCSI error code) if an error occurred.
   1732  */
   1733 
   1734 int
   1735 init_text_parameters(connection_t *conn, ccb_t *ccb)
   1736 {
   1737 	negotiation_state_t *state;
   1738 
   1739 	state = malloc(sizeof(*state), M_TEMP, M_WAITOK | M_ZERO);
   1740 	if (state == NULL) {
   1741 		DEBOUT(("*** Out of memory in init_text_params\n"));
   1742 		return ISCSI_STATUS_NO_RESOURCES;
   1743 	}
   1744 	ccb->temp_data = state;
   1745 
   1746 	state->HeaderDigest = conn->HeaderDigest;
   1747 	state->DataDigest = conn->DataDigest;
   1748 	state->MaxRecvDataSegmentLength = conn->MaxRecvDataSegmentLength;
   1749 	init_session_parameters(conn->session, state);
   1750 
   1751 	return 0;
   1752 }
   1753 
   1754 
   1755 /*
   1756  * assemble_send_targets:
   1757  *    Assemble send targets request
   1758  *
   1759  *    Parameter:
   1760  *          pdu      The transmit PDU
   1761  *          val      The SendTargets key value
   1762  *
   1763  *    Returns:    0     On success
   1764  *                > 0   (an ISCSI error code) if an error occurred.
   1765  */
   1766 
   1767 int
   1768 assemble_send_targets(pdu_t *pdu, uint8_t *val)
   1769 {
   1770 	negotiation_parameter_t par;
   1771 	uint8_t *buf;
   1772 	int len;
   1773 
   1774 	par.key = K_SendTargets;
   1775 	par.list_num = 1;
   1776 	par.val.sval = val;
   1777 
   1778 	len = parameter_size(&par);
   1779 
   1780 	if ((buf = malloc(len, M_TEMP, M_WAITOK)) == NULL) {
   1781 		DEBOUT(("*** Out of memory in assemble_send_targets\n"));
   1782 		return ISCSI_STATUS_NO_RESOURCES;
   1783 	}
   1784 	pdu->temp_data = buf;
   1785 	pdu->temp_data_len = len;
   1786 
   1787 	if (put_parameter(buf, len, &par) == 0)
   1788 		return ISCSI_STATUS_PARAMETER_INVALID;
   1789 
   1790 	return 0;
   1791 }
   1792 
   1793 
   1794 /*
   1795  * set_negotiated_parameters:
   1796  *    Copy the negotiated parameters into the connection and session structure.
   1797  *
   1798  *    Parameter:
   1799  *          ccb      The ccb containing the state information
   1800  */
   1801 
   1802 void
   1803 set_negotiated_parameters(ccb_t *ccb)
   1804 {
   1805 	negotiation_state_t *state = (negotiation_state_t *) ccb->temp_data;
   1806 	connection_t *conn = ccb->connection;
   1807 	session_t *sess = ccb->session;
   1808 
   1809 	conn->HeaderDigest = state->HeaderDigest;
   1810 	conn->DataDigest = state->DataDigest;
   1811 	sess->ErrorRecoveryLevel = state->ErrorRecoveryLevel;
   1812 	sess->InitialR2T = state->InitialR2T;
   1813 	sess->ImmediateData = state->ImmediateData;
   1814 	conn->MaxRecvDataSegmentLength = state->MaxRecvDataSegmentLength;
   1815 	sess->MaxConnections = state->MaxConnections;
   1816 	sess->DefaultTime2Wait = conn->Time2Wait = state->DefaultTime2Wait;
   1817 	sess->DefaultTime2Retain = conn->Time2Retain =
   1818 		state->DefaultTime2Retain;
   1819 
   1820 	/* set idle connection timeout to half the Time2Retain window so we */
   1821 	/* don't miss it, unless Time2Retain is ridiculously small. */
   1822 	conn->idle_timeout_val = (conn->Time2Retain >= 10) ?
   1823 		(conn->Time2Retain / 2) * hz : CONNECTION_IDLE_TIMEOUT;
   1824 
   1825 	sess->MaxBurstLength = state->MaxBurstLength;
   1826 	sess->FirstBurstLength = state->FirstBurstLength;
   1827 	sess->MaxOutstandingR2T = state->MaxOutstandingR2T;
   1828 
   1829 	DEBC(conn, 10,("SetNegPar: MRDSL=%d, MBL=%d, FBL=%d, IR2T=%d, ImD=%d\n",
   1830 		state->MaxRecvDataSegmentLength, state->MaxBurstLength,
   1831 		state->FirstBurstLength, state->InitialR2T,
   1832 		state->ImmediateData));
   1833 
   1834 	conn->max_transfer = min(sess->MaxBurstLength, conn->MaxRecvDataSegmentLength);
   1835 
   1836 	conn->max_firstimmed = (!sess->ImmediateData) ? 0 :
   1837 				min(sess->FirstBurstLength, conn->max_transfer);
   1838 
   1839 	conn->max_firstdata = (sess->InitialR2T || sess->FirstBurstLength < conn->max_firstimmed) ? 0 :
   1840 				min(sess->FirstBurstLength - conn->max_firstimmed, conn->max_transfer);
   1841 
   1842 }
   1843