[Midnightbsd-cvs] src: sbin/ip6fw: Add iScsi part 1 of 2.
laffer1 at midnightbsd.org
laffer1 at midnightbsd.org
Tue Nov 11 16:30:43 EST 2008
Log Message:
-----------
Add iScsi part 1 of 2.
Remove ip6fw since ipfw is going ipv6.
Added Files:
-----------
src/sbin/iscontrol:
Makefile (r1.1)
auth_subr.c (r1.1)
config.c (r1.1)
fsm.c (r1.1)
iscontrol.8 (r1.1)
iscontrol.c (r1.1)
iscontrol.h (r1.1)
iscsi.conf.5 (r1.1)
login.c (r1.1)
misc.c (r1.1)
pdu.c (r1.1)
pdu.h (r1.1)
Removed Files:
-------------
src/sbin/ip6fw:
Makefile
ip6fw.8
ip6fw.c
sample.sh
-------------- next part --------------
--- sbin/ip6fw/ip6fw.8
+++ /dev/null
@@ -1,582 +0,0 @@
-.\"
-.\" $FreeBSD: src/sbin/ip6fw/ip6fw.8,v 1.25 2005/02/13 22:25:15 ru Exp $
-.\"
-.\" $KAME$
-.\"
-.\" Copyright (C) 1998, 1999, 2000 and 2001 WIDE Project.
-.\" 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.
-.\" 3. Neither the name of the project nor the names of its contributors
-.\" may be used to endorse or promote products derived from this software
-.\" without specific prior written permission.
-.\"
-.\" THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
-.\"
-.Dd March 13, 2000
-.Dt IP6FW 8
-.Os
-.Sh NAME
-.Nm ip6fw
-.Nd controlling utility for IPv6 firewall
-.Sh SYNOPSIS
-.Nm
-.Op Fl nq
-.Oo
-.Fl p Ar preproc
-.Oo Fl D
-.Ar macro Ns Op = Ns Ar value
-.Oc
-.Op Fl U Ar macro
-.Oc
-.Ar pathname
-.Nm
-.Op Fl n
-.Op Fl f | Fl q
-flush
-.Nm
-.Op Fl nq
-zero
-.Op Ar number ...
-.Nm
-.Op Fl n
-delete
-.Ar number ...
-.Nm
-.Op Fl aftN
-list
-.Op Ar number ...
-.Nm
-.Op Fl ftN
-show
-.Op Ar number ...
-.Nm
-.Op Fl nq
-add
-.Op Ar number
-.Ar action
-.Op log
-.Ar proto
-from
-.Ar src
-to
-.Ar dst
-.Op via Ar name | ipv6no
-.Op Ar options
-.Sh DESCRIPTION
-To ease configuration, rules can be put into a file which is
-processed using
-.Nm
-as shown in the first synopsis line.
-An absolute
-.Ar pathname
-must be used.
-The file
-will be read line by line and applied as arguments to the
-.Nm
-utility.
-.Pp
-Optionally, a preprocessor can be specified using
-.Fl p Ar preproc
-where
-.Ar pathname
-is to be piped through.
-Useful preprocessors include
-.Xr cpp 1
-and
-.Xr m4 1 .
-If
-.Ar preproc
-does not start with a slash
-.Pq Ql /
-as its first character, the usual
-.Ev PATH
-name search is performed.
-Care should be taken with this in environments where not all
-file systems are mounted (yet) by the time
-.Nm
-is being run (e.g.\& when they are mounted over NFS).
-Once
-.Fl p
-has been specified, optional
-.Fl D
-and
-.Fl U
-specifications can follow and will be passed on to the preprocessor.
-This allows for flexible configuration files (like conditionalizing
-them on the local hostname) and the use of macros to centralize
-frequently required arguments like IP addresses.
-.Pp
-The
-.Nm
-code works by going through the rule-list for each packet,
-until a match is found.
-All rules have two associated counters, a packet count and
-a byte count.
-These counters are updated when a packet matches the rule.
-.Pp
-The rules are ordered by a
-.Dq line-number
-from 1 to 65534 that is used
-to order and delete rules.
-Rules are tried in increasing order, and the
-first rule that matches a packet applies.
-Multiple rules may share the same number and apply in
-the order in which they were added.
-.Pp
-If a rule is added without a number, it is numbered 100 higher
-than the previous rule.
-If the highest defined rule number is
-greater than 65434, new rules are appended to the last rule.
-.Pp
-The delete operation deletes the first rule with number
-.Ar number ,
-if any.
-.Pp
-The list command prints out the current rule set.
-.Pp
-The show command is equivalent to `ip6fw -a list'.
-.Pp
-The zero operation zeroes the counters associated with rule number
-.Ar number .
-.Pp
-The flush operation removes all rules.
-.Pp
-Any command beginning with a
-.Sq # ,
-or being all blank, is ignored.
-.Pp
-One rule is always present:
-.Bd -literal -offset center
-65535 deny all from any to any
-.Ed
-.Pp
-This rule is the default policy, i.e., do not allow anything at all.
-Your job in setting up rules is to modify this policy to match your
-needs.
-.Pp
-The following options are available:
-.Bl -tag -width flag
-.It Fl a
-While listing, show counter values.
-See also
-.Dq show
-command.
-.It Fl f
-Do not ask for confirmation for commands that can cause problems if misused
-(ie; flush).
-.Ar Note ,
-if there is no tty associated with the process, this is implied.
-.It Fl n
-Only check syntax of the command strings,
-without actually passing them into the kernel.
-.It Fl q
-While adding, zeroing or flushing, be quiet about actions (implies '-f').
-This is useful for adjusting rules by executing multiple ip6fw commands in a
-script (e.g.\& sh /etc/rc.firewall), or by processing a file of many ip6fw rules,
-across a remote login session.
-If a flush is performed in normal
-(verbose) mode, it prints a message.
-Because all rules are flushed, the
-message cannot be delivered to the login session, the login session is
-closed and the remainder of the ruleset is not processed.
-Access to the
-console is required to recover.
-.It Fl t
-While listing, show last match timestamp.
-.It Fl N
-Try to resolve addresses and service names in output.
-.El
-.Pp
-.Ar action :
-.Bl -hang -offset flag -width 16n
-.It Ar allow
-Allow packets that match rule.
-The search terminates.
-Aliases are
-.Ar pass ,
-.Ar permit ,
-and
-.Ar accept .
-.It Ar deny
-Discard packets that match this rule.
-The search terminates.
-.Ar Drop
-is an alias for
-.Ar deny .
-.It Ar reject
-(Deprecated.)
-Discard packets that match this rule, and try to send an ICMPv6
-host unreachable notice.
-The search terminates.
-.It Ar unreach code
-Discard packets that match this rule, and try to send an ICMPv6
-unreachable notice with code
-.Ar code ,
-where
-.Ar code
-is a number from zero to 255, or one of these aliases:
-.Ar noroute ,
-.Ar admin ,
-.Ar notneighbor ,
-.Ar addr ,
-or
-.Ar noport ,
-The search terminates.
-.It Ar reset
-TCP packets only.
-Discard packets that match this rule,
-and try to send a TCP reset (RST) notice.
-The search terminates
-.It Ar count
-Update counters for all packets that match rule.
-The search continues with the next rule.
-.It Ar skipto number
-Skip all subsequent rules numbered less than
-.Ar number .
-The search continues with the first rule numbered
-.Ar number
-or higher.
-.El
-.Pp
-If the kernel was compiled with
-.Dv IPV6FIREWALL_VERBOSE ,
-then when a packet matches a rule with the
-.Dq log
-keyword or a clear/resetlog is performed, a message will be logged to
-.Xr syslogd 8 ,
-or, if that fails, to the console.
-If the kernel was compiled with the
-.Dv IPV6FIREWALL_VERBOSE_LIMIT
-option, then logging will cease after the number of packets
-specified by the option are received for that particular
-chain entry.
-When this limit is reached, the limit and rule number will be logged.
-Logging may then be re-enabled by clearing
-the packet counter for that entry.
-.Pp
-The
-.Xr syslogd 8
-logging and the default log limit are adjustable dynamically through the
-.Xr sysctl 8
-interface.
-.Pp
-.Ar proto :
-.Bl -hang -offset flag -width 16n
-.It Ar ipv6
-All packets match.
-The alias
-.Ar all
-has the same effect.
-.It Ar tcp
-Only TCP packets match.
-.It Ar udp
-Only UDP packets match.
-.It Ar ipv6-icmp
-Only ICMPv6 packets match.
-.It Ar <number|name>
-Only packets for the specified protocol matches (see
-.Pa /etc/protocols
-for a complete list).
-.El
-.Pp
-.Ar src
-and
-.Ar dst :
-.Bl -hang -offset flag
-.It Ar <address/prefixlen>
-.Op Ar ports
-.El
-.Pp
-The
-.Em <address/prefixlen>
-may be specified as:
-.Bl -hang -offset flag -width 16n
-.It Ar ipv6no
-An ipv6number of the form
-.Li fec0::1:2:3:4 .
-.It Ar ipv6no/prefixlen
-An ipv6number with a prefix length of the form
-.Li fec0::1:2:3:4/112 .
-.El
-.Pp
-The sense of the match can be inverted by preceding an address with the
-.Dq not
-modifier, causing all other addresses to be matched instead.
-This
-does not affect the selection of port numbers.
-.Pp
-With the TCP and UDP protocols, optional
-.Em ports
-may be specified as:
-.Pp
-.Bl -hang -offset flag
-.It Ns {port|port-port} Ns Op ,port Ns Op ,...
-.El
-.Pp
-Service names (from
-.Pa /etc/services )
-may be used instead of numeric port values.
-A range may only be specified as the first value,
-and the length of the port list is limited to
-.Dv IPV6_FW_MAX_PORTS
-(as defined in
-.In netinet6/ip6_fw.h )
-ports.
-.Pp
-Fragmented packets which have a non-zero offset (i.e., not the first
-fragment) will never match a rule which has one or more port
-specifications.
-See the
-.Ar frag
-option for details on matching fragmented packets.
-.Pp
-Rules can apply to packets when they are incoming, or outgoing, or both.
-The
-.Ar in
-keyword indicates the rule should only match incoming packets.
-The
-.Ar out
-keyword indicates the rule should only match outgoing packets.
-.Pp
-To match packets going through a certain interface, specify
-the interface using
-.Ar via :
-.Bl -hang -offset flag -width 16n
-.It Ar via ifX
-Packet must be going through interface
-.Ar ifX .
-.It Ar via if*
-Packet must be going through interface
-.Ar ifX ,
-where X is any unit number.
-.It Ar via any
-Packet must be going through
-.Em some
-interface.
-.It Ar via ipv6no
-Packet must be going through the interface having IPv6 address
-.Ar ipv6no .
-.El
-.Pp
-The
-.Ar via
-keyword causes the interface to always be checked.
-If
-.Ar recv
-or
-.Ar xmit
-is used instead of
-.Ar via ,
-then the only receive or transmit interface (respectively) is checked.
-By specifying both, it is possible to match packets based on both receive
-and transmit interface, e.g.:
-.Pp
-.Dl "ip6fw add 100 deny ip from any to any out recv ed0 xmit ed1"
-.Pp
-The
-.Ar recv
-interface can be tested on either incoming or outgoing packets, while the
-.Ar xmit
-interface can only be tested on outgoing packets.
-So
-.Ar out
-is required (and
-.Ar in
-invalid) whenever
-.Ar xmit
-is used.
-Specifying
-.Ar via
-together with
-.Ar xmit
-or
-.Ar recv
-is invalid.
-.Pp
-A packet may not have a receive or transmit interface: packets originating
-from the local host have no receive interface, while packets destined for
-the local host have no transmit interface.
-.Pp
-Additional
-.Ar options :
-.Bl -hang -offset flag -width 16n
-.It frag
-Matches if the packet is a fragment and this is not the first fragment
-of the datagram.
-.Ar frag
-may not be used in conjunction with either
-.Ar tcpflags
-or TCP/UDP port specifications.
-.It in
-Matches if this packet was on the way in.
-.It out
-Matches if this packet was on the way out.
-.It ipv6options Ar spec
-Matches if the IPv6 header contains the comma separated list of
-options specified in
-.Ar spec .
-The supported IPv6 options are:
-.Ar hopopt
-(hop-by-hop options header),
-.Ar route
-(routing header),
-.Ar frag
-(fragment header),
-.Ar esp
-(encapsulating security payload),
-.Ar ah
-(authentication header),
-.Ar nonxt
-(no next header), and
-.Ar opts
-(destination options header).
-The absence of a particular option may be denoted
-with a
-.Dq \&!
-.Em ( "not working yet" ) .
-.It established
-Matches packets that have the RST or ACK bits set.
-TCP packets only.
-.It setup
-Matches packets that have the SYN bit set but no ACK bit.
-TCP packets only.
-.It tcpflags Ar spec
-Matches if the TCP header contains the comma separated list of
-flags specified in
-.Ar spec .
-The supported TCP flags are:
-.Ar fin ,
-.Ar syn ,
-.Ar rst ,
-.Ar psh ,
-.Ar ack ,
-and
-.Ar urg .
-The absence of a particular flag may be denoted
-with a
-.Dq \&! .
-A rule which contains a
-.Ar tcpflags
-specification can never match a fragmented packet which has
-a non-zero offset.
-See the
-.Ar frag
-option for details on matching fragmented packets.
-.It icmptypes Ar types
-Matches if the ICMPv6 type is in the list
-.Ar types .
-The list may be specified as any combination of ranges
-or individual types separated by commas.
-.El
-.Sh CHECKLIST
-Here are some important points to consider when designing your
-rules:
-.Bl -bullet -offset flag
-.It
-Remember that you filter both packets going in and out.
-Most connections need packets going in both directions.
-.It
-Remember to test very carefully.
-It is a good idea to be near the console when doing this.
-.It
-Do not forget the loopback interface.
-.El
-.Sh FINE POINTS
-There is one kind of packet that the firewall will always discard,
-that is an IPv6 fragment with a fragment offset of one.
-This is a valid packet, but it only has one use, to try to circumvent
-firewalls.
-.Pp
-If you are logged in over a network, loading the KLD version of
-.Nm
-is probably not as straightforward as you would think
-.Em ( "not supported" ) .
-I recommend this command line:
-.Bd -literal -offset center
-kldload ip6fw && \e
-ip6fw add 32000 allow all from any to any
-.Ed
-.Pp
-Along the same lines, doing an
-.Bd -literal -offset center
-ip6fw flush
-.Ed
-.Pp
-in similar surroundings is also a bad idea.
-.Sh PACKET DIVERSION
-not supported.
-.Sh EXAMPLES
-This command adds an entry which denies all tcp packets from
-.Em hacker.evil.org
-to the telnet port of
-.Em wolf.tambov.su
-from being forwarded by the host:
-.Pp
-.Dl ip6fw add deny tcp from hacker.evil.org to wolf.tambov.su 23
-.Pp
-This one disallows any connection from the entire hackers network to
-my host:
-.Pp
-.Dl ip6fw add deny all from fec0::123:45:67:0/112 to my.host.org
-.Pp
-Here is a good usage of the list command to see accounting records
-and timestamp information:
-.Pp
-.Dl ip6fw -at l
-.Pp
-or in short form without timestamps:
-.Pp
-.Dl ip6fw -a l
-.Sh SEE ALSO
-.Xr ip 4 ,
-.Xr ipfirewall 4 ,
-.Xr protocols 5 ,
-.Xr services 5 ,
-.Xr reboot 8 ,
-.Xr sysctl 8 ,
-.Xr syslogd 8
-.Sh HISTORY
-A
-.Nm
-utility first appeared in
-.Fx 4.0 .
-.Sh AUTHORS
-.An Ugen J. S. Antsilevich ,
-.An Poul-Henning Kamp ,
-.An Alex Nash ,
-.An Archie Cobbs .
-.Pp
-.An -nosplit
-API based upon code written by
-.An Daniel Boulet
-for BSDI.
-.Sh BUGS
-.Em WARNING!!WARNING!!WARNING!!WARNING!!WARNING!!WARNING!!WARNING!!
-.Pp
-This program can put your computer in rather unusable state.
-When
-using it for the first time, work on the console of the computer, and
-do
-.Em NOT
-do anything you do not understand.
-.Pp
-When manipulating/adding chain entries, service and protocol names are
-not accepted.
--- sbin/ip6fw/sample.sh
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/sh -
-# $FreeBSD: src/sbin/ip6fw/sample.sh,v 1.2 2000/05/04 17:33:27 phantom Exp $
-
-fwcmd=/sbin/ip6fw
-
-$fwcmd -f flush
-
-#
-# loopback
-#
-$fwcmd add 1000 pass all from any to any via lo0
-
-#
-# ND
-#
-# DAD
-$fwcmd add 2000 pass ipv6-icmp from ff02::/16 to ::
-$fwcmd add 2100 pass ipv6-icmp from :: to ff02::/16
-# RS, RA, NS, NA, redirect...
-$fwcmd add 2300 pass ipv6-icmp from fe80::/10 to fe80::/10
-$fwcmd add 2400 pass ipv6-icmp from fe80::/10 to ff02::/16
-
-$fwcmd add 5000 pass tcp from any to any established
-
-# RIPng
-$fwcmd add 6000 pass udp from fe80::/10 521 to ff02::9 521
-
-$fwcmd add 65000 pass log all from any to any
--- sbin/ip6fw/ip6fw.c
+++ /dev/null
@@ -1,1453 +0,0 @@
-/* $KAME: ip6fw.c,v 1.14 2003/10/02 19:36:25 itojun Exp $ */
-
-/*
- * Copyright (C) 1998, 1999, 2000 and 2001 WIDE Project.
- * 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.
- * 3. Neither the name of the project nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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.
- */
-
-/*
- * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
- * Copyright (c) 1994 Ugen J.S.Antsilevich
- *
- * Idea and grammar partially left from:
- * Copyright (c) 1993 Daniel Boulet
- *
- * Redistribution and use in source forms, with and without modification,
- * are permitted provided that this entire comment appears intact.
- *
- * Redistribution in binary form may occur without any restrictions.
- * Obviously, it would be nice if you gave credit where credit is due
- * but requiring it would be too onerous.
- *
- * This software is provided ``AS IS'' without any warranties of any kind.
- *
- * NEW command line interface for IP firewall facility
- *
- * $Id: ip6fw.c,v 1.1.2.2.2.2 1999/05/14 05:13:50 shin Exp $
- * $FreeBSD: src/sbin/ip6fw/ip6fw.c,v 1.18 2004/07/29 18:04:06 kan Exp $
- */
-
-#include <sys/types.h>
-#include <sys/queue.h>
-#include <sys/socket.h>
-#include <sys/sockio.h>
-#include <sys/time.h>
-#include <sys/ioctl.h>
-#include <sys/wait.h>
-
-#include <ctype.h>
-#include <err.h>
-#include <limits.h>
-#include <netdb.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <stdarg.h>
-#include <string.h>
-#include <time.h>
-#include <timeconv.h>
-#include <unistd.h>
-#include <errno.h>
-#include <signal.h>
-#include <sysexits.h>
-
-#include <net/if.h>
-#include <netinet/in.h>
-#include <netinet/in_systm.h>
-#include <netinet/ip6.h>
-#include <netinet/icmp6.h>
-#include <netinet6/ip6_fw.h>
-#include <netinet/tcp.h>
-#include <arpa/inet.h>
-
-int lineno = -1;
-
-int s; /* main RAW socket */
-int do_resolv=0; /* Would try to resolv all */
-int do_acct=0; /* Show packet/byte count */
-int do_time=0; /* Show time stamps */
-int do_quiet=0; /* Be quiet in add and flush */
-int do_force=0; /* Don't ask for confirmation */
-int do_test=0; /* Don't load into Kernel */
-
-struct icmpcode {
- int code;
- char *str;
-};
-
-static struct icmpcode icmp6codes[] = {
- { ICMP6_DST_UNREACH_NOROUTE, "noroute" },
- { ICMP6_DST_UNREACH_ADMIN, "admin" },
- { ICMP6_DST_UNREACH_NOTNEIGHBOR, "notneighbor" },
- { ICMP6_DST_UNREACH_ADDR, "addr" },
- { ICMP6_DST_UNREACH_NOPORT, "noport" },
- { 0, NULL }
-};
-
-static char ntop_buf[INET6_ADDRSTRLEN];
-
-static void show_usage(const char *fmt, ...);
-
-static int
-mask_bits(u_char *m_ad, int m_len)
-{
- int h_num = 0,i;
-
- for (i = 0; i < m_len; i++, m_ad++) {
- if (*m_ad != 0xff)
- break;
- h_num += 8;
- }
- if (i < m_len) {
- switch (*m_ad) {
-#define MASKLEN(m, l) case m: h_num += l; break
- MASKLEN(0xfe, 7);
- MASKLEN(0xfc, 6);
- MASKLEN(0xf8, 5);
- MASKLEN(0xf0, 4);
- MASKLEN(0xe0, 3);
- MASKLEN(0xc0, 2);
- MASKLEN(0x80, 1);
-#undef MASKLEN
- }
- }
- return h_num;
-}
-
-static int pl2m[9] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
-
-struct in6_addr *plen2mask(int n)
-{
- static struct in6_addr ia;
- u_char *p;
- int i;
-
- memset(&ia, 0, sizeof(struct in6_addr));
- p = (u_char *)&ia;
- for (i = 0; i < 16; i++, p++, n -= 8) {
- if (n >= 8) {
- *p = 0xff;
- continue;
- }
- *p = pl2m[n];
- break;
- }
- return &ia;
-}
-
-void
-print_port(prot, port, comma)
- u_char prot;
- u_short port;
- const char *comma;
-{
- struct servent *se;
- struct protoent *pe;
- const char *protocol;
- int printed = 0;
-
- if (do_resolv) {
- pe = getprotobynumber(prot);
- if (pe)
- protocol = pe->p_name;
- else
- protocol = NULL;
-
- se = getservbyport(htons(port), protocol);
- if (se) {
- printf("%s%s", comma, se->s_name);
- printed = 1;
- }
- }
- if (!printed)
- printf("%s%d",comma,port);
-}
-
-static void
-print_iface(char *key, union ip6_fw_if *un, int byname)
-{
-
- if (byname) {
- printf(" %s %s", key, un->fu_via_if.name);
- } else if (!IN6_IS_ADDR_UNSPECIFIED(&un->fu_via_ip6)) {
- printf(" %s %s", key, inet_ntop(AF_INET6,&un->fu_via_ip6,ntop_buf,sizeof(ntop_buf)));
- } else
- printf(" %s any", key);
-}
-
-static void
-print_reject_code(int code)
-{
- struct icmpcode *ic;
-
- for (ic = icmp6codes; ic->str; ic++)
- if (ic->code == code) {
- printf("%s", ic->str);
- return;
- }
- printf("%u", code);
-}
-
-static void
-show_ip6fw(struct ip6_fw *chain)
-{
- char *comma;
- struct hostent *he;
- struct protoent *pe;
- int i, mb;
- int nsp = IPV6_FW_GETNSRCP(chain);
- int ndp = IPV6_FW_GETNDSTP(chain);
-
- if (do_resolv)
- setservent(1/*stayopen*/);
-
- printf("%05u ", chain->fw_number);
-
- if (do_acct)
- printf("%10lu %10lu ",chain->fw_pcnt,chain->fw_bcnt);
-
- if (do_time)
- {
- if (chain->timestamp)
- {
- char timestr[30];
- time_t t = _long_to_time(chain->timestamp);
-
- strcpy(timestr, ctime(&t));
- *strchr(timestr, '\n') = '\0';
- printf("%s ", timestr);
- }
- else
- printf(" ");
- }
-
- switch (chain->fw_flg & IPV6_FW_F_COMMAND)
- {
- case IPV6_FW_F_ACCEPT:
- printf("allow");
- break;
- case IPV6_FW_F_DENY:
- printf("deny");
- break;
- case IPV6_FW_F_COUNT:
- printf("count");
- break;
- case IPV6_FW_F_DIVERT:
- printf("divert %u", chain->fw_divert_port);
- break;
- case IPV6_FW_F_TEE:
- printf("tee %u", chain->fw_divert_port);
- break;
- case IPV6_FW_F_SKIPTO:
- printf("skipto %u", chain->fw_skipto_rule);
- break;
- case IPV6_FW_F_REJECT:
- if (chain->fw_reject_code == IPV6_FW_REJECT_RST)
- printf("reset");
- else {
- printf("unreach ");
- print_reject_code(chain->fw_reject_code);
- }
- break;
- default:
- errx(EX_OSERR, "impossible");
- }
-
- if (chain->fw_flg & IPV6_FW_F_PRN)
- printf(" log");
-
- pe = getprotobynumber(chain->fw_prot);
- if (pe)
- printf(" %s", pe->p_name);
- else
- printf(" %u", chain->fw_prot);
-
- printf(" from %s", chain->fw_flg & IPV6_FW_F_INVSRC ? "not " : "");
-
- mb=mask_bits((u_char *)&chain->fw_smsk,sizeof(chain->fw_smsk));
- if (mb==128 && do_resolv) {
- he=gethostbyaddr((char *)&(chain->fw_src),sizeof(chain->fw_src),AF_INET6);
- if (he==NULL) {
- printf(inet_ntop(AF_INET6,&chain->fw_src,ntop_buf,sizeof(ntop_buf)));
- } else
- printf("%s",he->h_name);
- } else {
- if (mb!=128) {
- if (mb == 0) {
- printf("any");
- } else {
- printf(inet_ntop(AF_INET6,&chain->fw_src,ntop_buf,sizeof(ntop_buf)));
- printf("/%d",mb);
- }
- } else
- printf(inet_ntop(AF_INET6,&chain->fw_src,ntop_buf,sizeof(ntop_buf)));
- }
-
- if (chain->fw_prot == IPPROTO_TCP || chain->fw_prot == IPPROTO_UDP) {
- comma = " ";
- for (i = 0; i < nsp; i++) {
- print_port(chain->fw_prot, chain->fw_pts[i], comma);
- if (i==0 && (chain->fw_flg & IPV6_FW_F_SRNG))
- comma = "-";
- else
- comma = ",";
- }
- }
-
- printf(" to %s", chain->fw_flg & IPV6_FW_F_INVDST ? "not " : "");
-
- mb=mask_bits((u_char *)&chain->fw_dmsk,sizeof(chain->fw_dmsk));
- if (mb==128 && do_resolv) {
- he=gethostbyaddr((char *)&(chain->fw_dst),sizeof(chain->fw_dst),AF_INET6);
- if (he==NULL) {
- printf(inet_ntop(AF_INET6,&chain->fw_dst,ntop_buf,sizeof(ntop_buf)));
- } else
- printf("%s",he->h_name);
- } else {
- if (mb!=128) {
- if (mb == 0) {
- printf("any");
- } else {
- printf(inet_ntop(AF_INET6,&chain->fw_dst,ntop_buf,sizeof(ntop_buf)));
- printf("/%d",mb);
- }
- } else
- printf(inet_ntop(AF_INET6,&chain->fw_dst,ntop_buf,sizeof(ntop_buf)));
- }
-
- if (chain->fw_prot == IPPROTO_TCP || chain->fw_prot == IPPROTO_UDP) {
- comma = " ";
- for (i = 0; i < ndp; i++) {
- print_port(chain->fw_prot, chain->fw_pts[nsp+i], comma);
- if (i==0 && (chain->fw_flg & IPV6_FW_F_DRNG))
- comma = "-";
- else
- comma = ",";
- }
- }
-
- /* Direction */
- if ((chain->fw_flg & IPV6_FW_F_IN) && !(chain->fw_flg & IPV6_FW_F_OUT))
- printf(" in");
- if (!(chain->fw_flg & IPV6_FW_F_IN) && (chain->fw_flg & IPV6_FW_F_OUT))
- printf(" out");
-
- /* Handle hack for "via" backwards compatibility */
- if ((chain->fw_flg & IF6_FW_F_VIAHACK) == IF6_FW_F_VIAHACK) {
- print_iface("via",
- &chain->fw_in_if, chain->fw_flg & IPV6_FW_F_IIFNAME);
- } else {
- /* Receive interface specified */
- if (chain->fw_flg & IPV6_FW_F_IIFACE)
- print_iface("recv", &chain->fw_in_if,
- chain->fw_flg & IPV6_FW_F_IIFNAME);
- /* Transmit interface specified */
- if (chain->fw_flg & IPV6_FW_F_OIFACE)
- print_iface("xmit", &chain->fw_out_if,
- chain->fw_flg & IPV6_FW_F_OIFNAME);
- }
-
- if (chain->fw_flg & IPV6_FW_F_FRAG)
- printf(" frag");
-
- if (chain->fw_ip6opt || chain->fw_ip6nopt) {
- int _opt_printed = 0;
-#define PRINTOPT(x) {if (_opt_printed) printf(",");\
- printf(x); _opt_printed = 1;}
-
- printf(" ip6opt ");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_HOPOPT) PRINTOPT("hopopt");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_HOPOPT) PRINTOPT("!hopopt");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_ROUTE) PRINTOPT("route");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_ROUTE) PRINTOPT("!route");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_FRAG) PRINTOPT("frag");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_FRAG) PRINTOPT("!frag");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_ESP) PRINTOPT("esp");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_ESP) PRINTOPT("!esp");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_AH) PRINTOPT("ah");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_AH) PRINTOPT("!ah");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_NONXT) PRINTOPT("nonxt");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_NONXT) PRINTOPT("!nonxt");
- if (chain->fw_ip6opt & IPV6_FW_IP6OPT_OPTS) PRINTOPT("opts");
- if (chain->fw_ip6nopt & IPV6_FW_IP6OPT_OPTS) PRINTOPT("!opts");
- }
-
- if (chain->fw_ipflg & IPV6_FW_IF_TCPEST)
- printf(" established");
- else if (chain->fw_tcpf == IPV6_FW_TCPF_SYN &&
- chain->fw_tcpnf == IPV6_FW_TCPF_ACK)
- printf(" setup");
- else if (chain->fw_tcpf || chain->fw_tcpnf) {
- int _flg_printed = 0;
-#define PRINTFLG(x) {if (_flg_printed) printf(",");\
- printf(x); _flg_printed = 1;}
-
- printf(" tcpflg ");
- if (chain->fw_tcpf & IPV6_FW_TCPF_FIN) PRINTFLG("fin");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_FIN) PRINTFLG("!fin");
- if (chain->fw_tcpf & IPV6_FW_TCPF_SYN) PRINTFLG("syn");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_SYN) PRINTFLG("!syn");
- if (chain->fw_tcpf & IPV6_FW_TCPF_RST) PRINTFLG("rst");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_RST) PRINTFLG("!rst");
- if (chain->fw_tcpf & IPV6_FW_TCPF_PSH) PRINTFLG("psh");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_PSH) PRINTFLG("!psh");
- if (chain->fw_tcpf & IPV6_FW_TCPF_ACK) PRINTFLG("ack");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_ACK) PRINTFLG("!ack");
- if (chain->fw_tcpf & IPV6_FW_TCPF_URG) PRINTFLG("urg");
- if (chain->fw_tcpnf & IPV6_FW_TCPF_URG) PRINTFLG("!urg");
- }
- if (chain->fw_flg & IPV6_FW_F_ICMPBIT) {
- int type_index;
- int first = 1;
-
- printf(" icmptype");
-
- for (type_index = 0; type_index < IPV6_FW_ICMPTYPES_DIM * sizeof(unsigned) * 8; ++type_index)
- if (chain->fw_icmp6types[type_index / (sizeof(unsigned) * 8)] &
- (1U << (type_index % (sizeof(unsigned) * 8)))) {
- printf("%c%d", first == 1 ? ' ' : ',', type_index);
- first = 0;
- }
- }
- printf("\n");
- if (do_resolv)
- endservent();
-}
-
-void
-list(ac, av)
- int ac;
- char **av;
-{
- struct ip6_fw *r, *rules, *n;
- int l,i;
- unsigned long rulenum;
- int nalloc, bytes, maxbytes;
-
- /* extract rules from kernel, resizing array as necessary */
- rules = NULL;
- nalloc = sizeof *rules;
- bytes = nalloc;
- maxbytes = 65536 * sizeof *rules;
- while (bytes >= nalloc) {
- if ((n = realloc(rules, nalloc * 2 + 200)) == NULL)
- err(EX_OSERR, "realloc");
- bytes = nalloc = nalloc * 2 + 200;
- rules = n;
- i = getsockopt(s, IPPROTO_IPV6, IPV6_FW_GET, rules, &bytes);
- if ((i < 0 && errno != EINVAL) || nalloc > maxbytes)
- err(EX_OSERR, "getsockopt(IPV6_FW_GET)");
- }
- if (!ac) {
- /* display all rules */
- for (r = rules, l = bytes; l >= sizeof rules[0];
- r++, l-=sizeof rules[0])
- show_ip6fw(r);
- }
- else {
- /* display specific rules requested on command line */
- int exitval = 0;
-
- while (ac--) {
- char *endptr;
- int seen;
-
- /* convert command line rule # */
- rulenum = strtoul(*av++, &endptr, 10);
- if (*endptr) {
- exitval = 1;
- warn("invalid rule number: %s", av[-1]);
- continue;
- }
- seen = 0;
- for (r = rules, l = bytes;
- l >= sizeof rules[0] && r->fw_number <= rulenum;
- r++, l-=sizeof rules[0])
- if (rulenum == r->fw_number) {
- show_ip6fw(r);
- seen = 1;
- }
- if (!seen) {
- exitval = 1;
- warnx("rule %lu does not exist", rulenum);
- }
- }
- if (exitval != 0)
- exit(exitval);
- }
-}
-
-static void
-show_usage(const char *fmt, ...)
-{
- if (fmt) {
- char buf[100];
- va_list args;
-
- va_start(args, fmt);
- vsnprintf(buf, sizeof(buf), fmt, args);
- va_end(args);
- warnx("error: %s", buf);
- }
- fprintf(stderr, "usage: ip6fw [options]\n"
-" flush\n"
-" add [number] rule\n"
-" delete number ...\n"
-" list [number ...]\n"
-" show [number ...]\n"
-" zero [number ...]\n"
-" rule: action proto src dst extras...\n"
-" action:\n"
-" {allow|permit|accept|pass|deny|drop|reject|unreach code|\n"
-" reset|count|skipto num} [log]\n"
-" proto: {ipv6|tcp|udp|ipv6-icmp|<number>}\n"
-" src: from [not] {any|ipv6[/prefixlen]} [{port|port-port},[port],...]\n"
-" dst: to [not] {any|ipv6[/prefixlen]} [{port|port-port},[port],...]\n"
-" extras:\n"
-" fragment (may not be used with ports or tcpflags)\n"
-" in\n"
-" out\n"
-" {xmit|recv|via} {iface|ipv6|any}\n"
-" {established|setup}\n"
-" tcpflags [!]{syn|fin|rst|ack|psh|urg},...\n"
-" ipv6options [!]{hopopt|route|frag|esp|ah|nonxt|opts},...\n"
-" icmptypes {type[,type]}...\n");
-
- exit(1);
-}
-
-static int
-lookup_host (host, addr, family)
- char *host;
- u_char *addr;
- int family;
-{
- struct hostent *he;
-
- if (inet_pton(family, host, addr) != 1) {
- if ((he = gethostbyname2(host, family)) == NULL)
- return(-1);
- memcpy(addr, he->h_addr_list[0], he->h_length);
- }
- return(0);
-}
-
-void
-fill_ip6(ipno, mask, acp, avp)
- struct in6_addr *ipno, *mask;
- int *acp;
- char ***avp;
-{
- int ac = *acp;
- char **av = *avp;
- char *p = 0, md = 0;
- int i;
-
- if (ac && !strncmp(*av,"any",strlen(*av))) {
- *ipno = *mask = in6addr_any; av++; ac--;
- } else {
- p = strchr(*av, '/');
- if (p) {
- md = *p;
- *p++ = '\0';
- }
-
- if (lookup_host(*av, (u_char *)ipno, AF_INET6) != 0)
- show_usage("hostname ``%s'' unknown", *av);
- switch (md) {
- case '/':
- if (atoi(p) == 0) {
- *mask = in6addr_any;
- } else if (atoi(p) > 128) {
- show_usage("bad width ``%s''", p);
- } else {
- *mask = *(plen2mask(atoi(p)));
- }
- break;
- default:
- *mask = *(plen2mask(128));
- break;
- }
- for (i = 0; i < sizeof(*ipno); i++)
- ipno->s6_addr[i] &= mask->s6_addr[i];
- av++;
- ac--;
- }
- *acp = ac;
- *avp = av;
-}
-
-static void
-fill_reject_code6(u_short *codep, char *str)
-{
- struct icmpcode *ic;
- u_long val;
- char *s;
-
- val = strtoul(str, &s, 0);
- if (s != str && *s == '\0' && val < 0x100) {
- *codep = val;
- return;
- }
- for (ic = icmp6codes; ic->str; ic++)
- if (!strcasecmp(str, ic->str)) {
- *codep = ic->code;
- return;
- }
- show_usage("unknown ICMP6 unreachable code ``%s''", str);
-}
-
-static void
-add_port(cnt, ptr, off, port)
- u_short *cnt, *ptr, off, port;
-{
- if (off + *cnt >= IPV6_FW_MAX_PORTS)
- errx(1, "too many ports (max is %d)", IPV6_FW_MAX_PORTS);
- ptr[off+*cnt] = port;
- (*cnt)++;
-}
-
-static int
-lookup_port(const char *arg, int test, int nodash)
-{
- int val;
- char *earg, buf[32];
- struct servent *s;
-
- snprintf(buf, sizeof(buf), "%s", arg);
- buf[strcspn(arg, nodash ? "-," : ",")] = 0;
- val = (int) strtoul(buf, &earg, 0);
- if (!*buf || *earg) {
- setservent(1);
- if ((s = getservbyname(buf, NULL))) {
- val = htons(s->s_port);
- } else {
- if (!test) {
- errx(1, "unknown port ``%s''", arg);
- }
- val = -1;
- }
- } else {
- if (val < 0 || val > 0xffff) {
- if (!test) {
- errx(1, "port ``%s'' out of range", arg);
- }
- val = -1;
- }
- }
- return(val);
-}
-
-int
-fill_port(cnt, ptr, off, arg)
- u_short *cnt, *ptr, off;
- char *arg;
-{
- char *s;
- int initial_range = 0;
-
- s = arg + strcspn(arg, "-,"); /* first port name can't have a dash */
- if (*s == '-') {
- *s++ = '\0';
- if (strchr(arg, ','))
- errx(1, "port range must be first in list");
- add_port(cnt, ptr, off, *arg ? lookup_port(arg, 0, 0) : 0x0000);
- arg = s;
- s = strchr(arg,',');
- if (s)
- *s++ = '\0';
- add_port(cnt, ptr, off, *arg ? lookup_port(arg, 0, 0) : 0xffff);
- arg = s;
- initial_range = 1;
- }
- while (arg != NULL) {
- s = strchr(arg,',');
- if (s)
- *s++ = '\0';
- add_port(cnt, ptr, off, lookup_port(arg, 0, 0));
- arg = s;
- }
- return initial_range;
-}
-
-void
-fill_tcpflag(set, reset, vp)
- u_char *set, *reset;
- char **vp;
-{
- char *p = *vp,*q;
- u_char *d;
-
- while (p && *p) {
- struct tpcflags {
- char * name;
- u_char value;
- } flags[] = {
- { "syn", IPV6_FW_TCPF_SYN },
- { "fin", IPV6_FW_TCPF_FIN },
- { "ack", IPV6_FW_TCPF_ACK },
- { "psh", IPV6_FW_TCPF_PSH },
- { "rst", IPV6_FW_TCPF_RST },
- { "urg", IPV6_FW_TCPF_URG }
- };
- int i;
-
- if (*p == '!') {
- p++;
- d = reset;
- } else {
- d = set;
- }
- q = strchr(p, ',');
- if (q)
- *q++ = '\0';
- for (i = 0; i < sizeof(flags) / sizeof(flags[0]); ++i)
- if (!strncmp(p, flags[i].name, strlen(p))) {
- *d |= flags[i].value;
- break;
- }
- if (i == sizeof(flags) / sizeof(flags[0]))
- show_usage("invalid tcp flag ``%s''", p);
- p = q;
- }
-}
-
-static void
-fill_ip6opt(u_char *set, u_char *reset, char **vp)
-{
- char *p = *vp,*q;
- u_char *d;
-
- while (p && *p) {
- if (*p == '!') {
- p++;
- d = reset;
- } else {
- d = set;
- }
- q = strchr(p, ',');
- if (q)
- *q++ = '\0';
- if (!strncmp(p,"hopopt",strlen(p))) *d |= IPV6_FW_IP6OPT_HOPOPT;
- if (!strncmp(p,"route",strlen(p))) *d |= IPV6_FW_IP6OPT_ROUTE;
- if (!strncmp(p,"frag",strlen(p))) *d |= IPV6_FW_IP6OPT_FRAG;
- if (!strncmp(p,"esp",strlen(p))) *d |= IPV6_FW_IP6OPT_ESP;
- if (!strncmp(p,"ah",strlen(p))) *d |= IPV6_FW_IP6OPT_AH;
- if (!strncmp(p,"nonxt",strlen(p))) *d |= IPV6_FW_IP6OPT_NONXT;
- if (!strncmp(p,"opts",strlen(p))) *d |= IPV6_FW_IP6OPT_OPTS;
- p = q;
- }
-}
-
-void
-fill_icmptypes(types, vp, fw_flg)
- u_long *types;
- char **vp;
- u_short *fw_flg;
-{
- char *c = *vp;
-
- while (*c)
- {
- unsigned long icmptype;
-
- if ( *c == ',' )
- ++c;
-
- icmptype = strtoul(c, &c, 0);
-
- if ( *c != ',' && *c != '\0' )
- show_usage("invalid ICMP6 type");
-
- if (icmptype >= IPV6_FW_ICMPTYPES_DIM * sizeof(unsigned) * 8)
- show_usage("ICMP6 type out of range");
-
- types[icmptype / (sizeof(unsigned) * 8)] |=
- 1 << (icmptype % (sizeof(unsigned) * 8));
- *fw_flg |= IPV6_FW_F_ICMPBIT;
- }
-}
-
-void
-delete(ac,av)
- int ac;
- char **av;
-{
- struct ip6_fw rule;
- int i;
- int exitval = 0;
-
- memset(&rule, 0, sizeof rule);
-
- av++; ac--;
-
- /* Rule number */
- while (ac && isdigit(**av)) {
- rule.fw_number = atoi(*av); av++; ac--;
- if (!do_test) {
- i = setsockopt(s, IPPROTO_IPV6, IPV6_FW_DEL, &rule, sizeof rule);
- if (i) {
- exitval = 1;
- warn("rule %u: setsockopt(%s)", rule.fw_number, "IPV6_FW_DEL");
- }
- }
- }
- if (exitval != 0)
- exit(exitval);
-}
-
-static void
-verify_interface(union ip6_fw_if *ifu)
-{
- struct ifreq ifr;
-
- strlcpy(ifr.ifr_name, ifu->fu_via_if.name, sizeof(ifr.ifr_name));
-
- if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0)
- warnx("warning: interface ``%s'' does not exist", ifr.ifr_name);
-}
-
-static void
-fill_iface(char *which, union ip6_fw_if *ifu, int *byname, int ac, char *arg)
-{
- if (!ac)
- show_usage("missing argument for ``%s''", which);
-
- /* Parse the interface or address */
- if (!strcmp(arg, "any")) {
- ifu->fu_via_ip6 = in6addr_any;
- *byname = 0;
- } else if (!isdigit(*arg)) {
- *byname = 1;
- strlcpy(ifu->fu_via_if.name, arg, sizeof(ifu->fu_via_if.name));
- /*
- * We assume that strings containing '*', '?', or '['
- * are ment to be shell pattern.
- */
- if (strpbrk(arg, "*?[") != NULL) {
- ifu->fu_via_if.glob = 1;
- } else {
- ifu->fu_via_if.glob = 0;
- verify_interface(ifu);
- }
- } else if (inet_pton(AF_INET6, arg, &ifu->fu_via_ip6) != 1) {
- show_usage("bad ip6 address ``%s''", arg);
- } else
- *byname = 0;
-}
-
-static void
-add(ac,av)
- int ac;
- char **av;
-{
- struct ip6_fw rule;
- int i;
- u_char proto;
- struct protoent *pe;
- int saw_xmrc = 0, saw_via = 0;
-
- memset(&rule, 0, sizeof rule);
-
- av++; ac--;
-
- /* Rule number */
- if (ac && isdigit(**av)) {
- rule.fw_number = atoi(*av); av++; ac--;
- }
-
- /* Action */
- if (ac == 0)
- show_usage("missing action");
- if (!strncmp(*av,"accept",strlen(*av))
- || !strncmp(*av,"pass",strlen(*av))
- || !strncmp(*av,"allow",strlen(*av))
- || !strncmp(*av,"permit",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_ACCEPT; av++; ac--;
- } else if (!strncmp(*av,"count",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_COUNT; av++; ac--;
- }
-#if 0
- else if (!strncmp(*av,"divert",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_DIVERT; av++; ac--;
- if (!ac)
- show_usage("missing divert port");
- rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
- if (rule.fw_divert_port == 0) {
- struct servent *s;
- setservent(1);
- s = getservbyname(av[-1], "divert");
- if (s != NULL)
- rule.fw_divert_port = ntohs(s->s_port);
- else
- show_usage("illegal divert port");
- }
- } else if (!strncmp(*av,"tee",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_TEE; av++; ac--;
- if (!ac)
- show_usage("missing divert port");
- rule.fw_divert_port = strtoul(*av, NULL, 0); av++; ac--;
- if (rule.fw_divert_port == 0) {
- struct servent *s;
- setservent(1);
- s = getservbyname(av[-1], "divert");
- if (s != NULL)
- rule.fw_divert_port = ntohs(s->s_port);
- else
- show_usage("illegal divert port");
- }
- }
-#endif
- else if (!strncmp(*av,"skipto",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_SKIPTO; av++; ac--;
- if (!ac)
- show_usage("missing skipto rule number");
- rule.fw_skipto_rule = strtoul(*av, NULL, 0); av++; ac--;
- } else if ((!strncmp(*av,"deny",strlen(*av))
- || !strncmp(*av,"drop",strlen(*av)))) {
- rule.fw_flg |= IPV6_FW_F_DENY; av++; ac--;
- } else if (!strncmp(*av,"reject",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_REJECT; av++; ac--;
- rule.fw_reject_code = ICMP6_DST_UNREACH_NOROUTE;
- } else if (!strncmp(*av,"reset",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_REJECT; av++; ac--;
- rule.fw_reject_code = IPV6_FW_REJECT_RST; /* check TCP later */
- } else if (!strncmp(*av,"unreach",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_REJECT; av++; ac--;
- fill_reject_code6(&rule.fw_reject_code, *av); av++; ac--;
- } else {
- show_usage("invalid action ``%s''", *av);
- }
-
- /* [log] */
- if (ac && !strncmp(*av,"log",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_PRN; av++; ac--;
- }
-
- /* protocol */
- if (ac == 0)
- show_usage("missing protocol");
- if ((proto = atoi(*av)) > 0) {
- rule.fw_prot = proto; av++; ac--;
- } else if (!strncmp(*av,"all",strlen(*av))) {
- rule.fw_prot = IPPROTO_IPV6; av++; ac--;
- } else if ((pe = getprotobyname(*av)) != NULL) {
- rule.fw_prot = pe->p_proto; av++; ac--;
- } else {
- show_usage("invalid protocol ``%s''", *av);
- }
-
- if (rule.fw_prot != IPPROTO_TCP
- && (rule.fw_flg & IPV6_FW_F_COMMAND) == IPV6_FW_F_REJECT
- && rule.fw_reject_code == IPV6_FW_REJECT_RST)
- show_usage("``reset'' is only valid for tcp packets");
-
- /* from */
- if (ac && !strncmp(*av,"from",strlen(*av))) { av++; ac--; }
- else
- show_usage("missing ``from''");
-
- if (ac && !strncmp(*av,"not",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_INVSRC;
- av++; ac--;
- }
- if (!ac)
- show_usage("missing arguments");
-
- fill_ip6(&rule.fw_src, &rule.fw_smsk, &ac, &av);
-
- if (ac && (isdigit(**av) || lookup_port(*av, 1, 1) >= 0)) {
- u_short nports = 0;
-
- if (fill_port(&nports, rule.fw_pts, 0, *av))
- rule.fw_flg |= IPV6_FW_F_SRNG;
- IPV6_FW_SETNSRCP(&rule, nports);
- av++; ac--;
- }
-
- /* to */
- if (ac && !strncmp(*av,"to",strlen(*av))) { av++; ac--; }
- else
- show_usage("missing ``to''");
-
- if (ac && !strncmp(*av,"not",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_INVDST;
- av++; ac--;
- }
- if (!ac)
- show_usage("missing arguments");
-
- fill_ip6(&rule.fw_dst, &rule.fw_dmsk, &ac, &av);
-
- if (ac && (isdigit(**av) || lookup_port(*av, 1, 1) >= 0)) {
- u_short nports = 0;
-
- if (fill_port(&nports,
- rule.fw_pts, IPV6_FW_GETNSRCP(&rule), *av))
- rule.fw_flg |= IPV6_FW_F_DRNG;
- IPV6_FW_SETNDSTP(&rule, nports);
- av++; ac--;
- }
-
- if ((rule.fw_prot != IPPROTO_TCP) && (rule.fw_prot != IPPROTO_UDP)
- && (IPV6_FW_GETNSRCP(&rule) || IPV6_FW_GETNDSTP(&rule))) {
- show_usage("only TCP and UDP protocols are valid"
- " with port specifications");
- }
-
- while (ac) {
- if (!strncmp(*av,"in",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_IN;
- av++; ac--; continue;
- }
- if (!strncmp(*av,"out",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_OUT;
- av++; ac--; continue;
- }
- if (ac && !strncmp(*av,"xmit",strlen(*av))) {
- union ip6_fw_if ifu;
- int byname;
-
- if (saw_via) {
-badviacombo:
- show_usage("``via'' is incompatible"
- " with ``xmit'' and ``recv''");
- }
- saw_xmrc = 1;
- av++; ac--;
- fill_iface("xmit", &ifu, &byname, ac, *av);
- rule.fw_out_if = ifu;
- rule.fw_flg |= IPV6_FW_F_OIFACE;
- if (byname)
- rule.fw_flg |= IPV6_FW_F_OIFNAME;
- av++; ac--; continue;
- }
- if (ac && !strncmp(*av,"recv",strlen(*av))) {
- union ip6_fw_if ifu;
- int byname;
-
- if (saw_via)
- goto badviacombo;
- saw_xmrc = 1;
- av++; ac--;
- fill_iface("recv", &ifu, &byname, ac, *av);
- rule.fw_in_if = ifu;
- rule.fw_flg |= IPV6_FW_F_IIFACE;
- if (byname)
- rule.fw_flg |= IPV6_FW_F_IIFNAME;
- av++; ac--; continue;
- }
- if (ac && !strncmp(*av,"via",strlen(*av))) {
- union ip6_fw_if ifu;
- int byname = 0;
-
- if (saw_xmrc)
- goto badviacombo;
- saw_via = 1;
- av++; ac--;
- fill_iface("via", &ifu, &byname, ac, *av);
- rule.fw_out_if = rule.fw_in_if = ifu;
- if (byname)
- rule.fw_flg |=
- (IPV6_FW_F_IIFNAME | IPV6_FW_F_OIFNAME);
- av++; ac--; continue;
- }
- if (!strncmp(*av,"fragment",strlen(*av))) {
- rule.fw_flg |= IPV6_FW_F_FRAG;
- av++; ac--; continue;
- }
- if (!strncmp(*av,"ipv6options",strlen(*av))) {
- av++; ac--;
- if (!ac)
- show_usage("missing argument"
- " for ``ipv6options''");
- fill_ip6opt(&rule.fw_ip6opt, &rule.fw_ip6nopt, av);
- av++; ac--; continue;
- }
- if (rule.fw_prot == IPPROTO_TCP) {
- if (!strncmp(*av,"established",strlen(*av))) {
- rule.fw_ipflg |= IPV6_FW_IF_TCPEST;
- av++; ac--; continue;
- }
- if (!strncmp(*av,"setup",strlen(*av))) {
- rule.fw_tcpf |= IPV6_FW_TCPF_SYN;
- rule.fw_tcpnf |= IPV6_FW_TCPF_ACK;
- av++; ac--; continue;
- }
- if (!strncmp(*av,"tcpflags",strlen(*av))) {
- av++; ac--;
- if (!ac)
- show_usage("missing argument"
- " for ``tcpflags''");
- fill_tcpflag(&rule.fw_tcpf, &rule.fw_tcpnf, av);
- av++; ac--; continue;
- }
- }
- if (rule.fw_prot == IPPROTO_ICMPV6) {
- if (!strncmp(*av,"icmptypes",strlen(*av))) {
- av++; ac--;
- if (!ac)
- show_usage("missing argument"
- " for ``icmptypes''");
- fill_icmptypes(rule.fw_icmp6types,
- av, &rule.fw_flg);
- av++; ac--; continue;
- }
- }
- show_usage("unknown argument ``%s''", *av);
- }
-
- /* No direction specified -> do both directions */
- if (!(rule.fw_flg & (IPV6_FW_F_OUT|IPV6_FW_F_IN)))
- rule.fw_flg |= (IPV6_FW_F_OUT|IPV6_FW_F_IN);
-
- /* Sanity check interface check, but handle "via" case separately */
- if (saw_via) {
- if (rule.fw_flg & IPV6_FW_F_IN)
- rule.fw_flg |= IPV6_FW_F_IIFACE;
- if (rule.fw_flg & IPV6_FW_F_OUT)
- rule.fw_flg |= IPV6_FW_F_OIFACE;
- } else if ((rule.fw_flg & IPV6_FW_F_OIFACE) && (rule.fw_flg & IPV6_FW_F_IN))
- show_usage("can't check xmit interface of incoming packets");
-
- /* frag may not be used in conjunction with ports or TCP flags */
- if (rule.fw_flg & IPV6_FW_F_FRAG) {
- if (rule.fw_tcpf || rule.fw_tcpnf)
- show_usage("can't mix 'frag' and tcpflags");
-
- if (rule.fw_nports)
- show_usage("can't mix 'frag' and port specifications");
- }
-
- if (!do_quiet)
- show_ip6fw(&rule);
- if (!do_test) {
- i = setsockopt(s, IPPROTO_IPV6, IPV6_FW_ADD, &rule, sizeof rule);
- if (i)
- err(EX_UNAVAILABLE, "setsockopt(%s)", "IPV6_FW_ADD");
- }
-}
-
-static void
-zero (ac, av)
- int ac;
- char **av;
-{
- av++; ac--;
-
- if (!ac) {
- /* clear all entries */
- if (!do_test) {
- if (setsockopt(s,IPPROTO_IPV6,IPV6_FW_ZERO,NULL,0)<0)
- err(EX_UNAVAILABLE, "setsockopt(%s)", "IPV6_FW_ZERO");
- if (!do_quiet)
- printf("Accounting cleared.\n");
- } else if (!do_quiet)
- printf("Accounting not cleared.\n");
- } else {
- struct ip6_fw rule;
- int failed = 0;
-
- memset(&rule, 0, sizeof rule);
- while (ac) {
- /* Rule number */
- if (isdigit(**av)) {
- rule.fw_number = atoi(*av); av++; ac--;
- if (!do_test) {
- if (setsockopt(s, IPPROTO_IPV6,
- IPV6_FW_ZERO, &rule, sizeof rule)) {
- warn("rule %u: setsockopt(%s)", rule.fw_number,"IPV6_FW_ZERO");
- failed = 1;
- }
- if (!do_quiet)
- printf("Entry %d cleared\n",
- rule.fw_number);
- }
- else if (!do_quiet)
- printf("Entry %d not cleared\n",
- rule.fw_number);
- } else
- show_usage("invalid rule number ``%s''", *av);
- }
- if (failed != 0)
- exit(failed);
- }
-}
-
-int
-ip6fw_main(ac,av)
- int ac;
- char **av;
-{
- int ch;
-
- /* init optind to 1 */
- optind = 1;
-
- if ( ac == 1 ) {
- show_usage(NULL);
- }
-
- /* Set the force flag for non-interactive processes */
- do_force = !isatty(STDIN_FILENO);
-
- while ((ch = getopt(ac, av ,"afnqtN")) != -1)
- switch(ch) {
- case 'a':
- do_acct=1;
- break;
- case 'f':
- do_force=1;
- break;
- case 'n':
- do_test=1;
- break;
- case 'q':
- do_quiet=1;
- break;
- case 't':
- do_time=1;
- break;
- case 'N':
- do_resolv=1;
- break;
- default:
- show_usage(NULL);
- }
-
- ac -= optind;
- if (*(av+=optind)==NULL) {
- show_usage("Bad arguments");
- }
-
- if (!strncmp(*av, "add", strlen(*av))) {
- add(ac,av);
- } else if (!strncmp(*av, "delete", strlen(*av))) {
- delete(ac,av);
- } else if (!strncmp(*av, "flush", strlen(*av))) {
- int do_flush = 0;
-
- if ( do_force || do_quiet )
- do_flush = 1;
- else {
- int c;
-
- /* Ask the user */
- printf("Are you sure? [yn] ");
- do {
- fflush(stdout);
- c = toupper(getc(stdin));
- while (c != '\n' && getc(stdin) != '\n')
- if (feof(stdin))
- return (0);
- } while (c != 'Y' && c != 'N');
- printf("\n");
- if (c == 'Y')
- do_flush = 1;
- }
- if ( do_flush ) {
- if (!do_test) {
- if (setsockopt(s,IPPROTO_IPV6,IPV6_FW_FLUSH,NULL,0) < 0)
- err(EX_UNAVAILABLE, "setsockopt(%s)", "IPV6_FW_FLUSH");
-
- if (!do_quiet)
- printf("Flushed all rules.\n");
- } else if (!do_quiet)
- printf("Rules not flushed.\n");
- }
- } else if (!strncmp(*av, "zero", strlen(*av))) {
- zero(ac,av);
- } else if (!strncmp(*av, "print", strlen(*av))) {
- list(--ac,++av);
- } else if (!strncmp(*av, "list", strlen(*av))) {
- list(--ac,++av);
- } else if (!strncmp(*av, "show", strlen(*av))) {
- do_acct++;
- list(--ac,++av);
- } else {
- show_usage("Bad arguments");
- }
- return 0;
-}
-
-int
-main(ac, av)
- int ac;
- char **av;
-{
-#define MAX_ARGS 32
-#define WHITESP " \t\f\v\n\r"
- char buf[BUFSIZ];
- char *a, *p, *args[MAX_ARGS], *cmd = NULL;
- char linename[10];
- int i, c, lineno, nflag, qflag, pflag, status;
- FILE *f = NULL;
- pid_t preproc = 0;
-
- s = socket( AF_INET6, SOCK_RAW, IPPROTO_RAW );
- if ( s < 0 )
- err(EX_UNAVAILABLE, "socket");
-
- setbuf(stdout,0);
-
- /*
- * Only interpret the last command line argument as a file to
- * be preprocessed if it is specified as an absolute pathname.
- */
-
- if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0) {
- nflag = qflag = pflag = i = 0;
- lineno = 0;
-
- while ((c = getopt(ac, av, "D:U:np:q")) != -1)
- switch(c) {
- case 'D':
- if (!pflag)
- errx(EX_USAGE, "-D requires -p");
- if (i > MAX_ARGS - 2)
- errx(EX_USAGE,
- "too many -D or -U options");
- args[i++] = "-D";
- args[i++] = optarg;
- break;
-
- case 'U':
- if (!pflag)
- errx(EX_USAGE, "-U requires -p");
- if (i > MAX_ARGS - 2)
- errx(EX_USAGE,
- "too many -D or -U options");
- args[i++] = "-U";
- args[i++] = optarg;
- break;
-
- case 'n':
- nflag = 1;
- break;
-
- case 'p':
- pflag = 1;
- cmd = optarg;
- args[0] = cmd;
- i = 1;
- break;
-
- case 'q':
- qflag = 1;
- break;
-
- default:
- show_usage(NULL);
- }
-
- av += optind;
- ac -= optind;
- if (ac != 1)
- show_usage("extraneous filename arguments");
-
- if ((f = fopen(av[0], "r")) == NULL)
- err(EX_UNAVAILABLE, "fopen: %s", av[0]);
-
- if (pflag) {
- /* pipe through preprocessor (cpp or m4) */
- int pipedes[2];
-
- args[i] = 0;
-
- if (pipe(pipedes) == -1)
- err(EX_OSERR, "cannot create pipe");
-
- switch((preproc = fork())) {
- case -1:
- err(EX_OSERR, "cannot fork");
-
- case 0:
- /* child */
- if (dup2(fileno(f), 0) == -1 ||
- dup2(pipedes[1], 1) == -1)
- err(EX_OSERR, "dup2()");
- fclose(f);
- close(pipedes[1]);
- close(pipedes[0]);
- execvp(cmd, args);
- err(EX_OSERR, "execvp(%s) failed", cmd);
-
- default:
- /* parent */
- fclose(f);
- close(pipedes[1]);
- if ((f = fdopen(pipedes[0], "r")) == NULL) {
- int savederrno = errno;
-
- (void)kill(preproc, SIGTERM);
- errno = savederrno;
- err(EX_OSERR, "fdopen()");
- }
- }
- }
-
- while (fgets(buf, BUFSIZ, f)) {
- lineno++;
- sprintf(linename, "Line %d", lineno);
- args[0] = linename;
-
- if (*buf == '#')
- continue;
- if ((p = strchr(buf, '#')) != NULL)
- *p = '\0';
- i=1;
- if (qflag) args[i++]="-q";
- if (nflag) args[i++]="-n";
- for (a = strtok(buf, WHITESP);
- a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
- args[i] = a;
- if (i == (qflag? 2: 1))
- continue;
- if (i == MAX_ARGS)
- errx(EX_USAGE, "%s: too many arguments", linename);
- args[i] = NULL;
-
- ip6fw_main(i, args);
- }
- fclose(f);
- if (pflag) {
- if (waitpid(preproc, &status, 0) != -1) {
- if (WIFEXITED(status)) {
- if (WEXITSTATUS(status) != EX_OK)
- errx(EX_UNAVAILABLE,
- "preprocessor exited with status %d",
- WEXITSTATUS(status));
- } else if (WIFSIGNALED(status)) {
- errx(EX_UNAVAILABLE,
- "preprocessor exited with signal %d",
- WTERMSIG(status));
- }
- }
- }
- } else
- ip6fw_main(ac,av);
- return 0;
-}
--- sbin/ip6fw/Makefile
+++ /dev/null
@@ -1,7 +0,0 @@
-# $FreeBSD: src/sbin/ip6fw/Makefile,v 1.6 2004/03/03 20:21:15 johan Exp $
-
-PROG= ip6fw
-WARNS?= 2
-MAN= ip6fw.8
-
-.include <bsd.prog.mk>
--- /dev/null
+++ sbin/iscontrol/fsm.c
@@ -0,0 +1,721 @@
+/*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny at 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: src/sbin/iscontrol/fsm.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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 at 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);
+}
--- /dev/null
+++ sbin/iscontrol/iscontrol.h
@@ -0,0 +1,159 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/iscontrol.h,v 1.1 2007/07/24 15:35:01 scottl Exp $
+ */
+/*
+ | $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);
--- /dev/null
+++ sbin/iscontrol/pdu.h
@@ -0,0 +1,134 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/pdu.h,v 1.1 2007/07/24 15:35:01 scottl Exp $
+ */
+/*
+ | $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;
--- /dev/null
+++ sbin/iscontrol/iscsi.conf.5
@@ -0,0 +1,210 @@
+.\" Copyright (c) 2007 Daniel Braniss <danny at 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: src/sbin/iscontrol/iscsi.conf.5,v 1.2 2007/07/24 18:08:15 brueffer Exp $
+.\"
+.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
+currently 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 kilobytes.
+The default is 128.
+.El
+.sp
+If
+.Em AuthMethod
+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 ASCII 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 do not 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.
--- /dev/null
+++ sbin/iscontrol/iscontrol.8
@@ -0,0 +1,123 @@
+.\" Copyright (c) 2007 Daniel Braniss <danny at 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: src/sbin/iscontrol/iscontrol.8,v 1.2 2007/07/24 18:08:15 brueffer Exp $
+.\"
+.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
+.Xr 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 successful 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
+.Xr 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
+.Xr iscsi.conf 5
+.It Fl t Ar target
+is the target's IP address or name
+.It Ar variable Ns = Ns Ar value
+see
+.Xr 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 permission, but a
+.Em full session
+certainly does.
+.sp
+.Dl iscontrol -c /etc/iscsi.conf -n myiscsi
+.Pp
+will read options from
+.Pa /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 da 4 ,
+.Xr iscsi_initiator 4 ,
+.Xr sa 4 ,
+.Xr iscsi.conf 5 ,
+.Xr camcontrol 8
+.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 Functions.
+The error recovery, though not
+.Em fully compliant
+does a brave effort to recover from network disconnects.
--- /dev/null
+++ sbin/iscontrol/pdu.c
@@ -0,0 +1,175 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/pdu.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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;
+ }
+}
--- /dev/null
+++ sbin/iscontrol/iscontrol.c
@@ -0,0 +1,227 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/iscontrol.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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);
+}
--- /dev/null
+++ sbin/iscontrol/misc.c
@@ -0,0 +1,226 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/misc.c,v 1.1.4.1 2008/02/07 00:08:57 pb Exp $");
+
+#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;
+ unsigned char *cp;
+
+ if(strncasecmp(encoding, "0x", 2) == 0) {
+ char ofmt[5];
+
+ len = blen * 2;
+ dst = malloc(len + 3);
+ strcpy(dst, encoding);
+ ds = dst + 2;
+ cp = 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 = md;
+ b6 = 0; // to keep compiler 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;
+}
--- /dev/null
+++ sbin/iscontrol/config.c
@@ -0,0 +1,376 @@
+ /*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny at 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: src/sbin/iscontrol/config.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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);
+}
--- /dev/null
+++ sbin/iscontrol/auth_subr.c
@@ -0,0 +1,208 @@
+/*-
+ * Copyright (c) 2005-2007 Daniel Braniss <danny at 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: src/sbin/iscontrol/auth_subr.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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
--- /dev/null
+++ sbin/iscontrol/login.c
@@ -0,0 +1,440 @@
+/*-
+ * Copyright (c) 2005 Daniel Braniss <danny at 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: src/sbin/iscontrol/login.c,v 1.1 2007/07/24 15:35:01 scottl Exp $");
+
+#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;
+}
--- /dev/null
+++ sbin/iscontrol/Makefile
@@ -0,0 +1,14 @@
+# $MidnightBSD: src/sbin/iscontrol/Makefile,v 1.1 2008/11/11 21:30:40 laffer1 Exp $
+# $FreeBSD: src/sbin/iscontrol/Makefile,v 1.1 2007/07/24 15:35:01 scottl Exp $
+
+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>
More information about the Midnightbsd-cvs
mailing list