summaryrefslogtreecommitdiffstats
path: root/sbin/iscontrol
diff options
context:
space:
mode:
authorscottl <scottl@FreeBSD.org>2007-07-24 15:35:02 +0000
committerscottl <scottl@FreeBSD.org>2007-07-24 15:35:02 +0000
commit08b4d87cfeb6a16578e5ea85388ed36884d14f49 (patch)
tree2ea97a85d2ad3ef80513af697b1ce0fa11f34156 /sbin/iscontrol
parent67705357ae28711ac9af6e507a24c9b7fadd6f16 (diff)
downloadFreeBSD-src-08b4d87cfeb6a16578e5ea85388ed36884d14f49.zip
FreeBSD-src-08b4d87cfeb6a16578e5ea85388ed36884d14f49.tar.gz
Introduce Danny Braniss' iSCSI initiator, version 2.0.99. Please read the
included man pages on how to use it. This code is still somewhat experimental but has been successfully tested on a number of targets. Many thanks to Danny for contributing this. Approved by: re
Diffstat (limited to 'sbin/iscontrol')
-rw-r--r--sbin/iscontrol/Makefile13
-rw-r--r--sbin/iscontrol/auth_subr.c208
-rw-r--r--sbin/iscontrol/config.c376
-rw-r--r--sbin/iscontrol/fsm.c721
-rw-r--r--sbin/iscontrol/iscontrol.8116
-rw-r--r--sbin/iscontrol/iscontrol.c227
-rw-r--r--sbin/iscontrol/iscontrol.h159
-rw-r--r--sbin/iscontrol/iscsi.conf.5204
-rw-r--r--sbin/iscontrol/login.c440
-rw-r--r--sbin/iscontrol/misc.c225
-rw-r--r--sbin/iscontrol/pdu.c175
-rw-r--r--sbin/iscontrol/pdu.h134
12 files changed, 2998 insertions, 0 deletions
diff --git a/sbin/iscontrol/Makefile b/sbin/iscontrol/Makefile
new file mode 100644
index 0000000..2b09fa9
--- /dev/null
+++ b/sbin/iscontrol/Makefile
@@ -0,0 +1,13 @@
+# $FreeBSD$
+
+SRCS= iscontrol.c pdu.c fsm.c config.c login.c auth_subr.c misc.c
+PROG= iscontrol
+DPADD= ${LIBCAM} ${LIBMD}
+LDADD= -lcam -lmd
+
+CFLAGS += -I${.CURDIR}/../../sys/dev/iscsi/initiator
+#CFLAGS += -g -DDEBUG
+
+MAN= iscsi.conf.5 iscontrol.8
+
+.include <bsd.prog.mk>
diff --git a/sbin/iscontrol/auth_subr.c b/sbin/iscontrol/auth_subr.c
new file mode 100644
index 0000000..8381687
--- /dev/null
+++ b/sbin/iscontrol/auth_subr.c
@@ -0,0 +1,208 @@
+/*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ | $Id: auth_subr.c,v 2.2 2007/06/01 08:09:37 danny Exp $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#if __FreeBSD_version < 500000
+#include <sys/time.h>
+#endif
+#include <unistd.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <fcntl.h>
+
+#include <md5.h>
+#include <sha.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+#include "pdu.h"
+
+static int
+chapMD5(char id, char *cp, char *chapSecret, unsigned char *digest)
+{
+ MD5_CTX ctx;
+ char *tmp;
+ int len;
+
+ debug_called(3);
+
+ MD5Init(&ctx);
+
+ MD5Update(&ctx, &id, 1);
+
+ if((len = str2bin(chapSecret, &tmp)) == 0) {
+ // print error
+ return -1;
+ }
+ MD5Update(&ctx, tmp, len);
+ free(tmp);
+
+ if((len = str2bin(cp, &tmp)) == 0) {
+ // print error
+ return -1;
+ }
+ MD5Update(&ctx, tmp, len);
+ free(tmp);
+
+ MD5Final(digest, &ctx);
+
+
+ return 0;
+}
+
+static int
+chapSHA1(char id, char *cp, char *chapSecret, unsigned char *digest)
+{
+ SHA1_CTX ctx;
+ char *tmp;
+ int len;
+
+ debug_called(3);
+
+ SHA1_Init(&ctx);
+
+ SHA1_Update(&ctx, &id, 1);
+
+ if((len = str2bin(chapSecret, &tmp)) == 0) {
+ // print error
+ return -1;
+ }
+ SHA1_Update(&ctx, tmp, len);
+ free(tmp);
+
+ if((len = str2bin(cp, &tmp)) == 0) {
+ // print error
+ return -1;
+ }
+ SHA1_Update(&ctx, tmp, len);
+ free(tmp);
+
+ SHA1_Final(digest, &ctx);
+
+ return 0;
+
+}
+/*
+ | the input text format can be anything that the rfc3270 defines
+ | (see section 5.1 and str2bin)
+ | digest length for md5 is 128bits, and for sha1 is 160bits.
+ | digest is an ASCII string which represents the bits in
+ | hexadecimal or base64 according to the challenge(cp) format
+ */
+char *
+chapDigest(char *ap, char id, char *cp, char *chapSecret)
+{
+ int len;
+ unsigned char digest[20];
+ char encoding[3];
+
+ debug_called(3);
+
+ len = 0;
+ if(strcmp(ap, "5") == 0 && chapMD5(id, cp, chapSecret, digest) == 0)
+ len = 16;
+ else
+ if(strcmp(ap, "7") == 0 && chapSHA1(id, cp, chapSecret, digest) == 0)
+ len = 20;
+
+ if(len) {
+ sprintf(encoding, "%.2s", cp);
+ return bin2str(encoding, digest, len);
+ }
+
+ return NULL;
+}
+
+char *
+genChapChallenge(char *encoding, int len)
+{
+ int fd;
+ unsigned char tmp[1024];
+
+ if(len > sizeof(tmp))
+ return NULL;
+
+ if((fd = open("/dev/random", O_RDONLY)) != -1) {
+ read(fd, tmp, len);
+ close(fd);
+ return bin2str(encoding, tmp, len);
+ }
+ perror("/dev/random");
+ // make up something ...
+ return NULL;
+}
+
+#ifdef TEST_AUTH
+static void
+puke(char *str, unsigned char *dg, int len)
+{
+ printf("%3d] %s\n 0x", len, str);
+ while(len-- > 0)
+ printf("%02x", *dg++);
+ printf("\n");
+}
+
+main(int cc, char **vv)
+{
+ char *p, *ap, *ip, *cp, *chapSecret, *digest;
+ int len;
+
+#if 0
+ ap = "5";
+ chapSecret = "0xa5aff013dd839b1edd31ee73a1df0b1b";
+// chapSecret = "abcdefghijklmnop";
+ len = str2bin(chapSecret, &cp);
+ puke(chapSecret, cp, len);
+
+ ip = "238";
+ cp = "0xbd456029";
+
+
+ if((digest = chapDigest(ap, ip, cp, chapSecret)) != NULL) {
+ len = str2bin(digest, &cp);
+ puke(digest, cp, len);
+ }
+#else
+ printf("%d] %s\n", 24, genChallenge("0X", 24));
+#endif
+}
+#endif
diff --git a/sbin/iscontrol/config.c b/sbin/iscontrol/config.c
new file mode 100644
index 0000000..409ed2c
--- /dev/null
+++ b/sbin/iscontrol/config.c
@@ -0,0 +1,376 @@
+ /*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+/*
+ | $Id: config.c,v 2.1 2006/11/12 08:06:51 danny Exp danny $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <time.h>
+#include <ctype.h>
+#include <camlib.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+
+/*
+ | ints
+ */
+#define OPT_port 1
+#define OPT_tags 2
+
+#define OPT_maxConnections 3
+#define OPT_maxRecvDataSegmentLength 4
+#define OPT_maxXmitDataSegmentLength 5
+#define OPT_maxBurstLength 6
+#define OPT_firstBurstLength 7
+#define OPT_defaultTime2Wait 8
+#define OPT_defaultTime2Retain 9
+#define OPT_maxOutstandingR2T 10
+#define OPT_errorRecoveryLevel 11
+#define OPT_targetPortalGroupTag 12
+#define OPT_headerDigest 13
+#define OPT_dataDigest 14
+/*
+ | Booleans
+ */
+#define OPT_initialR2T 16
+#define OPT_immediateData 17
+#define OPT_dataPDUInOrder 18
+#define OPT_dataSequenceInOrder 19
+/*
+ | strings
+ */
+#define OPT_sessionType 15
+
+#define OPT_targetAddress 21
+#define OPT_targetAlias 22
+#define OPT_targetName 23
+#define OPT_initiatorName 24
+#define OPT_initiatorAlias 25
+#define OPT_authMethod 26
+
+#define OPT_chapSecret 27
+#define OPT_chapIName 28
+#define OPT_chapDigest 29
+#define OPT_tgtChapName 30
+#define OPT_tgtChapSecret 31
+#define OPT_tgtChallengeLen 32
+/*
+ | private
+ */
+#define OPT_maxluns 33
+#define OPT_iqn 34
+#define OPT_sockbufsize 35
+
+#define _OFF(v) ((int)&((isc_opt_t *)NULL)->v)
+#define _E(u, s, v) {.usage=u, .scope=s, .name=#v, .tokenID=OPT_##v}
+
+textkey_t keyMap[] = {
+ _E(U_PR, S_PR, port),
+ _E(U_PR, S_PR, tags),
+ _E(U_PR, S_PR, maxluns),
+ _E(U_PR, S_PR, sockbufsize),
+
+ _E(U_PR, S_PR, iqn),
+ _E(U_PR, S_PR, chapSecret),
+ _E(U_PR, S_PR, chapIName),
+ _E(U_PR, S_PR, chapDigest),
+ _E(U_PR, S_PR, tgtChapName),
+ _E(U_PR, S_PR, tgtChapSecret),
+ _E(U_PR, S_PR, tgtChallengeLen),
+
+ _E(U_IO, S_CO, headerDigest),
+ _E(U_IO, S_CO, dataDigest),
+
+ _E(U_IO, S_CO, authMethod),
+
+ _E(U_LO, S_SW, maxConnections),
+ _E(U_IO, S_SW, targetName),
+
+ _E(U_IO, S_SW, initiatorName),
+ _E(U_ALL,S_SW, targetAlias),
+ _E(U_ALL,S_SW, initiatorAlias),
+ _E(U_ALL,S_SW, targetAddress),
+
+ _E(U_ALL,S_SW, targetPortalGroupTag),
+
+ _E(U_LO, S_SW, initialR2T),
+ _E(U_LO, S_SW, immediateData),
+
+ _E(U_ALL,S_CO, maxRecvDataSegmentLength),
+ _E(U_ALL,S_CO, maxXmitDataSegmentLength),
+
+ _E(U_LO, S_SW, maxBurstLength),
+ _E(U_LO, S_SW, firstBurstLength),
+ _E(U_LO, S_SW, defaultTime2Wait),
+ _E(U_LO, S_SW, defaultTime2Retain),
+
+ _E(U_LO, S_SW, maxOutstandingR2T),
+ _E(U_LO, S_SW, dataPDUInOrder),
+ _E(U_LO, S_SW, dataSequenceInOrder),
+
+ _E(U_LO, S_SW, errorRecoveryLevel),
+
+ _E(U_LO, S_SW, sessionType),
+
+ {0}
+};
+
+#define _OPT_INT(w) strtol((char *)w, NULL, 0)
+#define _OPT_STR(w) (char *)(w)
+
+static __inline int
+_OPT_BOOL(char *w)
+{
+ if(isalpha(*w))
+ return strcasecmp(w, "TRUE") == 0;
+ else
+ return _OPT_INT(w);
+}
+
+#define _CASE(k, v) case OPT_##k: op->k = v; break
+static void
+setOption(isc_opt_t *op, int which, void *rval)
+{
+ switch(which) {
+ _CASE(port, _OPT_INT(rval));
+ _CASE(tags, _OPT_INT(rval));
+ _CASE(maxluns, _OPT_INT(rval));
+ _CASE(iqn, _OPT_STR(rval));
+ _CASE(sockbufsize, _OPT_INT(rval));
+
+ _CASE(maxConnections, _OPT_INT(rval));
+ _CASE(maxRecvDataSegmentLength, _OPT_INT(rval));
+ _CASE(maxXmitDataSegmentLength, _OPT_INT(rval));
+ _CASE(maxBurstLength, _OPT_INT(rval));
+ _CASE(firstBurstLength, _OPT_INT(rval));
+ _CASE(defaultTime2Wait, _OPT_INT(rval));
+ _CASE(defaultTime2Retain, _OPT_INT(rval));
+ _CASE(maxOutstandingR2T, _OPT_INT(rval));
+ _CASE(errorRecoveryLevel, _OPT_INT(rval));
+ _CASE(targetPortalGroupTag, _OPT_INT(rval));
+ _CASE(headerDigest, _OPT_STR(rval));
+ _CASE(dataDigest, _OPT_STR(rval));
+
+ _CASE(targetAddress, _OPT_STR(rval));
+ _CASE(targetAlias, _OPT_STR(rval));
+ _CASE(targetName, _OPT_STR(rval));
+ _CASE(initiatorName, _OPT_STR(rval));
+ _CASE(initiatorAlias, _OPT_STR(rval));
+ _CASE(authMethod, _OPT_STR(rval));
+ _CASE(chapSecret, _OPT_STR(rval));
+ _CASE(chapIName, _OPT_STR(rval));
+ _CASE(chapDigest, _OPT_STR(rval));
+
+ _CASE(tgtChapName, _OPT_STR(rval));
+ _CASE(tgtChapSecret, _OPT_STR(rval));
+
+ _CASE(initialR2T, _OPT_BOOL(rval));
+ _CASE(immediateData, _OPT_BOOL(rval));
+ _CASE(dataPDUInOrder, _OPT_BOOL(rval));
+ _CASE(dataSequenceInOrder, _OPT_BOOL(rval));
+ }
+}
+
+static char *
+getline(FILE *fd)
+{
+ static char *sp, line[BUFSIZ];
+ char *lp, *p;
+
+ do {
+ if(sp == NULL)
+ sp = fgets(line, sizeof line, fd);
+
+ if((lp = sp) == NULL)
+ break;
+ if((p = strchr(lp, '\n')) != NULL)
+ *p = 0;
+ if((p = strchr(lp, '#')) != NULL)
+ *p = 0;
+ if((p = strchr(lp, ';')) != NULL) {
+ *p++ = 0;
+ sp = p;
+ } else
+ sp = NULL;
+ if(*lp)
+ return lp;
+ } while (feof(fd) == 0);
+ return NULL;
+}
+
+static int
+getConfig(FILE *fd, char *key, char **Ar, int *nargs)
+{
+ char *lp, *p, **ar;
+ int state, len, n;
+
+ ar = Ar;
+ if(key)
+ len = strlen(key);
+ else
+ len = 0;
+ state = 0;
+ while((lp = getline(fd)) != NULL) {
+ for(; isspace(*lp); lp++)
+ ;
+ switch(state) {
+ case 0:
+ if((p = strchr(lp, '{')) != NULL) {
+ n = 0;
+ while((--p > lp) && *p && isspace(*p));
+ n = p - lp;
+ if(len && strncmp(lp, key, MAX(n, len)) == 0)
+ state = 2;
+ else
+ state = 1;
+ continue;
+ }
+ break;
+
+ case 1:
+ if(*lp == '}')
+ state = 0;
+ continue;
+
+ case 2:
+ if(*lp == '}')
+ goto done;
+
+ break;
+ }
+
+
+ for(p = &lp[strlen(lp)-1]; isspace(*p); p--)
+ *p = 0;
+ if((*nargs)-- > 0)
+ *ar++ = strdup(lp);
+ }
+
+ done:
+ if(*nargs > 0)
+ *ar = 0;
+ *nargs = ar - Ar;
+ return ar - Ar;
+}
+
+static textkey_t *
+keyLookup(char *key)
+{
+ textkey_t *tk;
+
+ for(tk = keyMap; tk->name; tk++) {
+ if(strcasecmp(key, tk->name) == 0)
+ return tk;
+ }
+ return NULL;
+}
+
+static void
+puke(isc_opt_t *op)
+{
+ printf("%24s = %d\n", "port", op->port);
+ printf("%24s = %d\n", "tags", op->tags);
+ printf("%24s = %d\n", "maxluns", op->maxluns);
+ printf("%24s = %s\n", "iqn", op->iqn);
+
+ printf("%24s = %d\n", "maxConnections", op->maxConnections);
+ printf("%24s = %d\n", "maxRecvDataSegmentLength", op->maxRecvDataSegmentLength);
+ printf("%24s = %d\n", "maxXmitDataSegmentLength", op->maxRecvDataSegmentLength);
+ printf("%24s = %d\n", "maxBurstLength", op->maxBurstLength);
+ printf("%24s = %d\n", "firstBurstLength", op->firstBurstLength);
+ printf("%24s = %d\n", "defaultTime2Wait", op->defaultTime2Wait);
+ printf("%24s = %d\n", "defaultTime2Retain", op->defaultTime2Retain);
+ printf("%24s = %d\n", "maxOutstandingR2T", op->maxOutstandingR2T);
+ printf("%24s = %d\n", "errorRecoveryLevel", op->errorRecoveryLevel);
+ printf("%24s = %d\n", "targetPortalGroupTag", op->targetPortalGroupTag);
+
+ printf("%24s = %s\n", "headerDigest", op->headerDigest);
+ printf("%24s = %s\n", "dataDigest", op->dataDigest);
+
+ printf("%24s = %d\n", "initialR2T", op->initialR2T);
+ printf("%24s = %d\n", "immediateData", op->immediateData);
+ printf("%24s = %d\n", "dataPDUInOrder", op->dataPDUInOrder);
+ printf("%24s = %d\n", "dataSequenceInOrder", op->dataSequenceInOrder);
+
+ printf("%24s = %s\n", "sessionType", op->sessionType);
+ printf("%24s = %s\n", "targetAddress", op->targetAddress);
+ printf("%24s = %s\n", "targetAlias", op->targetAlias);
+ printf("%24s = %s\n", "targetName", op->targetName);
+ printf("%24s = %s\n", "initiatorName", op->initiatorName);
+ printf("%24s = %s\n", "initiatorAlias", op->initiatorAlias);
+ printf("%24s = %s\n", "authMethod", op->authMethod);
+ printf("%24s = %s\n", "chapSecret", op->chapSecret);
+ printf("%24s = %s\n", "chapIName", op->chapIName);
+ printf("%24s = %s\n", "tgtChapName", op->tgtChapName);
+ printf("%24s = %s\n", "tgtChapSecret", op->tgtChapSecret);
+ printf("%24s = %d\n", "tgttgtChallengeLen", op->tgtChallengeLen);
+}
+
+void
+parseArgs(int nargs, char **args, isc_opt_t *op)
+{
+ char **ar;
+ char *p, *v;
+ textkey_t *tk;
+
+ for(ar = args; nargs > 0; nargs--, ar++) {
+ p = strchr(*ar, '=');
+ if(p == NULL)
+ continue;
+ *p = 0;
+ v = p + 1;
+ while(isspace(*--p))
+ *p = 0;
+ while(isspace(*v))
+ v++;
+ if((tk = keyLookup(*ar)) == NULL)
+ continue;
+ setOption(op, tk->tokenID, v);
+ }
+}
+
+void
+parseConfig(FILE *fd, char *key, isc_opt_t *op)
+{
+ char *Ar[256];
+ int cc;
+
+ cc = 256;
+ if(getConfig(fd, key, Ar, &cc))
+ parseArgs(cc, Ar, op);
+ if(vflag)
+ puke(op);
+}
diff --git a/sbin/iscontrol/fsm.c b/sbin/iscontrol/fsm.c
new file mode 100644
index 0000000..6a1c529
--- /dev/null
+++ b/sbin/iscontrol/fsm.c
@@ -0,0 +1,721 @@
+/*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ | $Id: fsm.c,v 2.8 2007/05/19 16:34:21 danny Exp danny $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#if __FreeBSD_version < 500000
+#include <sys/time.h>
+#endif
+#include <sys/ioctl.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <time.h>
+#include <syslog.h>
+#include <stdarg.h>
+#include <camlib.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+#include "pdu.h"
+
+typedef enum {
+ T1 = 1,
+ T2, /*T3,*/ T4, T5, /*T6,*/ T7, T8, T9,
+ T10, T11, T12, T13, T14, T15, T16, T18
+} trans_t;
+
+static trans_t
+tcpConnect(isess_t *sess)
+{
+ isc_opt_t *op = sess->op;
+ int val, sv_errno;
+ struct addrinfo *res, hints;
+ struct sockaddr_in sn;
+ struct in_addr ipn;
+ time_t sec;
+
+ debug_called(3);
+ if(sess->flags & (SESS_RECONNECT|SESS_REDIRECT)) {
+ syslog(LOG_INFO, "%s", (sess->flags & SESS_RECONNECT)
+ ? "Reconnect": "Redirected");
+
+ debug(3, "%s", (sess->flags & SESS_RECONNECT) ? "Reconnect": "Redirected");
+ shutdown(sess->soc, SHUT_RDWR);
+ //close(sess->soc);
+ sleep(5); // XXX: actually should be ?
+ sess->soc = -1;
+
+ sess->flags &= ~SESS_CONNECTED;
+ if(sess->flags & SESS_REDIRECT) {
+ if(sess->redirect_cnt++ > MAXREDIRECTS) {
+ syslog(LOG_WARNING, "too many redirects > %d", MAXREDIRECTS);
+ return 0;
+ }
+ sess->flags |= SESS_RECONNECT;
+ }
+ if((sess->flags & SESS_RECONNECT) == 0)
+ return 0;
+
+ // make sure we are not in a loop
+ // XXX: this code has to be tested
+ sec = time(0) - sess->reconnect_time;
+ if(sec > (5*60)) {
+ // if we've been connected for more that 5 minutes
+ // then just reconnect
+ sess->reconnect_time = sec;
+ sess->reconnect_cnt1 = 0;
+ }
+ else {
+ //
+ sess->reconnect_cnt1++;
+ if((sec / sess->reconnect_cnt1) < 2) {
+ // if less that 2 seconds from the last reconnect
+ // we are most probably looping
+ syslog(LOG_CRIT, "too many reconnects %d", sess->reconnect_cnt1);
+ return 0;
+ }
+ }
+ sess->reconnect_cnt++;
+ // sess->flags &= ~(SESS_RECONNECT|SESS_REDIRECT);
+ }
+
+ if((sess->soc = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
+ fprintf(stderr, "tcpConnect: socket: %m");
+ return 0;
+ }
+
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = PF_INET;
+ hints.ai_socktype = SOCK_STREAM;
+
+ debug(3, "targetAddress=%s port=%d", op->targetAddress, op->port);
+ if(inet_aton(op->targetAddress, &ipn))
+ hints.ai_flags |= AI_NUMERICHOST;
+ if((val = getaddrinfo(op->targetAddress, NULL, &hints, &res)) != 0) {
+ fprintf(stderr, "getaddrinfo(%s): %s\n", op->targetAddress, gai_strerror(val));
+ return 0;
+ }
+ memcpy(&sn, res->ai_addr, sizeof(struct sockaddr_in));
+ sn.sin_port = htons(op->port);
+ freeaddrinfo(res);
+
+ // from Patrick.Guelat@imp.ch:
+ // iscontrol can be called without waiting for the socket entry to time out
+ val = 1;
+ if(setsockopt(sess->soc, SOL_SOCKET, SO_REUSEADDR, &val, (socklen_t)sizeof(val)) < 0) {
+ fprintf(stderr, "Cannot set socket SO_REUSEADDR %d: %s\n\n",
+ errno, strerror(errno));
+ }
+
+ sess->flags &= ~SESS_CONNECTED;
+
+ if(connect(sess->soc, (struct sockaddr *)&sn, sizeof(struct sockaddr_in)) != -1) {
+#if 0
+ struct timeval timeout;
+
+ val = 1;
+ if(setsockopt(sess->soc, IPPROTO_TCP, TCP_KEEPALIVE, &val, sizeof(val)) < 0)
+ fprintf(stderr, "Cannot set socket KEEPALIVE option err=%d %s\n",
+ errno, strerror(errno));
+
+ if(setsockopt(sess->soc, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) < 0)
+ fprintf(stderr, "Cannot set socket NO delay option err=%d %s\n",
+ errno, strerror(errno));
+
+ timeout.tv_sec = 10;
+ timeout.tv_usec = 0;
+ if((setsockopt(sess->soc, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout)) < 0)
+ || (setsockopt(sess->soc, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0)) {
+ fprintf(stderr, "Cannot set socket timeout to %ld err=%d %s\n",
+ timeout.tv_sec, errno, strerror(errno));
+ }
+#endif
+#ifdef CURIOUS
+ {
+ int len = sizeof(val);
+ if(getsockopt(sess->soc, SOL_SOCKET, SO_SNDBUF, &val, &len) == 0)
+ fprintf(stderr, "was: SO_SNDBUF=%dK\n", val/1024);
+ }
+#endif
+ if(sess->op->sockbufsize) {
+ val = sess->op->sockbufsize * 1024;
+ if((setsockopt(sess->soc, SOL_SOCKET, SO_SNDBUF, &val, sizeof(val)) < 0)
+ || (setsockopt(sess->soc, SOL_SOCKET, SO_RCVBUF, &val, sizeof(val)) < 0)) {
+ fprintf(stderr, "Cannot set socket sndbuf & rcvbuf to %d err=%d %s\n",
+ val, errno, strerror(errno));
+ return 0;
+ }
+ }
+ sess->flags |= SESS_CONNECTED;
+ return T1;
+
+ }
+ sv_errno = errno;
+ fprintf(stderr, "errno=%d\n", sv_errno);
+ perror("connect");
+ switch(sv_errno) {
+ case ECONNREFUSED:
+ case ENETUNREACH:
+ case ETIMEDOUT:
+ sleep(5); // for now ...
+ return T1;
+ default:
+ return 0; // terminal error
+ }
+
+}
+
+int
+setOptions(isess_t *sess, int flag)
+{
+ isc_opt_t oop;
+ char *sep;
+
+ debug_called(3);
+
+ bzero(&oop, sizeof(isc_opt_t));
+
+ if((flag & SESS_FULLFEATURE) == 0) {
+ oop.initiatorName = sess->op->initiatorName;
+ oop.targetAddress = sess->op->targetAddress;
+ if(sess->op->targetName != 0)
+ oop.targetName = sess->op->targetName;
+
+ oop.maxRecvDataSegmentLength = sess->op->maxRecvDataSegmentLength;
+ oop.maxXmitDataSegmentLength = sess->op->maxXmitDataSegmentLength; // XXX:
+ oop.maxBurstLength = sess->op->maxBurstLength;
+ oop.maxluns = sess->op->maxluns;
+ }
+ else {
+ /*
+ | turn on digestion only after login
+ */
+ if(sess->op->headerDigest != NULL) {
+ sep = strchr(sess->op->headerDigest, ',');
+ if(sep == NULL)
+ oop.headerDigest = sess->op->headerDigest;
+ debug(1, "oop.headerDigest=%s", oop.headerDigest);
+ }
+ if(sess->op->dataDigest != NULL) {
+ sep = strchr(sess->op->dataDigest, ',');
+ if(sep == NULL)
+ oop.dataDigest = sess->op->dataDigest;
+ debug(1, "oop.dataDigest=%s", oop.dataDigest);
+ }
+ }
+
+ if(ioctl(sess->fd, ISCSISETOPT, &oop)) {
+ perror("ISCSISETOPT");
+ return -1;
+ }
+ return 0;
+}
+
+static trans_t
+startSession(isess_t *sess)
+{
+
+ int n, fd, nfd;
+ char *dev;
+
+ debug_called(3);
+
+ if((sess->flags & SESS_CONNECTED) == 0) {
+ return T2;
+ }
+ if(sess->fd == -1) {
+ fd = open(iscsidev, O_RDWR);
+ if(fd < 0) {
+ perror(iscsidev);
+ return 0;
+ }
+ {
+ // XXX: this has to go
+ size_t n;
+ n = sizeof(sess->isid);
+ if(sysctlbyname("net.iscsi.isid", (void *)sess->isid, (size_t *)&n, 0, 0) != 0)
+ perror("sysctlbyname");
+ }
+ if(ioctl(fd, ISCSISETSES, &n)) {
+ perror("ISCSISETSES");
+ return 0;
+ }
+ asprintf(&dev, "%s%d", iscsidev, n);
+ nfd = open(dev, O_RDWR);
+ if(nfd < 0) {
+ perror(dev);
+ free(dev);
+ return 0;
+ }
+ free(dev);
+ close(fd);
+ sess->fd = nfd;
+
+ if(setOptions(sess, 0) != 0)
+ return -1;
+ }
+
+ if(ioctl(sess->fd, ISCSISETSOC, &sess->soc)) {
+ perror("ISCSISETSOC");
+ return 0;
+ }
+
+ return T4;
+}
+
+isess_t *currsess;
+
+static void
+trap(int sig)
+{
+ syslog(LOG_NOTICE, "trapped signal %d", sig);
+ fprintf(stderr, "trapped signal %d\n", sig);
+
+ switch(sig) {
+ case SIGHUP:
+ currsess->flags |= SESS_DISCONNECT;
+ break;
+
+ case SIGUSR1:
+ currsess->flags |= SESS_RECONNECT;
+ break;
+
+ case SIGINT:
+ case SIGTERM:
+ default:
+ return; // ignore
+ }
+}
+
+static void
+doCAM(isess_t *sess)
+{
+ char pathstr[1024];
+ union ccb *ccb;
+ int i;
+
+ if(ioctl(sess->fd, ISCSIGETCAM, &sess->cam) != 0) {
+ syslog(LOG_WARNING, "ISCSIGETCAM failed: %d", errno);
+ return;
+ }
+ debug(2, "nluns=%d", sess->cam.target_nluns);
+ /*
+ | for now will do this for each lun ...
+ */
+ for(i = 0; i < sess->cam.target_nluns; i++) {
+ debug(2, "CAM path_id=%d target_id=%d target_lun=%d",
+ sess->cam.path_id, sess->cam.target_id, sess->cam.target_lun[i]);
+
+ sess->camdev = cam_open_btl(sess->cam.path_id, sess->cam.target_id,
+ sess->cam.target_lun[i], O_RDWR, NULL);
+ if(sess->camdev == NULL) {
+ syslog(LOG_WARNING, "%s", cam_errbuf);
+ debug(3, "%s", cam_errbuf);
+ continue;
+ }
+
+ cam_path_string(sess->camdev, pathstr, sizeof(pathstr));
+ debug(2, "pathstr=%s", pathstr);
+
+ ccb = cam_getccb(sess->camdev);
+ bzero(&(&ccb->ccb_h)[1], sizeof(struct ccb_relsim) - sizeof(struct ccb_hdr));
+ ccb->ccb_h.func_code = XPT_REL_SIMQ;
+ ccb->crs.release_flags = RELSIM_ADJUST_OPENINGS;
+ ccb->crs.openings = sess->op->tags;
+
+ if(cam_send_ccb(sess->camdev, ccb) < 0)
+ syslog(LOG_WARNING, "%s", cam_errbuf);
+ else
+ if((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
+ syslog(LOG_WARNING, "XPT_REL_SIMQ CCB failed");
+ // cam_error_print(sess->camdev, ccb, CAM_ESF_ALL, CAM_EPF_ALL, stderr);
+ }
+ else
+ syslog(LOG_INFO, "%s tagged openings now %d\n", pathstr, ccb->crs.openings);
+
+ cam_freeccb(ccb);
+ cam_close_device(sess->camdev);
+ }
+}
+
+static trans_t
+supervise(isess_t *sess)
+{
+ int sig, val;
+
+ debug_called(3);
+
+ if(strcmp(sess->op->sessionType, "Discovery") == 0) {
+ sess->flags |= SESS_DISCONNECT;
+ return T9;
+ }
+
+ if(vflag)
+ printf("ready to go scsi\n");
+
+ if(setOptions(sess, SESS_FULLFEATURE) != 0)
+ return 0; // failure
+
+ if((sess->flags & SESS_FULLFEATURE) == 0) {
+ if(daemon(0, 1) != 0) {
+ perror("daemon");
+ exit(1);
+ }
+
+ openlog("iscontrol", LOG_CONS|LOG_PERROR|LOG_PID|LOG_NDELAY, LOG_KERN);
+ syslog(LOG_INFO, "running");
+
+ currsess = sess;
+ if(ioctl(sess->fd, ISCSISTART)) {
+ perror("ISCSISTART");
+ return -1;
+ }
+ doCAM(sess);
+
+ }
+ else {
+
+ if(ioctl(sess->fd, ISCSIRESTART)) {
+ perror("ISCSIRESTART");
+ return -1;
+ }
+ }
+
+ signal(SIGINT, trap);
+ signal(SIGHUP, trap);
+ signal(SIGTERM, trap);
+
+ sig = SIGUSR1;
+ signal(sig, trap);
+ if(ioctl(sess->fd, ISCSISIGNAL, &sig)) {
+ perror("ISCSISIGNAL");
+ return -1;
+ }
+ sess->flags |= SESS_FULLFEATURE;
+
+ sess->flags &= ~(SESS_REDIRECT | SESS_RECONNECT);
+ printf("iscontrol: supervise starting main loop\n");
+ /*
+ | the main loop - actually do nothing
+ | all the work is done inside the kernel
+ */
+ while((sess->flags & (SESS_REDIRECT|SESS_RECONNECT|SESS_DISCONNECT)) == 0) {
+ // do something?
+ // like sending a nop_out?
+ sleep(60);
+ }
+ printf("iscontrol: supervise going down\n");
+ syslog(LOG_INFO, "sess flags=%x", sess->flags);
+
+ sig = 0;
+ if(ioctl(sess->fd, ISCSISIGNAL, &sig)) {
+ perror("ISCSISIGNAL");
+ }
+
+ if(sess->flags & SESS_DISCONNECT) {
+ val = 0;
+ if(ioctl(sess->fd, ISCSISTOP, &val)) {
+ perror("ISCSISTOP");
+ }
+ sess->flags &= ~SESS_FULLFEATURE;
+ return T9;
+ }
+ else {
+ sess->flags |= SESS_INITIALLOGIN1;
+ }
+ return T8;
+}
+
+static int
+handledDiscoveryResp(isess_t *sess, pdu_t *pp)
+{
+ u_char *ptr;
+ int len, n;
+
+ debug_called(3);
+
+ len = pp->ds_len;
+ ptr = pp->ds;
+ while(len > 0) {
+ if(*ptr != 0)
+ printf("%s\n", ptr);
+ n = strlen((char *)ptr) + 1;
+ len -= n;
+ ptr += n;
+ }
+ return 0;
+}
+
+static int
+doDiscovery(isess_t *sess)
+{
+ pdu_t spp;
+ text_req_t *tp = (text_req_t *)&spp.ipdu.bhs;
+
+ debug_called(3);
+
+ bzero(&spp, sizeof(pdu_t));
+ tp->cmd = ISCSI_TEXT_CMD /*| 0x40 */; // because of a bug in openiscsi-target
+ tp->F = 1;
+ tp->ttt = 0xffffffff;
+ addText(&spp, "SendTargets=All");
+ return sendPDU(sess, &spp, handledDiscoveryResp);
+}
+
+static trans_t
+doLogin(isess_t *sess)
+{
+ isc_opt_t *op = sess->op;
+ int status, count;
+
+ debug_called(3);
+
+ if(op->chapSecret == NULL && op->tgtChapSecret == NULL)
+ /*
+ | don't need any security negotiation
+ | or in other words: we don't have any secrets to exchange
+ */
+ sess->csg = LON_PHASE;
+ else
+ sess->csg = SN_PHASE;
+
+ if(sess->tsih) {
+ sess->tsih = 0; // XXX: no 'reconnect' yet
+ sess->flags &= ~SESS_NEGODONE; // XXX: KLUDGE
+ }
+ count = 10; // should be more than enough
+ do {
+ debug(3, "count=%d csg=%d", count, sess->csg);
+ status = loginPhase(sess);
+ if(count-- == 0)
+ // just in case we get into a loop
+ status = -1;
+ } while(status == 0 && (sess->csg != FF_PHASE));
+
+ sess->flags &= ~SESS_INITIALLOGIN;
+ debug(3, "status=%d", status);
+
+ switch(status) {
+ case 0: // all is ok ...
+ sess->flags |= SESS_LOGGEDIN;
+ if(strcmp(sess->op->sessionType, "Discovery") == 0)
+ doDiscovery(sess);
+ return T5;
+
+ case 1: // redirect - temporary/permanent
+ /*
+ | start from scratch?
+ */
+ sess->flags &= ~SESS_NEGODONE;
+ sess->flags |= (SESS_REDIRECT | SESS_INITIALLOGIN1);
+ syslog(LOG_DEBUG, "target sent REDIRECT");
+ return T7;
+
+ case 2: // initiator terminal error
+ case 3: // target terminal error -- could retry ...
+ default:
+ return 0;
+ }
+}
+
+static int
+handleLogoutResp(isess_t *sess, pdu_t *pp)
+{
+ if(sess->flags & SESS_DISCONNECT)
+ return 0;
+ return T13;
+}
+
+static trans_t
+startLogout(isess_t *sess)
+{
+ pdu_t spp;
+ logout_req_t *p = (logout_req_t *)&spp.ipdu.bhs;
+
+ bzero(&spp, sizeof(pdu_t));
+ p->cmd = ISCSI_LOGOUT_CMD| 0x40;
+ p->reason = BIT(7) | 0;
+ p->CID = htons(1);
+
+ return sendPDU(sess, &spp, handleLogoutResp);
+}
+
+static trans_t
+inLogout(isess_t *sess)
+{
+ if(sess->flags & SESS_RECONNECT)
+ return T18;
+ return 0;
+}
+
+typedef enum {
+ S1, S2, /*S3,*/ S4, S5, S6, S7, S8
+} state_t;
+
+#if 0
+ S1: FREE
+ S2: XPT_WAIT
+ S4: IN_LOGIN
+ S5: LOGGED_IN
+ S6: IN_LOGOUT
+ S7: LOGOUT_REQUESTED
+ S8: CLEANUP_WAIT
+
+ -------<-------------+
+ +--------->/ S1 \<----+ |
+ T13| +->\ /<-+ \ |
+ | / ---+--- \ \ |
+ | / | T2 \ | |
+ | T8 | |T1 | | |
+ | | | / |T7 |
+ | | | / | |
+ | | | / | |
+ | | V / / |
+ | | ------- / / |
+ | | / S2 \ / |
+ | | \ / / |
+ | | ---+--- / |
+ | | |T4 / |
+ | | V / | T18
+ | | ------- / |
+ | | / S4 \ |
+ | | \ / |
+ | | ---+--- | T15
+ | | |T5 +--------+---------+
+ | | | /T16+-----+------+ |
+ | | | / -+-----+--+ | |
+ | | | / / S7 \ |T12| |
+ | | | / +->\ /<-+ V V
+ | | | / / -+----- -------
+ | | | / /T11 |T10 / S8 \
+ | | V / / V +----+ \ /
+ | | ---+-+- ----+-- | -------
+ | | / S5 \T9 / S6 \<+ ^
+ | +-----\ /--->\ / T14 |
+ | ------- --+----+------+T17
+ +---------------------------+
+#endif
+
+int
+fsm(isc_opt_t *op)
+{
+ state_t state;
+ isess_t *sess;
+
+ if((sess = calloc(1, sizeof(isess_t))) == NULL) {
+ // boy, is this a bad start ...
+ fprintf(stderr, "no memory!\n");
+ return -1;
+ }
+
+ state = S1;
+ sess->op = op;
+ sess->fd = -1;
+ sess->soc = -1;
+
+ sess->flags = SESS_INITIALLOGIN | SESS_INITIALLOGIN1;
+
+ do {
+ switch(state) {
+
+ case S1:
+ switch(tcpConnect(sess)) {
+ case T1: state = S2; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S2:
+ switch(startSession(sess)) {
+ case T2: state = S1; break;
+ case T4: state = S4; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S4:
+ switch(doLogin(sess)) {
+ case T7: state = S1; break;
+ case T5: state = S5; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S5:
+ switch(supervise(sess)) {
+ case T8: state = S1; break;
+ case T9: state = S6; break;
+ case T11: state = S7; break;
+ case T15: state = S8; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S6:
+ switch(startLogout(sess)) {
+ case T13: state = S1; break;
+ case T14: state = S6; break;
+ case T16: state = S8; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S7:
+ switch(inLogout(sess)) {
+ case T18: state = S1; break;
+ case T10: state = S6; break;
+ case T12: state = S7; break;
+ case T16: state = S8; break;
+ default: state = S8; break;
+ }
+ break;
+
+ case S8:
+ // maybe do some clean up?
+ syslog(LOG_INFO, "terminated");
+ return 0;
+ }
+ } while(1);
+}
diff --git a/sbin/iscontrol/iscontrol.8 b/sbin/iscontrol/iscontrol.8
new file mode 100644
index 0000000..f9a3dd1
--- /dev/null
+++ b/sbin/iscontrol/iscontrol.8
@@ -0,0 +1,116 @@
+.\" Copyright (c) 2007 Daniel Braniss <danny@cs.huji.ac.il>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd February 22, 2007
+.Dt ISCONTROL 8
+.Os
+.Sh NAME
+.Nm iscontrol
+.Nd login/negotiator/control for an iSCSI initiator session
+.Sh SYNOPSIS
+.Nm
+.Op Fl vd
+.Oo
+.Op Fl Ar file
+.Op Fl n Ar nickname
+.Oc
+.Op Fl t Ar target
+.Op Ar variable Ns = Ns Ar value
+.Sh DESCRIPTION
+Internet SCSI (iSCSI) is a network protocol standard, that allows the
+use of the SCSI protocol over TCP/IP networks,
+the
+.Nm
+program is the userland side of an iSCSI session, see
+iscsi_initiator(4).
+It has 2 modes of operation, if -d (discovery session) is specified,
+it will print out the
+.Em target names
+returned by the target and exit.
+In the second mode, it will, after a succesful login/negotiation, run
+in daemon mode, monitoring the connection, and will try to reconnect
+in case of a network/target failure. It will terminate/logout the session
+when a SIGHUP signal is received.
+The flags are as follows:
+.Bl -tag -width variable=value
+.It Fl v
+verbose mode.
+.It Fl d
+do a
+.Em discovery session
+and exit.
+.It Fl c Ar file
+a file containing configuration
+.Em key-options ,
+see iscsi.conf(5)
+.It Fl n Ar nickname
+if
+.Sy -c file
+is specified, then search for the block named
+.Em nickname
+in that file, see iscsi.conf(5)
+.It Fl t Ar target
+is the target's IP address or name
+.It Ar variable Ns = Ns Ar value
+see iscsi.conf(5) for the complete list of variables/options and their
+possible values.
+.El
+.Sh EXAMPLES
+.Dl iscontrol -dt myiscsitarget
+.Pp
+will start a
+.Em discovery session
+with the target and
+print to stdout the list of available targetnames/targetadresses.
+Note: this listing does not necessarily mean availability, since
+depending on the target configuration, a discovery session might
+not need login/access permition, but a
+.Em full session
+certainly does.
+.sp
+.Dl iscontrol -c /etc/iscsi.conf -n myiscsi
+.Pp
+will read options from file /etc/iscsi.conf, use the targetaddress
+found in the block nicknamed myiscsi, login and negotiate
+whatever options are specified, and start an iscsi-session.
+.Sh SEE ALSO
+.Xr iscsi_initiator 4 ,
+.Xr iscsi.conf 5 ,
+.Xr camcontrol 8 ,
+.Xr da 4 ,
+.Xr sa 4
+.Sh STANDARDS
+RFC 3720
+.\"Sh HISTORY
+.Sh BUGS
+.Nm
+should probably load the iscsi_initiator module if needed.
+.br
+Not all functions/specifications have been implemented yet, noticeably
+missing are the Task Management Funtions.
+The error recovery, though not
+.Em fully compliant
+does a brave effort to recover from network disconnects.
diff --git a/sbin/iscontrol/iscontrol.c b/sbin/iscontrol/iscontrol.c
new file mode 100644
index 0000000..d5d5929
--- /dev/null
+++ b/sbin/iscontrol/iscontrol.c
@@ -0,0 +1,227 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+/*
+ | $Id: iscontrol.c,v 2.2 2006/12/01 09:11:56 danny Exp danny $
+ */
+/*
+ | the user level initiator (client)
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#include <sys/ioctl.h>
+#include <netdb.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdio.h>
+#include <string.h>
+#include <errno.h>
+#include <fcntl.h>
+#include <time.h>
+#include <camlib.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+//#include "pdu.h"
+
+#define USAGE "[-v] [-d] [-c config] [-n name] [-t target] "
+#define OPTIONS "vdc:t:n:"
+
+#ifndef DEBUG
+//int vflag;
+#endif
+
+token_t AuthMethods[] = {
+ {"None", NONE},
+ {"KRB5", KRB5},
+ {"SPKM1", SPKM1},
+ {"SPKM2", SPKM2},
+ {"SRP", SRP},
+ {"CHAP", CHAP},
+ {0}
+};
+
+token_t DigestMethods[] = {
+ {"None", 0},
+ {"CRC32", 1},
+ {"CRC32C", 1},
+ {0}
+};
+
+u_char isid[6 + 6];
+/*
+ | Default values
+ */
+isc_opt_t opvals = {
+ .port = 3260,
+ .sockbufsize = 128,
+ .iqn = "iqn.2005-01.il.ac.huji.cs:",
+
+ .sessionType = "Normal",
+ .targetAddress = 0,
+ .targetName = 0,
+ .initiatorName = 0,
+ .authMethod = "None",
+ .headerDigest = "None,CRC32C",
+ .dataDigest = "None,CRC32C",
+ .maxConnections = 1,
+ .maxRecvDataSegmentLength = 64 * 1024,
+ .maxXmitDataSegmentLength = 8 * 1024, // 64 * 1024,
+ .maxBurstLength = 128 * 1024,
+ .firstBurstLength = 64 * 1024, // must be less than maxBurstLength
+ .defaultTime2Wait = 0,
+ .defaultTime2Retain = 0,
+ .maxOutstandingR2T = 1,
+ .errorRecoveryLevel = 0,
+
+ .dataPDUInOrder = TRUE,
+ .dataSequenceInOrder = TRUE,
+
+ .initialR2T = TRUE,
+ .immediateData = TRUE,
+};
+
+int
+lookup(token_t *tbl, char *m)
+{
+ token_t *tp;
+
+ for(tp = tbl; tp->name != NULL; tp++)
+ if(strcasecmp(tp->name, m) == 0)
+ return tp->val;
+ return 0;
+}
+
+int
+main(int cc, char **vv)
+{
+ int ch, disco;
+ char *pname, *p, *ta, *kw;
+ isc_opt_t *op;
+ FILE *fd;
+
+ op = &opvals;
+ iscsidev = "/dev/"ISCSIDEV;
+ fd = NULL;
+ pname = vv[0];
+ if((p = strrchr(pname, '/')) != NULL)
+ pname = p + 1;
+
+ kw = ta = 0;
+ disco = 0;
+
+ while((ch = getopt(cc, vv, OPTIONS)) != -1) {
+ switch(ch) {
+ case 'v':
+ vflag++;
+ break;
+ case 'c':
+ fd = fopen(optarg, "r");
+ if(fd == NULL) {
+ perror(optarg);
+ exit(1);
+ }
+ break;
+ case 'd':
+ disco = 1;
+ break;
+ case 't':
+ ta = optarg;
+ break;
+ case 'n':
+ kw = optarg;
+ break;
+ default:
+ badu:
+ fprintf(stderr, "Usage: %s %s\n", pname, USAGE);
+ exit(1);
+ }
+ }
+ if(fd == NULL)
+ fd = fopen("/etc/iscsi.conf", "r");
+
+ if(fd != NULL) {
+ parseConfig(fd, kw, op);
+ fclose(fd);
+ }
+ cc -= optind;
+ vv += optind;
+ if(cc > 0) {
+ if(vflag)
+ printf("adding '%s'\n", *vv);
+ parseArgs(cc, vv, op);
+ }
+ if(ta)
+ op->targetAddress = ta;
+
+ if(op->targetAddress == NULL) {
+ fprintf(stderr, "No target!\n");
+ goto badu;
+ }
+ if((p = strchr(op->targetAddress, ':')) != NULL) {
+ *p++ = 0;
+ op->port = atoi(p);
+ p = strchr(p, ',');
+ }
+ if(p || ((p = strchr(op->targetAddress, ',')) != NULL)) {
+ *p++ = 0;
+ op->targetPortalGroupTag = atoi(p);
+ }
+ if(op->initiatorName == 0) {
+ char hostname[256];
+
+ if(op->iqn) {
+ if(gethostname(hostname, sizeof(hostname)) == 0)
+ asprintf(&op->initiatorName, "%s:%s", op->iqn, hostname);
+ else
+ asprintf(&op->initiatorName, "%s:%d", op->iqn, (int)time(0) & 0xff); // XXX:
+ }
+ else {
+ if(gethostname(hostname, sizeof(hostname)) == 0)
+ asprintf(&op->initiatorName, "%s", hostname);
+ else
+ asprintf(&op->initiatorName, "%d", (int)time(0) & 0xff); // XXX:
+ }
+ }
+ if(disco) {
+ op->sessionType = "Discovery";
+ op->targetName = 0;
+ }
+
+ fsm(op);
+
+ exit(0);
+}
diff --git a/sbin/iscontrol/iscontrol.h b/sbin/iscontrol/iscontrol.h
new file mode 100644
index 0000000..c93c35a
--- /dev/null
+++ b/sbin/iscontrol/iscontrol.h
@@ -0,0 +1,159 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD$
+ */
+/*
+ | $Id: iscontrol.h,v 2.3 2007/04/27 08:36:49 danny Exp danny $
+ */
+#ifdef DEBUG
+int vflag;
+
+# define debug(level, fmt, args...) do {if (level <= vflag) printf("%s: " fmt "\n", __func__ , ##args);} while(0)
+# define debug_called(level) do {if (level <= vflag) printf("%s: called\n", __func__);} while(0)
+#else
+# define debug(level, fmt, args...)
+# define debug_called(level)
+#endif // DEBUG
+#define xdebug(fmt, args...) printf("%s: " fmt "\n", __func__ , ##args)
+
+#define BIT(n) (1 <<(n))
+
+#define MAXREDIRECTS 2
+
+typedef int auth_t(void *sess);
+
+typedef struct isess {
+ int flags;
+#define SESS_CONNECTED BIT(0)
+#define SESS_DISCONNECT BIT(1)
+#define SESS_LOGGEDIN BIT(2)
+#define SESS_RECONNECT BIT(3)
+#define SESS_REDIRECT BIT(4)
+
+#define SESS_NEGODONE BIT(10) // XXX: kludge
+
+#define SESS_FULLFEATURE BIT(29)
+#define SESS_INITIALLOGIN1 BIT(30)
+#define SESS_INITIALLOGIN BIT(31)
+
+
+ isc_opt_t *op; // operational values
+ int fd; // the session fd
+ int soc; // the socket
+ iscsi_cam_t cam;
+ struct cam_device *camdev;
+
+ time_t open_time;
+ int redirect_cnt;
+ time_t redirect_time;
+ int reconnect_cnt;
+ int reconnect_cnt1;
+ time_t reconnect_time;
+ char isid[6+1];
+ int csg; // current stage
+ int nsg; // next stage
+ // Phases/Stages
+#define SN_PHASE 0 // Security Negotiation
+#define LON_PHASE 1 // Login Operational Negotiation
+#define FF_PHASE 3 // FuLL-Feature
+ uint tsih;
+ sn_t sn;
+} isess_t;
+
+typedef struct token {
+ char *name;
+ int val;
+} token_t;
+
+typedef enum {
+ NONE = 0,
+ KRB5,
+ SPKM1,
+ SPKM2,
+ SRP,
+ CHAP
+} authm_t;
+
+extern token_t AuthMethods[];
+extern token_t DigestMethods[];
+
+typedef enum {
+ SET,
+ GET
+} oper_t;
+
+typedef enum {
+ U_PR, // private
+ U_IO, // Initialize Only -- during login
+ U_LO, // Leading Only -- when TSIH is zero
+ U_FFPO, // Full Feature Phase Only
+ U_ALL // in any phase
+} usage_t;
+
+typedef enum {
+ S_PR,
+ S_CO, // Connect only
+ S_SW // Session Wide
+} scope_t;
+
+typedef void keyfun_t(isess_t *, oper_t);
+
+typedef struct {
+ usage_t usage;
+ scope_t scope;
+ char *name;
+ int tokenID;
+} textkey_t;
+
+typedef int handler_t(isess_t *sess, pdu_t *pp);
+
+int authenticateLogin(isess_t *sess);
+int fsm(isc_opt_t *op);
+int sendPDU(isess_t *sess, pdu_t *pp, handler_t *hdlr);
+int addText(pdu_t *pp, char *fmt, ...);
+void freePDU(pdu_t *pp);
+int xmitpdu(isess_t *sess, pdu_t *pp);
+int recvpdu(isess_t *sess, pdu_t *pp);
+void pukeText(char *it, pdu_t *pp);
+
+int lookup(token_t *tbl, char *m);
+
+int vflag;
+char *iscsidev;
+
+void parseArgs(int nargs, char **args, isc_opt_t *op);
+void parseConfig(FILE *fd, char *key, isc_opt_t *op);
+
+char *chapDigest(char *ap, char id, char *cp, char *chapSecret);
+char *genChapChallenge(char *encoding, int len);
+
+int str2bin(char *str, char **rsp);
+char *bin2str(char *fmt, unsigned char *md, int blen);
+
+int negotiateOPV(isess_t *sess);
+int setOptions(isess_t *sess, int flag);
+
+int loginPhase(isess_t *sess);
diff --git a/sbin/iscontrol/iscsi.conf.5 b/sbin/iscontrol/iscsi.conf.5
new file mode 100644
index 0000000..a8d558a
--- /dev/null
+++ b/sbin/iscontrol/iscsi.conf.5
@@ -0,0 +1,204 @@
+.\" Copyright (c) 2007 Daniel Braniss <danny@cs.huji.ac.il>
+.\" All rights reserved.
+.\"
+.\" Redistribution and use in source and binary forms, with or without
+.\" modification, are permitted provided that the following conditions
+.\" are met:
+.\" 1. Redistributions of source code must retain the above copyright
+.\" notice, this list of conditions and the following disclaimer.
+.\" 2. Redistributions in binary form must reproduce the above copyright
+.\" notice, this list of conditions and the following disclaimer in the
+.\" documentation and/or other materials provided with the distribution.
+.\"
+.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+.\" SUCH DAMAGE.
+.\"
+.\" $FreeBSD$
+.\"
+.Dd June 5, 2007
+.Os
+.Dt ISCSI.CONF 5
+.Sh NAME
+.Nm iscsi.conf
+.Nd key options to be negotiated in an iSCSI session
+.Sh DESCRIPTION
+The file
+.Nm ,
+is read by the
+.Xr iscontrol 8
+program, it contains declarations and parameter/key-options.
+The syntax is very simple,
+.D1 Li variable = value;
+and they can be grouped via a
+.Em block
+declaration:
+.Bf Li
+.Bd -literal
+ # this is a comment
+ target_1 { # nickname
+ variable = value;
+ ...
+ } # this must be on a line by itself.
+.Ed
+.Ef
+.Pp
+The following are specified in the iSCSI RFC 3720,
+for a full description see sections 11/12 of the RFC.
+.Bl -tag -width MaxConnections
+.It Cm AuthMethod
+current only supported authentication method is CHAP, with
+digest either MD5 or SHA. Default is none.
+.It Cm HeaderDigest
+a
+.Em digest
+is calculated on the header of all iSCSI PDUs, and
+checked. Only CRC32C is implemented. Default is none.
+.It Cm DataDigest
+same as for HeaderDigest, but on the data part of the iSCSI PDU.
+.It Cm MaxConnections
+is the number of simultaneous connections per session,
+currently only 1.
+.It Cm TargetName
+is the name by which the target is known, not to be confused with
+target address, either obtained via the target administrator, or
+from a
+.Em discovery session.
+.It Cm InitiatorName
+if not specified, defaults to
+.Sy iqn.2005-01.il.ac.huji.cs:
+.Aq hostname .
+.It Cm TargetAlias / InitiatorAlias
+not implemented.
+.It Cm TargetAddress
+is of the form
+.Sy domainname[:port][,portal-group-tag]
+to quote the RFC:
+.Bd -ragged -compact
+The domainname can be specified as either a DNS host name, a
+dotted-decimal IPv4 address, or a bracketed IPv6 address as specified
+in [RFC2732].
+.Ed
+Note: portal-group-tag is unused at the moment.
+.It Cm TargetPortalGroupTag
+.Em not implemented yet.
+.It Cm InitialR2T
+.Em not implemented yet.
+.It Cm ImmediateData
+.Em not implemented yet.
+.It Cm MaxRecvDataSegmentLength
+the maximum data segment length in
+bytes it can receive in an iSCSI PDU, default is 8192.
+.It Cm MaxBurstLength
+.Em not implemented yet.
+.It Cm FirstBurstLength
+.Em not implemented yet.
+.It Cm DefaultTime2Wait
+.Em not implemented yet.
+.It Cm DefaultTime2Retain
+.Em not implemented yet.
+.It Cm MaxOutstandingR2T
+is used to calculate/negotiate the
+.Em tag opening ,
+can be overriden by the
+.Sy tag
+option.
+.It Cm DataPDUInOrder
+.Em not implemented yet.
+.It Cm DataSequenceInOrder
+.Em not implemented yet.
+.It Cm ErrorRecoveryLevel
+Only level 0 is supported.
+.It Cm SessionType
+either Discovery or Normal, default is Normal, see the
+.Fl d
+flag of
+.Cm iscontrol .
+.El
+.sp
+The following are not specified in the
+.Sy RFC 3720
+.Bl -tag -width sockbufsize
+.It Cm port
+The iscsi port used by the iscsi protocol, defaults to 3260.
+.It Cm tags
+Sets the
+.Em tag opening
+to the value specified.
+.It Cm maxluns
+overrides the compiled value of
+.Sy luns ,
+see
+.Xr iscsi_initiator 4 . This value can only be reduced.
+.It Cm sockbufsize
+sets the receiver and transmitter socket buffer size to
+.Em size,
+in kilobites. The default is 128.
+.El
+.sp
+If
+.Em AutheMethod
+is set to
+.Cm CHAP ,
+then the following must also be set:
+.Bl -tag -width chapSecret
+.It Cm chapSecret
+this
+.Em shared-secret.
+Can be either an ascci string (e.g. hello world), a hex string (e.g
+0xababcd0987654321...), or base64 string (eg 0b...)
+.It Cm chapIName
+the chap-name, defaults to
+.Em hostname .
+.It Cm chapDigest
+can be MD5 or SHA1.
+.It Cm tgtChapSecret/tgtChapName
+same as the none
+.Em tgt
+counterpart, but to authenticate the target.
+.El
+.Sh FILES
+.Pa /etc/iscsi.conf
+.Sh EXAMPLES
+.Bd -literal
+#
+# Globals
+#
+port = 3260
+#
+myiscsi { # nickname
+ targetaddress = iscsi1
+ targetname = iqn.1900.com.com:sn.123456
+}
+chaptest {
+ targetaddress= 10.0.0.1;
+ targetname = iqn.1900.com.com:sn.123456
+ initiatorname= iqn.2005-01.il.ac.huji.cs:nobody
+ authmethod = CHAP; chapDigest = SHA1;
+ chapsecret = 0x3713c3336d9a224c2791c873d3d2b174
+ tags = 256
+}
+.Ed
+.Sh ERRORS
+The parsing is very primitive, so don't expect - at the moment - any
+error messages.
+.Sh SEE ALSO
+.Xr iscsi_initiator 4 ,
+.Xr iscontrol 8
+.Sh STANDARDS
+ISCSI RFC 3720
+.\"Sh HISTORY
+.\"Sh AUTHORS
+.Sh BUGS
+Some options have not been implemented, either they were found
+to be unecessary, or not understood, this can change in the future.
+.br
+The tags opening value is difficult to calculate, use wisely.
diff --git a/sbin/iscontrol/login.c b/sbin/iscontrol/login.c
new file mode 100644
index 0000000..44ea889
--- /dev/null
+++ b/sbin/iscontrol/login.c
@@ -0,0 +1,440 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+/*
+ | $Id: login.c,v 1.4 2007/04/27 07:40:40 danny Exp danny $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#if __FreeBSD_version < 500000
+#include <sys/time.h>
+#endif
+#include <sys/ioctl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+#include "pdu.h"
+
+static char *status_class1[] = {
+ "Initiator error",
+ "Authentication failure",
+ "Authorization failure",
+ "Not found",
+ "Target removed",
+ "Unsupported version",
+ "Too many connections",
+ "Missing parameter",
+ "Can't include in session",
+ "Session type not suported",
+ "Session does not exist",
+ "Invalid during login",
+};
+#define CLASS1_ERRS ((sizeof status_class1) / sizeof(char *))
+
+static char *status_class3[] = {
+ "Target error",
+ "Service unavailable",
+ "Out of resources"
+};
+#define CLASS3_ERRS ((sizeof status_class3) / sizeof(char *))
+
+static char *
+selectFrom(char *str, token_t *list)
+{
+ char *sep, *sp;
+ token_t *lp;
+ int n;
+
+ sp = str;
+ do {
+ sep = strchr(sp, ',');
+ if(sep != NULL)
+ n = sep - sp;
+ else
+ n = strlen(sp);
+
+ for(lp = list; lp->name != NULL; lp++) {
+ if(strncasecmp(lp->name, sp, n) == 0)
+ return strdup(lp->name);
+ }
+ sp = sep + 1;
+ } while(sep != NULL);
+
+ return NULL;
+}
+
+static char *
+getkeyval(char *key, pdu_t *pp)
+{
+ char *ptr;
+ int klen, len, n;
+
+ debug_called(3);
+
+ len = pp->ds_len;
+ ptr = (char *)pp->ds;
+ klen = strlen(key);
+ while(len > klen) {
+ if(strncmp(key, ptr, klen) == 0)
+ return ptr+klen;
+ n = strlen(ptr) + 1;
+ len -= n;
+ ptr += n;
+ }
+ return 0;
+}
+
+static int
+handleTgtResp(isess_t *sess, pdu_t *pp)
+{
+ isc_opt_t *op = sess->op;
+ char *np, *rp, *d1, *d2;
+ int res, l1, l2;
+
+ res = -1;
+ if(((np = getkeyval("CHAP_N=", pp)) == NULL) ||
+ ((rp = getkeyval("CHAP_R=", pp)) == NULL))
+ goto out;
+ if(strcmp(np, op->tgtChapName? op->tgtChapName: op->initiatorName) != 0) {
+ fprintf(stderr, "%s does not match\n", np);
+ goto out;
+ }
+ l1 = str2bin(op->tgtChapDigest, &d1);
+ l2 = str2bin(rp, &d2);
+
+ debug(3, "l1=%d '%s' l2=%d '%s'", l1, op->tgtChapDigest, l2, rp);
+ if(l1 == l2 && memcmp(d1, d2, l1) == 0)
+ res = 0;
+ if(l1)
+ free(d1);
+ if(l2)
+ free(d2);
+ out:
+ free(op->tgtChapDigest);
+ op->tgtChapDigest = NULL;
+
+ debug(3, "res=%d", res);
+
+ return res;
+}
+
+static void
+processParams(isess_t *sess, pdu_t *pp)
+{
+ isc_opt_t *op = sess->op;
+ int len, klen, n;
+ char *eq, *ptr;
+
+ debug_called(3);
+
+ len = pp->ds_len;
+ ptr = (char *)pp->ds;
+ while(len > 0) {
+ if(vflag > 1)
+ printf("got: len=%d %s\n", len, ptr);
+ klen = 0;
+ if((eq = strchr(ptr, '=')) != NULL)
+ klen = eq - ptr;
+ if(klen > 0) {
+ if(strncmp(ptr, "TargetAddress", klen) == 0) {
+ char *p, *q;
+
+ // TargetAddress=domainname[:port][,portal-group-tag]
+ // XXX: if(op->targetAddress) free(op->targetAddress);
+ q = op->targetAddress = strdup(eq+1);
+ if(*q == '[') {
+ // bracketed IPv6
+ if((q = strchr(q, ']')) != NULL)
+ q++;
+ else
+ q = op->targetAddress;
+ }
+ if((p = strchr(q, ',')) != NULL) {
+ *p++ = 0;
+ op->targetPortalGroupTag = atoi(p);
+ }
+ if((p = strchr(q, ':')) != NULL) {
+ *p++ = 0;
+ op->port = atoi(p);
+ }
+ } else if(strncmp(ptr, "MaxRecvDataSegmentLength", klen) == 0) {
+ // danny's RFC
+ op->maxXmitDataSegmentLength = strtol(eq+1, (char **)NULL, 0);
+ } else if(strncmp(ptr, "TargetPortalGroupTag", klen) == 0) {
+ op->targetPortalGroupTag = strtol(eq+1, (char **)NULL, 0);
+ } else if(strncmp(ptr, "HeaderDigest", klen) == 0) {
+ op->headerDigest = selectFrom(eq+1, DigestMethods);
+ } else if(strncmp(ptr, "DataDigest", klen) == 0) {
+ op->dataDigest = selectFrom(eq+1, DigestMethods);
+ } else if(strncmp(ptr, "MaxOutstandingR2T", klen) == 0)
+ op->maxOutstandingR2T = strtol(eq+1, (char **)NULL, 0);
+#if 0
+ else
+ for(kp = keyMap; kp->name; kp++) {
+ if(strncmp(ptr, kp->name, kp->len) == 0 && ptr[kp->len] == '=')
+ mp->func(sess, ptr+kp->len+1, GET);
+ }
+#endif
+ }
+ n = strlen(ptr) + 1;
+ len -= n;
+ ptr += n;
+ }
+
+}
+
+static int
+handleLoginResp(isess_t *sess, pdu_t *pp)
+{
+ login_rsp_t *lp = (login_rsp_t *)pp;
+ uint st_class, status = ntohs(lp->status);
+
+ debug_called(3);
+ debug(4, "Tbit=%d csg=%d nsg=%d status=%x", lp->T, lp->CSG, lp->NSG, status);
+
+ st_class = status >> 8;
+ if(status) {
+ int st_detail = status & 0xff;
+
+ switch(st_class) {
+ case 1: // Redirect
+ switch(st_detail) {
+ // the ITN (iSCSI target Name) requests a:
+ case 1: // temporary address change
+ case 2: // permanent address change
+ status = 0;
+ }
+ break;
+
+ case 2: // Initiator Error
+ if(st_detail < CLASS1_ERRS)
+ printf("0x%04x: %s\n", status, status_class1[st_detail]);
+ break;
+
+ case 3:
+ if(st_detail < CLASS3_ERRS)
+ printf("0x%04x: %s\n", status, status_class3[st_detail]);
+ break;
+ }
+ }
+
+ if(status == 0) {
+ processParams(sess, pp);
+ setOptions(sess, 0); // XXX: just in case ...
+
+ if(lp->T) {
+ isc_opt_t *op = sess->op;
+
+ if(sess->csg == SN_PHASE && (op->tgtChapDigest != NULL))
+ if(handleTgtResp(sess, pp) != 0)
+ return 1; // XXX: Authentication failure ...
+ sess->csg = lp->NSG;
+ if(sess->csg == FF_PHASE) {
+ // XXX: will need this when implementing reconnect.
+ sess->tsih = lp->tsih;
+ debug(2, "TSIH=%x", sess->tsih);
+ }
+ }
+ }
+
+ return st_class;
+}
+
+static int
+handleChap(isess_t *sess, pdu_t *pp)
+{
+ pdu_t spp;
+ login_req_t *lp;
+ isc_opt_t *op = sess->op;
+ char *ap, *ip, *cp, *digest; // MD5 is 128bits, SHA1 160bits
+
+ debug_called(3);
+
+ bzero(&spp, sizeof(pdu_t));
+ lp = (login_req_t *)&spp.ipdu.bhs;
+ lp->cmd = ISCSI_LOGIN_CMD | 0x40; // login request + Inmediate
+ memcpy(lp->isid, sess->isid, 6);
+ lp->tsih = sess->tsih; // MUST be zero the first time!
+ lp->CID = htons(1);
+ lp->CSG = SN_PHASE; // Security Negotiation
+ lp->NSG = LON_PHASE;
+ lp->T = 1;
+
+ if(((ap = getkeyval("CHAP_A=", pp)) == NULL) ||
+ ((ip = getkeyval("CHAP_I=", pp)) == NULL) ||
+ ((cp = getkeyval("CHAP_C=", pp)) == NULL))
+ return -1;
+
+ if((digest = chapDigest(ap, (char)strtol(ip, (char **)NULL, 0), cp, op->chapSecret)) == NULL)
+ return -1;
+
+ addText(&spp, "CHAP_N=%s", op->chapIName? op->chapIName: op->initiatorName);
+ addText(&spp, "CHAP_R=%s", digest);
+ free(digest);
+
+ if(op->tgtChapSecret != NULL) {
+ op->tgtChapID = (random() >> 24) % 255; // should be random enough ...
+ addText(&spp, "CHAP_I=%d", op->tgtChapID);
+ cp = genChapChallenge(cp, op->tgtChallengeLen? op->tgtChallengeLen: 8);
+ addText(&spp, "CHAP_C=%s", cp);
+ op->tgtChapDigest = chapDigest(ap, op->tgtChapID, cp, op->tgtChapSecret);
+ }
+
+ return sendPDU(sess, &spp, handleLoginResp);
+}
+
+static int
+authenticate(isess_t *sess)
+{
+ pdu_t spp;
+ login_req_t *lp;
+ isc_opt_t *op = sess->op;
+
+ bzero(&spp, sizeof(pdu_t));
+ lp = (login_req_t *)&spp.ipdu.bhs;
+ lp->cmd = ISCSI_LOGIN_CMD | 0x40; // login request + Inmediate
+ memcpy(lp->isid, sess->isid, 6);
+ lp->tsih = sess->tsih; // MUST be zero the first time!
+ lp->CID = htons(1);
+ lp->CSG = SN_PHASE; // Security Negotiation
+ lp->NSG = SN_PHASE;
+ lp->T = 0;
+
+ switch((authm_t)lookup(AuthMethods, op->authMethod)) {
+ case NONE:
+ return 0;
+
+ case KRB5:
+ case SPKM1:
+ case SPKM2:
+ case SRP:
+ return 2;
+
+ case CHAP:
+ if(op->chapDigest == 0)
+ addText(&spp, "CHAP_A=5");
+ else
+ if(strcmp(op->chapDigest, "MD5") == 0)
+ addText(&spp, "CHAP_A=5");
+ else
+ if(strcmp(op->chapDigest, "SHA1") == 0)
+ addText(&spp, "CHAP_A=7");
+ else
+ addText(&spp, "CHAP_A=5,7");
+ return sendPDU(sess, &spp, handleChap);
+ }
+ return 1;
+}
+
+int
+loginPhase(isess_t *sess)
+{
+ pdu_t spp, *sp = &spp;
+ isc_opt_t *op = sess->op;
+ login_req_t *lp;
+ int status = 1;
+
+ debug_called(3);
+
+ bzero(sp, sizeof(pdu_t));
+ lp = (login_req_t *)&spp.ipdu.bhs;
+ lp->cmd = ISCSI_LOGIN_CMD | 0x40; // login request + Inmediate
+ memcpy(lp->isid, sess->isid, 6);
+ lp->tsih = sess->tsih; // MUST be zero the first time!
+ lp->CID = htons(1); // sess->cid?
+
+ if((lp->CSG = sess->csg) == LON_PHASE)
+ lp->NSG = FF_PHASE; // lets try and go full feature ...
+ else
+ lp->NSG = LON_PHASE;
+ lp->T = 1; // transit to next login stage
+
+ if(sess->flags & SESS_INITIALLOGIN1) {
+ sess->flags &= ~SESS_INITIALLOGIN1;
+
+ addText(sp, "SessionType=%s", op->sessionType);
+ addText(sp, "InitiatorName=%s", op->initiatorName);
+ if(strcmp(op->sessionType, "Discovery") != 0) {
+ addText(sp, "TargetName=%s", op->targetName);
+ }
+ }
+ switch(sess->csg) {
+ case SN_PHASE: // Security Negotiation
+ addText(sp, "AuthMethod=%s", op->authMethod);
+ break;
+
+ case LON_PHASE: // Login Operational Negotiation
+ if((sess->flags & SESS_NEGODONE) == 0) {
+ sess->flags |= SESS_NEGODONE;
+ addText(sp, "MaxBurstLength=%d", op->maxBurstLength);
+ addText(sp, "HeaderDigest=%s", op->headerDigest);
+ addText(sp, "DataDigest=%s", op->dataDigest);
+ addText(sp, "MaxRecvDataSegmentLength=%d", op->maxRecvDataSegmentLength);
+ addText(sp, "ErrorRecoveryLevel=%d", op->errorRecoveryLevel);
+ addText(sp, "DefaultTime2Wait=%d", op->defaultTime2Wait);
+ addText(sp, "DefaultTime2Retain=%d", op->defaultTime2Retain);
+ addText(sp, "DataPDUInOrder=%s", op->dataPDUInOrder? "Yes": "No");
+ addText(sp, "DataSequenceInOrder=%s", op->dataSequenceInOrder? "Yes": "No");
+ addText(sp, "MaxOutstandingR2T=%d", op->maxOutstandingR2T);
+
+ if(strcmp(op->sessionType, "Discovery") != 0) {
+ addText(sp, "MaxConnections=%d", op->maxConnections);
+ addText(sp, "FirstBurstLength=%d", op->firstBurstLength);
+ addText(sp, "InitialR2T=%s", op->initialR2T? "Yes": "No");
+ addText(sp, "ImmediateData=%s", op->immediateData? "Yes": "No");
+ }
+ }
+
+ break;
+ }
+
+ status = sendPDU(sess, &spp, handleLoginResp);
+
+ switch(status) {
+ case 0: // all is ok ...
+ if(sess->csg == SN_PHASE)
+ /*
+ | if we are still here, then we need
+ | to exchange some secrets ...
+ */
+ status = authenticate(sess);
+ }
+
+ return status;
+}
diff --git a/sbin/iscontrol/misc.c b/sbin/iscontrol/misc.c
new file mode 100644
index 0000000..6586082
--- /dev/null
+++ b/sbin/iscontrol/misc.c
@@ -0,0 +1,225 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+
+/*
+ | $Id: misc.c,v 2.1 2006/11/12 08:06:51 danny Exp $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/sysctl.h>
+
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <arpa/inet.h>
+#if __FreeBSD_version < 500000
+#include <sys/time.h>
+#endif
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+
+static inline char
+c2b(unsigned char c)
+{
+ switch(c) {
+ case '0' ... '9':
+ return c - '0';
+ case 'a' ... 'f':
+ return c - 'a' + 10;
+ case 'A' ... 'F':
+ return c - 'A' + 10;
+ }
+ return 0;
+}
+
+static char base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "0123456789+/";
+
+static __inline unsigned char
+c64tobin(unsigned char c64)
+{
+ int i;
+ for(i = 0; i < 64; i++)
+ if(base64[i] == c64)
+ break;
+ return i;
+}
+/*
+ | according to rfc3720, the binary string
+ | cannot be larger than 1024 - but i can't find it :-) XXX
+ | not enforced yet.
+ */
+int
+str2bin(char *str, char **rsp)
+{
+ char *src, *dst, *tmp;
+ int i, len = 0;
+
+ src = str;
+ tmp = NULL;
+ if(strncasecmp("0x", src, 2) == 0) {
+ src += 2;
+ len = strlen(src);
+
+ if((tmp = malloc((len+1)/2)) == NULL) {
+ // XXX: print some error?
+ return 0;
+ }
+ dst = tmp;
+ if(len & 1)
+ *dst++ = c2b(*src++);
+ while(*src) {
+ *dst = c2b(*src++) << 4;
+ *dst++ |= c2b(*src++);
+ }
+ len = dst - tmp;
+ } else
+ if(strncasecmp("0b", src , 2) == 0) {
+ // base64
+ unsigned char b6;
+
+ src += 2;
+ len = strlen(src) / 4 * 3;
+ if((tmp = malloc(len)) == NULL) {
+ // XXX: print some error?
+ return 0;
+ }
+ dst = tmp;
+ i = 0;
+ while(*src && ((b6 = c64tobin(*src++)) != 64)) {
+ switch(i % 4) {
+ case 0:
+ *dst = b6 << 2;
+ break;
+ case 1:
+ *dst++ |= b6 >> 4;
+ *dst = b6 << 4;
+ break;
+ case 2:
+ *dst++ |= b6 >> 2;
+ *dst = b6 << 6;
+ break;
+ case 3:
+ *dst++ |= b6;
+ break;
+ }
+ i++;
+ }
+ len = dst - tmp;
+ }
+ else {
+ /*
+ | assume it to be an ascii string, so just copy it
+ */
+ len = strlen(str);
+ if((tmp = malloc(len)) == NULL)
+ return 0;
+ dst = tmp;
+ src = str;
+ while(*src)
+ *dst++ = *src++;
+ }
+
+ *rsp = tmp;
+ return len;
+}
+
+char *
+bin2str(char *encoding, unsigned char *md, int blen)
+{
+ int len;
+ char *dst, *ds, *cp;
+
+ if(strncasecmp(encoding, "0x", 2) == 0) {
+ char ofmt[5];
+
+ len = blen * 2;
+ dst = malloc(len + 3);
+ strcpy(dst, encoding);
+ ds = dst + 2;
+ cp = (char *)md;
+ sprintf(ofmt, "%%02%c", encoding[1]);
+ while(blen-- > 0) {
+ sprintf(ds, ofmt, *cp++);
+ ds += 2;
+ }
+ *ds = 0;
+ return dst;
+ }
+ if(strncasecmp(encoding, "0b", 2) == 0) {
+ int i, b6;
+
+ len = (blen + 2) * 4 / 3;
+ dst = malloc(len + 3);
+ strcpy(dst, encoding);
+ ds = dst + 2;
+ cp = (char *)md;
+ b6 = 0; // to keep copiler happy.
+ for(i = 0; i < blen; i++) {
+ switch(i % 3) {
+ case 0:
+ *ds++ = base64[*cp >> 2];
+ b6 = (*cp & 0x3) << 4;
+ break;
+ case 1:
+ b6 += (*cp >> 4);
+ *ds++ = base64[b6];
+ b6 = (*cp & 0xf) << 2;
+ break;
+ case 2:
+ b6 += (*cp >> 6);
+ *ds++ = base64[b6];
+ *ds++ = base64[*cp & 0x3f];
+ }
+ cp++;
+ }
+ switch(blen % 3) {
+ case 0:
+ break;
+ case 1:
+ *ds++ = base64[b6];
+ *ds++ = '=';
+ *ds++ = '=';
+ break;
+ case 2:
+ *ds++ = base64[b6];
+ *ds++ = '=';
+ break;
+ }
+
+ *ds = 0;
+ return dst;
+ }
+
+ return NULL;
+}
diff --git a/sbin/iscontrol/pdu.c b/sbin/iscontrol/pdu.c
new file mode 100644
index 0000000..18dfdfc
--- /dev/null
+++ b/sbin/iscontrol/pdu.c
@@ -0,0 +1,175 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ */
+/*
+ | $Id: pdu.c,v 2.2 2006/12/01 09:11:56 danny Exp danny $
+ */
+
+#include <sys/cdefs.h>
+__FBSDID("$FreeBSD$");
+
+#include <sys/types.h>
+#include <sys/time.h>
+#include <sys/uio.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <errno.h>
+#include <stdio.h>
+#include <stdarg.h>
+#include <camlib.h>
+
+#include "iscsi.h"
+#include "iscontrol.h"
+#include "pdu.h"
+
+int
+xmitpdu(isess_t *sess, pdu_t *pp)
+{
+ if(ioctl(sess->fd, ISCSISEND, pp)) {
+ perror("xmitpdu");
+ return -1;
+ }
+ if(vflag)
+ pukeText("I-", pp);
+
+ return 0;
+}
+
+int
+recvpdu(isess_t *sess, pdu_t *pp)
+{
+ if(ioctl(sess->fd, ISCSIRECV, pp)) {
+ perror("recvpdu");
+ return -1;
+ }
+ // XXX: return error if truncated via
+ // the FUDGE factor.
+ if(vflag)
+ pukeText("T-", pp);
+
+ return 0;
+}
+
+int
+sendPDU(isess_t *sess, pdu_t *pp, handler_t *hdlr)
+{
+ if(xmitpdu(sess, pp))
+ return 0;
+ if(hdlr) {
+ int res;
+
+ pp->ahs_size = 8 * 1024;
+ if((pp->ahs = malloc(pp->ahs_size)) == NULL) {
+ fprintf(stderr, "out of mem!");
+ return -1;
+ }
+ pp->ds_size = 0;
+ if((res = recvpdu(sess, pp)) != 0) {
+ fprintf(stderr, "recvpdu failed\n");
+ return res;
+ }
+ res = hdlr(sess, pp);
+ freePDU(pp);
+ return res;
+ }
+ return 1;
+}
+
+
+#define FUDGE (512 * 8)
+/*
+ | We use the same memory for the response
+ | so make enough room ...
+ | XXX: must find a better way.
+ */
+int
+addText(pdu_t *pp, char *fmt, ...)
+{
+ u_int len;
+ char *str;
+ va_list ap;
+
+ va_start(ap, fmt);
+ len = vasprintf(&str, fmt, ap) + 1;
+ if((pp->ds_len + len) > 0xffffff) {
+ printf("ds overflow\n");
+ free(str);
+ return 0;
+ }
+
+ if((pp->ds_len + len) > pp->ds_size) {
+ u_char *np;
+
+ np = realloc(pp->ds, pp->ds_size + len + FUDGE);
+ if(np == NULL) {
+ free(str);
+ //XXX: out of memory!
+ return -1;
+ }
+ pp->ds = np;
+ pp->ds_size += len + FUDGE;
+ }
+ memcpy(pp->ds + pp->ds_len, str, len);
+ pp->ds_len += len;
+ free(str);
+ return len;
+}
+
+void
+freePDU(pdu_t *pp)
+{
+ if(pp->ahs_size)
+ free(pp->ahs);
+ if(pp->ds_size)
+ free(pp->ds);
+ bzero(&pp->ipdu, sizeof(union ipdu_u));
+ pp->ahs = NULL;
+ pp->ds = NULL;
+ pp->ahs_size = 0;
+ pp->ds_size = pp->ds_len = 0;
+}
+
+void
+pukeText(char *it, pdu_t *pp)
+{
+ char *ptr;
+ int cmd;
+ size_t len, n;
+
+ len = pp->ds_len;
+ ptr = (char *)pp->ds;
+ cmd = pp->ipdu.bhs.opcode;
+
+ printf("%s: cmd=0x%x len=%d\n", it, cmd, (int)len);
+ while(len > 0) {
+ printf("\t%s\n", ptr);
+ n = strlen(ptr) + 1;
+ len -= n;
+ ptr += n;
+ }
+}
diff --git a/sbin/iscontrol/pdu.h b/sbin/iscontrol/pdu.h
new file mode 100644
index 0000000..0154f9e
--- /dev/null
+++ b/sbin/iscontrol/pdu.h
@@ -0,0 +1,134 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny@cs.huji.ac.il>
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
+ * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+ * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ *
+ * $FreeBSD$
+ */
+/*
+ | $Id: pdu.h,v 2.1 2006/11/12 08:06:51 danny Exp $
+ */
+
+/*
+ | keep in BIG endian order (network byte order).
+ */
+
+typedef struct login_req {
+ char cmd; // 0x03
+
+ u_char NSG:2;
+ u_char CSG:2;
+ u_char _:2;
+ u_char C:1;
+ u_char T:1;
+
+ char v_max;
+ char v_min;
+
+ int len; // remapped via standard bhs
+ char isid[6];
+ short tsih;
+ int itt; // Initiator Task Tag;
+
+ int CID:16;
+ int rsv:16;
+
+ int cmdSN;
+ int expStatSN;
+ int unused[4];
+} login_req_t;
+
+typedef struct login_rsp {
+ char cmd; // 0x23
+ u_char NSG:2;
+ u_char CSG:2;
+ u_char _1:2;
+ u_char C:1;
+ u_char T:1;
+
+ char v_max;
+ char v_act;
+
+ int len; // remapped via standard bhs
+ char isid[6];
+ short tsih;
+ int itt; // Initiator Task Tag;
+ int _2;
+ rsp_sn_t sn;
+ int status:16;
+ int _3:16;
+ int _4[2];
+} login_rsp_t;
+
+typedef struct text_req {
+ char cmd; // 0x04
+
+ u_char _1:6;
+ u_char C:1; // Continuation
+ u_char F:1; // Final
+ char _2[2];
+
+ int len;
+ int itt; // Initiator Task Tag
+ int LUN[2];
+ int ttt; // Target Transfer Tag
+ int cmdSN;
+ int expStatSN;
+ int unused[4];
+} text_req_t;
+
+/*
+ | Responses
+ */
+typedef struct logout_req {
+ char cmd; // 0x06
+ char reason; // 0 - close session
+ // 1 - close connection
+ // 2 - remove the connection for recovery
+ char _2[2];
+
+ int len;
+ int _r[2];
+ int itt; // Initiator Task Tag;
+
+ u_int CID:16;
+ u_int rsv:16;
+
+ int cmdSN;
+ int expStatSN;
+ int unused[4];
+} logout_req_t;
+
+typedef struct logout_rsp {
+ char cmd; // 0x26
+ char cbits;
+ char _1[2];
+ int len;
+ int _2[2];
+ int itt;
+ int _3;
+ rsp_sn_t sn;
+ short time2wait;
+ short time2retain;
+ int _4;
+} logout_rsp_t;
OpenPOWER on IntegriCloud